hash
stringlengths
64
64
content
stringlengths
0
1.51M
f33e825b0ec378a82186a42dcfc7f8a074ae09001cddac333e25781cb4829a9a
from sympy import sin, cos, symbols, pi, Float, ImmutableMatrix as Matrix from sympy.physics.vector import ReferenceFrame, Vector, dynamicsymbols 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)
5b6fe7642dda9de8473f20ac61005f57e4cde86b3ebc1d5b0655640266de25a2
r""" N-dim array module for SymPy. Four classes are provided to handle N-dim arrays, given by the combinations dense/sparse (i.e. whether to store all elements or only the non-zero ones in memory) and mutable/immutable (immutable classes are SymPy objects, but cannot change after they have been created). Examples ======== The following examples show the usage of ``Array``. This is an abbreviation for ``ImmutableDenseNDimArray``, that is an immutable and dense N-dim array, the other classes are analogous. For mutable classes it is also possible to change element values after the object has been constructed. Array construction can detect the shape of nested lists and tuples: >>> from sympy import Array >>> a1 = Array([[1, 2], [3, 4], [5, 6]]) >>> a1 [[1, 2], [3, 4], [5, 6]] >>> a1.shape (3, 2) >>> a1.rank() 2 >>> from sympy.abc import x, y, z >>> a2 = Array([[[x, y], [z, x*z]], [[1, x*y], [1/x, x/y]]]) >>> a2 [[[x, y], [z, x*z]], [[1, x*y], [1/x, x/y]]] >>> a2.shape (2, 2, 2) >>> a2.rank() 3 Otherwise one could pass a 1-dim array followed by a shape tuple: >>> m1 = Array(range(12), (3, 4)) >>> m1 [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]] >>> m2 = Array(range(12), (3, 2, 2)) >>> m2 [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]] >>> m2[1,1,1] 7 >>> m2.reshape(4, 3) [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]] Slice support: >>> m2[:, 1, 1] [3, 7, 11] Elementwise derivative: >>> from sympy.abc import x, y, z >>> m3 = Array([x**3, x*y, z]) >>> m3.diff(x) [3*x**2, y, 0] >>> m3.diff(z) [0, 0, 1] Multiplication with other SymPy expressions is applied elementwisely: >>> (1+x)*m3 [x**3*(x + 1), x*y*(x + 1), z*(x + 1)] To apply a function to each element of the N-dim array, use ``applyfunc``: >>> m3.applyfunc(lambda x: x/2) [x**3/2, x*y/2, z/2] N-dim arrays can be converted to nested lists by the ``tolist()`` method: >>> m2.tolist() [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]] >>> isinstance(m2.tolist(), list) True If the rank is 2, it is possible to convert them to matrices with ``tomatrix()``: >>> m1.tomatrix() Matrix([ [0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]) Products and contractions ------------------------- Tensor product between arrays `A_{i_1,\ldots,i_n}` and `B_{j_1,\ldots,j_m}` creates the combined array `P = A \otimes B` defined as `P_{i_1,\ldots,i_n,j_1,\ldots,j_m} := A_{i_1,\ldots,i_n}\cdot B_{j_1,\ldots,j_m}.` It is available through ``tensorproduct(...)``: >>> from sympy import Array, tensorproduct >>> from sympy.abc import x,y,z,t >>> A = Array([x, y, z, t]) >>> B = Array([1, 2, 3, 4]) >>> tensorproduct(A, B) [[x, 2*x, 3*x, 4*x], [y, 2*y, 3*y, 4*y], [z, 2*z, 3*z, 4*z], [t, 2*t, 3*t, 4*t]] Tensor product between a rank-1 array and a matrix creates a rank-3 array: >>> from sympy import eye >>> p1 = tensorproduct(A, eye(4)) >>> p1 [[[x, 0, 0, 0], [0, x, 0, 0], [0, 0, x, 0], [0, 0, 0, x]], [[y, 0, 0, 0], [0, y, 0, 0], [0, 0, y, 0], [0, 0, 0, y]], [[z, 0, 0, 0], [0, z, 0, 0], [0, 0, z, 0], [0, 0, 0, z]], [[t, 0, 0, 0], [0, t, 0, 0], [0, 0, t, 0], [0, 0, 0, t]]] Now, to get back `A_0 \otimes \mathbf{1}` one can access `p_{0,m,n}` by slicing: >>> p1[0,:,:] [[x, 0, 0, 0], [0, x, 0, 0], [0, 0, x, 0], [0, 0, 0, x]] Tensor contraction sums over the specified axes, for example contracting positions `a` and `b` means `A_{i_1,\ldots,i_a,\ldots,i_b,\ldots,i_n} \implies \sum_k A_{i_1,\ldots,k,\ldots,k,\ldots,i_n}` Remember that Python indexing is zero starting, to contract the a-th and b-th axes it is therefore necessary to specify `a-1` and `b-1` >>> from sympy import tensorcontraction >>> C = Array([[x, y], [z, t]]) The matrix trace is equivalent to the contraction of a rank-2 array: `A_{m,n} \implies \sum_k A_{k,k}` >>> tensorcontraction(C, (0, 1)) t + x Matrix product is equivalent to a tensor product of two rank-2 arrays, followed by a contraction of the 2nd and 3rd axes (in Python indexing axes number 1, 2). `A_{m,n}\cdot B_{i,j} \implies \sum_k A_{m, k}\cdot B_{k, j}` >>> D = Array([[2, 1], [0, -1]]) >>> tensorcontraction(tensorproduct(C, D), (1, 2)) [[2*x, x - y], [2*z, -t + z]] One may verify that the matrix product is equivalent: >>> from sympy import Matrix >>> Matrix([[x, y], [z, t]])*Matrix([[2, 1], [0, -1]]) Matrix([ [2*x, x - y], [2*z, -t + z]]) or equivalently >>> C.tomatrix()*D.tomatrix() Matrix([ [2*x, x - y], [2*z, -t + z]]) Diagonal operator ----------------- The ``tensordiagonal`` function acts in a similar manner as ``tensorcontraction``, but the joined indices are not summed over, for example diagonalizing positions `a` and `b` means `A_{i_1,\ldots,i_a,\ldots,i_b,\ldots,i_n} \implies A_{i_1,\ldots,k,\ldots,k,\ldots,i_n} \implies \tilde{A}_{i_1,\ldots,i_{a-1},i_{a+1},\ldots,i_{b-1},i_{b+1},\ldots,i_n,k}` where `\tilde{A}` is the array equivalent to the diagonal of `A` at positions `a` and `b` moved to the last index slot. Compare the difference between contraction and diagonal operators: >>> from sympy import tensordiagonal >>> from sympy.abc import a, b, c, d >>> m = Matrix([[a, b], [c, d]]) >>> tensorcontraction(m, [0, 1]) a + d >>> tensordiagonal(m, [0, 1]) [a, d] In short, no summation occurs with ``tensordiagonal``. Derivatives by array -------------------- The usual derivative operation may be extended to support derivation with respect to arrays, provided that all elements in the that array are symbols or expressions suitable for derivations. The definition of a derivative by an array is as follows: given the array `A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}` the derivative of arrays will return a new array `B` defined by `B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}` The function ``derive_by_array`` performs such an operation: >>> from sympy import derive_by_array >>> from sympy.abc import x, y, z, t >>> from sympy import sin, exp With scalars, it behaves exactly as the ordinary derivative: >>> derive_by_array(sin(x*y), x) y*cos(x*y) Scalar derived by an array basis: >>> derive_by_array(sin(x*y), [x, y, z]) [y*cos(x*y), x*cos(x*y), 0] Deriving array by an array basis: `B^{nm} := \frac{\partial A^m}{\partial x^n}` >>> basis = [x, y, z] >>> ax = derive_by_array([exp(x), sin(y*z), t], basis) >>> ax [[exp(x), 0, 0], [0, z*cos(y*z), 0], [0, y*cos(y*z), 0]] Contraction of the resulting array: `\sum_m \frac{\partial A^m}{\partial x^m}` >>> tensorcontraction(ax, (0, 1)) z*cos(y*z) + exp(x) """ from .dense_ndim_array import MutableDenseNDimArray, ImmutableDenseNDimArray, DenseNDimArray from .sparse_ndim_array import MutableSparseNDimArray, ImmutableSparseNDimArray, SparseNDimArray from .ndim_array import NDimArray from .arrayop import tensorproduct, tensorcontraction, tensordiagonal, derive_by_array, permutedims from .array_comprehension import ArrayComprehension, ArrayComprehensionMap Array = ImmutableDenseNDimArray __all__ = [ 'MutableDenseNDimArray', 'ImmutableDenseNDimArray', 'DenseNDimArray', 'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'SparseNDimArray', 'NDimArray', 'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array', 'permutedims', 'ArrayComprehension', 'ArrayComprehensionMap', 'Array', ]
582fbd6b66e347d0135484164c52192a29b322e2eab991b29e17a2c26f3a7907
import itertools from collections.abc import Iterable from sympy import S, Tuple, diff, Basic 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. 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: if isinstance(dx, array_types): return ImmutableDenseNDimArray([expr.diff(i) for i in Flatten(dx)], dx.shape) else: 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__()
fa8737679983be9431e7a66a82e8a4d0b3ca79aca210022d9e8f1efc07583795
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.compatibility import SYMPY_INTS from sympy.printing.defaults import Printable import itertools from collections.abc import Iterable 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) 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")
54cdea2b2221005acc280cf4b170ccf908cbdb6141944f22316fdc3f341a29ec
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)) 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]))
eaf898706bdeacc7583162c5f5c965dc9f8158ff92155e0d429b9c52890653a8
from sympy import ( Rational, Symbol, N, I, Abs, sqrt, exp, Float, sin, cos, symbols) from sympy.matrices import eye, Matrix from sympy.core.singleton import S from sympy.testing.pytest import raises, XFAIL from sympy.matrices.matrices import NonSquareMatrixError, MatrixError from sympy.matrices.expressions.fourier import DFT from sympy.simplify.simplify import simplify from sympy.matrices.immutable import ImmutableMatrix from sympy.testing.pytest import slow from sympy.testing.matrices import allclose def test_eigen(): R = Rational M = Matrix.eye(3) assert M.eigenvals(multiple=False) == {S.One: 3} assert M.eigenvals(multiple=True) == [1, 1, 1] assert M.eigenvects() == ( [(1, 3, [Matrix([1, 0, 0]), Matrix([0, 1, 0]), Matrix([0, 0, 1])])]) assert M.left_eigenvects() == ( [(1, 3, [Matrix([[1, 0, 0]]), Matrix([[0, 1, 0]]), Matrix([[0, 0, 1]])])]) M = Matrix([[0, 1, 1], [1, 0, 0], [1, 1, 1]]) assert M.eigenvals() == {2*S.One: 1, -S.One: 1, S.Zero: 1} assert M.eigenvects() == ( [ (-1, 1, [Matrix([-1, 1, 0])]), ( 0, 1, [Matrix([0, -1, 1])]), ( 2, 1, [Matrix([R(2, 3), R(1, 3), 1])]) ]) assert M.left_eigenvects() == ( [ (-1, 1, [Matrix([[-2, 1, 1]])]), (0, 1, [Matrix([[-1, -1, 1]])]), (2, 1, [Matrix([[1, 1, 1]])]) ]) a = Symbol('a') M = Matrix([[a, 0], [0, 1]]) assert M.eigenvals() == {a: 1, S.One: 1} M = Matrix([[1, -1], [1, 3]]) assert M.eigenvects() == ([(2, 2, [Matrix(2, 1, [-1, 1])])]) assert M.left_eigenvects() == ([(2, 2, [Matrix([[1, 1]])])]) M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) a = R(15, 2) b = 3*33**R(1, 2) c = R(13, 2) d = (R(33, 8) + 3*b/8) e = (R(33, 8) - 3*b/8) def NS(e, n): return str(N(e, n)) r = [ (a - b/2, 1, [Matrix([(12 + 24/(c - b/2))/((c - b/2)*e) + 3/(c - b/2), (6 + 12/(c - b/2))/e, 1])]), ( 0, 1, [Matrix([1, -2, 1])]), (a + b/2, 1, [Matrix([(12 + 24/(c + b/2))/((c + b/2)*d) + 3/(c + b/2), (6 + 12/(c + b/2))/d, 1])]), ] r1 = [(NS(r[i][0], 2), NS(r[i][1], 2), [NS(j, 2) for j in r[i][2][0]]) for i in range(len(r))] r = M.eigenvects() r2 = [(NS(r[i][0], 2), NS(r[i][1], 2), [NS(j, 2) for j in r[i][2][0]]) for i in range(len(r))] assert sorted(r1) == sorted(r2) eps = Symbol('eps', real=True) M = Matrix([[abs(eps), I*eps ], [-I*eps, abs(eps) ]]) assert M.eigenvects() == ( [ ( 0, 1, [Matrix([[-I*eps/abs(eps)], [1]])]), ( 2*abs(eps), 1, [ Matrix([[I*eps/abs(eps)], [1]]) ] ), ]) assert M.left_eigenvects() == ( [ (0, 1, [Matrix([[I*eps/Abs(eps), 1]])]), (2*Abs(eps), 1, [Matrix([[-I*eps/Abs(eps), 1]])]) ]) M = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2]) M._eigenvects = M.eigenvects(simplify=False) assert max(i.q for i in M._eigenvects[0][2][0]) > 1 M._eigenvects = M.eigenvects(simplify=True) assert max(i.q for i in M._eigenvects[0][2][0]) == 1 M = Matrix([[Rational(1, 4), 1], [1, 1]]) assert M.eigenvects() == [ (Rational(5, 8) - sqrt(73)/8, 1, [Matrix([[-sqrt(73)/8 - Rational(3, 8)], [1]])]), (Rational(5, 8) + sqrt(73)/8, 1, [Matrix([[Rational(-3, 8) + sqrt(73)/8], [1]])])] # issue 10719 assert Matrix([]).eigenvals() == {} assert Matrix([]).eigenvals(multiple=True) == [] assert Matrix([]).eigenvects() == [] # issue 15119 raises(NonSquareMatrixError, lambda: Matrix([[1, 2], [0, 4], [0, 0]]).eigenvals()) raises(NonSquareMatrixError, lambda: Matrix([[1, 0], [3, 4], [5, 6]]).eigenvals()) raises(NonSquareMatrixError, lambda: Matrix([[1, 2, 3], [0, 5, 6]]).eigenvals()) raises(NonSquareMatrixError, lambda: Matrix([[1, 0, 0], [4, 5, 0]]).eigenvals()) raises(NonSquareMatrixError, lambda: Matrix([[1, 2, 3], [0, 5, 6]]).eigenvals( error_when_incomplete = False)) raises(NonSquareMatrixError, lambda: Matrix([[1, 0, 0], [4, 5, 0]]).eigenvals( error_when_incomplete = False)) m = Matrix([[1, 2], [3, 4]]) assert isinstance(m.eigenvals(simplify=True, multiple=False), dict) assert isinstance(m.eigenvals(simplify=True, multiple=True), list) assert isinstance(m.eigenvals(simplify=lambda x: x, multiple=False), dict) assert isinstance(m.eigenvals(simplify=lambda x: x, multiple=True), list) @slow def test_eigen_slow(): # issue 15125 from sympy.core.function import count_ops q = Symbol("q", positive = True) m = Matrix([[-2, exp(-q), 1], [exp(q), -2, 1], [1, 1, -2]]) assert count_ops(m.eigenvals(simplify=False)) > \ count_ops(m.eigenvals(simplify=True)) assert count_ops(m.eigenvals(simplify=lambda x: x)) > \ count_ops(m.eigenvals(simplify=True)) def test_float_eigenvals(): m = Matrix([[1, .6, .6], [.6, .9, .9], [.9, .6, .6]]) evals = [ Rational(5, 4) - sqrt(385)/20, sqrt(385)/20 + Rational(5, 4), S.Zero] n_evals = m.eigenvals(rational=True, multiple=True) n_evals = sorted(n_evals) s_evals = [x.evalf() for x in evals] s_evals = sorted(s_evals) for x, y in zip(n_evals, s_evals): assert abs(x-y) < 10**-9 @XFAIL def test_eigen_vects(): m = Matrix(2, 2, [1, 0, 0, I]) raises(NotImplementedError, lambda: m.is_diagonalizable(True)) # !!! bug because of eigenvects() or roots(x**2 + (-1 - I)*x + I, x) # see issue 5292 assert not m.is_diagonalizable(True) raises(MatrixError, lambda: m.diagonalize(True)) (P, D) = m.diagonalize(True) def test_issue_8240(): # Eigenvalues of large triangular matrices x, y = symbols('x y') n = 200 diagonal_variables = [Symbol('x%s' % i) for i in range(n)] M = [[0 for i in range(n)] for j in range(n)] for i in range(n): M[i][i] = diagonal_variables[i] M = Matrix(M) eigenvals = M.eigenvals() assert len(eigenvals) == n for i in range(n): assert eigenvals[diagonal_variables[i]] == 1 eigenvals = M.eigenvals(multiple=True) assert set(eigenvals) == set(diagonal_variables) # with multiplicity M = Matrix([[x, 0, 0], [1, y, 0], [2, 3, x]]) eigenvals = M.eigenvals() assert eigenvals == {x: 2, y: 1} eigenvals = M.eigenvals(multiple=True) assert len(eigenvals) == 3 assert eigenvals.count(x) == 2 assert eigenvals.count(y) == 1 def test_eigenvals(): M = Matrix([[0, 1, 1], [1, 0, 0], [1, 1, 1]]) assert M.eigenvals() == {2*S.One: 1, -S.One: 1, S.Zero: 1} m = Matrix([ [3, 0, 0, 0, -3], [0, -3, -3, 0, 3], [0, 3, 0, 3, 0], [0, 0, 3, 0, 3], [3, 0, 0, 3, 0]]) # XXX Used dry-run test because arbitrary symbol that appears in # CRootOf may not be unique. assert m.eigenvals() def test_eigenvects(): M = Matrix([[0, 1, 1], [1, 0, 0], [1, 1, 1]]) vecs = M.eigenvects() for val, mult, vec_list in vecs: assert len(vec_list) == 1 assert M*vec_list[0] == val*vec_list[0] def test_left_eigenvects(): M = Matrix([[0, 1, 1], [1, 0, 0], [1, 1, 1]]) vecs = M.left_eigenvects() for val, mult, vec_list in vecs: assert len(vec_list) == 1 assert vec_list[0]*M == val*vec_list[0] @slow def test_bidiagonalize(): M = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) assert M.bidiagonalize() == M assert M.bidiagonalize(upper=False) == M assert M.bidiagonalize() == M assert M.bidiagonal_decomposition() == (M, M, M) assert M.bidiagonal_decomposition(upper=False) == (M, M, M) assert M.bidiagonalize() == M import random #Real Tests for real_test in range(2): test_values = [] row = 2 col = 2 for _ in range(row * col): value = random.randint(-1000000000, 1000000000) test_values = test_values + [value] # L -> Lower Bidiagonalization # M -> Mutable Matrix # N -> Immutable Matrix # 0 -> Bidiagonalized form # 1,2,3 -> Bidiagonal_decomposition matrices # 4 -> Product of 1 2 3 M = Matrix(row, col, test_values) N = ImmutableMatrix(M) N1, N2, N3 = N.bidiagonal_decomposition() M1, M2, M3 = M.bidiagonal_decomposition() M0 = M.bidiagonalize() N0 = N.bidiagonalize() N4 = N1 * N2 * N3 M4 = M1 * M2 * M3 N2.simplify() N4.simplify() N0.simplify() M0.simplify() M2.simplify() M4.simplify() LM0 = M.bidiagonalize(upper=False) LM1, LM2, LM3 = M.bidiagonal_decomposition(upper=False) LN0 = N.bidiagonalize(upper=False) LN1, LN2, LN3 = N.bidiagonal_decomposition(upper=False) LN4 = LN1 * LN2 * LN3 LM4 = LM1 * LM2 * LM3 LN2.simplify() LN4.simplify() LN0.simplify() LM0.simplify() LM2.simplify() LM4.simplify() assert M == M4 assert M2 == M0 assert N == N4 assert N2 == N0 assert M == LM4 assert LM2 == LM0 assert N == LN4 assert LN2 == LN0 #Complex Tests for complex_test in range(2): test_values = [] size = 2 for _ in range(size * size): real = random.randint(-1000000000, 1000000000) comp = random.randint(-1000000000, 1000000000) value = real + comp * I test_values = test_values + [value] M = Matrix(size, size, test_values) N = ImmutableMatrix(M) # L -> Lower Bidiagonalization # M -> Mutable Matrix # N -> Immutable Matrix # 0 -> Bidiagonalized form # 1,2,3 -> Bidiagonal_decomposition matrices # 4 -> Product of 1 2 3 N1, N2, N3 = N.bidiagonal_decomposition() M1, M2, M3 = M.bidiagonal_decomposition() M0 = M.bidiagonalize() N0 = N.bidiagonalize() N4 = N1 * N2 * N3 M4 = M1 * M2 * M3 N2.simplify() N4.simplify() N0.simplify() M0.simplify() M2.simplify() M4.simplify() LM0 = M.bidiagonalize(upper=False) LM1, LM2, LM3 = M.bidiagonal_decomposition(upper=False) LN0 = N.bidiagonalize(upper=False) LN1, LN2, LN3 = N.bidiagonal_decomposition(upper=False) LN4 = LN1 * LN2 * LN3 LM4 = LM1 * LM2 * LM3 LN2.simplify() LN4.simplify() LN0.simplify() LM0.simplify() LM2.simplify() LM4.simplify() assert M == M4 assert M2 == M0 assert N == N4 assert N2 == N0 assert M == LM4 assert LM2 == LM0 assert N == LN4 assert LN2 == LN0 M = Matrix(18, 8, range(1, 145)) M = M.applyfunc(lambda i: Float(i)) assert M.bidiagonal_decomposition()[1] == M.bidiagonalize() assert M.bidiagonal_decomposition(upper=False)[1] == M.bidiagonalize(upper=False) a, b, c = M.bidiagonal_decomposition() diff = a * b * c - M assert abs(max(diff)) < 10**-12 def test_diagonalize(): m = Matrix(2, 2, [0, -1, 1, 0]) raises(MatrixError, lambda: m.diagonalize(reals_only=True)) P, D = m.diagonalize() assert D.is_diagonal() assert D == Matrix([ [-I, 0], [ 0, I]]) # make sure we use floats out if floats are passed in m = Matrix(2, 2, [0, .5, .5, 0]) P, D = m.diagonalize() assert all(isinstance(e, Float) for e in D.values()) assert all(isinstance(e, Float) for e in P.values()) _, D2 = m.diagonalize(reals_only=True) assert D == D2 m = Matrix( [[0, 1, 0, 0], [1, 0, 0, 0.002], [0.002, 0, 0, 1], [0, 0, 1, 0]]) P, D = m.diagonalize() assert allclose(P*D, m*P) def test_is_diagonalizable(): a, b, c = symbols('a b c') m = Matrix(2, 2, [a, c, c, b]) assert m.is_symmetric() assert m.is_diagonalizable() assert not Matrix(2, 2, [1, 1, 0, 1]).is_diagonalizable() m = Matrix(2, 2, [0, -1, 1, 0]) assert m.is_diagonalizable() assert not m.is_diagonalizable(reals_only=True) def test_jordan_form(): m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10]) raises(NonSquareMatrixError, lambda: m.jordan_form()) # the next two tests test the cases where the old # algorithm failed due to the fact that the block structure can # *NOT* be determined from algebraic and geometric multiplicity alone # This can be seen most easily when one lets compute the J.c.f. of a matrix that # is in J.c.f already. m = Matrix(4, 4, [2, 1, 0, 0, 0, 2, 1, 0, 0, 0, 2, 0, 0, 0, 0, 2 ]) P, J = m.jordan_form() assert m == J m = Matrix(4, 4, [2, 1, 0, 0, 0, 2, 0, 0, 0, 0, 2, 1, 0, 0, 0, 2 ]) P, J = m.jordan_form() assert m == J A = Matrix([[ 2, 4, 1, 0], [-4, 2, 0, 1], [ 0, 0, 2, 4], [ 0, 0, -4, 2]]) P, J = A.jordan_form() assert simplify(P*J*P.inv()) == A assert Matrix(1, 1, [1]).jordan_form() == (Matrix([1]), Matrix([1])) assert Matrix(1, 1, [1]).jordan_form(calc_transform=False) == Matrix([1]) # If we have eigenvalues in CRootOf form, raise errors m = Matrix([[3, 0, 0, 0, -3], [0, -3, -3, 0, 3], [0, 3, 0, 3, 0], [0, 0, 3, 0, 3], [3, 0, 0, 3, 0]]) raises(MatrixError, lambda: m.jordan_form()) # make sure that if the input has floats, the output does too m = Matrix([ [ 0.6875, 0.125 + 0.1875*sqrt(3)], [0.125 + 0.1875*sqrt(3), 0.3125]]) P, J = m.jordan_form() assert all(isinstance(x, Float) or x == 0 for x in P) assert all(isinstance(x, Float) or x == 0 for x in J) def test_singular_values(): x = Symbol('x', real=True) A = Matrix([[0, 1*I], [2, 0]]) # if singular values can be sorted, they should be in decreasing order assert A.singular_values() == [2, 1] A = eye(3) A[1, 1] = x A[2, 2] = 5 vals = A.singular_values() # since Abs(x) cannot be sorted, test set equality assert set(vals) == {5, 1, Abs(x)} A = Matrix([[sin(x), cos(x)], [-cos(x), sin(x)]]) vals = [sv.trigsimp() for sv in A.singular_values()] assert vals == [S.One, S.One] A = Matrix([ [2, 4], [1, 3], [0, 0], [0, 0] ]) assert A.singular_values() == \ [sqrt(sqrt(221) + 15), sqrt(15 - sqrt(221))] assert A.T.singular_values() == \ [sqrt(sqrt(221) + 15), sqrt(15 - sqrt(221)), 0, 0] def test___eq__(): assert (Matrix( [[0, 1, 1], [1, 0, 0], [1, 1, 1]]) == {}) is False def test_definite(): # Examples from Gilbert Strang, "Introduction to Linear Algebra" # Positive definite matrices m = Matrix([[2, -1, 0], [-1, 2, -1], [0, -1, 2]]) assert m.is_positive_definite == True assert m.is_positive_semidefinite == True assert m.is_negative_definite == False assert m.is_negative_semidefinite == False assert m.is_indefinite == False m = Matrix([[5, 4], [4, 5]]) assert m.is_positive_definite == True assert m.is_positive_semidefinite == True assert m.is_negative_definite == False assert m.is_negative_semidefinite == False assert m.is_indefinite == False # Positive semidefinite matrices m = Matrix([[2, -1, -1], [-1, 2, -1], [-1, -1, 2]]) assert m.is_positive_definite == False assert m.is_positive_semidefinite == True assert m.is_negative_definite == False assert m.is_negative_semidefinite == False assert m.is_indefinite == False m = Matrix([[1, 2], [2, 4]]) assert m.is_positive_definite == False assert m.is_positive_semidefinite == True assert m.is_negative_definite == False assert m.is_negative_semidefinite == False assert m.is_indefinite == False # Examples from Mathematica documentation # Non-hermitian positive definite matrices m = Matrix([[2, 3], [4, 8]]) assert m.is_positive_definite == True assert m.is_positive_semidefinite == True assert m.is_negative_definite == False assert m.is_negative_semidefinite == False assert m.is_indefinite == False # Hermetian matrices m = Matrix([[1, 2*I], [-I, 4]]) assert m.is_positive_definite == True assert m.is_positive_semidefinite == True assert m.is_negative_definite == False assert m.is_negative_semidefinite == False assert m.is_indefinite == False # Symbolic matrices examples a = Symbol('a', positive=True) b = Symbol('b', negative=True) m = Matrix([[a, 0, 0], [0, a, 0], [0, 0, a]]) assert m.is_positive_definite == True assert m.is_positive_semidefinite == True assert m.is_negative_definite == False assert m.is_negative_semidefinite == False assert m.is_indefinite == False m = Matrix([[b, 0, 0], [0, b, 0], [0, 0, b]]) assert m.is_positive_definite == False assert m.is_positive_semidefinite == False assert m.is_negative_definite == True assert m.is_negative_semidefinite == True assert m.is_indefinite == False m = Matrix([[a, 0], [0, b]]) assert m.is_positive_definite == False assert m.is_positive_semidefinite == False assert m.is_negative_definite == False assert m.is_negative_semidefinite == False assert m.is_indefinite == True m = Matrix([ [0.0228202735623867, 0.00518748979085398, -0.0743036351048907, -0.00709135324903921], [0.00518748979085398, 0.0349045359786350, 0.0830317991056637, 0.00233147902806909], [-0.0743036351048907, 0.0830317991056637, 1.15859676366277, 0.340359081555988], [-0.00709135324903921, 0.00233147902806909, 0.340359081555988, 0.928147644848199] ]) assert m.is_positive_definite == True assert m.is_positive_semidefinite == True assert m.is_indefinite == False # test for issue 19547: https://github.com/sympy/sympy/issues/19547 m = Matrix([ [0, 0, 0], [0, 1, 2], [0, 2, 1] ]) assert not m.is_positive_definite assert not m.is_positive_semidefinite def test_positive_semidefinite_cholesky(): from sympy.matrices.eigen import _is_positive_semidefinite_cholesky m = Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) assert _is_positive_semidefinite_cholesky(m) == True m = Matrix([[0, 0, 0], [0, 5, -10*I], [0, 10*I, 5]]) assert _is_positive_semidefinite_cholesky(m) == False m = Matrix([[1, 0, 0], [0, 0, 0], [0, 0, -1]]) assert _is_positive_semidefinite_cholesky(m) == False m = Matrix([[0, 1], [1, 0]]) assert _is_positive_semidefinite_cholesky(m) == False # https://www.value-at-risk.net/cholesky-factorization/ m = Matrix([[4, -2, -6], [-2, 10, 9], [-6, 9, 14]]) assert _is_positive_semidefinite_cholesky(m) == True m = Matrix([[9, -3, 3], [-3, 2, 1], [3, 1, 6]]) assert _is_positive_semidefinite_cholesky(m) == True m = Matrix([[4, -2, 2], [-2, 1, -1], [2, -1, 5]]) assert _is_positive_semidefinite_cholesky(m) == True m = Matrix([[1, 2, -1], [2, 5, 1], [-1, 1, 9]]) assert _is_positive_semidefinite_cholesky(m) == False def test_issue_20582(): A = Matrix([ [5, -5, -3, 2, -7], [-2, -5, 0, 2, 1], [-2, -7, -5, -2, -6], [7, 10, 3, 9, -2], [4, -10, 3, -8, -4] ]) # XXX Used dry-run test because arbitrary symbol that appears in # CRootOf may not be unique. assert A.eigenvects() def test_issue_20275(): # XXX We use complex expansions because complex exponentials are not # recognized by polys.domains A = DFT(3).as_explicit().expand(complex=True) eigenvects = A.eigenvects() assert eigenvects[0] == ( -1, 1, [Matrix([[1 - sqrt(3)], [1], [1]])] ) assert eigenvects[1] == ( 1, 1, [Matrix([[1 + sqrt(3)], [1], [1]])] ) assert eigenvects[2] == ( -I, 1, [Matrix([[0], [-1], [1]])] ) A = DFT(4).as_explicit().expand(complex=True) eigenvects = A.eigenvects() assert eigenvects[0] == ( -1, 1, [Matrix([[-1], [1], [1], [1]])] ) assert eigenvects[1] == ( 1, 2, [Matrix([[1], [0], [1], [0]]), Matrix([[2], [1], [0], [1]])] ) assert eigenvects[2] == ( -I, 1, [Matrix([[0], [-1], [0], [1]])] ) # XXX We skip test for some parts of eigenvectors which are very # complicated and fragile under expression tree changes A = DFT(5).as_explicit().expand(complex=True) eigenvects = A.eigenvects() assert eigenvects[0] == ( -1, 1, [Matrix([[1 - sqrt(5)], [1], [1], [1], [1]])] ) assert eigenvects[1] == ( 1, 2, [Matrix([[S(1)/2 + sqrt(5)/2], [0], [1], [1], [0]]), Matrix([[S(1)/2 + sqrt(5)/2], [1], [0], [0], [1]])] )
3eaafc37d8c4d65187c0433972f3d30e817af8e4b6e6d4bfecc3a7e36b94c100
from sympy import ( I, Rational, S, Symbol, simplify, symbols, sympify, expand_mul) from sympy.matrices.matrices import (ShapeError, NonSquareMatrixError) from sympy.matrices import ( ImmutableMatrix, Matrix, eye, ones, ImmutableDenseMatrix, dotprodsimp) from sympy.testing.pytest import raises from sympy.matrices.common import NonInvertibleMatrixError from sympy.solvers.solveset import linsolve from sympy.abc import x, y def test_issue_17247_expression_blowup_29(): M = Matrix(S('''[ [ -3/4, 45/32 - 37*I/16, 0, 0], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.gauss_jordan_solve(ones(4, 1)) == (Matrix(S('''[ [ -32549314808672/3306971225785 - 17397006745216*I/3306971225785], [ 67439348256/3306971225785 - 9167503335872*I/3306971225785], [-15091965363354518272/21217636514687010905 + 16890163109293858304*I/21217636514687010905], [ -11328/952745 + 87616*I/952745]]''')), Matrix(0, 1, [])) def test_issue_17247_expression_blowup_30(): M = Matrix(S('''[ [ -3/4, 45/32 - 37*I/16, 0, 0], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.cholesky_solve(ones(4, 1)) == Matrix(S('''[ [ -32549314808672/3306971225785 - 17397006745216*I/3306971225785], [ 67439348256/3306971225785 - 9167503335872*I/3306971225785], [-15091965363354518272/21217636514687010905 + 16890163109293858304*I/21217636514687010905], [ -11328/952745 + 87616*I/952745]]''')) # @XFAIL # This calculation hangs with dotprodsimp. # def test_issue_17247_expression_blowup_31(): # M = Matrix([ # [x + 1, 1 - x, 0, 0], # [1 - x, x + 1, 0, x + 1], # [ 0, 1 - x, x + 1, 0], # [ 0, 0, 0, x + 1]]) # with dotprodsimp(True): # assert M.LDLsolve(ones(4, 1)) == Matrix([ # [(x + 1)/(4*x)], # [(x - 1)/(4*x)], # [(x + 1)/(4*x)], # [ 1/(x + 1)]]) def test_issue_17247_expression_blowup_32(): M = Matrix([ [x + 1, 1 - x, 0, 0], [1 - x, x + 1, 0, x + 1], [ 0, 1 - x, x + 1, 0], [ 0, 0, 0, x + 1]]) with dotprodsimp(True): assert M.LUsolve(ones(4, 1)) == Matrix([ [(x + 1)/(4*x)], [(x - 1)/(4*x)], [(x + 1)/(4*x)], [ 1/(x + 1)]]) def test_LUsolve(): A = Matrix([[2, 3, 5], [3, 6, 2], [8, 3, 6]]) x = Matrix(3, 1, [3, 7, 5]) b = A*x soln = A.LUsolve(b) assert soln == x A = Matrix([[0, -1, 2], [5, 10, 7], [8, 3, 4]]) x = Matrix(3, 1, [-1, 2, 5]) b = A*x soln = A.LUsolve(b) assert soln == x A = Matrix([[2, 1], [1, 0], [1, 0]]) # issue 14548 b = Matrix([3, 1, 1]) assert A.LUsolve(b) == Matrix([1, 1]) b = Matrix([3, 1, 2]) # inconsistent raises(ValueError, lambda: A.LUsolve(b)) A = Matrix([[0, -1, 2], [5, 10, 7], [8, 3, 4], [2, 3, 5], [3, 6, 2], [8, 3, 6]]) x = Matrix([2, 1, -4]) b = A*x soln = A.LUsolve(b) assert soln == x A = Matrix([[0, -1, 2], [5, 10, 7]]) # underdetermined x = Matrix([-1, 2, 0]) b = A*x raises(NotImplementedError, lambda: A.LUsolve(b)) A = Matrix(4, 4, lambda i, j: 1/(i+j+1) if i != 3 else 0) b = Matrix.zeros(4, 1) raises(NonInvertibleMatrixError, lambda: A.LUsolve(b)) def test_QRsolve(): A = Matrix([[2, 3, 5], [3, 6, 2], [8, 3, 6]]) x = Matrix(3, 1, [3, 7, 5]) b = A*x soln = A.QRsolve(b) assert soln == x x = Matrix([[1, 2], [3, 4], [5, 6]]) b = A*x soln = A.QRsolve(b) assert soln == x A = Matrix([[0, -1, 2], [5, 10, 7], [8, 3, 4]]) x = Matrix(3, 1, [-1, 2, 5]) b = A*x soln = A.QRsolve(b) assert soln == x x = Matrix([[7, 8], [9, 10], [11, 12]]) b = A*x soln = A.QRsolve(b) assert soln == x def test_errors(): raises(ShapeError, lambda: Matrix([1]).LUsolve(Matrix([[1, 2], [3, 4]]))) def test_cholesky_solve(): A = Matrix([[2, 3, 5], [3, 6, 2], [8, 3, 6]]) x = Matrix(3, 1, [3, 7, 5]) b = A*x soln = A.cholesky_solve(b) assert soln == x A = Matrix([[0, -1, 2], [5, 10, 7], [8, 3, 4]]) x = Matrix(3, 1, [-1, 2, 5]) b = A*x soln = A.cholesky_solve(b) assert soln == x A = Matrix(((1, 5), (5, 1))) x = Matrix((4, -3)) b = A*x soln = A.cholesky_solve(b) assert soln == x A = Matrix(((9, 3*I), (-3*I, 5))) x = Matrix((-2, 1)) b = A*x soln = A.cholesky_solve(b) assert expand_mul(soln) == x A = Matrix(((9*I, 3), (-3 + I, 5))) x = Matrix((2 + 3*I, -1)) b = A*x soln = A.cholesky_solve(b) assert expand_mul(soln) == x a00, a01, a11, b0, b1 = symbols('a00, a01, a11, b0, b1') A = Matrix(((a00, a01), (a01, a11))) b = Matrix((b0, b1)) x = A.cholesky_solve(b) assert simplify(A*x) == b def test_LDLsolve(): A = Matrix([[2, 3, 5], [3, 6, 2], [8, 3, 6]]) x = Matrix(3, 1, [3, 7, 5]) b = A*x soln = A.LDLsolve(b) assert soln == x A = Matrix([[0, -1, 2], [5, 10, 7], [8, 3, 4]]) x = Matrix(3, 1, [-1, 2, 5]) b = A*x soln = A.LDLsolve(b) assert soln == x A = Matrix(((9, 3*I), (-3*I, 5))) x = Matrix((-2, 1)) b = A*x soln = A.LDLsolve(b) assert expand_mul(soln) == x A = Matrix(((9*I, 3), (-3 + I, 5))) x = Matrix((2 + 3*I, -1)) b = A*x soln = A.LDLsolve(b) assert expand_mul(soln) == x A = Matrix(((9, 3), (3, 9))) x = Matrix((1, 1)) b = A * x soln = A.LDLsolve(b) assert expand_mul(soln) == x A = Matrix([[-5, -3, -4], [-3, -7, 7]]) x = Matrix([[8], [7], [-2]]) b = A * x raises(NotImplementedError, lambda: A.LDLsolve(b)) def test_lower_triangular_solve(): raises(NonSquareMatrixError, lambda: Matrix([1, 0]).lower_triangular_solve(Matrix([0, 1]))) raises(ShapeError, lambda: Matrix([[1, 0], [0, 1]]).lower_triangular_solve(Matrix([1]))) raises(ValueError, lambda: Matrix([[2, 1], [1, 2]]).lower_triangular_solve( Matrix([[1, 0], [0, 1]]))) A = Matrix([[1, 0], [0, 1]]) B = Matrix([[x, y], [y, x]]) C = Matrix([[4, 8], [2, 9]]) assert A.lower_triangular_solve(B) == B assert A.lower_triangular_solve(C) == C def test_upper_triangular_solve(): raises(NonSquareMatrixError, lambda: Matrix([1, 0]).upper_triangular_solve(Matrix([0, 1]))) raises(ShapeError, lambda: Matrix([[1, 0], [0, 1]]).upper_triangular_solve(Matrix([1]))) raises(TypeError, lambda: Matrix([[2, 1], [1, 2]]).upper_triangular_solve( Matrix([[1, 0], [0, 1]]))) A = Matrix([[1, 0], [0, 1]]) B = Matrix([[x, y], [y, x]]) C = Matrix([[2, 4], [3, 8]]) assert A.upper_triangular_solve(B) == B assert A.upper_triangular_solve(C) == C def test_diagonal_solve(): raises(TypeError, lambda: Matrix([1, 1]).diagonal_solve(Matrix([1]))) A = Matrix([[1, 0], [0, 1]])*2 B = Matrix([[x, y], [y, x]]) assert A.diagonal_solve(B) == B/2 A = Matrix([[1, 0], [1, 2]]) raises(TypeError, lambda: A.diagonal_solve(B)) def test_pinv_solve(): # Fully determined system (unique result, identical to other solvers). A = Matrix([[1, 5], [7, 9]]) B = Matrix([12, 13]) assert A.pinv_solve(B) == A.cholesky_solve(B) assert A.pinv_solve(B) == A.LDLsolve(B) assert A.pinv_solve(B) == Matrix([sympify('-43/26'), sympify('71/26')]) assert A * A.pinv() * B == B # Fully determined, with two-dimensional B matrix. B = Matrix([[12, 13, 14], [15, 16, 17]]) assert A.pinv_solve(B) == A.cholesky_solve(B) assert A.pinv_solve(B) == A.LDLsolve(B) assert A.pinv_solve(B) == Matrix([[-33, -37, -41], [69, 75, 81]]) / 26 assert A * A.pinv() * B == B # Underdetermined system (infinite results). A = Matrix([[1, 0, 1], [0, 1, 1]]) B = Matrix([5, 7]) solution = A.pinv_solve(B) w = {} for s in solution.atoms(Symbol): # Extract dummy symbols used in the solution. w[s.name] = s assert solution == Matrix([[w['w0_0']/3 + w['w1_0']/3 - w['w2_0']/3 + 1], [w['w0_0']/3 + w['w1_0']/3 - w['w2_0']/3 + 3], [-w['w0_0']/3 - w['w1_0']/3 + w['w2_0']/3 + 4]]) assert A * A.pinv() * B == B # Overdetermined system (least squares results). A = Matrix([[1, 0], [0, 0], [0, 1]]) B = Matrix([3, 2, 1]) assert A.pinv_solve(B) == Matrix([3, 1]) # Proof the solution is not exact. assert A * A.pinv() * B != B def test_pinv_rank_deficient(): # Test the four properties of the pseudoinverse for various matrices. As = [Matrix([[1, 1, 1], [2, 2, 2]]), Matrix([[1, 0], [0, 0]]), Matrix([[1, 2], [2, 4], [3, 6]])] for A in As: A_pinv = A.pinv(method="RD") AAp = A * A_pinv ApA = A_pinv * A assert simplify(AAp * A) == A assert simplify(ApA * A_pinv) == A_pinv assert AAp.H == AAp assert ApA.H == ApA for A in As: A_pinv = A.pinv(method="ED") AAp = A * A_pinv ApA = A_pinv * A assert simplify(AAp * A) == A assert simplify(ApA * A_pinv) == A_pinv assert AAp.H == AAp assert ApA.H == ApA # Test solving with rank-deficient matrices. A = Matrix([[1, 0], [0, 0]]) # Exact, non-unique solution. B = Matrix([3, 0]) solution = A.pinv_solve(B) w1 = solution.atoms(Symbol).pop() assert w1.name == 'w1_0' assert solution == Matrix([3, w1]) assert A * A.pinv() * B == B # Least squares, non-unique solution. B = Matrix([3, 1]) solution = A.pinv_solve(B) w1 = solution.atoms(Symbol).pop() assert w1.name == 'w1_0' assert solution == Matrix([3, w1]) assert A * A.pinv() * B != B def test_gauss_jordan_solve(): # Square, full rank, unique solution A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) b = Matrix([3, 6, 9]) sol, params = A.gauss_jordan_solve(b) assert sol == Matrix([[-1], [2], [0]]) assert params == Matrix(0, 1, []) # Square, full rank, unique solution, B has more columns than rows A = eye(3) B = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) sol, params = A.gauss_jordan_solve(B) assert sol == B assert params == Matrix(0, 4, []) # Square, reduced rank, parametrized solution A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) b = Matrix([3, 6, 9]) sol, params, freevar = A.gauss_jordan_solve(b, freevar=True) w = {} for s in sol.atoms(Symbol): # Extract dummy symbols used in the solution. w[s.name] = s assert sol == Matrix([[w['tau0'] - 1], [-2*w['tau0'] + 2], [w['tau0']]]) assert params == Matrix([[w['tau0']]]) assert freevar == [2] # Square, reduced rank, parametrized solution, B has two columns A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) B = Matrix([[3, 4], [6, 8], [9, 12]]) sol, params, freevar = A.gauss_jordan_solve(B, freevar=True) w = {} for s in sol.atoms(Symbol): # Extract dummy symbols used in the solution. w[s.name] = s assert sol == Matrix([[w['tau0'] - 1, w['tau1'] - Rational(4, 3)], [-2*w['tau0'] + 2, -2*w['tau1'] + Rational(8, 3)], [w['tau0'], w['tau1']],]) assert params == Matrix([[w['tau0'], w['tau1']]]) assert freevar == [2] # Square, reduced rank, parametrized solution A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]]) b = Matrix([0, 0, 0]) sol, params = A.gauss_jordan_solve(b) w = {} for s in sol.atoms(Symbol): w[s.name] = s assert sol == Matrix([[-2*w['tau0'] - 3*w['tau1']], [w['tau0']], [w['tau1']]]) assert params == Matrix([[w['tau0']], [w['tau1']]]) # Square, reduced rank, parametrized solution A = Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) b = Matrix([0, 0, 0]) sol, params = A.gauss_jordan_solve(b) w = {} for s in sol.atoms(Symbol): w[s.name] = s assert sol == Matrix([[w['tau0']], [w['tau1']], [w['tau2']]]) assert params == Matrix([[w['tau0']], [w['tau1']], [w['tau2']]]) # Square, reduced rank, no solution A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]]) b = Matrix([0, 0, 1]) raises(ValueError, lambda: A.gauss_jordan_solve(b)) # Rectangular, tall, full rank, unique solution A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]]) b = Matrix([0, 0, 1, 0]) sol, params = A.gauss_jordan_solve(b) assert sol == Matrix([[Rational(-1, 2)], [0], [Rational(1, 6)]]) assert params == Matrix(0, 1, []) # Rectangular, tall, full rank, unique solution, B has less columns than rows A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]]) B = Matrix([[0,0], [0, 0], [1, 2], [0, 0]]) sol, params = A.gauss_jordan_solve(B) assert sol == Matrix([[Rational(-1, 2), Rational(-2, 2)], [0, 0], [Rational(1, 6), Rational(2, 6)]]) assert params == Matrix(0, 2, []) # Rectangular, tall, full rank, no solution A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]]) b = Matrix([0, 0, 0, 1]) raises(ValueError, lambda: A.gauss_jordan_solve(b)) # Rectangular, tall, full rank, no solution, B has two columns (2nd has no solution) A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]]) B = Matrix([[0,0], [0, 0], [1, 0], [0, 1]]) raises(ValueError, lambda: A.gauss_jordan_solve(B)) # Rectangular, tall, full rank, no solution, B has two columns (1st has no solution) A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]]) B = Matrix([[0,0], [0, 0], [0, 1], [1, 0]]) raises(ValueError, lambda: A.gauss_jordan_solve(B)) # Rectangular, tall, reduced rank, parametrized solution A = Matrix([[1, 5, 3], [2, 10, 6], [3, 15, 9], [1, 4, 3]]) b = Matrix([0, 0, 0, 1]) sol, params = A.gauss_jordan_solve(b) w = {} for s in sol.atoms(Symbol): w[s.name] = s assert sol == Matrix([[-3*w['tau0'] + 5], [-1], [w['tau0']]]) assert params == Matrix([[w['tau0']]]) # Rectangular, tall, reduced rank, no solution A = Matrix([[1, 5, 3], [2, 10, 6], [3, 15, 9], [1, 4, 3]]) b = Matrix([0, 0, 1, 1]) raises(ValueError, lambda: A.gauss_jordan_solve(b)) # Rectangular, wide, full rank, parametrized solution A = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 1, 12]]) b = Matrix([1, 1, 1]) sol, params = A.gauss_jordan_solve(b) w = {} for s in sol.atoms(Symbol): w[s.name] = s assert sol == Matrix([[2*w['tau0'] - 1], [-3*w['tau0'] + 1], [0], [w['tau0']]]) assert params == Matrix([[w['tau0']]]) # Rectangular, wide, reduced rank, parametrized solution A = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [2, 4, 6, 8]]) b = Matrix([0, 1, 0]) sol, params = A.gauss_jordan_solve(b) w = {} for s in sol.atoms(Symbol): w[s.name] = s assert sol == Matrix([[w['tau0'] + 2*w['tau1'] + S.Half], [-2*w['tau0'] - 3*w['tau1'] - Rational(1, 4)], [w['tau0']], [w['tau1']]]) assert params == Matrix([[w['tau0']], [w['tau1']]]) # watch out for clashing symbols x0, x1, x2, _x0 = symbols('_tau0 _tau1 _tau2 tau1') M = Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, _x0]]) A = M[:, :-1] b = M[:, -1:] sol, params = A.gauss_jordan_solve(b) assert params == Matrix(3, 1, [x0, x1, x2]) assert sol == Matrix(5, 1, [x0, 0, x1, _x0, x2]) # Rectangular, wide, reduced rank, no solution A = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [2, 4, 6, 8]]) b = Matrix([1, 1, 1]) raises(ValueError, lambda: A.gauss_jordan_solve(b)) # Test for immutable matrix A = ImmutableMatrix([[1, 0], [0, 1]]) B = ImmutableMatrix([1, 2]) sol, params = A.gauss_jordan_solve(B) assert sol == ImmutableMatrix([1, 2]) assert params == ImmutableMatrix(0, 1, []) assert sol.__class__ == ImmutableDenseMatrix assert params.__class__ == ImmutableDenseMatrix # Test placement of free variables A = Matrix([[1, 0, 0, 0], [0, 0, 0, 1]]) b = Matrix([1, 1]) sol, params = A.gauss_jordan_solve(b) w = {} for s in sol.atoms(Symbol): w[s.name] = s assert sol == Matrix([[1], [w['tau0']], [w['tau1']], [1]]) assert params == Matrix([[w['tau0']], [w['tau1']]]) def test_linsolve_underdetermined_AND_gauss_jordan_solve(): #Test placement of free variables as per issue 19815 A = Matrix([[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]]) B = Matrix([1, 2, 1, 1, 1, 1, 1, 2]) sol, params = A.gauss_jordan_solve(B) w = {} for s in sol.atoms(Symbol): w[s.name] = s assert params == Matrix([[w['tau0']], [w['tau1']], [w['tau2']], [w['tau3']], [w['tau4']], [w['tau5']]]) assert sol == Matrix([[1 - 1*w['tau2']], [w['tau2']], [1 - 1*w['tau0'] + w['tau1']], [w['tau0']], [w['tau3'] + w['tau4']], [-1*w['tau3'] - 1*w['tau4'] - 1*w['tau1']], [1 - 1*w['tau2']], [w['tau1']], [w['tau2']], [w['tau3']], [w['tau4']], [1 - 1*w['tau5']], [w['tau5']], [1]]) from sympy.abc import j,f # https://github.com/sympy/sympy/issues/20046 A = Matrix([ [1, 1, 1, 1, 1, 1, 1, 1, 1], [0, -1, 0, -1, 0, -1, 0, -1, -j], [0, 0, 0, 0, 1, 1, 1, 1, f] ]) sol_1=Matrix(list(linsolve(A))[0]) tau0, tau1, tau2, tau3, tau4 = symbols('tau:5') assert sol_1 == Matrix([[-f - j - tau0 + tau2 + tau4 + 1], [j - tau1 - tau2 - tau4], [tau0], [tau1], [f - tau2 - tau3 - tau4], [tau2], [tau3], [tau4]]) # https://github.com/sympy/sympy/issues/19815 sol_2 = A[ : , : -1 ] * sol_1 - A[ : , -1 ] assert sol_2 == Matrix([[0] , [0] , [0]]) def test_solve(): A = Matrix([[1,2], [2,4]]) b = Matrix([[3], [4]]) raises(ValueError, lambda: A.solve(b)) #no solution b = Matrix([[ 4], [8]]) raises(ValueError, lambda: A.solve(b)) #infinite solution
c505752bcf228e6f4e793cce47ebbca9c1fc0051e678140a1b6fcdf7dc52198c
from sympy import Rational, I, expand_mul, S, simplify from sympy.matrices.matrices import NonSquareMatrixError from sympy.matrices import Matrix, zeros, eye, SparseMatrix from sympy.abc import x, y, z from sympy.testing.pytest import raises from sympy.testing.matrices import allclose def test_LUdecomp(): testmat = Matrix([[0, 2, 5, 3], [3, 3, 7, 4], [8, 4, 0, 2], [-2, 6, 3, 4]]) L, U, p = testmat.LUdecomposition() assert L.is_lower assert U.is_upper assert (L*U).permute_rows(p, 'backward') - testmat == zeros(4) testmat = Matrix([[6, -2, 7, 4], [0, 3, 6, 7], [1, -2, 7, 4], [-9, 2, 6, 3]]) L, U, p = testmat.LUdecomposition() assert L.is_lower assert U.is_upper assert (L*U).permute_rows(p, 'backward') - testmat == zeros(4) # non-square testmat = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) L, U, p = testmat.LUdecomposition(rankcheck=False) assert L.is_lower assert U.is_upper assert (L*U).permute_rows(p, 'backward') - testmat == zeros(4, 3) # square and singular testmat = Matrix([[1, 2, 3], [2, 4, 6], [4, 5, 6]]) L, U, p = testmat.LUdecomposition(rankcheck=False) assert L.is_lower assert U.is_upper assert (L*U).permute_rows(p, 'backward') - testmat == zeros(3) M = Matrix(((1, x, 1), (2, y, 0), (y, 0, z))) L, U, p = M.LUdecomposition() assert L.is_lower assert U.is_upper assert (L*U).permute_rows(p, 'backward') - M == zeros(3) mL = Matrix(( (1, 0, 0), (2, 3, 0), )) assert mL.is_lower is True assert mL.is_upper is False mU = Matrix(( (1, 2, 3), (0, 4, 5), )) assert mU.is_lower is False assert mU.is_upper is True # test FF LUdecomp M = Matrix([[1, 3, 3], [3, 2, 6], [3, 2, 2]]) P, L, Dee, U = M.LUdecompositionFF() assert P*M == L*Dee.inv()*U M = Matrix([[1, 2, 3, 4], [3, -1, 2, 3], [3, 1, 3, -2], [6, -1, 0, 2]]) P, L, Dee, U = M.LUdecompositionFF() assert P*M == L*Dee.inv()*U M = Matrix([[0, 0, 1], [2, 3, 0], [3, 1, 4]]) P, L, Dee, U = M.LUdecompositionFF() assert P*M == L*Dee.inv()*U # issue 15794 M = Matrix( [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) raises(ValueError, lambda : M.LUdecomposition_Simple(rankcheck=True)) def test_QR(): A = Matrix([[1, 2], [2, 3]]) Q, S = A.QRdecomposition() R = Rational assert Q == Matrix([ [ 5**R(-1, 2), (R(2)/5)*(R(1)/5)**R(-1, 2)], [2*5**R(-1, 2), (-R(1)/5)*(R(1)/5)**R(-1, 2)]]) assert S == Matrix([[5**R(1, 2), 8*5**R(-1, 2)], [0, (R(1)/5)**R(1, 2)]]) assert Q*S == A assert Q.T * Q == eye(2) A = Matrix([[1, 1, 1], [1, 1, 3], [2, 3, 4]]) Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R A = Matrix([[12, 0, -51], [6, 0, 167], [-4, 0, 24]]) Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R def test_QR_non_square(): # Narrow (cols < rows) matrices A = Matrix([[9, 0, 26], [12, 0, -7], [0, 4, 4], [0, -3, -3]]) Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R A = Matrix([[1, -1, 4], [1, 4, -2], [1, 4, 2], [1, -1, 0]]) Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R A = Matrix(2, 1, [1, 2]) Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R # Wide (cols > rows) matrices A = Matrix([[1, 2, 3], [4, 5, 6]]) Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R A = Matrix([[1, 2, 3, 4], [1, 4, 9, 16], [1, 8, 27, 64]]) Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R A = Matrix(1, 2, [1, 2]) Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R def test_QR_trivial(): # Rank deficient matrices A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R A = Matrix([[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]]) Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R A = Matrix([[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]]).T Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R # Zero rank matrices A = Matrix([[0, 0, 0]]) Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R A = Matrix([[0, 0, 0]]).T Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R A = Matrix([[0, 0, 0], [0, 0, 0]]) Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R A = Matrix([[0, 0, 0], [0, 0, 0]]).T Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R # Rank deficient matrices with zero norm from beginning columns A = Matrix([[0, 0, 0], [1, 2, 3]]).T Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R A = Matrix([[0, 0, 0, 0], [1, 2, 3, 4], [0, 0, 0, 0]]).T Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R A = Matrix([[0, 0, 0, 0], [1, 2, 3, 4], [0, 0, 0, 0], [2, 4, 6, 8]]).T Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R A = Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 2, 3]]).T Q, R = A.QRdecomposition() assert Q.T * Q == eye(Q.cols) assert R.is_upper assert A == Q*R def test_QR_float(): A = Matrix([[1, 1], [1, 1.01]]) Q, R = A.QRdecomposition() assert allclose(Q * R, A) assert allclose(Q * Q.T, Matrix.eye(2)) assert allclose(Q.T * Q, Matrix.eye(2)) A = Matrix([[1, 1], [1, 1.001]]) Q, R = A.QRdecomposition() assert allclose(Q * R, A) assert allclose(Q * Q.T, Matrix.eye(2)) assert allclose(Q.T * Q, Matrix.eye(2)) def test_LUdecomposition_Simple_iszerofunc(): # Test if callable passed to matrices.LUdecomposition_Simple() as iszerofunc keyword argument is used inside # matrices.LUdecomposition_Simple() magic_string = "I got passed in!" def goofyiszero(value): raise ValueError(magic_string) try: lu, p = Matrix([[1, 0], [0, 1]]).LUdecomposition_Simple(iszerofunc=goofyiszero) except ValueError as err: assert magic_string == err.args[0] return assert False def test_LUdecomposition_iszerofunc(): # Test if callable passed to matrices.LUdecomposition() as iszerofunc keyword argument is used inside # matrices.LUdecomposition_Simple() magic_string = "I got passed in!" def goofyiszero(value): raise ValueError(magic_string) try: l, u, p = Matrix([[1, 0], [0, 1]]).LUdecomposition(iszerofunc=goofyiszero) except ValueError as err: assert magic_string == err.args[0] return assert False def test_LDLdecomposition(): raises(NonSquareMatrixError, lambda: Matrix((1, 2)).LDLdecomposition()) raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).LDLdecomposition()) raises(ValueError, lambda: Matrix(((5 + I, 0), (0, 1))).LDLdecomposition()) raises(ValueError, lambda: Matrix(((1, 5), (5, 1))).LDLdecomposition()) raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).LDLdecomposition(hermitian=False)) A = Matrix(((1, 5), (5, 1))) L, D = A.LDLdecomposition(hermitian=False) assert L * D * L.T == A A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) L, D = A.LDLdecomposition() assert L * D * L.T == A assert L.is_lower assert L == Matrix([[1, 0, 0], [ Rational(3, 5), 1, 0], [Rational(-1, 5), Rational(1, 3), 1]]) assert D.is_diagonal() assert D == Matrix([[25, 0, 0], [0, 9, 0], [0, 0, 9]]) A = Matrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11))) L, D = A.LDLdecomposition() assert expand_mul(L * D * L.H) == A assert L.expand() == Matrix([[1, 0, 0], [I/2, 1, 0], [S.Half - I/2, 0, 1]]) assert D.expand() == Matrix(((4, 0, 0), (0, 1, 0), (0, 0, 9))) raises(NonSquareMatrixError, lambda: SparseMatrix((1, 2)).LDLdecomposition()) raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).LDLdecomposition()) raises(ValueError, lambda: SparseMatrix(((5 + I, 0), (0, 1))).LDLdecomposition()) raises(ValueError, lambda: SparseMatrix(((1, 5), (5, 1))).LDLdecomposition()) raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).LDLdecomposition(hermitian=False)) A = SparseMatrix(((1, 5), (5, 1))) L, D = A.LDLdecomposition(hermitian=False) assert L * D * L.T == A A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) L, D = A.LDLdecomposition() assert L * D * L.T == A assert L.is_lower assert L == Matrix([[1, 0, 0], [ Rational(3, 5), 1, 0], [Rational(-1, 5), Rational(1, 3), 1]]) assert D.is_diagonal() assert D == Matrix([[25, 0, 0], [0, 9, 0], [0, 0, 9]]) A = SparseMatrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11))) L, D = A.LDLdecomposition() assert expand_mul(L * D * L.H) == A assert L == Matrix(((1, 0, 0), (I/2, 1, 0), (S.Half - I/2, 0, 1))) assert D == Matrix(((4, 0, 0), (0, 1, 0), (0, 0, 9))) def test_pinv_succeeds_with_rank_decomposition_method(): # Test rank decomposition method of pseudoinverse succeeding As = [Matrix([ [61, 89, 55, 20, 71, 0], [62, 96, 85, 85, 16, 0], [69, 56, 17, 4, 54, 0], [10, 54, 91, 41, 71, 0], [ 7, 30, 10, 48, 90, 0], [0,0,0,0,0,0]])] for A in As: A_pinv = A.pinv(method="RD") AAp = A * A_pinv ApA = A_pinv * A assert simplify(AAp * A) == A assert simplify(ApA * A_pinv) == A_pinv assert AAp.H == AAp assert ApA.H == ApA def test_rank_decomposition(): a = Matrix(0, 0, []) c, f = a.rank_decomposition() assert f.is_echelon assert c.cols == f.rows == a.rank() assert c * f == a a = Matrix(1, 1, [5]) c, f = a.rank_decomposition() assert f.is_echelon assert c.cols == f.rows == a.rank() assert c * f == a a = Matrix(3, 3, [1, 2, 3, 1, 2, 3, 1, 2, 3]) c, f = a.rank_decomposition() assert f.is_echelon assert c.cols == f.rows == a.rank() assert c * f == a a = Matrix([ [0, 0, 1, 2, 2, -5, 3], [-1, 5, 2, 2, 1, -7, 5], [0, 0, -2, -3, -3, 8, -5], [-1, 5, 0, -1, -2, 1, 0]]) c, f = a.rank_decomposition() assert f.is_echelon assert c.cols == f.rows == a.rank() assert c * f == a
b37665c80cf737bba218bd89b7bb4d015df3e51ff94b30193470cbc7c1d79eb1
import random import concurrent.futures from collections.abc import Hashable from sympy import ( Abs, Add, E, Float, I, Integer, Max, Min, Poly, Pow, PurePoly, Rational, S, Symbol, cos, exp, log, oo, pi, signsimp, simplify, sin, sqrt, symbols, sympify, trigsimp, tan, sstr, diff, Function, expand, FiniteSet) from sympy.matrices.matrices import (ShapeError, MatrixError, NonSquareMatrixError, DeferredVector, _find_reasonable_pivot_naive, _simplify) from sympy.matrices import ( GramSchmidt, ImmutableMatrix, ImmutableSparseMatrix, Matrix, SparseMatrix, casoratian, diag, eye, hessian, matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2, rot_axis3, wronskian, zeros, MutableDenseMatrix, ImmutableDenseMatrix, MatrixSymbol, dotprodsimp) from sympy.matrices.utilities import _dotprodsimp_state from sympy.core.compatibility import iterable from sympy.core import Tuple, Wild from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.utilities.iterables import flatten, capture from sympy.testing.pytest import raises, XFAIL, skip, warns_deprecated_sympy from sympy.assumptions import Q from sympy.tensor.array import Array from sympy.matrices.expressions import MatPow from sympy.abc import a, b, c, d, x, y, z, t # don't re-order this list classes = (Matrix, SparseMatrix, ImmutableMatrix, ImmutableSparseMatrix) def test_args(): for n, cls in enumerate(classes): m = cls.zeros(3, 2) # all should give back the same type of arguments, e.g. ints for shape assert m.shape == (3, 2) and all(type(i) is int for i in m.shape) assert m.rows == 3 and type(m.rows) is int assert m.cols == 2 and type(m.cols) is int if not n % 2: assert type(m._mat) in (list, tuple, Tuple) else: assert type(m._smat) is dict def test_division(): v = Matrix(1, 2, [x, y]) assert v/z == Matrix(1, 2, [x/z, y/z]) def test_sum(): m = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]]) assert m + m == Matrix([[2, 4, 6], [2*x, 2*y, 2*x], [4*y, -100, 2*z*x]]) n = Matrix(1, 2, [1, 2]) raises(ShapeError, lambda: m + n) def test_abs(): m = Matrix(1, 2, [-3, x]) n = Matrix(1, 2, [3, Abs(x)]) assert abs(m) == n def test_addition(): a = Matrix(( (1, 2), (3, 1), )) b = Matrix(( (1, 2), (3, 0), )) assert a + b == a.add(b) == Matrix([[2, 4], [6, 1]]) def test_fancy_index_matrix(): for M in (Matrix, SparseMatrix): a = M(3, 3, range(9)) assert a == a[:, :] assert a[1, :] == Matrix(1, 3, [3, 4, 5]) assert a[:, 1] == Matrix([1, 4, 7]) assert a[[0, 1], :] == Matrix([[0, 1, 2], [3, 4, 5]]) assert a[[0, 1], 2] == a[[0, 1], [2]] assert a[2, [0, 1]] == a[[2], [0, 1]] assert a[:, [0, 1]] == Matrix([[0, 1], [3, 4], [6, 7]]) assert a[0, 0] == 0 assert a[0:2, :] == Matrix([[0, 1, 2], [3, 4, 5]]) assert a[:, 0:2] == Matrix([[0, 1], [3, 4], [6, 7]]) assert a[::2, 1] == a[[0, 2], 1] assert a[1, ::2] == a[1, [0, 2]] a = M(3, 3, range(9)) assert a[[0, 2, 1, 2, 1], :] == Matrix([ [0, 1, 2], [6, 7, 8], [3, 4, 5], [6, 7, 8], [3, 4, 5]]) assert a[:, [0,2,1,2,1]] == Matrix([ [0, 2, 1, 2, 1], [3, 5, 4, 5, 4], [6, 8, 7, 8, 7]]) a = SparseMatrix.zeros(3) a[1, 2] = 2 a[0, 1] = 3 a[2, 0] = 4 assert a.extract([1, 1], [2]) == Matrix([ [2], [2]]) assert a.extract([1, 0], [2, 2, 2]) == Matrix([ [2, 2, 2], [0, 0, 0]]) assert a.extract([1, 0, 1, 2], [2, 0, 1, 0]) == Matrix([ [2, 0, 0, 0], [0, 0, 3, 0], [2, 0, 0, 0], [0, 4, 0, 4]]) def test_multiplication(): a = Matrix(( (1, 2), (3, 1), (0, 6), )) b = Matrix(( (1, 2), (3, 0), )) c = a*b assert c[0, 0] == 7 assert c[0, 1] == 2 assert c[1, 0] == 6 assert c[1, 1] == 6 assert c[2, 0] == 18 assert c[2, 1] == 0 try: eval('c = a @ b') except SyntaxError: pass else: assert c[0, 0] == 7 assert c[0, 1] == 2 assert c[1, 0] == 6 assert c[1, 1] == 6 assert c[2, 0] == 18 assert c[2, 1] == 0 h = matrix_multiply_elementwise(a, c) assert h == a.multiply_elementwise(c) assert h[0, 0] == 7 assert h[0, 1] == 4 assert h[1, 0] == 18 assert h[1, 1] == 6 assert h[2, 0] == 0 assert h[2, 1] == 0 raises(ShapeError, lambda: matrix_multiply_elementwise(a, b)) c = b * Symbol("x") assert isinstance(c, Matrix) assert c[0, 0] == x assert c[0, 1] == 2*x assert c[1, 0] == 3*x assert c[1, 1] == 0 c2 = x * b assert c == c2 c = 5 * b assert isinstance(c, Matrix) assert c[0, 0] == 5 assert c[0, 1] == 2*5 assert c[1, 0] == 3*5 assert c[1, 1] == 0 try: eval('c = 5 @ b') except SyntaxError: pass else: assert isinstance(c, Matrix) assert c[0, 0] == 5 assert c[0, 1] == 2*5 assert c[1, 0] == 3*5 assert c[1, 1] == 0 def test_power(): raises(NonSquareMatrixError, lambda: Matrix((1, 2))**2) R = Rational A = Matrix([[2, 3], [4, 5]]) assert (A**-3)[:] == [R(-269)/8, R(153)/8, R(51)/2, R(-29)/2] assert (A**5)[:] == [6140, 8097, 10796, 14237] A = Matrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]]) assert (A**3)[:] == [290, 262, 251, 448, 440, 368, 702, 954, 433] assert A**0 == eye(3) assert A**1 == A assert (Matrix([[2]]) ** 100)[0, 0] == 2**100 assert eye(2)**10000000 == eye(2) assert Matrix([[1, 2], [3, 4]])**Integer(2) == Matrix([[7, 10], [15, 22]]) A = Matrix([[33, 24], [48, 57]]) assert (A**S.Half)[:] == [5, 2, 4, 7] A = Matrix([[0, 4], [-1, 5]]) assert (A**S.Half)**2 == A assert Matrix([[1, 0], [1, 1]])**S.Half == Matrix([[1, 0], [S.Half, 1]]) assert Matrix([[1, 0], [1, 1]])**0.5 == Matrix([[1.0, 0], [0.5, 1.0]]) from sympy.abc import a, b, n assert Matrix([[1, a], [0, 1]])**n == Matrix([[1, a*n], [0, 1]]) assert Matrix([[b, a], [0, b]])**n == Matrix([[b**n, a*b**(n-1)*n], [0, b**n]]) assert Matrix([ [a**n, a**(n - 1)*n, (a**n*n**2 - a**n*n)/(2*a**2)], [ 0, a**n, a**(n - 1)*n], [ 0, 0, a**n]]) assert Matrix([[a, 1, 0], [0, a, 0], [0, 0, b]])**n == Matrix([ [a**n, a**(n-1)*n, 0], [0, a**n, 0], [0, 0, b**n]]) A = Matrix([[1, 0], [1, 7]]) assert A._matrix_pow_by_jordan_blocks(S(3)) == A._eval_pow_by_recursion(3) A = Matrix([[2]]) assert A**10 == Matrix([[2**10]]) == A._matrix_pow_by_jordan_blocks(S(10)) == \ A._eval_pow_by_recursion(10) # testing a matrix that cannot be jordan blocked issue 11766 m = Matrix([[3, 0, 0, 0, -3], [0, -3, -3, 0, 3], [0, 3, 0, 3, 0], [0, 0, 3, 0, 3], [3, 0, 0, 3, 0]]) raises(MatrixError, lambda: m._matrix_pow_by_jordan_blocks(S(10))) # test issue 11964 raises(MatrixError, lambda: Matrix([[1, 1], [3, 3]])._matrix_pow_by_jordan_blocks(S(-10))) A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 0]]) # Nilpotent jordan block size 3 assert A**10.0 == Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) raises(ValueError, lambda: A**2.1) raises(ValueError, lambda: A**Rational(3, 2)) A = Matrix([[8, 1], [3, 2]]) assert A**10.0 == Matrix([[1760744107, 272388050], [817164150, 126415807]]) A = Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]]) # Nilpotent jordan block size 1 assert A**10.0 == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]]) A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 1]]) # Nilpotent jordan block size 2 assert A**10.0 == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]]) n = Symbol('n', integer=True) assert isinstance(A**n, MatPow) n = Symbol('n', integer=True, negative=True) raises(ValueError, lambda: A**n) n = Symbol('n', integer=True, nonnegative=True) assert A**n == Matrix([ [KroneckerDelta(0, n), KroneckerDelta(1, n), -KroneckerDelta(0, n) - KroneckerDelta(1, n) + 1], [ 0, KroneckerDelta(0, n), 1 - KroneckerDelta(0, n)], [ 0, 0, 1]]) assert A**(n + 2) == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]]) raises(ValueError, lambda: A**Rational(3, 2)) A = Matrix([[0, 0, 1], [3, 0, 1], [4, 3, 1]]) assert A**5.0 == Matrix([[168, 72, 89], [291, 144, 161], [572, 267, 329]]) assert A**5.0 == A**5 A = Matrix([[0, 1, 0],[-1, 0, 0],[0, 0, 0]]) n = Symbol("n") An = A**n assert An.subs(n, 2).doit() == A**2 raises(ValueError, lambda: An.subs(n, -2).doit()) assert An * An == A**(2*n) # concretizing behavior for non-integer and complex powers A = Matrix([[0,0,0],[0,0,0],[0,0,0]]) n = Symbol('n', integer=True, positive=True) assert A**n == A n = Symbol('n', integer=True, nonnegative=True) assert A**n == diag(0**n, 0**n, 0**n) assert (A**n).subs(n, 0) == eye(3) assert (A**n).subs(n, 1) == zeros(3) A = Matrix ([[2,0,0],[0,2,0],[0,0,2]]) assert A**2.1 == diag (2**2.1, 2**2.1, 2**2.1) assert A**I == diag (2**I, 2**I, 2**I) A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 1]]) raises(ValueError, lambda: A**2.1) raises(ValueError, lambda: A**I) A = Matrix([[S.Half, S.Half], [S.Half, S.Half]]) assert A**S.Half == A A = Matrix([[1, 1],[3, 3]]) assert A**S.Half == Matrix ([[S.Half, S.Half], [3*S.Half, 3*S.Half]]) def test_issue_17247_expression_blowup_1(): M = Matrix([[1+x, 1-x], [1-x, 1+x]]) with dotprodsimp(True): assert M.exp().expand() == Matrix([ [ (exp(2*x) + exp(2))/2, (-exp(2*x) + exp(2))/2], [(-exp(2*x) + exp(2))/2, (exp(2*x) + exp(2))/2]]) def test_issue_17247_expression_blowup_2(): M = Matrix([[1+x, 1-x], [1-x, 1+x]]) with dotprodsimp(True): P, J = M.jordan_form () assert P*J*P.inv() def test_issue_17247_expression_blowup_3(): M = Matrix([[1+x, 1-x], [1-x, 1+x]]) with dotprodsimp(True): assert M**100 == Matrix([ [633825300114114700748351602688*x**100 + 633825300114114700748351602688, 633825300114114700748351602688 - 633825300114114700748351602688*x**100], [633825300114114700748351602688 - 633825300114114700748351602688*x**100, 633825300114114700748351602688*x**100 + 633825300114114700748351602688]]) def test_issue_17247_expression_blowup_4(): # This matrix takes extremely long on current master even with intermediate simplification so an abbreviated version is used. It is left here for test in case of future optimizations. # M = Matrix(S('''[ # [ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128, 3/64 + 13*I/64, -23/32 - 59*I/256, 15/128 - 3*I/32, 19/256 + 551*I/1024], # [-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024, 119/128 + 143*I/128, -10879/2048 + 4343*I/4096, 129/256 - 549*I/512, 42533/16384 + 29103*I/8192], # [ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128, 3/64 + 13*I/64, -23/32 - 59*I/256], # [ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024, 119/128 + 143*I/128, -10879/2048 + 4343*I/4096], # [ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128], # [ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024], # [ -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64], # [ 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512], # [ -4*I, 27/2 + 6*I, -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64], # [ 1/4 + 5*I/2, -23/8 - 57*I/16, 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128], # [ -4, 9 - 5*I, -4*I, 27/2 + 6*I, -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16], # [ -2*I, 119/8 + 29*I/4, 1/4 + 5*I/2, -23/8 - 57*I/16, 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]''')) # assert M**10 == Matrix([ # [ 7*(-221393644768594642173548179825793834595 - 1861633166167425978847110897013541127952*I)/9671406556917033397649408, 15*(31670992489131684885307005100073928751695 + 10329090958303458811115024718207404523808*I)/77371252455336267181195264, 7*(-3710978679372178839237291049477017392703 + 1377706064483132637295566581525806894169*I)/19342813113834066795298816, (9727707023582419994616144751727760051598 - 59261571067013123836477348473611225724433*I)/9671406556917033397649408, (31896723509506857062605551443641668183707 + 54643444538699269118869436271152084599580*I)/38685626227668133590597632, (-2024044860947539028275487595741003997397402 + 130959428791783397562960461903698670485863*I)/309485009821345068724781056, 3*(26190251453797590396533756519358368860907 - 27221191754180839338002754608545400941638*I)/77371252455336267181195264, (1154643595139959842768960128434994698330461 + 3385496216250226964322872072260446072295634*I)/618970019642690137449562112, 3*(-31849347263064464698310044805285774295286 - 11877437776464148281991240541742691164309*I)/77371252455336267181195264, (4661330392283532534549306589669150228040221 - 4171259766019818631067810706563064103956871*I)/1237940039285380274899124224, (9598353794289061833850770474812760144506 + 358027153990999990968244906482319780943983*I)/309485009821345068724781056, (-9755135335127734571547571921702373498554177 - 4837981372692695195747379349593041939686540*I)/2475880078570760549798248448], # [(-379516731607474268954110071392894274962069 - 422272153179747548473724096872271700878296*I)/77371252455336267181195264, (41324748029613152354787280677832014263339501 - 12715121258662668420833935373453570749288074*I)/1237940039285380274899124224, (-339216903907423793947110742819264306542397 + 494174755147303922029979279454787373566517*I)/77371252455336267181195264, (-18121350839962855576667529908850640619878381 - 37413012454129786092962531597292531089199003*I)/1237940039285380274899124224, (2489661087330511608618880408199633556675926 + 1137821536550153872137379935240732287260863*I)/309485009821345068724781056, (-136644109701594123227587016790354220062972119 + 110130123468183660555391413889600443583585272*I)/4951760157141521099596496896, (1488043981274920070468141664150073426459593 - 9691968079933445130866371609614474474327650*I)/1237940039285380274899124224, 27*(4636797403026872518131756991410164760195942 + 3369103221138229204457272860484005850416533*I)/4951760157141521099596496896, (-8534279107365915284081669381642269800472363 + 2241118846262661434336333368511372725482742*I)/1237940039285380274899124224, (60923350128174260992536531692058086830950875 - 263673488093551053385865699805250505661590126*I)/9903520314283042199192993792, (18520943561240714459282253753348921824172569 + 24846649186468656345966986622110971925703604*I)/4951760157141521099596496896, (-232781130692604829085973604213529649638644431 + 35981505277760667933017117949103953338570617*I)/9903520314283042199192993792], # [ (8742968295129404279528270438201520488950 + 3061473358639249112126847237482570858327*I)/4835703278458516698824704, (-245657313712011778432792959787098074935273 + 253113767861878869678042729088355086740856*I)/38685626227668133590597632, (1947031161734702327107371192008011621193 - 19462330079296259148177542369999791122762*I)/9671406556917033397649408, (552856485625209001527688949522750288619217 + 392928441196156725372494335248099016686580*I)/77371252455336267181195264, (-44542866621905323121630214897126343414629 + 3265340021421335059323962377647649632959*I)/19342813113834066795298816, (136272594005759723105646069956434264218730 - 330975364731707309489523680957584684763587*I)/38685626227668133590597632, (27392593965554149283318732469825168894401 + 75157071243800133880129376047131061115278*I)/38685626227668133590597632, 7*(-357821652913266734749960136017214096276154 - 45509144466378076475315751988405961498243*I)/309485009821345068724781056, (104485001373574280824835174390219397141149 - 99041000529599568255829489765415726168162*I)/77371252455336267181195264, (1198066993119982409323525798509037696321291 + 4249784165667887866939369628840569844519936*I)/618970019642690137449562112, (-114985392587849953209115599084503853611014 - 52510376847189529234864487459476242883449*I)/77371252455336267181195264, (6094620517051332877965959223269600650951573 - 4683469779240530439185019982269137976201163*I)/1237940039285380274899124224], # [ (611292255597977285752123848828590587708323 - 216821743518546668382662964473055912169502*I)/77371252455336267181195264, (-1144023204575811464652692396337616594307487 + 12295317806312398617498029126807758490062855*I)/309485009821345068724781056, (-374093027769390002505693378578475235158281 - 573533923565898290299607461660384634333639*I)/77371252455336267181195264, (47405570632186659000138546955372796986832987 - 2837476058950808941605000274055970055096534*I)/1237940039285380274899124224, (-571573207393621076306216726219753090535121 + 533381457185823100878764749236639320783831*I)/77371252455336267181195264, (-7096548151856165056213543560958582513797519 - 24035731898756040059329175131592138642195366*I)/618970019642690137449562112, (2396762128833271142000266170154694033849225 + 1448501087375679588770230529017516492953051*I)/309485009821345068724781056, (-150609293845161968447166237242456473262037053 + 92581148080922977153207018003184520294188436*I)/4951760157141521099596496896, 5*(270278244730804315149356082977618054486347 - 1997830155222496880429743815321662710091562*I)/1237940039285380274899124224, (62978424789588828258068912690172109324360330 + 44803641177219298311493356929537007630129097*I)/2475880078570760549798248448, 19*(-451431106327656743945775812536216598712236 + 114924966793632084379437683991151177407937*I)/1237940039285380274899124224, (63417747628891221594106738815256002143915995 - 261508229397507037136324178612212080871150958*I)/9903520314283042199192993792], # [ (-2144231934021288786200752920446633703357 + 2305614436009705803670842248131563850246*I)/1208925819614629174706176, (-90720949337459896266067589013987007078153 - 221951119475096403601562347412753844534569*I)/19342813113834066795298816, (11590973613116630788176337262688659880376 + 6514520676308992726483494976339330626159*I)/4835703278458516698824704, 3*(-131776217149000326618649542018343107657237 + 79095042939612668486212006406818285287004*I)/38685626227668133590597632, (10100577916793945997239221374025741184951 - 28631383488085522003281589065994018550748*I)/9671406556917033397649408, 67*(10090295594251078955008130473573667572549 + 10449901522697161049513326446427839676762*I)/77371252455336267181195264, (-54270981296988368730689531355811033930513 - 3413683117592637309471893510944045467443*I)/19342813113834066795298816, (440372322928679910536575560069973699181278 - 736603803202303189048085196176918214409081*I)/77371252455336267181195264, (33220374714789391132887731139763250155295 + 92055083048787219934030779066298919603554*I)/38685626227668133590597632, 5*(-594638554579967244348856981610805281527116 - 82309245323128933521987392165716076704057*I)/309485009821345068724781056, (128056368815300084550013708313312073721955 - 114619107488668120303579745393765245911404*I)/77371252455336267181195264, 21*(59839959255173222962789517794121843393573 + 241507883613676387255359616163487405826334*I)/618970019642690137449562112], # [ (-13454485022325376674626653802541391955147 + 184471402121905621396582628515905949793486*I)/19342813113834066795298816, (-6158730123400322562149780662133074862437105 - 3416173052604643794120262081623703514107476*I)/154742504910672534362390528, (770558003844914708453618983120686116100419 - 127758381209767638635199674005029818518766*I)/77371252455336267181195264, (-4693005771813492267479835161596671660631703 + 12703585094750991389845384539501921531449948*I)/309485009821345068724781056, (-295028157441149027913545676461260860036601 - 841544569970643160358138082317324743450770*I)/77371252455336267181195264, (56716442796929448856312202561538574275502893 + 7216818824772560379753073185990186711454778*I)/1237940039285380274899124224, 15*(-87061038932753366532685677510172566368387 + 61306141156647596310941396434445461895538*I)/154742504910672534362390528, (-3455315109680781412178133042301025723909347 - 24969329563196972466388460746447646686670670*I)/618970019642690137449562112, (2453418854160886481106557323699250865361849 + 1497886802326243014471854112161398141242514*I)/309485009821345068724781056, (-151343224544252091980004429001205664193082173 + 90471883264187337053549090899816228846836628*I)/4951760157141521099596496896, (1652018205533026103358164026239417416432989 - 9959733619236515024261775397109724431400162*I)/1237940039285380274899124224, 3*(40676374242956907656984876692623172736522006 + 31023357083037817469535762230872667581366205*I)/4951760157141521099596496896], # [ (-1226990509403328460274658603410696548387 - 4131739423109992672186585941938392788458*I)/1208925819614629174706176, (162392818524418973411975140074368079662703 + 23706194236915374831230612374344230400704*I)/9671406556917033397649408, (-3935678233089814180000602553655565621193 + 2283744757287145199688061892165659502483*I)/1208925819614629174706176, (-2400210250844254483454290806930306285131 - 315571356806370996069052930302295432758205*I)/19342813113834066795298816, (13365917938215281056563183751673390817910 + 15911483133819801118348625831132324863881*I)/4835703278458516698824704, 3*(-215950551370668982657516660700301003897855 + 51684341999223632631602864028309400489378*I)/38685626227668133590597632, (20886089946811765149439844691320027184765 - 30806277083146786592790625980769214361844*I)/9671406556917033397649408, (562180634592713285745940856221105667874855 + 1031543963988260765153550559766662245114916*I)/77371252455336267181195264, (-65820625814810177122941758625652476012867 - 12429918324787060890804395323920477537595*I)/19342813113834066795298816, (319147848192012911298771180196635859221089 - 402403304933906769233365689834404519960394*I)/38685626227668133590597632, (23035615120921026080284733394359587955057 + 115351677687031786114651452775242461310624*I)/38685626227668133590597632, (-3426830634881892756966440108592579264936130 - 1022954961164128745603407283836365128598559*I)/309485009821345068724781056], # [ (-192574788060137531023716449082856117537757 - 69222967328876859586831013062387845780692*I)/19342813113834066795298816, (2736383768828013152914815341491629299773262 - 2773252698016291897599353862072533475408743*I)/77371252455336267181195264, (-23280005281223837717773057436155921656805 + 214784953368021840006305033048142888879224*I)/19342813113834066795298816, (-3035247484028969580570400133318947903462326 - 2195168903335435855621328554626336958674325*I)/77371252455336267181195264, (984552428291526892214541708637840971548653 - 64006622534521425620714598573494988589378*I)/77371252455336267181195264, (-3070650452470333005276715136041262898509903 + 7286424705750810474140953092161794621989080*I)/154742504910672534362390528, (-147848877109756404594659513386972921139270 - 416306113044186424749331418059456047650861*I)/38685626227668133590597632, (55272118474097814260289392337160619494260781 + 7494019668394781211907115583302403519488058*I)/1237940039285380274899124224, (-581537886583682322424771088996959213068864 + 542191617758465339135308203815256798407429*I)/77371252455336267181195264, (-6422548983676355789975736799494791970390991 - 23524183982209004826464749309156698827737702*I)/618970019642690137449562112, 7*(180747195387024536886923192475064903482083 + 84352527693562434817771649853047924991804*I)/154742504910672534362390528, (-135485179036717001055310712747643466592387031 + 102346575226653028836678855697782273460527608*I)/4951760157141521099596496896], # [ (3384238362616083147067025892852431152105 + 156724444932584900214919898954874618256*I)/604462909807314587353088, (-59558300950677430189587207338385764871866 + 114427143574375271097298201388331237478857*I)/4835703278458516698824704, (-1356835789870635633517710130971800616227 - 7023484098542340388800213478357340875410*I)/1208925819614629174706176, (234884918567993750975181728413524549575881 + 79757294640629983786895695752733890213506*I)/9671406556917033397649408, (-7632732774935120473359202657160313866419 + 2905452608512927560554702228553291839465*I)/1208925819614629174706176, (52291747908702842344842889809762246649489 - 520996778817151392090736149644507525892649*I)/19342813113834066795298816, (17472406829219127839967951180375981717322 + 23464704213841582137898905375041819568669*I)/4835703278458516698824704, (-911026971811893092350229536132730760943307 + 150799318130900944080399439626714846752360*I)/38685626227668133590597632, (26234457233977042811089020440646443590687 - 45650293039576452023692126463683727692890*I)/9671406556917033397649408, 3*(288348388717468992528382586652654351121357 + 454526517721403048270274049572136109264668*I)/77371252455336267181195264, (-91583492367747094223295011999405657956347 - 12704691128268298435362255538069612411331*I)/19342813113834066795298816, (411208730251327843849027957710164064354221 - 569898526380691606955496789378230959965898*I)/38685626227668133590597632], # [ (27127513117071487872628354831658811211795 - 37765296987901990355760582016892124833857*I)/4835703278458516698824704, (1741779916057680444272938534338833170625435 + 3083041729779495966997526404685535449810378*I)/77371252455336267181195264, 3*(-60642236251815783728374561836962709533401 - 24630301165439580049891518846174101510744*I)/19342813113834066795298816, 3*(445885207364591681637745678755008757483408 - 350948497734812895032502179455610024541643*I)/38685626227668133590597632, (-47373295621391195484367368282471381775684 + 219122969294089357477027867028071400054973*I)/19342813113834066795298816, (-2801565819673198722993348253876353741520438 - 2250142129822658548391697042460298703335701*I)/77371252455336267181195264, (801448252275607253266997552356128790317119 - 50890367688077858227059515894356594900558*I)/77371252455336267181195264, (-5082187758525931944557763799137987573501207 + 11610432359082071866576699236013484487676124*I)/309485009821345068724781056, (-328925127096560623794883760398247685166830 - 643447969697471610060622160899409680422019*I)/77371252455336267181195264, 15*(2954944669454003684028194956846659916299765 + 33434406416888505837444969347824812608566*I)/1237940039285380274899124224, (-415749104352001509942256567958449835766827 + 479330966144175743357171151440020955412219*I)/77371252455336267181195264, 3*(-4639987285852134369449873547637372282914255 - 11994411888966030153196659207284951579243273*I)/1237940039285380274899124224], # [ (-478846096206269117345024348666145495601 + 1249092488629201351470551186322814883283*I)/302231454903657293676544, (-17749319421930878799354766626365926894989 - 18264580106418628161818752318217357231971*I)/1208925819614629174706176, (2801110795431528876849623279389579072819 + 363258850073786330770713557775566973248*I)/604462909807314587353088, (-59053496693129013745775512127095650616252 + 78143588734197260279248498898321500167517*I)/4835703278458516698824704, (-283186724922498212468162690097101115349 - 6443437753863179883794497936345437398276*I)/1208925819614629174706176, (188799118826748909206887165661384998787543 + 84274736720556630026311383931055307398820*I)/9671406556917033397649408, (-5482217151670072904078758141270295025989 + 1818284338672191024475557065444481298568*I)/1208925819614629174706176, (56564463395350195513805521309731217952281 - 360208541416798112109946262159695452898431*I)/19342813113834066795298816, 11*(1259539805728870739006416869463689438068 + 1409136581547898074455004171305324917387*I)/4835703278458516698824704, 5*(-123701190701414554945251071190688818343325 + 30997157322590424677294553832111902279712*I)/38685626227668133590597632, (16130917381301373033736295883982414239781 - 32752041297570919727145380131926943374516*I)/9671406556917033397649408, (650301385108223834347093740500375498354925 + 899526407681131828596801223402866051809258*I)/77371252455336267181195264], # [ (9011388245256140876590294262420614839483 + 8167917972423946282513000869327525382672*I)/1208925819614629174706176, (-426393174084720190126376382194036323028924 + 180692224825757525982858693158209545430621*I)/9671406556917033397649408, (24588556702197802674765733448108154175535 - 45091766022876486566421953254051868331066*I)/4835703278458516698824704, (1872113939365285277373877183750416985089691 + 3030392393733212574744122057679633775773130*I)/77371252455336267181195264, (-222173405538046189185754954524429864167549 - 75193157893478637039381059488387511299116*I)/19342813113834066795298816, (2670821320766222522963689317316937579844558 - 2645837121493554383087981511645435472169191*I)/77371252455336267181195264, 5*(-2100110309556476773796963197283876204940 + 41957457246479840487980315496957337371937*I)/19342813113834066795298816, (-5733743755499084165382383818991531258980593 - 3328949988392698205198574824396695027195732*I)/154742504910672534362390528, (707827994365259025461378911159398206329247 - 265730616623227695108042528694302299777294*I)/77371252455336267181195264, (-1442501604682933002895864804409322823788319 + 11504137805563265043376405214378288793343879*I)/309485009821345068724781056, (-56130472299445561499538726459719629522285 - 61117552419727805035810982426639329818864*I)/9671406556917033397649408, (39053692321126079849054272431599539429908717 - 10209127700342570953247177602860848130710666*I)/1237940039285380274899124224]]) M = Matrix(S('''[ [ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512], [ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64], [ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128], [ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16], [ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M**10 == Matrix(S('''[ [ 7369525394972778926719607798014571861/604462909807314587353088 - 229284202061790301477392339912557559*I/151115727451828646838272, -19704281515163975949388435612632058035/1208925819614629174706176 + 14319858347987648723768698170712102887*I/302231454903657293676544, -3623281909451783042932142262164941211/604462909807314587353088 - 6039240602494288615094338643452320495*I/604462909807314587353088, 109260497799140408739847239685705357695/2417851639229258349412352 - 7427566006564572463236368211555511431*I/2417851639229258349412352, -16095803767674394244695716092817006641/2417851639229258349412352 + 10336681897356760057393429626719177583*I/1208925819614629174706176, -42207883340488041844332828574359769743/2417851639229258349412352 - 182332262671671273188016400290188468499*I/4835703278458516698824704], [50566491050825573392726324995779608259/1208925819614629174706176 - 90047007594468146222002432884052362145*I/2417851639229258349412352, 74273703462900000967697427843983822011/1208925819614629174706176 + 265947522682943571171988741842776095421*I/1208925819614629174706176, -116900341394390200556829767923360888429/2417851639229258349412352 - 53153263356679268823910621474478756845*I/2417851639229258349412352, 195407378023867871243426523048612490249/1208925819614629174706176 - 1242417915995360200584837585002906728929*I/9671406556917033397649408, -863597594389821970177319682495878193/302231454903657293676544 + 476936100741548328800725360758734300481*I/9671406556917033397649408, -3154451590535653853562472176601754835575/19342813113834066795298816 - 232909875490506237386836489998407329215*I/2417851639229258349412352], [ -1715444997702484578716037230949868543/302231454903657293676544 + 5009695651321306866158517287924120777*I/302231454903657293676544, -30551582497996879620371947949342101301/604462909807314587353088 - 7632518367986526187139161303331519629*I/151115727451828646838272, 312680739924495153190604170938220575/18889465931478580854784 - 108664334509328818765959789219208459*I/75557863725914323419136, -14693696966703036206178521686918865509/604462909807314587353088 + 72345386220900843930147151999899692401*I/1208925819614629174706176, -8218872496728882299722894680635296519/1208925819614629174706176 - 16776782833358893712645864791807664983*I/1208925819614629174706176, 143237839169380078671242929143670635137/2417851639229258349412352 + 2883817094806115974748882735218469447*I/2417851639229258349412352], [ 3087979417831061365023111800749855987/151115727451828646838272 + 34441942370802869368851419102423997089*I/604462909807314587353088, -148309181940158040917731426845476175667/604462909807314587353088 - 263987151804109387844966835369350904919*I/9671406556917033397649408, 50259518594816377378747711930008883165/1208925819614629174706176 - 95713974916869240305450001443767979653*I/2417851639229258349412352, 153466447023875527996457943521467271119/2417851639229258349412352 + 517285524891117105834922278517084871349*I/2417851639229258349412352, -29184653615412989036678939366291205575/604462909807314587353088 - 27551322282526322041080173287022121083*I/1208925819614629174706176, 196404220110085511863671393922447671649/1208925819614629174706176 - 1204712019400186021982272049902206202145*I/9671406556917033397649408], [ -2632581805949645784625606590600098779/151115727451828646838272 - 589957435912868015140272627522612771*I/37778931862957161709568, 26727850893953715274702844733506310247/302231454903657293676544 - 10825791956782128799168209600694020481*I/302231454903657293676544, -1036348763702366164044671908440791295/151115727451828646838272 + 3188624571414467767868303105288107375*I/151115727451828646838272, -36814959939970644875593411585393242449/604462909807314587353088 - 18457555789119782404850043842902832647*I/302231454903657293676544, 12454491297984637815063964572803058647/604462909807314587353088 - 340489532842249733975074349495329171*I/302231454903657293676544, -19547211751145597258386735573258916681/604462909807314587353088 + 87299583775782199663414539883938008933*I/1208925819614629174706176], [ -40281994229560039213253423262678393183/604462909807314587353088 - 2939986850065527327299273003299736641*I/604462909807314587353088, 331940684638052085845743020267462794181/2417851639229258349412352 - 284574901963624403933361315517248458969*I/1208925819614629174706176, 6453843623051745485064693628073010961/302231454903657293676544 + 36062454107479732681350914931391590957*I/604462909807314587353088, -147665869053634695632880753646441962067/604462909807314587353088 - 305987938660447291246597544085345123927*I/9671406556917033397649408, 107821369195275772166593879711259469423/2417851639229258349412352 - 11645185518211204108659001435013326687*I/302231454903657293676544, 64121228424717666402009446088588091619/1208925819614629174706176 + 265557133337095047883844369272389762133*I/1208925819614629174706176]]''')) def test_issue_17247_expression_blowup_5(): M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I) with dotprodsimp(True): assert M.charpoly('x') == PurePoly(x**6 + (-6 - 6*I)*x**5 + 36*I*x**4, x, domain='EX') def test_issue_17247_expression_blowup_6(): M = Matrix(8, 8, [x+i for i in range (64)]) with dotprodsimp(True): assert M.det('bareiss') == 0 def test_issue_17247_expression_blowup_7(): M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I) with dotprodsimp(True): assert M.det('berkowitz') == 0 def test_issue_17247_expression_blowup_8(): M = Matrix(8, 8, [x+i for i in range (64)]) with dotprodsimp(True): assert M.det('lu') == 0 def test_issue_17247_expression_blowup_9(): M = Matrix(8, 8, [x+i for i in range (64)]) with dotprodsimp(True): assert M.rref() == (Matrix([ [1, 0, -1, -2, -3, -4, -5, -6], [0, 1, 2, 3, 4, 5, 6, 7], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]), (0, 1)) def test_issue_17247_expression_blowup_10(): M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I) with dotprodsimp(True): assert M.cofactor(0, 0) == 0 def test_issue_17247_expression_blowup_11(): M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I) with dotprodsimp(True): assert M.cofactor_matrix() == Matrix(6, 6, [0]*36) def test_issue_17247_expression_blowup_12(): M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I) with dotprodsimp(True): assert M.eigenvals() == {6: 1, 6*I: 1, 0: 4} def test_issue_17247_expression_blowup_13(): M = Matrix([ [ 0, 1 - x, x + 1, 1 - x], [1 - x, x + 1, 0, x + 1], [ 0, 1 - x, x + 1, 1 - x], [ 0, 0, 1 - x, 0]]) ev = M.eigenvects() assert ev[0] == (0, 2, [Matrix([0, -1, 0, 1])]) assert ev[1][0] == x - sqrt(2)*(x - 1) + 1 assert ev[1][1] == 1 assert ev[1][2][0].expand(deep=False, numer=True) == Matrix([ [(-x + sqrt(2)*(x - 1) - 1)/(x - 1)], [-4*x/(x**2 - 2*x + 1) + (x + 1)*(x - sqrt(2)*(x - 1) + 1)/(x**2 - 2*x + 1)], [(-x + sqrt(2)*(x - 1) - 1)/(x - 1)], [1] ]) assert ev[2][0] == x + sqrt(2)*(x - 1) + 1 assert ev[2][1] == 1 assert ev[2][2][0].expand(deep=False, numer=True) == Matrix([ [(-x - sqrt(2)*(x - 1) - 1)/(x - 1)], [-4*x/(x**2 - 2*x + 1) + (x + 1)*(x + sqrt(2)*(x - 1) + 1)/(x**2 - 2*x + 1)], [(-x - sqrt(2)*(x - 1) - 1)/(x - 1)], [1] ]) def test_issue_17247_expression_blowup_14(): M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4) with dotprodsimp(True): assert M.echelon_form() == Matrix([ [x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x], [ 0, 4*x, 0, 4*x, 0, 4*x, 0, 4*x], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0]]) def test_issue_17247_expression_blowup_15(): M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4) with dotprodsimp(True): assert M.rowspace() == [Matrix([[x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x]]), Matrix([[0, 4*x, 0, 4*x, 0, 4*x, 0, 4*x]])] def test_issue_17247_expression_blowup_16(): M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4) with dotprodsimp(True): assert M.columnspace() == [Matrix([[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x]]), Matrix([[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1]])] def test_issue_17247_expression_blowup_17(): M = Matrix(8, 8, [x+i for i in range (64)]) with dotprodsimp(True): assert M.nullspace() == [ Matrix([[1],[-2],[1],[0],[0],[0],[0],[0]]), Matrix([[2],[-3],[0],[1],[0],[0],[0],[0]]), Matrix([[3],[-4],[0],[0],[1],[0],[0],[0]]), Matrix([[4],[-5],[0],[0],[0],[1],[0],[0]]), Matrix([[5],[-6],[0],[0],[0],[0],[1],[0]]), Matrix([[6],[-7],[0],[0],[0],[0],[0],[1]])] def test_issue_17247_expression_blowup_18(): M = Matrix(6, 6, ([1+x, 1-x]*3 + [1-x, 1+x]*3)*3) with dotprodsimp(True): assert not M.is_nilpotent() def test_issue_17247_expression_blowup_19(): M = Matrix(S('''[ [ -3/4, 0, 1/4 + I/2, 0], [ 0, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 1/2 - I, 0, 0, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert not M.is_diagonalizable() def test_issue_17247_expression_blowup_20(): M = Matrix([ [x + 1, 1 - x, 0, 0], [1 - x, x + 1, 0, x + 1], [ 0, 1 - x, x + 1, 0], [ 0, 0, 0, x + 1]]) with dotprodsimp(True): assert M.diagonalize() == (Matrix([ [1, 1, 0, (x + 1)/(x - 1)], [1, -1, 0, 0], [1, 1, 1, 0], [0, 0, 0, 1]]), Matrix([ [2, 0, 0, 0], [0, 2*x, 0, 0], [0, 0, x + 1, 0], [0, 0, 0, x + 1]])) def test_issue_17247_expression_blowup_21(): M = Matrix(S('''[ [ -3/4, 45/32 - 37*I/16, 0, 0], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.inv(method='GE') == Matrix(S('''[ [-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785], [4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785], [-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905], [0, 0, 0, -11328/952745 + 87616*I/952745]]''')) def test_issue_17247_expression_blowup_22(): M = Matrix(S('''[ [ -3/4, 45/32 - 37*I/16, 0, 0], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.inv(method='LU') == Matrix(S('''[ [-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785], [4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785], [-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905], [0, 0, 0, -11328/952745 + 87616*I/952745]]''')) def test_issue_17247_expression_blowup_23(): M = Matrix(S('''[ [ -3/4, 45/32 - 37*I/16, 0, 0], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.inv(method='ADJ').expand() == Matrix(S('''[ [-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785], [4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785], [-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905], [0, 0, 0, -11328/952745 + 87616*I/952745]]''')) def test_issue_17247_expression_blowup_24(): M = SparseMatrix(S('''[ [ -3/4, 45/32 - 37*I/16, 0, 0], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.inv(method='CH') == Matrix(S('''[ [-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785], [4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785], [-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905], [0, 0, 0, -11328/952745 + 87616*I/952745]]''')) def test_issue_17247_expression_blowup_25(): M = SparseMatrix(S('''[ [ -3/4, 45/32 - 37*I/16, 0, 0], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.inv(method='LDL') == Matrix(S('''[ [-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785], [4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785], [-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905], [0, 0, 0, -11328/952745 + 87616*I/952745]]''')) def test_issue_17247_expression_blowup_26(): M = Matrix(S('''[ [ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024], [ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64], [ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512], [ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64], [ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128], [ -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16], [ 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.rank() == 4 def test_issue_17247_expression_blowup_27(): M = Matrix([ [ 0, 1 - x, x + 1, 1 - x], [1 - x, x + 1, 0, x + 1], [ 0, 1 - x, x + 1, 1 - x], [ 0, 0, 1 - x, 0]]) with dotprodsimp(True): P, J = M.jordan_form() assert P.expand() == Matrix(S('''[ [ 0, 4*x/(x**2 - 2*x + 1), -(-17*x**4 + 12*sqrt(2)*x**4 - 4*sqrt(2)*x**3 + 6*x**3 - 6*x - 4*sqrt(2)*x + 12*sqrt(2) + 17)/(-7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 + 8*x**3 - 2*x**2 + 8*x + 6*sqrt(2)*x - 5*sqrt(2) - 7), -(12*sqrt(2)*x**4 + 17*x**4 - 6*x**3 - 4*sqrt(2)*x**3 - 4*sqrt(2)*x + 6*x - 17 + 12*sqrt(2))/(7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 - 8*x**3 + 2*x**2 - 8*x + 6*sqrt(2)*x - 5*sqrt(2) + 7)], [x - 1, x/(x - 1) + 1/(x - 1), (-7*x**3 + 5*sqrt(2)*x**3 - x**2 + sqrt(2)*x**2 - sqrt(2)*x - x - 5*sqrt(2) - 7)/(-3*x**3 + 2*sqrt(2)*x**3 - 2*sqrt(2)*x**2 + 3*x**2 + 2*sqrt(2)*x + 3*x - 3 - 2*sqrt(2)), (7*x**3 + 5*sqrt(2)*x**3 + x**2 + sqrt(2)*x**2 - sqrt(2)*x + x - 5*sqrt(2) + 7)/(2*sqrt(2)*x**3 + 3*x**3 - 3*x**2 - 2*sqrt(2)*x**2 - 3*x + 2*sqrt(2)*x - 2*sqrt(2) + 3)], [ 0, 1, -(-3*x**2 + 2*sqrt(2)*x**2 + 2*x - 3 - 2*sqrt(2))/(-x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x + 1 + sqrt(2)), -(2*sqrt(2)*x**2 + 3*x**2 - 2*x - 2*sqrt(2) + 3)/(x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x - 1 + sqrt(2))], [1 - x, 0, 1, 1]]''')).expand() assert J == Matrix(S('''[ [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, x - sqrt(2)*(x - 1) + 1, 0], [0, 0, 0, x + sqrt(2)*(x - 1) + 1]]''')) def test_issue_17247_expression_blowup_28(): M = Matrix(S('''[ [ -3/4, 45/32 - 37*I/16, 0, 0], [-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128], [ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0], [ 0, 0, 0, -177/128 - 1369*I/128]]''')) with dotprodsimp(True): assert M.singular_values() == S('''[ sqrt(14609315/131072 + sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) + 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2 + sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2), sqrt(14609315/131072 - sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) + 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2 + sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2), sqrt(14609315/131072 - sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2 + sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) - 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2), sqrt(14609315/131072 - sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2 - sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) - 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2)]''') def test_issue_16823(): # This still needs to be fixed if not using dotprodsimp. M = Matrix(S('''[ [1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I,3/64+13/64*I,-23/32-59/256*I,15/128-3/32*I,19/256+551/1024*I], [21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I,119/128+143/128*I,-10879/2048+4343/4096*I,129/256-549/512*I,42533/16384+29103/8192*I], [-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I,3/64+13/64*I,-23/32-59/256*I], [1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I,119/128+143/128*I,-10879/2048+4343/4096*I], [-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I], [1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I], [-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I], [-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I], [0,-6,-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I], [1,-9/4+3*I,-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I], [0,-4*I,0,-6,-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I], [0,1/4+1/2*I,1,-9/4+3*I,-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I]]''')) with dotprodsimp(True): assert M.rank() == 8 def test_issue_18531(): # solve_linear_system still needs fixing but the rref works. M = Matrix([ [1, 1, 1, 1, 1, 0, 1, 0, 0], [1 + sqrt(2), -1 + sqrt(2), 1 - sqrt(2), -sqrt(2) - 1, 1, 1, -1, 1, 1], [-5 + 2*sqrt(2), -5 - 2*sqrt(2), -5 - 2*sqrt(2), -5 + 2*sqrt(2), -7, 2, -7, -2, 0], [-3*sqrt(2) - 1, 1 - 3*sqrt(2), -1 + 3*sqrt(2), 1 + 3*sqrt(2), -7, -5, 7, -5, 3], [7 - 4*sqrt(2), 4*sqrt(2) + 7, 4*sqrt(2) + 7, 7 - 4*sqrt(2), 7, -12, 7, 12, 0], [-1 + 3*sqrt(2), 1 + 3*sqrt(2), -3*sqrt(2) - 1, 1 - 3*sqrt(2), 7, -5, -7, -5, 3], [-3 + 2*sqrt(2), -3 - 2*sqrt(2), -3 - 2*sqrt(2), -3 + 2*sqrt(2), -1, 2, -1, -2, 0], [1 - sqrt(2), -sqrt(2) - 1, 1 + sqrt(2), -1 + sqrt(2), -1, 1, 1, 1, 1] ]) with dotprodsimp(True): assert M.rref() == (Matrix([ [1, 0, 0, 0, 0, 0, 0, 0, 1/2], [0, 1, 0, 0, 0, 0, 0, 0, -1/2], [0, 0, 1, 0, 0, 0, 0, 0, 1/2], [0, 0, 0, 1, 0, 0, 0, 0, -1/2], [0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, -1/2], [0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, -1/2]]), (0, 1, 2, 3, 4, 5, 6, 7)) def test_creation(): raises(ValueError, lambda: Matrix(5, 5, range(20))) raises(ValueError, lambda: Matrix(5, -1, [])) raises(IndexError, lambda: Matrix((1, 2))[2]) with raises(IndexError): Matrix((1, 2))[1:2] = 5 with raises(IndexError): Matrix((1, 2))[3] = 5 assert Matrix() == Matrix([]) == Matrix([[]]) == Matrix(0, 0, []) # anything can go into a matrix (laplace_transform uses tuples) assert Matrix([[[], ()]]).tolist() == [[[], ()]] assert Matrix([[[], ()]]).T.tolist() == [[[]], [()]] a = Matrix([[x, 0], [0, 0]]) m = a assert m.cols == m.rows assert m.cols == 2 assert m[:] == [x, 0, 0, 0] b = Matrix(2, 2, [x, 0, 0, 0]) m = b assert m.cols == m.rows assert m.cols == 2 assert m[:] == [x, 0, 0, 0] assert a == b assert Matrix(b) == b c23 = Matrix(2, 3, range(1, 7)) c13 = Matrix(1, 3, range(7, 10)) c = Matrix([c23, c13]) assert c.cols == 3 assert c.rows == 3 assert c[:] == [1, 2, 3, 4, 5, 6, 7, 8, 9] assert Matrix(eye(2)) == eye(2) assert ImmutableMatrix(ImmutableMatrix(eye(2))) == ImmutableMatrix(eye(2)) assert ImmutableMatrix(c) == c.as_immutable() assert Matrix(ImmutableMatrix(c)) == ImmutableMatrix(c).as_mutable() assert c is not Matrix(c) dat = [[ones(3,2), ones(3,3)*2], [ones(2,3)*3, ones(2,2)*4]] M = Matrix(dat) assert M == Matrix([ [1, 1, 2, 2, 2], [1, 1, 2, 2, 2], [1, 1, 2, 2, 2], [3, 3, 3, 4, 4], [3, 3, 3, 4, 4]]) assert M.tolist() != dat # keep block form if evaluate=False assert Matrix(dat, evaluate=False).tolist() == dat A = MatrixSymbol("A", 2, 2) dat = [ones(2), A] assert Matrix(dat) == Matrix([ [ 1, 1], [ 1, 1], [A[0, 0], A[0, 1]], [A[1, 0], A[1, 1]]]) assert Matrix(dat, evaluate=False).tolist() == [[i] for i in dat] # 0-dim tolerance assert Matrix([ones(2), ones(0)]) == Matrix([ones(2)]) raises(ValueError, lambda: Matrix([ones(2), ones(0, 3)])) raises(ValueError, lambda: Matrix([ones(2), ones(3, 0)])) def test_irregular_block(): assert Matrix.irregular(3, ones(2,1), ones(3,3)*2, ones(2,2)*3, ones(1,1)*4, ones(2,2)*5, ones(1,2)*6, ones(1,2)*7) == Matrix([ [1, 2, 2, 2, 3, 3], [1, 2, 2, 2, 3, 3], [4, 2, 2, 2, 5, 5], [6, 6, 7, 7, 5, 5]]) def test_tolist(): lst = [[S.One, S.Half, x*y, S.Zero], [x, y, z, x**2], [y, -S.One, z*x, 3]] m = Matrix(lst) assert m.tolist() == lst def test_as_mutable(): assert zeros(0, 3).as_mutable() == zeros(0, 3) assert zeros(0, 3).as_immutable() == ImmutableMatrix(zeros(0, 3)) assert zeros(3, 0).as_immutable() == ImmutableMatrix(zeros(3, 0)) def test_slicing(): m0 = eye(4) assert m0[:3, :3] == eye(3) assert m0[2:4, 0:2] == zeros(2) m1 = Matrix(3, 3, lambda i, j: i + j) assert m1[0, :] == Matrix(1, 3, (0, 1, 2)) assert m1[1:3, 1] == Matrix(2, 1, (2, 3)) m2 = Matrix([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]) assert m2[:, -1] == Matrix(4, 1, [3, 7, 11, 15]) assert m2[-2:, :] == Matrix([[8, 9, 10, 11], [12, 13, 14, 15]]) def test_submatrix_assignment(): m = zeros(4) m[2:4, 2:4] = eye(2) assert m == Matrix(((0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1))) m[:2, :2] = eye(2) assert m == eye(4) m[:, 0] = Matrix(4, 1, (1, 2, 3, 4)) assert m == Matrix(((1, 0, 0, 0), (2, 1, 0, 0), (3, 0, 1, 0), (4, 0, 0, 1))) m[:, :] = zeros(4) assert m == zeros(4) m[:, :] = [(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)] assert m == Matrix(((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16))) m[:2, 0] = [0, 0] assert m == Matrix(((0, 2, 3, 4), (0, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16))) def test_extract(): m = Matrix(4, 3, lambda i, j: i*3 + j) assert m.extract([0, 1, 3], [0, 1]) == Matrix(3, 2, [0, 1, 3, 4, 9, 10]) assert m.extract([0, 3], [0, 0, 2]) == Matrix(2, 3, [0, 0, 2, 9, 9, 11]) assert m.extract(range(4), range(3)) == m raises(IndexError, lambda: m.extract([4], [0])) raises(IndexError, lambda: m.extract([0], [3])) def test_reshape(): m0 = eye(3) assert m0.reshape(1, 9) == Matrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1)) m1 = Matrix(3, 4, lambda i, j: i + j) assert m1.reshape( 4, 3) == Matrix(((0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5))) assert m1.reshape(2, 6) == Matrix(((0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5))) def test_applyfunc(): m0 = eye(3) assert m0.applyfunc(lambda x: 2*x) == eye(3)*2 assert m0.applyfunc(lambda x: 0) == zeros(3) def test_expand(): m0 = Matrix([[x*(x + y), 2], [((x + y)*y)*x, x*(y + x*(x + y))]]) # Test if expand() returns a matrix m1 = m0.expand() assert m1 == Matrix( [[x*y + x**2, 2], [x*y**2 + y*x**2, x*y + y*x**2 + x**3]]) a = Symbol('a', real=True) assert Matrix([exp(I*a)]).expand(complex=True) == \ Matrix([cos(a) + I*sin(a)]) assert Matrix([[0, 1, 2], [0, 0, -1], [0, 0, 0]]).exp() == Matrix([ [1, 1, Rational(3, 2)], [0, 1, -1], [0, 0, 1]] ) def test_refine(): m0 = Matrix([[Abs(x)**2, sqrt(x**2)], [sqrt(x**2)*Abs(y)**2, sqrt(y**2)*Abs(x)**2]]) m1 = m0.refine(Q.real(x) & Q.real(y)) assert m1 == Matrix([[x**2, Abs(x)], [y**2*Abs(x), x**2*Abs(y)]]) m1 = m0.refine(Q.positive(x) & Q.positive(y)) assert m1 == Matrix([[x**2, x], [x*y**2, x**2*y]]) m1 = m0.refine(Q.negative(x) & Q.negative(y)) assert m1 == Matrix([[x**2, -x], [-x*y**2, -x**2*y]]) def test_random(): M = randMatrix(3, 3) M = randMatrix(3, 3, seed=3) assert M == randMatrix(3, 3, seed=3) M = randMatrix(3, 4, 0, 150) M = randMatrix(3, seed=4, symmetric=True) assert M == randMatrix(3, seed=4, symmetric=True) S = M.copy() S.simplify() assert S == M # doesn't fail when elements are Numbers, not int rng = random.Random(4) assert M == randMatrix(3, symmetric=True, prng=rng) # Ensure symmetry for size in (10, 11): # Test odd and even for percent in (100, 70, 30): M = randMatrix(size, symmetric=True, percent=percent, prng=rng) assert M == M.T M = randMatrix(10, min=1, percent=70) zero_count = 0 for i in range(M.shape[0]): for j in range(M.shape[1]): if M[i, j] == 0: zero_count += 1 assert zero_count == 30 def test_inverse(): A = eye(4) assert A.inv() == eye(4) assert A.inv(method="LU") == eye(4) assert A.inv(method="ADJ") == eye(4) assert A.inv(method="CH") == eye(4) assert A.inv(method="LDL") == eye(4) assert A.inv(method="QR") == eye(4) A = Matrix([[2, 3, 5], [3, 6, 2], [8, 3, 6]]) Ainv = A.inv() assert A*Ainv == eye(3) assert A.inv(method="LU") == Ainv assert A.inv(method="ADJ") == Ainv assert A.inv(method="CH") == Ainv assert A.inv(method="LDL") == Ainv assert A.inv(method="QR") == Ainv AA = Matrix([[0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0], [1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0], [1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], [1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0], [1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1], [0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0], [1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1], [0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1], [1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0], [1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0], [0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1], [1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0], [0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0], [1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1], [0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1], [1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1], [0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1], [0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0]]) assert AA.inv(method="BLOCK") * AA == eye(AA.shape[0]) # test that immutability is not a problem cls = ImmutableMatrix m = cls([[48, 49, 31], [ 9, 71, 94], [59, 28, 65]]) assert all(type(m.inv(s)) is cls for s in 'GE ADJ LU CH LDL QR'.split()) cls = ImmutableSparseMatrix m = cls([[48, 49, 31], [ 9, 71, 94], [59, 28, 65]]) assert all(type(m.inv(s)) is cls for s in 'GE ADJ LU CH LDL QR'.split()) def test_matrix_inverse_mod(): A = Matrix(2, 1, [1, 0]) raises(NonSquareMatrixError, lambda: A.inv_mod(2)) A = Matrix(2, 2, [1, 0, 0, 0]) raises(ValueError, lambda: A.inv_mod(2)) A = Matrix(2, 2, [1, 2, 3, 4]) Ai = Matrix(2, 2, [1, 1, 0, 1]) assert A.inv_mod(3) == Ai A = Matrix(2, 2, [1, 0, 0, 1]) assert A.inv_mod(2) == A A = Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9]) raises(ValueError, lambda: A.inv_mod(5)) A = Matrix(3, 3, [5, 1, 3, 2, 6, 0, 2, 1, 1]) Ai = Matrix(3, 3, [6, 8, 0, 1, 5, 6, 5, 6, 4]) assert A.inv_mod(9) == Ai A = Matrix(3, 3, [1, 6, -3, 4, 1, -5, 3, -5, 5]) Ai = Matrix(3, 3, [4, 3, 3, 1, 2, 5, 1, 5, 1]) assert A.inv_mod(6) == Ai A = Matrix(3, 3, [1, 6, 1, 4, 1, 5, 3, 2, 5]) Ai = Matrix(3, 3, [6, 0, 3, 6, 6, 4, 1, 6, 1]) assert A.inv_mod(7) == Ai def test_jacobian_hessian(): L = Matrix(1, 2, [x**2*y, 2*y**2 + x*y]) syms = [x, y] assert L.jacobian(syms) == Matrix([[2*x*y, x**2], [y, 4*y + x]]) L = Matrix(1, 2, [x, x**2*y**3]) assert L.jacobian(syms) == Matrix([[1, 0], [2*x*y**3, x**2*3*y**2]]) f = x**2*y syms = [x, y] assert hessian(f, syms) == Matrix([[2*y, 2*x], [2*x, 0]]) f = x**2*y**3 assert hessian(f, syms) == \ Matrix([[2*y**3, 6*x*y**2], [6*x*y**2, 6*x**2*y]]) f = z + x*y**2 g = x**2 + 2*y**3 ans = Matrix([[0, 2*y], [2*y, 2*x]]) assert ans == hessian(f, Matrix([x, y])) assert ans == hessian(f, Matrix([x, y]).T) assert hessian(f, (y, x), [g]) == Matrix([ [ 0, 6*y**2, 2*x], [6*y**2, 2*x, 2*y], [ 2*x, 2*y, 0]]) def test_wronskian(): assert wronskian([cos(x), sin(x)], x) == cos(x)**2 + sin(x)**2 assert wronskian([exp(x), exp(2*x)], x) == exp(3*x) assert wronskian([exp(x), x], x) == exp(x) - x*exp(x) assert wronskian([1, x, x**2], x) == 2 w1 = -6*exp(x)*sin(x)*x + 6*cos(x)*exp(x)*x**2 - 6*exp(x)*cos(x)*x - \ exp(x)*cos(x)*x**3 + exp(x)*sin(x)*x**3 assert wronskian([exp(x), cos(x), x**3], x).expand() == w1 assert wronskian([exp(x), cos(x), x**3], x, method='berkowitz').expand() \ == w1 w2 = -x**3*cos(x)**2 - x**3*sin(x)**2 - 6*x*cos(x)**2 - 6*x*sin(x)**2 assert wronskian([sin(x), cos(x), x**3], x).expand() == w2 assert wronskian([sin(x), cos(x), x**3], x, method='berkowitz').expand() \ == w2 assert wronskian([], x) == 1 def test_subs(): assert Matrix([[1, x], [x, 4]]).subs(x, 5) == Matrix([[1, 5], [5, 4]]) assert Matrix([[x, 2], [x + y, 4]]).subs([[x, -1], [y, -2]]) == \ Matrix([[-1, 2], [-3, 4]]) assert Matrix([[x, 2], [x + y, 4]]).subs([(x, -1), (y, -2)]) == \ Matrix([[-1, 2], [-3, 4]]) assert Matrix([[x, 2], [x + y, 4]]).subs({x: -1, y: -2}) == \ Matrix([[-1, 2], [-3, 4]]) assert Matrix([x*y]).subs({x: y - 1, y: x - 1}, simultaneous=True) == \ Matrix([(x - 1)*(y - 1)]) for cls in classes: assert Matrix([[2, 0], [0, 2]]) == cls.eye(2).subs(1, 2) def test_xreplace(): assert Matrix([[1, x], [x, 4]]).xreplace({x: 5}) == \ Matrix([[1, 5], [5, 4]]) assert Matrix([[x, 2], [x + y, 4]]).xreplace({x: -1, y: -2}) == \ Matrix([[-1, 2], [-3, 4]]) for cls in classes: assert Matrix([[2, 0], [0, 2]]) == cls.eye(2).xreplace({1: 2}) def test_simplify(): n = Symbol('n') f = Function('f') M = Matrix([[ 1/x + 1/y, (x + x*y) / x ], [ (f(x) + y*f(x))/f(x), 2 * (1/n - cos(n * pi)/n) / pi ]]) M.simplify() assert M == Matrix([[ (x + y)/(x * y), 1 + y ], [ 1 + y, 2*((1 - 1*cos(pi*n))/(pi*n)) ]]) eq = (1 + x)**2 M = Matrix([[eq]]) M.simplify() assert M == Matrix([[eq]]) M.simplify(ratio=oo) == M assert M == Matrix([[eq.simplify(ratio=oo)]]) def test_transpose(): M = Matrix([[1, 2, 3, 4, 5, 6, 7, 8, 9, 0], [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]]) assert M.T == Matrix( [ [1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 7], [8, 8], [9, 9], [0, 0] ]) assert M.T.T == M assert M.T == M.transpose() def test_conjugate(): M = Matrix([[0, I, 5], [1, 2, 0]]) assert M.T == Matrix([[0, 1], [I, 2], [5, 0]]) assert M.C == Matrix([[0, -I, 5], [1, 2, 0]]) assert M.C == M.conjugate() assert M.H == M.T.C assert M.H == Matrix([[ 0, 1], [-I, 2], [ 5, 0]]) def test_conj_dirac(): raises(AttributeError, lambda: eye(3).D) M = Matrix([[1, I, I, I], [0, 1, I, I], [0, 0, 1, I], [0, 0, 0, 1]]) assert M.D == Matrix([[ 1, 0, 0, 0], [-I, 1, 0, 0], [-I, -I, -1, 0], [-I, -I, I, -1]]) def test_trace(): M = Matrix([[1, 0, 0], [0, 5, 0], [0, 0, 8]]) assert M.trace() == 14 def test_shape(): M = Matrix([[x, 0, 0], [0, y, 0]]) assert M.shape == (2, 3) def test_col_row_op(): M = Matrix([[x, 0, 0], [0, y, 0]]) M.row_op(1, lambda r, j: r + j + 1) assert M == Matrix([[x, 0, 0], [1, y + 2, 3]]) M.col_op(0, lambda c, j: c + y**j) assert M == Matrix([[x + 1, 0, 0], [1 + y, y + 2, 3]]) # neither row nor slice give copies that allow the original matrix to # be changed assert M.row(0) == Matrix([[x + 1, 0, 0]]) r1 = M.row(0) r1[0] = 42 assert M[0, 0] == x + 1 r1 = M[0, :-1] # also testing negative slice r1[0] = 42 assert M[0, 0] == x + 1 c1 = M.col(0) assert c1 == Matrix([x + 1, 1 + y]) c1[0] = 0 assert M[0, 0] == x + 1 c1 = M[:, 0] c1[0] = 42 assert M[0, 0] == x + 1 def test_zip_row_op(): for cls in classes[:2]: # XXX: immutable matrices don't support row ops M = cls.eye(3) M.zip_row_op(1, 0, lambda v, u: v + 2*u) assert M == cls([[1, 0, 0], [2, 1, 0], [0, 0, 1]]) M = cls.eye(3)*2 M[0, 1] = -1 M.zip_row_op(1, 0, lambda v, u: v + 2*u); M assert M == cls([[2, -1, 0], [4, 0, 0], [0, 0, 2]]) def test_issue_3950(): m = Matrix([1, 2, 3]) a = Matrix([1, 2, 3]) b = Matrix([2, 2, 3]) assert not (m in []) assert not (m in [1]) assert m != 1 assert m == a assert m != b def test_issue_3981(): class Index1: def __index__(self): return 1 class Index2: def __index__(self): return 2 index1 = Index1() index2 = Index2() m = Matrix([1, 2, 3]) assert m[index2] == 3 m[index2] = 5 assert m[2] == 5 m = Matrix([[1, 2, 3], [4, 5, 6]]) assert m[index1, index2] == 6 assert m[1, index2] == 6 assert m[index1, 2] == 6 m[index1, index2] = 4 assert m[1, 2] == 4 m[1, index2] = 6 assert m[1, 2] == 6 m[index1, 2] = 8 assert m[1, 2] == 8 def test_evalf(): a = Matrix([sqrt(5), 6]) assert all(a.evalf()[i] == a[i].evalf() for i in range(2)) assert all(a.evalf(2)[i] == a[i].evalf(2) for i in range(2)) assert all(a.n(2)[i] == a[i].n(2) for i in range(2)) def test_is_symbolic(): a = Matrix([[x, x], [x, x]]) assert a.is_symbolic() is True a = Matrix([[1, 2, 3, 4], [5, 6, 7, 8]]) assert a.is_symbolic() is False a = Matrix([[1, 2, 3, 4], [5, 6, x, 8]]) assert a.is_symbolic() is True a = Matrix([[1, x, 3]]) assert a.is_symbolic() is True a = Matrix([[1, 2, 3]]) assert a.is_symbolic() is False a = Matrix([[1], [x], [3]]) assert a.is_symbolic() is True a = Matrix([[1], [2], [3]]) assert a.is_symbolic() is False def test_is_upper(): a = Matrix([[1, 2, 3]]) assert a.is_upper is True a = Matrix([[1], [2], [3]]) assert a.is_upper is False a = zeros(4, 2) assert a.is_upper is True def test_is_lower(): a = Matrix([[1, 2, 3]]) assert a.is_lower is False a = Matrix([[1], [2], [3]]) assert a.is_lower is True def test_is_nilpotent(): a = Matrix(4, 4, [0, 2, 1, 6, 0, 0, 1, 2, 0, 0, 0, 3, 0, 0, 0, 0]) assert a.is_nilpotent() a = Matrix([[1, 0], [0, 1]]) assert not a.is_nilpotent() a = Matrix([]) assert a.is_nilpotent() def test_zeros_ones_fill(): n, m = 3, 5 a = zeros(n, m) a.fill( 5 ) b = 5 * ones(n, m) assert a == b assert a.rows == b.rows == 3 assert a.cols == b.cols == 5 assert a.shape == b.shape == (3, 5) assert zeros(2) == zeros(2, 2) assert ones(2) == ones(2, 2) assert zeros(2, 3) == Matrix(2, 3, [0]*6) assert ones(2, 3) == Matrix(2, 3, [1]*6) def test_empty_zeros(): a = zeros(0) assert a == Matrix() a = zeros(0, 2) assert a.rows == 0 assert a.cols == 2 a = zeros(2, 0) assert a.rows == 2 assert a.cols == 0 def test_issue_3749(): a = Matrix([[x**2, x*y], [x*sin(y), x*cos(y)]]) assert a.diff(x) == Matrix([[2*x, y], [sin(y), cos(y)]]) assert Matrix([ [x, -x, x**2], [exp(x), 1/x - exp(-x), x + 1/x]]).limit(x, oo) == \ Matrix([[oo, -oo, oo], [oo, 0, oo]]) assert Matrix([ [(exp(x) - 1)/x, 2*x + y*x, x**x ], [1/x, abs(x), abs(sin(x + 1))]]).limit(x, 0) == \ Matrix([[1, 0, 1], [oo, 0, sin(1)]]) assert a.integrate(x) == Matrix([ [Rational(1, 3)*x**3, y*x**2/2], [x**2*sin(y)/2, x**2*cos(y)/2]]) def test_inv_iszerofunc(): A = eye(4) A.col_swap(0, 1) for method in "GE", "LU": assert A.inv(method=method, iszerofunc=lambda x: x == 0) == \ A.inv(method="ADJ") def test_jacobian_metrics(): rho, phi = symbols("rho,phi") X = Matrix([rho*cos(phi), rho*sin(phi)]) Y = Matrix([rho, phi]) J = X.jacobian(Y) assert J == X.jacobian(Y.T) assert J == (X.T).jacobian(Y) assert J == (X.T).jacobian(Y.T) g = J.T*eye(J.shape[0])*J g = g.applyfunc(trigsimp) assert g == Matrix([[1, 0], [0, rho**2]]) def test_jacobian2(): rho, phi = symbols("rho,phi") X = Matrix([rho*cos(phi), rho*sin(phi), rho**2]) Y = Matrix([rho, phi]) J = Matrix([ [cos(phi), -rho*sin(phi)], [sin(phi), rho*cos(phi)], [ 2*rho, 0], ]) assert X.jacobian(Y) == J def test_issue_4564(): X = Matrix([exp(x + y + z), exp(x + y + z), exp(x + y + z)]) Y = Matrix([x, y, z]) for i in range(1, 3): for j in range(1, 3): X_slice = X[:i, :] Y_slice = Y[:j, :] J = X_slice.jacobian(Y_slice) assert J.rows == i assert J.cols == j for k in range(j): assert J[:, k] == X_slice def test_nonvectorJacobian(): X = Matrix([[exp(x + y + z), exp(x + y + z)], [exp(x + y + z), exp(x + y + z)]]) raises(TypeError, lambda: X.jacobian(Matrix([x, y, z]))) X = X[0, :] Y = Matrix([[x, y], [x, z]]) raises(TypeError, lambda: X.jacobian(Y)) raises(TypeError, lambda: X.jacobian(Matrix([ [x, y], [x, z] ]))) def test_vec(): m = Matrix([[1, 3], [2, 4]]) m_vec = m.vec() assert m_vec.cols == 1 for i in range(4): assert m_vec[i] == i + 1 def test_vech(): m = Matrix([[1, 2], [2, 3]]) m_vech = m.vech() assert m_vech.cols == 1 for i in range(3): assert m_vech[i] == i + 1 m_vech = m.vech(diagonal=False) assert m_vech[0] == 2 m = Matrix([[1, x*(x + y)], [y*x + x**2, 1]]) m_vech = m.vech(diagonal=False) assert m_vech[0] == y*x + x**2 m = Matrix([[1, x*(x + y)], [y*x, 1]]) m_vech = m.vech(diagonal=False, check_symmetry=False) assert m_vech[0] == y*x raises(ShapeError, lambda: Matrix([[1, 3]]).vech()) raises(ValueError, lambda: Matrix([[1, 3], [2, 4]]).vech()) raises(ShapeError, lambda: Matrix([[1, 3]]).vech()) raises(ValueError, lambda: Matrix([[1, 3], [2, 4]]).vech()) def test_diag(): # mostly tested in testcommonmatrix.py assert diag([1, 2, 3]) == Matrix([1, 2, 3]) m = [1, 2, [3]] raises(ValueError, lambda: diag(m)) assert diag(m, strict=False) == Matrix([1, 2, 3]) def test_get_diag_blocks1(): a = Matrix([[1, 2], [2, 3]]) b = Matrix([[3, x], [y, 3]]) c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]]) assert a.get_diag_blocks() == [a] assert b.get_diag_blocks() == [b] assert c.get_diag_blocks() == [c] def test_get_diag_blocks2(): a = Matrix([[1, 2], [2, 3]]) b = Matrix([[3, x], [y, 3]]) c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]]) assert diag(a, b, b).get_diag_blocks() == [a, b, b] assert diag(a, b, c).get_diag_blocks() == [a, b, c] assert diag(a, c, b).get_diag_blocks() == [a, c, b] assert diag(c, c, b).get_diag_blocks() == [c, c, b] def test_inv_block(): a = Matrix([[1, 2], [2, 3]]) b = Matrix([[3, x], [y, 3]]) c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]]) A = diag(a, b, b) assert A.inv(try_block_diag=True) == diag(a.inv(), b.inv(), b.inv()) A = diag(a, b, c) assert A.inv(try_block_diag=True) == diag(a.inv(), b.inv(), c.inv()) A = diag(a, c, b) assert A.inv(try_block_diag=True) == diag(a.inv(), c.inv(), b.inv()) A = diag(a, a, b, a, c, a) assert A.inv(try_block_diag=True) == diag( a.inv(), a.inv(), b.inv(), a.inv(), c.inv(), a.inv()) assert A.inv(try_block_diag=True, method="ADJ") == diag( a.inv(method="ADJ"), a.inv(method="ADJ"), b.inv(method="ADJ"), a.inv(method="ADJ"), c.inv(method="ADJ"), a.inv(method="ADJ")) def test_creation_args(): """ Check that matrix dimensions can be specified using any reasonable type (see issue 4614). """ raises(ValueError, lambda: zeros(3, -1)) raises(TypeError, lambda: zeros(1, 2, 3, 4)) assert zeros(int(3)) == zeros(3) assert zeros(Integer(3)) == zeros(3) raises(ValueError, lambda: zeros(3.)) assert eye(int(3)) == eye(3) assert eye(Integer(3)) == eye(3) raises(ValueError, lambda: eye(3.)) assert ones(int(3), Integer(4)) == ones(3, 4) raises(TypeError, lambda: Matrix(5)) raises(TypeError, lambda: Matrix(1, 2)) raises(ValueError, lambda: Matrix([1, [2]])) def test_diagonal_symmetrical(): m = Matrix(2, 2, [0, 1, 1, 0]) assert not m.is_diagonal() assert m.is_symmetric() assert m.is_symmetric(simplify=False) m = Matrix(2, 2, [1, 0, 0, 1]) assert m.is_diagonal() m = diag(1, 2, 3) assert m.is_diagonal() assert m.is_symmetric() m = Matrix(3, 3, [1, 0, 0, 0, 2, 0, 0, 0, 3]) assert m == diag(1, 2, 3) m = Matrix(2, 3, zeros(2, 3)) assert not m.is_symmetric() assert m.is_diagonal() m = Matrix(((5, 0), (0, 6), (0, 0))) assert m.is_diagonal() m = Matrix(((5, 0, 0), (0, 6, 0))) assert m.is_diagonal() m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3]) assert m.is_symmetric() assert not m.is_symmetric(simplify=False) assert m.expand().is_symmetric(simplify=False) def test_diagonalization(): m = Matrix([[1, 2+I], [2-I, 3]]) assert m.is_diagonalizable() m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10]) assert not m.is_diagonalizable() assert not m.is_symmetric() raises(NonSquareMatrixError, lambda: m.diagonalize()) # diagonalizable m = diag(1, 2, 3) (P, D) = m.diagonalize() assert P == eye(3) assert D == m m = Matrix(2, 2, [0, 1, 1, 0]) assert m.is_symmetric() assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D m = Matrix(2, 2, [1, 0, 0, 3]) assert m.is_symmetric() assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D assert P == eye(2) assert D == m m = Matrix(2, 2, [1, 1, 0, 0]) assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D m = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2]) assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D for i in P: assert i.as_numer_denom()[1] == 1 m = Matrix(2, 2, [1, 0, 0, 0]) assert m.is_diagonal() assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D assert P == Matrix([[0, 1], [1, 0]]) # diagonalizable, complex only m = Matrix(2, 2, [0, 1, -1, 0]) assert not m.is_diagonalizable(True) raises(MatrixError, lambda: m.diagonalize(True)) assert m.is_diagonalizable() (P, D) = m.diagonalize() assert P.inv() * m * P == D # not diagonalizable m = Matrix(2, 2, [0, 1, 0, 0]) assert not m.is_diagonalizable() raises(MatrixError, lambda: m.diagonalize()) m = Matrix(3, 3, [-3, 1, -3, 20, 3, 10, 2, -2, 4]) assert not m.is_diagonalizable() raises(MatrixError, lambda: m.diagonalize()) # symbolic a, b, c, d = symbols('a b c d') m = Matrix(2, 2, [a, c, c, b]) assert m.is_symmetric() assert m.is_diagonalizable() def test_issue_15887(): # Mutable matrix should not use cache a = MutableDenseMatrix([[0, 1], [1, 0]]) assert a.is_diagonalizable() is True a[1, 0] = 0 assert a.is_diagonalizable() is False a = MutableDenseMatrix([[0, 1], [1, 0]]) a.diagonalize() a[1, 0] = 0 raises(MatrixError, lambda: a.diagonalize()) # Test deprecated cache and kwargs with warns_deprecated_sympy(): a.is_diagonalizable(clear_cache=True) with warns_deprecated_sympy(): a.is_diagonalizable(clear_subproducts=True) def test_jordan_form(): m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10]) raises(NonSquareMatrixError, lambda: m.jordan_form()) # diagonalizable m = Matrix(3, 3, [7, -12, 6, 10, -19, 10, 12, -24, 13]) Jmust = Matrix(3, 3, [-1, 0, 0, 0, 1, 0, 0, 0, 1]) P, J = m.jordan_form() assert Jmust == J assert Jmust == m.diagonalize()[1] # m = Matrix(3, 3, [0, 6, 3, 1, 3, 1, -2, 2, 1]) # m.jordan_form() # very long # m.jordan_form() # # diagonalizable, complex only # Jordan cells # complexity: one of eigenvalues is zero m = Matrix(3, 3, [0, 1, 0, -4, 4, 0, -2, 1, 2]) # The blocks are ordered according to the value of their eigenvalues, # in order to make the matrix compatible with .diagonalize() Jmust = Matrix(3, 3, [2, 1, 0, 0, 2, 0, 0, 0, 2]) P, J = m.jordan_form() assert Jmust == J # complexity: all of eigenvalues are equal m = Matrix(3, 3, [2, 6, -15, 1, 1, -5, 1, 2, -6]) # Jmust = Matrix(3, 3, [-1, 0, 0, 0, -1, 1, 0, 0, -1]) # same here see 1456ff Jmust = Matrix(3, 3, [-1, 1, 0, 0, -1, 0, 0, 0, -1]) P, J = m.jordan_form() assert Jmust == J # complexity: two of eigenvalues are zero m = Matrix(3, 3, [4, -5, 2, 5, -7, 3, 6, -9, 4]) Jmust = Matrix(3, 3, [0, 1, 0, 0, 0, 0, 0, 0, 1]) P, J = m.jordan_form() assert Jmust == J m = Matrix(4, 4, [6, 5, -2, -3, -3, -1, 3, 3, 2, 1, -2, -3, -1, 1, 5, 5]) Jmust = Matrix(4, 4, [2, 1, 0, 0, 0, 2, 0, 0, 0, 0, 2, 1, 0, 0, 0, 2] ) P, J = m.jordan_form() assert Jmust == J m = Matrix(4, 4, [6, 2, -8, -6, -3, 2, 9, 6, 2, -2, -8, -6, -1, 0, 3, 4]) # Jmust = Matrix(4, 4, [2, 0, 0, 0, 0, 2, 1, 0, 0, 0, 2, 0, 0, 0, 0, -2]) # same here see 1456ff Jmust = Matrix(4, 4, [-2, 0, 0, 0, 0, 2, 1, 0, 0, 0, 2, 0, 0, 0, 0, 2]) P, J = m.jordan_form() assert Jmust == J m = Matrix(4, 4, [5, 4, 2, 1, 0, 1, -1, -1, -1, -1, 3, 0, 1, 1, -1, 2]) assert not m.is_diagonalizable() Jmust = Matrix(4, 4, [1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 4, 1, 0, 0, 0, 4]) P, J = m.jordan_form() assert Jmust == J # checking for maximum precision to remain unchanged m = Matrix([[Float('1.0', precision=110), Float('2.0', precision=110)], [Float('3.14159265358979323846264338327', precision=110), Float('4.0', precision=110)]]) P, J = m.jordan_form() for term in J._mat: if isinstance(term, Float): assert term._prec == 110 def test_jordan_form_complex_issue_9274(): A = Matrix([[ 2, 4, 1, 0], [-4, 2, 0, 1], [ 0, 0, 2, 4], [ 0, 0, -4, 2]]) p = 2 - 4*I; q = 2 + 4*I; Jmust1 = Matrix([[p, 1, 0, 0], [0, p, 0, 0], [0, 0, q, 1], [0, 0, 0, q]]) Jmust2 = Matrix([[q, 1, 0, 0], [0, q, 0, 0], [0, 0, p, 1], [0, 0, 0, p]]) P, J = A.jordan_form() assert J == Jmust1 or J == Jmust2 assert simplify(P*J*P.inv()) == A def test_issue_10220(): # two non-orthogonal Jordan blocks with eigenvalue 1 M = Matrix([[1, 0, 0, 1], [0, 1, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1]]) P, J = M.jordan_form() assert P == Matrix([[0, 1, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]]) assert J == Matrix([ [1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) def test_jordan_form_issue_15858(): A = Matrix([ [1, 1, 1, 0], [-2, -1, 0, -1], [0, 0, -1, -1], [0, 0, 2, 1]]) (P, J) = A.jordan_form() assert P.expand() == Matrix([ [ -I, -I/2, I, I/2], [-1 + I, 0, -1 - I, 0], [ 0, -S(1)/2 - I/2, 0, -S(1)/2 + I/2], [ 0, 1, 0, 1]]) assert J == Matrix([ [-I, 1, 0, 0], [0, -I, 0, 0], [0, 0, I, 1], [0, 0, 0, I]]) def test_Matrix_berkowitz_charpoly(): UA, K_i, K_w = symbols('UA K_i K_w') A = Matrix([[-K_i - UA + K_i**2/(K_i + K_w), K_i*K_w/(K_i + K_w)], [ K_i*K_w/(K_i + K_w), -K_w + K_w**2/(K_i + K_w)]]) charpoly = A.charpoly(x) assert charpoly == \ Poly(x**2 + (K_i*UA + K_w*UA + 2*K_i*K_w)/(K_i + K_w)*x + K_i*K_w*UA/(K_i + K_w), x, domain='ZZ(K_i,K_w,UA)') assert type(charpoly) is PurePoly A = Matrix([[1, 3], [2, 0]]) assert A.charpoly() == A.charpoly(x) == PurePoly(x**2 - x - 6) A = Matrix([[1, 2], [x, 0]]) p = A.charpoly(x) assert p.gen != x assert p.as_expr().subs(p.gen, x) == x**2 - 3*x def test_exp_jordan_block(): l = Symbol('lamda') m = Matrix.jordan_block(1, l) assert m._eval_matrix_exp_jblock() == Matrix([[exp(l)]]) m = Matrix.jordan_block(3, l) assert m._eval_matrix_exp_jblock() == \ Matrix([ [exp(l), exp(l), exp(l)/2], [0, exp(l), exp(l)], [0, 0, exp(l)]]) def test_exp(): m = Matrix([[3, 4], [0, -2]]) m_exp = Matrix([[exp(3), -4*exp(-2)/5 + 4*exp(3)/5], [0, exp(-2)]]) assert m.exp() == m_exp assert exp(m) == m_exp m = Matrix([[1, 0], [0, 1]]) assert m.exp() == Matrix([[E, 0], [0, E]]) assert exp(m) == Matrix([[E, 0], [0, E]]) m = Matrix([[1, -1], [1, 1]]) assert m.exp() == Matrix([[E*cos(1), -E*sin(1)], [E*sin(1), E*cos(1)]]) def test_log(): l = Symbol('lamda') m = Matrix.jordan_block(1, l) assert m._eval_matrix_log_jblock() == Matrix([[log(l)]]) m = Matrix.jordan_block(4, l) assert m._eval_matrix_log_jblock() == \ Matrix( [ [log(l), 1/l, -1/(2*l**2), 1/(3*l**3)], [0, log(l), 1/l, -1/(2*l**2)], [0, 0, log(l), 1/l], [0, 0, 0, log(l)] ] ) m = Matrix( [[0, 0, 1], [0, 0, 0], [-1, 0, 0]] ) raises(MatrixError, lambda: m.log()) def test_has(): A = Matrix(((x, y), (2, 3))) assert A.has(x) assert not A.has(z) assert A.has(Symbol) A = A.subs(x, 2) assert not A.has(x) def test_find_reasonable_pivot_naive_finds_guaranteed_nonzero1(): # Test if matrices._find_reasonable_pivot_naive() # finds a guaranteed non-zero pivot when the # some of the candidate pivots are symbolic expressions. # Keyword argument: simpfunc=None indicates that no simplifications # should be performed during the search. x = Symbol('x') column = Matrix(3, 1, [x, cos(x)**2 + sin(x)**2, S.Half]) pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\ _find_reasonable_pivot_naive(column) assert pivot_val == S.Half def test_find_reasonable_pivot_naive_finds_guaranteed_nonzero2(): # Test if matrices._find_reasonable_pivot_naive() # finds a guaranteed non-zero pivot when the # some of the candidate pivots are symbolic expressions. # Keyword argument: simpfunc=_simplify indicates that the search # should attempt to simplify candidate pivots. x = Symbol('x') column = Matrix(3, 1, [x, cos(x)**2+sin(x)**2+x**2, cos(x)**2+sin(x)**2]) pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\ _find_reasonable_pivot_naive(column, simpfunc=_simplify) assert pivot_val == 1 def test_find_reasonable_pivot_naive_simplifies(): # Test if matrices._find_reasonable_pivot_naive() # simplifies candidate pivots, and reports # their offsets correctly. x = Symbol('x') column = Matrix(3, 1, [x, cos(x)**2+sin(x)**2+x, cos(x)**2+sin(x)**2]) pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\ _find_reasonable_pivot_naive(column, simpfunc=_simplify) assert len(simplified) == 2 assert simplified[0][0] == 1 assert simplified[0][1] == 1+x assert simplified[1][0] == 2 assert simplified[1][1] == 1 def test_errors(): raises(ValueError, lambda: Matrix([[1, 2], [1]])) raises(IndexError, lambda: Matrix([[1, 2]])[1.2, 5]) raises(IndexError, lambda: Matrix([[1, 2]])[1, 5.2]) raises(ValueError, lambda: randMatrix(3, c=4, symmetric=True)) raises(ValueError, lambda: Matrix([1, 2]).reshape(4, 6)) raises(ShapeError, lambda: Matrix([[1, 2], [3, 4]]).copyin_matrix([1, 0], Matrix([1, 2]))) raises(TypeError, lambda: Matrix([[1, 2], [3, 4]]).copyin_list([0, 1], set())) raises(NonSquareMatrixError, lambda: Matrix([[1, 2, 3], [2, 3, 0]]).inv()) raises(ShapeError, lambda: Matrix(1, 2, [1, 2]).row_join(Matrix([[1, 2], [3, 4]]))) raises( ShapeError, lambda: Matrix([1, 2]).col_join(Matrix([[1, 2], [3, 4]]))) raises(ShapeError, lambda: Matrix([1]).row_insert(1, Matrix([[1, 2], [3, 4]]))) raises(ShapeError, lambda: Matrix([1]).col_insert(1, Matrix([[1, 2], [3, 4]]))) raises(NonSquareMatrixError, lambda: Matrix([1, 2]).trace()) raises(TypeError, lambda: Matrix([1]).applyfunc(1)) raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).minor(4, 5)) raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).minor_submatrix(4, 5)) raises(TypeError, lambda: Matrix([1, 2, 3]).cross(1)) raises(TypeError, lambda: Matrix([1, 2, 3]).dot(1)) raises(ShapeError, lambda: Matrix([1, 2, 3]).dot(Matrix([1, 2]))) raises(ShapeError, lambda: Matrix([1, 2]).dot([])) raises(TypeError, lambda: Matrix([1, 2]).dot('a')) with warns_deprecated_sympy(): Matrix([[1, 2], [3, 4]]).dot(Matrix([[4, 3], [1, 2]])) raises(ShapeError, lambda: Matrix([1, 2]).dot([1, 2, 3])) raises(NonSquareMatrixError, lambda: Matrix([1, 2, 3]).exp()) raises(ShapeError, lambda: Matrix([[1, 2], [3, 4]]).normalized()) raises(ValueError, lambda: Matrix([1, 2]).inv(method='not a method')) raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_GE()) raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inverse_GE()) raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_ADJ()) raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inverse_ADJ()) raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_LU()) raises(NonSquareMatrixError, lambda: Matrix([1, 2]).is_nilpotent()) raises(NonSquareMatrixError, lambda: Matrix([1, 2]).det()) raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).det(method='Not a real method')) raises(ValueError, lambda: Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]).det(iszerofunc="Not function")) raises(ValueError, lambda: Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]).det(iszerofunc=False)) raises(ValueError, lambda: hessian(Matrix([[1, 2], [3, 4]]), Matrix([[1, 2], [2, 1]]))) raises(ValueError, lambda: hessian(Matrix([[1, 2], [3, 4]]), [])) raises(ValueError, lambda: hessian(Symbol('x')**2, 'a')) raises(IndexError, lambda: eye(3)[5, 2]) raises(IndexError, lambda: eye(3)[2, 5]) M = Matrix(((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16))) raises(ValueError, lambda: M.det('method=LU_decomposition()')) V = Matrix([[10, 10, 10]]) M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) raises(ValueError, lambda: M.row_insert(4.7, V)) M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) raises(ValueError, lambda: M.col_insert(-4.2, V)) def test_len(): assert len(Matrix()) == 0 assert len(Matrix([[1, 2]])) == len(Matrix([[1], [2]])) == 2 assert len(Matrix(0, 2, lambda i, j: 0)) == \ len(Matrix(2, 0, lambda i, j: 0)) == 0 assert len(Matrix([[0, 1, 2], [3, 4, 5]])) == 6 assert Matrix([1]) == Matrix([[1]]) assert not Matrix() assert Matrix() == Matrix([]) def test_integrate(): A = Matrix(((1, 4, x), (y, 2, 4), (10, 5, x**2))) assert A.integrate(x) == \ Matrix(((x, 4*x, x**2/2), (x*y, 2*x, 4*x), (10*x, 5*x, x**3/3))) assert A.integrate(y) == \ Matrix(((y, 4*y, x*y), (y**2/2, 2*y, 4*y), (10*y, 5*y, y*x**2))) def test_limit(): A = Matrix(((1, 4, sin(x)/x), (y, 2, 4), (10, 5, x**2 + 1))) assert A.limit(x, 0) == Matrix(((1, 4, 1), (y, 2, 4), (10, 5, 1))) def test_diff(): A = MutableDenseMatrix(((1, 4, x), (y, 2, 4), (10, 5, x**2 + 1))) assert isinstance(A.diff(x), type(A)) assert A.diff(x) == MutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x))) assert A.diff(y) == MutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0))) assert diff(A, x) == MutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x))) assert diff(A, y) == MutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0))) A_imm = A.as_immutable() assert isinstance(A_imm.diff(x), type(A_imm)) assert A_imm.diff(x) == ImmutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x))) assert A_imm.diff(y) == ImmutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0))) assert diff(A_imm, x) == ImmutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x))) assert diff(A_imm, y) == ImmutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0))) def test_diff_by_matrix(): # Derive matrix by matrix: A = MutableDenseMatrix([[x, y], [z, t]]) assert A.diff(A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]]) assert diff(A, A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]]) A_imm = A.as_immutable() assert A_imm.diff(A_imm) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]]) assert diff(A_imm, A_imm) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]]) # Derive a constant matrix: assert A.diff(a) == MutableDenseMatrix([[0, 0], [0, 0]]) B = ImmutableDenseMatrix([a, b]) assert A.diff(B) == Array.zeros(2, 1, 2, 2) assert A.diff(A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]]) # Test diff with tuples: dB = B.diff([[a, b]]) assert dB.shape == (2, 2, 1) assert dB == Array([[[1], [0]], [[0], [1]]]) f = Function("f") fxyz = f(x, y, z) assert fxyz.diff([[x, y, z]]) == Array([fxyz.diff(x), fxyz.diff(y), fxyz.diff(z)]) assert fxyz.diff(([x, y, z], 2)) == Array([ [fxyz.diff(x, 2), fxyz.diff(x, y), fxyz.diff(x, z)], [fxyz.diff(x, y), fxyz.diff(y, 2), fxyz.diff(y, z)], [fxyz.diff(x, z), fxyz.diff(z, y), fxyz.diff(z, 2)], ]) expr = sin(x)*exp(y) assert expr.diff([[x, y]]) == Array([cos(x)*exp(y), sin(x)*exp(y)]) assert expr.diff(y, ((x, y),)) == Array([cos(x)*exp(y), sin(x)*exp(y)]) assert expr.diff(x, ((x, y),)) == Array([-sin(x)*exp(y), cos(x)*exp(y)]) assert expr.diff(((y, x),), [[x, y]]) == Array([[cos(x)*exp(y), -sin(x)*exp(y)], [sin(x)*exp(y), cos(x)*exp(y)]]) # Test different notations: fxyz.diff(x).diff(y).diff(x) == fxyz.diff(((x, y, z),), 3)[0, 1, 0] fxyz.diff(z).diff(y).diff(x) == fxyz.diff(((x, y, z),), 3)[2, 1, 0] fxyz.diff([[x, y, z]], ((z, y, x),)) == Array([[fxyz.diff(i).diff(j) for i in (x, y, z)] for j in (z, y, x)]) # Test scalar derived by matrix remains matrix: res = x.diff(Matrix([[x, y]])) assert isinstance(res, ImmutableDenseMatrix) assert res == Matrix([[1, 0]]) res = (x**3).diff(Matrix([[x, y]])) assert isinstance(res, ImmutableDenseMatrix) assert res == Matrix([[3*x**2, 0]]) def test_getattr(): A = Matrix(((1, 4, x), (y, 2, 4), (10, 5, x**2 + 1))) raises(AttributeError, lambda: A.nonexistantattribute) assert getattr(A, 'diff')(x) == Matrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x))) def test_hessenberg(): A = Matrix([[3, 4, 1], [2, 4, 5], [0, 1, 2]]) assert A.is_upper_hessenberg A = A.T assert A.is_lower_hessenberg A[0, -1] = 1 assert A.is_lower_hessenberg is False A = Matrix([[3, 4, 1], [2, 4, 5], [3, 1, 2]]) assert not A.is_upper_hessenberg A = zeros(5, 2) assert A.is_upper_hessenberg def test_cholesky(): raises(NonSquareMatrixError, lambda: Matrix((1, 2)).cholesky()) raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).cholesky()) raises(ValueError, lambda: Matrix(((5 + I, 0), (0, 1))).cholesky()) raises(ValueError, lambda: Matrix(((1, 5), (5, 1))).cholesky()) raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).cholesky(hermitian=False)) assert Matrix(((5 + I, 0), (0, 1))).cholesky(hermitian=False) == Matrix([ [sqrt(5 + I), 0], [0, 1]]) A = Matrix(((1, 5), (5, 1))) L = A.cholesky(hermitian=False) assert L == Matrix([[1, 0], [5, 2*sqrt(6)*I]]) assert L*L.T == A A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) L = A.cholesky() assert L * L.T == A assert L.is_lower assert L == Matrix([[5, 0, 0], [3, 3, 0], [-1, 1, 3]]) A = Matrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11))) assert A.cholesky().expand() == Matrix(((2, 0, 0), (I, 1, 0), (1 - I, 0, 3))) raises(NonSquareMatrixError, lambda: SparseMatrix((1, 2)).cholesky()) raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).cholesky()) raises(ValueError, lambda: SparseMatrix(((5 + I, 0), (0, 1))).cholesky()) raises(ValueError, lambda: SparseMatrix(((1, 5), (5, 1))).cholesky()) raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).cholesky(hermitian=False)) assert SparseMatrix(((5 + I, 0), (0, 1))).cholesky(hermitian=False) == Matrix([ [sqrt(5 + I), 0], [0, 1]]) A = SparseMatrix(((1, 5), (5, 1))) L = A.cholesky(hermitian=False) assert L == Matrix([[1, 0], [5, 2*sqrt(6)*I]]) assert L*L.T == A A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) L = A.cholesky() assert L * L.T == A assert L.is_lower assert L == Matrix([[5, 0, 0], [3, 3, 0], [-1, 1, 3]]) A = SparseMatrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11))) assert A.cholesky() == Matrix(((2, 0, 0), (I, 1, 0), (1 - I, 0, 3))) def test_matrix_norm(): # Vector Tests # Test columns and symbols x = Symbol('x', real=True) v = Matrix([cos(x), sin(x)]) assert trigsimp(v.norm(2)) == 1 assert v.norm(10) == Pow(cos(x)**10 + sin(x)**10, Rational(1, 10)) # Test Rows A = Matrix([[5, Rational(3, 2)]]) assert A.norm() == Pow(25 + Rational(9, 4), S.Half) assert A.norm(oo) == max(A._mat) assert A.norm(-oo) == min(A._mat) # Matrix Tests # Intuitive test A = Matrix([[1, 1], [1, 1]]) assert A.norm(2) == 2 assert A.norm(-2) == 0 assert A.norm('frobenius') == 2 assert eye(10).norm(2) == eye(10).norm(-2) == 1 assert A.norm(oo) == 2 # Test with Symbols and more complex entries A = Matrix([[3, y, y], [x, S.Half, -pi]]) assert (A.norm('fro') == sqrt(Rational(37, 4) + 2*abs(y)**2 + pi**2 + x**2)) # Check non-square A = Matrix([[1, 2, -3], [4, 5, Rational(13, 2)]]) assert A.norm(2) == sqrt(Rational(389, 8) + sqrt(78665)/8) assert A.norm(-2) is S.Zero assert A.norm('frobenius') == sqrt(389)/2 # Test properties of matrix norms # https://en.wikipedia.org/wiki/Matrix_norm#Definition # Two matrices A = Matrix([[1, 2], [3, 4]]) B = Matrix([[5, 5], [-2, 2]]) C = Matrix([[0, -I], [I, 0]]) D = Matrix([[1, 0], [0, -1]]) L = [A, B, C, D] alpha = Symbol('alpha', real=True) for order in ['fro', 2, -2]: # Zero Check assert zeros(3).norm(order) is S.Zero # Check Triangle Inequality for all Pairs of Matrices for X in L: for Y in L: dif = (X.norm(order) + Y.norm(order) - (X + Y).norm(order)) assert (dif >= 0) # Scalar multiplication linearity for M in [A, B, C, D]: dif = simplify((alpha*M).norm(order) - abs(alpha) * M.norm(order)) assert dif == 0 # Test Properties of Vector Norms # https://en.wikipedia.org/wiki/Vector_norm # Two column vectors a = Matrix([1, 1 - 1*I, -3]) b = Matrix([S.Half, 1*I, 1]) c = Matrix([-1, -1, -1]) d = Matrix([3, 2, I]) e = Matrix([Integer(1e2), Rational(1, 1e2), 1]) L = [a, b, c, d, e] alpha = Symbol('alpha', real=True) for order in [1, 2, -1, -2, S.Infinity, S.NegativeInfinity, pi]: # Zero Check if order > 0: assert Matrix([0, 0, 0]).norm(order) is S.Zero # Triangle inequality on all pairs if order >= 1: # Triangle InEq holds only for these norms for X in L: for Y in L: dif = (X.norm(order) + Y.norm(order) - (X + Y).norm(order)) assert simplify(dif >= 0) is S.true # Linear to scalar multiplication if order in [1, 2, -1, -2, S.Infinity, S.NegativeInfinity]: for X in L: dif = simplify((alpha*X).norm(order) - (abs(alpha) * X.norm(order))) assert dif == 0 # ord=1 M = Matrix(3, 3, [1, 3, 0, -2, -1, 0, 3, 9, 6]) assert M.norm(1) == 13 def test_condition_number(): x = Symbol('x', real=True) A = eye(3) A[0, 0] = 10 A[2, 2] = Rational(1, 10) assert A.condition_number() == 100 A[1, 1] = x assert A.condition_number() == Max(10, Abs(x)) / Min(Rational(1, 10), Abs(x)) M = Matrix([[cos(x), sin(x)], [-sin(x), cos(x)]]) Mc = M.condition_number() assert all(Float(1.).epsilon_eq(Mc.subs(x, val).evalf()) for val in [Rational(1, 5), S.Half, Rational(1, 10), pi/2, pi, pi*Rational(7, 4) ]) #issue 10782 assert Matrix([]).condition_number() == 0 def test_equality(): A = Matrix(((1, 2, 3), (4, 5, 6), (7, 8, 9))) B = Matrix(((9, 8, 7), (6, 5, 4), (3, 2, 1))) assert A == A[:, :] assert not A != A[:, :] assert not A == B assert A != B assert A != 10 assert not A == 10 # A SparseMatrix can be equal to a Matrix C = SparseMatrix(((1, 0, 0), (0, 1, 0), (0, 0, 1))) D = Matrix(((1, 0, 0), (0, 1, 0), (0, 0, 1))) assert C == D assert not C != D def test_col_join(): assert eye(3).col_join(Matrix([[7, 7, 7]])) == \ Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1], [7, 7, 7]]) def test_row_insert(): r4 = Matrix([[4, 4, 4]]) for i in range(-4, 5): l = [1, 0, 0] l.insert(i, 4) assert flatten(eye(3).row_insert(i, r4).col(0).tolist()) == l def test_col_insert(): c4 = Matrix([4, 4, 4]) for i in range(-4, 5): l = [0, 0, 0] l.insert(i, 4) assert flatten(zeros(3).col_insert(i, c4).row(0).tolist()) == l def test_normalized(): assert Matrix([3, 4]).normalized() == \ Matrix([Rational(3, 5), Rational(4, 5)]) # Zero vector trivial cases assert Matrix([0, 0, 0]).normalized() == Matrix([0, 0, 0]) # Machine precision error truncation trivial cases m = Matrix([0,0,1.e-100]) assert m.normalized( iszerofunc=lambda x: x.evalf(n=10, chop=True).is_zero ) == Matrix([0, 0, 0]) def test_print_nonzero(): assert capture(lambda: eye(3).print_nonzero()) == \ '[X ]\n[ X ]\n[ X]\n' assert capture(lambda: eye(3).print_nonzero('.')) == \ '[. ]\n[ . ]\n[ .]\n' def test_zeros_eye(): assert Matrix.eye(3) == eye(3) assert Matrix.zeros(3) == zeros(3) assert ones(3, 4) == Matrix(3, 4, [1]*12) i = Matrix([[1, 0], [0, 1]]) z = Matrix([[0, 0], [0, 0]]) for cls in classes: m = cls.eye(2) assert i == m # but m == i will fail if m is immutable assert i == eye(2, cls=cls) assert type(m) == cls m = cls.zeros(2) assert z == m assert z == zeros(2, cls=cls) assert type(m) == cls def test_is_zero(): assert Matrix().is_zero_matrix assert Matrix([[0, 0], [0, 0]]).is_zero_matrix assert zeros(3, 4).is_zero_matrix assert not eye(3).is_zero_matrix assert Matrix([[x, 0], [0, 0]]).is_zero_matrix == None assert SparseMatrix([[x, 0], [0, 0]]).is_zero_matrix == None assert ImmutableMatrix([[x, 0], [0, 0]]).is_zero_matrix == None assert ImmutableSparseMatrix([[x, 0], [0, 0]]).is_zero_matrix == None assert Matrix([[x, 1], [0, 0]]).is_zero_matrix == False a = Symbol('a', nonzero=True) assert Matrix([[a, 0], [0, 0]]).is_zero_matrix == False def test_rotation_matrices(): # This tests the rotation matrices by rotating about an axis and back. theta = pi/3 r3_plus = rot_axis3(theta) r3_minus = rot_axis3(-theta) r2_plus = rot_axis2(theta) r2_minus = rot_axis2(-theta) r1_plus = rot_axis1(theta) r1_minus = rot_axis1(-theta) assert r3_minus*r3_plus*eye(3) == eye(3) assert r2_minus*r2_plus*eye(3) == eye(3) assert r1_minus*r1_plus*eye(3) == eye(3) # Check the correctness of the trace of the rotation matrix assert r1_plus.trace() == 1 + 2*cos(theta) assert r2_plus.trace() == 1 + 2*cos(theta) assert r3_plus.trace() == 1 + 2*cos(theta) # Check that a rotation with zero angle doesn't change anything. assert rot_axis1(0) == eye(3) assert rot_axis2(0) == eye(3) assert rot_axis3(0) == eye(3) def test_DeferredVector(): assert str(DeferredVector("vector")[4]) == "vector[4]" assert sympify(DeferredVector("d")) == DeferredVector("d") raises(IndexError, lambda: DeferredVector("d")[-1]) assert str(DeferredVector("d")) == "d" assert repr(DeferredVector("test")) == "DeferredVector('test')" def test_DeferredVector_not_iterable(): assert not iterable(DeferredVector('X')) def test_DeferredVector_Matrix(): raises(TypeError, lambda: Matrix(DeferredVector("V"))) def test_GramSchmidt(): R = Rational m1 = Matrix(1, 2, [1, 2]) m2 = Matrix(1, 2, [2, 3]) assert GramSchmidt([m1, m2]) == \ [Matrix(1, 2, [1, 2]), Matrix(1, 2, [R(2)/5, R(-1)/5])] assert GramSchmidt([m1.T, m2.T]) == \ [Matrix(2, 1, [1, 2]), Matrix(2, 1, [R(2)/5, R(-1)/5])] # from wikipedia assert GramSchmidt([Matrix([3, 1]), Matrix([2, 2])], True) == [ Matrix([3*sqrt(10)/10, sqrt(10)/10]), Matrix([-sqrt(10)/10, 3*sqrt(10)/10])] # https://github.com/sympy/sympy/issues/9488 L = FiniteSet(Matrix([1])) assert GramSchmidt(L) == [Matrix([[1]])] def test_casoratian(): assert casoratian([1, 2, 3, 4], 1) == 0 assert casoratian([1, 2, 3, 4], 1, zero=False) == 0 def test_zero_dimension_multiply(): assert (Matrix()*zeros(0, 3)).shape == (0, 3) assert zeros(3, 0)*zeros(0, 3) == zeros(3, 3) assert zeros(0, 3)*zeros(3, 0) == Matrix() def test_slice_issue_2884(): m = Matrix(2, 2, range(4)) assert m[1, :] == Matrix([[2, 3]]) assert m[-1, :] == Matrix([[2, 3]]) assert m[:, 1] == Matrix([[1, 3]]).T assert m[:, -1] == Matrix([[1, 3]]).T raises(IndexError, lambda: m[2, :]) raises(IndexError, lambda: m[2, 2]) def test_slice_issue_3401(): assert zeros(0, 3)[:, -1].shape == (0, 1) assert zeros(3, 0)[0, :] == Matrix(1, 0, []) def test_copyin(): s = zeros(3, 3) s[3] = 1 assert s[:, 0] == Matrix([0, 1, 0]) assert s[3] == 1 assert s[3: 4] == [1] s[1, 1] = 42 assert s[1, 1] == 42 assert s[1, 1:] == Matrix([[42, 0]]) s[1, 1:] = Matrix([[5, 6]]) assert s[1, :] == Matrix([[1, 5, 6]]) s[1, 1:] = [[42, 43]] assert s[1, :] == Matrix([[1, 42, 43]]) s[0, 0] = 17 assert s[:, :1] == Matrix([17, 1, 0]) s[0, 0] = [1, 1, 1] assert s[:, 0] == Matrix([1, 1, 1]) s[0, 0] = Matrix([1, 1, 1]) assert s[:, 0] == Matrix([1, 1, 1]) s[0, 0] = SparseMatrix([1, 1, 1]) assert s[:, 0] == Matrix([1, 1, 1]) def test_invertible_check(): # sometimes a singular matrix will have a pivot vector shorter than # the number of rows in a matrix... assert Matrix([[1, 2], [1, 2]]).rref() == (Matrix([[1, 2], [0, 0]]), (0,)) raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inv()) m = Matrix([ [-1, -1, 0], [ x, 1, 1], [ 1, x, -1], ]) assert len(m.rref()[1]) != m.rows # in addition, unless simplify=True in the call to rref, the identity # matrix will be returned even though m is not invertible assert m.rref()[0] != eye(3) assert m.rref(simplify=signsimp)[0] != eye(3) raises(ValueError, lambda: m.inv(method="ADJ")) raises(ValueError, lambda: m.inv(method="GE")) raises(ValueError, lambda: m.inv(method="LU")) def test_issue_3959(): x, y = symbols('x, y') e = x*y assert e.subs(x, Matrix([3, 5, 3])) == Matrix([3, 5, 3])*y def test_issue_5964(): assert str(Matrix([[1, 2], [3, 4]])) == 'Matrix([[1, 2], [3, 4]])' def test_issue_7604(): x, y = symbols("x y") assert sstr(Matrix([[x, 2*y], [y**2, x + 3]])) == \ 'Matrix([\n[ x, 2*y],\n[y**2, x + 3]])' def test_is_Identity(): assert eye(3).is_Identity assert eye(3).as_immutable().is_Identity assert not zeros(3).is_Identity assert not ones(3).is_Identity # issue 6242 assert not Matrix([[1, 0, 0]]).is_Identity # issue 8854 assert SparseMatrix(3,3, {(0,0):1, (1,1):1, (2,2):1}).is_Identity assert not SparseMatrix(2,3, range(6)).is_Identity assert not SparseMatrix(3,3, {(0,0):1, (1,1):1}).is_Identity assert not SparseMatrix(3,3, {(0,0):1, (1,1):1, (2,2):1, (0,1):2, (0,2):3}).is_Identity def test_dot(): assert ones(1, 3).dot(ones(3, 1)) == 3 assert ones(1, 3).dot([1, 1, 1]) == 3 assert Matrix([1, 2, 3]).dot(Matrix([1, 2, 3])) == 14 assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I])) == -5 + I assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=False) == -5 + I assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=True) == 13 + I assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=True, conjugate_convention="physics") == 13 - I assert Matrix([1, 2, 3*I]).dot(Matrix([4, 5*I, 6]), hermitian=True, conjugate_convention="right") == 4 + 8*I assert Matrix([1, 2, 3*I]).dot(Matrix([4, 5*I, 6]), hermitian=True, conjugate_convention="left") == 4 - 8*I assert Matrix([I, 2*I]).dot(Matrix([I, 2*I]), hermitian=False, conjugate_convention="left") == -5 assert Matrix([I, 2*I]).dot(Matrix([I, 2*I]), conjugate_convention="left") == 5 raises(ValueError, lambda: Matrix([1, 2]).dot(Matrix([3, 4]), hermitian=True, conjugate_convention="test")) def test_dual(): B_x, B_y, B_z, E_x, E_y, E_z = symbols( 'B_x B_y B_z E_x E_y E_z', real=True) F = Matrix(( ( 0, E_x, E_y, E_z), (-E_x, 0, B_z, -B_y), (-E_y, -B_z, 0, B_x), (-E_z, B_y, -B_x, 0) )) Fd = Matrix(( ( 0, -B_x, -B_y, -B_z), (B_x, 0, E_z, -E_y), (B_y, -E_z, 0, E_x), (B_z, E_y, -E_x, 0) )) assert F.dual().equals(Fd) assert eye(3).dual().equals(zeros(3)) assert F.dual().dual().equals(-F) def test_anti_symmetric(): assert Matrix([1, 2]).is_anti_symmetric() is False m = Matrix(3, 3, [0, x**2 + 2*x + 1, y, -(x + 1)**2, 0, x*y, -y, -x*y, 0]) assert m.is_anti_symmetric() is True assert m.is_anti_symmetric(simplify=False) is False assert m.is_anti_symmetric(simplify=lambda x: x) is False # tweak to fail m[2, 1] = -m[2, 1] assert m.is_anti_symmetric() is False # untweak m[2, 1] = -m[2, 1] m = m.expand() assert m.is_anti_symmetric(simplify=False) is True m[0, 0] = 1 assert m.is_anti_symmetric() is False def test_normalize_sort_diogonalization(): A = Matrix(((1, 2), (2, 1))) P, Q = A.diagonalize(normalize=True) assert P*P.T == P.T*P == eye(P.cols) P, Q = A.diagonalize(normalize=True, sort=True) assert P*P.T == P.T*P == eye(P.cols) assert P*Q*P.inv() == A def test_issue_5321(): raises(ValueError, lambda: Matrix([[1, 2, 3], Matrix(0, 1, [])])) def test_issue_5320(): assert Matrix.hstack(eye(2), 2*eye(2)) == Matrix([ [1, 0, 2, 0], [0, 1, 0, 2] ]) assert Matrix.vstack(eye(2), 2*eye(2)) == Matrix([ [1, 0], [0, 1], [2, 0], [0, 2] ]) cls = SparseMatrix assert cls.hstack(cls(eye(2)), cls(2*eye(2))) == Matrix([ [1, 0, 2, 0], [0, 1, 0, 2] ]) def test_issue_11944(): A = Matrix([[1]]) AIm = sympify(A) assert Matrix.hstack(AIm, A) == Matrix([[1, 1]]) assert Matrix.vstack(AIm, A) == Matrix([[1], [1]]) def test_cross(): a = [1, 2, 3] b = [3, 4, 5] col = Matrix([-2, 4, -2]) row = col.T def test(M, ans): assert ans == M assert type(M) == cls for cls in classes: A = cls(a) B = cls(b) test(A.cross(B), col) test(A.cross(B.T), col) test(A.T.cross(B.T), row) test(A.T.cross(B), row) raises(ShapeError, lambda: Matrix(1, 2, [1, 1]).cross(Matrix(1, 2, [1, 1]))) def test_hash(): for cls in classes[-2:]: s = {cls.eye(1), cls.eye(1)} assert len(s) == 1 and s.pop() == cls.eye(1) # issue 3979 for cls in classes[:2]: assert not isinstance(cls.eye(1), Hashable) @XFAIL def test_issue_3979(): # when this passes, delete this and change the [1:2] # to [:2] in the test_hash above for issue 3979 cls = classes[0] raises(AttributeError, lambda: hash(cls.eye(1))) def test_adjoint(): dat = [[0, I], [1, 0]] ans = Matrix([[0, 1], [-I, 0]]) for cls in classes: assert ans == cls(dat).adjoint() def test_simplify_immutable(): from sympy import simplify, sin, cos assert simplify(ImmutableMatrix([[sin(x)**2 + cos(x)**2]])) == \ ImmutableMatrix([[1]]) def test_replace(): from sympy import symbols, Function, Matrix F, G = symbols('F, G', cls=Function) K = Matrix(2, 2, lambda i, j: G(i+j)) M = Matrix(2, 2, lambda i, j: F(i+j)) N = M.replace(F, G) assert N == K def test_replace_map(): from sympy import symbols, Function, Matrix F, G = symbols('F, G', cls=Function) K = Matrix(2, 2, [(G(0), {F(0): G(0)}), (G(1), {F(1): G(1)}), (G(1), {F(1)\ : G(1)}), (G(2), {F(2): G(2)})]) M = Matrix(2, 2, lambda i, j: F(i+j)) N = M.replace(F, G, True) assert N == K def test_atoms(): m = Matrix([[1, 2], [x, 1 - 1/x]]) assert m.atoms() == {S.One,S(2),S.NegativeOne, x} assert m.atoms(Symbol) == {x} def test_pinv(): # Pseudoinverse of an invertible matrix is the inverse. A1 = Matrix([[a, b], [c, d]]) assert simplify(A1.pinv(method="RD")) == simplify(A1.inv()) # Test the four properties of the pseudoinverse for various matrices. As = [Matrix([[13, 104], [2212, 3], [-3, 5]]), Matrix([[1, 7, 9], [11, 17, 19]]), Matrix([a, b])] for A in As: A_pinv = A.pinv(method="RD") AAp = A * A_pinv ApA = A_pinv * A assert simplify(AAp * A) == A assert simplify(ApA * A_pinv) == A_pinv assert AAp.H == AAp assert ApA.H == ApA # XXX Pinv with diagonalization makes expression too complicated. for A in As: A_pinv = simplify(A.pinv(method="ED")) AAp = A * A_pinv ApA = A_pinv * A assert simplify(AAp * A) == A assert simplify(ApA * A_pinv) == A_pinv assert AAp.H == AAp assert ApA.H == ApA # XXX Computing pinv using diagonalization makes an expression that # is too complicated to simplify. # A1 = Matrix([[a, b], [c, d]]) # assert simplify(A1.pinv(method="ED")) == simplify(A1.inv()) # so this is tested numerically at a fixed random point from sympy.core.numbers import comp q = A1.pinv(method="ED") w = A1.inv() reps = {a: -73633, b: 11362, c: 55486, d: 62570} assert all( comp(i.n(), j.n()) for i, j in zip(q.subs(reps), w.subs(reps)) ) @XFAIL def test_pinv_rank_deficient_when_diagonalization_fails(): # Test the four properties of the pseudoinverse for matrices when # diagonalization of A.H*A fails. As = [ Matrix([ [61, 89, 55, 20, 71, 0], [62, 96, 85, 85, 16, 0], [69, 56, 17, 4, 54, 0], [10, 54, 91, 41, 71, 0], [ 7, 30, 10, 48, 90, 0], [0, 0, 0, 0, 0, 0]]) ] for A in As: A_pinv = A.pinv(method="ED") AAp = A * A_pinv ApA = A_pinv * A assert AAp.H == AAp assert ApA.H == ApA def test_issue_7201(): assert ones(0, 1) + ones(0, 1) == Matrix(0, 1, []) assert ones(1, 0) + ones(1, 0) == Matrix(1, 0, []) def test_free_symbols(): for M in ImmutableMatrix, ImmutableSparseMatrix, Matrix, SparseMatrix: assert M([[x], [0]]).free_symbols == {x} def test_from_ndarray(): """See issue 7465.""" try: from numpy import array except ImportError: skip('NumPy must be available to test creating matrices from ndarrays') assert Matrix(array([1, 2, 3])) == Matrix([1, 2, 3]) assert Matrix(array([[1, 2, 3]])) == Matrix([[1, 2, 3]]) assert Matrix(array([[1, 2, 3], [4, 5, 6]])) == \ Matrix([[1, 2, 3], [4, 5, 6]]) assert Matrix(array([x, y, z])) == Matrix([x, y, z]) raises(NotImplementedError, lambda: Matrix(array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]))) assert Matrix([array([1, 2]), array([3, 4])]) == Matrix([[1, 2], [3, 4]]) assert Matrix([array([1, 2]), [3, 4]]) == Matrix([[1, 2], [3, 4]]) assert Matrix([array([]), array([])]) == Matrix([]) def test_17522_numpy(): from sympy.matrices.common import _matrixify try: from numpy import array, matrix except ImportError: skip('NumPy must be available to test indexing matrixified NumPy ndarrays and matrices') m = _matrixify(array([[1, 2], [3, 4]])) assert m[3] == 4 assert list(m) == [1, 2, 3, 4] m = _matrixify(matrix([[1, 2], [3, 4]])) assert m[3] == 4 assert list(m) == [1, 2, 3, 4] def test_17522_mpmath(): from sympy.matrices.common import _matrixify try: from mpmath import matrix except ImportError: skip('mpmath must be available to test indexing matrixified mpmath matrices') m = _matrixify(matrix([[1, 2], [3, 4]])) assert m[3] == 4 assert list(m) == [1, 2, 3, 4] def test_17522_scipy(): from sympy.matrices.common import _matrixify try: from scipy.sparse import csr_matrix except ImportError: skip('SciPy must be available to test indexing matrixified SciPy sparse matrices') m = _matrixify(csr_matrix([[1, 2], [3, 4]])) assert m[3] == 4 assert list(m) == [1, 2, 3, 4] def test_hermitian(): a = Matrix([[1, I], [-I, 1]]) assert a.is_hermitian a[0, 0] = 2*I assert a.is_hermitian is False a[0, 0] = x assert a.is_hermitian is None a[0, 1] = a[1, 0]*I assert a.is_hermitian is False def test_doit(): a = Matrix([[Add(x,x, evaluate=False)]]) assert a[0] != 2*x assert a.doit() == Matrix([[2*x]]) def test_issue_9457_9467_9876(): # for row_del(index) M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) M.row_del(1) assert M == Matrix([[1, 2, 3], [3, 4, 5]]) N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) N.row_del(-2) assert N == Matrix([[1, 2, 3], [3, 4, 5]]) O = Matrix([[1, 2, 3], [5, 6, 7], [9, 10, 11]]) O.row_del(-1) assert O == Matrix([[1, 2, 3], [5, 6, 7]]) P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) raises(IndexError, lambda: P.row_del(10)) Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) raises(IndexError, lambda: Q.row_del(-10)) # for col_del(index) M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) M.col_del(1) assert M == Matrix([[1, 3], [2, 4], [3, 5]]) N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) N.col_del(-2) assert N == Matrix([[1, 3], [2, 4], [3, 5]]) P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) raises(IndexError, lambda: P.col_del(10)) Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]]) raises(IndexError, lambda: Q.col_del(-10)) def test_issue_9422(): x, y = symbols('x y', commutative=False) a, b = symbols('a b') M = eye(2) M1 = Matrix(2, 2, [x, y, y, z]) assert y*x*M != x*y*M assert b*a*M == a*b*M assert x*M1 != M1*x assert a*M1 == M1*a assert y*x*M == Matrix([[y*x, 0], [0, y*x]]) def test_issue_10770(): M = Matrix([]) a = ['col_insert', 'row_join'], Matrix([9, 6, 3]) b = ['row_insert', 'col_join'], a[1].T c = ['row_insert', 'col_insert'], Matrix([[1, 2], [3, 4]]) for ops, m in (a, b, c): for op in ops: f = getattr(M, op) new = f(m) if 'join' in op else f(42, m) assert new == m and id(new) != id(m) def test_issue_10658(): A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert A.extract([0, 1, 2], [True, True, False]) == \ Matrix([[1, 2], [4, 5], [7, 8]]) assert A.extract([0, 1, 2], [True, False, False]) == Matrix([[1], [4], [7]]) assert A.extract([True, False, False], [0, 1, 2]) == Matrix([[1, 2, 3]]) assert A.extract([True, False, True], [0, 1, 2]) == \ Matrix([[1, 2, 3], [7, 8, 9]]) assert A.extract([0, 1, 2], [False, False, False]) == Matrix(3, 0, []) assert A.extract([False, False, False], [0, 1, 2]) == Matrix(0, 3, []) assert A.extract([True, False, True], [False, True, False]) == \ Matrix([[2], [8]]) def test_opportunistic_simplification(): # this test relates to issue #10718, #9480, #11434 # issue #9480 m = Matrix([[-5 + 5*sqrt(2), -5], [-5*sqrt(2)/2 + 5, -5*sqrt(2)/2]]) assert m.rank() == 1 # issue #10781 m = Matrix([[3+3*sqrt(3)*I, -9],[4,-3+3*sqrt(3)*I]]) assert simplify(m.rref()[0] - Matrix([[1, -9/(3 + 3*sqrt(3)*I)], [0, 0]])) == zeros(2, 2) # issue #11434 ax,ay,bx,by,cx,cy,dx,dy,ex,ey,t0,t1 = symbols('a_x a_y b_x b_y c_x c_y d_x d_y e_x e_y t_0 t_1') m = Matrix([[ax,ay,ax*t0,ay*t0,0],[bx,by,bx*t0,by*t0,0],[cx,cy,cx*t0,cy*t0,1],[dx,dy,dx*t0,dy*t0,1],[ex,ey,2*ex*t1-ex*t0,2*ey*t1-ey*t0,0]]) assert m.rank() == 4 def test_partial_pivoting(): # example from https://en.wikipedia.org/wiki/Pivot_element # partial pivoting with back substitution gives a perfect result # naive pivoting give an error ~1e-13, so anything better than # 1e-15 is good mm=Matrix([[0.003 ,59.14, 59.17],[ 5.291, -6.13,46.78]]) assert (mm.rref()[0] - Matrix([[1.0, 0, 10.0], [ 0, 1.0, 1.0]])).norm() < 1e-15 # issue #11549 m_mixed = Matrix([[6e-17, 1.0, 4],[ -1.0, 0, 8],[ 0, 0, 1]]) m_float = Matrix([[6e-17, 1.0, 4.],[ -1.0, 0., 8.],[ 0., 0., 1.]]) m_inv = Matrix([[ 0, -1.0, 8.0],[1.0, 6.0e-17, -4.0],[ 0, 0, 1]]) # this example is numerically unstable and involves a matrix with a norm >= 8, # this comparing the difference of the results with 1e-15 is numerically sound. assert (m_mixed.inv() - m_inv).norm() < 1e-15 assert (m_float.inv() - m_inv).norm() < 1e-15 def test_iszero_substitution(): """ When doing numerical computations, all elements that pass the iszerofunc test should be set to numerically zero if they aren't already. """ # Matrix from issue #9060 m = Matrix([[0.9, -0.1, -0.2, 0],[-0.8, 0.9, -0.4, 0],[-0.1, -0.8, 0.6, 0]]) m_rref = m.rref(iszerofunc=lambda x: abs(x)<6e-15)[0] m_correct = Matrix([[1.0, 0, -0.301369863013699, 0],[ 0, 1.0, -0.712328767123288, 0],[ 0, 0, 0, 0]]) m_diff = m_rref - m_correct assert m_diff.norm() < 1e-15 # if a zero-substitution wasn't made, this entry will be -1.11022302462516e-16 assert m_rref[2,2] == 0 def test_issue_11238(): from sympy import Point xx = 8*tan(pi*Rational(13, 45))/(tan(pi*Rational(13, 45)) + sqrt(3)) yy = (-8*sqrt(3)*tan(pi*Rational(13, 45))**2 + 24*tan(pi*Rational(13, 45)))/(-3 + tan(pi*Rational(13, 45))**2) p1 = Point(0, 0) p2 = Point(1, -sqrt(3)) p0 = Point(xx,yy) m1 = Matrix([p1 - simplify(p0), p2 - simplify(p0)]) m2 = Matrix([p1 - p0, p2 - p0]) m3 = Matrix([simplify(p1 - p0), simplify(p2 - p0)]) # This system has expressions which are zero and # cannot be easily proved to be such, so without # numerical testing, these assertions will fail. Z = lambda x: abs(x.n()) < 1e-20 assert m1.rank(simplify=True, iszerofunc=Z) == 1 assert m2.rank(simplify=True, iszerofunc=Z) == 1 assert m3.rank(simplify=True, iszerofunc=Z) == 1 def test_as_real_imag(): m1 = Matrix(2,2,[1,2,3,4]) m2 = m1*S.ImaginaryUnit m3 = m1 + m2 for kls in classes: a,b = kls(m3).as_real_imag() assert list(a) == list(m1) assert list(b) == list(m1) def test_deprecated(): # Maintain tests for deprecated functions. We must capture # the deprecation warnings. When the deprecated functionality is # removed, the corresponding tests should be removed. m = Matrix(3, 3, [0, 1, 0, -4, 4, 0, -2, 1, 2]) P, Jcells = m.jordan_cells() assert Jcells[1] == Matrix(1, 1, [2]) assert Jcells[0] == Matrix(2, 2, [2, 1, 0, 2]) with warns_deprecated_sympy(): assert Matrix([[1,2],[3,4]]).dot(Matrix([[1,3],[4,5]])) == [10, 19, 14, 28] def test_issue_14489(): from sympy import Mod A = Matrix([-1, 1, 2]) B = Matrix([10, 20, -15]) assert Mod(A, 3) == Matrix([2, 1, 2]) assert Mod(B, 4) == Matrix([2, 0, 1]) def test_issue_14943(): # Test that __array__ accepts the optional dtype argument try: from numpy import array except ImportError: skip('NumPy must be available to test creating matrices from ndarrays') M = Matrix([[1,2], [3,4]]) assert array(M, dtype=float).dtype.name == 'float64' def test_case_6913(): m = MatrixSymbol('m', 1, 1) a = Symbol("a") a = m[0, 0]>0 assert str(a) == 'm[0, 0] > 0' def test_issue_11948(): A = MatrixSymbol('A', 3, 3) a = Wild('a') assert A.match(a) == {a: A} def test_gramschmidt_conjugate_dot(): vecs = [Matrix([1, I]), Matrix([1, -I])] assert Matrix.orthogonalize(*vecs) == \ [Matrix([[1], [I]]), Matrix([[1], [-I]])] vecs = [Matrix([1, I, 0]), Matrix([I, 0, -I])] assert Matrix.orthogonalize(*vecs) == \ [Matrix([[1], [I], [0]]), Matrix([[I/2], [S(1)/2], [-I]])] mat = Matrix([[1, I], [1, -I]]) Q, R = mat.QRdecomposition() assert Q * Q.H == Matrix.eye(2) def test_issue_8207(): a = Matrix(MatrixSymbol('a', 3, 1)) b = Matrix(MatrixSymbol('b', 3, 1)) c = a.dot(b) d = diff(c, a[0, 0]) e = diff(d, a[0, 0]) assert d == b[0, 0] assert e == 0 def test_func(): from sympy.simplify.simplify import nthroot A = Matrix([[1, 2],[0, 3]]) assert A.analytic_func(sin(x*t), x) == Matrix([[sin(t), sin(3*t) - sin(t)], [0, sin(3*t)]]) A = Matrix([[2, 1],[1, 2]]) assert (pi * A / 6).analytic_func(cos(x), x) == Matrix([[sqrt(3)/4, -sqrt(3)/4], [-sqrt(3)/4, sqrt(3)/4]]) raises(ValueError, lambda : zeros(5).analytic_func(log(x), x)) raises(ValueError, lambda : (A*x).analytic_func(log(x), x)) A = Matrix([[0, -1, -2, 3], [0, -1, -2, 3], [0, 1, 0, -1], [0, 0, -1, 1]]) assert A.analytic_func(exp(x), x) == A.exp() raises(ValueError, lambda : A.analytic_func(sqrt(x), x)) A = Matrix([[41, 12],[12, 34]]) assert simplify(A.analytic_func(sqrt(x), x)**2) == A A = Matrix([[3, -12, 4], [-1, 0, -2], [-1, 5, -1]]) assert simplify(A.analytic_func(nthroot(x, 3), x)**3) == A A = Matrix([[2, 0, 0, 0], [1, 2, 0, 0], [0, 1, 3, 0], [0, 0, 1, 3]]) assert A.analytic_func(exp(x), x) == A.exp() A = Matrix([[0, 2, 1, 6], [0, 0, 1, 2], [0, 0, 0, 3], [0, 0, 0, 0]]) assert A.analytic_func(exp(x*t), x) == expand(simplify((A*t).exp())) def test_issue_19809(): def f(): assert _dotprodsimp_state.state == None m = Matrix([[1]]) m = m * m return True with dotprodsimp(True): with concurrent.futures.ThreadPoolExecutor() as executor: future = executor.submit(f) assert future.result()
80094c3d4b7fb76b434b6723e81b4a191d34e3cca98395277e9e01e12b8cc188
from sympy import ask, Q from sympy.core import Basic, Add, Mul, S from sympy.core.sympify import _sympify from sympy.matrices.common import NonInvertibleMatrixError from sympy.strategies import typed, exhaust, condition, do_one, unpack from sympy.strategies.traverse import bottom_up from sympy.utilities import sift from sympy.utilities.misc import filldedent from sympy.matrices.expressions.matexpr import MatrixExpr, MatrixElement from sympy.matrices.expressions.matmul import MatMul from sympy.matrices.expressions.matadd import MatAdd from sympy.matrices.expressions.matpow import MatPow from sympy.matrices.expressions.transpose import Transpose, transpose from sympy.matrices.expressions.trace import trace from sympy.matrices.expressions.determinant import det, Determinant from sympy.matrices.expressions.slice import MatrixSlice from sympy.matrices.expressions.inverse import Inverse from sympy.matrices.expressions.special import ZeroMatrix, Identity from sympy.matrices import Matrix, ShapeError from sympy.functions.elementary.complexes import re, im class BlockMatrix(MatrixExpr): """A BlockMatrix is a Matrix comprised of other matrices. The submatrices are stored in a SymPy Matrix object but accessed as part of a Matrix Expression >>> from sympy import (MatrixSymbol, BlockMatrix, symbols, ... Identity, ZeroMatrix, block_collapse) >>> n,m,l = symbols('n m l') >>> X = MatrixSymbol('X', n, n) >>> Y = MatrixSymbol('Y', m ,m) >>> Z = MatrixSymbol('Z', n, m) >>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]]) >>> print(B) Matrix([ [X, Z], [0, Y]]) >>> C = BlockMatrix([[Identity(n), Z]]) >>> print(C) Matrix([[I, Z]]) >>> print(block_collapse(C*B)) Matrix([[X, Z + Z*Y]]) Some matrices might be comprised of rows of blocks with the matrices in each row having the same height and the rows all having the same total number of columns but not having the same number of columns for each matrix in each row. In this case, the matrix is not a block matrix and should be instantiated by Matrix. >>> from sympy import ones, Matrix >>> dat = [ ... [ones(3,2), ones(3,3)*2], ... [ones(2,3)*3, ones(2,2)*4]] ... >>> BlockMatrix(dat) Traceback (most recent call last): ... ValueError: Although this matrix is comprised of blocks, the blocks do not fill the matrix in a size-symmetric fashion. To create a full matrix from these arguments, pass them directly to Matrix. >>> Matrix(dat) Matrix([ [1, 1, 2, 2, 2], [1, 1, 2, 2, 2], [1, 1, 2, 2, 2], [3, 3, 3, 4, 4], [3, 3, 3, 4, 4]]) See Also ======== sympy.matrices.matrices.MatrixBase.irregular """ def __new__(cls, *args, **kwargs): from sympy.matrices.immutable import ImmutableDenseMatrix from sympy.utilities.iterables import is_sequence isMat = lambda i: getattr(i, 'is_Matrix', False) if len(args) != 1 or \ not is_sequence(args[0]) or \ len({isMat(r) for r in args[0]}) != 1: raise ValueError(filldedent(''' expecting a sequence of 1 or more rows containing Matrices.''')) rows = args[0] if args else [] if not isMat(rows): if rows and isMat(rows[0]): rows = [rows] # rows is not list of lists or [] # regularity check # same number of matrices in each row blocky = ok = len({len(r) for r in rows}) == 1 if ok: # same number of rows for each matrix in a row for r in rows: ok = len({i.rows for i in r}) == 1 if not ok: break blocky = ok if ok: # same number of cols for each matrix in each col for c in range(len(rows[0])): ok = len({rows[i][c].cols for i in range(len(rows))}) == 1 if not ok: break if not ok: # same total cols in each row ok = len({ sum([i.cols for i in r]) for r in rows}) == 1 if blocky and ok: raise ValueError(filldedent(''' Although this matrix is comprised of blocks, the blocks do not fill the matrix in a size-symmetric fashion. To create a full matrix from these arguments, pass them directly to Matrix.''')) raise ValueError(filldedent(''' When there are not the same number of rows in each row's matrices or there are not the same number of total columns in each row, the matrix is not a block matrix. If this matrix is known to consist of blocks fully filling a 2-D space then see Matrix.irregular.''')) mat = ImmutableDenseMatrix(rows, evaluate=False) obj = Basic.__new__(cls, mat) return obj @property def shape(self): numrows = numcols = 0 M = self.blocks for i in range(M.shape[0]): numrows += M[i, 0].shape[0] for i in range(M.shape[1]): numcols += M[0, i].shape[1] return (numrows, numcols) @property def blockshape(self): return self.blocks.shape @property def blocks(self): return self.args[0] @property def rowblocksizes(self): return [self.blocks[i, 0].rows for i in range(self.blockshape[0])] @property def colblocksizes(self): return [self.blocks[0, i].cols for i in range(self.blockshape[1])] def structurally_equal(self, other): return (isinstance(other, BlockMatrix) and self.shape == other.shape and self.blockshape == other.blockshape and self.rowblocksizes == other.rowblocksizes and self.colblocksizes == other.colblocksizes) def _blockmul(self, other): if (isinstance(other, BlockMatrix) and self.colblocksizes == other.rowblocksizes): return BlockMatrix(self.blocks*other.blocks) return self * other def _blockadd(self, other): if (isinstance(other, BlockMatrix) and self.structurally_equal(other)): return BlockMatrix(self.blocks + other.blocks) return self + other def _eval_transpose(self): # Flip all the individual matrices matrices = [transpose(matrix) for matrix in self.blocks] # Make a copy M = Matrix(self.blockshape[0], self.blockshape[1], matrices) # Transpose the block structure M = M.transpose() return BlockMatrix(M) def _eval_trace(self): if self.rowblocksizes == self.colblocksizes: return Add(*[trace(self.blocks[i, i]) for i in range(self.blockshape[0])]) raise NotImplementedError( "Can't perform trace of irregular blockshape") def _eval_determinant(self): if self.blockshape == (1, 1): return det(self.blocks[0, 0]) if self.blockshape == (2, 2): [[A, B], [C, D]] = self.blocks.tolist() if ask(Q.invertible(A)): return det(A)*det(D - C*A.I*B) elif ask(Q.invertible(D)): return det(D)*det(A - B*D.I*C) return Determinant(self) def as_real_imag(self): real_matrices = [re(matrix) for matrix in self.blocks] real_matrices = Matrix(self.blockshape[0], self.blockshape[1], real_matrices) im_matrices = [im(matrix) for matrix in self.blocks] im_matrices = Matrix(self.blockshape[0], self.blockshape[1], im_matrices) return (real_matrices, im_matrices) def transpose(self): """Return transpose of matrix. Examples ======== >>> from sympy import MatrixSymbol, BlockMatrix, ZeroMatrix >>> from sympy.abc import m, n >>> X = MatrixSymbol('X', n, n) >>> Y = MatrixSymbol('Y', m ,m) >>> Z = MatrixSymbol('Z', n, m) >>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]]) >>> B.transpose() Matrix([ [X.T, 0], [Z.T, Y.T]]) >>> _.transpose() Matrix([ [X, Z], [0, Y]]) """ return self._eval_transpose() def schur(self, mat = 'A', generalized = False): """Return the Schur Complement of the 2x2 BlockMatrix Parameters ========== mat : String, optional The matrix with respect to which the Schur Complement is calculated. 'A' is used by default generalized : bool, optional If True, returns the generalized Schur Component which uses Moore-Penrose Inverse Examples ======== >>> from sympy import symbols, MatrixSymbol, BlockMatrix >>> m, n = symbols('m n') >>> A = MatrixSymbol('A', n, n) >>> B = MatrixSymbol('B', n, m) >>> C = MatrixSymbol('C', m, n) >>> D = MatrixSymbol('D', m, m) >>> X = BlockMatrix([[A, B], [C, D]]) The default Schur Complement is evaluated with "A" >>> X.schur() -C*A**(-1)*B + D >>> X.schur('D') A - B*D**(-1)*C Schur complement with non-invertible matrices is not defined. Instead, the generalized Schur complement can be calculated which uses the Moore-Penrose Inverse. To achieve this, `generalized` must be set to `True` >>> X.schur('B', generalized=True) C - D*(B.T*B)**(-1)*B.T*A >>> X.schur('C', generalized=True) -A*(C.T*C)**(-1)*C.T*D + B Returns ======= M : Matrix The Schur Complement Matrix Raises ====== ShapeError If the block matrix is not a 2x2 matrix NonInvertibleMatrixError If given matrix is non-invertible References ========== .. [1] Wikipedia Article on Schur Component : https://en.wikipedia.org/wiki/Schur_complement See Also ======== sympy.matrices.matrices.MatrixBase.pinv """ if self.blockshape == (2, 2): [[A, B], [C, D]] = self.blocks.tolist() d={'A' : A, 'B' : B, 'C' : C, 'D' : D} try: inv = (d[mat].T*d[mat]).inv()*d[mat].T if generalized else d[mat].inv() if mat == 'A': return D - C * inv * B elif mat == 'B': return C - D * inv * A elif mat == 'C': return B - A * inv * D elif mat == 'D': return A - B * inv * C #For matrices where no sub-matrix is square return self except NonInvertibleMatrixError: raise NonInvertibleMatrixError('The given matrix is not invertible. Please set generalized=True \ to compute the generalized Schur Complement which uses Moore-Penrose Inverse') else: raise ShapeError('Schur Complement can only be calculated for 2x2 block matrices') def LDUdecomposition(self): """Returns the Block LDU decomposition of a 2x2 Block Matrix Returns ======= (L, D, U) : Matrices L : Lower Diagonal Matrix D : Diagonal Matrix U : Upper Diagonal Matrix Examples ======== >>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse >>> m, n = symbols('m n') >>> A = MatrixSymbol('A', n, n) >>> B = MatrixSymbol('B', n, m) >>> C = MatrixSymbol('C', m, n) >>> D = MatrixSymbol('D', m, m) >>> X = BlockMatrix([[A, B], [C, D]]) >>> L, D, U = X.LDUdecomposition() >>> block_collapse(L*D*U) Matrix([ [A, B], [C, D]]) Raises ====== ShapeError If the block matrix is not a 2x2 matrix NonInvertibleMatrixError If the matrix "A" is non-invertible See Also ======== sympy.matrices.expressions.blockmatrix.BlockMatrix.UDLdecomposition sympy.matrices.expressions.blockmatrix.BlockMatrix.LUdecomposition """ if self.blockshape == (2,2): [[A, B], [C, D]] = self.blocks.tolist() try: AI = A.I except NonInvertibleMatrixError: raise NonInvertibleMatrixError('Block LDU decomposition cannot be calculated when\ "A" is singular') Ip = Identity(B.shape[0]) Iq = Identity(B.shape[1]) Z = ZeroMatrix(*B.shape) L = BlockMatrix([[Ip, Z], [C*AI, Iq]]) D = BlockDiagMatrix(A, self.schur()) U = BlockMatrix([[Ip, AI*B],[Z.T, Iq]]) return L, D, U else: raise ShapeError("Block LDU decomposition is supported only for 2x2 block matrices") def UDLdecomposition(self): """Returns the Block UDL decomposition of a 2x2 Block Matrix Returns ======= (U, D, L) : Matrices U : Upper Diagonal Matrix D : Diagonal Matrix L : Lower Diagonal Matrix Examples ======== >>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse >>> m, n = symbols('m n') >>> A = MatrixSymbol('A', n, n) >>> B = MatrixSymbol('B', n, m) >>> C = MatrixSymbol('C', m, n) >>> D = MatrixSymbol('D', m, m) >>> X = BlockMatrix([[A, B], [C, D]]) >>> U, D, L = X.UDLdecomposition() >>> block_collapse(U*D*L) Matrix([ [A, B], [C, D]]) Raises ====== ShapeError If the block matrix is not a 2x2 matrix NonInvertibleMatrixError If the matrix "D" is non-invertible See Also ======== sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition sympy.matrices.expressions.blockmatrix.BlockMatrix.LUdecomposition """ if self.blockshape == (2,2): [[A, B], [C, D]] = self.blocks.tolist() try: DI = D.I except NonInvertibleMatrixError: raise NonInvertibleMatrixError('Block UDL decomposition cannot be calculated when\ "D" is singular') Ip = Identity(A.shape[0]) Iq = Identity(B.shape[1]) Z = ZeroMatrix(*B.shape) U = BlockMatrix([[Ip, B*DI], [Z.T, Iq]]) D = BlockDiagMatrix(self.schur('D'), D) L = BlockMatrix([[Ip, Z],[DI*C, Iq]]) return U, D, L else: raise ShapeError("Block UDL decomposition is supported only for 2x2 block matrices") def LUdecomposition(self): """Returns the Block LU decomposition of a 2x2 Block Matrix Returns ======= (L, U) : Matrices L : Lower Diagonal Matrix U : Upper Diagonal Matrix Examples ======== >>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse >>> m, n = symbols('m n') >>> A = MatrixSymbol('A', n, n) >>> B = MatrixSymbol('B', n, m) >>> C = MatrixSymbol('C', m, n) >>> D = MatrixSymbol('D', m, m) >>> X = BlockMatrix([[A, B], [C, D]]) >>> L, U = X.LUdecomposition() >>> block_collapse(L*U) Matrix([ [A, B], [C, D]]) Raises ====== ShapeError If the block matrix is not a 2x2 matrix NonInvertibleMatrixError If the matrix "A" is non-invertible See Also ======== sympy.matrices.expressions.blockmatrix.BlockMatrix.UDLdecomposition sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition """ if self.blockshape == (2,2): [[A, B], [C, D]] = self.blocks.tolist() try: A = A**0.5 AI = A.I except NonInvertibleMatrixError: raise NonInvertibleMatrixError('Block LU decomposition cannot be calculated when\ "A" is singular') Z = ZeroMatrix(*B.shape) Q = self.schur()**0.5 L = BlockMatrix([[A, Z], [C*AI, Q]]) U = BlockMatrix([[A, AI*B],[Z.T, Q]]) return L, U else: raise ShapeError("Block LU decomposition is supported only for 2x2 block matrices") def _entry(self, i, j, **kwargs): # Find row entry orig_i, orig_j = i, j for row_block, numrows in enumerate(self.rowblocksizes): cmp = i < numrows if cmp == True: break elif cmp == False: i -= numrows elif row_block < self.blockshape[0] - 1: # Can't tell which block and it's not the last one, return unevaluated return MatrixElement(self, orig_i, orig_j) for col_block, numcols in enumerate(self.colblocksizes): cmp = j < numcols if cmp == True: break elif cmp == False: j -= numcols elif col_block < self.blockshape[1] - 1: return MatrixElement(self, orig_i, orig_j) return self.blocks[row_block, col_block][i, j] @property def is_Identity(self): if self.blockshape[0] != self.blockshape[1]: return False for i in range(self.blockshape[0]): for j in range(self.blockshape[1]): if i==j and not self.blocks[i, j].is_Identity: return False if i!=j and not self.blocks[i, j].is_ZeroMatrix: return False return True @property def is_structurally_symmetric(self): return self.rowblocksizes == self.colblocksizes def equals(self, other): if self == other: return True if (isinstance(other, BlockMatrix) and self.blocks == other.blocks): return True return super().equals(other) class BlockDiagMatrix(BlockMatrix): """A sparse matrix with block matrices along its diagonals Examples ======== >>> from sympy import MatrixSymbol, BlockDiagMatrix, symbols >>> n, m, l = symbols('n m l') >>> X = MatrixSymbol('X', n, n) >>> Y = MatrixSymbol('Y', m ,m) >>> BlockDiagMatrix(X, Y) Matrix([ [X, 0], [0, Y]]) Notes ===== If you want to get the individual diagonal blocks, use :meth:`get_diag_blocks`. See Also ======== sympy.matrices.dense.diag """ def __new__(cls, *mats): return Basic.__new__(BlockDiagMatrix, *[_sympify(m) for m in mats]) @property def diag(self): return self.args @property def blocks(self): from sympy.matrices.immutable import ImmutableDenseMatrix mats = self.args data = [[mats[i] if i == j else ZeroMatrix(mats[i].rows, mats[j].cols) for j in range(len(mats))] for i in range(len(mats))] return ImmutableDenseMatrix(data, evaluate=False) @property def shape(self): return (sum(block.rows for block in self.args), sum(block.cols for block in self.args)) @property def blockshape(self): n = len(self.args) return (n, n) @property def rowblocksizes(self): return [block.rows for block in self.args] @property def colblocksizes(self): return [block.cols for block in self.args] def _all_square_blocks(self): """Returns true if all blocks are square""" return all(mat.is_square for mat in self.args) def _eval_determinant(self): if self._all_square_blocks(): return Mul(*[det(mat) for mat in self.args]) # At least one block is non-square. Since the entire matrix must be square we know there must # be at least two blocks in this matrix, in which case the entire matrix is necessarily rank-deficient return S.Zero def _eval_inverse(self, expand='ignored'): if self._all_square_blocks(): return BlockDiagMatrix(*[mat.inverse() for mat in self.args]) # See comment in _eval_determinant() raise NonInvertibleMatrixError('Matrix det == 0; not invertible.') def _eval_transpose(self): return BlockDiagMatrix(*[mat.transpose() for mat in self.args]) def _blockmul(self, other): if (isinstance(other, BlockDiagMatrix) and self.colblocksizes == other.rowblocksizes): return BlockDiagMatrix(*[a*b for a, b in zip(self.args, other.args)]) else: return BlockMatrix._blockmul(self, other) def _blockadd(self, other): if (isinstance(other, BlockDiagMatrix) and self.blockshape == other.blockshape and self.rowblocksizes == other.rowblocksizes and self.colblocksizes == other.colblocksizes): return BlockDiagMatrix(*[a + b for a, b in zip(self.args, other.args)]) else: return BlockMatrix._blockadd(self, other) def get_diag_blocks(self): """Return the list of diagonal blocks of the matrix. Examples ======== >>> from sympy.matrices import BlockDiagMatrix, Matrix >>> A = Matrix([[1, 2], [3, 4]]) >>> B = Matrix([[5, 6], [7, 8]]) >>> M = BlockDiagMatrix(A, B) How to get diagonal blocks from the block diagonal matrix: >>> diag_blocks = M.get_diag_blocks() >>> diag_blocks[0] Matrix([ [1, 2], [3, 4]]) >>> diag_blocks[1] Matrix([ [5, 6], [7, 8]]) """ return self.args def block_collapse(expr): """Evaluates a block matrix expression >>> from sympy import MatrixSymbol, BlockMatrix, symbols, \ Identity, ZeroMatrix, block_collapse >>> n,m,l = symbols('n m l') >>> X = MatrixSymbol('X', n, n) >>> Y = MatrixSymbol('Y', m ,m) >>> Z = MatrixSymbol('Z', n, m) >>> B = BlockMatrix([[X, Z], [ZeroMatrix(m, n), Y]]) >>> print(B) Matrix([ [X, Z], [0, Y]]) >>> C = BlockMatrix([[Identity(n), Z]]) >>> print(C) Matrix([[I, Z]]) >>> print(block_collapse(C*B)) Matrix([[X, Z + Z*Y]]) """ from sympy.strategies.util import expr_fns hasbm = lambda expr: isinstance(expr, MatrixExpr) and expr.has(BlockMatrix) conditioned_rl = condition( hasbm, typed( {MatAdd: do_one(bc_matadd, bc_block_plus_ident), MatMul: do_one(bc_matmul, bc_dist), MatPow: bc_matmul, Transpose: bc_transpose, Inverse: bc_inverse, BlockMatrix: do_one(bc_unpack, deblock)} ) ) rule = exhaust( bottom_up( exhaust(conditioned_rl), fns=expr_fns ) ) result = rule(expr) doit = getattr(result, 'doit', None) if doit is not None: return doit() else: return result def bc_unpack(expr): if expr.blockshape == (1, 1): return expr.blocks[0, 0] return expr def bc_matadd(expr): args = sift(expr.args, lambda M: isinstance(M, BlockMatrix)) blocks = args[True] if not blocks: return expr nonblocks = args[False] block = blocks[0] for b in blocks[1:]: block = block._blockadd(b) if nonblocks: return MatAdd(*nonblocks) + block else: return block def bc_block_plus_ident(expr): idents = [arg for arg in expr.args if arg.is_Identity] if not idents: return expr blocks = [arg for arg in expr.args if isinstance(arg, BlockMatrix)] if (blocks and all(b.structurally_equal(blocks[0]) for b in blocks) and blocks[0].is_structurally_symmetric): block_id = BlockDiagMatrix(*[Identity(k) for k in blocks[0].rowblocksizes]) rest = [arg for arg in expr.args if not arg.is_Identity and not isinstance(arg, BlockMatrix)] return MatAdd(block_id * len(idents), *blocks, *rest).doit() return expr def bc_dist(expr): """ Turn a*[X, Y] into [a*X, a*Y] """ factor, mat = expr.as_coeff_mmul() if factor == 1: return expr unpacked = unpack(mat) if isinstance(unpacked, BlockDiagMatrix): B = unpacked.diag new_B = [factor * mat for mat in B] return BlockDiagMatrix(*new_B) elif isinstance(unpacked, BlockMatrix): B = unpacked.blocks new_B = [ [factor * B[i, j] for j in range(B.cols)] for i in range(B.rows)] return BlockMatrix(new_B) return unpacked def bc_matmul(expr): if isinstance(expr, MatPow): if expr.args[1].is_Integer: factor, matrices = (1, [expr.args[0]]*expr.args[1]) else: return expr else: factor, matrices = expr.as_coeff_matrices() i = 0 while (i+1 < len(matrices)): A, B = matrices[i:i+2] if isinstance(A, BlockMatrix) and isinstance(B, BlockMatrix): matrices[i] = A._blockmul(B) matrices.pop(i+1) elif isinstance(A, BlockMatrix): matrices[i] = A._blockmul(BlockMatrix([[B]])) matrices.pop(i+1) elif isinstance(B, BlockMatrix): matrices[i] = BlockMatrix([[A]])._blockmul(B) matrices.pop(i+1) else: i+=1 return MatMul(factor, *matrices).doit() def bc_transpose(expr): collapse = block_collapse(expr.arg) return collapse._eval_transpose() def bc_inverse(expr): if isinstance(expr.arg, BlockDiagMatrix): return expr.inverse() expr2 = blockinverse_1x1(expr) if expr != expr2: return expr2 return blockinverse_2x2(Inverse(reblock_2x2(expr.arg))) def blockinverse_1x1(expr): if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (1, 1): mat = Matrix([[expr.arg.blocks[0].inverse()]]) return BlockMatrix(mat) return expr def blockinverse_2x2(expr): if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (2, 2): # See: Inverses of 2x2 Block Matrices, Tzon-Tzer Lu and Sheng-Hua Shiou [[A, B], [C, D]] = expr.arg.blocks.tolist() formula = _choose_2x2_inversion_formula(A, B, C, D) if formula != None: MI = expr.arg.schur(formula).I if formula == 'A': AI = A.I return BlockMatrix([[AI + AI * B * MI * C * AI, -AI * B * MI], [-MI * C * AI, MI]]) if formula == 'B': BI = B.I return BlockMatrix([[-MI * D * BI, MI], [BI + BI * A * MI * D * BI, -BI * A * MI]]) if formula == 'C': CI = C.I return BlockMatrix([[-CI * D * MI, CI + CI * D * MI * A * CI], [MI, -MI * A * CI]]) if formula == 'D': DI = D.I return BlockMatrix([[MI, -MI * B * DI], [-DI * C * MI, DI + DI * C * MI * B * DI]]) return expr def _choose_2x2_inversion_formula(A, B, C, D): """ Assuming [[A, B], [C, D]] would form a valid square block matrix, find which of the classical 2x2 block matrix inversion formulas would be best suited. Returns 'A', 'B', 'C', 'D' to represent the algorithm involving inversion of the given argument or None if the matrix cannot be inverted using any of those formulas. """ # Try to find a known invertible matrix. Note that the Schur complement # is currently not being considered for this A_inv = ask(Q.invertible(A)) if A_inv == True: return 'A' B_inv = ask(Q.invertible(B)) if B_inv == True: return 'B' C_inv = ask(Q.invertible(C)) if C_inv == True: return 'C' D_inv = ask(Q.invertible(D)) if D_inv == True: return 'D' # Otherwise try to find a matrix that isn't known to be non-invertible if A_inv != False: return 'A' if B_inv != False: return 'B' if C_inv != False: return 'C' if D_inv != False: return 'D' return None def deblock(B): """ Flatten a BlockMatrix of BlockMatrices """ if not isinstance(B, BlockMatrix) or not B.blocks.has(BlockMatrix): return B wrap = lambda x: x if isinstance(x, BlockMatrix) else BlockMatrix([[x]]) bb = B.blocks.applyfunc(wrap) # everything is a block from sympy import Matrix try: MM = Matrix(0, sum(bb[0, i].blocks.shape[1] for i in range(bb.shape[1])), []) for row in range(0, bb.shape[0]): M = Matrix(bb[row, 0].blocks) for col in range(1, bb.shape[1]): M = M.row_join(bb[row, col].blocks) MM = MM.col_join(M) return BlockMatrix(MM) except ShapeError: return B def reblock_2x2(expr): """ Reblock a BlockMatrix so that it has 2x2 blocks of block matrices. If possible in such a way that the matrix continues to be invertible using the classical 2x2 block inversion formulas. """ if not isinstance(expr, BlockMatrix) or not all(d > 2 for d in expr.blockshape): return expr BM = BlockMatrix # for brevity's sake rowblocks, colblocks = expr.blockshape blocks = expr.blocks for i in range(1, rowblocks): for j in range(1, colblocks): # try to split rows at i and cols at j A = bc_unpack(BM(blocks[:i, :j])) B = bc_unpack(BM(blocks[:i, j:])) C = bc_unpack(BM(blocks[i:, :j])) D = bc_unpack(BM(blocks[i:, j:])) formula = _choose_2x2_inversion_formula(A, B, C, D) if formula is not None: return BlockMatrix([[A, B], [C, D]]) # else: nothing worked, just split upper left corner return BM([[blocks[0, 0], BM(blocks[0, 1:])], [BM(blocks[1:, 0]), BM(blocks[1:, 1:])]]) def bounds(sizes): """ Convert sequence of numbers into pairs of low-high pairs >>> from sympy.matrices.expressions.blockmatrix import bounds >>> bounds((1, 10, 50)) [(0, 1), (1, 11), (11, 61)] """ low = 0 rv = [] for size in sizes: rv.append((low, low + size)) low += size return rv def blockcut(expr, rowsizes, colsizes): """ Cut a matrix expression into Blocks >>> from sympy import ImmutableMatrix, blockcut >>> M = ImmutableMatrix(4, 4, range(16)) >>> B = blockcut(M, (1, 3), (1, 3)) >>> type(B).__name__ 'BlockMatrix' >>> ImmutableMatrix(B.blocks[0, 1]) Matrix([[1, 2, 3]]) """ rowbounds = bounds(rowsizes) colbounds = bounds(colsizes) return BlockMatrix([[MatrixSlice(expr, rowbound, colbound) for colbound in colbounds] for rowbound in rowbounds])
ab689abe17f2a124468ffde5351b86ce8a2dd7fa5b8cd8eb9bfe4e8e48c1f288
from functools import reduce import operator from sympy.core import Add, Basic, sympify from sympy.core.add import add from sympy.functions import adjoint from sympy.matrices.common import ShapeError from sympy.matrices.matrices import MatrixBase from sympy.matrices.expressions.transpose import transpose from sympy.strategies import (rm_id, unpack, flatten, sort, condition, exhaust, do_one, glom) from sympy.matrices.expressions.matexpr import MatrixExpr from sympy.matrices.expressions.special import ZeroMatrix, GenericZeroMatrix from sympy.utilities import default_sort_key, sift # XXX: MatAdd should perhaps not subclass directly from Add class MatAdd(MatrixExpr, Add): """A Sum of Matrix Expressions MatAdd inherits from and operates like SymPy Add Examples ======== >>> from sympy import MatAdd, MatrixSymbol >>> A = MatrixSymbol('A', 5, 5) >>> B = MatrixSymbol('B', 5, 5) >>> C = MatrixSymbol('C', 5, 5) >>> MatAdd(A, B, C) A + B + C """ is_MatAdd = True identity = GenericZeroMatrix() def __new__(cls, *args, evaluate=False, check=False, _sympify=True): if not args: return cls.identity # This must be removed aggressively in the constructor to avoid # TypeErrors from GenericZeroMatrix().shape args = list(filter(lambda i: cls.identity != i, args)) if _sympify: args = list(map(sympify, args)) obj = Basic.__new__(cls, *args) if check: if all(not isinstance(i, MatrixExpr) for i in args): return Add.fromiter(args) validate(*args) if evaluate: if all(not isinstance(i, MatrixExpr) for i in args): return Add(*args, evaluate=True) obj = canonicalize(obj) return obj @property def shape(self): return self.args[0].shape def _entry(self, i, j, **kwargs): return Add(*[arg._entry(i, j, **kwargs) for arg in self.args]) def _eval_transpose(self): return MatAdd(*[transpose(arg) for arg in self.args]).doit() def _eval_adjoint(self): return MatAdd(*[adjoint(arg) for arg in self.args]).doit() def _eval_trace(self): from .trace import trace return Add(*[trace(arg) for arg in self.args]).doit() 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 canonicalize(MatAdd(*args)) def _eval_derivative_matrix_lines(self, x): add_lines = [arg._eval_derivative_matrix_lines(x) for arg in self.args] return [j for i in add_lines for j in i] add.register_handlerclass((Add, MatAdd), MatAdd) def validate(*args): if not all(arg.is_Matrix for arg in args): raise TypeError("Mix of Matrix and Scalar symbols") A = args[0] for B in args[1:]: if A.shape != B.shape: raise ShapeError("Matrices %s and %s are not aligned"%(A, B)) factor_of = lambda arg: arg.as_coeff_mmul()[0] matrix_of = lambda arg: unpack(arg.as_coeff_mmul()[1]) def combine(cnt, mat): if cnt == 1: return mat else: return cnt * mat def merge_explicit(matadd): """ Merge explicit MatrixBase arguments Examples ======== >>> from sympy import MatrixSymbol, eye, Matrix, MatAdd, pprint >>> from sympy.matrices.expressions.matadd import merge_explicit >>> A = MatrixSymbol('A', 2, 2) >>> B = eye(2) >>> C = Matrix([[1, 2], [3, 4]]) >>> X = MatAdd(A, B, C) >>> pprint(X) [1 0] [1 2] A + [ ] + [ ] [0 1] [3 4] >>> pprint(merge_explicit(X)) [2 2] A + [ ] [3 5] """ groups = sift(matadd.args, lambda arg: isinstance(arg, MatrixBase)) if len(groups[True]) > 1: return MatAdd(*(groups[False] + [reduce(operator.add, groups[True])])) else: return matadd rules = (rm_id(lambda x: x == 0 or isinstance(x, ZeroMatrix)), unpack, flatten, glom(matrix_of, factor_of, combine), merge_explicit, sort(default_sort_key)) canonicalize = exhaust(condition(lambda x: isinstance(x, MatAdd), do_one(*rules)))
e0ea24a30388ac2e60c9183ff2e75e14f5d85d0c08c643211a54c58b2a445cfe
from sympy import Trace from sympy.testing.pytest import raises, slow from sympy.matrices.expressions.blockmatrix import ( block_collapse, bc_matmul, bc_block_plus_ident, BlockDiagMatrix, BlockMatrix, bc_dist, bc_matadd, bc_transpose, bc_inverse, blockcut, reblock_2x2, deblock) from sympy.matrices.expressions import (MatrixSymbol, Identity, Inverse, trace, Transpose, det, ZeroMatrix) from sympy.matrices.common import NonInvertibleMatrixError from sympy.matrices import ( Matrix, ImmutableMatrix, ImmutableSparseMatrix) from sympy.core import Tuple, symbols, Expr from sympy.functions import transpose i, j, k, l, m, n, p = symbols('i:n, p', integer=True) A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, n) C = MatrixSymbol('C', n, n) D = MatrixSymbol('D', n, n) G = MatrixSymbol('G', n, n) H = MatrixSymbol('H', n, n) b1 = BlockMatrix([[G, H]]) b2 = BlockMatrix([[G], [H]]) def test_bc_matmul(): assert bc_matmul(H*b1*b2*G) == BlockMatrix([[(H*G*G + H*H*H)*G]]) def test_bc_matadd(): assert bc_matadd(BlockMatrix([[G, H]]) + BlockMatrix([[H, H]])) == \ BlockMatrix([[G+H, H+H]]) def test_bc_transpose(): assert bc_transpose(Transpose(BlockMatrix([[A, B], [C, D]]))) == \ BlockMatrix([[A.T, C.T], [B.T, D.T]]) def test_bc_dist_diag(): A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', m, m) C = MatrixSymbol('C', l, l) X = BlockDiagMatrix(A, B, C) assert bc_dist(X+X).equals(BlockDiagMatrix(2*A, 2*B, 2*C)) def test_block_plus_ident(): A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, m) C = MatrixSymbol('C', m, n) D = MatrixSymbol('D', m, m) X = BlockMatrix([[A, B], [C, D]]) Z = MatrixSymbol('Z', n + m, n + m) assert bc_block_plus_ident(X + Identity(m + n) + Z) == \ BlockDiagMatrix(Identity(n), Identity(m)) + X + Z def test_BlockMatrix(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', n, k) C = MatrixSymbol('C', l, m) D = MatrixSymbol('D', l, k) M = MatrixSymbol('M', m + k, p) N = MatrixSymbol('N', l + n, k + m) X = BlockMatrix(Matrix([[A, B], [C, D]])) assert X.__class__(*X.args) == X # block_collapse does nothing on normal inputs E = MatrixSymbol('E', n, m) assert block_collapse(A + 2*E) == A + 2*E F = MatrixSymbol('F', m, m) assert block_collapse(E.T*A*F) == E.T*A*F assert X.shape == (l + n, k + m) assert X.blockshape == (2, 2) assert transpose(X) == BlockMatrix(Matrix([[A.T, C.T], [B.T, D.T]])) assert transpose(X).shape == X.shape[::-1] # Test that BlockMatrices and MatrixSymbols can still mix assert (X*M).is_MatMul assert X._blockmul(M).is_MatMul assert (X*M).shape == (n + l, p) assert (X + N).is_MatAdd assert X._blockadd(N).is_MatAdd assert (X + N).shape == X.shape E = MatrixSymbol('E', m, 1) F = MatrixSymbol('F', k, 1) Y = BlockMatrix(Matrix([[E], [F]])) assert (X*Y).shape == (l + n, 1) assert block_collapse(X*Y).blocks[0, 0] == A*E + B*F assert block_collapse(X*Y).blocks[1, 0] == C*E + D*F # block_collapse passes down into container objects, transposes, and inverse assert block_collapse(transpose(X*Y)) == transpose(block_collapse(X*Y)) assert block_collapse(Tuple(X*Y, 2*X)) == ( block_collapse(X*Y), block_collapse(2*X)) # Make sure that MatrixSymbols will enter 1x1 BlockMatrix if it simplifies Ab = BlockMatrix([[A]]) Z = MatrixSymbol('Z', *A.shape) assert block_collapse(Ab + Z) == A + Z def test_block_collapse_explicit_matrices(): A = Matrix([[1, 2], [3, 4]]) assert block_collapse(BlockMatrix([[A]])) == A A = ImmutableSparseMatrix([[1, 2], [3, 4]]) assert block_collapse(BlockMatrix([[A]])) == A def test_issue_17624(): a = MatrixSymbol("a", 2, 2) z = ZeroMatrix(2, 2) b = BlockMatrix([[a, z], [z, z]]) assert block_collapse(b * b) == BlockMatrix([[a**2, z], [z, z]]) assert block_collapse(b * b * b) == BlockMatrix([[a**3, z], [z, z]]) def test_issue_18618(): A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert A == Matrix(BlockDiagMatrix(A)) def test_BlockMatrix_trace(): A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD'] X = BlockMatrix([[A, B], [C, D]]) assert trace(X) == trace(A) + trace(D) assert trace(BlockMatrix([ZeroMatrix(n, n)])) == 0 def test_BlockMatrix_Determinant(): A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD'] X = BlockMatrix([[A, B], [C, D]]) from sympy import assuming, Q with assuming(Q.invertible(A)): assert det(X) == det(A) * det(X.schur('A')) assert isinstance(det(X), Expr) assert det(BlockMatrix([A])) == det(A) assert det(BlockMatrix([ZeroMatrix(n, n)])) == 0 def test_squareBlockMatrix(): A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, m) C = MatrixSymbol('C', m, n) D = MatrixSymbol('D', m, m) X = BlockMatrix([[A, B], [C, D]]) Y = BlockMatrix([[A]]) assert X.is_square Q = X + Identity(m + n) assert (block_collapse(Q) == BlockMatrix([[A + Identity(n), B], [C, D + Identity(m)]])) assert (X + MatrixSymbol('Q', n + m, n + m)).is_MatAdd assert (X * MatrixSymbol('Q', n + m, n + m)).is_MatMul assert block_collapse(Y.I) == A.I assert isinstance(X.inverse(), Inverse) assert not X.is_Identity Z = BlockMatrix([[Identity(n), B], [C, D]]) assert not Z.is_Identity def test_BlockMatrix_2x2_inverse_symbolic(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', n, k - m) C = MatrixSymbol('C', k - n, m) D = MatrixSymbol('D', k - n, k - m) X = BlockMatrix([[A, B], [C, D]]) assert X.is_square and X.shape == (k, k) assert isinstance(block_collapse(X.I), Inverse) # Can't invert when none of the blocks is square # test code path where only A is invertible A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, m) C = MatrixSymbol('C', m, n) D = ZeroMatrix(m, m) X = BlockMatrix([[A, B], [C, D]]) assert block_collapse(X.inverse()) == BlockMatrix([ [A.I + A.I * B * X.schur('A').I * C * A.I, -A.I * B * X.schur('A').I], [-X.schur('A').I * C * A.I, X.schur('A').I], ]) # test code path where only B is invertible A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', n, n) C = ZeroMatrix(m, m) D = MatrixSymbol('D', m, n) X = BlockMatrix([[A, B], [C, D]]) assert block_collapse(X.inverse()) == BlockMatrix([ [-X.schur('B').I * D * B.I, X.schur('B').I], [B.I + B.I * A * X.schur('B').I * D * B.I, -B.I * A * X.schur('B').I], ]) # test code path where only C is invertible A = MatrixSymbol('A', n, m) B = ZeroMatrix(n, n) C = MatrixSymbol('C', m, m) D = MatrixSymbol('D', m, n) X = BlockMatrix([[A, B], [C, D]]) assert block_collapse(X.inverse()) == BlockMatrix([ [-C.I * D * X.schur('C').I, C.I + C.I * D * X.schur('C').I * A * C.I], [X.schur('C').I, -X.schur('C').I * A * C.I], ]) # test code path where only D is invertible A = ZeroMatrix(n, n) B = MatrixSymbol('B', n, m) C = MatrixSymbol('C', m, n) D = MatrixSymbol('D', m, m) X = BlockMatrix([[A, B], [C, D]]) assert block_collapse(X.inverse()) == BlockMatrix([ [X.schur('D').I, -X.schur('D').I * B * D.I], [-D.I * C * X.schur('D').I, D.I + D.I * C * X.schur('D').I * B * D.I], ]) def test_BlockMatrix_2x2_inverse_numeric(): """Test 2x2 block matrix inversion numerically for all 4 formulas""" M = Matrix([[1, 2], [3, 4]]) # rank deficient matrices that have full rank when two of them combined D1 = Matrix([[1, 2], [2, 4]]) D2 = Matrix([[1, 3], [3, 9]]) D3 = Matrix([[1, 4], [4, 16]]) assert D1.rank() == D2.rank() == D3.rank() == 1 assert (D1 + D2).rank() == (D2 + D3).rank() == (D3 + D1).rank() == 2 # Only A is invertible K = BlockMatrix([[M, D1], [D2, D3]]) assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv() # Only B is invertible K = BlockMatrix([[D1, M], [D2, D3]]) assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv() # Only C is invertible K = BlockMatrix([[D1, D2], [M, D3]]) assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv() # Only D is invertible K = BlockMatrix([[D1, D2], [D3, M]]) assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv() @slow def test_BlockMatrix_3x3_symbolic(): # Only test one of these, instead of all permutations, because it's slow rowblocksizes = (n, m, k) colblocksizes = (m, k, n) K = BlockMatrix([ [MatrixSymbol('M%s%s' % (rows, cols), rows, cols) for cols in colblocksizes] for rows in rowblocksizes ]) collapse = block_collapse(K.I) assert isinstance(collapse, BlockMatrix) def test_BlockDiagMatrix(): A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', m, m) C = MatrixSymbol('C', l, l) M = MatrixSymbol('M', n + m + l, n + m + l) X = BlockDiagMatrix(A, B, C) Y = BlockDiagMatrix(A, 2*B, 3*C) assert X.blocks[1, 1] == B assert X.shape == (n + m + l, n + m + l) assert all(X.blocks[i, j].is_ZeroMatrix if i != j else X.blocks[i, j] in [A, B, C] for i in range(3) for j in range(3)) assert X.__class__(*X.args) == X assert X.get_diag_blocks() == (A, B, C) assert isinstance(block_collapse(X.I * X), Identity) assert bc_matmul(X*X) == BlockDiagMatrix(A*A, B*B, C*C) assert block_collapse(X*X) == BlockDiagMatrix(A*A, B*B, C*C) #XXX: should be == ?? assert block_collapse(X + X).equals(BlockDiagMatrix(2*A, 2*B, 2*C)) assert block_collapse(X*Y) == BlockDiagMatrix(A*A, 2*B*B, 3*C*C) assert block_collapse(X + Y) == BlockDiagMatrix(2*A, 3*B, 4*C) # Ensure that BlockDiagMatrices can still interact with normal MatrixExprs assert (X*(2*M)).is_MatMul assert (X + (2*M)).is_MatAdd assert (X._blockmul(M)).is_MatMul assert (X._blockadd(M)).is_MatAdd def test_BlockDiagMatrix_nonsquare(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', k, l) X = BlockDiagMatrix(A, B) assert X.shape == (n + k, m + l) assert X.shape == (n + k, m + l) assert X.rowblocksizes == [n, k] assert X.colblocksizes == [m, l] C = MatrixSymbol('C', n, m) D = MatrixSymbol('D', k, l) Y = BlockDiagMatrix(C, D) assert block_collapse(X + Y) == BlockDiagMatrix(A + C, B + D) assert block_collapse(X * Y.T) == BlockDiagMatrix(A * C.T, B * D.T) raises(NonInvertibleMatrixError, lambda: BlockDiagMatrix(A, C.T).inverse()) def test_BlockDiagMatrix_determinant(): A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', m, m) assert det(BlockDiagMatrix()) == 1 assert det(BlockDiagMatrix(A)) == det(A) assert det(BlockDiagMatrix(A, B)) == det(A) * det(B) # non-square blocks C = MatrixSymbol('C', m, n) D = MatrixSymbol('D', n, m) assert det(BlockDiagMatrix(C, D)) == 0 def test_BlockDiagMatrix_trace(): assert trace(BlockDiagMatrix()) == 0 assert trace(BlockDiagMatrix(ZeroMatrix(n, n))) == 0 A = MatrixSymbol('A', n, n) assert trace(BlockDiagMatrix(A)) == trace(A) B = MatrixSymbol('B', m, m) assert trace(BlockDiagMatrix(A, B)) == trace(A) + trace(B) # non-square blocks C = MatrixSymbol('C', m, n) D = MatrixSymbol('D', n, m) assert isinstance(trace(BlockDiagMatrix(C, D)), Trace) def test_BlockDiagMatrix_transpose(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', k, l) assert transpose(BlockDiagMatrix()) == BlockDiagMatrix() assert transpose(BlockDiagMatrix(A)) == BlockDiagMatrix(A.T) assert transpose(BlockDiagMatrix(A, B)) == BlockDiagMatrix(A.T, B.T) def test_issue_2460(): bdm1 = BlockDiagMatrix(Matrix([i]), Matrix([j])) bdm2 = BlockDiagMatrix(Matrix([k]), Matrix([l])) assert block_collapse(bdm1 + bdm2) == BlockDiagMatrix(Matrix([i + k]), Matrix([j + l])) def test_blockcut(): A = MatrixSymbol('A', n, m) B = blockcut(A, (n/2, n/2), (m/2, m/2)) assert B == BlockMatrix([[A[:n/2, :m/2], A[:n/2, m/2:]], [A[n/2:, :m/2], A[n/2:, m/2:]]]) M = ImmutableMatrix(4, 4, range(16)) B = blockcut(M, (2, 2), (2, 2)) assert M == ImmutableMatrix(B) B = blockcut(M, (1, 3), (2, 2)) assert ImmutableMatrix(B.blocks[0, 1]) == ImmutableMatrix([[2, 3]]) def test_reblock_2x2(): B = BlockMatrix([[MatrixSymbol('A_%d%d'%(i,j), 2, 2) for j in range(3)] for i in range(3)]) assert B.blocks.shape == (3, 3) BB = reblock_2x2(B) assert BB.blocks.shape == (2, 2) assert B.shape == BB.shape assert B.as_explicit() == BB.as_explicit() def test_deblock(): B = BlockMatrix([[MatrixSymbol('A_%d%d'%(i,j), n, n) for j in range(4)] for i in range(4)]) assert deblock(reblock_2x2(B)) == B def test_block_collapse_type(): bm1 = BlockDiagMatrix(ImmutableMatrix([1]), ImmutableMatrix([2])) bm2 = BlockDiagMatrix(ImmutableMatrix([3]), ImmutableMatrix([4])) assert bm1.T.__class__ == BlockDiagMatrix assert block_collapse(bm1 - bm2).__class__ == BlockDiagMatrix assert block_collapse(Inverse(bm1)).__class__ == BlockDiagMatrix assert block_collapse(Transpose(bm1)).__class__ == BlockDiagMatrix assert bc_transpose(Transpose(bm1)).__class__ == BlockDiagMatrix assert bc_inverse(Inverse(bm1)).__class__ == BlockDiagMatrix def test_invalid_block_matrix(): raises(ValueError, lambda: BlockMatrix([ [Identity(2), Identity(5)], ])) raises(ValueError, lambda: BlockMatrix([ [Identity(n), Identity(m)], ])) raises(ValueError, lambda: BlockMatrix([ [ZeroMatrix(n, n), ZeroMatrix(n, n)], [ZeroMatrix(n, n - 1), ZeroMatrix(n, n + 1)], ])) raises(ValueError, lambda: BlockMatrix([ [ZeroMatrix(n - 1, n), ZeroMatrix(n, n)], [ZeroMatrix(n + 1, n), ZeroMatrix(n, n)], ])) def test_block_lu_decomposition(): A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, m) C = MatrixSymbol('C', m, n) D = MatrixSymbol('D', m, m) X = BlockMatrix([[A, B], [C, D]]) #LDU decomposition L, D, U = X.LDUdecomposition() assert block_collapse(L*D*U) == X #UDL decomposition U, D, L = X.UDLdecomposition() assert block_collapse(U*D*L) == X #LU decomposition L, U = X.LUdecomposition() assert block_collapse(L*U) == X
4a2e5fdcf931138feba86657074b48205e548827878314a65e6667c24894ab62
""" Some examples have been taken from: http://www.math.uwaterloo.ca/~hwolkowi//matrixcookbook.pdf """ from sympy import (MatrixSymbol, Inverse, symbols, Determinant, Trace, sin, exp, cos, tan, log, S, sqrt, hadamard_product, DiagMatrix, OneMatrix, HadamardProduct, HadamardPower, KroneckerDelta, Sum, Rational) from sympy import MatAdd, Identity, MatMul, ZeroMatrix from sympy.tensor.array.array_derivatives import ArrayDerivative from sympy.matrices.expressions import hadamard_power k = symbols("k") i, j = symbols("i j") m, n = symbols("m n") X = MatrixSymbol("X", k, k) x = MatrixSymbol("x", k, 1) y = MatrixSymbol("y", k, 1) A = MatrixSymbol("A", k, k) B = MatrixSymbol("B", k, k) C = MatrixSymbol("C", k, k) D = MatrixSymbol("D", k, k) a = MatrixSymbol("a", k, 1) b = MatrixSymbol("b", k, 1) c = MatrixSymbol("c", k, 1) d = MatrixSymbol("d", k, 1) KDelta = lambda i, j: KroneckerDelta(i, j, (0, k-1)) def _check_derivative_with_explicit_matrix(expr, x, diffexpr, dim=2): # TODO: this is commented because it slows down the tests. return expr = expr.xreplace({k: dim}) x = x.xreplace({k: dim}) diffexpr = diffexpr.xreplace({k: dim}) expr = expr.as_explicit() x = x.as_explicit() diffexpr = diffexpr.as_explicit() assert expr.diff(x).reshape(*diffexpr.shape).tomatrix() == diffexpr def test_matrix_derivative_by_scalar(): assert A.diff(i) == ZeroMatrix(k, k) assert (A*(X + B)*c).diff(i) == ZeroMatrix(k, 1) assert x.diff(i) == ZeroMatrix(k, 1) assert (x.T*y).diff(i) == ZeroMatrix(1, 1) assert (x*x.T).diff(i) == ZeroMatrix(k, k) assert (x + y).diff(i) == ZeroMatrix(k, 1) assert hadamard_power(x, 2).diff(i) == ZeroMatrix(k, 1) assert hadamard_power(x, i).diff(i).dummy_eq( HadamardProduct(x.applyfunc(log), HadamardPower(x, i))) assert hadamard_product(x, y).diff(i) == ZeroMatrix(k, 1) assert hadamard_product(i*OneMatrix(k, 1), x, y).diff(i) == hadamard_product(x, y) assert (i*x).diff(i) == x assert (sin(i)*A*B*x).diff(i) == cos(i)*A*B*x assert x.applyfunc(sin).diff(i) == ZeroMatrix(k, 1) assert Trace(i**2*X).diff(i) == 2*i*Trace(X) mu = symbols("mu") expr = (2*mu*x) assert expr.diff(x) == 2*mu*Identity(k) def test_matrix_derivative_non_matrix_result(): # This is a 4-dimensional array: assert A.diff(A) == ArrayDerivative(A, A) assert A.T.diff(A) == ArrayDerivative(A.T, A) assert (2*A).diff(A) == ArrayDerivative(2*A, A) assert MatAdd(A, A).diff(A) == ArrayDerivative(MatAdd(A, A), A) assert (A + B).diff(A) == ArrayDerivative(A + B, A) # TODO: `B` can be removed. def test_matrix_derivative_trivial_cases(): # Cookbook example 33: # TODO: find a way to represent a four-dimensional zero-array: assert X.diff(A) == ArrayDerivative(X, A) def test_matrix_derivative_with_inverse(): # Cookbook example 61: expr = a.T*Inverse(X)*b assert expr.diff(X) == -Inverse(X).T*a*b.T*Inverse(X).T # Cookbook example 62: expr = Determinant(Inverse(X)) # Not implemented yet: # assert expr.diff(X) == -Determinant(X.inv())*(X.inv()).T # Cookbook example 63: expr = Trace(A*Inverse(X)*B) assert expr.diff(X) == -(X**(-1)*B*A*X**(-1)).T # Cookbook example 64: expr = Trace(Inverse(X + A)) assert expr.diff(X) == -(Inverse(X + A)).T**2 def test_matrix_derivative_vectors_and_scalars(): assert x.diff(x) == Identity(k) assert x[i, 0].diff(x[m, 0]).doit() == KDelta(m, i) assert x.T.diff(x) == Identity(k) # Cookbook example 69: expr = x.T*a assert expr.diff(x) == a assert expr[0, 0].diff(x[m, 0]).doit() == a[m, 0] expr = a.T*x assert expr.diff(x) == a # Cookbook example 70: expr = a.T*X*b assert expr.diff(X) == a*b.T # Cookbook example 71: expr = a.T*X.T*b assert expr.diff(X) == b*a.T # Cookbook example 72: expr = a.T*X*a assert expr.diff(X) == a*a.T expr = a.T*X.T*a assert expr.diff(X) == a*a.T # Cookbook example 77: expr = b.T*X.T*X*c assert expr.diff(X) == X*b*c.T + X*c*b.T # Cookbook example 78: expr = (B*x + b).T*C*(D*x + d) assert expr.diff(x) == B.T*C*(D*x + d) + D.T*C.T*(B*x + b) # Cookbook example 81: expr = x.T*B*x assert expr.diff(x) == B*x + B.T*x # Cookbook example 82: expr = b.T*X.T*D*X*c assert expr.diff(X) == D.T*X*b*c.T + D*X*c*b.T # Cookbook example 83: expr = (X*b + c).T*D*(X*b + c) assert expr.diff(X) == D*(X*b + c)*b.T + D.T*(X*b + c)*b.T assert str(expr[0, 0].diff(X[m, n]).doit()) == \ 'b[n, 0]*Sum((c[_i_1, 0] + Sum(X[_i_1, _i_3]*b[_i_3, 0], (_i_3, 0, k - 1)))*D[_i_1, m], (_i_1, 0, k - 1)) + Sum((c[_i_2, 0] + Sum(X[_i_2, _i_4]*b[_i_4, 0], (_i_4, 0, k - 1)))*D[m, _i_2]*b[n, 0], (_i_2, 0, k - 1))' def test_matrix_derivatives_of_traces(): expr = Trace(A)*A assert expr.diff(A) == ArrayDerivative(Trace(A)*A, A) assert expr[i, j].diff(A[m, n]).doit() == ( KDelta(i, m)*KDelta(j, n)*Trace(A) + KDelta(m, n)*A[i, j] ) ## First order: # Cookbook example 99: expr = Trace(X) assert expr.diff(X) == Identity(k) assert expr.rewrite(Sum).diff(X[m, n]).doit() == KDelta(m, n) # Cookbook example 100: expr = Trace(X*A) assert expr.diff(X) == A.T assert expr.rewrite(Sum).diff(X[m, n]).doit() == A[n, m] # Cookbook example 101: expr = Trace(A*X*B) assert expr.diff(X) == A.T*B.T assert expr.rewrite(Sum).diff(X[m, n]).doit().dummy_eq((A.T*B.T)[m, n]) # Cookbook example 102: expr = Trace(A*X.T*B) assert expr.diff(X) == B*A # Cookbook example 103: expr = Trace(X.T*A) assert expr.diff(X) == A # Cookbook example 104: expr = Trace(A*X.T) assert expr.diff(X) == A # Cookbook example 105: # TODO: TensorProduct is not supported #expr = Trace(TensorProduct(A, X)) #assert expr.diff(X) == Trace(A)*Identity(k) ## Second order: # Cookbook example 106: expr = Trace(X**2) assert expr.diff(X) == 2*X.T # Cookbook example 107: expr = Trace(X**2*B) assert expr.diff(X) == (X*B + B*X).T expr = Trace(MatMul(X, X, B)) assert expr.diff(X) == (X*B + B*X).T # Cookbook example 108: expr = Trace(X.T*B*X) assert expr.diff(X) == B*X + B.T*X # Cookbook example 109: expr = Trace(B*X*X.T) assert expr.diff(X) == B*X + B.T*X # Cookbook example 110: expr = Trace(X*X.T*B) assert expr.diff(X) == B*X + B.T*X # Cookbook example 111: expr = Trace(X*B*X.T) assert expr.diff(X) == X*B.T + X*B # Cookbook example 112: expr = Trace(B*X.T*X) assert expr.diff(X) == X*B.T + X*B # Cookbook example 113: expr = Trace(X.T*X*B) assert expr.diff(X) == X*B.T + X*B # Cookbook example 114: expr = Trace(A*X*B*X) assert expr.diff(X) == A.T*X.T*B.T + B.T*X.T*A.T # Cookbook example 115: expr = Trace(X.T*X) assert expr.diff(X) == 2*X expr = Trace(X*X.T) assert expr.diff(X) == 2*X # Cookbook example 116: expr = Trace(B.T*X.T*C*X*B) assert expr.diff(X) == C.T*X*B*B.T + C*X*B*B.T # Cookbook example 117: expr = Trace(X.T*B*X*C) assert expr.diff(X) == B*X*C + B.T*X*C.T # Cookbook example 118: expr = Trace(A*X*B*X.T*C) assert expr.diff(X) == A.T*C.T*X*B.T + C*A*X*B # Cookbook example 119: expr = Trace((A*X*B + C)*(A*X*B + C).T) assert expr.diff(X) == 2*A.T*(A*X*B + C)*B.T # Cookbook example 120: # TODO: no support for TensorProduct. # expr = Trace(TensorProduct(X, X)) # expr = Trace(X)*Trace(X) # expr.diff(X) == 2*Trace(X)*Identity(k) # Higher Order # Cookbook example 121: expr = Trace(X**k) #assert expr.diff(X) == k*(X**(k-1)).T # Cookbook example 122: expr = Trace(A*X**k) #assert expr.diff(X) == # Needs indices # Cookbook example 123: expr = Trace(B.T*X.T*C*X*X.T*C*X*B) assert expr.diff(X) == C*X*X.T*C*X*B*B.T + C.T*X*B*B.T*X.T*C.T*X + C*X*B*B.T*X.T*C*X + C.T*X*X.T*C.T*X*B*B.T # Other # Cookbook example 124: expr = Trace(A*X**(-1)*B) assert expr.diff(X) == -Inverse(X).T*A.T*B.T*Inverse(X).T # Cookbook example 125: expr = Trace(Inverse(X.T*C*X)*A) # Warning: result in the cookbook is equivalent if B and C are symmetric: assert expr.diff(X) == - X.inv().T*A.T*X.inv()*C.inv().T*X.inv().T - X.inv().T*A*X.inv()*C.inv()*X.inv().T # Cookbook example 126: expr = Trace((X.T*C*X).inv()*(X.T*B*X)) assert expr.diff(X) == -2*C*X*(X.T*C*X).inv()*X.T*B*X*(X.T*C*X).inv() + 2*B*X*(X.T*C*X).inv() # Cookbook example 127: expr = Trace((A + X.T*C*X).inv()*(X.T*B*X)) # Warning: result in the cookbook is equivalent if B and C are symmetric: assert expr.diff(X) == B*X*Inverse(A + X.T*C*X) - C*X*Inverse(A + X.T*C*X)*X.T*B*X*Inverse(A + X.T*C*X) - C.T*X*Inverse(A.T + (C*X).T*X)*X.T*B.T*X*Inverse(A.T + (C*X).T*X) + B.T*X*Inverse(A.T + (C*X).T*X) def test_derivatives_of_complicated_matrix_expr(): expr = a.T*(A*X*(X.T*B + X*A) + B.T*X.T*(a*b.T*(X*D*X.T + X*(X.T*B + A*X)*D*B - X.T*C.T*A)*B + B*(X*D.T + B*A*X*A.T - 3*X*D))*B + 42*X*B*X.T*A.T*(X + X.T))*b result = (B*(B*A*X*A.T - 3*X*D + X*D.T) + a*b.T*(X*(A*X + X.T*B)*D*B + X*D*X.T - X.T*C.T*A)*B)*B*b*a.T*B.T + B**2*b*a.T*B.T*X.T*a*b.T*X*D + 42*A*X*B.T*X.T*a*b.T + B*D*B**3*b*a.T*B.T*X.T*a*b.T*X + B*b*a.T*A*X + 42*a*b.T*(X + X.T)*A*X*B.T + b*a.T*X*B*a*b.T*B.T**2*X*D.T + b*a.T*X*B*a*b.T*B.T**3*D.T*(B.T*X + X.T*A.T) + 42*b*a.T*X*B*X.T*A.T + 42*A.T*(X + X.T)*b*a.T*X*B + A.T*B.T**2*X*B*a*b.T*B.T*A + A.T*a*b.T*(A.T*X.T + B.T*X) + A.T*X.T*b*a.T*X*B*a*b.T*B.T**3*D.T + B.T*X*B*a*b.T*B.T*D - 3*B.T*X*B*a*b.T*B.T*D.T - C.T*A*B**2*b*a.T*B.T*X.T*a*b.T + X.T*A.T*a*b.T*A.T assert expr.diff(X) == result def test_mixed_deriv_mixed_expressions(): expr = 3*Trace(A) assert expr.diff(A) == 3*Identity(k) expr = k deriv = expr.diff(A) assert isinstance(deriv, ZeroMatrix) assert deriv == ZeroMatrix(k, k) expr = Trace(A)**2 assert expr.diff(A) == (2*Trace(A))*Identity(k) expr = Trace(A)*A # TODO: this is not yet supported: assert expr.diff(A) == ArrayDerivative(expr, A) expr = Trace(Trace(A)*A) assert expr.diff(A) == (2*Trace(A))*Identity(k) expr = Trace(Trace(Trace(A)*A)*A) assert expr.diff(A) == (3*Trace(A)**2)*Identity(k) def test_derivatives_matrix_norms(): expr = x.T*y assert expr.diff(x) == y assert expr[0, 0].diff(x[m, 0]).doit() == y[m, 0] expr = (x.T*y)**S.Half assert expr.diff(x) == y/(2*sqrt(x.T*y)) expr = (x.T*x)**S.Half assert expr.diff(x) == x*(x.T*x)**Rational(-1, 2) expr = (c.T*a*x.T*b)**S.Half assert expr.diff(x) == b/(2*sqrt(c.T*a*x.T*b))*c.T*a expr = (c.T*a*x.T*b)**Rational(1, 3) assert expr.diff(x) == b*(c.T*a*x.T*b)**Rational(-2, 3)*c.T*a/3 expr = (a.T*X*b)**S.Half assert expr.diff(X) == a/(2*sqrt(a.T*X*b))*b.T expr = d.T*x*(a.T*X*b)**S.Half*y.T*c assert expr.diff(X) == a*d.T*x/(2*sqrt(a.T*X*b))*y.T*c*b.T def test_derivatives_elementwise_applyfunc(): from sympy.matrices.expressions.diagonal import DiagMatrix expr = x.applyfunc(tan) assert expr.diff(x).dummy_eq( DiagMatrix(x.applyfunc(lambda x: tan(x)**2 + 1))) assert expr[i, 0].diff(x[m, 0]).doit() == (tan(x[i, 0])**2 + 1)*KDelta(i, m) _check_derivative_with_explicit_matrix(expr, x, expr.diff(x)) expr = (i**2*x).applyfunc(sin) assert expr.diff(i).dummy_eq( HadamardProduct((2*i)*x, (i**2*x).applyfunc(cos))) assert expr[i, 0].diff(i).doit() == 2*i*x[i, 0]*cos(i**2*x[i, 0]) _check_derivative_with_explicit_matrix(expr, i, expr.diff(i)) expr = (log(i)*A*B).applyfunc(sin) assert expr.diff(i).dummy_eq( HadamardProduct(A*B/i, (log(i)*A*B).applyfunc(cos))) _check_derivative_with_explicit_matrix(expr, i, expr.diff(i)) expr = A*x.applyfunc(exp) assert expr.diff(x).dummy_eq(DiagMatrix(x.applyfunc(exp))*A.T) _check_derivative_with_explicit_matrix(expr, x, expr.diff(x)) expr = x.T*A*x + k*y.applyfunc(sin).T*x assert expr.diff(x).dummy_eq(A.T*x + A*x + k*y.applyfunc(sin)) _check_derivative_with_explicit_matrix(expr, x, expr.diff(x)) expr = x.applyfunc(sin).T*y assert expr.diff(x).dummy_eq(DiagMatrix(x.applyfunc(cos))*y) _check_derivative_with_explicit_matrix(expr, x, expr.diff(x)) expr = (a.T * X * b).applyfunc(sin) assert expr.diff(X).dummy_eq(a*(a.T*X*b).applyfunc(cos)*b.T) _check_derivative_with_explicit_matrix(expr, X, expr.diff(X)) expr = a.T * X.applyfunc(sin) * b assert expr.diff(X).dummy_eq( DiagMatrix(a)*X.applyfunc(cos)*DiagMatrix(b)) _check_derivative_with_explicit_matrix(expr, X, expr.diff(X)) expr = a.T * (A*X*B).applyfunc(sin) * b assert expr.diff(X).dummy_eq( A.T*DiagMatrix(a)*(A*X*B).applyfunc(cos)*DiagMatrix(b)*B.T) _check_derivative_with_explicit_matrix(expr, X, expr.diff(X)) expr = a.T * (A*X*b).applyfunc(sin) * b.T # TODO: not implemented #assert expr.diff(X) == ... #_check_derivative_with_explicit_matrix(expr, X, expr.diff(X)) expr = a.T*A*X.applyfunc(sin)*B*b assert expr.diff(X).dummy_eq( DiagMatrix(A.T*a)*X.applyfunc(cos)*DiagMatrix(B*b)) expr = a.T * (A*X.applyfunc(sin)*B).applyfunc(log) * b # TODO: wrong # assert expr.diff(X) == A.T*DiagMatrix(a)*(A*X.applyfunc(sin)*B).applyfunc(Lambda(k, 1/k))*DiagMatrix(b)*B.T expr = a.T * (X.applyfunc(sin)).applyfunc(log) * b # TODO: wrong # assert expr.diff(X) == DiagMatrix(a)*X.applyfunc(sin).applyfunc(Lambda(k, 1/k))*DiagMatrix(b) def test_derivatives_of_hadamard_expressions(): # Hadamard Product expr = hadamard_product(a, x, b) assert expr.diff(x) == DiagMatrix(hadamard_product(b, a)) expr = a.T*hadamard_product(A, X, B)*b assert expr.diff(X) == DiagMatrix(a)*hadamard_product(B, A)*DiagMatrix(b) # Hadamard Power expr = hadamard_power(x, 2) assert expr.diff(x).doit() == 2*DiagMatrix(x) expr = hadamard_power(x.T, 2) assert expr.diff(x).doit() == 2*DiagMatrix(x) expr = hadamard_power(x, S.Half) assert expr.diff(x) == S.Half*DiagMatrix(hadamard_power(x, Rational(-1, 2))) expr = hadamard_power(a.T*X*b, 2) assert expr.diff(X) == 2*a*a.T*X*b*b.T expr = hadamard_power(a.T*X*b, S.Half) assert expr.diff(X) == a/2*hadamard_power(a.T*X*b, Rational(-1, 2))*b.T
3daad1ccde675dfedc55c60f142a69064d169b25017243dc8fcfa727b3cf086d
from sympy.core.expr import unchanged from sympy.sets.fancysets import (ImageSet, Range, normalize_theta_set, ComplexRegion) from sympy.sets.sets import (FiniteSet, Interval, imageset, Union, Intersection, ProductSet, Contains) from sympy.simplify.simplify import simplify from sympy import (S, Symbol, Lambda, symbols, cos, sin, pi, oo, Basic, Rational, sqrt, tan, log, exp, Abs, I, Tuple, eye, Dummy, floor, And, Eq) from sympy.utilities.iterables import cartes from sympy.testing.pytest import XFAIL, raises from sympy.abc import x, y, t import itertools def test_naturals(): N = S.Naturals assert 5 in N assert -5 not in N assert 5.5 not in N ni = iter(N) a, b, c, d = next(ni), next(ni), next(ni), next(ni) assert (a, b, c, d) == (1, 2, 3, 4) assert isinstance(a, Basic) assert N.intersect(Interval(-5, 5)) == Range(1, 6) assert N.intersect(Interval(-5, 5, True, True)) == Range(1, 5) assert N.boundary == N assert N.is_open == False assert N.is_closed == True assert N.inf == 1 assert N.sup is oo assert not N.contains(oo) for s in (S.Naturals0, S.Naturals): assert s.intersection(S.Reals) is s assert s.is_subset(S.Reals) assert N.as_relational(x) == And(Eq(floor(x), x), x >= 1, x < oo) def test_naturals0(): N = S.Naturals0 assert 0 in N assert -1 not in N assert next(iter(N)) == 0 assert not N.contains(oo) assert N.contains(sin(x)) == Contains(sin(x), N) def test_integers(): Z = S.Integers assert 5 in Z assert -5 in Z assert 5.5 not in Z assert not Z.contains(oo) assert not Z.contains(-oo) zi = iter(Z) a, b, c, d = next(zi), next(zi), next(zi), next(zi) assert (a, b, c, d) == (0, 1, -1, 2) assert isinstance(a, Basic) assert Z.intersect(Interval(-5, 5)) == Range(-5, 6) assert Z.intersect(Interval(-5, 5, True, True)) == Range(-4, 5) assert Z.intersect(Interval(5, S.Infinity)) == Range(5, S.Infinity) assert Z.intersect(Interval.Lopen(5, S.Infinity)) == Range(6, S.Infinity) assert Z.inf is -oo assert Z.sup is oo assert Z.boundary == Z assert Z.is_open == False assert Z.is_closed == True assert Z.as_relational(x) == And(Eq(floor(x), x), -oo < x, x < oo) def test_ImageSet(): raises(ValueError, lambda: ImageSet(x, S.Integers)) assert ImageSet(Lambda(x, 1), S.Integers) == FiniteSet(1) assert ImageSet(Lambda(x, y), S.Integers) == {y} assert ImageSet(Lambda(x, 1), S.EmptySet) == S.EmptySet empty = Intersection(FiniteSet(log(2)/pi), S.Integers) assert unchanged(ImageSet, Lambda(x, 1), empty) # issue #17471 squares = ImageSet(Lambda(x, x**2), S.Naturals) assert 4 in squares assert 5 not in squares assert FiniteSet(*range(10)).intersect(squares) == FiniteSet(1, 4, 9) assert 16 not in squares.intersect(Interval(0, 10)) si = iter(squares) a, b, c, d = next(si), next(si), next(si), next(si) assert (a, b, c, d) == (1, 4, 9, 16) harmonics = ImageSet(Lambda(x, 1/x), S.Naturals) assert Rational(1, 5) in harmonics assert Rational(.25) in harmonics assert 0.25 not in harmonics assert Rational(.3) not in harmonics assert (1, 2) not in harmonics assert harmonics.is_iterable assert imageset(x, -x, Interval(0, 1)) == Interval(-1, 0) assert ImageSet(Lambda(x, x**2), Interval(0, 2)).doit() == Interval(0, 4) assert ImageSet(Lambda((x, y), 2*x), {4}, {3}).doit() == FiniteSet(8) assert (ImageSet(Lambda((x, y), x+y), {1, 2, 3}, {10, 20, 30}).doit() == FiniteSet(11, 12, 13, 21, 22, 23, 31, 32, 33)) c = Interval(1, 3) * Interval(1, 3) assert Tuple(2, 6) in ImageSet(Lambda(((x, y),), (x, 2*y)), c) assert Tuple(2, S.Half) in ImageSet(Lambda(((x, y),), (x, 1/y)), c) assert Tuple(2, -2) not in ImageSet(Lambda(((x, y),), (x, y**2)), c) assert Tuple(2, -2) in ImageSet(Lambda(((x, y),), (x, -2)), c) c3 = ProductSet(Interval(3, 7), Interval(8, 11), Interval(5, 9)) assert Tuple(8, 3, 9) in ImageSet(Lambda(((t, y, x),), (y, t, x)), c3) assert Tuple(Rational(1, 8), 3, 9) in ImageSet(Lambda(((t, y, x),), (1/y, t, x)), c3) assert 2/pi not in ImageSet(Lambda(((x, y),), 2/x), c) assert 2/S(100) not in ImageSet(Lambda(((x, y),), 2/x), c) assert Rational(2, 3) in ImageSet(Lambda(((x, y),), 2/x), c) S1 = imageset(lambda x, y: x + y, S.Integers, S.Naturals) assert S1.base_pset == ProductSet(S.Integers, S.Naturals) assert S1.base_sets == (S.Integers, S.Naturals) # Passing a set instead of a FiniteSet shouldn't raise assert unchanged(ImageSet, Lambda(x, x**2), {1, 2, 3}) S2 = ImageSet(Lambda(((x, y),), x+y), {(1, 2), (3, 4)}) assert 3 in S2.doit() # FIXME: This doesn't yet work: #assert 3 in S2 assert S2._contains(3) is None raises(TypeError, lambda: ImageSet(Lambda(x, x**2), 1)) def test_image_is_ImageSet(): assert isinstance(imageset(x, sqrt(sin(x)), Range(5)), ImageSet) def test_halfcircle(): r, th = symbols('r, theta', real=True) L = Lambda(((r, th),), (r*cos(th), r*sin(th))) halfcircle = ImageSet(L, Interval(0, 1)*Interval(0, pi)) assert (1, 0) in halfcircle assert (0, -1) not in halfcircle assert (0, 0) in halfcircle assert halfcircle._contains((r, 0)) is None # This one doesn't work: #assert (r, 2*pi) not in halfcircle assert not halfcircle.is_iterable def test_ImageSet_iterator_not_injective(): L = Lambda(x, x - x % 2) # produces 0, 2, 2, 4, 4, 6, 6, ... evens = ImageSet(L, S.Naturals) i = iter(evens) # No repeats here assert (next(i), next(i), next(i), next(i)) == (0, 2, 4, 6) def test_inf_Range_len(): raises(ValueError, lambda: len(Range(0, oo, 2))) assert Range(0, oo, 2).size is S.Infinity assert Range(0, -oo, -2).size is S.Infinity assert Range(oo, 0, -2).size is S.Infinity assert Range(-oo, 0, 2).size is S.Infinity def test_Range_set(): empty = Range(0) assert Range(5) == Range(0, 5) == Range(0, 5, 1) r = Range(10, 20, 2) assert 12 in r assert 8 not in r assert 11 not in r assert 30 not in r assert list(Range(0, 5)) == list(range(5)) assert list(Range(5, 0, -1)) == list(range(5, 0, -1)) assert Range(5, 15).sup == 14 assert Range(5, 15).inf == 5 assert Range(15, 5, -1).sup == 15 assert Range(15, 5, -1).inf == 6 assert Range(10, 67, 10).sup == 60 assert Range(60, 7, -10).inf == 10 assert len(Range(10, 38, 10)) == 3 assert Range(0, 0, 5) == empty assert Range(oo, oo, 1) == empty assert Range(oo, 1, 1) == empty assert Range(-oo, 1, -1) == empty assert Range(1, oo, -1) == empty assert Range(1, -oo, 1) == empty assert Range(1, -4, oo) == empty assert Range(1, -4, -oo) == Range(1, 2) assert Range(1, 4, oo) == Range(1, 2) assert Range(-oo, oo).size == oo assert Range(oo, -oo, -1).size == oo raises(ValueError, lambda: Range(-oo, oo, 2)) raises(ValueError, lambda: Range(x, pi, y)) raises(ValueError, lambda: Range(x, y, 0)) assert 5 in Range(0, oo, 5) assert -5 in Range(-oo, 0, 5) assert oo not in Range(0, oo) ni = symbols('ni', integer=False) assert ni not in Range(oo) u = symbols('u', integer=None) assert Range(oo).contains(u) is not False inf = symbols('inf', infinite=True) assert inf not in Range(-oo, oo) raises(ValueError, lambda: Range(0, oo, 2)[-1]) raises(ValueError, lambda: Range(0, -oo, -2)[-1]) assert Range(-oo, 1, 1)[-1] is S.Zero assert Range(oo, 1, -1)[-1] == 2 assert inf not in Range(oo) inf = symbols('inf', infinite=True) assert inf not in Range(oo) assert Range(-oo, 1, 1)[-1] is S.Zero assert Range(oo, 1, -1)[-1] == 2 assert Range(1, 10, 1)[-1] == 9 assert all(i.is_Integer for i in Range(0, -1, 1)) it = iter(Range(-oo, 0, 2)) raises(TypeError, lambda: next(it)) assert empty.intersect(S.Integers) == empty assert Range(-1, 10, 1).intersect(S.Integers) == Range(-1, 10, 1) assert Range(-1, 10, 1).intersect(S.Naturals) == Range(1, 10, 1) assert Range(-1, 10, 1).intersect(S.Naturals0) == Range(0, 10, 1) # test slicing assert Range(1, 10, 1)[5] == 6 assert Range(1, 12, 2)[5] == 11 assert Range(1, 10, 1)[-1] == 9 assert Range(1, 10, 3)[-1] == 7 raises(ValueError, lambda: Range(oo,0,-1)[1:3:0]) raises(ValueError, lambda: Range(oo,0,-1)[:1]) raises(ValueError, lambda: Range(1, oo)[-2]) raises(ValueError, lambda: Range(-oo, 1)[2]) raises(IndexError, lambda: Range(10)[-20]) raises(IndexError, lambda: Range(10)[20]) raises(ValueError, lambda: Range(2, -oo, -2)[2:2:0]) assert Range(2, -oo, -2)[2:2:2] == empty assert Range(2, -oo, -2)[:2:2] == Range(2, -2, -4) raises(ValueError, lambda: Range(-oo, 4, 2)[:2:2]) assert Range(-oo, 4, 2)[::-2] == Range(2, -oo, -4) raises(ValueError, lambda: Range(-oo, 4, 2)[::2]) assert Range(oo, 2, -2)[::] == Range(oo, 2, -2) assert Range(-oo, 4, 2)[:-2:-2] == Range(2, 0, -4) assert Range(-oo, 4, 2)[:-2:2] == Range(-oo, 0, 4) raises(ValueError, lambda: Range(-oo, 4, 2)[:0:-2]) raises(ValueError, lambda: Range(-oo, 4, 2)[:2:-2]) assert Range(-oo, 4, 2)[-2::-2] == Range(0, -oo, -4) raises(ValueError, lambda: Range(-oo, 4, 2)[-2:0:-2]) raises(ValueError, lambda: Range(-oo, 4, 2)[0::2]) assert Range(oo, 2, -2)[0::] == Range(oo, 2, -2) raises(ValueError, lambda: Range(-oo, 4, 2)[0:-2:2]) assert Range(oo, 2, -2)[0:-2:] == Range(oo, 6, -2) raises(ValueError, lambda: Range(oo, 2, -2)[0:2:]) raises(ValueError, lambda: Range(-oo, 4, 2)[2::-1]) assert Range(-oo, 4, 2)[-2::2] == Range(0, 4, 4) assert Range(oo, 0, -2)[-10:0:2] == empty raises(ValueError, lambda: Range(oo, 0, -2)[-10:10:2]) raises(ValueError, lambda: Range(oo, 0, -2)[0::-2]) assert Range(oo, 0, -2)[0:-4:-2] == empty assert Range(oo, 0, -2)[:0:2] == empty raises(ValueError, lambda: Range(oo, 0, -2)[:1:-1]) # test empty Range assert Range(x, x, y) == empty assert empty.reversed == empty assert 0 not in empty assert list(empty) == [] assert len(empty) == 0 assert empty.size is S.Zero assert empty.intersect(FiniteSet(0)) is S.EmptySet assert bool(empty) is False raises(IndexError, lambda: empty[0]) assert empty[:0] == empty raises(NotImplementedError, lambda: empty.inf) raises(NotImplementedError, lambda: empty.sup) AB = [None] + list(range(12)) for R in [ Range(1, 10), Range(1, 10, 2), ]: r = list(R) for a, b, c in cartes(AB, AB, [-3, -1, None, 1, 3]): for reverse in range(2): r = list(reversed(r)) R = R.reversed result = list(R[a:b:c]) ans = r[a:b:c] txt = ('\n%s[%s:%s:%s] = %s -> %s' % ( R, a, b, c, result, ans)) check = ans == result assert check, txt assert Range(1, 10, 1).boundary == Range(1, 10, 1) for r in (Range(1, 10, 2), Range(1, oo, 2)): rev = r.reversed assert r.inf == rev.inf and r.sup == rev.sup assert r.step == -rev.step builtin_range = range raises(TypeError, lambda: Range(builtin_range(1))) assert S(builtin_range(10)) == Range(10) assert S(builtin_range(1000000000000)) == Range(1000000000000) # test Range.as_relational assert Range(1, 4).as_relational(x) == (x >= 1) & (x <= 3) & Eq(x, floor(x)) assert Range(oo, 1, -2).as_relational(x) == (x >= 3) & (x < oo) & Eq(x, floor(x)) def test_Range_symbolic(): # symbolic Range sr = Range(x, y, t) i = Symbol('i', integer=True) ip = Symbol('i', integer=True, positive=True) ir = Range(i, i + 20, 2) inf = symbols('inf', infinite=True) # args assert sr.args == (x, y, t) assert ir.args == (i, i + 20, 2) # reversed raises(ValueError, lambda: sr.reversed) assert ir.reversed == Range(i + 18, i - 2, -2) # contains assert inf not in sr assert inf not in ir assert .1 not in sr assert .1 not in ir assert i + 1 not in ir assert i + 2 in ir raises(TypeError, lambda: 1 in sr) # XXX is this what contains is supposed to do? # iter raises(ValueError, lambda: next(iter(sr))) assert next(iter(ir)) == i assert sr.intersect(S.Integers) == sr assert sr.intersect(FiniteSet(x)) == Intersection({x}, sr) raises(ValueError, lambda: sr[:2]) raises(ValueError, lambda: sr[0]) raises(ValueError, lambda: sr.as_relational(x)) # len assert len(ir) == ir.size == 10 raises(ValueError, lambda: len(sr)) raises(ValueError, lambda: sr.size) # bool assert bool(ir) == bool(sr) == True # getitem raises(ValueError, lambda: sr[0]) raises(ValueError, lambda: sr[-1]) raises(ValueError, lambda: sr[:2]) assert ir[:2] == Range(i, i + 4, 2) assert ir[0] == i assert ir[-2] == i + 16 assert ir[-1] == i + 18 raises(ValueError, lambda: Range(i)[-1]) assert Range(ip)[-1] == ip - 1 assert ir.inf == i assert ir.sup == i + 18 assert Range(ip).inf == 0 assert Range(ip).sup == ip - 1 raises(ValueError, lambda: Range(i).inf) # as_relational raises(ValueError, lambda: sr.as_relational(x)) assert ir.as_relational(x) == ( x >= i) & Eq(x, floor(x)) & (x <= i + 18) assert Range(i, i + 1).as_relational(x) == Eq(x, i) # contains() for symbolic values (issue #18146) e = Symbol('e', integer=True, even=True) o = Symbol('o', integer=True, odd=True) assert Range(5).contains(i) == And(i >= 0, i <= 4) assert Range(1).contains(i) == Eq(i, 0) assert Range(-oo, 5, 1).contains(i) == (i <= 4) assert Range(-oo, oo).contains(i) == True assert Range(0, 8, 2).contains(i) == Contains(i, Range(0, 8, 2)) assert Range(0, 8, 2).contains(e) == And(e >= 0, e <= 6) assert Range(0, 8, 2).contains(2*i) == And(2*i >= 0, 2*i <= 6) assert Range(0, 8, 2).contains(o) == False assert Range(1, 9, 2).contains(e) == False assert Range(1, 9, 2).contains(o) == And(o >= 1, o <= 7) assert Range(8, 0, -2).contains(o) == False assert Range(9, 1, -2).contains(o) == And(o >= 3, o <= 9) assert Range(-oo, 8, 2).contains(i) == Contains(i, Range(-oo, 8, 2)) def test_range_range_intersection(): for a, b, r in [ (Range(0), Range(1), S.EmptySet), (Range(3), Range(4, oo), S.EmptySet), (Range(3), Range(-3, -1), S.EmptySet), (Range(1, 3), Range(0, 3), Range(1, 3)), (Range(1, 3), Range(1, 4), Range(1, 3)), (Range(1, oo, 2), Range(2, oo, 2), S.EmptySet), (Range(0, oo, 2), Range(oo), Range(0, oo, 2)), (Range(0, oo, 2), Range(100), Range(0, 100, 2)), (Range(2, oo, 2), Range(oo), Range(2, oo, 2)), (Range(0, oo, 2), Range(5, 6), S.EmptySet), (Range(2, 80, 1), Range(55, 71, 4), Range(55, 71, 4)), (Range(0, 6, 3), Range(-oo, 5, 3), S.EmptySet), (Range(0, oo, 2), Range(5, oo, 3), Range(8, oo, 6)), (Range(4, 6, 2), Range(2, 16, 7), S.EmptySet),]: assert a.intersect(b) == r assert a.intersect(b.reversed) == r assert a.reversed.intersect(b) == r assert a.reversed.intersect(b.reversed) == r a, b = b, a assert a.intersect(b) == r assert a.intersect(b.reversed) == r assert a.reversed.intersect(b) == r assert a.reversed.intersect(b.reversed) == r def test_range_interval_intersection(): p = symbols('p', positive=True) assert isinstance(Range(3).intersect(Interval(p, p + 2)), Intersection) assert Range(4).intersect(Interval(0, 3)) == Range(4) assert Range(4).intersect(Interval(-oo, oo)) == Range(4) assert Range(4).intersect(Interval(1, oo)) == Range(1, 4) assert Range(4).intersect(Interval(1.1, oo)) == Range(2, 4) assert Range(4).intersect(Interval(0.1, 3)) == Range(1, 4) assert Range(4).intersect(Interval(0.1, 3.1)) == Range(1, 4) assert Range(4).intersect(Interval.open(0, 3)) == Range(1, 3) assert Range(4).intersect(Interval.open(0.1, 0.5)) is S.EmptySet # Null Range intersections assert Range(0).intersect(Interval(0.2, 0.8)) is S.EmptySet assert Range(0).intersect(Interval(-oo, oo)) is S.EmptySet def test_range_is_finite_set(): assert Range(-100, 100).is_finite_set is True assert Range(2, oo).is_finite_set is False assert Range(-oo, 50).is_finite_set is False assert Range(-oo, oo).is_finite_set is False assert Range(oo, -oo).is_finite_set is True assert Range(0, 0).is_finite_set is True assert Range(oo, oo).is_finite_set is True assert Range(-oo, -oo).is_finite_set is True n = Symbol('n', integer=True) m = Symbol('m', integer=True) assert Range(n, n + 49).is_finite_set is True assert Range(n, 0).is_finite_set is True assert Range(-3, n + 7).is_finite_set is True assert Range(n, m).is_finite_set is True assert Range(n + m, m - n).is_finite_set is True assert Range(n, n + m + n).is_finite_set is True assert Range(n, oo).is_finite_set is False assert Range(-oo, n).is_finite_set is False # assert Range(n, -oo).is_finite_set is True # assert Range(oo, n).is_finite_set is True # Above tests fail due to a (potential) bug in sympy.sets.fancysets.Range.size (See issue #18999) def test_Integers_eval_imageset(): ans = ImageSet(Lambda(x, 2*x + Rational(3, 7)), S.Integers) im = imageset(Lambda(x, -2*x + Rational(3, 7)), S.Integers) assert im == ans im = imageset(Lambda(x, -2*x - Rational(11, 7)), S.Integers) assert im == ans y = Symbol('y') L = imageset(x, 2*x + y, S.Integers) assert y + 4 in L _x = symbols('x', negative=True) eq = _x**2 - _x + 1 assert imageset(_x, eq, S.Integers).lamda.expr == _x**2 + _x + 1 eq = 3*_x - 1 assert imageset(_x, eq, S.Integers).lamda.expr == 3*_x + 2 assert imageset(x, (x, 1/x), S.Integers) == \ ImageSet(Lambda(x, (x, 1/x)), S.Integers) def test_Range_eval_imageset(): a, b, c = symbols('a b c') assert imageset(x, a*(x + b) + c, Range(3)) == \ imageset(x, a*x + a*b + c, Range(3)) eq = (x + 1)**2 assert imageset(x, eq, Range(3)).lamda.expr == eq eq = a*(x + b) + c r = Range(3, -3, -2) imset = imageset(x, eq, r) assert imset.lamda.expr != eq assert list(imset) == [eq.subs(x, i).expand() for i in list(r)] def test_fun(): assert (FiniteSet(*ImageSet(Lambda(x, sin(pi*x/4)), Range(-10, 11))) == FiniteSet(-1, -sqrt(2)/2, 0, sqrt(2)/2, 1)) def test_Reals(): assert 5 in S.Reals assert S.Pi in S.Reals assert -sqrt(2) in S.Reals assert (2, 5) not in S.Reals assert sqrt(-1) not in S.Reals assert S.Reals == Interval(-oo, oo) assert S.Reals != Interval(0, oo) assert S.Reals.is_subset(Interval(-oo, oo)) assert S.Reals.intersect(Range(-oo, oo)) == Range(-oo, oo) def test_Complex(): assert 5 in S.Complexes assert 5 + 4*I in S.Complexes assert S.Pi in S.Complexes assert -sqrt(2) in S.Complexes assert -I in S.Complexes assert sqrt(-1) in S.Complexes assert S.Complexes.intersect(S.Reals) == S.Reals assert S.Complexes.union(S.Reals) == S.Complexes assert S.Complexes == ComplexRegion(S.Reals*S.Reals) assert (S.Complexes == ComplexRegion(Interval(1, 2)*Interval(3, 4))) == False assert str(S.Complexes) == "S.Complexes" assert repr(S.Complexes) == "S.Complexes" def take(n, iterable): "Return first n items of the iterable as a list" return list(itertools.islice(iterable, n)) def test_intersections(): assert S.Integers.intersect(S.Reals) == S.Integers assert 5 in S.Integers.intersect(S.Reals) assert 5 in S.Integers.intersect(S.Reals) assert -5 not in S.Naturals.intersect(S.Reals) assert 5.5 not in S.Integers.intersect(S.Reals) assert 5 in S.Integers.intersect(Interval(3, oo)) assert -5 in S.Integers.intersect(Interval(-oo, 3)) assert all(x.is_Integer for x in take(10, S.Integers.intersect(Interval(3, oo)) )) def test_infinitely_indexed_set_1(): from sympy.abc import n, m, t assert imageset(Lambda(n, n), S.Integers) == imageset(Lambda(m, m), S.Integers) assert imageset(Lambda(n, 2*n), S.Integers).intersect( imageset(Lambda(m, 2*m + 1), S.Integers)) is S.EmptySet assert imageset(Lambda(n, 2*n), S.Integers).intersect( imageset(Lambda(n, 2*n + 1), S.Integers)) is S.EmptySet assert imageset(Lambda(m, 2*m), S.Integers).intersect( imageset(Lambda(n, 3*n), S.Integers)).dummy_eq( ImageSet(Lambda(t, 6*t), S.Integers)) assert imageset(x, x/2 + Rational(1, 3), S.Integers).intersect(S.Integers) is S.EmptySet assert imageset(x, x/2 + S.Half, S.Integers).intersect(S.Integers) is S.Integers # https://github.com/sympy/sympy/issues/17355 S53 = ImageSet(Lambda(n, 5*n + 3), S.Integers) assert S53.intersect(S.Integers) == S53 def test_infinitely_indexed_set_2(): from sympy.abc import n a = Symbol('a', integer=True) assert imageset(Lambda(n, n), S.Integers) == \ imageset(Lambda(n, n + a), S.Integers) assert imageset(Lambda(n, n + pi), S.Integers) == \ imageset(Lambda(n, n + a + pi), S.Integers) assert imageset(Lambda(n, n), S.Integers) == \ imageset(Lambda(n, -n + a), S.Integers) assert imageset(Lambda(n, -6*n), S.Integers) == \ ImageSet(Lambda(n, 6*n), S.Integers) assert imageset(Lambda(n, 2*n + pi), S.Integers) == \ ImageSet(Lambda(n, 2*n + pi - 2), S.Integers) def test_imageset_intersect_real(): from sympy import I from sympy.abc import n assert imageset(Lambda(n, n + (n - 1)*(n + 1)*I), S.Integers).intersect(S.Reals) == \ FiniteSet(-1, 1) s = ImageSet( Lambda(n, -I*(I*(2*pi*n - pi/4) + log(Abs(sqrt(-I))))), S.Integers) # s is unevaluated, but after intersection the result # should be canonical assert s.intersect(S.Reals) == imageset( Lambda(n, 2*n*pi - pi/4), S.Integers) == ImageSet( Lambda(n, 2*pi*n + pi*Rational(7, 4)), S.Integers) def test_imageset_intersect_interval(): from sympy.abc import n f1 = ImageSet(Lambda(n, n*pi), S.Integers) f2 = ImageSet(Lambda(n, 2*n), Interval(0, pi)) f3 = ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers) # complex expressions f4 = ImageSet(Lambda(n, n*I*pi), S.Integers) f5 = ImageSet(Lambda(n, 2*I*n*pi + pi/2), S.Integers) # non-linear expressions f6 = ImageSet(Lambda(n, log(n)), S.Integers) f7 = ImageSet(Lambda(n, n**2), S.Integers) f8 = ImageSet(Lambda(n, Abs(n)), S.Integers) f9 = ImageSet(Lambda(n, exp(n)), S.Naturals0) assert f1.intersect(Interval(-1, 1)) == FiniteSet(0) assert f1.intersect(Interval(0, 2*pi, False, True)) == FiniteSet(0, pi) assert f2.intersect(Interval(1, 2)) == Interval(1, 2) assert f3.intersect(Interval(-1, 1)) == S.EmptySet assert f3.intersect(Interval(-5, 5)) == FiniteSet(pi*Rational(-3, 2), pi/2) assert f4.intersect(Interval(-1, 1)) == FiniteSet(0) assert f4.intersect(Interval(1, 2)) == S.EmptySet assert f5.intersect(Interval(0, 1)) == S.EmptySet assert f6.intersect(Interval(0, 1)) == FiniteSet(S.Zero, log(2)) assert f7.intersect(Interval(0, 10)) == Intersection(f7, Interval(0, 10)) assert f8.intersect(Interval(0, 2)) == Intersection(f8, Interval(0, 2)) assert f9.intersect(Interval(1, 2)) == Intersection(f9, Interval(1, 2)) def test_imageset_intersect_diophantine(): from sympy.abc import m, n # Check that same lambda variable for both ImageSets is handled correctly img1 = ImageSet(Lambda(n, 2*n + 1), S.Integers) img2 = ImageSet(Lambda(n, 4*n + 1), S.Integers) assert img1.intersect(img2) == img2 # Empty solution set returned by diophantine: assert ImageSet(Lambda(n, 2*n), S.Integers).intersect( ImageSet(Lambda(n, 2*n + 1), S.Integers)) == S.EmptySet # Check intersection with S.Integers: assert ImageSet(Lambda(n, 9/n + 20*n/3), S.Integers).intersect( S.Integers) == FiniteSet(-61, -23, 23, 61) # Single solution (2, 3) for diophantine solution: assert ImageSet(Lambda(n, (n - 2)**2), S.Integers).intersect( ImageSet(Lambda(n, -(n - 3)**2), S.Integers)) == FiniteSet(0) # Single parametric solution for diophantine solution: assert ImageSet(Lambda(n, n**2 + 5), S.Integers).intersect( ImageSet(Lambda(m, 2*m), S.Integers)).dummy_eq(ImageSet( Lambda(n, 4*n**2 + 4*n + 6), S.Integers)) # 4 non-parametric solution couples for dioph. equation: assert ImageSet(Lambda(n, n**2 - 9), S.Integers).intersect( ImageSet(Lambda(m, -m**2), S.Integers)) == FiniteSet(-9, 0) # Double parametric solution for diophantine solution: assert ImageSet(Lambda(m, m**2 + 40), S.Integers).intersect( ImageSet(Lambda(n, 41*n), S.Integers)).dummy_eq(Intersection( ImageSet(Lambda(m, m**2 + 40), S.Integers), ImageSet(Lambda(n, 41*n), S.Integers))) # Check that diophantine returns *all* (8) solutions (permute=True) assert ImageSet(Lambda(n, n**4 - 2**4), S.Integers).intersect( ImageSet(Lambda(m, -m**4 + 3**4), S.Integers)) == FiniteSet(0, 65) assert ImageSet(Lambda(n, pi/12 + n*5*pi/12), S.Integers).intersect( ImageSet(Lambda(n, 7*pi/12 + n*11*pi/12), S.Integers)).dummy_eq(ImageSet( Lambda(n, 55*pi*n/12 + 17*pi/4), S.Integers)) # TypeError raised by diophantine (#18081) assert ImageSet(Lambda(n, n*log(2)), S.Integers).intersection( S.Integers).dummy_eq(Intersection(ImageSet( Lambda(n, n*log(2)), S.Integers), S.Integers)) # NotImplementedError raised by diophantine (no solver for cubic_thue) assert ImageSet(Lambda(n, n**3 + 1), S.Integers).intersect( ImageSet(Lambda(n, n**3), S.Integers)).dummy_eq(Intersection( ImageSet(Lambda(n, n**3 + 1), S.Integers), ImageSet(Lambda(n, n**3), S.Integers))) def test_infinitely_indexed_set_3(): from sympy.abc import n, m, t assert imageset(Lambda(m, 2*pi*m), S.Integers).intersect( imageset(Lambda(n, 3*pi*n), S.Integers)).dummy_eq( ImageSet(Lambda(t, 6*pi*t), S.Integers)) assert imageset(Lambda(n, 2*n + 1), S.Integers) == \ imageset(Lambda(n, 2*n - 1), S.Integers) assert imageset(Lambda(n, 3*n + 2), S.Integers) == \ imageset(Lambda(n, 3*n - 1), S.Integers) def test_ImageSet_simplification(): from sympy.abc import n, m assert imageset(Lambda(n, n), S.Integers) == S.Integers assert imageset(Lambda(n, sin(n)), imageset(Lambda(m, tan(m)), S.Integers)) == \ imageset(Lambda(m, sin(tan(m))), S.Integers) assert imageset(n, 1 + 2*n, S.Naturals) == Range(3, oo, 2) assert imageset(n, 1 + 2*n, S.Naturals0) == Range(1, oo, 2) assert imageset(n, 1 - 2*n, S.Naturals) == Range(-1, -oo, -2) def test_ImageSet_contains(): from sympy.abc import x assert (2, S.Half) in imageset(x, (x, 1/x), S.Integers) assert imageset(x, x + I*3, S.Integers).intersection(S.Reals) is S.EmptySet i = Dummy(integer=True) q = imageset(x, x + I*y, S.Integers).intersection(S.Reals) assert q.subs(y, I*i).intersection(S.Integers) is S.Integers q = imageset(x, x + I*y/x, S.Integers).intersection(S.Reals) assert q.subs(y, 0) is S.Integers assert q.subs(y, I*i*x).intersection(S.Integers) is S.Integers z = cos(1)**2 + sin(1)**2 - 1 q = imageset(x, x + I*z, S.Integers).intersection(S.Reals) assert q is not S.EmptySet def test_ComplexRegion_contains(): r = Symbol('r', real=True) # contains in ComplexRegion a = Interval(2, 3) b = Interval(4, 6) c = Interval(7, 9) c1 = ComplexRegion(a*b) c2 = ComplexRegion(Union(a*b, c*a)) assert 2.5 + 4.5*I in c1 assert 2 + 4*I in c1 assert 3 + 4*I in c1 assert 8 + 2.5*I in c2 assert 2.5 + 6.1*I not in c1 assert 4.5 + 3.2*I not in c1 assert c1.contains(x) == Contains(x, c1, evaluate=False) assert c1.contains(r) == False assert c2.contains(x) == Contains(x, c2, evaluate=False) assert c2.contains(r) == False r1 = Interval(0, 1) theta1 = Interval(0, 2*S.Pi) c3 = ComplexRegion(r1*theta1, polar=True) assert (0.5 + I*Rational(6, 10)) in c3 assert (S.Half + I*Rational(6, 10)) in c3 assert (S.Half + .6*I) in c3 assert (0.5 + .6*I) in c3 assert I in c3 assert 1 in c3 assert 0 in c3 assert 1 + I not in c3 assert 1 - I not in c3 assert c3.contains(x) == Contains(x, c3, evaluate=False) assert c3.contains(r + 2*I) == Contains( r + 2*I, c3, evaluate=False) # is in fact False assert c3.contains(1/(1 + r**2)) == Contains( 1/(1 + r**2), c3, evaluate=False) # is in fact True r2 = Interval(0, 3) theta2 = Interval(pi, 2*pi, left_open=True) c4 = ComplexRegion(r2*theta2, polar=True) assert c4.contains(0) == True assert c4.contains(2 + I) == False assert c4.contains(-2 + I) == False assert c4.contains(-2 - I) == True assert c4.contains(2 - I) == True assert c4.contains(-2) == False assert c4.contains(2) == True assert c4.contains(x) == Contains(x, c4, evaluate=False) assert c4.contains(3/(1 + r**2)) == Contains( 3/(1 + r**2), c4, evaluate=False) # is in fact True raises(ValueError, lambda: ComplexRegion(r1*theta1, polar=2)) def test_ComplexRegion_intersect(): # Polar form X_axis = ComplexRegion(Interval(0, oo)*FiniteSet(0, S.Pi), polar=True) unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True) upper_half_unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True) upper_half_disk = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi), polar=True) lower_half_disk = ComplexRegion(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True) right_half_disk = ComplexRegion(Interval(0, oo)*Interval(-S.Pi/2, S.Pi/2), polar=True) first_quad_disk = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi/2), polar=True) assert upper_half_disk.intersect(unit_disk) == upper_half_unit_disk assert right_half_disk.intersect(first_quad_disk) == first_quad_disk assert upper_half_disk.intersect(right_half_disk) == first_quad_disk assert upper_half_disk.intersect(lower_half_disk) == X_axis c1 = ComplexRegion(Interval(0, 4)*Interval(0, 2*S.Pi), polar=True) assert c1.intersect(Interval(1, 5)) == Interval(1, 4) assert c1.intersect(Interval(4, 9)) == FiniteSet(4) assert c1.intersect(Interval(5, 12)) is S.EmptySet # Rectangular form X_axis = ComplexRegion(Interval(-oo, oo)*FiniteSet(0)) unit_square = ComplexRegion(Interval(-1, 1)*Interval(-1, 1)) upper_half_unit_square = ComplexRegion(Interval(-1, 1)*Interval(0, 1)) upper_half_plane = ComplexRegion(Interval(-oo, oo)*Interval(0, oo)) lower_half_plane = ComplexRegion(Interval(-oo, oo)*Interval(-oo, 0)) right_half_plane = ComplexRegion(Interval(0, oo)*Interval(-oo, oo)) first_quad_plane = ComplexRegion(Interval(0, oo)*Interval(0, oo)) assert upper_half_plane.intersect(unit_square) == upper_half_unit_square assert right_half_plane.intersect(first_quad_plane) == first_quad_plane assert upper_half_plane.intersect(right_half_plane) == first_quad_plane assert upper_half_plane.intersect(lower_half_plane) == X_axis c1 = ComplexRegion(Interval(-5, 5)*Interval(-10, 10)) assert c1.intersect(Interval(2, 7)) == Interval(2, 5) assert c1.intersect(Interval(5, 7)) == FiniteSet(5) assert c1.intersect(Interval(6, 9)) is S.EmptySet # unevaluated object C1 = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True) C2 = ComplexRegion(Interval(-1, 1)*Interval(-1, 1)) assert C1.intersect(C2) == Intersection(C1, C2, evaluate=False) def test_ComplexRegion_union(): # Polar form c1 = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True) c2 = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True) c3 = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi), polar=True) c4 = ComplexRegion(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True) p1 = Union(Interval(0, 1)*Interval(0, 2*S.Pi), Interval(0, 1)*Interval(0, S.Pi)) p2 = Union(Interval(0, oo)*Interval(0, S.Pi), Interval(0, oo)*Interval(S.Pi, 2*S.Pi)) assert c1.union(c2) == ComplexRegion(p1, polar=True) assert c3.union(c4) == ComplexRegion(p2, polar=True) # Rectangular form c5 = ComplexRegion(Interval(2, 5)*Interval(6, 9)) c6 = ComplexRegion(Interval(4, 6)*Interval(10, 12)) c7 = ComplexRegion(Interval(0, 10)*Interval(-10, 0)) c8 = ComplexRegion(Interval(12, 16)*Interval(14, 20)) p3 = Union(Interval(2, 5)*Interval(6, 9), Interval(4, 6)*Interval(10, 12)) p4 = Union(Interval(0, 10)*Interval(-10, 0), Interval(12, 16)*Interval(14, 20)) assert c5.union(c6) == ComplexRegion(p3) assert c7.union(c8) == ComplexRegion(p4) assert c1.union(Interval(2, 4)) == Union(c1, Interval(2, 4), evaluate=False) assert c5.union(Interval(2, 4)) == Union(c5, ComplexRegion.from_real(Interval(2, 4))) def test_ComplexRegion_from_real(): c1 = ComplexRegion(Interval(0, 1) * Interval(0, 2 * S.Pi), polar=True) raises(ValueError, lambda: c1.from_real(c1)) assert c1.from_real(Interval(-1, 1)) == ComplexRegion(Interval(-1, 1) * FiniteSet(0), False) def test_ComplexRegion_measure(): a, b = Interval(2, 5), Interval(4, 8) theta1, theta2 = Interval(0, 2*S.Pi), Interval(0, S.Pi) c1 = ComplexRegion(a*b) c2 = ComplexRegion(Union(a*theta1, b*theta2), polar=True) assert c1.measure == 12 assert c2.measure == 9*pi def test_normalize_theta_set(): # Interval assert normalize_theta_set(Interval(pi, 2*pi)) == \ Union(FiniteSet(0), Interval.Ropen(pi, 2*pi)) assert normalize_theta_set(Interval(pi*Rational(9, 2), 5*pi)) == Interval(pi/2, pi) assert normalize_theta_set(Interval(pi*Rational(-3, 2), pi/2)) == Interval.Ropen(0, 2*pi) assert normalize_theta_set(Interval.open(pi*Rational(-3, 2), pi/2)) == \ Union(Interval.Ropen(0, pi/2), Interval.open(pi/2, 2*pi)) assert normalize_theta_set(Interval.open(pi*Rational(-7, 2), pi*Rational(-3, 2))) == \ Union(Interval.Ropen(0, pi/2), Interval.open(pi/2, 2*pi)) assert normalize_theta_set(Interval(-pi/2, pi/2)) == \ Union(Interval(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi)) assert normalize_theta_set(Interval.open(-pi/2, pi/2)) == \ Union(Interval.Ropen(0, pi/2), Interval.open(pi*Rational(3, 2), 2*pi)) assert normalize_theta_set(Interval(-4*pi, 3*pi)) == Interval.Ropen(0, 2*pi) assert normalize_theta_set(Interval(pi*Rational(-3, 2), -pi/2)) == Interval(pi/2, pi*Rational(3, 2)) assert normalize_theta_set(Interval.open(0, 2*pi)) == Interval.open(0, 2*pi) assert normalize_theta_set(Interval.Ropen(-pi/2, pi/2)) == \ Union(Interval.Ropen(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi)) assert normalize_theta_set(Interval.Lopen(-pi/2, pi/2)) == \ Union(Interval(0, pi/2), Interval.open(pi*Rational(3, 2), 2*pi)) assert normalize_theta_set(Interval(-pi/2, pi/2)) == \ Union(Interval(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi)) assert normalize_theta_set(Interval.open(4*pi, pi*Rational(9, 2))) == Interval.open(0, pi/2) assert normalize_theta_set(Interval.Lopen(4*pi, pi*Rational(9, 2))) == Interval.Lopen(0, pi/2) assert normalize_theta_set(Interval.Ropen(4*pi, pi*Rational(9, 2))) == Interval.Ropen(0, pi/2) assert normalize_theta_set(Interval.open(3*pi, 5*pi)) == \ Union(Interval.Ropen(0, pi), Interval.open(pi, 2*pi)) # FiniteSet assert normalize_theta_set(FiniteSet(0, pi, 3*pi)) == FiniteSet(0, pi) assert normalize_theta_set(FiniteSet(0, pi/2, pi, 2*pi)) == FiniteSet(0, pi/2, pi) assert normalize_theta_set(FiniteSet(0, -pi/2, -pi, -2*pi)) == FiniteSet(0, pi, pi*Rational(3, 2)) assert normalize_theta_set(FiniteSet(pi*Rational(-3, 2), pi/2)) == \ FiniteSet(pi/2) assert normalize_theta_set(FiniteSet(2*pi)) == FiniteSet(0) # Unions assert normalize_theta_set(Union(Interval(0, pi/3), Interval(pi/2, pi))) == \ Union(Interval(0, pi/3), Interval(pi/2, pi)) assert normalize_theta_set(Union(Interval(0, pi), Interval(2*pi, pi*Rational(7, 3)))) == \ Interval(0, pi) # ValueError for non-real sets raises(ValueError, lambda: normalize_theta_set(S.Complexes)) # NotImplementedError for subset of reals raises(NotImplementedError, lambda: normalize_theta_set(Interval(0, 1))) # NotImplementedError without pi as coefficient raises(NotImplementedError, lambda: normalize_theta_set(Interval(1, 2*pi))) raises(NotImplementedError, lambda: normalize_theta_set(Interval(2*pi, 10))) raises(NotImplementedError, lambda: normalize_theta_set(FiniteSet(0, 3, 3*pi))) def test_ComplexRegion_FiniteSet(): x, y, z, a, b, c = symbols('x y z a b c') # Issue #9669 assert ComplexRegion(FiniteSet(a, b, c)*FiniteSet(x, y, z)) == \ FiniteSet(a + I*x, a + I*y, a + I*z, b + I*x, b + I*y, b + I*z, c + I*x, c + I*y, c + I*z) assert ComplexRegion(FiniteSet(2)*FiniteSet(3)) == FiniteSet(2 + 3*I) def test_union_RealSubSet(): assert (S.Complexes).union(Interval(1, 2)) == S.Complexes assert (S.Complexes).union(S.Integers) == S.Complexes def test_issue_9980(): c1 = ComplexRegion(Interval(1, 2)*Interval(2, 3)) c2 = ComplexRegion(Interval(1, 5)*Interval(1, 3)) R = Union(c1, c2) assert simplify(R) == ComplexRegion(Union(Interval(1, 2)*Interval(2, 3), \ Interval(1, 5)*Interval(1, 3)), False) assert c1.func(*c1.args) == c1 assert R.func(*R.args) == R def test_issue_11732(): interval12 = Interval(1, 2) finiteset1234 = FiniteSet(1, 2, 3, 4) pointComplex = Tuple(1, 5) assert (interval12 in S.Naturals) == False assert (interval12 in S.Naturals0) == False assert (interval12 in S.Integers) == False assert (interval12 in S.Complexes) == False assert (finiteset1234 in S.Naturals) == False assert (finiteset1234 in S.Naturals0) == False assert (finiteset1234 in S.Integers) == False assert (finiteset1234 in S.Complexes) == False assert (pointComplex in S.Naturals) == False assert (pointComplex in S.Naturals0) == False assert (pointComplex in S.Integers) == False assert (pointComplex in S.Complexes) == True def test_issue_11730(): unit = Interval(0, 1) square = ComplexRegion(unit ** 2) assert Union(S.Complexes, FiniteSet(oo)) != S.Complexes assert Union(S.Complexes, FiniteSet(eye(4))) != S.Complexes assert Union(unit, square) == square assert Intersection(S.Reals, square) == unit def test_issue_11938(): unit = Interval(0, 1) ival = Interval(1, 2) cr1 = ComplexRegion(ival * unit) assert Intersection(cr1, S.Reals) == ival assert Intersection(cr1, unit) == FiniteSet(1) arg1 = Interval(0, S.Pi) arg2 = FiniteSet(S.Pi) arg3 = Interval(S.Pi / 4, 3 * S.Pi / 4) cp1 = ComplexRegion(unit * arg1, polar=True) cp2 = ComplexRegion(unit * arg2, polar=True) cp3 = ComplexRegion(unit * arg3, polar=True) assert Intersection(cp1, S.Reals) == Interval(-1, 1) assert Intersection(cp2, S.Reals) == Interval(-1, 0) assert Intersection(cp3, S.Reals) == FiniteSet(0) def test_issue_11914(): a, b = Interval(0, 1), Interval(0, pi) c, d = Interval(2, 3), Interval(pi, 3 * pi / 2) cp1 = ComplexRegion(a * b, polar=True) cp2 = ComplexRegion(c * d, polar=True) assert -3 in cp1.union(cp2) assert -3 in cp2.union(cp1) assert -5 not in cp1.union(cp2) def test_issue_9543(): assert ImageSet(Lambda(x, x**2), S.Naturals).is_subset(S.Reals) def test_issue_16871(): assert ImageSet(Lambda(x, x), FiniteSet(1)) == {1} assert ImageSet(Lambda(x, x - 3), S.Integers ).intersection(S.Integers) is S.Integers @XFAIL def test_issue_16871b(): assert ImageSet(Lambda(x, x - 3), S.Integers).is_subset(S.Integers) def test_issue_18050(): assert imageset(Lambda(x, I*x + 1), S.Integers ) == ImageSet(Lambda(x, I*x + 1), S.Integers) assert imageset(Lambda(x, 3*I*x + 4 + 8*I), S.Integers ) == ImageSet(Lambda(x, 3*I*x + 4 + 2*I), S.Integers) # no 'Mod' for next 2 tests: assert imageset(Lambda(x, 2*x + 3*I), S.Integers ) == ImageSet(Lambda(x, 2*x + 3*I), S.Integers) r = Symbol('r', positive=True) assert imageset(Lambda(x, r*x + 10), S.Integers ) == ImageSet(Lambda(x, r*x + 10), S.Integers) # reduce real part: assert imageset(Lambda(x, 3*x + 8 + 5*I), S.Integers ) == ImageSet(Lambda(x, 3*x + 2 + 5*I), S.Integers) def test_Rationals(): assert S.Integers.is_subset(S.Rationals) assert S.Naturals.is_subset(S.Rationals) assert S.Naturals0.is_subset(S.Rationals) assert S.Rationals.is_subset(S.Reals) assert S.Rationals.inf is -oo assert S.Rationals.sup is oo it = iter(S.Rationals) assert [next(it) for i in range(12)] == [ 0, 1, -1, S.Half, 2, Rational(-1, 2), -2, Rational(1, 3), 3, Rational(-1, 3), -3, Rational(2, 3)] assert Basic() not in S.Rationals assert S.Half in S.Rationals assert S.Rationals.contains(0.5) == Contains(0.5, S.Rationals, evaluate=False) assert 2 in S.Rationals r = symbols('r', rational=True) assert r in S.Rationals raises(TypeError, lambda: x in S.Rationals) # issue #18134: assert S.Rationals.boundary == S.Reals assert S.Rationals.closure == S.Reals assert S.Rationals.is_open == False assert S.Rationals.is_closed == False def test_NZQRC_unions(): # check that all trivial number set unions are simplified: nbrsets = (S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals, S.Complexes) unions = (Union(a, b) for a in nbrsets for b in nbrsets) assert all(u.is_Union is False for u in unions) def test_imageset_intersection(): n = Dummy() s = ImageSet(Lambda(n, -I*(I*(2*pi*n - pi/4) + log(Abs(sqrt(-I))))), S.Integers) assert s.intersect(S.Reals) == ImageSet( Lambda(n, 2*pi*n + pi*Rational(7, 4)), S.Integers) def test_issue_17858(): assert 1 in Range(-oo, oo) assert 0 in Range(oo, -oo, -1) assert oo not in Range(-oo, oo) assert -oo not in Range(-oo, oo) def test_issue_17859(): r = Range(-oo,oo) raises(ValueError,lambda: r[::2]) raises(ValueError, lambda: r[::-2]) r = Range(oo,-oo,-1) raises(ValueError,lambda: r[::2]) raises(ValueError, lambda: r[::-2])
71ea2e17cb7c7a60398d9c67885430b4f4c8d54aa437460ee374f1a1262da015
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)) not in (S.true, 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_20379(): #https://github.com/sympy/sympy/issues/20379 x = pi - 3.14159265358979 assert FiniteSet(x).evalf(2) == FiniteSet(Float('3.23108914886517e-15', 2))
c678ea81c0cf5698ca5bdc50f17d8280e3e009ee1f55e525d6162dc00463e528
import os from tempfile import TemporaryDirectory from sympy import ( pi, sin, cos, Symbol, Integral, Sum, sqrt, log, exp, Ne, oo, LambertW, I, meijerg, exp_polar, Piecewise, And, real_root) from sympy.core.singleton import S from sympy.core.sympify import sympify from sympy.external import import_module from sympy.plotting.plot import ( Plot, plot, plot_parametric, plot3d_parametric_line, plot3d, plot3d_parametric_surface) from sympy.plotting.plot import ( unset_show, plot_contour, PlotGrid, DefaultBackend, MatplotlibBackend, TextBackend, BaseBackend) from sympy.testing.pytest import skip, raises, warns from sympy.utilities import lambdify as lambdify_ unset_show() matplotlib = import_module( 'matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) class DummyBackendNotOk(BaseBackend): """ Used to verify if users can create their own backends. This backend is meant to raise NotImplementedError for methods `show`, `save`, `close`. """ pass class DummyBackendOk(BaseBackend): """ Used to verify if users can create their own backends. This backend is meant to pass all tests. """ def show(self): pass def save(self): pass def close(self): pass def test_plot_and_save_1(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') with TemporaryDirectory(prefix='sympy_') as tmpdir: ### # Examples from the 'introduction' notebook ### p = plot(x, legend=True, label='f1') p = plot(x*sin(x), x*cos(x), label='f2') p.extend(p) p[0].line_color = lambda a: a p[1].line_color = 'b' p.title = 'Big title' p.xlabel = 'the x axis' p[1].label = 'straight line' p.legend = True p.aspect_ratio = (1, 1) p.xlim = (-15, 20) filename = 'test_basic_options_and_colors.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p.extend(plot(x + 1)) p.append(plot(x + 3, x**2)[1]) filename = 'test_plot_extend_append.png' p.save(os.path.join(tmpdir, filename)) p[2] = plot(x**2, (x, -2, 3)) filename = 'test_plot_setitem.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(sin(x), (x, -2*pi, 4*pi)) filename = 'test_line_explicit.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(sin(x)) filename = 'test_line_default_range.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot((x**2, (x, -5, 5)), (x**3, (x, -3, 3))) filename = 'test_line_multiple_range.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() raises(ValueError, lambda: plot(x, y)) #Piecewise plots p = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1)) filename = 'test_plot_piecewise.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(Piecewise((x, x < 1), (x**2, True)), (x, -3, 3)) filename = 'test_plot_piecewise_2.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # test issue 7471 p1 = plot(x) p2 = plot(3) p1.extend(p2) filename = 'test_horizontal_line.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # test issue 10925 f = Piecewise((-1, x < -1), (x, And(-1 <= x, x < 0)), \ (x**2, And(0 <= x, x < 1)), (x**3, x >= 1)) p = plot(f, (x, -3, 3)) filename = 'test_plot_piecewise_3.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_plot_and_save_2(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') z = Symbol('z') with TemporaryDirectory(prefix='sympy_') as tmpdir: #parametric 2d plots. #Single plot with default range. p = plot_parametric(sin(x), cos(x)) filename = 'test_parametric.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #Single plot with range. p = plot_parametric( sin(x), cos(x), (x, -5, 5), legend=True, label='parametric_plot') filename = 'test_parametric_range.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #Multiple plots with same range. p = plot_parametric((sin(x), cos(x)), (x, sin(x))) filename = 'test_parametric_multiple.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #Multiple plots with different ranges. p = plot_parametric( (sin(x), cos(x), (x, -3, 3)), (x, sin(x), (x, -5, 5))) filename = 'test_parametric_multiple_ranges.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #depth of recursion specified. p = plot_parametric(x, sin(x), depth=13) filename = 'test_recursion_depth.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #No adaptive sampling. p = plot_parametric(cos(x), sin(x), adaptive=False, nb_of_points=500) filename = 'test_adaptive.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #3d parametric plots p = plot3d_parametric_line( sin(x), cos(x), x, legend=True, label='3d_parametric_plot') filename = 'test_3d_line.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot3d_parametric_line( (sin(x), cos(x), x, (x, -5, 5)), (cos(x), sin(x), x, (x, -3, 3))) filename = 'test_3d_line_multiple.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot3d_parametric_line(sin(x), cos(x), x, nb_of_points=30) filename = 'test_3d_line_points.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # 3d surface single plot. p = plot3d(x * y) filename = 'test_surface.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Multiple 3D plots with same range. p = plot3d(-x * y, x * y, (x, -5, 5)) filename = 'test_surface_multiple.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Multiple 3D plots with different ranges. p = plot3d( (x * y, (x, -3, 3), (y, -3, 3)), (-x * y, (x, -3, 3), (y, -3, 3))) filename = 'test_surface_multiple_ranges.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Single Parametric 3D plot p = plot3d_parametric_surface(sin(x + y), cos(x - y), x - y) filename = 'test_parametric_surface.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Multiple Parametric 3D plots. p = plot3d_parametric_surface( (x*sin(z), x*cos(z), z, (x, -5, 5), (z, -5, 5)), (sin(x + y), cos(x - y), x - y, (x, -5, 5), (y, -5, 5))) filename = 'test_parametric_surface.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Single Contour plot. p = plot_contour(sin(x)*sin(y), (x, -5, 5), (y, -5, 5)) filename = 'test_contour_plot.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Multiple Contour plots with same range. p = plot_contour(x**2 + y**2, x**3 + y**3, (x, -5, 5), (y, -5, 5)) filename = 'test_contour_plot.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Multiple Contour plots with different range. p = plot_contour( (x**2 + y**2, (x, -5, 5), (y, -5, 5)), (x**3 + y**3, (x, -3, 3), (y, -3, 3))) filename = 'test_contour_plot.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_plot_and_save_3(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') z = Symbol('z') with TemporaryDirectory(prefix='sympy_') as tmpdir: ### # Examples from the 'colors' notebook ### p = plot(sin(x)) p[0].line_color = lambda a: a filename = 'test_colors_line_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].line_color = lambda a, b: b filename = 'test_colors_line_arity2.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(x*sin(x), x*cos(x), (x, 0, 10)) p[0].line_color = lambda a: a filename = 'test_colors_param_line_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].line_color = lambda a, b: a filename = 'test_colors_param_line_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].line_color = lambda a, b: b filename = 'test_colors_param_line_arity2b.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot3d_parametric_line(sin(x) + 0.1*sin(x)*cos(7*x), cos(x) + 0.1*cos(x)*cos(7*x), 0.1*sin(7*x), (x, 0, 2*pi)) p[0].line_color = lambdify_(x, sin(4*x)) filename = 'test_colors_3d_line_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].line_color = lambda a, b: b filename = 'test_colors_3d_line_arity2.png' p.save(os.path.join(tmpdir, filename)) p[0].line_color = lambda a, b, c: c filename = 'test_colors_3d_line_arity3.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot3d(sin(x)*y, (x, 0, 6*pi), (y, -5, 5)) p[0].surface_color = lambda a: a filename = 'test_colors_surface_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].surface_color = lambda a, b: b filename = 'test_colors_surface_arity2.png' p.save(os.path.join(tmpdir, filename)) p[0].surface_color = lambda a, b, c: c filename = 'test_colors_surface_arity3a.png' p.save(os.path.join(tmpdir, filename)) p[0].surface_color = lambdify_((x, y, z), sqrt((x - 3*pi)**2 + y**2)) filename = 'test_colors_surface_arity3b.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot3d_parametric_surface(x * cos(4 * y), x * sin(4 * y), y, (x, -1, 1), (y, -1, 1)) p[0].surface_color = lambda a: a filename = 'test_colors_param_surf_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].surface_color = lambda a, b: a*b filename = 'test_colors_param_surf_arity2.png' p.save(os.path.join(tmpdir, filename)) p[0].surface_color = lambdify_((x, y, z), sqrt(x**2 + y**2 + z**2)) filename = 'test_colors_param_surf_arity3.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_plot_and_save_4(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') ### # Examples from the 'advanced' notebook ### # XXX: This raises the warning "The evaluation of the expression is # problematic. We are trying a failback method that may still work. Please # report this as a bug." It has to use the fallback because using evalf() # is the only way to evaluate the integral. We should perhaps just remove # that warning. with TemporaryDirectory(prefix='sympy_') as tmpdir: with warns( UserWarning, match="The evaluation of the expression is problematic"): i = Integral(log((sin(x)**2 + 1)*sqrt(x**2 + 1)), (x, 0, y)) p = plot(i, (y, 1, 5)) filename = 'test_advanced_integral.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_plot_and_save_5(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') with TemporaryDirectory(prefix='sympy_') as tmpdir: s = Sum(1/x**y, (x, 1, oo)) p = plot(s, (y, 2, 10)) filename = 'test_advanced_inf_sum.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(Sum(1/x, (x, 1, y)), (y, 2, 10), show=False) p[0].only_integers = True p[0].steps = True filename = 'test_advanced_fin_sum.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_plot_and_save_6(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') with TemporaryDirectory(prefix='sympy_') as tmpdir: filename = 'test.png' ### # Test expressions that can not be translated to np and generate complex # results. ### p = plot(sin(x) + I*cos(x)) p.save(os.path.join(tmpdir, filename)) p = plot(sqrt(sqrt(-x))) p.save(os.path.join(tmpdir, filename)) p = plot(LambertW(x)) p.save(os.path.join(tmpdir, filename)) p = plot(sqrt(LambertW(x))) p.save(os.path.join(tmpdir, filename)) #Characteristic function of a StudentT distribution with nu=10 x1 = 5 * x**2 * exp_polar(-I*pi)/2 m1 = meijerg(((1 / 2,), ()), ((5, 0, 1 / 2), ()), x1) x2 = 5*x**2 * exp_polar(I*pi)/2 m2 = meijerg(((1/2,), ()), ((5, 0, 1/2), ()), x2) expr = (m1 + m2) / (48 * pi) p = plot(expr, (x, 1e-6, 1e-2)) p.save(os.path.join(tmpdir, filename)) def test_plotgrid_and_save(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') with TemporaryDirectory(prefix='sympy_') as tmpdir: p1 = plot(x) p2 = plot_parametric((sin(x), cos(x)), (x, sin(x)), show=False) p3 = plot_parametric( cos(x), sin(x), adaptive=False, nb_of_points=500, show=False) p4 = plot3d_parametric_line(sin(x), cos(x), x, show=False) # symmetric grid p = PlotGrid(2, 2, p1, p2, p3, p4) filename = 'test_grid1.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # grid size greater than the number of subplots p = PlotGrid(3, 4, p1, p2, p3, p4) filename = 'test_grid2.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p5 = plot(cos(x),(x, -pi, pi), show=False) p5[0].line_color = lambda a: a p6 = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1), show=False) p7 = plot_contour( (x**2 + y**2, (x, -5, 5), (y, -5, 5)), (x**3 + y**3, (x, -3, 3), (y, -3, 3)), show=False) # unsymmetric grid (subplots in one line) p = PlotGrid(1, 3, p5, p6, p7) filename = 'test_grid3.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_append_issue_7140(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p1 = plot(x) p2 = plot(x**2) plot(x + 2) # append a series p2.append(p1[0]) assert len(p2._series) == 2 with raises(TypeError): p1.append(p2) with raises(TypeError): p1.append(p2._series) def test_issue_15265(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') eqn = sin(x) p = plot(eqn, xlim=(-S.Pi, S.Pi), ylim=(-1, 1)) p._backend.close() p = plot(eqn, xlim=(-1, 1), ylim=(-S.Pi, S.Pi)) p._backend.close() p = plot(eqn, xlim=(-1, 1), ylim=(sympify('-3.14'), sympify('3.14'))) p._backend.close() p = plot(eqn, xlim=(sympify('-3.14'), sympify('3.14')), ylim=(-1, 1)) p._backend.close() raises(ValueError, lambda: plot(eqn, xlim=(-S.ImaginaryUnit, 1), ylim=(-1, 1))) raises(ValueError, lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.ImaginaryUnit))) raises(ValueError, lambda: plot(eqn, xlim=(S.NegativeInfinity, 1), ylim=(-1, 1))) raises(ValueError, lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.Infinity))) def test_empty_Plot(): if not matplotlib: skip("Matplotlib not the default backend") # No exception showing an empty plot plot() p = Plot() p.show() def test_issue_17405(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') f = x**0.3 - 10*x**3 + x**2 p = plot(f, (x, -10, 10), show=False) # Random number of segments, probably more than 100, but we want to see # that there are segments generated, as opposed to when the bug was present assert len(p[0].get_segments()) >= 30 def test_logplot_PR_16796(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p = plot(x, (x, .001, 100), xscale='log', show=False) # Random number of segments, probably more than 100, but we want to see # that there are segments generated, as opposed to when the bug was present assert len(p[0].get_segments()) >= 30 assert p[0].end == 100.0 assert p[0].start == .001 def test_issue_16572(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p = plot(LambertW(x), show=False) # Random number of segments, probably more than 50, but we want to see # that there are segments generated, as opposed to when the bug was present assert len(p[0].get_segments()) >= 30 def test_issue_11865(): if not matplotlib: skip("Matplotlib not the default backend") k = Symbol('k', integer=True) f = Piecewise((-I*exp(I*pi*k)/k + I*exp(-I*pi*k)/k, Ne(k, 0)), (2*pi, True)) p = plot(f, show=False) # Random number of segments, probably more than 100, but we want to see # that there are segments generated, as opposed to when the bug was present # and that there are no exceptions. assert len(p[0].get_segments()) >= 30 def test_issue_11461(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p = plot(real_root((log(x/(x-2))), 3), show=False) # Random number of segments, probably more than 100, but we want to see # that there are segments generated, as opposed to when the bug was present # and that there are no exceptions. assert len(p[0].get_segments()) >= 30 def test_issue_11764(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p = plot_parametric(cos(x), sin(x), (x, 0, 2 * pi), aspect_ratio=(1,1), show=False) p.aspect_ratio == (1, 1) # Random number of segments, probably more than 100, but we want to see # that there are segments generated, as opposed to when the bug was present assert len(p[0].get_segments()) >= 30 def test_issue_13516(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') pm = plot(sin(x), backend="matplotlib", show=False) assert pm.backend == MatplotlibBackend assert len(pm[0].get_segments()) >= 30 pt = plot(sin(x), backend="text", show=False) assert pt.backend == TextBackend assert len(pt[0].get_segments()) >= 30 pd = plot(sin(x), backend="default", show=False) assert pd.backend == DefaultBackend assert len(pd[0].get_segments()) >= 30 p = plot(sin(x), show=False) assert p.backend == DefaultBackend assert len(p[0].get_segments()) >= 30 def test_plot_limits(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p = plot(x, x**2, (x, -10, 10)) backend = p._backend xmin, xmax = backend.ax[0].get_xlim() assert abs(xmin + 10) < 2 assert abs(xmax - 10) < 2 ymin, ymax = backend.ax[0].get_ylim() assert abs(ymin + 10) < 10 assert abs(ymax - 100) < 10 def test_plot3d_parametric_line_limits(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') v1 = (2*cos(x), 2*sin(x), 2*x, (x, -5, 5)) v2 = (sin(x), cos(x), x, (x, -5, 5)) p = plot3d_parametric_line(v1, v2) backend = p._backend xmin, xmax = backend.ax[0].get_xlim() assert abs(xmin + 2) < 1e-2 assert abs(xmax - 2) < 1e-2 ymin, ymax = backend.ax[0].get_ylim() assert abs(ymin + 2) < 1e-2 assert abs(ymax - 2) < 1e-2 zmin, zmax = backend.ax[0].get_zlim() assert abs(zmin + 10) < 1e-2 assert abs(zmax - 10) < 1e-2 p = plot3d_parametric_line(v2, v1) backend = p._backend xmin, xmax = backend.ax[0].get_xlim() assert abs(xmin + 2) < 1e-2 assert abs(xmax - 2) < 1e-2 ymin, ymax = backend.ax[0].get_ylim() assert abs(ymin + 2) < 1e-2 assert abs(ymax - 2) < 1e-2 zmin, zmax = backend.ax[0].get_zlim() assert abs(zmin + 10) < 1e-2 assert abs(zmax - 10) < 1e-2 def test_plot_size(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p1 = plot(sin(x), backend="matplotlib", size=(8, 4)) s1 = p1._backend.fig.get_size_inches() assert (s1[0] == 8) and (s1[1] == 4) p2 = plot(sin(x), backend="matplotlib", size=(5, 10)) s2 = p2._backend.fig.get_size_inches() assert (s2[0] == 5) and (s2[1] == 10) p3 = PlotGrid(2, 1, p1, p2, size=(6, 2)) s3 = p3._backend.fig.get_size_inches() assert (s3[0] == 6) and (s3[1] == 2) with raises(ValueError): plot(sin(x), backend="matplotlib", size=(-1, 3)) def test_issue_20113(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') # verify the capability to use custom backends with raises(TypeError): plot(sin(x), backend=Plot, show=False) p2 = plot(sin(x), backend=MatplotlibBackend, show=False) assert p2.backend == MatplotlibBackend assert len(p2[0].get_segments()) >= 30 p3 = plot(sin(x), backend=DummyBackendOk, show=False) assert p3.backend == DummyBackendOk assert len(p3[0].get_segments()) >= 30 # test for an improper coded backend p4 = plot(sin(x), backend=DummyBackendNotOk, show=False) assert p4.backend == DummyBackendNotOk assert len(p4[0].get_segments()) >= 30 with raises(NotImplementedError): p4.show() with raises(NotImplementedError): p4.save("test/path") with raises(NotImplementedError): p4._backend.close()
598d6a46dcae6f830325a662cf0e9c5d023934c1085c13bd50458f108f34696f
""" The module contains implemented functions for interval arithmetic.""" from functools import reduce from sympy.plotting.intervalmath import interval from sympy.external import import_module def Abs(x): if isinstance(x, (int, float)): return interval(abs(x)) elif isinstance(x, interval): if x.start < 0 and x.end > 0: return interval(0, max(abs(x.start), abs(x.end)), is_valid=x.is_valid) else: return interval(abs(x.start), abs(x.end)) else: raise NotImplementedError #Monotonic def exp(x): """evaluates the exponential of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): return interval(np.exp(x), np.exp(x)) elif isinstance(x, interval): return interval(np.exp(x.start), np.exp(x.end), is_valid=x.is_valid) else: raise NotImplementedError #Monotonic def log(x): """evaluates the natural logarithm of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): if x <= 0: return interval(-np.inf, np.inf, is_valid=False) else: return interval(np.log(x)) elif isinstance(x, interval): if not x.is_valid: return interval(-np.inf, np.inf, is_valid=x.is_valid) elif x.end <= 0: return interval(-np.inf, np.inf, is_valid=False) elif x.start <= 0: return interval(-np.inf, np.inf, is_valid=None) return interval(np.log(x.start), np.log(x.end)) else: raise NotImplementedError #Monotonic def log10(x): """evaluates the logarithm to the base 10 of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): if x <= 0: return interval(-np.inf, np.inf, is_valid=False) else: return interval(np.log10(x)) elif isinstance(x, interval): if not x.is_valid: return interval(-np.inf, np.inf, is_valid=x.is_valid) elif x.end <= 0: return interval(-np.inf, np.inf, is_valid=False) elif x.start <= 0: return interval(-np.inf, np.inf, is_valid=None) return interval(np.log10(x.start), np.log10(x.end)) else: raise NotImplementedError #Monotonic def atan(x): """evaluates the tan inverse of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): return interval(np.arctan(x)) elif isinstance(x, interval): start = np.arctan(x.start) end = np.arctan(x.end) return interval(start, end, is_valid=x.is_valid) else: raise NotImplementedError #periodic def sin(x): """evaluates the sine of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): return interval(np.sin(x)) elif isinstance(x, interval): if not x.is_valid: return interval(-1, 1, is_valid=x.is_valid) na, __ = divmod(x.start, np.pi / 2.0) nb, __ = divmod(x.end, np.pi / 2.0) start = min(np.sin(x.start), np.sin(x.end)) end = max(np.sin(x.start), np.sin(x.end)) if nb - na > 4: return interval(-1, 1, is_valid=x.is_valid) elif na == nb: return interval(start, end, is_valid=x.is_valid) else: if (na - 1) // 4 != (nb - 1) // 4: #sin has max end = 1 if (na - 3) // 4 != (nb - 3) // 4: #sin has min start = -1 return interval(start, end) else: raise NotImplementedError #periodic def cos(x): """Evaluates the cos of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): return interval(np.sin(x)) elif isinstance(x, interval): if not (np.isfinite(x.start) and np.isfinite(x.end)): return interval(-1, 1, is_valid=x.is_valid) na, __ = divmod(x.start, np.pi / 2.0) nb, __ = divmod(x.end, np.pi / 2.0) start = min(np.cos(x.start), np.cos(x.end)) end = max(np.cos(x.start), np.cos(x.end)) if nb - na > 4: #differ more than 2*pi return interval(-1, 1, is_valid=x.is_valid) elif na == nb: #in the same quadarant return interval(start, end, is_valid=x.is_valid) else: if (na) // 4 != (nb) // 4: #cos has max end = 1 if (na - 2) // 4 != (nb - 2) // 4: #cos has min start = -1 return interval(start, end, is_valid=x.is_valid) else: raise NotImplementedError def tan(x): """Evaluates the tan of an interval""" return sin(x) / cos(x) #Monotonic def sqrt(x): """Evaluates the square root of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): if x > 0: return interval(np.sqrt(x)) else: return interval(-np.inf, np.inf, is_valid=False) elif isinstance(x, interval): #Outside the domain if x.end < 0: return interval(-np.inf, np.inf, is_valid=False) #Partially outside the domain elif x.start < 0: return interval(-np.inf, np.inf, is_valid=None) else: return interval(np.sqrt(x.start), np.sqrt(x.end), is_valid=x.is_valid) else: raise NotImplementedError def imin(*args): """Evaluates the minimum of a list of intervals""" np = import_module('numpy') if not all(isinstance(arg, (int, float, interval)) for arg in args): return NotImplementedError else: new_args = [a for a in args if isinstance(a, (int, float)) or a.is_valid] if len(new_args) == 0: if all(a.is_valid is False for a in args): return interval(-np.inf, np.inf, is_valid=False) else: return interval(-np.inf, np.inf, is_valid=None) start_array = [a if isinstance(a, (int, float)) else a.start for a in new_args] end_array = [a if isinstance(a, (int, float)) else a.end for a in new_args] return interval(min(start_array), min(end_array)) def imax(*args): """Evaluates the maximum of a list of intervals""" np = import_module('numpy') if not all(isinstance(arg, (int, float, interval)) for arg in args): return NotImplementedError else: new_args = [a for a in args if isinstance(a, (int, float)) or a.is_valid] if len(new_args) == 0: if all(a.is_valid is False for a in args): return interval(-np.inf, np.inf, is_valid=False) else: return interval(-np.inf, np.inf, is_valid=None) start_array = [a if isinstance(a, (int, float)) else a.start for a in new_args] end_array = [a if isinstance(a, (int, float)) else a.end for a in new_args] return interval(max(start_array), max(end_array)) #Monotonic def sinh(x): """Evaluates the hyperbolic sine of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): return interval(np.sinh(x), np.sinh(x)) elif isinstance(x, interval): return interval(np.sinh(x.start), np.sinh(x.end), is_valid=x.is_valid) else: raise NotImplementedError def cosh(x): """Evaluates the hyperbolic cos of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): return interval(np.cosh(x), np.cosh(x)) elif isinstance(x, interval): #both signs if x.start < 0 and x.end > 0: end = max(np.cosh(x.start), np.cosh(x.end)) return interval(1, end, is_valid=x.is_valid) else: #Monotonic start = np.cosh(x.start) end = np.cosh(x.end) return interval(start, end, is_valid=x.is_valid) else: raise NotImplementedError #Monotonic def tanh(x): """Evaluates the hyperbolic tan of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): return interval(np.tanh(x), np.tanh(x)) elif isinstance(x, interval): return interval(np.tanh(x.start), np.tanh(x.end), is_valid=x.is_valid) else: raise NotImplementedError def asin(x): """Evaluates the inverse sine of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): #Outside the domain if abs(x) > 1: return interval(-np.inf, np.inf, is_valid=False) else: return interval(np.arcsin(x), np.arcsin(x)) elif isinstance(x, interval): #Outside the domain if x.is_valid is False or x.start > 1 or x.end < -1: return interval(-np.inf, np.inf, is_valid=False) #Partially outside the domain elif x.start < -1 or x.end > 1: return interval(-np.inf, np.inf, is_valid=None) else: start = np.arcsin(x.start) end = np.arcsin(x.end) return interval(start, end, is_valid=x.is_valid) def acos(x): """Evaluates the inverse cos of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): if abs(x) > 1: #Outside the domain return interval(-np.inf, np.inf, is_valid=False) else: return interval(np.arccos(x), np.arccos(x)) elif isinstance(x, interval): #Outside the domain if x.is_valid is False or x.start > 1 or x.end < -1: return interval(-np.inf, np.inf, is_valid=False) #Partially outside the domain elif x.start < -1 or x.end > 1: return interval(-np.inf, np.inf, is_valid=None) else: start = np.arccos(x.start) end = np.arccos(x.end) return interval(start, end, is_valid=x.is_valid) def ceil(x): """Evaluates the ceiling of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): return interval(np.ceil(x)) elif isinstance(x, interval): if x.is_valid is False: return interval(-np.inf, np.inf, is_valid=False) else: start = np.ceil(x.start) end = np.ceil(x.end) #Continuous over the interval if start == end: return interval(start, end, is_valid=x.is_valid) else: #Not continuous over the interval return interval(start, end, is_valid=None) else: return NotImplementedError def floor(x): """Evaluates the floor of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): return interval(np.floor(x)) elif isinstance(x, interval): if x.is_valid is False: return interval(-np.inf, np.inf, is_valid=False) else: start = np.floor(x.start) end = np.floor(x.end) #continuous over the argument if start == end: return interval(start, end, is_valid=x.is_valid) else: #not continuous over the interval return interval(start, end, is_valid=None) else: return NotImplementedError def acosh(x): """Evaluates the inverse hyperbolic cosine of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): #Outside the domain if x < 1: return interval(-np.inf, np.inf, is_valid=False) else: return interval(np.arccosh(x)) elif isinstance(x, interval): #Outside the domain if x.end < 1: return interval(-np.inf, np.inf, is_valid=False) #Partly outside the domain elif x.start < 1: return interval(-np.inf, np.inf, is_valid=None) else: start = np.arccosh(x.start) end = np.arccosh(x.end) return interval(start, end, is_valid=x.is_valid) else: return NotImplementedError #Monotonic def asinh(x): """Evaluates the inverse hyperbolic sine of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): return interval(np.arcsinh(x)) elif isinstance(x, interval): start = np.arcsinh(x.start) end = np.arcsinh(x.end) return interval(start, end, is_valid=x.is_valid) else: return NotImplementedError def atanh(x): """Evaluates the inverse hyperbolic tangent of an interval""" np = import_module('numpy') if isinstance(x, (int, float)): #Outside the domain if abs(x) >= 1: return interval(-np.inf, np.inf, is_valid=False) else: return interval(np.arctanh(x)) elif isinstance(x, interval): #outside the domain if x.is_valid is False or x.start >= 1 or x.end <= -1: return interval(-np.inf, np.inf, is_valid=False) #partly outside the domain elif x.start <= -1 or x.end >= 1: return interval(-np.inf, np.inf, is_valid=None) else: start = np.arctanh(x.start) end = np.arctanh(x.end) return interval(start, end, is_valid=x.is_valid) else: return NotImplementedError #Three valued logic for interval plotting. def And(*args): """Defines the three valued ``And`` behaviour for a 2-tuple of three valued logic values""" def reduce_and(cmp_intervala, cmp_intervalb): if cmp_intervala[0] is False or cmp_intervalb[0] is False: first = False elif cmp_intervala[0] is None or cmp_intervalb[0] is None: first = None else: first = True if cmp_intervala[1] is False or cmp_intervalb[1] is False: second = False elif cmp_intervala[1] is None or cmp_intervalb[1] is None: second = None else: second = True return (first, second) return reduce(reduce_and, args) def Or(*args): """Defines the three valued ``Or`` behaviour for a 2-tuple of three valued logic values""" def reduce_or(cmp_intervala, cmp_intervalb): if cmp_intervala[0] is True or cmp_intervalb[0] is True: first = True elif cmp_intervala[0] is None or cmp_intervalb[0] is None: first = None else: first = False if cmp_intervala[1] is True or cmp_intervalb[1] is True: second = True elif cmp_intervala[1] is None or cmp_intervalb[1] is None: second = None else: second = False return (first, second) return reduce(reduce_or, args)
e8202f49800222da6d7a1c90f009b45f2ba6b665fbf1681a825607ca4524a2f0
#!/usr/bin/env python import os import json from subprocess import check_output from collections import OrderedDict, defaultdict from collections.abc import Mapping import glob from contextlib import contextmanager from getpass import getpass import requests from requests_oauthlib import OAuth2 from requests.auth import HTTPBasicAuth def main(version, push=None): """ WARNING: If push is given as --push then this will push the release to github. """ push = push == '--push' _GitHub_release(version, push) def error(msg): raise ValueError(msg) def blue(text): return "\033[34m%s\033[0m" % text def red(text): return "\033[31m%s\033[0m" % text def green(text): return "\033[32m%s\033[0m" % text def _GitHub_release(version, push, username=None, user='sympy', token=None, token_file_path="~/.sympy/release-token", repo='sympy', draft=False): """ Upload the release files to GitHub. The tag must be pushed up first. You can test on another repo by changing user and repo. """ if not requests: error("requests and requests-oauthlib must be installed to upload to GitHub") release_text = GitHub_release_text(version) short_version = get_sympy_short_version(version) tag = 'sympy-' + version prerelease = short_version != version urls = URLs(user=user, repo=repo) if not username: username = input("GitHub username: ") token = load_token_file(token_file_path) if not token: username, password, token = GitHub_authenticate(urls, username, token) # If the tag in question is not pushed up yet, then GitHub will just # create it off of master automatically, which is not what we want. We # could make it create it off the release branch, but even then, we would # not be sure that the correct commit is tagged. So we require that the # tag exist first. if not check_tag_exists(version): sys.exit(red("The tag for this version has not been pushed yet. Cannot upload the release.")) # See https://developer.github.com/v3/repos/releases/#create-a-release # First, create the release post = {} post['tag_name'] = tag post['name'] = "SymPy " + version post['body'] = release_text post['draft'] = draft post['prerelease'] = prerelease print("Creating release for tag", tag, end=' ') if push: result = query_GitHub(urls.releases_url, username, password=None, token=token, data=json.dumps(post)).json() release_id = result['id'] else: print(green("Not pushing!")) print(green("Done")) # Then, upload all the files to it. for key in descriptions: tarball = get_tarball_name(key, version) params = {} params['name'] = tarball if tarball.endswith('gz'): headers = {'Content-Type':'application/gzip'} elif tarball.endswith('pdf'): headers = {'Content-Type':'application/pdf'} elif tarball.endswith('zip'): headers = {'Content-Type':'application/zip'} else: headers = {'Content-Type':'application/octet-stream'} print("Uploading", tarball, end=' ') sys.stdout.flush() with open(os.path.join('release/release-' + version, tarball), 'rb') as f: if push: result = query_GitHub(urls.release_uploads_url % release_id, username, password=None, token=token, data=f, params=params, headers=headers).json() else: print(green("Not uploading!")) print(green("Done")) # TODO: download the files and check that they have the right sha256 sum def GitHub_release_text(version): """ Generate text to put in the GitHub release Markdown box """ shortversion = get_sympy_short_version(version) htmltable = table(version) out = """\ See https://github.com/sympy/sympy/wiki/release-notes-for-{shortversion} for the release notes. {htmltable} **Note**: Do not download the **Source code (zip)** or the **Source code (tar.gz)** files below. """ out = out.format(shortversion=shortversion, htmltable=htmltable) print(blue("Here are the release notes to copy into the GitHub release " "Markdown form:")) print() print(out) return out def get_sympy_short_version(version): """ Get the short version of SymPy being released, not including any rc tags (like 0.7.3) """ parts = version.split('.') # Remove rc tags # Handle both 1.0.rc1 and 1.1rc1 if not parts[-1].isdigit(): if parts[-1][0].isdigit(): parts[-1] = parts[-1][0] else: parts.pop(-1) return '.'.join(parts) class URLs(object): """ This class contains URLs and templates which used in requests to GitHub API """ def __init__(self, user="sympy", repo="sympy", api_url="https://api.github.com", authorize_url="https://api.github.com/authorizations", uploads_url='https://uploads.github.com', main_url='https://github.com'): """Generates all URLs and templates""" self.user = user self.repo = repo self.api_url = api_url self.authorize_url = authorize_url self.uploads_url = uploads_url self.main_url = main_url self.pull_list_url = api_url + "/repos" + "/" + user + "/" + repo + "/pulls" self.issue_list_url = api_url + "/repos/" + user + "/" + repo + "/issues" self.releases_url = api_url + "/repos/" + user + "/" + repo + "/releases" self.single_issue_template = self.issue_list_url + "/%d" self.single_pull_template = self.pull_list_url + "/%d" self.user_info_template = api_url + "/users/%s" self.user_repos_template = api_url + "/users/%s/repos" self.issue_comment_template = (api_url + "/repos" + "/" + user + "/" + repo + "/issues/%d" + "/comments") self.release_uploads_url = (uploads_url + "/repos/" + user + "/" + repo + "/releases/%d" + "/assets") self.release_download_url = (main_url + "/" + user + "/" + repo + "/releases/download/%s/%s") def load_token_file(path="~/.sympy/release-token"): print("> Using token file %s" % path) path = os.path.expanduser(path) path = os.path.abspath(path) if os.path.isfile(path): try: with open(path) as f: token = f.readline() except IOError: print("> Unable to read token file") return else: print("> Token file does not exist") return return token.strip() def GitHub_authenticate(urls, username, token=None): _login_message = """\ Enter your GitHub username & password or press ^C to quit. The password will be kept as a Python variable as long as this script is running and https to authenticate with GitHub, otherwise not saved anywhere else:\ """ if username: print("> Authenticating as %s" % username) else: print(_login_message) username = input("Username: ") authenticated = False if token: print("> Authenticating using token") try: GitHub_check_authentication(urls, username, None, token) except AuthenticationFailed: print("> Authentication failed") else: print("> OK") password = None authenticated = True while not authenticated: password = getpass("Password: ") try: print("> Checking username and password ...") GitHub_check_authentication(urls, username, password, None) except AuthenticationFailed: print("> Authentication failed") else: print("> OK.") authenticated = True if password: generate = input("> Generate API token? [Y/n] ") if generate.lower() in ["y", "ye", "yes", ""]: name = input("> Name of token on GitHub? [SymPy Release] ") if name == "": name = "SymPy Release" token = generate_token(urls, username, password, name=name) print("Your token is", token) print("Use this token from now on as GitHub_release:token=" + token + ",username=" + username) print(red("DO NOT share this token with anyone")) save = input("Do you want to save this token to a file [yes]? ") if save.lower().strip() in ['y', 'yes', 'ye', '']: save_token_file(token) return username, password, token def run(*cmdline, cwd=None): """ Run command in subprocess and get lines of output """ return check_output(cmdline, encoding='utf-8', cwd=cwd).splitlines() def check_tag_exists(version): """ Check if the tag for this release has been uploaded yet. """ tag = 'sympy-' + version all_tag_lines = run('git', 'ls-remote', '--tags', 'origin') return any(tag in tag_line for tag_line in all_tag_lines) def generate_token(urls, username, password, OTP=None, name="SymPy Release"): enc_data = json.dumps( { "scopes": ["public_repo"], "note": name } ) url = urls.authorize_url rep = query_GitHub(url, username=username, password=password, data=enc_data).json() return rep["token"] def GitHub_check_authentication(urls, username, password, token): """ Checks that username & password is valid. """ query_GitHub(urls.api_url, username, password, token) class AuthenticationFailed(Exception): pass def query_GitHub(url, username=None, password=None, token=None, data=None, OTP=None, headers=None, params=None, files=None): """ Query GitHub API. In case of a multipage result, DOES NOT query the next page. """ headers = headers or {} if OTP: headers['X-GitHub-OTP'] = OTP if token: auth = OAuth2(client_id=username, token=dict(access_token=token, token_type='bearer')) else: auth = HTTPBasicAuth(username, password) if data: r = requests.post(url, auth=auth, data=data, headers=headers, params=params, files=files) else: r = requests.get(url, auth=auth, headers=headers, params=params, stream=True) if r.status_code == 401: two_factor = r.headers.get('X-GitHub-OTP') if two_factor: print("A two-factor authentication code is required:", two_factor.split(';')[1].strip()) OTP = input("Authentication code: ") return query_GitHub(url, username=username, password=password, token=token, data=data, OTP=OTP) raise AuthenticationFailed("invalid username or password") r.raise_for_status() return r def save_token_file(token): token_file = input("> Enter token file location [~/.sympy/release-token] ") token_file = token_file or "~/.sympy/release-token" token_file_expand = os.path.expanduser(token_file) token_file_expand = os.path.abspath(token_file_expand) token_folder, _ = os.path.split(token_file_expand) try: if not os.path.isdir(token_folder): os.mkdir(token_folder, 0o700) with open(token_file_expand, 'w') as f: f.write(token + '\n') os.chmod(token_file_expand, stat.S_IREAD | stat.S_IWRITE) except OSError as e: print("> Unable to create folder for token file: ", e) return except IOError as e: print("> Unable to save token file: ", e) return return token_file def table(version): """ Make an html table of the downloads. This is for pasting into the GitHub releases page. See GitHub_release(). """ tarball_formatter_dict = dict(_tarball_format(version)) shortversion = get_sympy_short_version(version) tarball_formatter_dict['version'] = shortversion sha256s = [i.split('\t') for i in _sha256(version, print_=False, local=True).split('\n')] sha256s_dict = {name: sha256 for sha256, name in sha256s} sizes = [i.split('\t') for i in _size(version, print_=False).split('\n')] sizes_dict = {name: size for size, name in sizes} table = [] # https://docs.python.org/2/library/contextlib.html#contextlib.contextmanager. Not # recommended as a real way to generate html, but it works better than # anything else I've tried. @contextmanager def tag(name): table.append("<%s>" % name) yield table.append("</%s>" % name) @contextmanager def a_href(link): table.append("<a href=\"%s\">" % link) yield table.append("</a>") with tag('table'): with tag('tr'): for headname in ["Filename", "Description", "size", "sha256"]: with tag("th"): table.append(headname) for key in descriptions: name = get_tarball_name(key, version) with tag('tr'): with tag('td'): with a_href('https://github.com/sympy/sympy/releases/download/sympy-%s/%s' % (version, name)): with tag('b'): table.append(name) with tag('td'): table.append(descriptions[key].format(**tarball_formatter_dict)) with tag('td'): table.append(sizes_dict[name]) with tag('td'): table.append(sha256s_dict[name]) out = ' '.join(table) return out descriptions = OrderedDict([ ('source', "The SymPy source installer.",), ('wheel', "A wheel of the package.",), ('html', '''Html documentation. This is the same as the <a href="https://docs.sympy.org/latest/index.html">online documentation</a>.''',), ('pdf', '''Pdf version of the <a href="https://docs.sympy.org/latest/index.html"> html documentation</a>.''',), ]) def _size(version, print_=True): """ Print the sizes of the release files. Run locally. """ out = run(*(['du', '-h'] + release_files(version))) out = [i.split() for i in out] out = '\n'.join(["%s\t%s" % (i, os.path.split(j)[1]) for i, j in out]) if print_: print(out) return out def _sha256(version, print_=True, local=False): if local: out = run(*(['shasum', '-a', '256'] + release_files(version))) else: raise ValueError('Should not get here...') out = run(*(['shasum', '-a', '256', '/root/release/*'])) # Remove the release/ part for printing. Useful for copy-pasting into the # release notes. out = [i.split() for i in out] out = '\n'.join(["%s\t%s" % (i, os.path.split(j)[1]) for i, j in out]) if print_: print(out) return out def get_tarball_name(file, version): """ Get the name of a tarball file should be one of source-orig: The original name of the source tarball source-orig-notar: The name of the untarred directory source: The source tarball (after renaming) wheel: The wheel html: The name of the html zip html-nozip: The name of the html, without ".zip" pdf-orig: The original name of the pdf file pdf: The name of the pdf file (after renaming) """ doctypename = defaultdict(str, {'html': 'zip', 'pdf': 'pdf'}) if file in {'source-orig', 'source'}: name = 'sympy-{version}.tar.gz' elif file == 'source-orig-notar': name = "sympy-{version}" elif file in {'html', 'pdf', 'html-nozip'}: name = "sympy-docs-{type}-{version}" if file == 'html-nozip': # zip files keep the name of the original zipped directory. See # https://github.com/sympy/sympy/issues/7087. file = 'html' else: name += ".{extension}" elif file == 'pdf-orig': name = "sympy-{version}.pdf" elif file == 'wheel': name = 'sympy-{version}-py3-none-any.whl' else: raise ValueError(file + " is not a recognized argument") ret = name.format(version=version, type=file, extension=doctypename[file]) return ret def release_files(version): """ Returns the list of local release files """ paths = glob.glob('release/release-' + version + '/*') if not paths: raise ValueError("No release files found") return paths tarball_name_types = { 'source-orig', 'source-orig-notar', 'source', 'wheel', 'html', 'html-nozip', 'pdf-orig', 'pdf', } # Have to make this lazy so that version can be defined. class _tarball_format(Mapping): def __init__(self, version): self.version = version def __getitem__(self, name): return get_tarball_name(name, self.version) def __iter__(self): return iter(tarball_name_types) def __len__(self): return len(tarball_name_types) if __name__ == "__main__": import sys main(*sys.argv[1:])
8421de24fed541fa06b3c9aab8fef0388016c6ccf406ec26253fd64ebbf869c8
#!/usr/bin/env python3 import os from pathlib import Path from subprocess import check_output def main(version, outdir): outdir = Path(outdir) build_files = [ outdir / f'sympy-{version}.pdf', outdir / f'sympy-{version}.tar.gz', outdir / f'sympy-{version}-py3-none-any.whl', outdir / f'sympy-docs-html-{version}.zip', ] out = check_output(['shasum', '-a', '256'] + build_files) out = out.decode('ascii') # Remove the release/ part for printing. Useful for copy-pasting into the # release notes. out = [i.split() for i in out.strip().split('\n')] out = '\n'.join(["%s\t%s" % (i, os.path.split(j)[1]) for i, j in out]) # Output to file and to screen with open(outdir / 'sha256.txt', 'w') as shafile: shafile.write(out) print(out) if __name__ == "__main__": import sys sys.exit(main(*sys.argv[1:]))
c31181d5778d25e5dac95da52e976255405653a5793c48c3d883a96dccde9f5f
#!/usr/bin/env python3 import os from os.path import dirname, join, basename, normpath from os import chdir import shutil from helpers import run ROOTDIR = dirname(dirname(__file__)) DOCSDIR = join(ROOTDIR, 'doc') def main(version, outputdir): os.makedirs(outputdir, exist_ok=True) build_html(DOCSDIR, outputdir, version) build_latex(DOCSDIR, outputdir, version) def build_html(docsdir, outputdir, version): run('make', 'clean', cwd=docsdir) run('make', 'html', cwd=docsdir) builddir = join(docsdir, '_build') docsname = 'sympy-docs-html-%s' % (version,) zipname = docsname + '.zip' cwd = os.getcwd() try: chdir(builddir) shutil.move('html', docsname) run('zip', '-9lr', zipname, docsname) finally: chdir(cwd) shutil.move(join(builddir, zipname), join(outputdir, zipname)) def build_latex(docsdir, outputdir, version): run('make', 'clean', cwd=docsdir) run('make', 'latex', cwd=docsdir) latexdir = join(docsdir, '_build', 'latex') env = os.environ.copy() env['LATEXMKOPTS'] = '-xelatex -silent' run('make', 'clean', cwd=latexdir, env=env) run('make', 'all', cwd=latexdir, env=env) filename = 'sympy-%s.pdf' % (version,) src = join('doc', '_build', 'latex', filename) dst = join(outputdir, filename) shutil.copyfile(src, dst) if __name__ == "__main__": import sys main(*sys.argv[1:])
a8ea2a5d33cd4e7a6987ccb21596645c184ab656bb3cc3f4e5c55d76a9d67118
#!/usr/bin/env python3 from subprocess import check_output import sys import os.path def main(tarname, gitroot): """Run this as ./compare_tar_against_git.py TARFILE GITROOT Args ==== TARFILE: Path to the built sdist (sympy-xx.tar.gz) GITROOT: Path ro root of git (dir containing .git) """ compare_tar_against_git(tarname, gitroot) ## TARBALL WHITELISTS # If a file does not end up in the tarball that should, add it to setup.py if # it is Python, or MANIFEST.in if it is not. (There is a command at the top # of setup.py to gather all the things that should be there). # TODO: Also check that this whitelist isn't growing out of date from files # removed from git. # Files that are in git that should not be in the tarball git_whitelist = { # Git specific dotfiles '.gitattributes', '.gitignore', '.mailmap', # Travis and CI '.travis.yml', '.github/workflows/runtests.yml', '.ci/durations.json', '.ci/generate_durations_log.sh', '.ci/parse_durations_log.py', '.ci/blacklisted.json', '.ci/README.rst', '.github/FUNDING.yml', '.editorconfig', '.coveragerc', 'CODEOWNERS', 'asv.conf.travis.json', 'coveragerc_travis', 'codecov.yml', 'pytest.ini', 'MANIFEST.in', # Code of conduct 'CODE_OF_CONDUCT.md', # Pull request template 'PULL_REQUEST_TEMPLATE.md', # Contributing guide 'CONTRIBUTING.md', # Nothing from bin/ should be shipped unless we intend to install it. Most # of this stuff is for development anyway. To run the tests from the # tarball, use setup.py test, or import sympy and run sympy.test() or # sympy.doctest(). 'bin/adapt_paths.py', 'bin/ask_update.py', 'bin/authors_update.py', 'bin/build_doc.sh', 'bin/coverage_doctest.py', 'bin/coverage_report.py', 'bin/deploy_doc.sh', 'bin/diagnose_imports', 'bin/doctest', 'bin/generate_module_list.py', 'bin/generate_test_list.py', 'bin/get_sympy.py', 'bin/mailmap_update.py', 'bin/py.bench', 'bin/strip_whitespace', 'bin/sympy_time.py', 'bin/sympy_time_cache.py', 'bin/test', 'bin/test_external_imports.py', 'bin/test_executable.py', 'bin/test_import', 'bin/test_import.py', 'bin/test_isolated', 'bin/test_py2_import.py', 'bin/test_setup.py', 'bin/test_submodule_imports.py', 'bin/test_travis.sh', # The notebooks are not ready for shipping yet. They need to be cleaned # up, and preferably doctested. See also # https://github.com/sympy/sympy/issues/6039. 'examples/advanced/identitysearch_example.ipynb', 'examples/beginner/plot_advanced.ipynb', 'examples/beginner/plot_colors.ipynb', 'examples/beginner/plot_discont.ipynb', 'examples/beginner/plot_gallery.ipynb', 'examples/beginner/plot_intro.ipynb', 'examples/intermediate/limit_examples_advanced.ipynb', 'examples/intermediate/schwarzschild.ipynb', 'examples/notebooks/density.ipynb', 'examples/notebooks/fidelity.ipynb', 'examples/notebooks/fresnel_integrals.ipynb', 'examples/notebooks/qubits.ipynb', 'examples/notebooks/sho1d_example.ipynb', 'examples/notebooks/spin.ipynb', 'examples/notebooks/trace.ipynb', 'examples/notebooks/Bezout_Dixon_resultant.ipynb', 'examples/notebooks/IntegrationOverPolytopes.ipynb', 'examples/notebooks/Macaulay_resultant.ipynb', 'examples/notebooks/Sylvester_resultant.ipynb', 'examples/notebooks/README.txt', # This stuff :) 'release/.gitignore', 'release/README.md', 'release/Vagrantfile', 'release/fabfile.py', 'release/Dockerfile', 'release/Dockerfile-base', 'release/release.sh', 'release/rever.xsh', 'release/pull_and_run_rever.sh', 'release/compare_tar_against_git.py', 'release/update_docs.py', 'release/aptinstall.sh', 'release/build_docs.py', 'release/github_release.py', 'release/helpers.py', 'release/releasecheck.py', 'release/requirements.txt', 'release/update_requirements.sh', 'release/test_install.py', 'release/sha256.py', 'release/authors.py', # This is just a distribute version of setup.py. Used mainly for setup.py # develop, which we don't care about in the release tarball 'setupegg.py', # pytest stuff 'conftest.py', # Encrypted deploy key for deploying dev docs to GitHub 'github_deploy_key.enc', } # Files that should be in the tarball should not be in git tarball_whitelist = { # Generated by setup.py. Contains metadata for PyPI. "PKG-INFO", # Generated by setuptools. More metadata. 'setup.cfg', 'sympy.egg-info/PKG-INFO', 'sympy.egg-info/SOURCES.txt', 'sympy.egg-info/dependency_links.txt', 'sympy.egg-info/requires.txt', 'sympy.egg-info/top_level.txt', 'sympy.egg-info/not-zip-safe', 'sympy.egg-info/entry_points.txt', # Not sure where this is generated from... 'doc/commit_hash.txt', } def blue(text): return "\033[34m%s\033[0m" % text def red(text): return "\033[31m%s\033[0m" % text def run(*cmdline, cwd=None): """ Run command in subprocess and get lines of output """ return check_output(cmdline, encoding='utf-8', cwd=cwd).splitlines() def full_path_split(path): """ Function to do a full split on a path. """ # Based on https://stackoverflow.com/a/13505966/161801 rest, tail = os.path.split(path) if not rest or rest == os.path.sep: return (tail,) return full_path_split(rest) + (tail,) def compare_tar_against_git(tarname, gitroot): """ Compare the contents of the tarball against git ls-files See the bottom of the file for the whitelists. """ git_lsfiles = set(i.strip() for i in run('git', 'ls-files', cwd=gitroot)) tar_output_orig = set(run('tar', 'tf', tarname)) tar_output = set() for file in tar_output_orig: # The tar files are like sympy-0.7.3/sympy/__init__.py, and the git # files are like sympy/__init__.py. split_path = full_path_split(file) if split_path[-1]: # Exclude directories, as git ls-files does not include them tar_output.add(os.path.join(*split_path[1:])) # print tar_output # print git_lsfiles fail = False print() print(blue("Files in the tarball from git that should not be there:")) print() for line in sorted(tar_output.intersection(git_whitelist)): fail = True print(line) print() print(blue("Files in git but not in the tarball:")) print() for line in sorted(git_lsfiles - tar_output - git_whitelist): fail = True print(line) print() print(blue("Files in the tarball but not in git:")) print() for line in sorted(tar_output - git_lsfiles - tarball_whitelist): fail = True print(line) print() if fail: sys.exit(red("Non-whitelisted files found or not found in the tarball")) if __name__ == "__main__": main(*sys.argv[1:])
55600221e23f085de3df0498792c597764220e9867e1165621e1c92db325b41d
""" 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, 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) 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, MutableDenseNDimArray, ImmutableDenseNDimArray, MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray, tensorproduct, tensorcontraction, 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', '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', # 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', 'MutableDenseNDimArray', 'ImmutableDenseNDimArray', 'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray', 'tensorproduct', 'tensorcontraction', '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', ])
ac7aa83aa6b72f1597beb0669e79b62c3995f489663046f9a8e9b0e5da23ddf9
__version__ = "1.7.1"
553be7043f928ec0e997ca66e464aef2227e20e535f1e921019ee84ab13c2322
import random import itertools from typing import Sequence as tSequence, Union as tUnion, List as tList, Tuple as tTuple from sympy import (Matrix, MatrixSymbol, S, Indexed, Basic, Tuple, Range, Set, And, Eq, FiniteSet, ImmutableMatrix, Integer, igcd, Lambda, Mul, Dummy, IndexedBase, Add, Interval, oo, linsolve, eye, Or, Not, Intersection, factorial, Contains, Union, Expr, Function, exp, cacheit, sqrt, pi, gamma, Ge, Piecewise, Symbol, NonSquareMatrixError, EmptySet, ceiling, MatrixBase, ConditionSet, ones, zeros, Identity) from sympy.core.relational import Relational from sympy.logic.boolalg import Boolean from sympy.utilities.exceptions import SymPyDeprecationWarning from sympy.utilities.iterables import strongly_connected_components from sympy.stats.joint_rv import JointDistribution from sympy.stats.joint_rv_types import JointDistributionHandmade from sympy.stats.rv import (RandomIndexedSymbol, random_symbols, RandomSymbol, _symbol_converter, _value_check, pspace, given, dependent, is_random, sample_iter) from sympy.stats.stochastic_process import StochasticPSpace from sympy.stats.symbolic_probability import Probability, Expectation from sympy.stats.frv_types import Bernoulli, BernoulliDistribution, FiniteRV from sympy.stats.drv_types import Poisson, PoissonDistribution from sympy.stats.crv_types import Normal, NormalDistribution, Gamma, GammaDistribution from sympy.core.sympify import _sympify, sympify __all__ = [ 'StochasticProcess', 'DiscreteTimeStochasticProcess', 'DiscreteMarkovChain', 'TransitionMatrixOf', 'StochasticStateSpaceOf', 'GeneratorMatrixOf', 'ContinuousMarkovChain', 'BernoulliProcess', 'PoissonProcess', 'WienerProcess', 'GammaProcess' ] @is_random.register(Indexed) def _(x): return is_random(x.base) @is_random.register(RandomIndexedSymbol) # type: ignore def _(x): return True def _set_converter(itr): """ Helper function for converting list/tuple/set to Set. If parameter is not an instance of list/tuple/set then no operation is performed. Returns ======= Set The argument converted to Set. Raises ====== TypeError If the argument is not an instance of list/tuple/set. """ if isinstance(itr, (list, tuple, set)): itr = FiniteSet(*itr) if not isinstance(itr, Set): raise TypeError("%s is not an instance of list/tuple/set."%(itr)) return itr def _state_converter(itr: tSequence) -> tUnion[Tuple, Range]: """ Helper function for converting list/tuple/set/Range/Tuple/FiniteSet to tuple/Range. """ if isinstance(itr, (Tuple, set, FiniteSet)): itr = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr)) elif isinstance(itr, (list, tuple)): # check if states are unique if len(set(itr)) != len(itr): raise ValueError('The state space must have unique elements.') itr = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr)) elif isinstance(itr, Range): # the only ordered set in sympy I know of # try to convert to tuple try: itr = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr)) except ValueError: pass else: raise TypeError("%s is not an instance of list/tuple/set/Range/Tuple/FiniteSet." % (itr)) return itr def _sym_sympify(arg): """ Converts an arbitrary expression to a type that can be used inside SymPy. As generally strings are unwise to use in the expressions, it returns the Symbol of argument if the string type argument is passed. Parameters ========= arg: The parameter to be converted to be used in Sympy. Returns ======= The converted parameter. """ if isinstance(arg, str): return Symbol(arg) else: return _sympify(arg) def _matrix_checks(matrix): if not isinstance(matrix, (Matrix, MatrixSymbol, ImmutableMatrix)): raise TypeError("Transition probabilities either should " "be a Matrix or a MatrixSymbol.") if matrix.shape[0] != matrix.shape[1]: raise NonSquareMatrixError("%s is not a square matrix"%(matrix)) if isinstance(matrix, Matrix): matrix = ImmutableMatrix(matrix.tolist()) return matrix class StochasticProcess(Basic): """ Base class for all the stochastic processes whether discrete or continuous. Parameters ========== sym: Symbol or str state_space: Set The state space of the stochastic process, by default S.Reals. For discrete sets it is zero indexed. See Also ======== DiscreteTimeStochasticProcess """ index_set = S.Reals def __new__(cls, sym, state_space=S.Reals, **kwargs): sym = _symbol_converter(sym) state_space = _set_converter(state_space) return Basic.__new__(cls, sym, state_space) @property def symbol(self): return self.args[0] @property def state_space(self) -> tUnion[FiniteSet, Range]: if not isinstance(self.args[1], (FiniteSet, Range)): return FiniteSet(*self.args[1]) return self.args[1] @property def distribution(self): return None def __call__(self, time): """ Overridden in ContinuousTimeStochasticProcess. """ raise NotImplementedError("Use [] for indexing discrete time stochastic process.") def __getitem__(self, time): """ Overridden in DiscreteTimeStochasticProcess. """ raise NotImplementedError("Use () for indexing continuous time stochastic process.") def probability(self, condition): raise NotImplementedError() def joint_distribution(self, *args): """ Computes the joint distribution of the random indexed variables. Parameters ========== args: iterable The finite list of random indexed variables/the key of a stochastic process whose joint distribution has to be computed. Returns ======= JointDistribution The joint distribution of the list of random indexed variables. An unevaluated object is returned if it is not possible to compute the joint distribution. Raises ====== ValueError: When the arguments passed are not of type RandomIndexSymbol or Number. """ args = list(args) for i, arg in enumerate(args): if S(arg).is_Number: if self.index_set.is_subset(S.Integers): args[i] = self.__getitem__(arg) else: args[i] = self.__call__(arg) elif not isinstance(arg, RandomIndexedSymbol): raise ValueError("Expected a RandomIndexedSymbol or " "key not %s"%(type(arg))) if args[0].pspace.distribution == None: # checks if there is any distribution available return JointDistribution(*args) pdf = Lambda(tuple(args), expr=Mul.fromiter(arg.pspace.process.density(arg) for arg in args)) return JointDistributionHandmade(pdf) def expectation(self, condition, given_condition): raise NotImplementedError("Abstract method for expectation queries.") def sample(self): raise NotImplementedError("Abstract method for sampling queries.") class DiscreteTimeStochasticProcess(StochasticProcess): """ Base class for all discrete stochastic processes. """ def __getitem__(self, time): """ For indexing discrete time stochastic processes. Returns ======= RandomIndexedSymbol """ if time not in self.index_set: raise IndexError("%s is not in the index set of %s"%(time, self.symbol)) idx_obj = Indexed(self.symbol, time) pspace_obj = StochasticPSpace(self.symbol, self, self.distribution) return RandomIndexedSymbol(idx_obj, pspace_obj) class ContinuousTimeStochasticProcess(StochasticProcess): """ Base class for all continuous time stochastic process. """ def __call__(self, time): """ For indexing continuous time stochastic processes. Returns ======= RandomIndexedSymbol """ if time not in self.index_set: raise IndexError("%s is not in the index set of %s"%(time, self.symbol)) func_obj = Function(self.symbol)(time) pspace_obj = StochasticPSpace(self.symbol, self, self.distribution) return RandomIndexedSymbol(func_obj, pspace_obj) class TransitionMatrixOf(Boolean): """ Assumes that the matrix is the transition matrix of the process. """ def __new__(cls, process, matrix): if not isinstance(process, DiscreteMarkovChain): raise ValueError("Currently only DiscreteMarkovChain " "support TransitionMatrixOf.") matrix = _matrix_checks(matrix) return Basic.__new__(cls, process, matrix) process = property(lambda self: self.args[0]) matrix = property(lambda self: self.args[1]) class GeneratorMatrixOf(TransitionMatrixOf): """ Assumes that the matrix is the generator matrix of the process. """ def __new__(cls, process, matrix): if not isinstance(process, ContinuousMarkovChain): raise ValueError("Currently only ContinuousMarkovChain " "support GeneratorMatrixOf.") matrix = _matrix_checks(matrix) return Basic.__new__(cls, process, matrix) class StochasticStateSpaceOf(Boolean): def __new__(cls, process, state_space): if not isinstance(process, (DiscreteMarkovChain, ContinuousMarkovChain)): raise ValueError("Currently only DiscreteMarkovChain and ContinuousMarkovChain " "support StochasticStateSpaceOf.") state_space = _state_converter(state_space) if isinstance(state_space, Range): ss_size = ceiling((state_space.stop - state_space.start) / state_space.step) else: ss_size = len(state_space) state_index = Range(ss_size) return Basic.__new__(cls, process, state_index) process = property(lambda self: self.args[0]) state_index = property(lambda self: self.args[1]) class MarkovProcess(StochasticProcess): """ Contains methods that handle queries common to Markov processes. """ @property def number_of_states(self) -> tUnion[Integer, Symbol]: """ The number of states in the Markov Chain. """ return _sympify(self.args[2].shape[0]) @property def _state_index(self) -> Range: """ Returns state index as Range. """ return self.args[1] @classmethod def _sanity_checks(cls, state_space, trans_probs): # Try to never have None as state_space or trans_probs. # This helps a lot if we get it done at the start. if (state_space is None) and (trans_probs is None): _n = Dummy('n', integer=True, nonnegative=True) state_space = _state_converter(Range(_n)) trans_probs = _matrix_checks(MatrixSymbol('_T', _n, _n)) elif state_space is None: trans_probs = _matrix_checks(trans_probs) state_space = _state_converter(Range(trans_probs.shape[0])) elif trans_probs is None: state_space = _state_converter(state_space) if isinstance(state_space, Range): _n = ceiling((state_space.stop - state_space.start) / state_space.step) else: _n = len(state_space) trans_probs = MatrixSymbol('_T', _n, _n) else: state_space = _state_converter(state_space) trans_probs = _matrix_checks(trans_probs) # Range object doesn't want to give a symbolic size # so we do it ourselves. if isinstance(state_space, Range): ss_size = ceiling((state_space.stop - state_space.start) / state_space.step) else: ss_size = len(state_space) if ss_size != trans_probs.shape[0]: raise ValueError('The size of the state space and the number of ' 'rows of the transition matrix must be the same.') return state_space, trans_probs def _extract_information(self, given_condition): """ Helper function to extract information, like, transition matrix/generator matrix, state space, etc. """ if isinstance(self, DiscreteMarkovChain): trans_probs = self.transition_probabilities state_index = self._state_index elif isinstance(self, ContinuousMarkovChain): trans_probs = self.generator_matrix state_index = self._state_index if isinstance(given_condition, And): gcs = given_condition.args given_condition = S.true for gc in gcs: if isinstance(gc, TransitionMatrixOf): trans_probs = gc.matrix if isinstance(gc, StochasticStateSpaceOf): state_index = gc.state_index if isinstance(gc, Relational): given_condition = given_condition & gc if isinstance(given_condition, TransitionMatrixOf): trans_probs = given_condition.matrix given_condition = S.true if isinstance(given_condition, StochasticStateSpaceOf): state_index = given_condition.state_index given_condition = S.true return trans_probs, state_index, given_condition def _check_trans_probs(self, trans_probs, row_sum=1): """ Helper function for checking the validity of transition probabilities. """ if not isinstance(trans_probs, MatrixSymbol): rows = trans_probs.tolist() for row in rows: if (sum(row) - row_sum) != 0: raise ValueError("Values in a row must sum to %s. " "If you are using Float or floats then please use Rational."%(row_sum)) def _work_out_state_index(self, state_index, given_condition, trans_probs): """ Helper function to extract state space if there is a random symbol in the given condition. """ # if given condition is None, then there is no need to work out # state_space from random variables if given_condition != None: rand_var = list(given_condition.atoms(RandomSymbol) - given_condition.atoms(RandomIndexedSymbol)) if len(rand_var) == 1: state_index = rand_var[0].pspace.set # `not None` is `True`. So the old test fails for symbolic sizes. # Need to build the statement differently. sym_cond = not isinstance(self.number_of_states, (int, Integer)) cond1 = not sym_cond and len(state_index) != trans_probs.shape[0] if cond1: raise ValueError("state space is not compatible with the transition probabilities.") if not isinstance(trans_probs.shape[0], Symbol): state_index = FiniteSet(*[i for i in range(trans_probs.shape[0])]) return state_index @cacheit def _preprocess(self, given_condition, evaluate): """ Helper function for pre-processing the information. """ is_insufficient = False if not evaluate: # avoid pre-processing if the result is not to be evaluated return (True, None, None, None) # extracting transition matrix and state space trans_probs, state_index, given_condition = self._extract_information(given_condition) # given_condition does not have sufficient information # for computations if trans_probs == None or \ given_condition == None: is_insufficient = True else: # checking transition probabilities if isinstance(self, DiscreteMarkovChain): self._check_trans_probs(trans_probs, row_sum=1) elif isinstance(self, ContinuousMarkovChain): self._check_trans_probs(trans_probs, row_sum=0) # working out state space state_index = self._work_out_state_index(state_index, given_condition, trans_probs) return is_insufficient, trans_probs, state_index, given_condition def replace_with_index(self, condition): if isinstance(condition, Relational): lhs, rhs = condition.lhs, condition.rhs if not isinstance(lhs, RandomIndexedSymbol): lhs, rhs = rhs, lhs condition = type(condition)(self.index_of.get(lhs, lhs), self.index_of.get(rhs, rhs)) return condition def probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Handles probability queries for Markov process. Parameters ========== condition: Relational given_condition: Relational/And Returns ======= Probability If the information is not sufficient. Expr In all other cases. Note ==== Any information passed at the time of query overrides any information passed at the time of object creation like transition probabilities, state space. Pass the transition matrix using TransitionMatrixOf, generator matrix using GeneratorMatrixOf and state space using StochasticStateSpaceOf in given_condition using & or And. """ check, mat, state_index, new_given_condition = \ self._preprocess(given_condition, evaluate) if check: return Probability(condition, new_given_condition) if isinstance(self, ContinuousMarkovChain): trans_probs = self.transition_probabilities(mat) elif isinstance(self, DiscreteMarkovChain): trans_probs = mat condition=self.replace_with_index(condition) given_condition=self.replace_with_index(given_condition) new_given_condition=self.replace_with_index(new_given_condition) if isinstance(condition, Relational): rv, states = (list(condition.atoms(RandomIndexedSymbol))[0], condition.as_set()) if isinstance(new_given_condition, And): gcs = new_given_condition.args else: gcs = (new_given_condition, ) grvs = new_given_condition.atoms(RandomIndexedSymbol) min_key_rv = None for grv in grvs: if grv.key <= rv.key: min_key_rv = grv if min_key_rv == None: return Probability(condition) prob, gstate = dict(), None for gc in gcs: if gc.has(min_key_rv): if gc.has(Probability): p, gp = (gc.rhs, gc.lhs) if isinstance(gc.lhs, Probability) \ else (gc.lhs, gc.rhs) gr = gp.args[0] gset = Intersection(gr.as_set(), state_index) gstate = list(gset)[0] prob[gset] = p else: _, gstate = (gc.lhs.key, gc.rhs) if isinstance(gc.lhs, RandomIndexedSymbol) \ else (gc.rhs.key, gc.lhs) if any((k not in self.index_set) for k in (rv.key, min_key_rv.key)): raise IndexError("The timestamps of the process are not in it's index set.") states = Intersection(states, state_index) if not isinstance(self.number_of_states, Symbol) else states for state in Union(states, FiniteSet(gstate)): if not isinstance(state, (int, Integer)) or Ge(state, mat.shape[0]) is True: raise IndexError("No information is available for (%s, %s) in " "transition probabilities of shape, (%s, %s). " "State space is zero indexed." %(gstate, state, mat.shape[0], mat.shape[1])) if prob: gstates = Union(*prob.keys()) if len(gstates) == 1: gstate = list(gstates)[0] gprob = list(prob.values())[0] prob[gstates] = gprob elif len(gstates) == len(state_index) - 1: gstate = list(state_index - gstates)[0] gprob = S.One - sum(prob.values()) prob[state_index - gstates] = gprob else: raise ValueError("Conflicting information.") else: gprob = S.One if min_key_rv == rv: return sum([prob[FiniteSet(state)] for state in states]) if isinstance(self, ContinuousMarkovChain): return gprob * sum([trans_probs(rv.key - min_key_rv.key).__getitem__((gstate, state)) for state in states]) if isinstance(self, DiscreteMarkovChain): return gprob * sum([(trans_probs**(rv.key - min_key_rv.key)).__getitem__((gstate, state)) for state in states]) if isinstance(condition, Not): expr = condition.args[0] return S.One - self.probability(expr, given_condition, evaluate, **kwargs) if isinstance(condition, And): compute_later, state2cond, conds = [], dict(), condition.args for expr in conds: if isinstance(expr, Relational): ris = list(expr.atoms(RandomIndexedSymbol))[0] if state2cond.get(ris, None) is None: state2cond[ris] = S.true state2cond[ris] &= expr else: compute_later.append(expr) ris = [] for ri in state2cond: ris.append(ri) cset = Intersection(state2cond[ri].as_set(), state_index) if len(cset) == 0: return S.Zero state2cond[ri] = cset.as_relational(ri) sorted_ris = sorted(ris, key=lambda ri: ri.key) prod = self.probability(state2cond[sorted_ris[0]], given_condition, evaluate, **kwargs) for i in range(1, len(sorted_ris)): ri, prev_ri = sorted_ris[i], sorted_ris[i-1] if not isinstance(state2cond[ri], Eq): raise ValueError("The process is in multiple states at %s, unable to determine the probability."%(ri)) mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat) prod *= self.probability(state2cond[ri], state2cond[prev_ri] & mat_of & StochasticStateSpaceOf(self, state_index), evaluate, **kwargs) for expr in compute_later: prod *= self.probability(expr, given_condition, evaluate, **kwargs) return prod if isinstance(condition, Or): return sum([self.probability(expr, given_condition, evaluate, **kwargs) for expr in condition.args]) raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been " "implemented yet."%(condition, given_condition)) def expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Handles expectation queries for markov process. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. Returns ======= Expectation Unevaluated object if computations cannot be done due to insufficient information. Expr In all other cases when the computations are successful. Note ==== Any information passed at the time of query overrides any information passed at the time of object creation like transition probabilities, state space. Pass the transition matrix using TransitionMatrixOf, generator matrix using GeneratorMatrixOf and state space using StochasticStateSpaceOf in given_condition using & or And. """ check, mat, state_index, condition = \ self._preprocess(condition, evaluate) if check: return Expectation(expr, condition) rvs = random_symbols(expr) if isinstance(expr, Expr) and isinstance(condition, Eq) \ and len(rvs) == 1: # handle queries similar to E(f(X[i]), Eq(X[i-m], <some-state>)) condition=self.replace_with_index(condition) state_index=self.replace_with_index(state_index) rv = list(rvs)[0] lhsg, rhsg = condition.lhs, condition.rhs if not isinstance(lhsg, RandomIndexedSymbol): lhsg, rhsg = (rhsg, lhsg) if rhsg not in state_index: raise ValueError("%s state is not in the state space."%(rhsg)) if rv.key < lhsg.key: raise ValueError("Incorrect given condition is given, expectation " "time %s < time %s"%(rv.key, rv.key)) mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat) cond = condition & mat_of & \ StochasticStateSpaceOf(self, state_index) func = lambda s: self.probability(Eq(rv, s), cond) * expr.subs(rv, self._state_index[s]) return sum([func(s) for s in state_index]) raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been " "implemented yet."%(expr, condition)) class DiscreteMarkovChain(DiscreteTimeStochasticProcess, MarkovProcess): """ Represents a finite discrete time-homogeneous Markov chain. This type of Markov Chain can be uniquely characterised by its (ordered) state space and its one-step transition probability matrix. Parameters ========== sym: The name given to the Markov Chain state_space: Optional, by default, Range(n) trans_probs: Optional, by default, MatrixSymbol('_T', n, n) Examples ======== >>> from sympy.stats import DiscreteMarkovChain, TransitionMatrixOf, P, E >>> from sympy import Matrix, MatrixSymbol, Eq, symbols >>> 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) >>> YS = DiscreteMarkovChain("Y") >>> Y.state_space FiniteSet(0, 1, 2) >>> Y.transition_probabilities Matrix([ [0.5, 0.2, 0.3], [0.2, 0.5, 0.3], [0.2, 0.3, 0.5]]) >>> TS = MatrixSymbol('T', 3, 3) >>> P(Eq(YS[3], 2), Eq(YS[1], 1) & TransitionMatrixOf(YS, TS)) T[0, 2]*T[1, 0] + T[1, 1]*T[1, 2] + T[1, 2]*T[2, 2] >>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2) 0.36 Probabilities will be calculated based on indexes rather than state names. For example, with the Sunny-Cloudy-Rainy model with string state names: >>> from sympy.core.symbol import Str >>> Y = DiscreteMarkovChain("Y", [Str('Sunny'), Str('Cloudy'), Str('Rainy')], T) >>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2) 0.36 This gives the same answer as the ``[0, 1, 2]`` state space. Currently, there is no support for state names within probability and expectation statements. Here is a work-around using ``Str``: >>> P(Eq(Str('Rainy'), Y[3]), Eq(Y[1], Str('Cloudy'))).round(2) 0.36 Symbol state names can also be used: >>> sunny, cloudy, rainy = symbols('Sunny, Cloudy, Rainy') >>> Y = DiscreteMarkovChain("Y", [sunny, cloudy, rainy], T) >>> P(Eq(Y[3], rainy), Eq(Y[1], cloudy)).round(2) 0.36 Expectations will be calculated as follows: >>> E(Y[3], Eq(Y[1], cloudy)) 0.38*Cloudy + 0.36*Rainy + 0.26*Sunny There is limited support for arbitrarily sized states: >>> n = symbols('n', nonnegative=True, integer=True) >>> T = MatrixSymbol('T', n, n) >>> Y = DiscreteMarkovChain("Y", trans_probs=T) >>> Y.state_space Range(0, n, 1) References ========== .. [1] https://en.wikipedia.org/wiki/Markov_chain#Discrete-time_Markov_chain .. [2] https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf """ index_set = S.Naturals0 def __new__(cls, sym, state_space=None, trans_probs=None): # type: (Basic, tUnion[str, Symbol], tSequence, tUnion[MatrixBase, MatrixSymbol]) -> DiscreteMarkovChain sym = _symbol_converter(sym) state_space, trans_probs = MarkovProcess._sanity_checks(state_space, trans_probs) obj = Basic.__new__(cls, sym, state_space, trans_probs) indices = dict() if isinstance(obj.number_of_states, Integer): for index, state in enumerate(obj._state_index): indices[state] = index obj.index_of = indices return obj @property def transition_probabilities(self) -> tUnion[MatrixBase, MatrixSymbol]: """ Transition probabilities of discrete Markov chain, either an instance of Matrix or MatrixSymbol. """ return self.args[2] def _transient2transient(self): """ Computes the one step probabilities of transient states to transient states. Used in finding fundamental matrix, absorbing probabilities. """ trans_probs = self.transition_probabilities if not isinstance(trans_probs, ImmutableMatrix): return None m = trans_probs.shape[0] trans_states = [i for i in range(m) if trans_probs[i, i] != 1] t2t = [[trans_probs[si, sj] for sj in trans_states] for si in trans_states] return ImmutableMatrix(t2t) def _transient2absorbing(self): """ Computes the one step probabilities of transient states to absorbing states. Used in finding fundamental matrix, absorbing probabilities. """ trans_probs = self.transition_probabilities if not isinstance(trans_probs, ImmutableMatrix): return None m, trans_states, absorb_states = \ trans_probs.shape[0], [], [] for i in range(m): if trans_probs[i, i] == 1: absorb_states.append(i) else: trans_states.append(i) if not absorb_states or not trans_states: return None t2a = [[trans_probs[si, sj] for sj in absorb_states] for si in trans_states] return ImmutableMatrix(t2a) def communication_classes(self) -> tList[tTuple[tList[Basic], Boolean, Integer]]: """ Returns the list of communication classes that partition the states of the markov chain. A communication class is defined to be a set of states such that every state in that set is reachable from every other state in that set. Due to its properties this forms a class in the mathematical sense. Communication classes are also known as recurrence classes. Returns ======= classes : List of Tuple of List, Boolean, Intger The ``classes`` are a list of tuples. Each tuple represents a single communication class with its properties. The first element in the tuple is the list of states in the class, the second element is whether the class is recurrent and the third element is the period of the communication class. Examples ======== >>> from sympy.stats import DiscreteMarkovChain >>> from sympy import Matrix >>> T = Matrix([[0, 1, 0], ... [1, 0, 0], ... [1, 0, 0]]) >>> X = DiscreteMarkovChain('X', [1, 2, 3], T) >>> classes = X.communication_classes() >>> for states, is_recurrent, period in classes: ... states, is_recurrent, period ([1, 2], True, 2) ([3], False, 1) From this we can see that states ``1`` and ``2`` communicate, are recurrent and have a period of 2. We can also see state ``3`` is transient with a period of 1. Notes ===== The algorithm used is of order ``O(n**2)`` where ``n`` is the number of states in the markov chain. It uses Tarjan's algorithm to find the classes themselves and then it uses a breadth-first search algorithm to find each class's periodicity. Most of the algorithm's components approach ``O(n)`` as the matrix becomes more and more sparse. References ========== .. [1] http://www.columbia.edu/~ww2040/4701Sum07/4701-06-Notes-MCII.pdf .. [2] http://cecas.clemson.edu/~shierd/Shier/markov.pdf .. [3] https://ujcontent.uj.ac.za/vital/access/services/Download/uj:7506/CONTENT1 .. [4] https://www.mathworks.com/help/econ/dtmc.classify.html """ n = self.number_of_states T = self.transition_probabilities # begin Tarjan's algorithm V = Range(n) # don't use state names. Rather use state # indexes since we use them for matrix # indexing here and later onward E = [(i, j) for i in V for j in V if T[i, j] != 0] classes = strongly_connected_components((V, E)) # end Tarjan's algorithm recurrence = [] periods = [] for class_ in classes: # begin recurrent check (similar to self._check_trans_probs()) submatrix = T[class_, class_] # get the submatrix with those states is_recurrent = S.true rows = submatrix.tolist() for row in rows: if (sum(row) - 1) != 0: is_recurrent = S.false break recurrence.append(is_recurrent) # end recurrent check # begin breadth-first search non_tree_edge_values = set() visited = {class_[0]} newly_visited = {class_[0]} level = {class_[0]: 0} current_level = 0 done = False # imitate a do-while loop while not done: # runs at most len(class_) times done = len(visited) == len(class_) current_level += 1 # this loop and the while loop above run a combined len(class_) number of times. # so this triple nested loop runs through each of the n states once. for i in newly_visited: # the loop below runs len(class_) number of times # complexity is around about O(n * avg(len(class_))) newly_visited = {j for j in class_ if T[i, j] != 0} new_tree_edges = newly_visited.difference(visited) for j in new_tree_edges: level[j] = current_level new_non_tree_edges = newly_visited.intersection(visited) new_non_tree_edge_values = {level[i]-level[j]+1 for j in new_non_tree_edges} non_tree_edge_values = non_tree_edge_values.union(new_non_tree_edge_values) visited = visited.union(new_tree_edges) # igcd needs at least 2 arguments g = igcd(len(class_), len(class_), *{val_e for val_e in non_tree_edge_values if val_e > 0}) periods.append(g) # end breadth-first search # convert back to the user's state names classes = [[self._state_index[i] for i in class_] for class_ in classes] return sympify(list(zip(classes, recurrence, periods))) def fundamental_matrix(self): Q = self._transient2transient() if Q == None: return None I = eye(Q.shape[0]) if (I - Q).det() == 0: raise ValueError("Fundamental matrix doesn't exists.") return ImmutableMatrix((I - Q).inv().tolist()) def absorbing_probabilities(self): """ Computes the absorbing probabilities, i.e., the ij-th entry of the matrix denotes the probability of Markov chain being absorbed in state j starting from state i. """ R = self._transient2absorbing() N = self.fundamental_matrix() if R == None or N == None: return None return N*R def absorbing_probabilites(self): SymPyDeprecationWarning( feature="absorbing_probabilites", useinstead="absorbing_probabilities", issue=20042, deprecated_since_version="1.7" ).warn() return self.absorbing_probabilities() def is_regular(self): w = self.fixed_row_vector() if w is None or isinstance(w, (Lambda)): return None return all((wi > 0) == True for wi in w.row(0)) def is_absorbing_state(self, state): trans_probs = self.transition_probabilities if isinstance(trans_probs, ImmutableMatrix) and \ state < trans_probs.shape[0]: return S(trans_probs[state, state]) is S.One def is_absorbing_chain(self): trans_probs = self.transition_probabilities return any(self.is_absorbing_state(state) == True for state in range(trans_probs.shape[0])) def stationary_distribution(self, condition_set=False) -> tUnion[ImmutableMatrix, ConditionSet, Lambda]: """ The stationary distribution is any row vector, p, that solves p = pP, is row stochastic and each element in p must be nonnegative. That means in matrix form: :math:`(P-I)^T p^T = 0` and :math:`(1, ..., 1) p = 1` where ``P`` is the one-step transition matrix. All time-homogeneous Markov Chains with a finite state space have at least one stationary distribution. In addition, if a finite time-homogeneous Markov Chain is irreducible, the stationary distribution is unique. Parameters ========== condition_set : bool If the chain has a symbolic size or transition matrix, it will return a ``Lambda`` if ``False`` and return a ``ConditionSet`` if ``True``. Examples ======== >>> from sympy.stats import DiscreteMarkovChain >>> from sympy import Matrix, S An irreducible Markov Chain >>> T = Matrix([[S(1)/2, S(1)/2, 0], ... [S(4)/5, S(1)/5, 0], ... [1, 0, 0]]) >>> X = DiscreteMarkovChain('X', trans_probs=T) >>> X.stationary_distribution() Matrix([[8/13, 5/13, 0]]) A reducible Markov Chain >>> T = Matrix([[S(1)/2, S(1)/2, 0], ... [S(4)/5, S(1)/5, 0], ... [0, 0, 1]]) >>> X = DiscreteMarkovChain('X', trans_probs=T) >>> X.stationary_distribution() Matrix([[8/13 - 8*tau0/13, 5/13 - 5*tau0/13, tau0]]) >>> Y = DiscreteMarkovChain('Y') >>> Y.stationary_distribution() Lambda((wm, _T), Eq(wm*_T, wm)) >>> Y.stationary_distribution(condition_set=True) ConditionSet(wm, Eq(wm*_T, wm)) References ========== .. [1] https://www.probabilitycourse.com/chapter11/11_2_6_stationary_and_limiting_distributions.php .. [2] https://galton.uchicago.edu/~yibi/teaching/stat317/2014/Lectures/Lecture4_6up.pdf See Also ======== sympy.stats.stochastic_process_types.DiscreteMarkovChain.limiting_distribution """ trans_probs = self.transition_probabilities n = self.number_of_states if n == 0: return ImmutableMatrix(Matrix([[]])) # symbolic matrix version if isinstance(trans_probs, MatrixSymbol): wm = MatrixSymbol('wm', 1, n) if condition_set: return ConditionSet(wm, Eq(wm * trans_probs, wm)) else: return Lambda((wm, trans_probs), Eq(wm * trans_probs, wm)) # numeric matrix version a = Matrix(trans_probs - Identity(n)).T a[0, 0:n] = ones(1, n) b = zeros(n, 1) b[0, 0] = 1 soln = list(linsolve((a, b)))[0] return ImmutableMatrix([[sol for sol in soln]]) def fixed_row_vector(self): """ A wrapper for ``stationary_distribution()``. """ return self.stationary_distribution() @property def limiting_distribution(self): """ The fixed row vector is the limiting distribution of a discrete Markov chain. """ return self.fixed_row_vector() def sample(self): """ Returns ======= sample: iterator object iterator object containing the sample """ if not isinstance(self.transition_probabilities, (Matrix, ImmutableMatrix)): raise ValueError("Transition Matrix must be provided for sampling") Tlist = self.transition_probabilities.tolist() samps = [random.choice(list(self.state_space))] yield samps[0] time = 1 densities = {} for state in self.state_space: states = list(self.state_space) densities[state] = {states[i]: Tlist[state][i] for i in range(len(states))} while time < S.Infinity: samps.append(next(sample_iter(FiniteRV("_", densities[samps[time - 1]])))) yield samps[time] time += 1 class ContinuousMarkovChain(ContinuousTimeStochasticProcess, MarkovProcess): """ Represents continuous time Markov chain. Parameters ========== sym: Symbol/str state_space: Set Optional, by default, S.Reals gen_mat: Matrix/ImmutableMatrix/MatrixSymbol Optional, by default, None Examples ======== >>> from sympy.stats import ContinuousMarkovChain >>> from sympy import Matrix, S >>> G = Matrix([[-S(1), S(1)], [S(1), -S(1)]]) >>> C = ContinuousMarkovChain('C', state_space=[0, 1], gen_mat=G) >>> C.limiting_distribution() Matrix([[1/2, 1/2]]) References ========== .. [1] https://en.wikipedia.org/wiki/Markov_chain#Continuous-time_Markov_chain .. [2] http://u.math.biu.ac.il/~amirgi/CTMCnotes.pdf """ index_set = S.Reals def __new__(cls, sym, state_space=None, gen_mat=None): sym = _symbol_converter(sym) state_space, gen_mat = MarkovProcess._sanity_checks(state_space, gen_mat) obj = Basic.__new__(cls, sym, state_space, gen_mat) indices = dict() if isinstance(obj.number_of_states, Integer): for index, state in enumerate(obj.state_space): indices[state] = index obj.index_of = indices return obj @property def generator_matrix(self): return self.args[2] @cacheit def transition_probabilities(self, gen_mat=None): t = Dummy('t') if isinstance(gen_mat, (Matrix, ImmutableMatrix)) and \ gen_mat.is_diagonalizable(): # for faster computation use diagonalized generator matrix Q, D = gen_mat.diagonalize() return Lambda(t, Q*exp(t*D)*Q.inv()) if gen_mat != None: return Lambda(t, exp(t*gen_mat)) def limiting_distribution(self): gen_mat = self.generator_matrix if gen_mat == None: return None if isinstance(gen_mat, MatrixSymbol): wm = MatrixSymbol('wm', 1, gen_mat.shape[0]) return Lambda((wm, gen_mat), Eq(wm*gen_mat, wm)) w = IndexedBase('w') wi = [w[i] for i in range(gen_mat.shape[0])] wm = Matrix([wi]) eqs = (wm*gen_mat).tolist()[0] eqs.append(sum(wi) - 1) soln = list(linsolve(eqs, wi))[0] return ImmutableMatrix([[sol for sol in soln]]) class BernoulliProcess(DiscreteTimeStochasticProcess): """ The Bernoulli process consists of repeated independent Bernoulli process trials with the same parameter `p`. It's assumed that the probability `p` applies to every trial and that the outcomes of each trial are independent of all the rest. Therefore Bernoulli Processs is Discrete State and Discrete Time Stochastic Process. Parameters ========== sym: Symbol/str success: Integer/str The event which is considered to be success, by default is 1. failure: Integer/str The event which is considered to be failure, by default is 0. p: Real Number between 0 and 1 Represents the probability of getting success. Examples ======== >>> from sympy.stats import BernoulliProcess, P, E >>> from sympy import Eq, Gt >>> B = BernoulliProcess("B", p=0.7, success=1, failure=0) >>> B.state_space FiniteSet(0, 1) >>> (B.p).round(2) 0.70 >>> B.success 1 >>> B.failure 0 >>> X = B[1] + B[2] + B[3] >>> P(Eq(X, 0)).round(2) 0.03 >>> P(Eq(X, 2)).round(2) 0.44 >>> P(Eq(X, 4)).round(2) 0 >>> P(Gt(X, 1)).round(2) 0.78 >>> P(Eq(B[1], 0) & Eq(B[2], 1) & Eq(B[3], 0) & Eq(B[4], 1)).round(2) 0.04 >>> B.joint_distribution(B[1], B[2]) JointDistributionHandmade(Lambda((B[1], B[2]), Piecewise((0.7, Eq(B[1], 1)), (0.3, Eq(B[1], 0)), (0, True))*Piecewise((0.7, Eq(B[2], 1)), (0.3, Eq(B[2], 0)), (0, True)))) >>> E(2*B[1] + B[2]).round(2) 2.10 >>> P(B[1] < 1).round(2) 0.30 References ========== .. [1] https://en.wikipedia.org/wiki/Bernoulli_process .. [2] https://mathcs.clarku.edu/~djoyce/ma217/bernoulli.pdf """ index_set = S.Naturals0 def __new__(cls, sym, p, success=1, failure=0): _value_check(p >= 0 and p <= 1, 'Value of p must be between 0 and 1.') sym = _symbol_converter(sym) p = _sympify(p) success = _sym_sympify(success) failure = _sym_sympify(failure) return Basic.__new__(cls, sym, p, success, failure) @property def symbol(self): return self.args[0] @property def p(self): return self.args[1] @property def success(self): return self.args[2] @property def failure(self): return self.args[3] @property def state_space(self): return _set_converter([self.success, self.failure]) @property def distribution(self): return BernoulliDistribution(self.p) def simple_rv(self, rv): return Bernoulli(rv.name, p=self.p, succ=self.success, fail=self.failure) def expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Computes expectation. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. Returns ======= Expectation of the RandomIndexedSymbol. """ return _SubstituteRV._expectation(expr, condition, evaluate, **kwargs) def probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Computes probability. Parameters ========== condition: Relational Condition for which probability has to be computed. Must contain a RandomIndexedSymbol of the process. given_condition: Relational/And The given conditions under which computations should be done. Returns ======= Probability of the condition. """ return _SubstituteRV._probability(condition, given_condition, evaluate, **kwargs) def density(self, x): return Piecewise((self.p, Eq(x, self.success)), (1 - self.p, Eq(x, self.failure)), (S.Zero, True)) class _SubstituteRV: """ Internal class to handle the queries of expectation and probability by substitution. """ @staticmethod def _rvindexed_subs(expr, condition=None): """ Substitutes the RandomIndexedSymbol with the RandomSymbol with same name, distribution and probability as RandomIndexedSymbol. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. """ rvs_expr = random_symbols(expr) if len(rvs_expr) != 0: swapdict_expr = {} for rv in rvs_expr: if isinstance(rv, RandomIndexedSymbol): newrv = rv.pspace.process.simple_rv(rv) # substitute with equivalent simple rv swapdict_expr[rv] = newrv expr = expr.subs(swapdict_expr) rvs_cond = random_symbols(condition) if len(rvs_cond)!=0: swapdict_cond = {} for rv in rvs_cond: if isinstance(rv, RandomIndexedSymbol): newrv = rv.pspace.process.simple_rv(rv) swapdict_cond[rv] = newrv condition = condition.subs(swapdict_cond) return expr, condition @classmethod def _expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Internal method for computing expectation of indexed RV. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. Returns ======= Expectation of the RandomIndexedSymbol. """ new_expr, new_condition = self._rvindexed_subs(expr, condition) if not is_random(new_expr): return new_expr new_pspace = pspace(new_expr) if new_condition is not None: new_expr = given(new_expr, new_condition) if new_expr.is_Add: # As E is Linear return Add(*[new_pspace.compute_expectation( expr=arg, evaluate=evaluate, **kwargs) for arg in new_expr.args]) return new_pspace.compute_expectation( new_expr, evaluate=evaluate, **kwargs) @classmethod def _probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Internal method for computing probability of indexed RV Parameters ========== condition: Relational Condition for which probability has to be computed. Must contain a RandomIndexedSymbol of the process. given_condition: Relational/And The given conditions under which computations should be done. Returns ======= Probability of the condition. """ new_condition, new_givencondition = self._rvindexed_subs(condition, given_condition) if isinstance(new_givencondition, RandomSymbol): condrv = random_symbols(new_condition) if len(condrv) == 1 and condrv[0] == new_givencondition: return BernoulliDistribution(self._probability(new_condition), 0, 1) if any([dependent(rv, new_givencondition) for rv in condrv]): return Probability(new_condition, new_givencondition) else: return self._probability(new_condition) if new_givencondition is not None and \ not isinstance(new_givencondition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (new_givencondition)) if new_givencondition == False or new_condition == False: return S.Zero if new_condition == True: return S.One if not isinstance(new_condition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (new_condition)) if new_givencondition is not None: # If there is a condition # Recompute on new conditional expr return self._probability(given(new_condition, new_givencondition, **kwargs), **kwargs) result = pspace(new_condition).probability(new_condition, **kwargs) if evaluate and hasattr(result, 'doit'): return result.doit() else: return result def get_timerv_swaps(expr, condition): """ Finds the appropriate interval for each time stamp in expr by parsing the given condition and returns intervals for each timestamp and dictionary that maps variable time-stamped Random Indexed Symbol to its corresponding Random Indexed variable with fixed time stamp. Parameters ========== expr: Sympy Expression Expression containing Random Indexed Symbols with variable time stamps condition: Relational/Boolean Expression Expression containing time bounds of variable time stamps in expr Examples ======== >>> from sympy.stats.stochastic_process_types import get_timerv_swaps, PoissonProcess >>> from sympy import symbols, Contains, Interval >>> x, t, d = symbols('x t d', positive=True) >>> X = PoissonProcess("X", 3) >>> get_timerv_swaps(x*X(t), Contains(t, Interval.Lopen(0, 1))) ([Interval.Lopen(0, 1)], {X(t): X(1)}) >>> get_timerv_swaps((X(t)**2 + X(d)**2), Contains(t, Interval.Lopen(0, 1)) ... & Contains(d, Interval.Ropen(1, 4))) # doctest: +SKIP ([Interval.Ropen(1, 4), Interval.Lopen(0, 1)], {X(d): X(3), X(t): X(1)}) Returns ======= intervals: list List of Intervals/FiniteSet on which each time stamp is defined rv_swap: dict Dictionary mapping variable time Random Indexed Symbol to constant time Random Indexed Variable """ if not isinstance(condition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (condition)) expr_syms = list(expr.atoms(RandomIndexedSymbol)) if isinstance(condition, (And, Or)): given_cond_args = condition.args else: # single condition given_cond_args = (condition, ) rv_swap = {} intervals = [] for expr_sym in expr_syms: for arg in given_cond_args: if arg.has(expr_sym.key) and isinstance(expr_sym.key, Symbol): intv = _set_converter(arg.args[1]) diff_key = intv._sup - intv._inf if diff_key == oo: raise ValueError("%s should have finite bounds" % str(expr_sym.name)) elif diff_key == S.Zero: # has singleton set diff_key = intv._sup rv_swap[expr_sym] = expr_sym.subs({expr_sym.key: diff_key}) intervals.append(intv) return intervals, rv_swap class CountingProcess(ContinuousTimeStochasticProcess): """ This class handles the common methods of the Counting Processes such as Poisson, Wiener and Gamma Processes """ index_set = _set_converter(Interval(0, oo)) @property def symbol(self): return self.args[0] def expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Computes expectation Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Boolean The given conditions under which computations should be done, i.e, the intervals on which each variable time stamp in expr is defined Returns ======= Expectation of the given expr """ if condition is not None: intervals, rv_swap = get_timerv_swaps(expr, condition) # they are independent when they have non-overlapping intervals if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet for intv_comb in itertools.combinations(intervals, 2)): if expr.is_Add: return Add.fromiter(self.expectation(arg, condition) for arg in expr.args) expr = expr.subs(rv_swap) else: return Expectation(expr, condition) return _SubstituteRV._expectation(expr, evaluate=evaluate, **kwargs) def _solve_argwith_tworvs(self, arg): if arg.args[0].key >= arg.args[1].key or isinstance(arg, Eq): diff_key = abs(arg.args[0].key - arg.args[1].key) rv = arg.args[0] arg = arg.__class__(rv.pspace.process(diff_key), 0) else: diff_key = arg.args[1].key - arg.args[0].key rv = arg.args[1] arg = arg.__class__(rv.pspace.process(diff_key), 0) return arg def _solve_numerical(self, condition, given_condition=None): if isinstance(condition, And): args_list = list(condition.args) else: args_list = [condition] if given_condition is not None: if isinstance(given_condition, And): args_list.extend(list(given_condition.args)) else: args_list.extend([given_condition]) # sort the args based on timestamp to get the independent increments in # each segment using all the condition args as well as given_condition args args_list = sorted(args_list, key=lambda x: x.args[0].key) result = [] cond_args = list(condition.args) if isinstance(condition, And) else [condition] if args_list[0] in cond_args and not (is_random(args_list[0].args[0]) and is_random(args_list[0].args[1])): result.append(_SubstituteRV._probability(args_list[0])) if is_random(args_list[0].args[0]) and is_random(args_list[0].args[1]): arg = self._solve_argwith_tworvs(args_list[0]) result.append(_SubstituteRV._probability(arg)) for i in range(len(args_list) - 1): curr, nex = args_list[i], args_list[i + 1] diff_key = nex.args[0].key - curr.args[0].key working_set = curr.args[0].pspace.process.state_space if curr.args[1] > nex.args[1]: #impossible condition so return 0 result.append(0) break if isinstance(curr, Eq): working_set = Intersection(working_set, Interval.Lopen(curr.args[1], oo)) else: working_set = Intersection(working_set, curr.as_set()) if isinstance(nex, Eq): working_set = Intersection(working_set, Interval(-oo, nex.args[1])) else: working_set = Intersection(working_set, nex.as_set()) if working_set == EmptySet: rv = Eq(curr.args[0].pspace.process(diff_key), 0) result.append(_SubstituteRV._probability(rv)) else: if working_set.is_finite_set: if isinstance(curr, Eq) and isinstance(nex, Eq): rv = Eq(curr.args[0].pspace.process(diff_key), len(working_set)) result.append(_SubstituteRV._probability(rv)) elif isinstance(curr, Eq) ^ isinstance(nex, Eq): result.append(Add.fromiter(_SubstituteRV._probability(Eq( curr.args[0].pspace.process(diff_key), x)) for x in range(len(working_set)))) else: n = len(working_set) result.append(Add.fromiter((n - x)*_SubstituteRV._probability(Eq( curr.args[0].pspace.process(diff_key), x)) for x in range(n))) else: result.append(_SubstituteRV._probability( curr.args[0].pspace.process(diff_key) <= working_set._sup - working_set._inf)) return Mul.fromiter(result) def probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Computes probability Parameters ========== condition: Relational Condition for which probability has to be computed. Must contain a RandomIndexedSymbol of the process. given_condition: Relational, Boolean The given conditions under which computations should be done, i.e, the intervals on which each variable time stamp in expr is defined Returns ======= Probability of the condition """ check_numeric = True if isinstance(condition, (And, Or)): cond_args = condition.args else: cond_args = (condition, ) # check that condition args are numeric or not if not all(arg.args[0].key.is_number for arg in cond_args): check_numeric = False if given_condition is not None: check_given_numeric = True if isinstance(given_condition, (And, Or)): given_cond_args = given_condition.args else: given_cond_args = (given_condition, ) # check that given condition args are numeric or not if given_condition.has(Contains): check_given_numeric = False # Handle numerical queries if check_numeric and check_given_numeric: res = [] if isinstance(condition, Or): res.append(Add.fromiter(self._solve_numerical(arg, given_condition) for arg in condition.args)) if isinstance(given_condition, Or): res.append(Add.fromiter(self._solve_numerical(condition, arg) for arg in given_condition.args)) if res: return Add.fromiter(res) return self._solve_numerical(condition, given_condition) # No numeric queries, go by Contains?... then check that all the # given condition are in form of `Contains` if not all(arg.has(Contains) for arg in given_cond_args): raise ValueError("If given condition is passed with `Contains`, then " "please pass the evaluated condition with its corresponding information " "in terms of intervals of each time stamp to be passed in given condition.") intervals, rv_swap = get_timerv_swaps(condition, given_condition) # they are independent when they have non-overlapping intervals if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet for intv_comb in itertools.combinations(intervals, 2)): if isinstance(condition, And): return Mul.fromiter(self.probability(arg, given_condition) for arg in condition.args) elif isinstance(condition, Or): return Add.fromiter(self.probability(arg, given_condition) for arg in condition.args) condition = condition.subs(rv_swap) else: return Probability(condition, given_condition) if check_numeric: return self._solve_numerical(condition) return _SubstituteRV._probability(condition, evaluate=evaluate, **kwargs) class PoissonProcess(CountingProcess): """ The Poisson process is a counting process. It is usually used in scenarios where we are counting the occurrences of certain events that appear to happen at a certain rate, but completely at random. Parameters ========== sym: Symbol/str lamda: Positive number Rate of the process, ``lamda > 0`` Examples ======== >>> from sympy.stats import PoissonProcess, P, E >>> from sympy import symbols, Eq, Ne, Contains, Interval >>> X = PoissonProcess("X", lamda=3) >>> X.state_space Naturals0 >>> X.lamda 3 >>> t1, t2 = symbols('t1 t2', positive=True) >>> P(X(t1) < 4) (9*t1**3/2 + 9*t1**2/2 + 3*t1 + 1)*exp(-3*t1) >>> P(Eq(X(t1), 2) | Ne(X(t1), 4), Contains(t1, Interval.Ropen(2, 4))) 1 - 36*exp(-6) >>> P(Eq(X(t1), 2) & Eq(X(t2), 3), Contains(t1, Interval.Lopen(0, 2)) ... & Contains(t2, Interval.Lopen(2, 4))) 648*exp(-12) >>> E(X(t1)) 3*t1 >>> E(X(t1)**2 + 2*X(t2), Contains(t1, Interval.Lopen(0, 1)) ... & Contains(t2, Interval.Lopen(1, 2))) 18 >>> P(X(3) < 1, Eq(X(1), 0)) exp(-6) >>> P(Eq(X(4), 3), Eq(X(2), 3)) exp(-6) >>> P(X(2) <= 3, X(1) > 1) 5*exp(-3) Merging two Poisson Processes >>> Y = PoissonProcess("Y", lamda=4) >>> Z = X + Y >>> Z.lamda 7 Splitting a Poisson Process into two independent Poisson Processes >>> N, M = Z.split(l1=2, l2=5) >>> N.lamda, M.lamda (2, 5) References ========== .. [1] https://www.probabilitycourse.com/chapter11/11_0_0_intro.php .. [2] https://en.wikipedia.org/wiki/Poisson_point_process """ def __new__(cls, sym, lamda): _value_check(lamda > 0, 'lamda should be a positive number.') sym = _symbol_converter(sym) lamda = _sympify(lamda) return Basic.__new__(cls, sym, lamda) @property def lamda(self): return self.args[1] @property def state_space(self): return S.Naturals0 def distribution(self, rv): return PoissonDistribution(self.lamda*rv.key) def density(self, x): return (self.lamda*x.key)**x / factorial(x) * exp(-(self.lamda*x.key)) def simple_rv(self, rv): return Poisson(rv.name, lamda=self.lamda*rv.key) def __add__(self, other): if not isinstance(other, PoissonProcess): raise ValueError("Only instances of Poisson Process can be merged") return PoissonProcess(Dummy(self.symbol.name + other.symbol.name), self.lamda + other.lamda) def split(self, l1, l2): if _sympify(l1 + l2) != self.lamda: raise ValueError("Sum of l1 and l2 should be %s" % str(self.lamda)) return PoissonProcess(Dummy("l1"), l1), PoissonProcess(Dummy("l2"), l2) class WienerProcess(CountingProcess): """ The Wiener process is a real valued continuous-time stochastic process. In physics it is used to study Brownian motion and therefore also known as Brownian Motion. Parameters ========== sym: Symbol/str Examples ======== >>> from sympy.stats import WienerProcess, P, E >>> from sympy import symbols, Contains, Interval >>> X = WienerProcess("X") >>> X.state_space Reals >>> t1, t2 = symbols('t1 t2', positive=True) >>> P(X(t1) < 7).simplify() erf(7*sqrt(2)/(2*sqrt(t1)))/2 + 1/2 >>> P((X(t1) > 2) | (X(t1) < 4), Contains(t1, Interval.Ropen(2, 4))).simplify() -erf(1)/2 + erf(2)/2 + 1 >>> E(X(t1)) 0 >>> E(X(t1) + 2*X(t2), Contains(t1, Interval.Lopen(0, 1)) ... & Contains(t2, Interval.Lopen(1, 2))) 0 References ========== .. [1] https://www.probabilitycourse.com/chapter11/11_4_0_brownian_motion_wiener_process.php .. [2] https://en.wikipedia.org/wiki/Wiener_process """ def __new__(cls, sym): sym = _symbol_converter(sym) return Basic.__new__(cls, sym) @property def state_space(self): return S.Reals def distribution(self, rv): return NormalDistribution(0, sqrt(rv.key)) def density(self, x): return exp(-x**2/(2*x.key)) / (sqrt(2*pi)*sqrt(x.key)) def simple_rv(self, rv): return Normal(rv.name, 0, sqrt(rv.key)) class GammaProcess(CountingProcess): """ A Gamma process is a random process with independent gamma distributed increments. It is a pure-jump increasing Levy process. Parameters ========== sym: Symbol/str lamda: Positive number Jump size of the process, ``lamda > 0`` gamma: Positive number Rate of jump arrivals, ``gamma > 0`` Examples ======== >>> from sympy.stats import GammaProcess, E, P, variance >>> from sympy import symbols, Contains, Interval, Not >>> t, d, x, l, g = symbols('t d x l g', positive=True) >>> X = GammaProcess("X", l, g) >>> E(X(t)) g*t/l >>> variance(X(t)).simplify() g*t/l**2 >>> X = GammaProcess('X', 1, 2) >>> P(X(t) < 1).simplify() lowergamma(2*t, 1)/gamma(2*t) >>> P(Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) & ... Contains(d, Interval.Lopen(7, 8))).simplify() -4*exp(-3) + 472*exp(-8)/3 + 1 >>> E(X(2) + x*E(X(5))) 10*x + 4 References ========== .. [1] https://en.wikipedia.org/wiki/Gamma_process """ def __new__(cls, sym, lamda, gamma): _value_check(lamda > 0, 'lamda should be a positive number') _value_check(gamma > 0, 'gamma should be a positive number') sym = _symbol_converter(sym) gamma = _sympify(gamma) lamda = _sympify(lamda) return Basic.__new__(cls, sym, lamda, gamma) @property def lamda(self): return self.args[1] @property def gamma(self): return self.args[2] @property def state_space(self): return _set_converter(Interval(0, oo)) def distribution(self, rv): return GammaDistribution(self.gamma*rv.key, 1/self.lamda) def density(self, x): k = self.gamma*x.key theta = 1/self.lamda return x**(k - 1) * exp(-x/theta) / (gamma(k)*theta**k) def simple_rv(self, rv): return Gamma(rv.name, self.gamma*rv.key, 1/self.lamda)
f95318ffcaff0c8e64ffb5628e11d45c86feda7a0b2f18cff8278a4c4e100744
from sympy import S, Basic, exp, multigamma, pi from sympy.core.sympify import sympify, _sympify from sympy.matrices import (ImmutableMatrix, Inverse, Trace, Determinant, MatrixSymbol, MatrixBase, Transpose, MatrixSet, matrix2numpy) from sympy.stats.rv import (_value_check, RandomMatrixSymbol, NamedArgsMixin, PSpace, _symbol_converter, MatrixDomain) from sympy.external import import_module ################################################################################ #------------------------Matrix Probability Space------------------------------# ################################################################################ class MatrixPSpace(PSpace): """ Represents probability space for Matrix Distributions """ def __new__(cls, sym, distribution, dim_n, dim_m): sym = _symbol_converter(sym) dim_n, dim_m = _sympify(dim_n), _sympify(dim_m) if not (dim_n.is_integer and dim_m.is_integer): raise ValueError("Dimensions should be integers") return Basic.__new__(cls, sym, distribution, dim_n, dim_m) distribution = property(lambda self: self.args[1]) symbol = property(lambda self: self.args[0]) @property def domain(self): return MatrixDomain(self.symbol, self.distribution.set) @property def value(self): return RandomMatrixSymbol(self.symbol, self.args[2], self.args[3], self) @property def values(self): return {self.value} def compute_density(self, expr, *args): rms = expr.atoms(RandomMatrixSymbol) if len(rms) > 1 or (not isinstance(expr, RandomMatrixSymbol)): raise NotImplementedError("Currently, no algorithm has been " "implemented to handle general expressions containing " "multiple matrix distributions.") return self.distribution.pdf(expr) def sample(self, size=(), library='scipy', seed=None): """ Internal sample method Returns dictionary mapping RandomMatrixSymbol to realization value. """ return {self.value: self.distribution.sample(size, library=library, seed=seed)} def rv(symbol, cls, args): args = list(map(sympify, args)) dist = cls(*args) dist.check(*args) dim = dist.dimension pspace = MatrixPSpace(symbol, dist, dim[0], dim[1]) return pspace.value class SampleMatrixScipy: """Returns the sample from scipy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_scipy(dist, size, seed) @classmethod def _sample_scipy(cls, dist, size, seed): """Sample from SciPy.""" from scipy import stats as scipy_stats import numpy scipy_rv_map = { 'WishartDistribution': lambda dist, size, rand_state: scipy_stats.wishart.rvs( df=int(dist.n), scale=matrix2numpy(dist.scale_matrix, float), size=size), 'MatrixNormalDistribution': lambda dist, size, rand_state: scipy_stats.matrix_normal.rvs( mean=matrix2numpy(dist.location_matrix, float), rowcov=matrix2numpy(dist.scale_matrix_1, float), colcov=matrix2numpy(dist.scale_matrix_2, float), size=size, random_state=rand_state) } dist_list = scipy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None samples = [] if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed for _ in range(size[0]): samp = scipy_rv_map[dist.__class__.__name__](dist, size[1], rand_state) samples.append(samp) return samples class SampleMatrixNumpy: """Returns the sample from numpy of the given distribution""" ### TODO: Add tests after adding matrix distributions in numpy_rv_map def __new__(cls, dist, size, seed=None): return cls._sample_numpy(dist, size, seed) @classmethod def _sample_numpy(cls, dist, size, seed): """Sample from NumPy.""" numpy_rv_map = { } dist_list = numpy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None samples = [] import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed for _ in range(size[0]): samp = numpy_rv_map[dist.__class__.__name__](dist, size[1], rand_state) samples.append(samp) return samples class SampleMatrixPymc: """Returns the sample from pymc3 of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_pymc3(dist, size, seed) @classmethod def _sample_pymc3(cls, dist, size, seed): """Sample from PyMC3.""" import pymc3 pymc3_rv_map = { 'MatrixNormalDistribution': lambda dist: pymc3.MatrixNormal('X', mu=matrix2numpy(dist.location_matrix, float), rowcov=matrix2numpy(dist.scale_matrix_1, float), colcov=matrix2numpy(dist.scale_matrix_2, float), shape=dist.location_matrix.shape), 'WishartDistribution': lambda dist: pymc3.WishartBartlett('X', nu=int(dist.n), S=matrix2numpy(dist.scale_matrix, float)) } dist_list = pymc3_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None with pymc3.Model(): pymc3_rv_map[dist.__class__.__name__](dist) return pymc3.sample(size, chains=1, progressbar=False)[:]['X'] _get_sample_class_matrixrv = { 'scipy': SampleMatrixScipy, 'pymc3': SampleMatrixPymc, 'numpy': SampleMatrixNumpy } ################################################################################ #-------------------------Matrix Distribution----------------------------------# ################################################################################ class MatrixDistribution(Basic, NamedArgsMixin): """ Abstract class for Matrix Distribution """ def __new__(cls, *args): args = list(map(sympify, args)) return Basic.__new__(cls, *args) @staticmethod def check(*args): pass def __call__(self, expr): if isinstance(expr, list): expr = ImmutableMatrix(expr) return self.pdf(expr) def sample(self, size=(), library='scipy', seed=None): """ Internal sample method Returns dictionary mapping RandomSymbol to realization value. """ libraries = ['scipy', 'numpy', 'pymc3'] if library not in libraries: raise NotImplementedError("Sampling from %s is not supported yet." % str(library)) if not import_module(library): raise ValueError("Failed to import %s" % library) samps = _get_sample_class_matrixrv[library](self, size, seed) if samps is not None: return samps raise NotImplementedError( "Sampling for %s is not currently implemented from %s" % (self.__class__.__name__, library) ) ################################################################################ #------------------------Matrix Distribution Types-----------------------------# ################################################################################ #------------------------------------------------------------------------------- # Matrix Gamma distribution ---------------------------------------------------- class MatrixGammaDistribution(MatrixDistribution): _argnames = ('alpha', 'beta', 'scale_matrix') @staticmethod def check(alpha, beta, scale_matrix): if not isinstance(scale_matrix , MatrixSymbol): _value_check(scale_matrix.is_positive_definite, "The shape " "matrix must be positive definite.") _value_check(scale_matrix.is_square, "Should " "be square matrix") _value_check(alpha.is_positive, "Shape parameter should be positive.") _value_check(beta.is_positive, "Scale parameter should be positive.") @property def set(self): k = self.scale_matrix.shape[0] return MatrixSet(k, k, S.Reals) @property def dimension(self): return self.scale_matrix.shape def pdf(self, x): alpha , beta , scale_matrix = self.alpha, self.beta, self.scale_matrix p = scale_matrix.shape[0] if isinstance(x, list): x = ImmutableMatrix(x) if not isinstance(x, (MatrixBase, MatrixSymbol)): raise ValueError("%s should be an isinstance of Matrix " "or MatrixSymbol" % str(x)) sigma_inv_x = - Inverse(scale_matrix)*x / beta term1 = exp(Trace(sigma_inv_x))/((beta**(p*alpha)) * multigamma(alpha, p)) term2 = (Determinant(scale_matrix))**(-alpha) term3 = (Determinant(x))**(alpha - S(p + 1)/2) return term1 * term2 * term3 def MatrixGamma(symbol, alpha, beta, scale_matrix): """ Creates a random variable with Matrix Gamma Distribution. The density of the said distribution can be found at [1]. Parameters ========== alpha: Positive Real number Shape Parameter beta: Positive Real number Scale Parameter scale_matrix: Positive definite real square matrix Scale Matrix Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import density, MatrixGamma >>> from sympy import MatrixSymbol, symbols >>> a, b = symbols('a b', positive=True) >>> M = MatrixGamma('M', a, b, [[2, 1], [1, 2]]) >>> X = MatrixSymbol('X', 2, 2) >>> density(M)(X).doit() 3**(-a)*b**(-2*a)*exp(Trace(Matrix([ [-2/3, 1/3], [ 1/3, -2/3]])*X)/b)*Determinant(X)**(a - 3/2)/(sqrt(pi)*gamma(a)*gamma(a - 1/2)) >>> density(M)([[1, 0], [0, 1]]).doit() 3**(-a)*b**(-2*a)*exp(-4/(3*b))/(sqrt(pi)*gamma(a)*gamma(a - 1/2)) References ========== .. [1] https://en.wikipedia.org/wiki/Matrix_gamma_distribution """ if isinstance(scale_matrix, list): scale_matrix = ImmutableMatrix(scale_matrix) return rv(symbol, MatrixGammaDistribution, (alpha, beta, scale_matrix)) #------------------------------------------------------------------------------- # Wishart Distribution --------------------------------------------------------- class WishartDistribution(MatrixDistribution): _argnames = ('n', 'scale_matrix') @staticmethod def check(n, scale_matrix): if not isinstance(scale_matrix , MatrixSymbol): _value_check(scale_matrix.is_positive_definite, "The shape " "matrix must be positive definite.") _value_check(scale_matrix.is_square, "Should " "be square matrix") _value_check(n.is_positive, "Shape parameter should be positive.") @property def set(self): k = self.scale_matrix.shape[0] return MatrixSet(k, k, S.Reals) @property def dimension(self): return self.scale_matrix.shape def pdf(self, x): n, scale_matrix = self.n, self.scale_matrix p = scale_matrix.shape[0] if isinstance(x, list): x = ImmutableMatrix(x) if not isinstance(x, (MatrixBase, MatrixSymbol)): raise ValueError("%s should be an isinstance of Matrix " "or MatrixSymbol" % str(x)) sigma_inv_x = - Inverse(scale_matrix)*x / S(2) term1 = exp(Trace(sigma_inv_x))/((2**(p*n/S(2))) * multigamma(n/S(2), p)) term2 = (Determinant(scale_matrix))**(-n/S(2)) term3 = (Determinant(x))**(S(n - p - 1)/2) return term1 * term2 * term3 def Wishart(symbol, n, scale_matrix): """ Creates a random variable with Wishart Distribution. The density of the said distribution can be found at [1]. Parameters ========== n: Positive Real number Represents degrees of freedom scale_matrix: Positive definite real square matrix Scale Matrix Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import density, Wishart >>> from sympy import MatrixSymbol, symbols >>> n = symbols('n', positive=True) >>> W = Wishart('W', n, [[2, 1], [1, 2]]) >>> X = MatrixSymbol('X', 2, 2) >>> density(W)(X).doit() 2**(-n)*3**(-n/2)*exp(Trace(Matrix([ [-1/3, 1/6], [ 1/6, -1/3]])*X))*Determinant(X)**(n/2 - 3/2)/(sqrt(pi)*gamma(n/2)*gamma(n/2 - 1/2)) >>> density(W)([[1, 0], [0, 1]]).doit() 2**(-n)*3**(-n/2)*exp(-2/3)/(sqrt(pi)*gamma(n/2)*gamma(n/2 - 1/2)) References ========== .. [1] https://en.wikipedia.org/wiki/Wishart_distribution """ if isinstance(scale_matrix, list): scale_matrix = ImmutableMatrix(scale_matrix) return rv(symbol, WishartDistribution, (n, scale_matrix)) #------------------------------------------------------------------------------- # Matrix Normal distribution --------------------------------------------------- class MatrixNormalDistribution(MatrixDistribution): _argnames = ('location_matrix', 'scale_matrix_1', 'scale_matrix_2') @staticmethod def check(location_matrix, scale_matrix_1, scale_matrix_2): if not isinstance(scale_matrix_1 , MatrixSymbol): _value_check(scale_matrix_1.is_positive_definite, "The shape " "matrix must be positive definite.") if not isinstance(scale_matrix_2 , MatrixSymbol): _value_check(scale_matrix_2.is_positive_definite, "The shape " "matrix must be positive definite.") _value_check(scale_matrix_1.is_square, "Scale matrix 1 should be " "be square matrix") _value_check(scale_matrix_2.is_square, "Scale matrix 2 should be " "be square matrix") n = location_matrix.shape[0] p = location_matrix.shape[1] _value_check(scale_matrix_1.shape[0] == n, "Scale matrix 1 should be" " of shape %s x %s"% (str(n), str(n))) _value_check(scale_matrix_2.shape[0] == p, "Scale matrix 2 should be" " of shape %s x %s"% (str(p), str(p))) @property def set(self): n, p = self.location_matrix.shape return MatrixSet(n, p, S.Reals) @property def dimension(self): return self.location_matrix.shape def pdf(self, x): M , U , V = self.location_matrix, self.scale_matrix_1, self.scale_matrix_2 n, p = M.shape if isinstance(x, list): x = ImmutableMatrix(x) if not isinstance(x, (MatrixBase, MatrixSymbol)): raise ValueError("%s should be an isinstance of Matrix " "or MatrixSymbol" % str(x)) term1 = Inverse(V)*Transpose(x - M)*Inverse(U)*(x - M) num = exp(-Trace(term1)/S(2)) den = (2*pi)**(S(n*p)/2) * Determinant(U)**S(p)/2 * Determinant(V)**S(n)/2 return num/den def MatrixNormal(symbol, location_matrix, scale_matrix_1, scale_matrix_2): """ Creates a random variable with Matrix Normal Distribution. The density of the said distribution can be found at [1]. Parameters ========== location_matrix: Real ``n x p`` matrix Represents degrees of freedom scale_matrix_1: Positive definite matrix Scale Matrix of shape ``n x n`` scale_matrix_2: Positive definite matrix Scale Matrix of shape ``p x p`` Returns ======= RandomSymbol Examples ======== >>> from sympy import MatrixSymbol >>> from sympy.stats import density, MatrixNormal >>> M = MatrixNormal('M', [[1, 2]], [1], [[1, 0], [0, 1]]) >>> X = MatrixSymbol('X', 1, 2) >>> density(M)(X).doit() 2*exp(-Trace((Matrix([ [-1], [-2]]) + X.T)*(Matrix([[-1, -2]]) + X))/2)/pi >>> density(M)([[3, 4]]).doit() 2*exp(-4)/pi References ========== .. [1] https://en.wikipedia.org/wiki/Matrix_normal_distribution """ if isinstance(location_matrix, list): location_matrix = ImmutableMatrix(location_matrix) if isinstance(scale_matrix_1, list): scale_matrix_1 = ImmutableMatrix(scale_matrix_1) if isinstance(scale_matrix_2, list): scale_matrix_2 = ImmutableMatrix(scale_matrix_2) args = (location_matrix, scale_matrix_1, scale_matrix_2) return rv(symbol, MatrixNormalDistribution, args)
154c016a931f0317d967050a0860f868746bc55c6791701816ffd2284d2df905
""" 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} 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 for rv in rvs: if isinstance(rv.pspace, CompoundPSpace): 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) 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 gd = given_fn(*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 gd = given_fn(*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] yield fn(*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)) 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()
11c30e72f1d366810811b18cc45d8c9fd837318cc324ed6a1ae89cf724ffcc1c
""" Joint Random Variables Module See Also ======== sympy.stats.rv sympy.stats.frv sympy.stats.crv sympy.stats.drv """ from sympy import (Basic, Lambda, sympify, Indexed, Symbol, ProductSet, S, Dummy) from sympy.concrete.products import Product from sympy.concrete.summations import Sum, summation from sympy.core.compatibility import iterable from sympy.core.containers import Tuple from sympy.integrals.integrals import Integral, integrate from sympy.matrices import ImmutableMatrix, matrix2numpy, list2numpy from sympy.stats.crv import SingleContinuousDistribution, SingleContinuousPSpace from sympy.stats.drv import SingleDiscreteDistribution, SingleDiscretePSpace from sympy.stats.rv import (ProductPSpace, NamedArgsMixin, ProductDomain, RandomSymbol, random_symbols, SingleDomain, _symbol_converter) from sympy.utilities.misc import filldedent from sympy.external import import_module # __all__ = ['marginal_distribution'] class JointPSpace(ProductPSpace): """ Represents a joint probability space. Represented using symbols for each component and a distribution. """ def __new__(cls, sym, dist): if isinstance(dist, SingleContinuousDistribution): return SingleContinuousPSpace(sym, dist) if isinstance(dist, SingleDiscreteDistribution): return SingleDiscretePSpace(sym, dist) sym = _symbol_converter(sym) return Basic.__new__(cls, sym, dist) @property def set(self): return self.domain.set @property def symbol(self): return self.args[0] @property def distribution(self): return self.args[1] @property def value(self): return JointRandomSymbol(self.symbol, self) @property def component_count(self): _set = self.distribution.set if isinstance(_set, ProductSet): return S(len(_set.args)) elif isinstance(_set, Product): return _set.limits[0][-1] return S.One @property def pdf(self): sym = [Indexed(self.symbol, i) for i in range(self.component_count)] return self.distribution(*sym) @property def domain(self): rvs = random_symbols(self.distribution) if not rvs: return SingleDomain(self.symbol, self.distribution.set) return ProductDomain(*[rv.pspace.domain for rv in rvs]) def component_domain(self, index): return self.set.args[index] def marginal_distribution(self, *indices): count = self.component_count if count.atoms(Symbol): raise ValueError("Marginal distributions cannot be computed " "for symbolic dimensions. It is a work under progress.") orig = [Indexed(self.symbol, i) for i in range(count)] all_syms = [Symbol(str(i)) for i in orig] replace_dict = dict(zip(all_syms, orig)) sym = tuple(Symbol(str(Indexed(self.symbol, i))) for i in indices) limits = list([i,] for i in all_syms if i not in sym) index = 0 for i in range(count): if i not in indices: limits[index].append(self.distribution.set.args[i]) limits[index] = tuple(limits[index]) index += 1 if self.distribution.is_Continuous: f = Lambda(sym, integrate(self.distribution(*all_syms), *limits)) elif self.distribution.is_Discrete: f = Lambda(sym, summation(self.distribution(*all_syms), *limits)) return f.xreplace(replace_dict) def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs): syms = tuple(self.value[i] for i in range(self.component_count)) rvs = rvs or syms if not any([i in rvs for i in syms]): return expr expr = expr*self.pdf for rv in rvs: if isinstance(rv, Indexed): expr = expr.xreplace({rv: Indexed(str(rv.base), rv.args[1])}) elif isinstance(rv, RandomSymbol): expr = expr.xreplace({rv: rv.symbol}) if self.value in random_symbols(expr): raise NotImplementedError(filldedent(''' Expectations of expression with unindexed joint random symbols cannot be calculated yet.''')) limits = tuple((Indexed(str(rv.base),rv.args[1]), self.distribution.set.args[rv.args[1]]) for rv in syms) return Integral(expr, *limits) def where(self, condition): raise NotImplementedError() def compute_density(self, expr): raise NotImplementedError() def sample(self, size=(), library='scipy', seed=None): """ Internal sample method Returns dictionary mapping RandomSymbol to realization value. """ return {RandomSymbol(self.symbol, self): self.distribution.sample(size, library=library, seed=seed)} def probability(self, condition): raise NotImplementedError() class SampleJointScipy: """Returns the sample from scipy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_scipy(dist, size, seed) @classmethod def _sample_scipy(cls, dist, size, seed): """Sample from SciPy.""" from scipy import stats as scipy_stats scipy_rv_map = { 'MultivariateNormalDistribution': lambda dist, size: scipy_stats.multivariate_normal.rvs( mean=matrix2numpy(dist.mu).flatten(), cov=matrix2numpy(dist.sigma), size=size, random_state=seed), 'MultivariateBetaDistribution': lambda dist, size: scipy_stats.dirichlet.rvs( alpha=list2numpy(dist.alpha, float).flatten(), size=size, random_state=seed), 'MultinomialDistribution': lambda dist, size: scipy_stats.multinomial.rvs( n=int(dist.n), p=list2numpy(dist.p, float).flatten(), size=size, random_state=seed) } dist_list = scipy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None samples = scipy_rv_map[dist.__class__.__name__](dist, size) if samples.shape[0:len(size)] != size: samples = samples.reshape((size[0],) + samples.shape) return samples class SampleJointNumpy: """Returns the sample from numpy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_numpy(dist, size, seed) @classmethod def _sample_numpy(cls, dist, size, seed): """Sample from NumPy.""" import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed numpy_rv_map = { 'MultivariateNormalDistribution': lambda dist, size: rand_state.multivariate_normal( mean=matrix2numpy(dist.mu, float).flatten(), cov=matrix2numpy(dist.sigma, float), size=size), 'MultivariateBetaDistribution': lambda dist, size: rand_state.dirichlet( alpha=list2numpy(dist.alpha, float).flatten(), size=size), 'MultinomialDistribution': lambda dist, size: rand_state.multinomial( n=int(dist.n), pvals=list2numpy(dist.p, float).flatten(), size=size) } dist_list = numpy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None samples = numpy_rv_map[dist.__class__.__name__](dist, size) if samples.shape[0:len(size)] != size: samples = samples.reshape((size[0],) + samples.shape) return samples class SampleJointPymc: """Returns the sample from pymc3 of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_pymc3(dist, size, seed) @classmethod def _sample_pymc3(cls, dist, size, seed): """Sample from PyMC3.""" import pymc3 pymc3_rv_map = { 'MultivariateNormalDistribution': lambda dist: pymc3.MvNormal('X', mu=matrix2numpy(dist.mu, float).flatten(), cov=matrix2numpy(dist.sigma, float), shape=(1, dist.mu.shape[0])), 'MultivariateBetaDistribution': lambda dist: pymc3.Dirichlet('X', a=list2numpy(dist.alpha, float).flatten()), 'MultinomialDistribution': lambda dist: pymc3.Multinomial('X', n=int(dist.n), p=list2numpy(dist.p, float).flatten(), shape=(1, len(dist.p))) } dist_list = pymc3_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None with pymc3.Model(): pymc3_rv_map[dist.__class__.__name__](dist) samples = pymc3.sample(size, chains=1, progressbar=False, random_seed=seed)[:]['X'] if samples.shape[0:len(size)] != size: samples = samples.reshape((size[0],) + samples.shape) return samples _get_sample_class_jrv = { 'scipy': SampleJointScipy, 'pymc3': SampleJointPymc, 'numpy': SampleJointNumpy } class JointDistribution(Basic, NamedArgsMixin): """ Represented by the random variables part of the joint distribution. Contains methods for PDF, CDF, sampling, marginal densities, etc. """ _argnames = ('pdf', ) def __new__(cls, *args): args = list(map(sympify, args)) for i in range(len(args)): if isinstance(args[i], list): args[i] = ImmutableMatrix(args[i]) return Basic.__new__(cls, *args) @property def domain(self): return ProductDomain(self.symbols) @property def pdf(self): return self.density.args[1] def cdf(self, other): if not isinstance(other, dict): raise ValueError("%s should be of type dict, got %s"%(other, type(other))) rvs = other.keys() _set = self.domain.set.sets expr = self.pdf(tuple(i.args[0] for i in self.symbols)) for i in range(len(other)): if rvs[i].is_Continuous: density = Integral(expr, (rvs[i], _set[i].inf, other[rvs[i]])) elif rvs[i].is_Discrete: density = Sum(expr, (rvs[i], _set[i].inf, other[rvs[i]])) return density def sample(self, size=(), library='scipy', seed=None): """ A random realization from the distribution """ libraries = ['scipy', 'numpy', 'pymc3'] if library not in libraries: raise NotImplementedError("Sampling from %s is not supported yet." % str(library)) if not import_module(library): raise ValueError("Failed to import %s" % library) samps = _get_sample_class_jrv[library](self, size, seed=seed) if samps is not None: return samps raise NotImplementedError( "Sampling for %s is not currently implemented from %s" % (self.__class__.__name__, library) ) def __call__(self, *args): return self.pdf(*args) class JointRandomSymbol(RandomSymbol): """ Representation of random symbols with joint probability distributions to allow indexing." """ def __getitem__(self, key): if isinstance(self.pspace, JointPSpace): if (self.pspace.component_count <= key) == True: raise ValueError("Index keys for %s can only up to %s." % (self.name, self.pspace.component_count - 1)) return Indexed(self, key) class MarginalDistribution(Basic): """ Represents the marginal distribution of a joint probability space. Initialised using a probability distribution and random variables(or their indexed components) which should be a part of the resultant distribution. """ def __new__(cls, dist, *rvs): if len(rvs) == 1 and iterable(rvs[0]): rvs = tuple(rvs[0]) if not all([isinstance(rv, (Indexed, RandomSymbol))] for rv in rvs): raise ValueError(filldedent('''Marginal distribution can be intitialised only in terms of random variables or indexed random variables''')) rvs = Tuple.fromiter(rv for rv in rvs) if not isinstance(dist, JointDistribution) and len(random_symbols(dist)) == 0: return dist return Basic.__new__(cls, dist, rvs) def check(self): pass @property def set(self): rvs = [i for i in self.args[1] if isinstance(i, RandomSymbol)] return ProductSet(*[rv.pspace.set for rv in rvs]) @property def symbols(self): rvs = self.args[1] return {rv.pspace.symbol for rv in rvs} def pdf(self, *x): expr, rvs = self.args[0], self.args[1] marginalise_out = [i for i in random_symbols(expr) if i not in rvs] if isinstance(expr, JointDistribution): count = len(expr.domain.args) x = Dummy('x', real=True, finite=True) syms = tuple(Indexed(x, i) for i in count) expr = expr.pdf(syms) else: syms = tuple(rv.pspace.symbol if isinstance(rv, RandomSymbol) else rv.args[0] for rv in rvs) return Lambda(syms, self.compute_pdf(expr, marginalise_out))(*x) def compute_pdf(self, expr, rvs): for rv in rvs: lpdf = 1 if isinstance(rv, RandomSymbol): lpdf = rv.pspace.pdf expr = self.marginalise_out(expr*lpdf, rv) return expr def marginalise_out(self, expr, rv): from sympy.concrete.summations import Sum if isinstance(rv, RandomSymbol): dom = rv.pspace.set elif isinstance(rv, Indexed): dom = rv.base.component_domain( rv.pspace.component_domain(rv.args[1])) expr = expr.xreplace({rv: rv.pspace.symbol}) if rv.pspace.is_Continuous: #TODO: Modify to support integration #for all kinds of sets. expr = Integral(expr, (rv.pspace.symbol, dom)) elif rv.pspace.is_Discrete: #incorporate this into `Sum`/`summation` if dom in (S.Integers, S.Naturals, S.Naturals0): dom = (dom.inf, dom.sup) expr = Sum(expr, (rv.pspace.symbol, dom)) return expr def __call__(self, *args): return self.pdf(*args)
28e1aa53ec2f6bb97b8d3e5f15148137e8975222ddfdd3e6e180f70c3f5c2baf
from sympy import (Basic, sympify, symbols, Dummy, Lambda, summation, Piecewise, S, cacheit, Sum, exp, I, Ne, Eq, poly, series, factorial, And, lambdify) 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) 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 from sympy.external import import_module class DiscreteDistribution(Basic): def __call__(self, *args): return self.pdf(*args) class SampleDiscreteScipy: """Returns the sample from scipy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_scipy(dist, size, seed) @classmethod def _sample_scipy(cls, dist, size, seed): """Sample from SciPy.""" from scipy import stats as scipy_stats scipy_rv_map = { 'GeometricDistribution': lambda dist, size: scipy_stats.geom.rvs(p=float(dist.p), size=size, random_state=seed), 'LogarithmicDistribution': lambda dist, size: scipy_stats.logser.rvs(p=float(dist.p), size=size, random_state=seed), 'NegativeBinomialDistribution': lambda dist, size: scipy_stats.nbinom.rvs(n=float(dist.r), p=float(dist.p), size=size, random_state=seed), 'PoissonDistribution': lambda dist, size: scipy_stats.poisson.rvs(mu=float(dist.lamda), size=size, random_state=seed), 'SkellamDistribution': lambda dist, size: scipy_stats.skellam.rvs(mu1=float(dist.mu1), mu2=float(dist.mu2), size=size, random_state=seed), 'YuleSimonDistribution': lambda dist, size: scipy_stats.yulesimon.rvs(alpha=float(dist.rho), size=size, random_state=seed), 'ZetaDistribution': lambda dist, size: scipy_stats.zipf.rvs(a=float(dist.s), size=size, random_state=seed) } dist_list = scipy_rv_map.keys() if dist.__class__.__name__ == 'DiscreteDistributionHandmade': from scipy.stats import rv_discrete z = Dummy('z') handmade_pmf = lambdify(z, dist.pdf(z), ['numpy', 'scipy']) class scipy_pmf(rv_discrete): def _pmf(self, 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) if dist.__class__.__name__ not in dist_list: return None return scipy_rv_map[dist.__class__.__name__](dist, size) class SampleDiscreteNumpy: """Returns the sample from numpy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_numpy(dist, size, seed) @classmethod def _sample_numpy(cls, dist, size, seed): """Sample from NumPy.""" import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed numpy_rv_map = { 'GeometricDistribution': lambda dist, size: rand_state.geometric(p=float(dist.p), size=size), 'PoissonDistribution': lambda dist, size: rand_state.poisson(lam=float(dist.lamda), size=size), 'ZetaDistribution': lambda dist, size: rand_state.zipf(a=float(dist.s), size=size) } dist_list = numpy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None return numpy_rv_map[dist.__class__.__name__](dist, size) class SampleDiscretePymc: """Returns the sample from pymc3 of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_pymc3(dist, size, seed) @classmethod def _sample_pymc3(cls, dist, size, seed): """Sample from PyMC3.""" import pymc3 pymc3_rv_map = { 'GeometricDistribution': lambda dist: pymc3.Geometric('X', p=float(dist.p)), 'PoissonDistribution': lambda dist: pymc3.Poisson('X', mu=float(dist.lamda)), 'NegativeBinomialDistribution': lambda dist: pymc3.NegativeBinomial('X', mu=float((dist.p*dist.r)/(1-dist.p)), alpha=float(dist.r)) } dist_list = pymc3_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None with pymc3.Model(): pymc3_rv_map[dist.__class__.__name__](dist) return pymc3.sample(size, chains=1, progressbar=False, random_seed=seed)[:]['X'] _get_sample_class_drv = { 'scipy': SampleDiscreteScipy, 'pymc3': SampleDiscretePymc, 'numpy': SampleDiscreteNumpy } 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 def sample(self, size=(), library='scipy', seed=None): """ A random realization from the distribution""" libraries = ['scipy', 'numpy', 'pymc3'] if library not in libraries: raise NotImplementedError("Sampling from %s is not supported yet." % str(library)) if not import_module(library): raise ValueError("Failed to import %s" % library) samps = _get_sample_class_drv[library](self, size, seed) if samps is not None: return samps raise NotImplementedError( "Sampling for %s is not currently implemented from %s" % (self.__class__.__name__, library) ) @cacheit def compute_cdf(self, **kwargs): """ Compute the CDF from the PDF Returns a Lambda """ x, z = symbols('x, z', integer=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, 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()
7a710aa14e4129ed77f0b199256ddbeacdf25452ea2e02566313d656f504963e
""" 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, lambdify) 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.external import import_module from sympy.stats.rv import (RandomDomain, SingleDomain, ConditionalDomain, is_random, ProductDomain, PSpace, SinglePSpace, random_symbols, NamedArgsMixin) 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(Basic): def __call__(self, *args): return self.pdf(*args) class SampleContinuousScipy: """Returns the sample from scipy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_scipy(dist, size, seed=seed) @classmethod def _sample_scipy(cls, dist, size, seed): """Sample from SciPy.""" import scipy.stats # 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. scipy_rv_map = { 'BetaDistribution': lambda dist, size: scipy.stats.beta.rvs( a=float(dist.alpha), b=float(dist.beta), size=size, random_state=seed), # same parametrisation 'CauchyDistribution': lambda dist, size: scipy.stats.cauchy.rvs( loc=float(dist.x0), scale=float(dist.gamma), size=size, random_state=seed), # same parametrisation 'ChiSquaredDistribution': lambda dist, size: scipy.stats.chi2.rvs( df=float(dist.k), size=size, random_state=seed), # same parametrisation 'ExponentialDistribution': lambda dist, size: scipy.stats.expon.rvs( scale=1 / float(dist.rate), size=size, random_state=seed), # https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.expon.html#scipy.stats.expon 'GammaDistribution': lambda dist, size: scipy.stats.gamma.rvs( a=float(dist.k), scale=float(dist.theta), size=size, random_state=seed), # https://stackoverflow.com/questions/42150965/how-to-plot-gamma-distribution-with-alpha-and-beta-parameters-in-python 'LogNormalDistribution': lambda dist, size: scipy.stats.lognorm.rvs( scale=float(exp(dist.mean)), s=float(dist.std), size=size, random_state=seed), # https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lognorm.html 'NormalDistribution': lambda dist, size: scipy.stats.norm.rvs( loc=float(dist.mean), scale=float(dist.std), size=size, random_state=seed), # same parametrisation 'ParetoDistribution': lambda dist, size: scipy.stats.pareto.rvs( b=float(dist.alpha), scale=float(dist.xm), size=size, random_state=seed), # https://stackoverflow.com/questions/42260519/defining-pareto-distribution-in-python-scipy 'StudentTDistribution': lambda dist, size: scipy.stats.t.rvs( df=float(dist.nu), size=size, random_state=seed), # same parametrisation 'UniformDistribution': lambda dist, size: scipy.stats.uniform.rvs( loc=float(dist.left), scale=float(dist.right - dist.left), size=size, random_state=seed) # https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.uniform.html } # if we don't need to make a handmade pdf, we won't if dist.__class__.__name__ in scipy_rv_map: return scipy_rv_map[dist.__class__.__name__](dist, size) z = Dummy('z') handmade_pdf = lambdify(z, dist.pdf(z), ['numpy', 'scipy']) class scipy_pdf(scipy.stats.rv_continuous): def _pdf(self, 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) class SampleContinuousNumpy: """Returns the sample from numpy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_numpy(dist, size, seed) @classmethod def _sample_numpy(cls, dist, size, seed): """Sample from NumPy.""" import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed numpy_rv_map = { 'BetaDistribution': lambda dist, size: rand_state.beta(a=float(dist.alpha), b=float(dist.beta), size=size), 'ChiSquaredDistribution': lambda dist, size: rand_state.chisquare( df=float(dist.k), size=size), 'ExponentialDistribution': lambda dist, size: rand_state.exponential( 1/float(dist.rate), size=size), 'GammaDistribution': lambda dist, size: rand_state.gamma(float(dist.k), float(dist.theta), size=size), 'LogNormalDistribution': lambda dist, size: rand_state.lognormal( float(dist.mean), float(dist.std), size=size), 'NormalDistribution': lambda dist, size: rand_state.normal( float(dist.mean), float(dist.std), size=size), 'ParetoDistribution': lambda dist, size: (rand_state.pareto( a=float(dist.alpha), size=size) + 1) * float(dist.xm), 'UniformDistribution': lambda dist, size: rand_state.uniform( low=float(dist.left), high=float(dist.right), size=size) } dist_list = numpy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None return numpy_rv_map[dist.__class__.__name__](dist, size) class SampleContinuousPymc: """Returns the sample from pymc3 of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_pymc3(dist, size, seed) @classmethod def _sample_pymc3(cls, dist, size, seed): """Sample from PyMC3.""" import pymc3 pymc3_rv_map = { 'BetaDistribution': lambda dist: pymc3.Beta('X', alpha=float(dist.alpha), beta=float(dist.beta)), 'CauchyDistribution': lambda dist: pymc3.Cauchy('X', alpha=float(dist.x0), beta=float(dist.gamma)), 'ChiSquaredDistribution': lambda dist: pymc3.ChiSquared('X', nu=float(dist.k)), 'ExponentialDistribution': lambda dist: pymc3.Exponential('X', lam=float(dist.rate)), 'GammaDistribution': lambda dist: pymc3.Gamma('X', alpha=float(dist.k), beta=1/float(dist.theta)), 'LogNormalDistribution': lambda dist: pymc3.Lognormal('X', mu=float(dist.mean), sigma=float(dist.std)), 'NormalDistribution': lambda dist: pymc3.Normal('X', float(dist.mean), float(dist.std)), 'GaussianInverseDistribution': lambda dist: pymc3.Wald('X', mu=float(dist.mean), lam=float(dist.shape)), 'ParetoDistribution': lambda dist: pymc3.Pareto('X', alpha=float(dist.alpha), m=float(dist.xm)), 'UniformDistribution': lambda dist: pymc3.Uniform('X', lower=float(dist.left), upper=float(dist.right)) } dist_list = pymc3_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None with pymc3.Model(): pymc3_rv_map[dist.__class__.__name__](dist) return pymc3.sample(size, chains=1, progressbar=False, random_seed=seed)[:]['X'] _get_sample_class_crv = { 'scipy': SampleContinuousScipy, 'pymc3': SampleContinuousPymc, 'numpy': SampleContinuousNumpy } 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 def sample(self, size=(), library='scipy', seed=None): """ A random realization from the distribution """ libraries = ['scipy', 'numpy', 'pymc3'] if library not in libraries: raise NotImplementedError("Sampling from %s is not supported yet." % str(library)) if not import_module(library): raise ValueError("Failed to import %s" % library) samps = _get_sample_class_crv[library](self, size, seed) if samps is not None: return samps raise NotImplementedError( "Sampling for %s is not currently implemented from %s" % (self.__class__.__name__, library) ) @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) 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
ff3bdbe0030e442a8f8b078cf2140395379b5d183e52392d44eb8b205d13f112
""" 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) from sympy.external import import_module 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(Basic, 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. """ libraries = ['scipy', 'numpy', 'pymc3'] if library not in libraries: raise NotImplementedError("Sampling from %s is not supported yet." % str(library)) if not import_module(library): raise ValueError("Failed to import %s" % library) samps = _get_sample_class_frv[library](self.distribution, size, seed) if samps is not None: return {self.value: samps} raise NotImplementedError( "Sampling for %s is not currently implemented from %s" % (self.__class__.__name__, library) ) class SampleFiniteScipy: """Returns the sample from scipy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_scipy(dist, size, seed) @classmethod def _sample_scipy(cls, dist, size, seed): """Sample from SciPy.""" # 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) class SampleFiniteNumpy: """Returns the sample from numpy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_numpy(dist, size, seed) @classmethod def _sample_numpy(cls, dist, size, seed): """Sample from NumPy.""" import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed numpy_rv_map = { 'BinomialDistribution': lambda dist, size: rand_state.binomial(n=int(dist.n), p=float(dist.p), size=size) } dist_list = numpy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None return numpy_rv_map[dist.__class__.__name__](dist, size) class SampleFinitePymc: """Returns the sample from pymc3 of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_pymc3(dist, size, seed) @classmethod def _sample_pymc3(cls, dist, size, seed): """Sample from PyMC3.""" import pymc3 pymc3_rv_map = { 'BernoulliDistribution': lambda dist: pymc3.Bernoulli('X', p=float(dist.p)), 'BinomialDistribution': lambda dist: pymc3.Binomial('X', n=int(dist.n), p=float(dist.p)) } dist_list = pymc3_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None with pymc3.Model(): pymc3_rv_map[dist.__class__.__name__](dist) return pymc3.sample(size, chains=1, progressbar=False, random_seed=seed)[:]['X'] _get_sample_class_frv = { 'scipy': SampleFiniteScipy, 'pymc3': SampleFinitePymc, 'numpy': SampleFiniteNumpy } 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)
84dc8edcd19e75bda0d9d93b97625fbb25e3ebbaeabdad745cc01fdaa9b84454
""" This file contains some classical ciphers and routines implementing a linear-feedback shift register (LFSR) and the Diffie-Hellman key exchange. .. warning:: This module is intended for educational purposes only. Do not use the functions in this module for real cryptographic applications. If you wish to encrypt real data, we recommend using something like the `cryptography <https://cryptography.io/en/latest/>`_ module. """ from string import whitespace, ascii_uppercase as uppercase, printable from functools import reduce import warnings from itertools import cycle from sympy import nextprime from sympy.core import Rational, Symbol from sympy.core.numbers import igcdex, mod_inverse, igcd from sympy.core.compatibility import as_int from sympy.matrices import Matrix from sympy.ntheory import isprime, primitive_root, factorint from sympy.polys.domains import FF from sympy.polys.polytools import gcd, Poly from sympy.utilities.misc import filldedent, translate from sympy.utilities.iterables import uniq, multiset from sympy.testing.randtest import _randrange, _randint class NonInvertibleCipherWarning(RuntimeWarning): """A warning raised if the cipher is not invertible.""" def __init__(self, msg): self.fullMessage = msg def __str__(self): return '\n\t' + self.fullMessage def warn(self, stacklevel=2): warnings.warn(self, stacklevel=stacklevel) def AZ(s=None): """Return the letters of ``s`` in uppercase. In case more than one string is passed, each of them will be processed and a list of upper case strings will be returned. Examples ======== >>> from sympy.crypto.crypto import AZ >>> AZ('Hello, world!') 'HELLOWORLD' >>> AZ('Hello, world!'.split()) ['HELLO', 'WORLD'] See Also ======== check_and_join """ if not s: return uppercase t = type(s) is str if t: s = [s] rv = [check_and_join(i.upper().split(), uppercase, filter=True) for i in s] if t: return rv[0] return rv bifid5 = AZ().replace('J', '') bifid6 = AZ() + '0123456789' bifid10 = printable def padded_key(key, symbols): """Return a string of the distinct characters of ``symbols`` with those of ``key`` appearing first. A ValueError is raised if a) there are duplicate characters in ``symbols`` or b) there are characters in ``key`` that are not in ``symbols``. Examples ======== >>> from sympy.crypto.crypto import padded_key >>> padded_key('PUPPY', 'OPQRSTUVWXY') 'PUYOQRSTVWX' >>> padded_key('RSA', 'ARTIST') Traceback (most recent call last): ... ValueError: duplicate characters in symbols: T """ syms = list(uniq(symbols)) if len(syms) != len(symbols): extra = ''.join(sorted({ i for i in symbols if symbols.count(i) > 1})) raise ValueError('duplicate characters in symbols: %s' % extra) extra = set(key) - set(syms) if extra: raise ValueError( 'characters in key but not symbols: %s' % ''.join( sorted(extra))) key0 = ''.join(list(uniq(key))) # remove from syms characters in key0 return key0 + translate(''.join(syms), None, key0) def check_and_join(phrase, symbols=None, filter=None): """ Joins characters of ``phrase`` and if ``symbols`` is given, raises an error if any character in ``phrase`` is not in ``symbols``. Parameters ========== phrase String or list of strings to be returned as a string. symbols Iterable of characters allowed in ``phrase``. If ``symbols`` is ``None``, no checking is performed. Examples ======== >>> from sympy.crypto.crypto import check_and_join >>> check_and_join('a phrase') 'a phrase' >>> check_and_join('a phrase'.upper().split()) 'APHRASE' >>> check_and_join('a phrase!'.upper().split(), 'ARE', filter=True) 'ARAE' >>> check_and_join('a phrase!'.upper().split(), 'ARE') Traceback (most recent call last): ... ValueError: characters in phrase but not symbols: "!HPS" """ rv = ''.join(''.join(phrase)) if symbols is not None: symbols = check_and_join(symbols) missing = ''.join(list(sorted(set(rv) - set(symbols)))) if missing: if not filter: raise ValueError( 'characters in phrase but not symbols: "%s"' % missing) rv = translate(rv, None, missing) return rv def _prep(msg, key, alp, default=None): if not alp: if not default: alp = AZ() msg = AZ(msg) key = AZ(key) else: alp = default else: alp = ''.join(alp) key = check_and_join(key, alp, filter=True) msg = check_and_join(msg, alp, filter=True) return msg, key, alp def cycle_list(k, n): """ Returns the elements of the list ``range(n)`` shifted to the left by ``k`` (so the list starts with ``k`` (mod ``n``)). Examples ======== >>> from sympy.crypto.crypto import cycle_list >>> cycle_list(3, 10) [3, 4, 5, 6, 7, 8, 9, 0, 1, 2] """ k = k % n return list(range(k, n)) + list(range(k)) ######## shift cipher examples ############ def encipher_shift(msg, key, symbols=None): """ Performs shift cipher encryption on plaintext msg, and returns the ciphertext. Parameters ========== key : int The secret key. msg : str Plaintext of upper-case letters. Returns ======= str Ciphertext of upper-case letters. Examples ======== >>> from sympy.crypto.crypto import encipher_shift, decipher_shift >>> msg = "GONAVYBEATARMY" >>> ct = encipher_shift(msg, 1); ct 'HPOBWZCFBUBSNZ' To decipher the shifted text, change the sign of the key: >>> encipher_shift(ct, -1) 'GONAVYBEATARMY' There is also a convenience function that does this with the original key: >>> decipher_shift(ct, 1) 'GONAVYBEATARMY' Notes ===== ALGORITHM: STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``msg`` a list ``L1`` of corresponding integers. 2. Compute from the list ``L1`` a new list ``L2``, given by adding ``(k mod 26)`` to each element in ``L1``. 3. Compute from the list ``L2`` a string ``ct`` of corresponding letters. The shift cipher is also called the Caesar cipher, after Julius Caesar, who, according to Suetonius, used it with a shift of three to protect messages of military significance. Caesar's nephew Augustus reportedly used a similar cipher, but with a right shift of 1. References ========== .. [1] https://en.wikipedia.org/wiki/Caesar_cipher .. [2] http://mathworld.wolfram.com/CaesarsMethod.html See Also ======== decipher_shift """ msg, _, A = _prep(msg, '', symbols) shift = len(A) - key % len(A) key = A[shift:] + A[:shift] return translate(msg, key, A) def decipher_shift(msg, key, symbols=None): """ Return the text by shifting the characters of ``msg`` to the left by the amount given by ``key``. Examples ======== >>> from sympy.crypto.crypto import encipher_shift, decipher_shift >>> msg = "GONAVYBEATARMY" >>> ct = encipher_shift(msg, 1); ct 'HPOBWZCFBUBSNZ' To decipher the shifted text, change the sign of the key: >>> encipher_shift(ct, -1) 'GONAVYBEATARMY' Or use this function with the original key: >>> decipher_shift(ct, 1) 'GONAVYBEATARMY' """ return encipher_shift(msg, -key, symbols) def encipher_rot13(msg, symbols=None): """ Performs the ROT13 encryption on a given plaintext ``msg``. Notes ===== ROT13 is a substitution cipher which substitutes each letter in the plaintext message for the letter furthest away from it in the English alphabet. Equivalently, it is just a Caeser (shift) cipher with a shift key of 13 (midway point of the alphabet). References ========== .. [1] https://en.wikipedia.org/wiki/ROT13 See Also ======== decipher_rot13 encipher_shift """ return encipher_shift(msg, 13, symbols) def decipher_rot13(msg, symbols=None): """ Performs the ROT13 decryption on a given plaintext ``msg``. Notes ===== ``decipher_rot13`` is equivalent to ``encipher_rot13`` as both ``decipher_shift`` with a key of 13 and ``encipher_shift`` key with a key of 13 will return the same results. Nonetheless, ``decipher_rot13`` has nonetheless been explicitly defined here for consistency. Examples ======== >>> from sympy.crypto.crypto import encipher_rot13, decipher_rot13 >>> msg = 'GONAVYBEATARMY' >>> ciphertext = encipher_rot13(msg);ciphertext 'TBANILORNGNEZL' >>> decipher_rot13(ciphertext) 'GONAVYBEATARMY' >>> encipher_rot13(msg) == decipher_rot13(msg) True >>> msg == decipher_rot13(ciphertext) True """ return decipher_shift(msg, 13, symbols) ######## affine cipher examples ############ def encipher_affine(msg, key, symbols=None, _inverse=False): r""" Performs the affine cipher encryption on plaintext ``msg``, and returns the ciphertext. Encryption is based on the map `x \rightarrow ax+b` (mod `N`) where ``N`` is the number of characters in the alphabet. Decryption is based on the map `x \rightarrow cx+d` (mod `N`), where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`). In particular, for the map to be invertible, we need `\mathrm{gcd}(a, N) = 1` and an error will be raised if this is not true. Parameters ========== msg : str Characters that appear in ``symbols``. a, b : int, int A pair integers, with ``gcd(a, N) = 1`` (the secret key). symbols String of characters (default = uppercase letters). When no symbols are given, ``msg`` is converted to upper case letters and all other characters are ignored. Returns ======= ct String of characters (the ciphertext message) Notes ===== ALGORITHM: STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``msg`` a list ``L1`` of corresponding integers. 2. Compute from the list ``L1`` a new list ``L2``, given by replacing ``x`` by ``a*x + b (mod N)``, for each element ``x`` in ``L1``. 3. Compute from the list ``L2`` a string ``ct`` of corresponding letters. This is a straightforward generalization of the shift cipher with the added complexity of requiring 2 characters to be deciphered in order to recover the key. References ========== .. [1] https://en.wikipedia.org/wiki/Affine_cipher See Also ======== decipher_affine """ msg, _, A = _prep(msg, '', symbols) N = len(A) a, b = key assert gcd(a, N) == 1 if _inverse: c = mod_inverse(a, N) d = -b*c a, b = c, d B = ''.join([A[(a*i + b) % N] for i in range(N)]) return translate(msg, A, B) def decipher_affine(msg, key, symbols=None): r""" Return the deciphered text that was made from the mapping, `x \rightarrow ax+b` (mod `N`), where ``N`` is the number of characters in the alphabet. Deciphering is done by reciphering with a new key: `x \rightarrow cx+d` (mod `N`), where `c = a^{-1}` (mod `N`) and `d = -a^{-1}b` (mod `N`). Examples ======== >>> from sympy.crypto.crypto import encipher_affine, decipher_affine >>> msg = "GO NAVY BEAT ARMY" >>> key = (3, 1) >>> encipher_affine(msg, key) 'TROBMVENBGBALV' >>> decipher_affine(_, key) 'GONAVYBEATARMY' See Also ======== encipher_affine """ return encipher_affine(msg, key, symbols, _inverse=True) def encipher_atbash(msg, symbols=None): r""" Enciphers a given ``msg`` into its Atbash ciphertext and returns it. Notes ===== Atbash is a substitution cipher originally used to encrypt the Hebrew alphabet. Atbash works on the principle of mapping each alphabet to its reverse / counterpart (i.e. a would map to z, b to y etc.) Atbash is functionally equivalent to the affine cipher with ``a = 25`` and ``b = 25`` See Also ======== decipher_atbash """ return encipher_affine(msg, (25, 25), symbols) def decipher_atbash(msg, symbols=None): r""" Deciphers a given ``msg`` using Atbash cipher and returns it. Notes ===== ``decipher_atbash`` is functionally equivalent to ``encipher_atbash``. However, it has still been added as a separate function to maintain consistency. Examples ======== >>> from sympy.crypto.crypto import encipher_atbash, decipher_atbash >>> msg = 'GONAVYBEATARMY' >>> encipher_atbash(msg) 'TLMZEBYVZGZINB' >>> decipher_atbash(msg) 'TLMZEBYVZGZINB' >>> encipher_atbash(msg) == decipher_atbash(msg) True >>> msg == encipher_atbash(encipher_atbash(msg)) True References ========== .. [1] https://en.wikipedia.org/wiki/Atbash See Also ======== encipher_atbash """ return decipher_affine(msg, (25, 25), symbols) #################### substitution cipher ########################### def encipher_substitution(msg, old, new=None): r""" Returns the ciphertext obtained by replacing each character that appears in ``old`` with the corresponding character in ``new``. If ``old`` is a mapping, then new is ignored and the replacements defined by ``old`` are used. Notes ===== This is a more general than the affine cipher in that the key can only be recovered by determining the mapping for each symbol. Though in practice, once a few symbols are recognized the mappings for other characters can be quickly guessed. Examples ======== >>> from sympy.crypto.crypto import encipher_substitution, AZ >>> old = 'OEYAG' >>> new = '034^6' >>> msg = AZ("go navy! beat army!") >>> ct = encipher_substitution(msg, old, new); ct '60N^V4B3^T^RM4' To decrypt a substitution, reverse the last two arguments: >>> encipher_substitution(ct, new, old) 'GONAVYBEATARMY' In the special case where ``old`` and ``new`` are a permutation of order 2 (representing a transposition of characters) their order is immaterial: >>> old = 'NAVY' >>> new = 'ANYV' >>> encipher = lambda x: encipher_substitution(x, old, new) >>> encipher('NAVY') 'ANYV' >>> encipher(_) 'NAVY' The substitution cipher, in general, is a method whereby "units" (not necessarily single characters) of plaintext are replaced with ciphertext according to a regular system. >>> ords = dict(zip('abc', ['\\%i' % ord(i) for i in 'abc'])) >>> print(encipher_substitution('abc', ords)) \97\98\99 References ========== .. [1] https://en.wikipedia.org/wiki/Substitution_cipher """ return translate(msg, old, new) ###################################################################### #################### Vigenere cipher examples ######################## ###################################################################### def encipher_vigenere(msg, key, symbols=None): """ Performs the Vigenere cipher encryption on plaintext ``msg``, and returns the ciphertext. Examples ======== >>> from sympy.crypto.crypto import encipher_vigenere, AZ >>> key = "encrypt" >>> msg = "meet me on monday" >>> encipher_vigenere(msg, key) 'QRGKKTHRZQEBPR' Section 1 of the Kryptos sculpture at the CIA headquarters uses this cipher and also changes the order of the the alphabet [2]_. Here is the first line of that section of the sculpture: >>> from sympy.crypto.crypto import decipher_vigenere, padded_key >>> alp = padded_key('KRYPTOS', AZ()) >>> key = 'PALIMPSEST' >>> msg = 'EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJ' >>> decipher_vigenere(msg, key, alp) 'BETWEENSUBTLESHADINGANDTHEABSENC' Notes ===== The Vigenere cipher is named after Blaise de Vigenere, a sixteenth century diplomat and cryptographer, by a historical accident. Vigenere actually invented a different and more complicated cipher. The so-called *Vigenere cipher* was actually invented by Giovan Batista Belaso in 1553. This cipher was used in the 1800's, for example, during the American Civil War. The Confederacy used a brass cipher disk to implement the Vigenere cipher (now on display in the NSA Museum in Fort Meade) [1]_. The Vigenere cipher is a generalization of the shift cipher. Whereas the shift cipher shifts each letter by the same amount (that amount being the key of the shift cipher) the Vigenere cipher shifts a letter by an amount determined by the key (which is a word or phrase known only to the sender and receiver). For example, if the key was a single letter, such as "C", then the so-called Vigenere cipher is actually a shift cipher with a shift of `2` (since "C" is the 2nd letter of the alphabet, if you start counting at `0`). If the key was a word with two letters, such as "CA", then the so-called Vigenere cipher will shift letters in even positions by `2` and letters in odd positions are left alone (shifted by `0`, since "A" is the 0th letter, if you start counting at `0`). ALGORITHM: INPUT: ``msg``: string of characters that appear in ``symbols`` (the plaintext) ``key``: a string of characters that appear in ``symbols`` (the secret key) ``symbols``: a string of letters defining the alphabet OUTPUT: ``ct``: string of characters (the ciphertext message) STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``key`` a list ``L1`` of corresponding integers. Let ``n1 = len(L1)``. 2. Compute from the string ``msg`` a list ``L2`` of corresponding integers. Let ``n2 = len(L2)``. 3. Break ``L2`` up sequentially into sublists of size ``n1``; the last sublist may be smaller than ``n1`` 4. For each of these sublists ``L`` of ``L2``, compute a new list ``C`` given by ``C[i] = L[i] + L1[i] (mod N)`` to the ``i``-th element in the sublist, for each ``i``. 5. Assemble these lists ``C`` by concatenation into a new list of length ``n2``. 6. Compute from the new list a string ``ct`` of corresponding letters. Once it is known that the key is, say, `n` characters long, frequency analysis can be applied to every `n`-th letter of the ciphertext to determine the plaintext. This method is called *Kasiski examination* (although it was first discovered by Babbage). If they key is as long as the message and is comprised of randomly selected characters -- a one-time pad -- the message is theoretically unbreakable. The cipher Vigenere actually discovered is an "auto-key" cipher described as follows. ALGORITHM: INPUT: ``key``: a string of letters (the secret key) ``msg``: string of letters (the plaintext message) OUTPUT: ``ct``: string of upper-case letters (the ciphertext message) STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``msg`` a list ``L2`` of corresponding integers. Let ``n2 = len(L2)``. 2. Let ``n1`` be the length of the key. Append to the string ``key`` the first ``n2 - n1`` characters of the plaintext message. Compute from this string (also of length ``n2``) a list ``L1`` of integers corresponding to the letter numbers in the first step. 3. Compute a new list ``C`` given by ``C[i] = L1[i] + L2[i] (mod N)``. 4. Compute from the new list a string ``ct`` of letters corresponding to the new integers. To decipher the auto-key ciphertext, the key is used to decipher the first ``n1`` characters and then those characters become the key to decipher the next ``n1`` characters, etc...: >>> m = AZ('go navy, beat army! yes you can'); m 'GONAVYBEATARMYYESYOUCAN' >>> key = AZ('gold bug'); n1 = len(key); n2 = len(m) >>> auto_key = key + m[:n2 - n1]; auto_key 'GOLDBUGGONAVYBEATARMYYE' >>> ct = encipher_vigenere(m, auto_key); ct 'MCYDWSHKOGAMKZCELYFGAYR' >>> n1 = len(key) >>> pt = [] >>> while ct: ... part, ct = ct[:n1], ct[n1:] ... pt.append(decipher_vigenere(part, key)) ... key = pt[-1] ... >>> ''.join(pt) == m True References ========== .. [1] https://en.wikipedia.org/wiki/Vigenere_cipher .. [2] http://web.archive.org/web/20071116100808/ .. [3] http://filebox.vt.edu/users/batman/kryptos.html (short URL: https://goo.gl/ijr22d) """ msg, key, A = _prep(msg, key, symbols) map = {c: i for i, c in enumerate(A)} key = [map[c] for c in key] N = len(map) k = len(key) rv = [] for i, m in enumerate(msg): rv.append(A[(map[m] + key[i % k]) % N]) rv = ''.join(rv) return rv def decipher_vigenere(msg, key, symbols=None): """ Decode using the Vigenere cipher. Examples ======== >>> from sympy.crypto.crypto import decipher_vigenere >>> key = "encrypt" >>> ct = "QRGK kt HRZQE BPR" >>> decipher_vigenere(ct, key) 'MEETMEONMONDAY' """ msg, key, A = _prep(msg, key, symbols) map = {c: i for i, c in enumerate(A)} N = len(A) # normally, 26 K = [map[c] for c in key] n = len(K) C = [map[c] for c in msg] rv = ''.join([A[(-K[i % n] + c) % N] for i, c in enumerate(C)]) return rv #################### Hill cipher ######################## def encipher_hill(msg, key, symbols=None, pad="Q"): r""" Return the Hill cipher encryption of ``msg``. Notes ===== The Hill cipher [1]_, invented by Lester S. Hill in the 1920's [2]_, was the first polygraphic cipher in which it was practical (though barely) to operate on more than three symbols at once. The following discussion assumes an elementary knowledge of matrices. First, each letter is first encoded as a number starting with 0. Suppose your message `msg` consists of `n` capital letters, with no spaces. This may be regarded an `n`-tuple M of elements of `Z_{26}` (if the letters are those of the English alphabet). A key in the Hill cipher is a `k x k` matrix `K`, all of whose entries are in `Z_{26}`, such that the matrix `K` is invertible (i.e., the linear transformation `K: Z_{N}^k \rightarrow Z_{N}^k` is one-to-one). Parameters ========== msg Plaintext message of `n` upper-case letters. key A `k \times k` invertible matrix `K`, all of whose entries are in `Z_{26}` (or whatever number of symbols are being used). pad Character (default "Q") to use to make length of text be a multiple of ``k``. Returns ======= ct Ciphertext of upper-case letters. Notes ===== ALGORITHM: STEPS: 0. Number the letters of the alphabet from 0, ..., N 1. Compute from the string ``msg`` a list ``L`` of corresponding integers. Let ``n = len(L)``. 2. Break the list ``L`` up into ``t = ceiling(n/k)`` sublists ``L_1``, ..., ``L_t`` of size ``k`` (with the last list "padded" to ensure its size is ``k``). 3. Compute new list ``C_1``, ..., ``C_t`` given by ``C[i] = K*L_i`` (arithmetic is done mod N), for each ``i``. 4. Concatenate these into a list ``C = C_1 + ... + C_t``. 5. Compute from ``C`` a string ``ct`` of corresponding letters. This has length ``k*t``. References ========== .. [1] https://en.wikipedia.org/wiki/Hill_cipher .. [2] Lester S. Hill, Cryptography in an Algebraic Alphabet, The American Mathematical Monthly Vol.36, June-July 1929, pp.306-312. See Also ======== decipher_hill """ assert key.is_square assert len(pad) == 1 msg, pad, A = _prep(msg, pad, symbols) map = {c: i for i, c in enumerate(A)} P = [map[c] for c in msg] N = len(A) k = key.cols n = len(P) m, r = divmod(n, k) if r: P = P + [map[pad]]*(k - r) m += 1 rv = ''.join([A[c % N] for j in range(m) for c in list(key*Matrix(k, 1, [P[i] for i in range(k*j, k*(j + 1))]))]) return rv def decipher_hill(msg, key, symbols=None): """ Deciphering is the same as enciphering but using the inverse of the key matrix. Examples ======== >>> from sympy.crypto.crypto import encipher_hill, decipher_hill >>> from sympy import Matrix >>> key = Matrix([[1, 2], [3, 5]]) >>> encipher_hill("meet me on monday", key) 'UEQDUEODOCTCWQ' >>> decipher_hill(_, key) 'MEETMEONMONDAY' When the length of the plaintext (stripped of invalid characters) is not a multiple of the key dimension, extra characters will appear at the end of the enciphered and deciphered text. In order to decipher the text, those characters must be included in the text to be deciphered. In the following, the key has a dimension of 4 but the text is 2 short of being a multiple of 4 so two characters will be added. >>> key = Matrix([[1, 1, 1, 2], [0, 1, 1, 0], ... [2, 2, 3, 4], [1, 1, 0, 1]]) >>> msg = "ST" >>> encipher_hill(msg, key) 'HJEB' >>> decipher_hill(_, key) 'STQQ' >>> encipher_hill(msg, key, pad="Z") 'ISPK' >>> decipher_hill(_, key) 'STZZ' If the last two characters of the ciphertext were ignored in either case, the wrong plaintext would be recovered: >>> decipher_hill("HD", key) 'ORMV' >>> decipher_hill("IS", key) 'UIKY' See Also ======== encipher_hill """ assert key.is_square msg, _, A = _prep(msg, '', symbols) map = {c: i for i, c in enumerate(A)} C = [map[c] for c in msg] N = len(A) k = key.cols n = len(C) m, r = divmod(n, k) if r: C = C + [0]*(k - r) m += 1 key_inv = key.inv_mod(N) rv = ''.join([A[p % N] for j in range(m) for p in list(key_inv*Matrix( k, 1, [C[i] for i in range(k*j, k*(j + 1))]))]) return rv #################### Bifid cipher ######################## def encipher_bifid(msg, key, symbols=None): r""" Performs the Bifid cipher encryption on plaintext ``msg``, and returns the ciphertext. This is the version of the Bifid cipher that uses an `n \times n` Polybius square. Parameters ========== msg Plaintext string. key Short string for key. Duplicate characters are ignored and then it is padded with the characters in ``symbols`` that were not in the short key. symbols `n \times n` characters defining the alphabet. (default is string.printable) Returns ======= ciphertext Ciphertext using Bifid5 cipher without spaces. See Also ======== decipher_bifid, encipher_bifid5, encipher_bifid6 References ========== .. [1] https://en.wikipedia.org/wiki/Bifid_cipher """ msg, key, A = _prep(msg, key, symbols, bifid10) long_key = ''.join(uniq(key)) or A n = len(A)**.5 if n != int(n): raise ValueError( 'Length of alphabet (%s) is not a square number.' % len(A)) N = int(n) if len(long_key) < N**2: long_key = list(long_key) + [x for x in A if x not in long_key] # the fractionalization row_col = {ch: divmod(i, N) for i, ch in enumerate(long_key)} r, c = zip(*[row_col[x] for x in msg]) rc = r + c ch = {i: ch for ch, i in row_col.items()} rv = ''.join(ch[i] for i in zip(rc[::2], rc[1::2])) return rv def decipher_bifid(msg, key, symbols=None): r""" Performs the Bifid cipher decryption on ciphertext ``msg``, and returns the plaintext. This is the version of the Bifid cipher that uses the `n \times n` Polybius square. Parameters ========== msg Ciphertext string. key Short string for key. Duplicate characters are ignored and then it is padded with the characters in symbols that were not in the short key. symbols `n \times n` characters defining the alphabet. (default=string.printable, a `10 \times 10` matrix) Returns ======= deciphered Deciphered text. Examples ======== >>> from sympy.crypto.crypto import ( ... encipher_bifid, decipher_bifid, AZ) Do an encryption using the bifid5 alphabet: >>> alp = AZ().replace('J', '') >>> ct = AZ("meet me on monday!") >>> key = AZ("gold bug") >>> encipher_bifid(ct, key, alp) 'IEILHHFSTSFQYE' When entering the text or ciphertext, spaces are ignored so it can be formatted as desired. Re-entering the ciphertext from the preceding, putting 4 characters per line and padding with an extra J, does not cause problems for the deciphering: >>> decipher_bifid(''' ... IEILH ... HFSTS ... FQYEJ''', key, alp) 'MEETMEONMONDAY' When no alphabet is given, all 100 printable characters will be used: >>> key = '' >>> encipher_bifid('hello world!', key) 'bmtwmg-bIo*w' >>> decipher_bifid(_, key) 'hello world!' If the key is changed, a different encryption is obtained: >>> key = 'gold bug' >>> encipher_bifid('hello world!', 'gold_bug') 'hg2sfuei7t}w' And if the key used to decrypt the message is not exact, the original text will not be perfectly obtained: >>> decipher_bifid(_, 'gold pug') 'heldo~wor6d!' """ msg, _, A = _prep(msg, '', symbols, bifid10) long_key = ''.join(uniq(key)) or A n = len(A)**.5 if n != int(n): raise ValueError( 'Length of alphabet (%s) is not a square number.' % len(A)) N = int(n) if len(long_key) < N**2: long_key = list(long_key) + [x for x in A if x not in long_key] # the reverse fractionalization row_col = { ch: divmod(i, N) for i, ch in enumerate(long_key)} rc = [i for c in msg for i in row_col[c]] n = len(msg) rc = zip(*(rc[:n], rc[n:])) ch = {i: ch for ch, i in row_col.items()} rv = ''.join(ch[i] for i in rc) return rv def bifid_square(key): """Return characters of ``key`` arranged in a square. Examples ======== >>> from sympy.crypto.crypto import ( ... bifid_square, AZ, padded_key, bifid5) >>> bifid_square(AZ().replace('J', '')) Matrix([ [A, B, C, D, E], [F, G, H, I, K], [L, M, N, O, P], [Q, R, S, T, U], [V, W, X, Y, Z]]) >>> bifid_square(padded_key(AZ('gold bug!'), bifid5)) Matrix([ [G, O, L, D, B], [U, A, C, E, F], [H, I, K, M, N], [P, Q, R, S, T], [V, W, X, Y, Z]]) See Also ======== padded_key """ A = ''.join(uniq(''.join(key))) n = len(A)**.5 if n != int(n): raise ValueError( 'Length of alphabet (%s) is not a square number.' % len(A)) n = int(n) f = lambda i, j: Symbol(A[n*i + j]) rv = Matrix(n, n, f) return rv def encipher_bifid5(msg, key): r""" Performs the Bifid cipher encryption on plaintext ``msg``, and returns the ciphertext. This is the version of the Bifid cipher that uses the `5 \times 5` Polybius square. The letter "J" is ignored so it must be replaced with something else (traditionally an "I") before encryption. ALGORITHM: (5x5 case) STEPS: 0. Create the `5 \times 5` Polybius square ``S`` associated to ``key`` as follows: a) moving from left-to-right, top-to-bottom, place the letters of the key into a `5 \times 5` matrix, b) if the key has less than 25 letters, add the letters of the alphabet not in the key until the `5 \times 5` square is filled. 1. Create a list ``P`` of pairs of numbers which are the coordinates in the Polybius square of the letters in ``msg``. 2. Let ``L1`` be the list of all first coordinates of ``P`` (length of ``L1 = n``), let ``L2`` be the list of all second coordinates of ``P`` (so the length of ``L2`` is also ``n``). 3. Let ``L`` be the concatenation of ``L1`` and ``L2`` (length ``L = 2*n``), except that consecutive numbers are paired ``(L[2*i], L[2*i + 1])``. You can regard ``L`` as a list of pairs of length ``n``. 4. Let ``C`` be the list of all letters which are of the form ``S[i, j]``, for all ``(i, j)`` in ``L``. As a string, this is the ciphertext of ``msg``. Parameters ========== msg : str Plaintext string. Converted to upper case and filtered of anything but all letters except J. key Short string for key; non-alphabetic letters, J and duplicated characters are ignored and then, if the length is less than 25 characters, it is padded with other letters of the alphabet (in alphabetical order). Returns ======= ct Ciphertext (all caps, no spaces). Examples ======== >>> from sympy.crypto.crypto import ( ... encipher_bifid5, decipher_bifid5) "J" will be omitted unless it is replaced with something else: >>> round_trip = lambda m, k: \ ... decipher_bifid5(encipher_bifid5(m, k), k) >>> key = 'a' >>> msg = "JOSIE" >>> round_trip(msg, key) 'OSIE' >>> round_trip(msg.replace("J", "I"), key) 'IOSIE' >>> j = "QIQ" >>> round_trip(msg.replace("J", j), key).replace(j, "J") 'JOSIE' Notes ===== The Bifid cipher was invented around 1901 by Felix Delastelle. It is a *fractional substitution* cipher, where letters are replaced by pairs of symbols from a smaller alphabet. The cipher uses a `5 \times 5` square filled with some ordering of the alphabet, except that "J" is replaced with "I" (this is a so-called Polybius square; there is a `6 \times 6` analog if you add back in "J" and also append onto the usual 26 letter alphabet, the digits 0, 1, ..., 9). According to Helen Gaines' book *Cryptanalysis*, this type of cipher was used in the field by the German Army during World War I. See Also ======== decipher_bifid5, encipher_bifid """ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5) key = padded_key(key, bifid5) return encipher_bifid(msg, '', key) def decipher_bifid5(msg, key): r""" Return the Bifid cipher decryption of ``msg``. This is the version of the Bifid cipher that uses the `5 \times 5` Polybius square; the letter "J" is ignored unless a ``key`` of length 25 is used. Parameters ========== msg Ciphertext string. key Short string for key; duplicated characters are ignored and if the length is less then 25 characters, it will be padded with other letters from the alphabet omitting "J". Non-alphabetic characters are ignored. Returns ======= plaintext Plaintext from Bifid5 cipher (all caps, no spaces). Examples ======== >>> from sympy.crypto.crypto import encipher_bifid5, decipher_bifid5 >>> key = "gold bug" >>> encipher_bifid5('meet me on friday', key) 'IEILEHFSTSFXEE' >>> encipher_bifid5('meet me on monday', key) 'IEILHHFSTSFQYE' >>> decipher_bifid5(_, key) 'MEETMEONMONDAY' """ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid5) key = padded_key(key, bifid5) return decipher_bifid(msg, '', key) def bifid5_square(key=None): r""" 5x5 Polybius square. Produce the Polybius square for the `5 \times 5` Bifid cipher. Examples ======== >>> from sympy.crypto.crypto import bifid5_square >>> bifid5_square("gold bug") Matrix([ [G, O, L, D, B], [U, A, C, E, F], [H, I, K, M, N], [P, Q, R, S, T], [V, W, X, Y, Z]]) """ if not key: key = bifid5 else: _, key, _ = _prep('', key.upper(), None, bifid5) key = padded_key(key, bifid5) return bifid_square(key) def encipher_bifid6(msg, key): r""" Performs the Bifid cipher encryption on plaintext ``msg``, and returns the ciphertext. This is the version of the Bifid cipher that uses the `6 \times 6` Polybius square. Parameters ========== msg Plaintext string (digits okay). key Short string for key (digits okay). If ``key`` is less than 36 characters long, the square will be filled with letters A through Z and digits 0 through 9. Returns ======= ciphertext Ciphertext from Bifid cipher (all caps, no spaces). See Also ======== decipher_bifid6, encipher_bifid """ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6) key = padded_key(key, bifid6) return encipher_bifid(msg, '', key) def decipher_bifid6(msg, key): r""" Performs the Bifid cipher decryption on ciphertext ``msg``, and returns the plaintext. This is the version of the Bifid cipher that uses the `6 \times 6` Polybius square. Parameters ========== msg Ciphertext string (digits okay); converted to upper case key Short string for key (digits okay). If ``key`` is less than 36 characters long, the square will be filled with letters A through Z and digits 0 through 9. All letters are converted to uppercase. Returns ======= plaintext Plaintext from Bifid cipher (all caps, no spaces). Examples ======== >>> from sympy.crypto.crypto import encipher_bifid6, decipher_bifid6 >>> key = "gold bug" >>> encipher_bifid6('meet me on monday at 8am', key) 'KFKLJJHF5MMMKTFRGPL' >>> decipher_bifid6(_, key) 'MEETMEONMONDAYAT8AM' """ msg, key, _ = _prep(msg.upper(), key.upper(), None, bifid6) key = padded_key(key, bifid6) return decipher_bifid(msg, '', key) def bifid6_square(key=None): r""" 6x6 Polybius square. Produces the Polybius square for the `6 \times 6` Bifid cipher. Assumes alphabet of symbols is "A", ..., "Z", "0", ..., "9". Examples ======== >>> from sympy.crypto.crypto import bifid6_square >>> key = "gold bug" >>> bifid6_square(key) Matrix([ [G, O, L, D, B, U], [A, C, E, F, H, I], [J, K, M, N, P, Q], [R, S, T, V, W, X], [Y, Z, 0, 1, 2, 3], [4, 5, 6, 7, 8, 9]]) """ if not key: key = bifid6 else: _, key, _ = _prep('', key.upper(), None, bifid6) key = padded_key(key, bifid6) return bifid_square(key) #################### RSA ############################# def _decipher_rsa_crt(i, d, factors): """Decipher RSA using chinese remainder theorem from the information of the relatively-prime factors of the modulus. Parameters ========== i : integer Ciphertext d : integer The exponent component factors : list of relatively-prime integers The integers given must be coprime and the product must equal the modulus component of the original RSA key. Examples ======== How to decrypt RSA with CRT: >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key >>> primes = [61, 53] >>> e = 17 >>> args = primes + [e] >>> puk = rsa_public_key(*args) >>> prk = rsa_private_key(*args) >>> from sympy.crypto.crypto import encipher_rsa, _decipher_rsa_crt >>> msg = 65 >>> crt_primes = primes >>> encrypted = encipher_rsa(msg, puk) >>> decrypted = _decipher_rsa_crt(encrypted, prk[1], primes) >>> decrypted 65 """ from sympy.ntheory.modular import crt moduluses = [pow(i, d, p) for p in factors] result = crt(factors, moduluses) if not result: raise ValueError("CRT failed") return result[0] def _rsa_key(*args, public=True, private=True, totient='Euler', index=None, multipower=None): r"""A private subroutine to generate RSA key Parameters ========== public, private : bool, optional Flag to generate either a public key, a private key totient : 'Euler' or 'Carmichael' Different notation used for totient. multipower : bool, optional Flag to bypass warning for multipower RSA. """ from sympy.ntheory import totient as _euler from sympy.ntheory import reduced_totient as _carmichael if len(args) < 2: return False if totient not in ('Euler', 'Carmichael'): raise ValueError( "The argument totient={} should either be " \ "'Euler', 'Carmichalel'." \ .format(totient)) if totient == 'Euler': _totient = _euler else: _totient = _carmichael if index is not None: index = as_int(index) if totient != 'Carmichael': raise ValueError( "Setting the 'index' keyword argument requires totient" "notation to be specified as 'Carmichael'.") primes, e = args[:-1], args[-1] if any(not isprime(p) for p in primes): new_primes = [] for i in primes: new_primes.extend(factorint(i, multiple=True)) primes = new_primes n = reduce(lambda i, j: i*j, primes) tally = multiset(primes) if all(v == 1 for v in tally.values()): multiple = list(tally.keys()) phi = _totient._from_distinct_primes(*multiple) else: if not multipower: NonInvertibleCipherWarning( 'Non-distinctive primes found in the factors {}. ' 'The cipher may not be decryptable for some numbers ' 'in the complete residue system Z[{}], but the cipher ' 'can still be valid if you restrict the domain to be ' 'the reduced residue system Z*[{}]. You can pass ' 'the flag multipower=True if you want to suppress this ' 'warning.' .format(primes, n, n) ).warn() phi = _totient._from_factors(tally) if igcd(e, phi) == 1: if public and not private: if isinstance(index, int): e = e % phi e += index * phi return n, e if private and not public: d = mod_inverse(e, phi) if isinstance(index, int): d += index * phi return n, d return False def rsa_public_key(*args, **kwargs): r"""Return the RSA *public key* pair, `(n, e)` Parameters ========== args : naturals If specified as `p, q, e` where `p` and `q` are distinct primes and `e` is a desired public exponent of the RSA, `n = p q` and `e` will be verified against the totient `\phi(n)` (Euler totient) or `\lambda(n)` (Carmichael totient) to be `\gcd(e, \phi(n)) = 1` or `\gcd(e, \lambda(n)) = 1`. If specified as `p_1, p_2, ..., p_n, e` where `p_1, p_2, ..., p_n` are specified as primes, and `e` is specified as a desired public exponent of the RSA, it will be able to form a multi-prime RSA, which is a more generalized form of the popular 2-prime RSA. It can also be possible to form a single-prime RSA by specifying the argument as `p, e`, which can be considered a trivial case of a multiprime RSA. Furthermore, it can be possible to form a multi-power RSA by specifying two or more pairs of the primes to be same. However, unlike the two-distinct prime RSA or multi-prime RSA, not every numbers in the complete residue system (`\mathbb{Z}_n`) will be decryptable since the mapping `\mathbb{Z}_{n} \rightarrow \mathbb{Z}_{n}` will not be bijective. (Only except for the trivial case when `e = 1` or more generally, .. math:: e \in \left \{ 1 + k \lambda(n) \mid k \in \mathbb{Z} \land k \geq 0 \right \} when RSA reduces to the identity.) However, the RSA can still be decryptable for the numbers in the reduced residue system (`\mathbb{Z}_n^{\times}`), since the mapping `\mathbb{Z}_{n}^{\times} \rightarrow \mathbb{Z}_{n}^{\times}` can still be bijective. If you pass a non-prime integer to the arguments `p_1, p_2, ..., p_n`, the particular number will be prime-factored and it will become either a multi-prime RSA or a multi-power RSA in its canonical form, depending on whether the product equals its radical or not. `p_1 p_2 ... p_n = \text{rad}(p_1 p_2 ... p_n)` totient : bool, optional If ``'Euler'``, it uses Euler's totient `\phi(n)` which is :meth:`sympy.ntheory.factor_.totient` in SymPy. If ``'Carmichael'``, it uses Carmichael's totient `\lambda(n)` which is :meth:`sympy.ntheory.factor_.reduced_totient` in SymPy. Unlike private key generation, this is a trivial keyword for public key generation because `\gcd(e, \phi(n)) = 1 \iff \gcd(e, \lambda(n)) = 1`. index : nonnegative integer, optional Returns an arbitrary solution of a RSA public key at the index specified at `0, 1, 2, ...`. This parameter needs to be specified along with ``totient='Carmichael'``. Similarly to the non-uniquenss of a RSA private key as described in the ``index`` parameter documentation in :meth:`rsa_private_key`, RSA public key is also not unique and there is an infinite number of RSA public exponents which can behave in the same manner. From any given RSA public exponent `e`, there are can be an another RSA public exponent `e + k \lambda(n)` where `k` is an integer, `\lambda` is a Carmichael's totient function. However, considering only the positive cases, there can be a principal solution of a RSA public exponent `e_0` in `0 < e_0 < \lambda(n)`, and all the other solutions can be canonicalzed in a form of `e_0 + k \lambda(n)`. ``index`` specifies the `k` notation to yield any possible value an RSA public key can have. An example of computing any arbitrary RSA public key: >>> from sympy.crypto.crypto import rsa_public_key >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=0) (3233, 17) >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=1) (3233, 797) >>> rsa_public_key(61, 53, 17, totient='Carmichael', index=2) (3233, 1577) multipower : bool, optional Any pair of non-distinct primes found in the RSA specification will restrict the domain of the cryptosystem, as noted in the explaination of the parameter ``args``. SymPy RSA key generator may give a warning before dispatching it as a multi-power RSA, however, you can disable the warning if you pass ``True`` to this keyword. Returns ======= (n, e) : int, int `n` is a product of any arbitrary number of primes given as the argument. `e` is relatively prime (coprime) to the Euler totient `\phi(n)`. False Returned if less than two arguments are given, or `e` is not relatively prime to the modulus. Examples ======== >>> from sympy.crypto.crypto import rsa_public_key A public key of a two-prime RSA: >>> p, q, e = 3, 5, 7 >>> rsa_public_key(p, q, e) (15, 7) >>> rsa_public_key(p, q, 30) False A public key of a multiprime RSA: >>> primes = [2, 3, 5, 7, 11, 13] >>> e = 7 >>> args = primes + [e] >>> rsa_public_key(*args) (30030, 7) Notes ===== Although the RSA can be generalized over any modulus `n`, using two large primes had became the most popular specification because a product of two large primes is usually the hardest to factor relatively to the digits of `n` can have. However, it may need further understanding of the time complexities of each prime-factoring algorithms to verify the claim. See Also ======== rsa_private_key encipher_rsa decipher_rsa References ========== .. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29 .. [2] http://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf .. [3] https://link.springer.com/content/pdf/10.1007%2FBFb0055738.pdf .. [4] http://www.itiis.org/digital-library/manuscript/1381 """ return _rsa_key(*args, public=True, private=False, **kwargs) def rsa_private_key(*args, **kwargs): r"""Return the RSA *private key* pair, `(n, d)` Parameters ========== args : naturals The keyword is identical to the ``args`` in :meth:`rsa_public_key`. totient : bool, optional If ``'Euler'``, it uses Euler's totient convention `\phi(n)` which is :meth:`sympy.ntheory.factor_.totient` in SymPy. If ``'Carmichael'``, it uses Carmichael's totient convention `\lambda(n)` which is :meth:`sympy.ntheory.factor_.reduced_totient` in SymPy. There can be some output differences for private key generation as examples below. Example using Euler's totient: >>> from sympy.crypto.crypto import rsa_private_key >>> rsa_private_key(61, 53, 17, totient='Euler') (3233, 2753) Example using Carmichael's totient: >>> from sympy.crypto.crypto import rsa_private_key >>> rsa_private_key(61, 53, 17, totient='Carmichael') (3233, 413) index : nonnegative integer, optional Returns an arbitrary solution of a RSA private key at the index specified at `0, 1, 2, ...`. This parameter needs to be specified along with ``totient='Carmichael'``. RSA private exponent is a non-unique solution of `e d \mod \lambda(n) = 1` and it is possible in any form of `d + k \lambda(n)`, where `d` is an another already-computed private exponent, and `\lambda` is a Carmichael's totient function, and `k` is any integer. However, considering only the positive cases, there can be a principal solution of a RSA private exponent `d_0` in `0 < d_0 < \lambda(n)`, and all the other solutions can be canonicalzed in a form of `d_0 + k \lambda(n)`. ``index`` specifies the `k` notation to yield any possible value an RSA private key can have. An example of computing any arbitrary RSA private key: >>> from sympy.crypto.crypto import rsa_private_key >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=0) (3233, 413) >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=1) (3233, 1193) >>> rsa_private_key(61, 53, 17, totient='Carmichael', index=2) (3233, 1973) multipower : bool, optional The keyword is identical to the ``multipower`` in :meth:`rsa_public_key`. Returns ======= (n, d) : int, int `n` is a product of any arbitrary number of primes given as the argument. `d` is the inverse of `e` (mod `\phi(n)`) where `e` is the exponent given, and `\phi` is a Euler totient. False Returned if less than two arguments are given, or `e` is not relatively prime to the totient of the modulus. Examples ======== >>> from sympy.crypto.crypto import rsa_private_key A private key of a two-prime RSA: >>> p, q, e = 3, 5, 7 >>> rsa_private_key(p, q, e) (15, 7) >>> rsa_private_key(p, q, 30) False A private key of a multiprime RSA: >>> primes = [2, 3, 5, 7, 11, 13] >>> e = 7 >>> args = primes + [e] >>> rsa_private_key(*args) (30030, 823) See Also ======== rsa_public_key encipher_rsa decipher_rsa References ========== .. [1] https://en.wikipedia.org/wiki/RSA_%28cryptosystem%29 .. [2] http://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf .. [3] https://link.springer.com/content/pdf/10.1007%2FBFb0055738.pdf .. [4] http://www.itiis.org/digital-library/manuscript/1381 """ return _rsa_key(*args, public=False, private=True, **kwargs) def _encipher_decipher_rsa(i, key, factors=None): n, d = key if not factors: return pow(i, d, n) def _is_coprime_set(l): is_coprime_set = True for i in range(len(l)): for j in range(i+1, len(l)): if igcd(l[i], l[j]) != 1: is_coprime_set = False break return is_coprime_set prod = reduce(lambda i, j: i*j, factors) if prod == n and _is_coprime_set(factors): return _decipher_rsa_crt(i, d, factors) return _encipher_decipher_rsa(i, key, factors=None) def encipher_rsa(i, key, factors=None): r"""Encrypt the plaintext with RSA. Parameters ========== i : integer The plaintext to be encrypted for. key : (n, e) where n, e are integers `n` is the modulus of the key and `e` is the exponent of the key. The encryption is computed by `i^e \bmod n`. The key can either be a public key or a private key, however, the message encrypted by a public key can only be decrypted by a private key, and vice versa, as RSA is an asymmetric cryptography system. factors : list of coprime integers This is identical to the keyword ``factors`` in :meth:`decipher_rsa`. Notes ===== Some specifications may make the RSA not cryptographically meaningful. For example, `0`, `1` will remain always same after taking any number of exponentiation, thus, should be avoided. Furthermore, if `i^e < n`, `i` may easily be figured out by taking `e` th root. And also, specifying the exponent as `1` or in more generalized form as `1 + k \lambda(n)` where `k` is an nonnegative integer, `\lambda` is a carmichael totient, the RSA becomes an identity mapping. Examples ======== >>> from sympy.crypto.crypto import encipher_rsa >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key Public Key Encryption: >>> p, q, e = 3, 5, 7 >>> puk = rsa_public_key(p, q, e) >>> msg = 12 >>> encipher_rsa(msg, puk) 3 Private Key Encryption: >>> p, q, e = 3, 5, 7 >>> prk = rsa_private_key(p, q, e) >>> msg = 12 >>> encipher_rsa(msg, prk) 3 Encryption using chinese remainder theorem: >>> encipher_rsa(msg, prk, factors=[p, q]) 3 """ return _encipher_decipher_rsa(i, key, factors=factors) def decipher_rsa(i, key, factors=None): r"""Decrypt the ciphertext with RSA. Parameters ========== i : integer The ciphertext to be decrypted for. key : (n, d) where n, d are integers `n` is the modulus of the key and `d` is the exponent of the key. The decryption is computed by `i^d \bmod n`. The key can either be a public key or a private key, however, the message encrypted by a public key can only be decrypted by a private key, and vice versa, as RSA is an asymmetric cryptography system. factors : list of coprime integers As the modulus `n` created from RSA key generation is composed of arbitrary prime factors `n = {p_1}^{k_1}{p_2}^{k_2}...{p_n}^{k_n}` where `p_1, p_2, ..., p_n` are distinct primes and `k_1, k_2, ..., k_n` are positive integers, chinese remainder theorem can be used to compute `i^d \bmod n` from the fragmented modulo operations like .. math:: i^d \bmod {p_1}^{k_1}, i^d \bmod {p_2}^{k_2}, ... , i^d \bmod {p_n}^{k_n} or like .. math:: i^d \bmod {p_1}^{k_1}{p_2}^{k_2}, i^d \bmod {p_3}^{k_3}, ... , i^d \bmod {p_n}^{k_n} as long as every moduli does not share any common divisor each other. The raw primes used in generating the RSA key pair can be a good option. Note that the speed advantage of using this is only viable for very large cases (Like 2048-bit RSA keys) since the overhead of using pure python implementation of :meth:`sympy.ntheory.modular.crt` may overcompensate the theoritical speed advantage. Notes ===== See the ``Notes`` section in the documentation of :meth:`encipher_rsa` Examples ======== >>> from sympy.crypto.crypto import decipher_rsa, encipher_rsa >>> from sympy.crypto.crypto import rsa_public_key, rsa_private_key Public Key Encryption and Decryption: >>> p, q, e = 3, 5, 7 >>> prk = rsa_private_key(p, q, e) >>> puk = rsa_public_key(p, q, e) >>> msg = 12 >>> new_msg = encipher_rsa(msg, prk) >>> new_msg 3 >>> decipher_rsa(new_msg, puk) 12 Private Key Encryption and Decryption: >>> p, q, e = 3, 5, 7 >>> prk = rsa_private_key(p, q, e) >>> puk = rsa_public_key(p, q, e) >>> msg = 12 >>> new_msg = encipher_rsa(msg, puk) >>> new_msg 3 >>> decipher_rsa(new_msg, prk) 12 Decryption using chinese remainder theorem: >>> decipher_rsa(new_msg, prk, factors=[p, q]) 12 """ return _encipher_decipher_rsa(i, key, factors=factors) #################### kid krypto (kid RSA) ############################# def kid_rsa_public_key(a, b, A, B): r""" Kid RSA is a version of RSA useful to teach grade school children since it does not involve exponentiation. Alice wants to talk to Bob. Bob generates keys as follows. Key generation: * Select positive integers `a, b, A, B` at random. * Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`, `n = (e d - 1)//M`. * The *public key* is `(n, e)`. Bob sends these to Alice. * The *private key* is `(n, d)`, which Bob keeps secret. Encryption: If `p` is the plaintext message then the ciphertext is `c = p e \pmod n`. Decryption: If `c` is the ciphertext message then the plaintext is `p = c d \pmod n`. Examples ======== >>> from sympy.crypto.crypto import kid_rsa_public_key >>> a, b, A, B = 3, 4, 5, 6 >>> kid_rsa_public_key(a, b, A, B) (369, 58) """ M = a*b - 1 e = A*M + a d = B*M + b n = (e*d - 1)//M return n, e def kid_rsa_private_key(a, b, A, B): """ Compute `M = a b - 1`, `e = A M + a`, `d = B M + b`, `n = (e d - 1) / M`. The *private key* is `d`, which Bob keeps secret. Examples ======== >>> from sympy.crypto.crypto import kid_rsa_private_key >>> a, b, A, B = 3, 4, 5, 6 >>> kid_rsa_private_key(a, b, A, B) (369, 70) """ M = a*b - 1 e = A*M + a d = B*M + b n = (e*d - 1)//M return n, d def encipher_kid_rsa(msg, key): """ Here ``msg`` is the plaintext and ``key`` is the public key. Examples ======== >>> from sympy.crypto.crypto import ( ... encipher_kid_rsa, kid_rsa_public_key) >>> msg = 200 >>> a, b, A, B = 3, 4, 5, 6 >>> key = kid_rsa_public_key(a, b, A, B) >>> encipher_kid_rsa(msg, key) 161 """ n, e = key return (msg*e) % n def decipher_kid_rsa(msg, key): """ Here ``msg`` is the plaintext and ``key`` is the private key. Examples ======== >>> from sympy.crypto.crypto import ( ... kid_rsa_public_key, kid_rsa_private_key, ... decipher_kid_rsa, encipher_kid_rsa) >>> a, b, A, B = 3, 4, 5, 6 >>> d = kid_rsa_private_key(a, b, A, B) >>> msg = 200 >>> pub = kid_rsa_public_key(a, b, A, B) >>> pri = kid_rsa_private_key(a, b, A, B) >>> ct = encipher_kid_rsa(msg, pub) >>> decipher_kid_rsa(ct, pri) 200 """ n, d = key return (msg*d) % n #################### Morse Code ###################################### morse_char = { ".-": "A", "-...": "B", "-.-.": "C", "-..": "D", ".": "E", "..-.": "F", "--.": "G", "....": "H", "..": "I", ".---": "J", "-.-": "K", ".-..": "L", "--": "M", "-.": "N", "---": "O", ".--.": "P", "--.-": "Q", ".-.": "R", "...": "S", "-": "T", "..-": "U", "...-": "V", ".--": "W", "-..-": "X", "-.--": "Y", "--..": "Z", "-----": "0", ".----": "1", "..---": "2", "...--": "3", "....-": "4", ".....": "5", "-....": "6", "--...": "7", "---..": "8", "----.": "9", ".-.-.-": ".", "--..--": ",", "---...": ":", "-.-.-.": ";", "..--..": "?", "-....-": "-", "..--.-": "_", "-.--.": "(", "-.--.-": ")", ".----.": "'", "-...-": "=", ".-.-.": "+", "-..-.": "/", ".--.-.": "@", "...-..-": "$", "-.-.--": "!"} char_morse = {v: k for k, v in morse_char.items()} def encode_morse(msg, sep='|', mapping=None): """ Encodes a plaintext into popular Morse Code with letters separated by `sep` and words by a double `sep`. Examples ======== >>> from sympy.crypto.crypto import encode_morse >>> msg = 'ATTACK RIGHT FLANK' >>> encode_morse(msg) '.-|-|-|.-|-.-.|-.-||.-.|..|--.|....|-||..-.|.-..|.-|-.|-.-' References ========== .. [1] https://en.wikipedia.org/wiki/Morse_code """ mapping = mapping or char_morse assert sep not in mapping word_sep = 2*sep mapping[" "] = word_sep suffix = msg and msg[-1] in whitespace # normalize whitespace msg = (' ' if word_sep else '').join(msg.split()) # omit unmapped chars chars = set(''.join(msg.split())) ok = set(mapping.keys()) msg = translate(msg, None, ''.join(chars - ok)) morsestring = [] words = msg.split() for word in words: morseword = [] for letter in word: morseletter = mapping[letter] morseword.append(morseletter) word = sep.join(morseword) morsestring.append(word) return word_sep.join(morsestring) + (word_sep if suffix else '') def decode_morse(msg, sep='|', mapping=None): """ Decodes a Morse Code with letters separated by `sep` (default is '|') and words by `word_sep` (default is '||) into plaintext. Examples ======== >>> from sympy.crypto.crypto import decode_morse >>> mc = '--|---|...-|.||.|.-|...|-' >>> decode_morse(mc) 'MOVE EAST' References ========== .. [1] https://en.wikipedia.org/wiki/Morse_code """ mapping = mapping or morse_char word_sep = 2*sep characterstring = [] words = msg.strip(word_sep).split(word_sep) for word in words: letters = word.split(sep) chars = [mapping[c] for c in letters] word = ''.join(chars) characterstring.append(word) rv = " ".join(characterstring) return rv #################### LFSRs ########################################## def lfsr_sequence(key, fill, n): r""" This function creates an LFSR sequence. Parameters ========== key : list A list of finite field elements, `[c_0, c_1, \ldots, c_k].` fill : list The list of the initial terms of the LFSR sequence, `[x_0, x_1, \ldots, x_k].` n Number of terms of the sequence that the function returns. Returns ======= L The LFSR sequence defined by `x_{n+1} = c_k x_n + \ldots + c_0 x_{n-k}`, for `n \leq k`. Notes ===== S. Golomb [G]_ gives a list of three statistical properties a sequence of numbers `a = \{a_n\}_{n=1}^\infty`, `a_n \in \{0,1\}`, should display to be considered "random". Define the autocorrelation of `a` to be .. math:: C(k) = C(k,a) = \lim_{N\rightarrow \infty} {1\over N}\sum_{n=1}^N (-1)^{a_n + a_{n+k}}. In the case where `a` is periodic with period `P` then this reduces to .. math:: C(k) = {1\over P}\sum_{n=1}^P (-1)^{a_n + a_{n+k}}. Assume `a` is periodic with period `P`. - balance: .. math:: \left|\sum_{n=1}^P(-1)^{a_n}\right| \leq 1. - low autocorrelation: .. math:: C(k) = \left\{ \begin{array}{cc} 1,& k = 0,\\ \epsilon, & k \ne 0. \end{array} \right. (For sequences satisfying these first two properties, it is known that `\epsilon = -1/P` must hold.) - proportional runs property: In each period, half the runs have length `1`, one-fourth have length `2`, etc. Moreover, there are as many runs of `1`'s as there are of `0`'s. Examples ======== >>> from sympy.crypto.crypto import lfsr_sequence >>> from sympy.polys.domains import FF >>> F = FF(2) >>> fill = [F(1), F(1), F(0), F(1)] >>> key = [F(1), F(0), F(0), F(1)] >>> lfsr_sequence(key, fill, 10) [1 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 0 mod 2, 1 mod 2, 1 mod 2, 0 mod 2, 0 mod 2, 1 mod 2] References ========== .. [G] Solomon Golomb, Shift register sequences, Aegean Park Press, Laguna Hills, Ca, 1967 """ if not isinstance(key, list): raise TypeError("key must be a list") if not isinstance(fill, list): raise TypeError("fill must be a list") p = key[0].mod F = FF(p) s = fill k = len(fill) L = [] for i in range(n): s0 = s[:] L.append(s[0]) s = s[1:k] x = sum([int(key[i]*s0[i]) for i in range(k)]) s.append(F(x)) return L # use [x.to_int() for x in L] for int version def lfsr_autocorrelation(L, P, k): """ This function computes the LFSR autocorrelation function. Parameters ========== L A periodic sequence of elements of `GF(2)`. L must have length larger than P. P The period of L. k : int An integer `k` (`0 < k < P`). Returns ======= autocorrelation The k-th value of the autocorrelation of the LFSR L. Examples ======== >>> from sympy.crypto.crypto import ( ... lfsr_sequence, lfsr_autocorrelation) >>> from sympy.polys.domains import FF >>> F = FF(2) >>> fill = [F(1), F(1), F(0), F(1)] >>> key = [F(1), F(0), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_autocorrelation(s, 15, 7) -1/15 >>> lfsr_autocorrelation(s, 15, 0) 1 """ if not isinstance(L, list): raise TypeError("L (=%s) must be a list" % L) P = int(P) k = int(k) L0 = L[:P] # slices makes a copy L1 = L0 + L0[:k] L2 = [(-1)**(L1[i].to_int() + L1[i + k].to_int()) for i in range(P)] tot = sum(L2) return Rational(tot, P) def lfsr_connection_polynomial(s): """ This function computes the LFSR connection polynomial. Parameters ========== s A sequence of elements of even length, with entries in a finite field. Returns ======= C(x) The connection polynomial of a minimal LFSR yielding s. This implements the algorithm in section 3 of J. L. Massey's article [M]_. Examples ======== >>> from sympy.crypto.crypto import ( ... lfsr_sequence, lfsr_connection_polynomial) >>> from sympy.polys.domains import FF >>> F = FF(2) >>> fill = [F(1), F(1), F(0), F(1)] >>> key = [F(1), F(0), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**4 + x + 1 >>> fill = [F(1), F(0), F(0), F(1)] >>> key = [F(1), F(1), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**3 + 1 >>> fill = [F(1), F(0), F(1)] >>> key = [F(1), F(1), F(0)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**3 + x**2 + 1 >>> fill = [F(1), F(0), F(1)] >>> key = [F(1), F(0), F(1)] >>> s = lfsr_sequence(key, fill, 20) >>> lfsr_connection_polynomial(s) x**3 + x + 1 References ========== .. [M] James L. Massey, "Shift-Register Synthesis and BCH Decoding." IEEE Trans. on Information Theory, vol. 15(1), pp. 122-127, Jan 1969. """ # Initialization: p = s[0].mod x = Symbol("x") C = 1*x**0 B = 1*x**0 m = 1 b = 1*x**0 L = 0 N = 0 while N < len(s): if L > 0: dC = Poly(C).degree() r = min(L + 1, dC + 1) coeffsC = [C.subs(x, 0)] + [C.coeff(x**i) for i in range(1, dC + 1)] d = (s[N].to_int() + sum([coeffsC[i]*s[N - i].to_int() for i in range(1, r)])) % p if L == 0: d = s[N].to_int()*x**0 if d == 0: m += 1 N += 1 if d > 0: if 2*L > N: C = (C - d*((b**(p - 2)) % p)*x**m*B).expand() m += 1 N += 1 else: T = C C = (C - d*((b**(p - 2)) % p)*x**m*B).expand() L = N + 1 - L m = 1 b = d B = T N += 1 dC = Poly(C).degree() coeffsC = [C.subs(x, 0)] + [C.coeff(x**i) for i in range(1, dC + 1)] return sum([coeffsC[i] % p*x**i for i in range(dC + 1) if coeffsC[i] is not None]) #################### ElGamal ############################# def elgamal_private_key(digit=10, seed=None): r""" Return three number tuple as private key. Elgamal encryption is based on the mathmatical problem called the Discrete Logarithm Problem (DLP). For example, `a^{b} \equiv c \pmod p` In general, if ``a`` and ``b`` are known, ``ct`` is easily calculated. If ``b`` is unknown, it is hard to use ``a`` and ``ct`` to get ``b``. Parameters ========== digit : int Minimum number of binary digits for key. Returns ======= tuple : (p, r, d) p = prime number. r = primitive root. d = random number. Notes ===== For testing purposes, the ``seed`` parameter may be set to control the output of this routine. See sympy.testing.randtest._randrange. Examples ======== >>> from sympy.crypto.crypto import elgamal_private_key >>> from sympy.ntheory import is_primitive_root, isprime >>> a, b, _ = elgamal_private_key() >>> isprime(a) True >>> is_primitive_root(b, a) True """ randrange = _randrange(seed) p = nextprime(2**digit) return p, primitive_root(p), randrange(2, p) def elgamal_public_key(key): r""" Return three number tuple as public key. Parameters ========== key : (p, r, e) Tuple generated by ``elgamal_private_key``. Returns ======= tuple : (p, r, e) `e = r**d \bmod p` `d` is a random number in private key. Examples ======== >>> from sympy.crypto.crypto import elgamal_public_key >>> elgamal_public_key((1031, 14, 636)) (1031, 14, 212) """ p, r, e = key return p, r, pow(r, e, p) def encipher_elgamal(i, key, seed=None): r""" Encrypt message with public key ``i`` is a plaintext message expressed as an integer. ``key`` is public key (p, r, e). In order to encrypt a message, a random number ``a`` in ``range(2, p)`` is generated and the encryped message is returned as `c_{1}` and `c_{2}` where: `c_{1} \equiv r^{a} \pmod p` `c_{2} \equiv m e^{a} \pmod p` Parameters ========== msg int of encoded message. key Public key. Returns ======= tuple : (c1, c2) Encipher into two number. Notes ===== For testing purposes, the ``seed`` parameter may be set to control the output of this routine. See sympy.testing.randtest._randrange. Examples ======== >>> from sympy.crypto.crypto import encipher_elgamal, elgamal_private_key, elgamal_public_key >>> pri = elgamal_private_key(5, seed=[3]); pri (37, 2, 3) >>> pub = elgamal_public_key(pri); pub (37, 2, 8) >>> msg = 36 >>> encipher_elgamal(msg, pub, seed=[3]) (8, 6) """ p, r, e = key if i < 0 or i >= p: raise ValueError( 'Message (%s) should be in range(%s)' % (i, p)) randrange = _randrange(seed) a = randrange(2, p) return pow(r, a, p), i*pow(e, a, p) % p def decipher_elgamal(msg, key): r""" Decrypt message with private key `msg = (c_{1}, c_{2})` `key = (p, r, d)` According to extended Eucliden theorem, `u c_{1}^{d} + p n = 1` `u \equiv 1/{{c_{1}}^d} \pmod p` `u c_{2} \equiv \frac{1}{c_{1}^d} c_{2} \equiv \frac{1}{r^{ad}} c_{2} \pmod p` `\frac{1}{r^{ad}} m e^a \equiv \frac{1}{r^{ad}} m {r^{d a}} \equiv m \pmod p` Examples ======== >>> from sympy.crypto.crypto import decipher_elgamal >>> from sympy.crypto.crypto import encipher_elgamal >>> from sympy.crypto.crypto import elgamal_private_key >>> from sympy.crypto.crypto import elgamal_public_key >>> pri = elgamal_private_key(5, seed=[3]) >>> pub = elgamal_public_key(pri); pub (37, 2, 8) >>> msg = 17 >>> decipher_elgamal(encipher_elgamal(msg, pub), pri) == msg True """ p, _, d = key c1, c2 = msg u = igcdex(c1**d, p)[0] return u * c2 % p ################ Diffie-Hellman Key Exchange ######################### def dh_private_key(digit=10, seed=None): r""" Return three integer tuple as private key. Diffie-Hellman key exchange is based on the mathematical problem called the Discrete Logarithm Problem (see ElGamal). Diffie-Hellman key exchange is divided into the following steps: * Alice and Bob agree on a base that consist of a prime ``p`` and a primitive root of ``p`` called ``g`` * Alice choses a number ``a`` and Bob choses a number ``b`` where ``a`` and ``b`` are random numbers in range `[2, p)`. These are their private keys. * Alice then publicly sends Bob `g^{a} \pmod p` while Bob sends Alice `g^{b} \pmod p` * They both raise the received value to their secretly chosen number (``a`` or ``b``) and now have both as their shared key `g^{ab} \pmod p` Parameters ========== digit Minimum number of binary digits required in key. Returns ======= tuple : (p, g, a) p = prime number. g = primitive root of p. a = random number from 2 through p - 1. Notes ===== For testing purposes, the ``seed`` parameter may be set to control the output of this routine. See sympy.testing.randtest._randrange. Examples ======== >>> from sympy.crypto.crypto import dh_private_key >>> from sympy.ntheory import isprime, is_primitive_root >>> p, g, _ = dh_private_key() >>> isprime(p) True >>> is_primitive_root(g, p) True >>> p, g, _ = dh_private_key(5) >>> isprime(p) True >>> is_primitive_root(g, p) True """ p = nextprime(2**digit) g = primitive_root(p) randrange = _randrange(seed) a = randrange(2, p) return p, g, a def dh_public_key(key): r""" Return three number tuple as public key. This is the tuple that Alice sends to Bob. Parameters ========== key : (p, g, a) A tuple generated by ``dh_private_key``. Returns ======= tuple : int, int, int A tuple of `(p, g, g^a \mod p)` with `p`, `g` and `a` given as parameters.s Examples ======== >>> from sympy.crypto.crypto import dh_private_key, dh_public_key >>> p, g, a = dh_private_key(); >>> _p, _g, x = dh_public_key((p, g, a)) >>> p == _p and g == _g True >>> x == pow(g, a, p) True """ p, g, a = key return p, g, pow(g, a, p) def dh_shared_key(key, b): """ Return an integer that is the shared key. This is what Bob and Alice can both calculate using the public keys they received from each other and their private keys. Parameters ========== key : (p, g, x) Tuple `(p, g, x)` generated by ``dh_public_key``. b Random number in the range of `2` to `p - 1` (Chosen by second key exchange member (Bob)). Returns ======= int A shared key. Examples ======== >>> from sympy.crypto.crypto import ( ... dh_private_key, dh_public_key, dh_shared_key) >>> prk = dh_private_key(); >>> p, g, x = dh_public_key(prk); >>> sk = dh_shared_key((p, g, x), 1000) >>> sk == pow(x, 1000, p) True """ p, _, x = key if 1 >= b or b >= p: raise ValueError(filldedent(''' Value of b should be greater 1 and less than prime %s.''' % p)) return pow(x, b, p) ################ Goldwasser-Micali Encryption ######################### def _legendre(a, p): """ Returns the legendre symbol of a and p assuming that p is a prime i.e. 1 if a is a quadratic residue mod p -1 if a is not a quadratic residue mod p 0 if a is divisible by p Parameters ========== a : int The number to test. p : prime The prime to test ``a`` against. Returns ======= int Legendre symbol (a / p). """ sig = pow(a, (p - 1)//2, p) if sig == 1: return 1 elif sig == 0: return 0 else: return -1 def _random_coprime_stream(n, seed=None): randrange = _randrange(seed) while True: y = randrange(n) if gcd(y, n) == 1: yield y def gm_private_key(p, q, a=None): """ Check if ``p`` and ``q`` can be used as private keys for the Goldwasser-Micali encryption. The method works roughly as follows. $\\cdot$ Pick two large primes $p$ and $q$. $\\cdot$ Call their product $N$. $\\cdot$ Given a message as an integer $i$, write $i$ in its bit representation $b_0$ , $\\dotsc$ , $b_n$ . $\\cdot$ For each $k$ , if $b_k$ = 0: let $a_k$ be a random square (quadratic residue) modulo $p q$ such that $jacobi \\_symbol(a, p q) = 1$ if $b_k$ = 1: let $a_k$ be a random non-square (non-quadratic residue) modulo $p q$ such that $jacobi \\_ symbol(a, p q) = 1$ returns [$a_1$ , $a_2$ , $\\dotsc$ ] $b_k$ can be recovered by checking whether or not $a_k$ is a residue. And from the $b_k$ 's, the message can be reconstructed. The idea is that, while $jacobi \\_ symbol(a, p q)$ can be easily computed (and when it is equal to $-1$ will tell you that $a$ is not a square mod $p q$ ), quadratic residuosity modulo a composite number is hard to compute without knowing its factorization. Moreover, approximately half the numbers coprime to $p q$ have $jacobi \\_ symbol$ equal to $1$ . And among those, approximately half are residues and approximately half are not. This maximizes the entropy of the code. Parameters ========== p, q, a Initialization variables. Returns ======= tuple : (p, q) The input value ``p`` and ``q``. Raises ====== ValueError If ``p`` and ``q`` are not distinct odd primes. """ if p == q: raise ValueError("expected distinct primes, " "got two copies of %i" % p) elif not isprime(p) or not isprime(q): raise ValueError("first two arguments must be prime, " "got %i of %i" % (p, q)) elif p == 2 or q == 2: raise ValueError("first two arguments must not be even, " "got %i of %i" % (p, q)) return p, q def gm_public_key(p, q, a=None, seed=None): """ Compute public keys for p and q. Note that in Goldwasser-Micali Encryption, public keys are randomly selected. Parameters ========== p, q, a : int, int, int Initialization variables. Returns ======= tuple : (a, N) ``a`` is the input ``a`` if it is not ``None`` otherwise some random integer coprime to ``p`` and ``q``. ``N`` is the product of ``p`` and ``q``. """ p, q = gm_private_key(p, q) N = p * q if a is None: randrange = _randrange(seed) while True: a = randrange(N) if _legendre(a, p) == _legendre(a, q) == -1: break else: if _legendre(a, p) != -1 or _legendre(a, q) != -1: return False return (a, N) def encipher_gm(i, key, seed=None): """ Encrypt integer 'i' using public_key 'key' Note that gm uses random encryption. Parameters ========== i : int The message to encrypt. key : (a, N) The public key. Returns ======= list : list of int The randomized encrypted message. """ if i < 0: raise ValueError( "message must be a non-negative " "integer: got %d instead" % i) a, N = key bits = [] while i > 0: bits.append(i % 2) i //= 2 gen = _random_coprime_stream(N, seed) rev = reversed(bits) encode = lambda b: next(gen)**2*pow(a, b) % N return [ encode(b) for b in rev ] def decipher_gm(message, key): """ Decrypt message 'message' using public_key 'key'. Parameters ========== message : list of int The randomized encrypted message. key : (p, q) The private key. Returns ======= int The encrypted message. """ p, q = key res = lambda m, p: _legendre(m, p) > 0 bits = [res(m, p) * res(m, q) for m in message] m = 0 for b in bits: m <<= 1 m += not b return m ########### RailFence Cipher ############# def encipher_railfence(message,rails): """ Performs Railfence Encryption on plaintext and returns ciphertext Examples ======== >>> from sympy.crypto.crypto import encipher_railfence >>> message = "hello world" >>> encipher_railfence(message,3) 'horel ollwd' Parameters ========== message : string, the message to encrypt. rails : int, the number of rails. Returns ======= The Encrypted string message. References ========== .. [1] https://en.wikipedia.org/wiki/Rail_fence_cipher """ r = list(range(rails)) p = cycle(r + r[-2:0:-1]) return ''.join(sorted(message, key=lambda i: next(p))) def decipher_railfence(ciphertext,rails): """ Decrypt the message using the given rails Examples ======== >>> from sympy.crypto.crypto import decipher_railfence >>> decipher_railfence("horel ollwd",3) 'hello world' Parameters ========== message : string, the message to encrypt. rails : int, the number of rails. Returns ======= The Decrypted string message. """ r = list(range(rails)) p = cycle(r + r[-2:0:-1]) idx = sorted(range(len(ciphertext)), key=lambda i: next(p)) res = [''] * len(ciphertext) for i, c in zip(idx, ciphertext): res[i] = c return ''.join(res) ################ Blum-Goldwasser cryptosystem ######################### def bg_private_key(p, q): """ Check if p and q can be used as private keys for the Blum-Goldwasser cryptosystem. The three necessary checks for p and q to pass so that they can be used as private keys: 1. p and q must both be prime 2. p and q must be distinct 3. p and q must be congruent to 3 mod 4 Parameters ========== p, q The keys to be checked. Returns ======= p, q Input values. Raises ====== ValueError If p and q do not pass the above conditions. """ if not isprime(p) or not isprime(q): raise ValueError("the two arguments must be prime, " "got %i and %i" %(p, q)) elif p == q: raise ValueError("the two arguments must be distinct, " "got two copies of %i. " %p) elif (p - 3) % 4 != 0 or (q - 3) % 4 != 0: raise ValueError("the two arguments must be congruent to 3 mod 4, " "got %i and %i" %(p, q)) return p, q def bg_public_key(p, q): """ Calculates public keys from private keys. The function first checks the validity of private keys passed as arguments and then returns their product. Parameters ========== p, q The private keys. Returns ======= N The public key. """ p, q = bg_private_key(p, q) N = p * q return N def encipher_bg(i, key, seed=None): """ Encrypts the message using public key and seed. ALGORITHM: 1. Encodes i as a string of L bits, m. 2. Select a random element r, where 1 < r < key, and computes x = r^2 mod key. 3. Use BBS pseudo-random number generator to generate L random bits, b, using the initial seed as x. 4. Encrypted message, c_i = m_i XOR b_i, 1 <= i <= L. 5. x_L = x^(2^L) mod key. 6. Return (c, x_L) Parameters ========== i Message, a non-negative integer key The public key Returns ======= Tuple (encrypted_message, x_L) Raises ====== ValueError If i is negative. """ if i < 0: raise ValueError( "message must be a non-negative " "integer: got %d instead" % i) enc_msg = [] while i > 0: enc_msg.append(i % 2) i //= 2 enc_msg.reverse() L = len(enc_msg) r = _randint(seed)(2, key - 1) x = r**2 % key x_L = pow(int(x), int(2**L), int(key)) rand_bits = [] for _ in range(L): rand_bits.append(x % 2) x = x**2 % key encrypt_msg = [m ^ b for (m, b) in zip(enc_msg, rand_bits)] return (encrypt_msg, x_L) def decipher_bg(message, key): """ Decrypts the message using private keys. ALGORITHM: 1. Let, c be the encrypted message, y the second number received, and p and q be the private keys. 2. Compute, r_p = y^((p+1)/4 ^ L) mod p and r_q = y^((q+1)/4 ^ L) mod q. 3. Compute x_0 = (q(q^-1 mod p)r_p + p(p^-1 mod q)r_q) mod N. 4. From, recompute the bits using the BBS generator, as in the encryption algorithm. 5. Compute original message by XORing c and b. Parameters ========== message Tuple of encrypted message and a non-negative integer. key Tuple of private keys. Returns ======= orig_msg The original message """ p, q = key encrypt_msg, y = message public_key = p * q L = len(encrypt_msg) p_t = ((p + 1)/4)**L q_t = ((q + 1)/4)**L r_p = pow(int(y), int(p_t), int(p)) r_q = pow(int(y), int(q_t), int(q)) x = (q * mod_inverse(q, p) * r_p + p * mod_inverse(p, q) * r_q) % public_key orig_bits = [] for _ in range(L): orig_bits.append(x % 2) x = x**2 % public_key orig_msg = 0 for (m, b) in zip(encrypt_msg, orig_bits): orig_msg = orig_msg * 2 orig_msg += (m ^ b) return orig_msg
07dde604092dafaa171dc6402d6a8dfa4fc6d8d75e696ad55257811c3f6f6c0f
""" This module contains functions to: - solve a single equation for a single variable, in any domain either real or complex. - solve a single transcendental equation for a single variable in any domain either real or complex. (currently supports solving in real domain only) - solve a system of linear equations with N variables and M equations. - solve a system of Non Linear Equations with N variables and M equations """ from __future__ import print_function, division from sympy.core.sympify import sympify from sympy.core import (S, Pow, Dummy, pi, Expr, Wild, Mul, Equality, Add) from sympy.core.containers import Tuple from sympy.core.numbers import I, Number, Rational, oo from sympy.core.function import (Lambda, expand_complex, AppliedUndef, expand_log) from sympy.core.mod import Mod from sympy.core.numbers import igcd from sympy.core.relational import Eq, Ne, Relational from sympy.core.symbol import Symbol, _uniquely_named_symbol from sympy.core.sympify import _sympify from sympy.simplify.simplify import simplify, fraction, trigsimp from sympy.simplify import powdenest, logcombine from sympy.functions import (log, Abs, tan, cot, sin, cos, sec, csc, exp, acos, asin, acsc, asec, arg, piecewise_fold, Piecewise) from sympy.functions.elementary.trigonometric import (TrigonometricFunction, HyperbolicFunction) from sympy.functions.elementary.miscellaneous import real_root from sympy.logic.boolalg import And from sympy.sets import (FiniteSet, EmptySet, imageset, Interval, Intersection, Union, ConditionSet, ImageSet, Complement, Contains) from sympy.sets.sets import Set, ProductSet from sympy.matrices import Matrix, MatrixBase from sympy.ntheory import totient from sympy.ntheory.factor_ import divisors from sympy.ntheory.residue_ntheory import discrete_log, nthroot_mod from sympy.polys import (roots, Poly, degree, together, PolynomialError, RootOf, factor, lcm, gcd) from sympy.polys.polyerrors import CoercionFailed from sympy.polys.polytools import invert from sympy.polys.solvers import (sympy_eqs_to_ring, solve_lin_sys, PolyNonlinearError) from sympy.solvers.solvers import (checksol, denoms, unrad, _simple_dens, recast_to_symbols) from sympy.solvers.polysys import solve_poly_system from sympy.solvers.inequalities import solve_univariate_inequality from sympy.utilities import filldedent from sympy.utilities.iterables import numbered_symbols, has_dups from sympy.calculus.util import periodicity, continuous_domain from sympy.core.compatibility import ordered, default_sort_key, is_sequence from types import GeneratorType from collections import defaultdict class NonlinearError(ValueError): """Raised when unexpectedly encountering nonlinear equations""" pass _rc = Dummy("R", real=True), Dummy("C", complex=True) def _masked(f, *atoms): """Return ``f``, with all objects given by ``atoms`` replaced with Dummy symbols, ``d``, and the list of replacements, ``(d, e)``, where ``e`` is an object of type given by ``atoms`` in which any other instances of atoms have been recursively replaced with Dummy symbols, too. The tuples are ordered so that if they are applied in sequence, the origin ``f`` will be restored. Examples ======== >>> from sympy import cos >>> from sympy.abc import x >>> from sympy.solvers.solveset import _masked >>> f = cos(cos(x) + 1) >>> f, reps = _masked(cos(1 + cos(x)), cos) >>> f _a1 >>> reps [(_a1, cos(_a0 + 1)), (_a0, cos(x))] >>> for d, e in reps: ... f = f.xreplace({d: e}) >>> f cos(cos(x) + 1) """ sym = numbered_symbols('a', cls=Dummy, real=True) mask = [] for a in ordered(f.atoms(*atoms)): for i in mask: a = a.replace(*i) mask.append((a, next(sym))) for i, (o, n) in enumerate(mask): f = f.replace(o, n) mask[i] = (n, o) mask = list(reversed(mask)) return f, mask def _invert(f_x, y, x, domain=S.Complexes): r""" Reduce the complex valued equation ``f(x) = y`` to a set of equations ``{g(x) = h_1(y), g(x) = h_2(y), ..., g(x) = h_n(y) }`` where ``g(x)`` is a simpler function than ``f(x)``. The return value is a tuple ``(g(x), set_h)``, where ``g(x)`` is a function of ``x`` and ``set_h`` is the set of function ``{h_1(y), h_2(y), ..., h_n(y)}``. Here, ``y`` is not necessarily a symbol. The ``set_h`` contains the functions, along with the information about the domain in which they are valid, through set operations. For instance, if ``y = Abs(x) - n`` is inverted in the real domain, then ``set_h`` is not simply `{-n, n}` as the nature of `n` is unknown; rather, it is: `Intersection([0, oo) {n}) U Intersection((-oo, 0], {-n})` By default, the complex domain is used which means that inverting even seemingly simple functions like ``exp(x)`` will give very different results from those obtained in the real domain. (In the case of ``exp(x)``, the inversion via ``log`` is multi-valued in the complex domain, having infinitely many branches.) If you are working with real values only (or you are not sure which function to use) you should probably set the domain to ``S.Reals`` (or use `invert\_real` which does that automatically). Examples ======== >>> from sympy.solvers.solveset import invert_complex, invert_real >>> from sympy.abc import x, y >>> from sympy import exp When does exp(x) == y? >>> invert_complex(exp(x), y, x) (x, ImageSet(Lambda(_n, I*(2*_n*pi + arg(y)) + log(Abs(y))), Integers)) >>> invert_real(exp(x), y, x) (x, Intersection(FiniteSet(log(y)), Reals)) When does exp(x) == 1? >>> invert_complex(exp(x), 1, x) (x, ImageSet(Lambda(_n, 2*_n*I*pi), Integers)) >>> invert_real(exp(x), 1, x) (x, FiniteSet(0)) See Also ======== invert_real, invert_complex """ x = sympify(x) if not x.is_Symbol: raise ValueError("x must be a symbol") f_x = sympify(f_x) if x not in f_x.free_symbols: raise ValueError("Inverse of constant function doesn't exist") y = sympify(y) if x in y.free_symbols: raise ValueError("y should be independent of x ") if domain.is_subset(S.Reals): x1, s = _invert_real(f_x, FiniteSet(y), x) else: x1, s = _invert_complex(f_x, FiniteSet(y), x) if not isinstance(s, FiniteSet) or x1 != x: return x1, s # Avoid adding gratuitous intersections with S.Complexes. Actual # conditions should be handled by the respective inverters. if domain is S.Complexes: return x1, s else: return x1, s.intersection(domain) invert_complex = _invert def invert_real(f_x, y, x, domain=S.Reals): """ Inverts a real-valued function. Same as _invert, but sets the domain to ``S.Reals`` before inverting. """ return _invert(f_x, y, x, domain) def _invert_real(f, g_ys, symbol): """Helper function for _invert.""" if f == symbol: return (f, g_ys) n = Dummy('n', real=True) if hasattr(f, 'inverse') and not isinstance(f, ( TrigonometricFunction, HyperbolicFunction, )): if len(f.args) > 1: raise ValueError("Only functions with one argument are supported.") return _invert_real(f.args[0], imageset(Lambda(n, f.inverse()(n)), g_ys), symbol) if isinstance(f, Abs): return _invert_abs(f.args[0], g_ys, symbol) if f.is_Add: # f = g + h g, h = f.as_independent(symbol) if g is not S.Zero: return _invert_real(h, imageset(Lambda(n, n - g), g_ys), symbol) if f.is_Mul: # f = g*h g, h = f.as_independent(symbol) if g is not S.One: return _invert_real(h, imageset(Lambda(n, n/g), g_ys), symbol) if f.is_Pow: base, expo = f.args base_has_sym = base.has(symbol) expo_has_sym = expo.has(symbol) if not expo_has_sym: res = imageset(Lambda(n, real_root(n, expo)), g_ys) if expo.is_rational: numer, denom = expo.as_numer_denom() if denom % 2 == 0: base_positive = solveset(base >= 0, symbol, S.Reals) res = imageset(Lambda(n, real_root(n, expo) ), g_ys.intersect( Interval.Ropen(S.Zero, S.Infinity))) _inv, _set = _invert_real(base, res, symbol) return (_inv, _set.intersect(base_positive)) elif numer % 2 == 0: n = Dummy('n') neg_res = imageset(Lambda(n, -n), res) return _invert_real(base, res + neg_res, symbol) else: return _invert_real(base, res, symbol) else: if not base.is_positive: raise ValueError("x**w where w is irrational is not " "defined for negative x") return _invert_real(base, res, symbol) if not base_has_sym: rhs = g_ys.args[0] if base.is_positive: return _invert_real(expo, imageset(Lambda(n, log(n, base, evaluate=False)), g_ys), symbol) elif base.is_negative: from sympy.core.power import integer_log s, b = integer_log(rhs, base) if b: return _invert_real(expo, FiniteSet(s), symbol) else: return _invert_real(expo, S.EmptySet, symbol) elif base.is_zero: one = Eq(rhs, 1) if one == S.true: # special case: 0**x - 1 return _invert_real(expo, FiniteSet(0), symbol) elif one == S.false: return _invert_real(expo, S.EmptySet, symbol) if isinstance(f, TrigonometricFunction): if isinstance(g_ys, FiniteSet): def inv(trig): if isinstance(f, (sin, csc)): F = asin if isinstance(f, sin) else acsc return (lambda a: n*pi + (-1)**n*F(a),) if isinstance(f, (cos, sec)): F = acos if isinstance(f, cos) else asec return ( lambda a: 2*n*pi + F(a), lambda a: 2*n*pi - F(a),) if isinstance(f, (tan, cot)): return (lambda a: n*pi + f.inverse()(a),) n = Dummy('n', integer=True) invs = S.EmptySet for L in inv(f): invs += Union(*[imageset(Lambda(n, L(g)), S.Integers) for g in g_ys]) return _invert_real(f.args[0], invs, symbol) return (f, g_ys) def _invert_complex(f, g_ys, symbol): """Helper function for _invert.""" if f == symbol: return (f, g_ys) n = Dummy('n') if f.is_Add: # f = g + h g, h = f.as_independent(symbol) if g is not S.Zero: return _invert_complex(h, imageset(Lambda(n, n - g), g_ys), symbol) if f.is_Mul: # f = g*h g, h = f.as_independent(symbol) if g is not S.One: if g in set([S.NegativeInfinity, S.ComplexInfinity, S.Infinity]): return (h, S.EmptySet) return _invert_complex(h, imageset(Lambda(n, n/g), g_ys), symbol) if hasattr(f, 'inverse') and \ not isinstance(f, TrigonometricFunction) and \ not isinstance(f, HyperbolicFunction) and \ not isinstance(f, exp): if len(f.args) > 1: raise ValueError("Only functions with one argument are supported.") return _invert_complex(f.args[0], imageset(Lambda(n, f.inverse()(n)), g_ys), symbol) if isinstance(f, exp): if isinstance(g_ys, FiniteSet): exp_invs = Union(*[imageset(Lambda(n, I*(2*n*pi + arg(g_y)) + log(Abs(g_y))), S.Integers) for g_y in g_ys if g_y != 0]) return _invert_complex(f.args[0], exp_invs, symbol) return (f, g_ys) def _invert_abs(f, g_ys, symbol): """Helper function for inverting absolute value functions. Returns the complete result of inverting an absolute value function along with the conditions which must also be satisfied. If it is certain that all these conditions are met, a `FiniteSet` of all possible solutions is returned. If any condition cannot be satisfied, an `EmptySet` is returned. Otherwise, a `ConditionSet` of the solutions, with all the required conditions specified, is returned. """ if not g_ys.is_FiniteSet: # this could be used for FiniteSet, but the # results are more compact if they aren't, e.g. # ConditionSet(x, Contains(n, Interval(0, oo)), {-n, n}) vs # Union(Intersection(Interval(0, oo), {n}), Intersection(Interval(-oo, 0), {-n})) # for the solution of abs(x) - n pos = Intersection(g_ys, Interval(0, S.Infinity)) parg = _invert_real(f, pos, symbol) narg = _invert_real(-f, pos, symbol) if parg[0] != narg[0]: raise NotImplementedError return parg[0], Union(narg[1], parg[1]) # check conditions: all these must be true. If any are unknown # then return them as conditions which must be satisfied unknown = [] for a in g_ys.args: ok = a.is_nonnegative if a.is_Number else a.is_positive if ok is None: unknown.append(a) elif not ok: return symbol, S.EmptySet if unknown: conditions = And(*[Contains(i, Interval(0, oo)) for i in unknown]) else: conditions = True n = Dummy('n', real=True) # this is slightly different than above: instead of solving # +/-f on positive values, here we solve for f on +/- g_ys g_x, values = _invert_real(f, Union( imageset(Lambda(n, n), g_ys), imageset(Lambda(n, -n), g_ys)), symbol) return g_x, ConditionSet(g_x, conditions, values) def domain_check(f, symbol, p): """Returns False if point p is infinite or any subexpression of f is infinite or becomes so after replacing symbol with p. If none of these conditions is met then True will be returned. Examples ======== >>> from sympy import Mul, oo >>> from sympy.abc import x >>> from sympy.solvers.solveset import domain_check >>> g = 1/(1 + (1/(x + 1))**2) >>> domain_check(g, x, -1) False >>> domain_check(x**2, x, 0) True >>> domain_check(1/x, x, oo) False * The function relies on the assumption that the original form of the equation has not been changed by automatic simplification. >>> domain_check(x/x, x, 0) # x/x is automatically simplified to 1 True * To deal with automatic evaluations use evaluate=False: >>> domain_check(Mul(x, 1/x, evaluate=False), x, 0) False """ f, p = sympify(f), sympify(p) if p.is_infinite: return False return _domain_check(f, symbol, p) def _domain_check(f, symbol, p): # helper for domain check if f.is_Atom and f.is_finite: return True elif f.subs(symbol, p).is_infinite: return False else: return all([_domain_check(g, symbol, p) for g in f.args]) def _is_finite_with_finite_vars(f, domain=S.Complexes): """ Return True if the given expression is finite. For symbols that don't assign a value for `complex` and/or `real`, the domain will be used to assign a value; symbols that don't assign a value for `finite` will be made finite. All other assumptions are left unmodified. """ def assumptions(s): A = s.assumptions0 A.setdefault('finite', A.get('finite', True)) if domain.is_subset(S.Reals): # if this gets set it will make complex=True, too A.setdefault('real', True) else: # don't change 'real' because being complex implies # nothing about being real A.setdefault('complex', True) return A reps = {s: Dummy(**assumptions(s)) for s in f.free_symbols} return f.xreplace(reps).is_finite def _is_function_class_equation(func_class, f, symbol): """ Tests whether the equation is an equation of the given function class. The given equation belongs to the given function class if it is comprised of functions of the function class which are multiplied by or added to expressions independent of the symbol. In addition, the arguments of all such functions must be linear in the symbol as well. Examples ======== >>> from sympy.solvers.solveset import _is_function_class_equation >>> from sympy import tan, sin, tanh, sinh, exp >>> from sympy.abc import x >>> from sympy.functions.elementary.trigonometric import (TrigonometricFunction, ... HyperbolicFunction) >>> _is_function_class_equation(TrigonometricFunction, exp(x) + tan(x), x) False >>> _is_function_class_equation(TrigonometricFunction, tan(x) + sin(x), x) True >>> _is_function_class_equation(TrigonometricFunction, tan(x**2), x) False >>> _is_function_class_equation(TrigonometricFunction, tan(x + 2), x) True >>> _is_function_class_equation(HyperbolicFunction, tanh(x) + sinh(x), x) True """ if f.is_Mul or f.is_Add: return all(_is_function_class_equation(func_class, arg, symbol) for arg in f.args) if f.is_Pow: if not f.exp.has(symbol): return _is_function_class_equation(func_class, f.base, symbol) else: return False if not f.has(symbol): return True if isinstance(f, func_class): try: g = Poly(f.args[0], symbol) return g.degree() <= 1 except PolynomialError: return False else: return False def _solve_as_rational(f, symbol, domain): """ solve rational functions""" f = together(f, deep=True) g, h = fraction(f) if not h.has(symbol): try: return _solve_as_poly(g, symbol, domain) except NotImplementedError: # The polynomial formed from g could end up having # coefficients in a ring over which finding roots # isn't implemented yet, e.g. ZZ[a] for some symbol a return ConditionSet(symbol, Eq(f, 0), domain) except CoercionFailed: # contained oo, zoo or nan return S.EmptySet else: valid_solns = _solveset(g, symbol, domain) invalid_solns = _solveset(h, symbol, domain) return valid_solns - invalid_solns class _SolveTrig1Error(Exception): """Raised when _solve_trig1 heuristics do not apply""" def _solve_trig(f, symbol, domain): """Function to call other helpers to solve trigonometric equations """ sol = None try: sol = _solve_trig1(f, symbol, domain) except _SolveTrig1Error: try: sol = _solve_trig2(f, symbol, domain) except ValueError: raise NotImplementedError(filldedent(''' Solution to this kind of trigonometric equations is yet to be implemented''')) return sol def _solve_trig1(f, symbol, domain): """Primary solver for trigonometric and hyperbolic equations Returns either the solution set as a ConditionSet (auto-evaluated to a union of ImageSets if no variables besides 'symbol' are involved) or raises _SolveTrig1Error if f == 0 can't be solved. Notes ===== Algorithm: 1. Do a change of variable x -> mu*x in arguments to trigonometric and hyperbolic functions, in order to reduce them to small integers. (This step is crucial to keep the degrees of the polynomials of step 4 low.) 2. Rewrite trigonometric/hyperbolic functions as exponentials. 3. Proceed to a 2nd change of variable, replacing exp(I*x) or exp(x) by y. 4. Solve the resulting rational equation. 5. Use invert_complex or invert_real to return to the original variable. 6. If the coefficients of 'symbol' were symbolic in nature, add the necessary consistency conditions in a ConditionSet. """ # Prepare change of variable x = Dummy('x') if _is_function_class_equation(HyperbolicFunction, f, symbol): cov = exp(x) inverter = invert_real if domain.is_subset(S.Reals) else invert_complex else: cov = exp(I*x) inverter = invert_complex f = trigsimp(f) f_original = f trig_functions = f.atoms(TrigonometricFunction, HyperbolicFunction) trig_arguments = [e.args[0] for e in trig_functions] # trigsimp may have reduced the equation to an expression # that is independent of 'symbol' (e.g. cos**2+sin**2) if not any(a.has(symbol) for a in trig_arguments): return solveset(f_original, symbol, domain) denominators = [] numerators = [] for ar in trig_arguments: try: poly_ar = Poly(ar, symbol) except PolynomialError: raise _SolveTrig1Error("trig argument is not a polynomial") if poly_ar.degree() > 1: # degree >1 still bad raise _SolveTrig1Error("degree of variable must not exceed one") if poly_ar.degree() == 0: # degree 0, don't care continue c = poly_ar.all_coeffs()[0] # got the coefficient of 'symbol' numerators.append(fraction(c)[0]) denominators.append(fraction(c)[1]) mu = lcm(denominators)/gcd(numerators) f = f.subs(symbol, mu*x) f = f.rewrite(exp) f = together(f) g, h = fraction(f) y = Dummy('y') g, h = g.expand(), h.expand() g, h = g.subs(cov, y), h.subs(cov, y) if g.has(x) or h.has(x): raise _SolveTrig1Error("change of variable not possible") solns = solveset_complex(g, y) - solveset_complex(h, y) if isinstance(solns, ConditionSet): raise _SolveTrig1Error("polynomial has ConditionSet solution") if isinstance(solns, FiniteSet): if any(isinstance(s, RootOf) for s in solns): raise _SolveTrig1Error("polynomial results in RootOf object") # revert the change of variable cov = cov.subs(x, symbol/mu) result = Union(*[inverter(cov, s, symbol)[1] for s in solns]) # In case of symbolic coefficients, the solution set is only valid # if numerator and denominator of mu are non-zero. if mu.has(Symbol): syms = (mu).atoms(Symbol) munum, muden = fraction(mu) condnum = munum.as_independent(*syms, as_Add=False)[1] condden = muden.as_independent(*syms, as_Add=False)[1] cond = And(Ne(condnum, 0), Ne(condden, 0)) else: cond = True # Actual conditions are returned as part of the ConditionSet. Adding an # intersection with C would only complicate some solution sets due to # current limitations of intersection code. (e.g. #19154) if domain is S.Complexes: # This is a slight abuse of ConditionSet. Ideally this should # be some kind of "PiecewiseSet". (See #19507 discussion) return ConditionSet(symbol, cond, result) else: return ConditionSet(symbol, cond, Intersection(result, domain)) elif solns is S.EmptySet: return S.EmptySet else: raise _SolveTrig1Error("polynomial solutions must form FiniteSet") def _solve_trig2(f, symbol, domain): """Secondary helper to solve trigonometric equations, called when first helper fails """ from sympy import ilcm, expand_trig, degree f = trigsimp(f) f_original = f trig_functions = f.atoms(sin, cos, tan, sec, cot, csc) trig_arguments = [e.args[0] for e in trig_functions] denominators = [] numerators = [] # todo: This solver can be extended to hyperbolics if the # analogous change of variable to tanh (instead of tan) # is used. if not trig_functions: return ConditionSet(symbol, Eq(f_original, 0), domain) # todo: The pre-processing below (extraction of numerators, denominators, # gcd, lcm, mu, etc.) should be updated to the enhanced version in # _solve_trig1. (See #19507) for ar in trig_arguments: try: poly_ar = Poly(ar, symbol) except PolynomialError: raise ValueError("give up, we can't solve if this is not a polynomial in x") if poly_ar.degree() > 1: # degree >1 still bad raise ValueError("degree of variable inside polynomial should not exceed one") if poly_ar.degree() == 0: # degree 0, don't care continue c = poly_ar.all_coeffs()[0] # got the coefficient of 'symbol' try: numerators.append(Rational(c).p) denominators.append(Rational(c).q) except TypeError: return ConditionSet(symbol, Eq(f_original, 0), domain) x = Dummy('x') # ilcm() and igcd() require more than one argument if len(numerators) > 1: mu = Rational(2)*ilcm(*denominators)/igcd(*numerators) else: assert len(numerators) == 1 mu = Rational(2)*denominators[0]/numerators[0] f = f.subs(symbol, mu*x) f = f.rewrite(tan) f = expand_trig(f) f = together(f) g, h = fraction(f) y = Dummy('y') g, h = g.expand(), h.expand() g, h = g.subs(tan(x), y), h.subs(tan(x), y) if g.has(x) or h.has(x): return ConditionSet(symbol, Eq(f_original, 0), domain) solns = solveset(g, y, S.Reals) - solveset(h, y, S.Reals) if isinstance(solns, FiniteSet): result = Union(*[invert_real(tan(symbol/mu), s, symbol)[1] for s in solns]) dsol = invert_real(tan(symbol/mu), oo, symbol)[1] if degree(h) > degree(g): # If degree(denom)>degree(num) then there result = Union(result, dsol) # would be another sol at Lim(denom-->oo) return Intersection(result, domain) elif solns is S.EmptySet: return S.EmptySet else: return ConditionSet(symbol, Eq(f_original, 0), S.Reals) def _solve_as_poly(f, symbol, domain=S.Complexes): """ Solve the equation using polynomial techniques if it already is a polynomial equation or, with a change of variables, can be made so. """ result = None if f.is_polynomial(symbol): solns = roots(f, symbol, cubics=True, quartics=True, quintics=True, domain='EX') num_roots = sum(solns.values()) if degree(f, symbol) <= num_roots: result = FiniteSet(*solns.keys()) else: poly = Poly(f, symbol) solns = poly.all_roots() if poly.degree() <= len(solns): result = FiniteSet(*solns) else: result = ConditionSet(symbol, Eq(f, 0), domain) else: poly = Poly(f) if poly is None: result = ConditionSet(symbol, Eq(f, 0), domain) gens = [g for g in poly.gens if g.has(symbol)] if len(gens) == 1: poly = Poly(poly, gens[0]) gen = poly.gen deg = poly.degree() poly = Poly(poly.as_expr(), poly.gen, composite=True) poly_solns = FiniteSet(*roots(poly, cubics=True, quartics=True, quintics=True).keys()) if len(poly_solns) < deg: result = ConditionSet(symbol, Eq(f, 0), domain) if gen != symbol: y = Dummy('y') inverter = invert_real if domain.is_subset(S.Reals) else invert_complex lhs, rhs_s = inverter(gen, y, symbol) if lhs == symbol: result = Union(*[rhs_s.subs(y, s) for s in poly_solns]) else: result = ConditionSet(symbol, Eq(f, 0), domain) else: result = ConditionSet(symbol, Eq(f, 0), domain) if result is not None: if isinstance(result, FiniteSet): # this is to simplify solutions like -sqrt(-I) to sqrt(2)/2 # - sqrt(2)*I/2. We are not expanding for solution with symbols # or undefined functions because that makes the solution more complicated. # For example, expand_complex(a) returns re(a) + I*im(a) if all([s.atoms(Symbol, AppliedUndef) == set() and not isinstance(s, RootOf) for s in result]): s = Dummy('s') result = imageset(Lambda(s, expand_complex(s)), result) if isinstance(result, FiniteSet) and domain != S.Complexes: # Avoid adding gratuitous intersections with S.Complexes. Actual # conditions should be handled elsewhere. result = result.intersection(domain) return result else: return ConditionSet(symbol, Eq(f, 0), domain) def _has_rational_power(expr, symbol): """ Returns (bool, den) where bool is True if the term has a non-integer rational power and den is the denominator of the expression's exponent. Examples ======== >>> from sympy.solvers.solveset import _has_rational_power >>> from sympy import sqrt >>> from sympy.abc import x >>> _has_rational_power(sqrt(x), x) (True, 2) >>> _has_rational_power(x**2, x) (False, 1) """ a, p, q = Wild('a'), Wild('p'), Wild('q') pattern_match = expr.match(a*p**q) or {} if pattern_match.get(a, S.Zero).is_zero: return (False, S.One) elif p not in pattern_match.keys(): return (False, S.One) elif isinstance(pattern_match[q], Rational) \ and pattern_match[p].has(symbol): if not pattern_match[q].q == S.One: return (True, pattern_match[q].q) if not isinstance(pattern_match[a], Pow) \ or isinstance(pattern_match[a], Mul): return (False, S.One) else: return _has_rational_power(pattern_match[a], symbol) def _solve_radical(f, symbol, solveset_solver): """ Helper function to solve equations with radicals """ res = unrad(f) eq, cov = res if res else (f, []) if not cov: result = solveset_solver(eq, symbol) - \ Union(*[solveset_solver(g, symbol) for g in denoms(f, symbol)]) else: y, yeq = cov if not solveset_solver(y - I, y): yreal = Dummy('yreal', real=True) yeq = yeq.xreplace({y: yreal}) eq = eq.xreplace({y: yreal}) y = yreal g_y_s = solveset_solver(yeq, symbol) f_y_sols = solveset_solver(eq, y) result = Union(*[imageset(Lambda(y, g_y), f_y_sols) for g_y in g_y_s]) if isinstance(result, Complement) or isinstance(result,ConditionSet): solution_set = result else: f_set = [] # solutions for FiniteSet c_set = [] # solutions for ConditionSet for s in result: if checksol(f, symbol, s): f_set.append(s) else: c_set.append(s) solution_set = FiniteSet(*f_set) + ConditionSet(symbol, Eq(f, 0), FiniteSet(*c_set)) return solution_set def _solve_abs(f, symbol, domain): """ Helper function to solve equation involving absolute value function """ if not domain.is_subset(S.Reals): raise ValueError(filldedent(''' Absolute values cannot be inverted in the complex domain.''')) p, q, r = Wild('p'), Wild('q'), Wild('r') pattern_match = f.match(p*Abs(q) + r) or {} f_p, f_q, f_r = [pattern_match.get(i, S.Zero) for i in (p, q, r)] if not (f_p.is_zero or f_q.is_zero): domain = continuous_domain(f_q, symbol, domain) q_pos_cond = solve_univariate_inequality(f_q >= 0, symbol, relational=False, domain=domain, continuous=True) q_neg_cond = q_pos_cond.complement(domain) sols_q_pos = solveset_real(f_p*f_q + f_r, symbol).intersect(q_pos_cond) sols_q_neg = solveset_real(f_p*(-f_q) + f_r, symbol).intersect(q_neg_cond) return Union(sols_q_pos, sols_q_neg) else: return ConditionSet(symbol, Eq(f, 0), domain) def solve_decomposition(f, symbol, domain): """ Function to solve equations via the principle of "Decomposition and Rewriting". Examples ======== >>> from sympy import exp, sin, Symbol, pprint, S >>> from sympy.solvers.solveset import solve_decomposition as sd >>> x = Symbol('x') >>> f1 = exp(2*x) - 3*exp(x) + 2 >>> sd(f1, x, S.Reals) FiniteSet(0, log(2)) >>> f2 = sin(x)**2 + 2*sin(x) + 1 >>> pprint(sd(f2, x, S.Reals), use_unicode=False) 3*pi {2*n*pi + ---- | n in Integers} 2 >>> f3 = sin(x + 2) >>> pprint(sd(f3, x, S.Reals), use_unicode=False) {2*n*pi - 2 | n in Integers} U {2*n*pi - 2 + pi | n in Integers} """ from sympy.solvers.decompogen import decompogen from sympy.calculus.util import function_range # decompose the given function g_s = decompogen(f, symbol) # `y_s` represents the set of values for which the function `g` is to be # solved. # `solutions` represent the solutions of the equations `g = y_s` or # `g = 0` depending on the type of `y_s`. # As we are interested in solving the equation: f = 0 y_s = FiniteSet(0) for g in g_s: frange = function_range(g, symbol, domain) y_s = Intersection(frange, y_s) result = S.EmptySet if isinstance(y_s, FiniteSet): for y in y_s: solutions = solveset(Eq(g, y), symbol, domain) if not isinstance(solutions, ConditionSet): result += solutions else: if isinstance(y_s, ImageSet): iter_iset = (y_s,) elif isinstance(y_s, Union): iter_iset = y_s.args elif y_s is EmptySet: # y_s is not in the range of g in g_s, so no solution exists #in the given domain return EmptySet for iset in iter_iset: new_solutions = solveset(Eq(iset.lamda.expr, g), symbol, domain) dummy_var = tuple(iset.lamda.expr.free_symbols)[0] (base_set,) = iset.base_sets if isinstance(new_solutions, FiniteSet): new_exprs = new_solutions elif isinstance(new_solutions, Intersection): if isinstance(new_solutions.args[1], FiniteSet): new_exprs = new_solutions.args[1] for new_expr in new_exprs: result += ImageSet(Lambda(dummy_var, new_expr), base_set) if result is S.EmptySet: return ConditionSet(symbol, Eq(f, 0), domain) y_s = result return y_s def _solveset(f, symbol, domain, _check=False): """Helper for solveset to return a result from an expression that has already been sympify'ed and is known to contain the given symbol.""" # _check controls whether the answer is checked or not from sympy.simplify.simplify import signsimp from sympy.logic.boolalg import BooleanTrue if isinstance(f, BooleanTrue): return domain orig_f = f if f.is_Mul: coeff, f = f.as_independent(symbol, as_Add=False) if coeff in set([S.ComplexInfinity, S.NegativeInfinity, S.Infinity]): f = together(orig_f) elif f.is_Add: a, h = f.as_independent(symbol) m, h = h.as_independent(symbol, as_Add=False) if m not in set([S.ComplexInfinity, S.Zero, S.Infinity, S.NegativeInfinity]): f = a/m + h # XXX condition `m != 0` should be added to soln # assign the solvers to use solver = lambda f, x, domain=domain: _solveset(f, x, domain) inverter = lambda f, rhs, symbol: _invert(f, rhs, symbol, domain) result = EmptySet if f.expand().is_zero: return domain elif not f.has(symbol): return EmptySet elif f.is_Mul and all(_is_finite_with_finite_vars(m, domain) for m in f.args): # if f(x) and g(x) are both finite we can say that the solution of # f(x)*g(x) == 0 is same as Union(f(x) == 0, g(x) == 0) is not true in # general. g(x) can grow to infinitely large for the values where # f(x) == 0. To be sure that we are not silently allowing any # wrong solutions we are using this technique only if both f and g are # finite for a finite input. result = Union(*[solver(m, symbol) for m in f.args]) elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \ _is_function_class_equation(HyperbolicFunction, f, symbol): result = _solve_trig(f, symbol, domain) elif isinstance(f, arg): a = f.args[0] result = solveset_real(a > 0, symbol) elif f.is_Piecewise: expr_set_pairs = f.as_expr_set_pairs(domain) for (expr, in_set) in expr_set_pairs: if in_set.is_Relational: in_set = in_set.as_set() solns = solver(expr, symbol, in_set) result += solns elif isinstance(f, Eq): result = solver(Add(f.lhs, - f.rhs, evaluate=False), symbol, domain) elif f.is_Relational: if not domain.is_subset(S.Reals): raise NotImplementedError(filldedent(''' Inequalities in the complex domain are not supported. Try the real domain by setting domain=S.Reals''')) try: result = solve_univariate_inequality( f, symbol, domain=domain, relational=False) except NotImplementedError: result = ConditionSet(symbol, f, domain) return result elif _is_modular(f, symbol): result = _solve_modular(f, symbol, domain) else: lhs, rhs_s = inverter(f, 0, symbol) if lhs == symbol: # do some very minimal simplification since # repeated inversion may have left the result # in a state that other solvers (e.g. poly) # would have simplified; this is done here # rather than in the inverter since here it # is only done once whereas there it would # be repeated for each step of the inversion if isinstance(rhs_s, FiniteSet): rhs_s = FiniteSet(*[Mul(* signsimp(i).as_content_primitive()) for i in rhs_s]) result = rhs_s elif isinstance(rhs_s, FiniteSet): for equation in [lhs - rhs for rhs in rhs_s]: if equation == f: if any(_has_rational_power(g, symbol)[0] for g in equation.args) or _has_rational_power( equation, symbol)[0]: result += _solve_radical(equation, symbol, solver) elif equation.has(Abs): result += _solve_abs(f, symbol, domain) else: result_rational = _solve_as_rational(equation, symbol, domain) if isinstance(result_rational, ConditionSet): # may be a transcendental type equation result += _transolve(equation, symbol, domain) else: result += result_rational else: result += solver(equation, symbol) elif rhs_s is not S.EmptySet: result = ConditionSet(symbol, Eq(f, 0), domain) if isinstance(result, ConditionSet): if isinstance(f, Expr): num, den = f.as_numer_denom() else: num, den = f, S.One if den.has(symbol): _result = _solveset(num, symbol, domain) if not isinstance(_result, ConditionSet): singularities = _solveset(den, symbol, domain) result = _result - singularities if _check: if isinstance(result, ConditionSet): # it wasn't solved or has enumerated all conditions # -- leave it alone return result # whittle away all but the symbol-containing core # to use this for testing if isinstance(orig_f, Expr): fx = orig_f.as_independent(symbol, as_Add=True)[1] fx = fx.as_independent(symbol, as_Add=False)[1] else: fx = orig_f if isinstance(result, FiniteSet): # check the result for invalid solutions result = FiniteSet(*[s for s in result if isinstance(s, RootOf) or domain_check(fx, symbol, s)]) return result def _is_modular(f, symbol): """ Helper function to check below mentioned types of modular equations. ``A - Mod(B, C) = 0`` A -> This can or cannot be a function of symbol. B -> This is surely a function of symbol. C -> It is an integer. Parameters ========== f : Expr The equation to be checked. symbol : Symbol The concerned variable for which the equation is to be checked. Examples ======== >>> from sympy import symbols, exp, Mod >>> from sympy.solvers.solveset import _is_modular as check >>> x, y = symbols('x y') >>> check(Mod(x, 3) - 1, x) True >>> check(Mod(x, 3) - 1, y) False >>> check(Mod(x, 3)**2 - 5, x) False >>> check(Mod(x, 3)**2 - y, x) False >>> check(exp(Mod(x, 3)) - 1, x) False >>> check(Mod(3, y) - 1, y) False """ if not f.has(Mod): return False # extract modterms from f. modterms = list(f.atoms(Mod)) return (len(modterms) == 1 and # only one Mod should be present modterms[0].args[0].has(symbol) and # B-> function of symbol modterms[0].args[1].is_integer and # C-> to be an integer. any(isinstance(term, Mod) for term in list(_term_factors(f))) # free from other funcs ) def _invert_modular(modterm, rhs, n, symbol): """ Helper function to invert modular equation. ``Mod(a, m) - rhs = 0`` Generally it is inverted as (a, ImageSet(Lambda(n, m*n + rhs), S.Integers)). More simplified form will be returned if possible. If it is not invertible then (modterm, rhs) is returned. The following cases arise while inverting equation ``Mod(a, m) - rhs = 0``: 1. If a is symbol then m*n + rhs is the required solution. 2. If a is an instance of ``Add`` then we try to find two symbol independent parts of a and the symbol independent part gets tranferred to the other side and again the ``_invert_modular`` is called on the symbol dependent part. 3. If a is an instance of ``Mul`` then same as we done in ``Add`` we separate out the symbol dependent and symbol independent parts and transfer the symbol independent part to the rhs with the help of invert and again the ``_invert_modular`` is called on the symbol dependent part. 4. If a is an instance of ``Pow`` then two cases arise as following: - If a is of type (symbol_indep)**(symbol_dep) then the remainder is evaluated with the help of discrete_log function and then the least period is being found out with the help of totient function. period*n + remainder is the required solution in this case. For reference: (https://en.wikipedia.org/wiki/Euler's_theorem) - If a is of type (symbol_dep)**(symbol_indep) then we try to find all primitive solutions list with the help of nthroot_mod function. m*n + rem is the general solution where rem belongs to solutions list from nthroot_mod function. Parameters ========== modterm, rhs : Expr The modular equation to be inverted, ``modterm - rhs = 0`` symbol : Symbol The variable in the equation to be inverted. n : Dummy Dummy variable for output g_n. Returns ======= A tuple (f_x, g_n) is being returned where f_x is modular independent function of symbol and g_n being set of values f_x can have. Examples ======== >>> from sympy import symbols, exp, Mod, Dummy, S >>> from sympy.solvers.solveset import _invert_modular as invert_modular >>> x, y = symbols('x y') >>> n = Dummy('n') >>> invert_modular(Mod(exp(x), 7), S(5), n, x) (Mod(exp(x), 7), 5) >>> invert_modular(Mod(x, 7), S(5), n, x) (x, ImageSet(Lambda(_n, 7*_n + 5), Integers)) >>> invert_modular(Mod(3*x + 8, 7), S(5), n, x) (x, ImageSet(Lambda(_n, 7*_n + 6), Integers)) >>> invert_modular(Mod(x**4, 7), S(5), n, x) (x, EmptySet) >>> invert_modular(Mod(2**(x**2 + x + 1), 7), S(2), n, x) (x**2 + x + 1, ImageSet(Lambda(_n, 3*_n + 1), Naturals0)) """ a, m = modterm.args if rhs.is_real is False or any(term.is_real is False for term in list(_term_factors(a))): # Check for complex arguments return modterm, rhs if abs(rhs) >= abs(m): # if rhs has value greater than value of m. return symbol, EmptySet if a == symbol: return symbol, ImageSet(Lambda(n, m*n + rhs), S.Integers) if a.is_Add: # g + h = a g, h = a.as_independent(symbol) if g is not S.Zero: x_indep_term = rhs - Mod(g, m) return _invert_modular(Mod(h, m), Mod(x_indep_term, m), n, symbol) if a.is_Mul: # g*h = a g, h = a.as_independent(symbol) if g is not S.One: x_indep_term = rhs*invert(g, m) return _invert_modular(Mod(h, m), Mod(x_indep_term, m), n, symbol) if a.is_Pow: # base**expo = a base, expo = a.args if expo.has(symbol) and not base.has(symbol): # remainder -> solution independent of n of equation. # m, rhs are made coprime by dividing igcd(m, rhs) try: remainder = discrete_log(m / igcd(m, rhs), rhs, a.base) except ValueError: # log does not exist return modterm, rhs # period -> coefficient of n in the solution and also referred as # the least period of expo in which it is repeats itself. # (a**(totient(m)) - 1) divides m. Here is link of theorem: # (https://en.wikipedia.org/wiki/Euler's_theorem) period = totient(m) for p in divisors(period): # there might a lesser period exist than totient(m). if pow(a.base, p, m / igcd(m, a.base)) == 1: period = p break # recursion is not applied here since _invert_modular is currently # not smart enough to handle infinite rhs as here expo has infinite # rhs = ImageSet(Lambda(n, period*n + remainder), S.Naturals0). return expo, ImageSet(Lambda(n, period*n + remainder), S.Naturals0) elif base.has(symbol) and not expo.has(symbol): try: remainder_list = nthroot_mod(rhs, expo, m, all_roots=True) if remainder_list == []: return symbol, EmptySet except (ValueError, NotImplementedError): return modterm, rhs g_n = EmptySet for rem in remainder_list: g_n += ImageSet(Lambda(n, m*n + rem), S.Integers) return base, g_n return modterm, rhs def _solve_modular(f, symbol, domain): r""" Helper function for solving modular equations of type ``A - Mod(B, C) = 0``, where A can or cannot be a function of symbol, B is surely a function of symbol and C is an integer. Currently ``_solve_modular`` is only able to solve cases where A is not a function of symbol. Parameters ========== f : Expr The modular equation to be solved, ``f = 0`` symbol : Symbol The variable in the equation to be solved. domain : Set A set over which the equation is solved. It has to be a subset of Integers. Returns ======= A set of integer solutions satisfying the given modular equation. A ``ConditionSet`` if the equation is unsolvable. Examples ======== >>> from sympy.solvers.solveset import _solve_modular as solve_modulo >>> from sympy import S, Symbol, sin, Intersection, Interval >>> from sympy.core.mod import Mod >>> x = Symbol('x') >>> solve_modulo(Mod(5*x - 8, 7) - 3, x, S.Integers) ImageSet(Lambda(_n, 7*_n + 5), Integers) >>> solve_modulo(Mod(5*x - 8, 7) - 3, x, S.Reals) # domain should be subset of integers. ConditionSet(x, Eq(Mod(5*x + 6, 7) - 3, 0), Reals) >>> solve_modulo(-7 + Mod(x, 5), x, S.Integers) EmptySet >>> solve_modulo(Mod(12**x, 21) - 18, x, S.Integers) ImageSet(Lambda(_n, 6*_n + 2), Naturals0) >>> solve_modulo(Mod(sin(x), 7) - 3, x, S.Integers) # not solvable ConditionSet(x, Eq(Mod(sin(x), 7) - 3, 0), Integers) >>> solve_modulo(3 - Mod(x, 5), x, Intersection(S.Integers, Interval(0, 100))) Intersection(ImageSet(Lambda(_n, 5*_n + 3), Integers), Range(0, 101, 1)) """ # extract modterm and g_y from f unsolved_result = ConditionSet(symbol, Eq(f, 0), domain) modterm = list(f.atoms(Mod))[0] rhs = -S.One*(f.subs(modterm, S.Zero)) if f.as_coefficients_dict()[modterm].is_negative: # checks if coefficient of modterm is negative in main equation. rhs *= -S.One if not domain.is_subset(S.Integers): return unsolved_result if rhs.has(symbol): # TODO Case: A-> function of symbol, can be extended here # in future. return unsolved_result n = Dummy('n', integer=True) f_x, g_n = _invert_modular(modterm, rhs, n, symbol) if f_x == modterm and g_n == rhs: return unsolved_result if f_x == symbol: if domain is not S.Integers: return domain.intersect(g_n) return g_n if isinstance(g_n, ImageSet): lamda_expr = g_n.lamda.expr lamda_vars = g_n.lamda.variables base_sets = g_n.base_sets sol_set = _solveset(f_x - lamda_expr, symbol, S.Integers) if isinstance(sol_set, FiniteSet): tmp_sol = EmptySet for sol in sol_set: tmp_sol += ImageSet(Lambda(lamda_vars, sol), *base_sets) sol_set = tmp_sol else: sol_set = ImageSet(Lambda(lamda_vars, sol_set), *base_sets) return domain.intersect(sol_set) return unsolved_result def _term_factors(f): """ Iterator to get the factors of all terms present in the given equation. Parameters ========== f : Expr Equation that needs to be addressed Returns ======= Factors of all terms present in the equation. Examples ======== >>> from sympy import symbols >>> from sympy.solvers.solveset import _term_factors >>> x = symbols('x') >>> list(_term_factors(-2 - x**2 + x*(x + 1))) [-2, -1, x**2, x, x + 1] """ for add_arg in Add.make_args(f): for mul_arg in Mul.make_args(add_arg): yield mul_arg def _solve_exponential(lhs, rhs, symbol, domain): r""" Helper function for solving (supported) exponential equations. Exponential equations are the sum of (currently) at most two terms with one or both of them having a power with a symbol-dependent exponent. For example .. math:: 5^{2x + 3} - 5^{3x - 1} .. math:: 4^{5 - 9x} - e^{2 - x} Parameters ========== lhs, rhs : Expr The exponential equation to be solved, `lhs = rhs` symbol : Symbol The variable in which the equation is solved domain : Set A set over which the equation is solved. Returns ======= A set of solutions satisfying the given equation. A ``ConditionSet`` if the equation is unsolvable or if the assumptions are not properly defined, in that case a different style of ``ConditionSet`` is returned having the solution(s) of the equation with the desired assumptions. Examples ======== >>> from sympy.solvers.solveset import _solve_exponential as solve_expo >>> from sympy import symbols, S >>> x = symbols('x', real=True) >>> a, b = symbols('a b') >>> solve_expo(2**x + 3**x - 5**x, 0, x, S.Reals) # not solvable ConditionSet(x, Eq(2**x + 3**x - 5**x, 0), Reals) >>> solve_expo(a**x - b**x, 0, x, S.Reals) # solvable but incorrect assumptions ConditionSet(x, (a > 0) & (b > 0), FiniteSet(0)) >>> solve_expo(3**(2*x) - 2**(x + 3), 0, x, S.Reals) FiniteSet(-3*log(2)/(-2*log(3) + log(2))) >>> solve_expo(2**x - 4**x, 0, x, S.Reals) FiniteSet(0) * Proof of correctness of the method The logarithm function is the inverse of the exponential function. The defining relation between exponentiation and logarithm is: .. math:: {\log_b x} = y \enspace if \enspace b^y = x Therefore if we are given an equation with exponent terms, we can convert every term to its corresponding logarithmic form. This is achieved by taking logarithms and expanding the equation using logarithmic identities so that it can easily be handled by ``solveset``. For example: .. math:: 3^{2x} = 2^{x + 3} Taking log both sides will reduce the equation to .. math:: (2x)\log(3) = (x + 3)\log(2) This form can be easily handed by ``solveset``. """ unsolved_result = ConditionSet(symbol, Eq(lhs - rhs, 0), domain) newlhs = powdenest(lhs) if lhs != newlhs: # it may also be advantageous to factor the new expr return _solveset(factor(newlhs - rhs), symbol, domain) # try again with _solveset if not (isinstance(lhs, Add) and len(lhs.args) == 2): # solving for the sum of more than two powers is possible # but not yet implemented return unsolved_result if rhs != 0: return unsolved_result a, b = list(ordered(lhs.args)) a_term = a.as_independent(symbol)[1] b_term = b.as_independent(symbol)[1] a_base, a_exp = a_term.base, a_term.exp b_base, b_exp = b_term.base, b_term.exp from sympy.functions.elementary.complexes import im if domain.is_subset(S.Reals): conditions = And( a_base > 0, b_base > 0, Eq(im(a_exp), 0), Eq(im(b_exp), 0)) else: conditions = And( Ne(a_base, 0), Ne(b_base, 0)) L, R = map(lambda i: expand_log(log(i), force=True), (a, -b)) solutions = _solveset(L - R, symbol, domain) return ConditionSet(symbol, conditions, solutions) def _is_exponential(f, symbol): r""" Return ``True`` if one or more terms contain ``symbol`` only in exponents, else ``False``. Parameters ========== f : Expr The equation to be checked symbol : Symbol The variable in which the equation is checked Examples ======== >>> from sympy import symbols, cos, exp >>> from sympy.solvers.solveset import _is_exponential as check >>> x, y = symbols('x y') >>> check(y, y) False >>> check(x**y - 1, y) True >>> check(x**y*2**y - 1, y) True >>> check(exp(x + 3) + 3**x, x) True >>> check(cos(2**x), x) False * Philosophy behind the helper The function extracts each term of the equation and checks if it is of exponential form w.r.t ``symbol``. """ rv = False for expr_arg in _term_factors(f): if symbol not in expr_arg.free_symbols: continue if (isinstance(expr_arg, Pow) and symbol not in expr_arg.base.free_symbols or isinstance(expr_arg, exp)): rv = True # symbol in exponent else: return False # dependent on symbol in non-exponential way return rv def _solve_logarithm(lhs, rhs, symbol, domain): r""" Helper to solve logarithmic equations which are reducible to a single instance of `\log`. Logarithmic equations are (currently) the equations that contains `\log` terms which can be reduced to a single `\log` term or a constant using various logarithmic identities. For example: .. math:: \log(x) + \log(x - 4) can be reduced to: .. math:: \log(x(x - 4)) Parameters ========== lhs, rhs : Expr The logarithmic equation to be solved, `lhs = rhs` symbol : Symbol The variable in which the equation is solved domain : Set A set over which the equation is solved. Returns ======= A set of solutions satisfying the given equation. A ``ConditionSet`` if the equation is unsolvable. Examples ======== >>> from sympy import symbols, log, S >>> from sympy.solvers.solveset import _solve_logarithm as solve_log >>> x = symbols('x') >>> f = log(x - 3) + log(x + 3) >>> solve_log(f, 0, x, S.Reals) FiniteSet(sqrt(10), -sqrt(10)) * Proof of correctness A logarithm is another way to write exponent and is defined by .. math:: {\log_b x} = y \enspace if \enspace b^y = x When one side of the equation contains a single logarithm, the equation can be solved by rewriting the equation as an equivalent exponential equation as defined above. But if one side contains more than one logarithm, we need to use the properties of logarithm to condense it into a single logarithm. Take for example .. math:: \log(2x) - 15 = 0 contains single logarithm, therefore we can directly rewrite it to exponential form as .. math:: x = \frac{e^{15}}{2} But if the equation has more than one logarithm as .. math:: \log(x - 3) + \log(x + 3) = 0 we use logarithmic identities to convert it into a reduced form Using, .. math:: \log(a) + \log(b) = \log(ab) the equation becomes, .. math:: \log((x - 3)(x + 3)) This equation contains one logarithm and can be solved by rewriting to exponents. """ new_lhs = logcombine(lhs, force=True) new_f = new_lhs - rhs return _solveset(new_f, symbol, domain) def _is_logarithmic(f, symbol): r""" Return ``True`` if the equation is in the form `a\log(f(x)) + b\log(g(x)) + ... + c` else ``False``. Parameters ========== f : Expr The equation to be checked symbol : Symbol The variable in which the equation is checked Returns ======= ``True`` if the equation is logarithmic otherwise ``False``. Examples ======== >>> from sympy import symbols, tan, log >>> from sympy.solvers.solveset import _is_logarithmic as check >>> x, y = symbols('x y') >>> check(log(x + 2) - log(x + 3), x) True >>> check(tan(log(2*x)), x) False >>> check(x*log(x), x) False >>> check(x + log(x), x) False >>> check(y + log(x), x) True * Philosophy behind the helper The function extracts each term and checks whether it is logarithmic w.r.t ``symbol``. """ rv = False for term in Add.make_args(f): saw_log = False for term_arg in Mul.make_args(term): if symbol not in term_arg.free_symbols: continue if isinstance(term_arg, log): if saw_log: return False # more than one log in term saw_log = True else: return False # dependent on symbol in non-log way if saw_log: rv = True return rv def _transolve(f, symbol, domain): r""" Function to solve transcendental equations. It is a helper to ``solveset`` and should be used internally. ``_transolve`` currently supports the following class of equations: - Exponential equations - Logarithmic equations Parameters ========== f : Any transcendental equation that needs to be solved. This needs to be an expression, which is assumed to be equal to ``0``. symbol : The variable for which the equation is solved. This needs to be of class ``Symbol``. domain : A set over which the equation is solved. This needs to be of class ``Set``. Returns ======= Set A set of values for ``symbol`` for which ``f`` is equal to zero. An ``EmptySet`` is returned if ``f`` does not have solutions in respective domain. A ``ConditionSet`` is returned as unsolved object if algorithms to evaluate complete solution are not yet implemented. How to use ``_transolve`` ========================= ``_transolve`` should not be used as an independent function, because it assumes that the equation (``f``) and the ``symbol`` comes from ``solveset`` and might have undergone a few modification(s). To use ``_transolve`` as an independent function the equation (``f``) and the ``symbol`` should be passed as they would have been by ``solveset``. Examples ======== >>> from sympy.solvers.solveset import _transolve as transolve >>> from sympy.solvers.solvers import _tsolve as tsolve >>> from sympy import symbols, S, pprint >>> x = symbols('x', real=True) # assumption added >>> transolve(5**(x - 3) - 3**(2*x + 1), x, S.Reals) FiniteSet(-(log(3) + 3*log(5))/(-log(5) + 2*log(3))) How ``_transolve`` works ======================== ``_transolve`` uses two types of helper functions to solve equations of a particular class: Identifying helpers: To determine whether a given equation belongs to a certain class of equation or not. Returns either ``True`` or ``False``. Solving helpers: Once an equation is identified, a corresponding helper either solves the equation or returns a form of the equation that ``solveset`` might better be able to handle. * Philosophy behind the module The purpose of ``_transolve`` is to take equations which are not already polynomial in their generator(s) and to either recast them as such through a valid transformation or to solve them outright. A pair of helper functions for each class of supported transcendental functions are employed for this purpose. One identifies the transcendental form of an equation and the other either solves it or recasts it into a tractable form that can be solved by ``solveset``. For example, an equation in the form `ab^{f(x)} - cd^{g(x)} = 0` can be transformed to `\log(a) + f(x)\log(b) - \log(c) - g(x)\log(d) = 0` (under certain assumptions) and this can be solved with ``solveset`` if `f(x)` and `g(x)` are in polynomial form. How ``_transolve`` is better than ``_tsolve`` ============================================= 1) Better output ``_transolve`` provides expressions in a more simplified form. Consider a simple exponential equation >>> f = 3**(2*x) - 2**(x + 3) >>> pprint(transolve(f, x, S.Reals), use_unicode=False) -3*log(2) {------------------} -2*log(3) + log(2) >>> pprint(tsolve(f, x), use_unicode=False) / 3 \ | --------| | log(2/9)| [-log\2 /] 2) Extensible The API of ``_transolve`` is designed such that it is easily extensible, i.e. the code that solves a given class of equations is encapsulated in a helper and not mixed in with the code of ``_transolve`` itself. 3) Modular ``_transolve`` is designed to be modular i.e, for every class of equation a separate helper for identification and solving is implemented. This makes it easy to change or modify any of the method implemented directly in the helpers without interfering with the actual structure of the API. 4) Faster Computation Solving equation via ``_transolve`` is much faster as compared to ``_tsolve``. In ``solve``, attempts are made computing every possibility to get the solutions. This series of attempts makes solving a bit slow. In ``_transolve``, computation begins only after a particular type of equation is identified. How to add new class of equations ================================= Adding a new class of equation solver is a three-step procedure: - Identify the type of the equations Determine the type of the class of equations to which they belong: it could be of ``Add``, ``Pow``, etc. types. Separate internal functions are used for each type. Write identification and solving helpers and use them from within the routine for the given type of equation (after adding it, if necessary). Something like: .. code-block:: python def add_type(lhs, rhs, x): .... if _is_exponential(lhs, x): new_eq = _solve_exponential(lhs, rhs, x) .... rhs, lhs = eq.as_independent(x) if lhs.is_Add: result = add_type(lhs, rhs, x) - Define the identification helper. - Define the solving helper. Apart from this, a few other things needs to be taken care while adding an equation solver: - Naming conventions: Name of the identification helper should be as ``_is_class`` where class will be the name or abbreviation of the class of equation. The solving helper will be named as ``_solve_class``. For example: for exponential equations it becomes ``_is_exponential`` and ``_solve_expo``. - The identifying helpers should take two input parameters, the equation to be checked and the variable for which a solution is being sought, while solving helpers would require an additional domain parameter. - Be sure to consider corner cases. - Add tests for each helper. - Add a docstring to your helper that describes the method implemented. The documentation of the helpers should identify: - the purpose of the helper, - the method used to identify and solve the equation, - a proof of correctness - the return values of the helpers """ def add_type(lhs, rhs, symbol, domain): """ Helper for ``_transolve`` to handle equations of ``Add`` type, i.e. equations taking the form as ``a*f(x) + b*g(x) + .... = c``. For example: 4**x + 8**x = 0 """ result = ConditionSet(symbol, Eq(lhs - rhs, 0), domain) # check if it is exponential type equation if _is_exponential(lhs, symbol): result = _solve_exponential(lhs, rhs, symbol, domain) # check if it is logarithmic type equation elif _is_logarithmic(lhs, symbol): result = _solve_logarithm(lhs, rhs, symbol, domain) return result result = ConditionSet(symbol, Eq(f, 0), domain) # invert_complex handles the call to the desired inverter based # on the domain specified. lhs, rhs_s = invert_complex(f, 0, symbol, domain) if isinstance(rhs_s, FiniteSet): assert (len(rhs_s.args)) == 1 rhs = rhs_s.args[0] if lhs.is_Add: result = add_type(lhs, rhs, symbol, domain) else: result = rhs_s return result def solveset(f, symbol=None, domain=S.Complexes): r"""Solves a given inequality or equation with set as output Parameters ========== f : Expr or a relational. The target equation or inequality symbol : Symbol The variable for which the equation is solved domain : Set The domain over which the equation is solved Returns ======= Set A set of values for `symbol` for which `f` is True or is equal to zero. An `EmptySet` is returned if `f` is False or nonzero. A `ConditionSet` is returned as unsolved object if algorithms to evaluate complete solution are not yet implemented. `solveset` claims to be complete in the solution set that it returns. Raises ====== NotImplementedError The algorithms to solve inequalities in complex domain are not yet implemented. ValueError The input is not valid. RuntimeError It is a bug, please report to the github issue tracker. Notes ===== Python interprets 0 and 1 as False and True, respectively, but in this function they refer to solutions of an expression. So 0 and 1 return the Domain and EmptySet, respectively, while True and False return the opposite (as they are assumed to be solutions of relational expressions). See Also ======== solveset_real: solver for real domain solveset_complex: solver for complex domain Examples ======== >>> from sympy import exp, sin, Symbol, pprint, S, Eq >>> from sympy.solvers.solveset import solveset, solveset_real * The default domain is complex. Not specifying a domain will lead to the solving of the equation in the complex domain (and this is not affected by the assumptions on the symbol): >>> x = Symbol('x') >>> pprint(solveset(exp(x) - 1, x), use_unicode=False) {2*n*I*pi | n in Integers} >>> x = Symbol('x', real=True) >>> pprint(solveset(exp(x) - 1, x), use_unicode=False) {2*n*I*pi | n in Integers} * If you want to use `solveset` to solve the equation in the real domain, provide a real domain. (Using ``solveset_real`` does this automatically.) >>> R = S.Reals >>> x = Symbol('x') >>> solveset(exp(x) - 1, x, R) FiniteSet(0) >>> solveset_real(exp(x) - 1, x) FiniteSet(0) The solution is unaffected by assumptions on the symbol: >>> p = Symbol('p', positive=True) >>> pprint(solveset(p**2 - 4)) {-2, 2} When a conditionSet is returned, symbols with assumptions that would alter the set are replaced with more generic symbols: >>> i = Symbol('i', imaginary=True) >>> solveset(Eq(i**2 + i*sin(i), 1), i, domain=S.Reals) ConditionSet(_R, Eq(_R**2 + _R*sin(_R) - 1, 0), Reals) * Inequalities can be solved over the real domain only. Use of a complex domain leads to a NotImplementedError. >>> solveset(exp(x) > 1, x, R) Interval.open(0, oo) """ f = sympify(f) symbol = sympify(symbol) if f is S.true: return domain if f is S.false: return S.EmptySet if not isinstance(f, (Expr, Relational, Number)): raise ValueError("%s is not a valid SymPy expression" % f) if not isinstance(symbol, (Expr, Relational)) and symbol is not None: raise ValueError("%s is not a valid SymPy symbol" % symbol) if not isinstance(domain, Set): raise ValueError("%s is not a valid domain" %(domain)) free_symbols = f.free_symbols if symbol is None and not free_symbols: b = Eq(f, 0) if b is S.true: return domain elif b is S.false: return S.EmptySet else: raise NotImplementedError(filldedent(''' relationship between value and 0 is unknown: %s''' % b)) if symbol is None: if len(free_symbols) == 1: symbol = free_symbols.pop() elif free_symbols: raise ValueError(filldedent(''' The independent variable must be specified for a multivariate equation.''')) elif not isinstance(symbol, Symbol): f, s, swap = recast_to_symbols([f], [symbol]) # the xreplace will be needed if a ConditionSet is returned return solveset(f[0], s[0], domain).xreplace(swap) # solveset should ignore assumptions on symbols if symbol not in _rc: x = _rc[0] if domain.is_subset(S.Reals) else _rc[1] rv = solveset(f.xreplace({symbol: x}), x, domain) # try to use the original symbol if possible try: _rv = rv.xreplace({x: symbol}) except TypeError: _rv = rv if rv.dummy_eq(_rv): rv = _rv return rv # Abs has its own handling method which avoids the # rewriting property that the first piece of abs(x) # is for x >= 0 and the 2nd piece for x < 0 -- solutions # can look better if the 2nd condition is x <= 0. Since # the solution is a set, duplication of results is not # an issue, e.g. {y, -y} when y is 0 will be {0} f, mask = _masked(f, Abs) f = f.rewrite(Piecewise) # everything that's not an Abs for d, e in mask: # everything *in* an Abs e = e.func(e.args[0].rewrite(Piecewise)) f = f.xreplace({d: e}) f = piecewise_fold(f) return _solveset(f, symbol, domain, _check=True) def solveset_real(f, symbol): return solveset(f, symbol, S.Reals) def solveset_complex(f, symbol): return solveset(f, symbol, S.Complexes) def _solveset_multi(eqs, syms, domains): '''Basic implementation of a multivariate solveset. For internal use (not ready for public consumption)''' rep = {} for sym, dom in zip(syms, domains): if dom is S.Reals: rep[sym] = Symbol(sym.name, real=True) eqs = [eq.subs(rep) for eq in eqs] syms = [sym.subs(rep) for sym in syms] syms = tuple(syms) if len(eqs) == 0: return ProductSet(*domains) if len(syms) == 1: sym = syms[0] domain = domains[0] solsets = [solveset(eq, sym, domain) for eq in eqs] solset = Intersection(*solsets) return ImageSet(Lambda((sym,), (sym,)), solset).doit() eqs = sorted(eqs, key=lambda eq: len(eq.free_symbols & set(syms))) for n in range(len(eqs)): sols = [] all_handled = True for sym in syms: if sym not in eqs[n].free_symbols: continue sol = solveset(eqs[n], sym, domains[syms.index(sym)]) if isinstance(sol, FiniteSet): i = syms.index(sym) symsp = syms[:i] + syms[i+1:] domainsp = domains[:i] + domains[i+1:] eqsp = eqs[:n] + eqs[n+1:] for s in sol: eqsp_sub = [eq.subs(sym, s) for eq in eqsp] sol_others = _solveset_multi(eqsp_sub, symsp, domainsp) fun = Lambda((symsp,), symsp[:i] + (s,) + symsp[i:]) sols.append(ImageSet(fun, sol_others).doit()) else: all_handled = False if all_handled: return Union(*sols) def solvify(f, symbol, domain): """Solves an equation using solveset and returns the solution in accordance with the `solve` output API. Returns ======= We classify the output based on the type of solution returned by `solveset`. Solution | Output ---------------------------------------- FiniteSet | list ImageSet, | list (if `f` is periodic) Union | EmptySet | empty list Others | None Raises ====== NotImplementedError A ConditionSet is the input. Examples ======== >>> from sympy.solvers.solveset import solvify >>> from sympy.abc import x >>> from sympy import S, tan, sin, exp >>> solvify(x**2 - 9, x, S.Reals) [-3, 3] >>> solvify(sin(x) - 1, x, S.Reals) [pi/2] >>> solvify(tan(x), x, S.Reals) [0] >>> solvify(exp(x) - 1, x, S.Complexes) >>> solvify(exp(x) - 1, x, S.Reals) [0] """ solution_set = solveset(f, symbol, domain) result = None if solution_set is S.EmptySet: result = [] elif isinstance(solution_set, ConditionSet): raise NotImplementedError('solveset is unable to solve this equation.') elif isinstance(solution_set, FiniteSet): result = list(solution_set) else: period = periodicity(f, symbol) if period is not None: solutions = S.EmptySet iter_solutions = () if isinstance(solution_set, ImageSet): iter_solutions = (solution_set,) elif isinstance(solution_set, Union): if all(isinstance(i, ImageSet) for i in solution_set.args): iter_solutions = solution_set.args for solution in iter_solutions: solutions += solution.intersect(Interval(0, period, False, True)) if isinstance(solutions, FiniteSet): result = list(solutions) else: solution = solution_set.intersect(domain) if isinstance(solution, FiniteSet): result += solution return result ############################################################################### ################################ LINSOLVE ##################################### ############################################################################### def linear_coeffs(eq, *syms, **_kw): """Return a list whose elements are the coefficients of the corresponding symbols in the sum of terms in ``eq``. The additive constant is returned as the last element of the list. Raises ====== NonlinearError The equation contains a nonlinear term Examples ======== >>> from sympy.solvers.solveset import linear_coeffs >>> from sympy.abc import x, y, z >>> linear_coeffs(3*x + 2*y - 1, x, y) [3, 2, -1] It is not necessary to expand the expression: >>> linear_coeffs(x + y*(z*(x*3 + 2) + 3), x) [3*y*z + 1, y*(2*z + 3)] But if there are nonlinear or cross terms -- even if they would cancel after simplification -- an error is raised so the situation does not pass silently past the caller's attention: >>> eq = 1/x*(x - 1) + 1/x >>> linear_coeffs(eq.expand(), x) [0, 1] >>> linear_coeffs(eq, x) Traceback (most recent call last): ... NonlinearError: nonlinear term encountered: 1/x >>> linear_coeffs(x*(y + 1) - x*y, x, y) Traceback (most recent call last): ... NonlinearError: nonlinear term encountered: x*(y + 1) """ d = defaultdict(list) eq = _sympify(eq) symset = set(syms) has = eq.free_symbols & symset if not has: return [S.Zero]*len(syms) + [eq] c, terms = eq.as_coeff_add(*has) d[0].extend(Add.make_args(c)) for t in terms: m, f = t.as_coeff_mul(*has) if len(f) != 1: break f = f[0] if f in symset: d[f].append(m) elif f.is_Add: d1 = linear_coeffs(f, *has, **{'dict': True}) d[0].append(m*d1.pop(0)) for xf, vf in d1.items(): d[xf].append(m*vf) else: break else: for k, v in d.items(): d[k] = Add(*v) if not _kw: return [d.get(s, S.Zero) for s in syms] + [d[0]] return d # default is still list but this won't matter raise NonlinearError('nonlinear term encountered: %s' % t) def linear_eq_to_matrix(equations, *symbols): r""" Converts a given System of Equations into Matrix form. Here `equations` must be a linear system of equations in `symbols`. Element M[i, j] corresponds to the coefficient of the jth symbol in the ith equation. The Matrix form corresponds to the augmented matrix form. For example: .. math:: 4x + 2y + 3z = 1 .. math:: 3x + y + z = -6 .. math:: 2x + 4y + 9z = 2 This system would return `A` & `b` as given below: :: [ 4 2 3 ] [ 1 ] A = [ 3 1 1 ] b = [-6 ] [ 2 4 9 ] [ 2 ] The only simplification performed is to convert `Eq(a, b) -> a - b`. Raises ====== NonlinearError The equations contain a nonlinear term. ValueError The symbols are not given or are not unique. Examples ======== >>> from sympy import linear_eq_to_matrix, symbols >>> c, x, y, z = symbols('c, x, y, z') The coefficients (numerical or symbolic) of the symbols will be returned as matrices: >>> eqns = [c*x + z - 1 - c, y + z, x - y] >>> A, b = linear_eq_to_matrix(eqns, [x, y, z]) >>> A Matrix([ [c, 0, 1], [0, 1, 1], [1, -1, 0]]) >>> b Matrix([ [c + 1], [ 0], [ 0]]) This routine does not simplify expressions and will raise an error if nonlinearity is encountered: >>> eqns = [ ... (x**2 - 3*x)/(x - 3) - 3, ... y**2 - 3*y - y*(y - 4) + x - 4] >>> linear_eq_to_matrix(eqns, [x, y]) Traceback (most recent call last): ... NonlinearError: The term (x**2 - 3*x)/(x - 3) is nonlinear in {x, y} Simplifying these equations will discard the removable singularity in the first, reveal the linear structure of the second: >>> [e.simplify() for e in eqns] [x - 3, x + y - 4] Any such simplification needed to eliminate nonlinear terms must be done before calling this routine. """ if not symbols: raise ValueError(filldedent(''' Symbols must be given, for which coefficients are to be found. ''')) if hasattr(symbols[0], '__iter__'): symbols = symbols[0] for i in symbols: if not isinstance(i, Symbol): raise ValueError(filldedent(''' Expecting a Symbol but got %s ''' % i)) if has_dups(symbols): raise ValueError('Symbols must be unique') equations = sympify(equations) if isinstance(equations, MatrixBase): equations = list(equations) elif isinstance(equations, (Expr, Eq)): equations = [equations] elif not is_sequence(equations): raise ValueError(filldedent(''' Equation(s) must be given as a sequence, Expr, Eq or Matrix. ''')) A, b = [], [] for i, f in enumerate(equations): if isinstance(f, Equality): f = f.rewrite(Add, evaluate=False) coeff_list = linear_coeffs(f, *symbols) b.append(-coeff_list.pop()) A.append(coeff_list) A, b = map(Matrix, (A, b)) return A, b def linsolve(system, *symbols): r""" Solve system of N linear equations with M variables; both underdetermined and overdetermined systems are supported. The possible number of solutions is zero, one or infinite. Zero solutions throws a ValueError, whereas infinite solutions are represented parametrically in terms of the given symbols. For unique solution a FiniteSet of ordered tuples is returned. All Standard input formats are supported: For the given set of Equations, the respective input types are given below: .. math:: 3x + 2y - z = 1 .. math:: 2x - 2y + 4z = -2 .. math:: 2x - y + 2z = 0 * Augmented Matrix Form, `system` given below: :: [3 2 -1 1] system = [2 -2 4 -2] [2 -1 2 0] * List Of Equations Form `system = [3x + 2y - z - 1, 2x - 2y + 4z + 2, 2x - y + 2z]` * Input A & b Matrix Form (from Ax = b) are given as below: :: [3 2 -1 ] [ 1 ] A = [2 -2 4 ] b = [ -2 ] [2 -1 2 ] [ 0 ] `system = (A, b)` Symbols can always be passed but are actually only needed when 1) a system of equations is being passed and 2) the system is passed as an underdetermined matrix and one wants to control the name of the free variables in the result. An error is raised if no symbols are used for case 1, but if no symbols are provided for case 2, internally generated symbols will be provided. When providing symbols for case 2, there should be at least as many symbols are there are columns in matrix A. The algorithm used here is Gauss-Jordan elimination, which results, after elimination, in a row echelon form matrix. Returns ======= A FiniteSet containing an ordered tuple of values for the unknowns for which the `system` has a solution. (Wrapping the tuple in FiniteSet is used to maintain a consistent output format throughout solveset.) Returns EmptySet, if the linear system is inconsistent. Raises ====== ValueError The input is not valid. The symbols are not given. Examples ======== >>> from sympy import Matrix, linsolve, symbols >>> x, y, z = symbols("x, y, z") >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) >>> b = Matrix([3, 6, 9]) >>> A Matrix([ [1, 2, 3], [4, 5, 6], [7, 8, 10]]) >>> b Matrix([ [3], [6], [9]]) >>> linsolve((A, b), [x, y, z]) FiniteSet((-1, 2, 0)) * Parametric Solution: In case the system is underdetermined, the function will return a parametric solution in terms of the given symbols. Those that are free will be returned unchanged. e.g. in the system below, `z` is returned as the solution for variable z; it can take on any value. >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> b = Matrix([3, 6, 9]) >>> linsolve((A, b), x, y, z) FiniteSet((z - 1, 2 - 2*z, z)) If no symbols are given, internally generated symbols will be used. The `tau0` in the 3rd position indicates (as before) that the 3rd variable -- whatever it's named -- can take on any value: >>> linsolve((A, b)) FiniteSet((tau0 - 1, 2 - 2*tau0, tau0)) * List of Equations as input >>> Eqns = [3*x + 2*y - z - 1, 2*x - 2*y + 4*z + 2, - x + y/2 - z] >>> linsolve(Eqns, x, y, z) FiniteSet((1, -2, -2)) * Augmented Matrix as input >>> aug = Matrix([[2, 1, 3, 1], [2, 6, 8, 3], [6, 8, 18, 5]]) >>> aug Matrix([ [2, 1, 3, 1], [2, 6, 8, 3], [6, 8, 18, 5]]) >>> linsolve(aug, x, y, z) FiniteSet((3/10, 2/5, 0)) * Solve for symbolic coefficients >>> a, b, c, d, e, f = symbols('a, b, c, d, e, f') >>> eqns = [a*x + b*y - c, d*x + e*y - f] >>> linsolve(eqns, x, y) FiniteSet(((-b*f + c*e)/(a*e - b*d), (a*f - c*d)/(a*e - b*d))) * A degenerate system returns solution as set of given symbols. >>> system = Matrix(([0, 0, 0], [0, 0, 0], [0, 0, 0])) >>> linsolve(system, x, y) FiniteSet((x, y)) * For an empty system linsolve returns empty set >>> linsolve([], x) EmptySet * An error is raised if, after expansion, any nonlinearity is detected: >>> linsolve([x*(1/x - 1), (y - 1)**2 - y**2 + 1], x, y) FiniteSet((1, 1)) >>> linsolve([x**2 - 1], x) Traceback (most recent call last): ... NonlinearError: nonlinear term encountered: x**2 """ if not system: return S.EmptySet # If second argument is an iterable if symbols and hasattr(symbols[0], '__iter__'): symbols = symbols[0] sym_gen = isinstance(symbols, GeneratorType) b = None # if we don't get b the input was bad syms_needed_msg = None # unpack system if hasattr(system, '__iter__'): # 1). (A, b) if len(system) == 2 and isinstance(system[0], MatrixBase): A, b = system # 2). (eq1, eq2, ...) if not isinstance(system[0], MatrixBase): if sym_gen or not symbols: raise ValueError(filldedent(''' When passing a system of equations, the explicit symbols for which a solution is being sought must be given as a sequence, too. ''')) eqs = system try: eqs, ring = sympy_eqs_to_ring(eqs, symbols) except PolynomialError as exc: # e.g. cos(x) contains an element of the set of generators raise NonlinearError(str(exc)) try: sol = solve_lin_sys(eqs, ring, _raw=False) except PolyNonlinearError as exc: raise NonlinearError(str(exc)) if sol is None: return S.EmptySet sol = FiniteSet(Tuple(*(sol.get(sym, sym) for sym in symbols))) return sol elif isinstance(system, MatrixBase) and not ( symbols and not isinstance(symbols, GeneratorType) and isinstance(symbols[0], MatrixBase)): # 3). A augmented with b A, b = system[:, :-1], system[:, -1:] if b is None: raise ValueError("Invalid arguments") syms_needed_msg = syms_needed_msg or 'columns of A' if sym_gen: symbols = [next(symbols) for i in range(A.cols)] if any(set(symbols) & (A.free_symbols | b.free_symbols)): raise ValueError(filldedent(''' At least one of the symbols provided already appears in the system to be solved. One way to avoid this is to use Dummy symbols in the generator, e.g. numbered_symbols('%s', cls=Dummy) ''' % symbols[0].name.rstrip('1234567890'))) if not symbols: symbols = [Dummy() for _ in range(A.cols)] name = _uniquely_named_symbol('tau', (A, b), compare=lambda i: str(i).rstrip('1234567890')).name gen = numbered_symbols(name) else: gen = None # This is just a wrapper for solve_lin_sys eqs = [] rows = A.tolist() for rowi, bi in zip(rows, b): terms = [elem * sym for elem, sym in zip(rowi, symbols) if elem] terms.append(-bi) eqs.append(Add(*terms)) eqs, ring = sympy_eqs_to_ring(eqs, symbols) sol = solve_lin_sys(eqs, ring, _raw=False) if sol is None: return S.EmptySet #sol = {sym:val for sym, val in sol.items() if sym != val} sol = FiniteSet(Tuple(*(sol.get(sym, sym) for sym in symbols))) if gen is not None: solsym = sol.free_symbols rep = {sym: next(gen) for sym in symbols if sym in solsym} sol = sol.subs(rep) return sol ############################################################################## # ------------------------------nonlinsolve ---------------------------------# ############################################################################## def _return_conditionset(eqs, symbols): # return conditionset eqs = (Eq(lhs, 0) for lhs in eqs) condition_set = ConditionSet( Tuple(*symbols), And(*eqs), S.Complexes**len(symbols)) return condition_set def substitution(system, symbols, result=[{}], known_symbols=[], exclude=[], all_symbols=None): r""" Solves the `system` using substitution method. It is used in `nonlinsolve`. This will be called from `nonlinsolve` when any equation(s) is non polynomial equation. Parameters ========== system : list of equations The target system of equations symbols : list of symbols to be solved. The variable(s) for which the system is solved known_symbols : list of solved symbols Values are known for these variable(s) result : An empty list or list of dict If No symbol values is known then empty list otherwise symbol as keys and corresponding value in dict. exclude : Set of expression. Mostly denominator expression(s) of the equations of the system. Final solution should not satisfy these expressions. all_symbols : known_symbols + symbols(unsolved). Returns ======= A FiniteSet of ordered tuple of values of `all_symbols` for which the `system` has solution. Order of values in the tuple is same as symbols present in the parameter `all_symbols`. If parameter `all_symbols` is None then same as symbols present in the parameter `symbols`. Please note that general FiniteSet is unordered, the solution returned here is not simply a FiniteSet of solutions, rather it is a FiniteSet of ordered tuple, i.e. the first & only argument to FiniteSet is a tuple of solutions, which is ordered, & hence the returned solution is ordered. Also note that solution could also have been returned as an ordered tuple, FiniteSet is just a wrapper `{}` around the tuple. It has no other significance except for the fact it is just used to maintain a consistent output format throughout the solveset. Raises ====== ValueError The input is not valid. The symbols are not given. AttributeError The input symbols are not `Symbol` type. Examples ======== >>> from sympy.core.symbol import symbols >>> x, y = symbols('x, y', real=True) >>> from sympy.solvers.solveset import substitution >>> substitution([x + y], [x], [{y: 1}], [y], set([]), [x, y]) FiniteSet((-1, 1)) * when you want soln should not satisfy eq `x + 1 = 0` >>> substitution([x + y], [x], [{y: 1}], [y], set([x + 1]), [y, x]) EmptySet >>> substitution([x + y], [x], [{y: 1}], [y], set([x - 1]), [y, x]) FiniteSet((1, -1)) >>> substitution([x + y - 1, y - x**2 + 5], [x, y]) FiniteSet((-3, 4), (2, -1)) * Returns both real and complex solution >>> x, y, z = symbols('x, y, z') >>> from sympy import exp, sin >>> substitution([exp(x) - sin(y), y**2 - 4], [x, y]) FiniteSet((ImageSet(Lambda(_n, 2*_n*I*pi + log(sin(2))), Integers), 2), (ImageSet(Lambda(_n, I*(2*_n*pi + pi) + log(sin(2))), Integers), -2)) >>> eqs = [z**2 + exp(2*x) - sin(y), -3 + exp(-y)] >>> substitution(eqs, [y, z]) FiniteSet((-log(3), sqrt(-exp(2*x) - sin(log(3)))), (-log(3), -sqrt(-exp(2*x) - sin(log(3)))), (ImageSet(Lambda(_n, 2*_n*I*pi - log(3)), Integers), ImageSet(Lambda(_n, sqrt(-exp(2*x) + sin(2*_n*I*pi - log(3)))), Integers)), (ImageSet(Lambda(_n, 2*_n*I*pi - log(3)), Integers), ImageSet(Lambda(_n, -sqrt(-exp(2*x) + sin(2*_n*I*pi - log(3)))), Integers))) """ from sympy import Complement from sympy.core.compatibility import is_sequence if not system: return S.EmptySet if not symbols: msg = ('Symbols must be given, for which solution of the ' 'system is to be found.') raise ValueError(filldedent(msg)) if not is_sequence(symbols): msg = ('symbols should be given as a sequence, e.g. a list.' 'Not type %s: %s') raise TypeError(filldedent(msg % (type(symbols), symbols))) if not getattr(symbols[0], 'is_Symbol', False): msg = ('Iterable of symbols must be given as ' 'second argument, not type %s: %s') raise ValueError(filldedent(msg % (type(symbols[0]), symbols[0]))) # By default `all_symbols` will be same as `symbols` if all_symbols is None: all_symbols = symbols old_result = result # storing complements and intersection for particular symbol complements = {} intersections = {} # when total_solveset_call equals total_conditionset # it means that solveset failed to solve all eqs. total_conditionset = -1 total_solveset_call = -1 def _unsolved_syms(eq, sort=False): """Returns the unsolved symbol present in the equation `eq`. """ free = eq.free_symbols unsolved = (free - set(known_symbols)) & set(all_symbols) if sort: unsolved = list(unsolved) unsolved.sort(key=default_sort_key) return unsolved # end of _unsolved_syms() # sort such that equation with the fewest potential symbols is first. # means eq with less number of variable first in the list. eqs_in_better_order = list( ordered(system, lambda _: len(_unsolved_syms(_)))) def add_intersection_complement(result, intersection_dict, complement_dict): # If solveset has returned some intersection/complement # for any symbol, it will be added in the final solution. final_result = [] for res in result: res_copy = res for key_res, value_res in res.items(): intersect_set, complement_set = None, None for key_sym, value_sym in intersection_dict.items(): if key_sym == key_res: intersect_set = value_sym for key_sym, value_sym in complement_dict.items(): if key_sym == key_res: complement_set = value_sym if intersect_set or complement_set: new_value = FiniteSet(value_res) if intersect_set and intersect_set != S.Complexes: new_value = Intersection(new_value, intersect_set) if complement_set: new_value = Complement(new_value, complement_set) if new_value is S.EmptySet: res_copy = None break elif new_value.is_FiniteSet and len(new_value) == 1: res_copy[key_res] = set(new_value).pop() else: res_copy[key_res] = new_value if res_copy is not None: final_result.append(res_copy) return final_result # end of def add_intersection_complement() def _extract_main_soln(sym, sol, soln_imageset): """Separate the Complements, Intersections, ImageSet lambda expr and its base_set. """ # if there is union, then need to check # Complement, Intersection, Imageset. # Order should not be changed. if isinstance(sol, Complement): # extract solution and complement complements[sym] = sol.args[1] sol = sol.args[0] # complement will be added at the end # using `add_intersection_complement` method if isinstance(sol, Intersection): # Interval/Set will be at 0th index always if sol.args[0] not in (S.Reals, S.Complexes): # Sometimes solveset returns soln with intersection # S.Reals or S.Complexes. We don't consider that # intersection. intersections[sym] = sol.args[0] sol = sol.args[1] # after intersection and complement Imageset should # be checked. if isinstance(sol, ImageSet): soln_imagest = sol expr2 = sol.lamda.expr sol = FiniteSet(expr2) soln_imageset[expr2] = soln_imagest # if there is union of Imageset or other in soln. # no testcase is written for this if block if isinstance(sol, Union): sol_args = sol.args sol = S.EmptySet # We need in sequence so append finteset elements # and then imageset or other. for sol_arg2 in sol_args: if isinstance(sol_arg2, FiniteSet): sol += sol_arg2 else: # ImageSet, Intersection, complement then # append them directly sol += FiniteSet(sol_arg2) if not isinstance(sol, FiniteSet): sol = FiniteSet(sol) return sol, soln_imageset # end of def _extract_main_soln() # helper function for _append_new_soln def _check_exclude(rnew, imgset_yes): rnew_ = rnew if imgset_yes: # replace all dummy variables (Imageset lambda variables) # with zero before `checksol`. Considering fundamental soln # for `checksol`. rnew_copy = rnew.copy() dummy_n = imgset_yes[0] for key_res, value_res in rnew_copy.items(): rnew_copy[key_res] = value_res.subs(dummy_n, 0) rnew_ = rnew_copy # satisfy_exclude == true if it satisfies the expr of `exclude` list. try: # something like : `Mod(-log(3), 2*I*pi)` can't be # simplified right now, so `checksol` returns `TypeError`. # when this issue is fixed this try block should be # removed. Mod(-log(3), 2*I*pi) == -log(3) satisfy_exclude = any( checksol(d, rnew_) for d in exclude) except TypeError: satisfy_exclude = None return satisfy_exclude # end of def _check_exclude() # helper function for _append_new_soln def _restore_imgset(rnew, original_imageset, newresult): restore_sym = set(rnew.keys()) & \ set(original_imageset.keys()) for key_sym in restore_sym: img = original_imageset[key_sym] rnew[key_sym] = img if rnew not in newresult: newresult.append(rnew) # end of def _restore_imgset() def _append_eq(eq, result, res, delete_soln, n=None): u = Dummy('u') if n: eq = eq.subs(n, 0) satisfy = checksol(u, u, eq, minimal=True) if satisfy is False: delete_soln = True res = {} else: result.append(res) return result, res, delete_soln def _append_new_soln(rnew, sym, sol, imgset_yes, soln_imageset, original_imageset, newresult, eq=None): """If `rnew` (A dict <symbol: soln>) contains valid soln append it to `newresult` list. `imgset_yes` is (base, dummy_var) if there was imageset in previously calculated result(otherwise empty tuple). `original_imageset` is dict of imageset expr and imageset from this result. `soln_imageset` dict of imageset expr and imageset of new soln. """ satisfy_exclude = _check_exclude(rnew, imgset_yes) delete_soln = False # soln should not satisfy expr present in `exclude` list. if not satisfy_exclude: local_n = None # if it is imageset if imgset_yes: local_n = imgset_yes[0] base = imgset_yes[1] if sym and sol: # when `sym` and `sol` is `None` means no new # soln. In that case we will append rnew directly after # substituting original imagesets in rnew values if present # (second last line of this function using _restore_imgset) dummy_list = list(sol.atoms(Dummy)) # use one dummy `n` which is in # previous imageset local_n_list = [ local_n for i in range( 0, len(dummy_list))] dummy_zip = zip(dummy_list, local_n_list) lam = Lambda(local_n, sol.subs(dummy_zip)) rnew[sym] = ImageSet(lam, base) if eq is not None: newresult, rnew, delete_soln = _append_eq( eq, newresult, rnew, delete_soln, local_n) elif eq is not None: newresult, rnew, delete_soln = _append_eq( eq, newresult, rnew, delete_soln) elif soln_imageset: rnew[sym] = soln_imageset[sol] # restore original imageset _restore_imgset(rnew, original_imageset, newresult) else: newresult.append(rnew) elif satisfy_exclude: delete_soln = True rnew = {} _restore_imgset(rnew, original_imageset, newresult) return newresult, delete_soln # end of def _append_new_soln() def _new_order_result(result, eq): # separate first, second priority. `res` that makes `eq` value equals # to zero, should be used first then other result(second priority). # If it is not done then we may miss some soln. first_priority = [] second_priority = [] for res in result: if not any(isinstance(val, ImageSet) for val in res.values()): if eq.subs(res) == 0: first_priority.append(res) else: second_priority.append(res) if first_priority or second_priority: return first_priority + second_priority return result def _solve_using_known_values(result, solver): """Solves the system using already known solution (result contains the dict <symbol: value>). solver is `solveset_complex` or `solveset_real`. """ # stores imageset <expr: imageset(Lambda(n, expr), base)>. soln_imageset = {} total_solvest_call = 0 total_conditionst = 0 # sort such that equation with the fewest potential symbols is first. # means eq with less variable first for index, eq in enumerate(eqs_in_better_order): newresult = [] original_imageset = {} # if imageset expr is used to solve other symbol imgset_yes = False result = _new_order_result(result, eq) for res in result: got_symbol = set() # symbols solved in one iteration if soln_imageset: # find the imageset and use its expr. for key_res, value_res in res.items(): if isinstance(value_res, ImageSet): res[key_res] = value_res.lamda.expr original_imageset[key_res] = value_res dummy_n = value_res.lamda.expr.atoms(Dummy).pop() (base,) = value_res.base_sets imgset_yes = (dummy_n, base) # update eq with everything that is known so far eq2 = eq.subs(res).expand() unsolved_syms = _unsolved_syms(eq2, sort=True) if not unsolved_syms: if res: newresult, delete_res = _append_new_soln( res, None, None, imgset_yes, soln_imageset, original_imageset, newresult, eq2) if delete_res: # `delete_res` is true, means substituting `res` in # eq2 doesn't return `zero` or deleting the `res` # (a soln) since it staisfies expr of `exclude` # list. result.remove(res) continue # skip as it's independent of desired symbols depen1, depen2 = (eq2.rewrite(Add)).as_independent(*unsolved_syms) if (depen1.has(Abs) or depen2.has(Abs)) and solver == solveset_complex: # Absolute values cannot be inverted in the # complex domain continue soln_imageset = {} for sym in unsolved_syms: not_solvable = False try: soln = solver(eq2, sym) total_solvest_call += 1 soln_new = S.EmptySet if isinstance(soln, Complement): # separate solution and complement complements[sym] = soln.args[1] soln = soln.args[0] # complement will be added at the end if isinstance(soln, Intersection): # Interval will be at 0th index always if soln.args[0] != Interval(-oo, oo): # sometimes solveset returns soln # with intersection S.Reals, to confirm that # soln is in domain=S.Reals intersections[sym] = soln.args[0] soln_new += soln.args[1] soln = soln_new if soln_new else soln if index > 0 and solver == solveset_real: # one symbol's real soln , another symbol may have # corresponding complex soln. if not isinstance(soln, (ImageSet, ConditionSet)): soln += solveset_complex(eq2, sym) except NotImplementedError: # If sovleset is not able to solve equation `eq2`. Next # time we may get soln using next equation `eq2` continue if isinstance(soln, ConditionSet): soln = S.EmptySet # don't do `continue` we may get soln # in terms of other symbol(s) not_solvable = True total_conditionst += 1 if soln is not S.EmptySet: soln, soln_imageset = _extract_main_soln( sym, soln, soln_imageset) for sol in soln: # sol is not a `Union` since we checked it # before this loop sol, soln_imageset = _extract_main_soln( sym, sol, soln_imageset) sol = set(sol).pop() free = sol.free_symbols if got_symbol and any([ ss in free for ss in got_symbol ]): # sol depends on previously solved symbols # then continue continue rnew = res.copy() # put each solution in res and append the new result # in the new result list (solution for symbol `s`) # along with old results. for k, v in res.items(): if isinstance(v, Expr): # if any unsolved symbol is present # Then subs known value rnew[k] = v.subs(sym, sol) # and add this new solution if soln_imageset: # replace all lambda variables with 0. imgst = soln_imageset[sol] rnew[sym] = imgst.lamda( *[0 for i in range(0, len( imgst.lamda.variables))]) else: rnew[sym] = sol newresult, delete_res = _append_new_soln( rnew, sym, sol, imgset_yes, soln_imageset, original_imageset, newresult) if delete_res: # deleting the `res` (a soln) since it staisfies # eq of `exclude` list result.remove(res) # solution got for sym if not not_solvable: got_symbol.add(sym) # next time use this new soln if newresult: result = newresult return result, total_solvest_call, total_conditionst # end def _solve_using_know_values() new_result_real, solve_call1, cnd_call1 = _solve_using_known_values( old_result, solveset_real) new_result_complex, solve_call2, cnd_call2 = _solve_using_known_values( old_result, solveset_complex) # when `total_solveset_call` is equals to `total_conditionset` # means solvest fails to solve all the eq. # return conditionset in this case total_conditionset += (cnd_call1 + cnd_call2) total_solveset_call += (solve_call1 + solve_call2) if total_conditionset == total_solveset_call and total_solveset_call != -1: return _return_conditionset(eqs_in_better_order, all_symbols) # overall result result = new_result_real + new_result_complex result_all_variables = [] result_infinite = [] for res in result: if not res: # means {None : None} continue # If length < len(all_symbols) means infinite soln. # Some or all the soln is dependent on 1 symbol. # eg. {x: y+2} then final soln {x: y+2, y: y} if len(res) < len(all_symbols): solved_symbols = res.keys() unsolved = list(filter( lambda x: x not in solved_symbols, all_symbols)) for unsolved_sym in unsolved: res[unsolved_sym] = unsolved_sym result_infinite.append(res) if res not in result_all_variables: result_all_variables.append(res) if result_infinite: # we have general soln # eg : [{x: -1, y : 1}, {x : -y , y: y}] then # return [{x : -y, y : y}] result_all_variables = result_infinite if intersections or complements: result_all_variables = add_intersection_complement( result_all_variables, intersections, complements) # convert to ordered tuple result = S.EmptySet for r in result_all_variables: temp = [r[symb] for symb in all_symbols] result += FiniteSet(tuple(temp)) return result # end of def substitution() def _solveset_work(system, symbols): soln = solveset(system[0], symbols[0]) if isinstance(soln, FiniteSet): _soln = FiniteSet(*[tuple((s,)) for s in soln]) return _soln else: return FiniteSet(tuple(FiniteSet(soln))) def _handle_positive_dimensional(polys, symbols, denominators): from sympy.polys.polytools import groebner # substitution method where new system is groebner basis of the system _symbols = list(symbols) _symbols.sort(key=default_sort_key) basis = groebner(polys, _symbols, polys=True) new_system = [] for poly_eq in basis: new_system.append(poly_eq.as_expr()) result = [{}] result = substitution( new_system, symbols, result, [], denominators) return result # end of def _handle_positive_dimensional() def _handle_zero_dimensional(polys, symbols, system): # solve 0 dimensional poly system using `solve_poly_system` result = solve_poly_system(polys, *symbols) # May be some extra soln is added because # we used `unrad` in `_separate_poly_nonpoly`, so # need to check and remove if it is not a soln. result_update = S.EmptySet for res in result: dict_sym_value = dict(list(zip(symbols, res))) if all(checksol(eq, dict_sym_value) for eq in system): result_update += FiniteSet(res) return result_update # end of def _handle_zero_dimensional() def _separate_poly_nonpoly(system, symbols): polys = [] polys_expr = [] nonpolys = [] denominators = set() poly = None for eq in system: # Store denom expression if it contains symbol denominators.update(_simple_dens(eq, symbols)) # try to remove sqrt and rational power without_radicals = unrad(simplify(eq)) if without_radicals: eq_unrad, cov = without_radicals if not cov: eq = eq_unrad if isinstance(eq, Expr): eq = eq.as_numer_denom()[0] poly = eq.as_poly(*symbols, extension=True) elif simplify(eq).is_number: continue if poly is not None: polys.append(poly) polys_expr.append(poly.as_expr()) else: nonpolys.append(eq) return polys, polys_expr, nonpolys, denominators # end of def _separate_poly_nonpoly() def nonlinsolve(system, *symbols): r""" Solve system of N nonlinear equations with M variables, which means both under and overdetermined systems are supported. Positive dimensional system is also supported (A system with infinitely many solutions is said to be positive-dimensional). In Positive dimensional system solution will be dependent on at least one symbol. Returns both real solution and complex solution(If system have). The possible number of solutions is zero, one or infinite. Parameters ========== system : list of equations The target system of equations symbols : list of Symbols symbols should be given as a sequence eg. list Returns ======= A FiniteSet of ordered tuple of values of `symbols` for which the `system` has solution. Order of values in the tuple is same as symbols present in the parameter `symbols`. Please note that general FiniteSet is unordered, the solution returned here is not simply a FiniteSet of solutions, rather it is a FiniteSet of ordered tuple, i.e. the first & only argument to FiniteSet is a tuple of solutions, which is ordered, & hence the returned solution is ordered. Also note that solution could also have been returned as an ordered tuple, FiniteSet is just a wrapper `{}` around the tuple. It has no other significance except for the fact it is just used to maintain a consistent output format throughout the solveset. For the given set of Equations, the respective input types are given below: .. math:: x*y - 1 = 0 .. math:: 4*x**2 + y**2 - 5 = 0 `system = [x*y - 1, 4*x**2 + y**2 - 5]` `symbols = [x, y]` Raises ====== ValueError The input is not valid. The symbols are not given. AttributeError The input symbols are not `Symbol` type. Examples ======== >>> from sympy.core.symbol import symbols >>> from sympy.solvers.solveset import nonlinsolve >>> x, y, z = symbols('x, y, z', real=True) >>> nonlinsolve([x*y - 1, 4*x**2 + y**2 - 5], [x, y]) FiniteSet((-1, -1), (-1/2, -2), (1/2, 2), (1, 1)) 1. Positive dimensional system and complements: >>> from sympy import pprint >>> from sympy.polys.polytools import is_zero_dimensional >>> a, b, c, d = symbols('a, b, c, d', extended_real=True) >>> eq1 = a + b + c + d >>> eq2 = a*b + b*c + c*d + d*a >>> eq3 = a*b*c + b*c*d + c*d*a + d*a*b >>> eq4 = a*b*c*d - 1 >>> system = [eq1, eq2, eq3, eq4] >>> is_zero_dimensional(system) False >>> pprint(nonlinsolve(system, [a, b, c, d]), use_unicode=False) -1 1 1 -1 {(---, -d, -, {d} \ {0}), (-, -d, ---, {d} \ {0})} d d d d >>> nonlinsolve([(x+y)**2 - 4, x + y - 2], [x, y]) FiniteSet((2 - y, y)) 2. If some of the equations are non-polynomial then `nonlinsolve` will call the `substitution` function and return real and complex solutions, if present. >>> from sympy import exp, sin >>> nonlinsolve([exp(x) - sin(y), y**2 - 4], [x, y]) FiniteSet((ImageSet(Lambda(_n, 2*_n*I*pi + log(sin(2))), Integers), 2), (ImageSet(Lambda(_n, I*(2*_n*pi + pi) + log(sin(2))), Integers), -2)) 3. If system is non-linear polynomial and zero-dimensional then it returns both solution (real and complex solutions, if present) using `solve_poly_system`: >>> from sympy import sqrt >>> nonlinsolve([x**2 - 2*y**2 -2, x*y - 2], [x, y]) FiniteSet((-2, -1), (2, 1), (-sqrt(2)*I, sqrt(2)*I), (sqrt(2)*I, -sqrt(2)*I)) 4. `nonlinsolve` can solve some linear (zero or positive dimensional) system (because it uses the `groebner` function to get the groebner basis and then uses the `substitution` function basis as the new `system`). But it is not recommended to solve linear system using `nonlinsolve`, because `linsolve` is better for general linear systems. >>> nonlinsolve([x + 2*y -z - 3, x - y - 4*z + 9 , y + z - 4], [x, y, z]) FiniteSet((3*z - 5, 4 - z, z)) 5. System having polynomial equations and only real solution is solved using `solve_poly_system`: >>> e1 = sqrt(x**2 + y**2) - 10 >>> e2 = sqrt(y**2 + (-x + 10)**2) - 3 >>> nonlinsolve((e1, e2), (x, y)) FiniteSet((191/20, -3*sqrt(391)/20), (191/20, 3*sqrt(391)/20)) >>> nonlinsolve([x**2 + 2/y - 2, x + y - 3], [x, y]) FiniteSet((1, 2), (1 - sqrt(5), 2 + sqrt(5)), (1 + sqrt(5), 2 - sqrt(5))) >>> nonlinsolve([x**2 + 2/y - 2, x + y - 3], [y, x]) FiniteSet((2, 1), (2 - sqrt(5), 1 + sqrt(5)), (2 + sqrt(5), 1 - sqrt(5))) 6. It is better to use symbols instead of Trigonometric Function or Function (e.g. replace `sin(x)` with symbol, replace `f(x)` with symbol and so on. Get soln from `nonlinsolve` and then using `solveset` get the value of `x`) How nonlinsolve is better than old solver `_solve_system` : =========================================================== 1. A positive dimensional system solver : nonlinsolve can return solution for positive dimensional system. It finds the Groebner Basis of the positive dimensional system(calling it as basis) then we can start solving equation(having least number of variable first in the basis) using solveset and substituting that solved solutions into other equation(of basis) to get solution in terms of minimum variables. Here the important thing is how we are substituting the known values and in which equations. 2. Real and Complex both solutions : nonlinsolve returns both real and complex solution. If all the equations in the system are polynomial then using `solve_poly_system` both real and complex solution is returned. If all the equations in the system are not polynomial equation then goes to `substitution` method with this polynomial and non polynomial equation(s), to solve for unsolved variables. Here to solve for particular variable solveset_real and solveset_complex is used. For both real and complex solution function `_solve_using_know_values` is used inside `substitution` function.(`substitution` function will be called when there is any non polynomial equation(s) is present). When solution is valid then add its general solution in the final result. 3. Complement and Intersection will be added if any : nonlinsolve maintains dict for complements and Intersections. If solveset find complements or/and Intersection with any Interval or set during the execution of `substitution` function ,then complement or/and Intersection for that variable is added before returning final solution. """ from sympy.polys.polytools import is_zero_dimensional if not system: return S.EmptySet if not symbols: msg = ('Symbols must be given, for which solution of the ' 'system is to be found.') raise ValueError(filldedent(msg)) if hasattr(symbols[0], '__iter__'): symbols = symbols[0] if not is_sequence(symbols) or not symbols: msg = ('Symbols must be given, for which solution of the ' 'system is to be found.') raise IndexError(filldedent(msg)) system, symbols, swap = recast_to_symbols(system, symbols) if swap: soln = nonlinsolve(system, symbols) return FiniteSet(*[tuple(i.xreplace(swap) for i in s) for s in soln]) if len(system) == 1 and len(symbols) == 1: return _solveset_work(system, symbols) # main code of def nonlinsolve() starts from here polys, polys_expr, nonpolys, denominators = _separate_poly_nonpoly( system, symbols) if len(symbols) == len(polys): # If all the equations in the system are poly if is_zero_dimensional(polys, symbols): # finite number of soln (Zero dimensional system) try: return _handle_zero_dimensional(polys, symbols, system) except NotImplementedError: # Right now it doesn't fail for any polynomial system of # equation. If `solve_poly_system` fails then `substitution` # method will handle it. result = substitution( polys_expr, symbols, exclude=denominators) return result # positive dimensional system res = _handle_positive_dimensional(polys, symbols, denominators) if res is EmptySet and any(not p.domain.is_Exact for p in polys): raise NotImplementedError("Equation not in exact domain. Try converting to rational") else: return res else: # If all the equations are not polynomial. # Use `substitution` method for the system result = substitution( polys_expr + nonpolys, symbols, exclude=denominators) return result
e4b126e81f1724bc11c2584aa0a77b293c958d529b3214f32dfac79f9c90e5b9
""" Python code printers This module contains python code printers for plain python as well as NumPy & SciPy enabled code. """ from collections import defaultdict from itertools import chain from sympy.core import S from .precedence import precedence from .codeprinter import CodePrinter _kw_py2and3 = { 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield', 'None' # 'None' is actually not in Python 2's keyword.kwlist } _kw_only_py2 = {'exec', 'print'} _kw_only_py3 = {'False', 'nonlocal', 'True'} _known_functions = { 'Abs': 'abs', } _known_functions_math = { 'acos': 'acos', 'acosh': 'acosh', 'asin': 'asin', 'asinh': 'asinh', 'atan': 'atan', 'atan2': 'atan2', 'atanh': 'atanh', 'ceiling': 'ceil', 'cos': 'cos', 'cosh': 'cosh', 'erf': 'erf', 'erfc': 'erfc', 'exp': 'exp', 'expm1': 'expm1', 'factorial': 'factorial', 'floor': 'floor', 'gamma': 'gamma', 'hypot': 'hypot', 'loggamma': 'lgamma', 'log': 'log', 'ln': 'log', 'log10': 'log10', 'log1p': 'log1p', 'log2': 'log2', 'sin': 'sin', 'sinh': 'sinh', 'Sqrt': 'sqrt', 'tan': 'tan', 'tanh': 'tanh' } # Not used from ``math``: [copysign isclose isfinite isinf isnan ldexp frexp pow modf # radians trunc fmod fsum gcd degrees fabs] _known_constants_math = { 'Exp1': 'e', 'Pi': 'pi', 'E': 'e' # Only in python >= 3.5: # 'Infinity': 'inf', # 'NaN': 'nan' } def _print_known_func(self, expr): known = self.known_functions[expr.__class__.__name__] return '{name}({args})'.format(name=self._module_format(known), args=', '.join(map(lambda arg: self._print(arg), expr.args))) def _print_known_const(self, expr): known = self.known_constants[expr.__class__.__name__] return self._module_format(known) class AbstractPythonCodePrinter(CodePrinter): printmethod = "_pythoncode" language = "Python" reserved_words = _kw_py2and3.union(_kw_only_py3) modules = None # initialized to a set in __init__ tab = ' ' _kf = dict(chain( _known_functions.items(), [(k, 'math.' + v) for k, v in _known_functions_math.items()] )) _kc = {k: 'math.'+v for k, v in _known_constants_math.items()} _operators = {'and': 'and', 'or': 'or', 'not': 'not'} _default_settings = dict( CodePrinter._default_settings, user_functions={}, precision=17, inline=True, fully_qualified_modules=True, contract=False, standard='python3', ) def __init__(self, settings=None): super(AbstractPythonCodePrinter, self).__init__(settings) # Python standard handler std = self._settings['standard'] if std is None: import sys std = 'python{}'.format(sys.version_info.major) if std not in ('python2', 'python3'): raise ValueError('Unrecognized python standard : {}'.format(std)) self.standard = std self.module_imports = defaultdict(set) # Known functions and constants handler self.known_functions = dict(self._kf, **(settings or {}).get( 'user_functions', {})) self.known_constants = dict(self._kc, **(settings or {}).get( 'user_constants', {})) def _declare_number_const(self, name, value): return "%s = %s" % (name, value) def _module_format(self, fqn, register=True): parts = fqn.split('.') if register and len(parts) > 1: self.module_imports['.'.join(parts[:-1])].add(parts[-1]) if self._settings['fully_qualified_modules']: return fqn else: return fqn.split('(')[0].split('[')[0].split('.')[-1] def _format_code(self, lines): return lines def _get_statement(self, codestring): return "{}".format(codestring) def _get_comment(self, text): return " # {0}".format(text) def _expand_fold_binary_op(self, op, args): """ This method expands a fold on binary operations. ``functools.reduce`` is an example of a folded operation. For example, the expression `A + B + C + D` is folded into `((A + B) + C) + D` """ if len(args) == 1: return self._print(args[0]) else: return "%s(%s, %s)" % ( self._module_format(op), self._expand_fold_binary_op(op, args[:-1]), self._print(args[-1]), ) def _expand_reduce_binary_op(self, op, args): """ This method expands a reductin on binary operations. Notice: this is NOT the same as ``functools.reduce``. For example, the expression `A + B + C + D` is reduced into: `(A + B) + (C + D)` """ if len(args) == 1: return self._print(args[0]) else: N = len(args) Nhalf = N // 2 return "%s(%s, %s)" % ( self._module_format(op), self._expand_reduce_binary_op(args[:Nhalf]), self._expand_reduce_binary_op(args[Nhalf:]), ) def _get_einsum_string(self, subranks, contraction_indices): letters = self._get_letter_generator_for_einsum() contraction_string = "" counter = 0 d = {j: min(i) for i in contraction_indices for j in i} indices = [] for rank_arg in subranks: lindices = [] for i in range(rank_arg): if counter in d: lindices.append(d[counter]) else: lindices.append(counter) counter += 1 indices.append(lindices) mapping = {} letters_free = [] letters_dum = [] for i in indices: for j in i: if j not in mapping: l = next(letters) mapping[j] = l else: l = mapping[j] contraction_string += l if j in d: if l not in letters_dum: letters_dum.append(l) else: letters_free.append(l) contraction_string += "," contraction_string = contraction_string[:-1] return contraction_string, letters_free, letters_dum def _print_NaN(self, expr): return "float('nan')" def _print_Infinity(self, expr): return "float('inf')" def _print_NegativeInfinity(self, expr): return "float('-inf')" def _print_ComplexInfinity(self, expr): return self._print_NaN(expr) def _print_Mod(self, expr): PREC = precedence(expr) return ('{0} % {1}'.format(*map(lambda x: self.parenthesize(x, PREC), expr.args))) def _print_Piecewise(self, expr): result = [] i = 0 for arg in expr.args: e = arg.expr c = arg.cond if i == 0: result.append('(') result.append('(') result.append(self._print(e)) result.append(')') result.append(' if ') result.append(self._print(c)) result.append(' else ') i += 1 result = result[:-1] if result[-1] == 'True': result = result[:-2] result.append(')') else: result.append(' else None)') return ''.join(result) def _print_Relational(self, expr): "Relational printer for Equality and Unequality" op = { '==' :'equal', '!=' :'not_equal', '<' :'less', '<=' :'less_equal', '>' :'greater', '>=' :'greater_equal', } if expr.rel_op in op: lhs = self._print(expr.lhs) rhs = self._print(expr.rhs) return '({lhs} {op} {rhs})'.format(op=expr.rel_op, lhs=lhs, rhs=rhs) return super(AbstractPythonCodePrinter, self)._print_Relational(expr) def _print_ITE(self, expr): from sympy.functions.elementary.piecewise import Piecewise return self._print(expr.rewrite(Piecewise)) def _print_Sum(self, expr): loops = ( 'for {i} in range({a}, {b}+1)'.format( i=self._print(i), a=self._print(a), b=self._print(b)) for i, a, b in expr.limits) return '(builtins.sum({function} {loops}))'.format( function=self._print(expr.function), loops=' '.join(loops)) def _print_ImaginaryUnit(self, expr): return '1j' def _print_KroneckerDelta(self, expr): a, b = expr.args return '(1 if {a} == {b} else 0)'.format( a = self._print(a), b = self._print(b) ) def _print_MatrixBase(self, expr): name = expr.__class__.__name__ func = self.known_functions.get(name, name) return "%s(%s)" % (func, self._print(expr.tolist())) _print_SparseMatrix = \ _print_MutableSparseMatrix = \ _print_ImmutableSparseMatrix = \ _print_Matrix = \ _print_DenseMatrix = \ _print_MutableDenseMatrix = \ _print_ImmutableMatrix = \ _print_ImmutableDenseMatrix = \ lambda self, expr: self._print_MatrixBase(expr) def _indent_codestring(self, codestring): return '\n'.join([self.tab + line for line in codestring.split('\n')]) def _print_FunctionDefinition(self, fd): body = '\n'.join(map(lambda arg: self._print(arg), fd.body)) return "def {name}({parameters}):\n{body}".format( name=self._print(fd.name), parameters=', '.join([self._print(var.symbol) for var in fd.parameters]), body=self._indent_codestring(body) ) def _print_While(self, whl): body = '\n'.join(map(lambda arg: self._print(arg), whl.body)) return "while {cond}:\n{body}".format( cond=self._print(whl.condition), body=self._indent_codestring(body) ) def _print_Declaration(self, decl): return '%s = %s' % ( self._print(decl.variable.symbol), self._print(decl.variable.value) ) def _print_Return(self, ret): arg, = ret.args return 'return %s' % self._print(arg) def _print_Print(self, prnt): print_args = ', '.join(map(lambda arg: self._print(arg), prnt.print_args)) if prnt.format_string != None: # Must be '!= None', cannot be 'is not None' print_args = '{0} % ({1})'.format( self._print(prnt.format_string), print_args) if prnt.file != None: # Must be '!= None', cannot be 'is not None' print_args += ', file=%s' % self._print(prnt.file) if self.standard == 'python2': return 'print %s' % print_args return 'print(%s)' % print_args def _print_Stream(self, strm): if str(strm.name) == 'stdout': return self._module_format('sys.stdout') elif str(strm.name) == 'stderr': return self._module_format('sys.stderr') else: return self._print(strm.name) def _print_NoneToken(self, arg): return 'None' def _hprint_Pow(self, expr, rational=False, sqrt='math.sqrt'): """Printing helper function for ``Pow`` Notes ===== This only preprocesses the ``sqrt`` as math formatter Examples ======== >>> from sympy.functions import sqrt >>> from sympy.printing.pycode import PythonCodePrinter >>> from sympy.abc import x Python code printer automatically looks up ``math.sqrt``. >>> printer = PythonCodePrinter({'standard':'python3'}) >>> printer._hprint_Pow(sqrt(x), rational=True) 'x**(1/2)' >>> printer._hprint_Pow(sqrt(x), rational=False) 'math.sqrt(x)' >>> printer._hprint_Pow(1/sqrt(x), rational=True) 'x**(-1/2)' >>> printer._hprint_Pow(1/sqrt(x), rational=False) '1/math.sqrt(x)' Using sqrt from numpy or mpmath >>> printer._hprint_Pow(sqrt(x), sqrt='numpy.sqrt') 'numpy.sqrt(x)' >>> printer._hprint_Pow(sqrt(x), sqrt='mpmath.sqrt') 'mpmath.sqrt(x)' See Also ======== sympy.printing.str.StrPrinter._print_Pow """ PREC = precedence(expr) if expr.exp == S.Half and not rational: func = self._module_format(sqrt) arg = self._print(expr.base) return '{func}({arg})'.format(func=func, arg=arg) if expr.is_commutative: if -expr.exp is S.Half and not rational: func = self._module_format(sqrt) num = self._print(S.One) arg = self._print(expr.base) return "{num}/{func}({arg})".format( num=num, func=func, arg=arg) base_str = self.parenthesize(expr.base, PREC, strict=False) exp_str = self.parenthesize(expr.exp, PREC, strict=False) return "{}**{}".format(base_str, exp_str) class PythonCodePrinter(AbstractPythonCodePrinter): def _print_sign(self, e): return '(0.0 if {e} == 0 else {f}(1, {e}))'.format( f=self._module_format('math.copysign'), e=self._print(e.args[0])) def _print_Not(self, expr): PREC = precedence(expr) return self._operators['not'] + self.parenthesize(expr.args[0], PREC) def _print_Indexed(self, expr): base = expr.args[0] index = expr.args[1:] return "{}[{}]".format(str(base), ", ".join([self._print(ind) for ind in index])) def _print_Pow(self, expr, rational=False): return self._hprint_Pow(expr, rational=rational) def _print_Rational(self, expr): if self.standard == 'python2': return '{}./{}.'.format(expr.p, expr.q) return '{}/{}'.format(expr.p, expr.q) def _print_Half(self, expr): return self._print_Rational(expr) def _print_frac(self, expr): from sympy import Mod return self._print_Mod(Mod(expr.args[0], 1)) _print_lowergamma = CodePrinter._print_not_supported _print_uppergamma = CodePrinter._print_not_supported _print_fresnelc = CodePrinter._print_not_supported _print_fresnels = CodePrinter._print_not_supported for k in PythonCodePrinter._kf: setattr(PythonCodePrinter, '_print_%s' % k, _print_known_func) for k in _known_constants_math: setattr(PythonCodePrinter, '_print_%s' % k, _print_known_const) def pycode(expr, **settings): """ Converts an expr to a string of Python code Parameters ========== expr : Expr A SymPy expression. fully_qualified_modules : bool Whether or not to write out full module names of functions (``math.sin`` vs. ``sin``). default: ``True``. standard : str or None, optional If 'python2', Python 2 sematics will be used. If 'python3', Python 3 sematics will be used. If None, the standard will be automatically detected. Default is 'python3'. And this parameter may be removed in the future. Examples ======== >>> from sympy import tan, Symbol >>> from sympy.printing.pycode import pycode >>> pycode(tan(Symbol('x')) + 1) 'math.tan(x) + 1' """ return PythonCodePrinter(settings).doprint(expr) _not_in_mpmath = 'log1p log2'.split() _in_mpmath = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_mpmath] _known_functions_mpmath = dict(_in_mpmath, **{ 'beta': 'beta', 'frac': 'frac', 'fresnelc': 'fresnelc', 'fresnels': 'fresnels', 'sign': 'sign', 'loggamma': 'loggamma', }) _known_constants_mpmath = { 'Exp1': 'e', 'Pi': 'pi', 'GoldenRatio': 'phi', 'EulerGamma': 'euler', 'Catalan': 'catalan', 'NaN': 'nan', 'Infinity': 'inf', 'NegativeInfinity': 'ninf' } def _unpack_integral_limits(integral_expr): """ helper function for _print_Integral that - accepts an Integral expression - returns a tuple of - a list variables of integration - a list of tuples of the upper and lower limits of integration """ integration_vars = [] limits = [] for integration_range in integral_expr.limits: if len(integration_range) == 3: integration_var, lower_limit, upper_limit = integration_range else: raise NotImplementedError("Only definite integrals are supported") integration_vars.append(integration_var) limits.append((lower_limit, upper_limit)) return integration_vars, limits class MpmathPrinter(PythonCodePrinter): """ Lambda printer for mpmath which maintains precision for floats """ printmethod = "_mpmathcode" language = "Python with mpmath" _kf = dict(chain( _known_functions.items(), [(k, 'mpmath.' + v) for k, v in _known_functions_mpmath.items()] )) _kc = {k: 'mpmath.'+v for k, v in _known_constants_mpmath.items()} def _print_Float(self, e): # XXX: This does not handle setting mpmath.mp.dps. It is assumed that # the caller of the lambdified function will have set it to sufficient # precision to match the Floats in the expression. # Remove 'mpz' if gmpy is installed. args = str(tuple(map(int, e._mpf_))) return '{func}({args})'.format(func=self._module_format('mpmath.mpf'), args=args) def _print_Rational(self, e): return "{func}({p})/{func}({q})".format( func=self._module_format('mpmath.mpf'), q=self._print(e.q), p=self._print(e.p) ) def _print_Half(self, e): return self._print_Rational(e) def _print_uppergamma(self, e): return "{0}({1}, {2}, {3})".format( self._module_format('mpmath.gammainc'), self._print(e.args[0]), self._print(e.args[1]), self._module_format('mpmath.inf')) def _print_lowergamma(self, e): return "{0}({1}, 0, {2})".format( self._module_format('mpmath.gammainc'), self._print(e.args[0]), self._print(e.args[1])) def _print_log2(self, e): return '{0}({1})/{0}(2)'.format( self._module_format('mpmath.log'), self._print(e.args[0])) def _print_log1p(self, e): return '{0}({1}+1)'.format( self._module_format('mpmath.log'), self._print(e.args[0])) def _print_Pow(self, expr, rational=False): return self._hprint_Pow(expr, rational=rational, sqrt='mpmath.sqrt') def _print_Integral(self, e): integration_vars, limits = _unpack_integral_limits(e) return "{0}(lambda {1}: {2}, {3})".format( self._module_format("mpmath.quad"), ", ".join(map(self._print, integration_vars)), self._print(e.args[0]), ", ".join("(%s, %s)" % tuple(map(self._print, l)) for l in limits)) for k in MpmathPrinter._kf: setattr(MpmathPrinter, '_print_%s' % k, _print_known_func) for k in _known_constants_mpmath: setattr(MpmathPrinter, '_print_%s' % k, _print_known_const) _not_in_numpy = 'erf erfc factorial gamma loggamma'.split() _in_numpy = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_numpy] _known_functions_numpy = dict(_in_numpy, **{ 'acos': 'arccos', 'acosh': 'arccosh', 'asin': 'arcsin', 'asinh': 'arcsinh', 'atan': 'arctan', 'atan2': 'arctan2', 'atanh': 'arctanh', 'exp2': 'exp2', 'sign': 'sign', 'logaddexp': 'logaddexp', 'logaddexp2': 'logaddexp2', }) _known_constants_numpy = { 'Exp1': 'e', 'Pi': 'pi', 'EulerGamma': 'euler_gamma', 'NaN': 'nan', 'Infinity': 'PINF', 'NegativeInfinity': 'NINF' } class NumPyPrinter(PythonCodePrinter): """ Numpy printer which handles vectorized piecewise functions, logical operators, etc. """ printmethod = "_numpycode" language = "Python with NumPy" _kf = dict(chain( PythonCodePrinter._kf.items(), [(k, 'numpy.' + v) for k, v in _known_functions_numpy.items()] )) _kc = {k: 'numpy.'+v for k, v in _known_constants_numpy.items()} def _print_seq(self, seq): "General sequence printer: converts to tuple" # Print tuples here instead of lists because numba supports # tuples in nopython mode. delimiter=', ' return '({},)'.format(delimiter.join(self._print(item) for item in seq)) def _print_MatMul(self, expr): "Matrix multiplication printer" if expr.as_coeff_matrices()[0] is not S.One: expr_list = expr.as_coeff_matrices()[1]+[(expr.as_coeff_matrices()[0])] return '({0})'.format(').dot('.join(self._print(i) for i in expr_list)) return '({0})'.format(').dot('.join(self._print(i) for i in expr.args)) def _print_MatPow(self, expr): "Matrix power printer" return '{0}({1}, {2})'.format(self._module_format('numpy.linalg.matrix_power'), self._print(expr.args[0]), self._print(expr.args[1])) def _print_Inverse(self, expr): "Matrix inverse printer" return '{0}({1})'.format(self._module_format('numpy.linalg.inv'), self._print(expr.args[0])) def _print_DotProduct(self, expr): # DotProduct allows any shape order, but numpy.dot does matrix # multiplication, so we have to make sure it gets 1 x n by n x 1. arg1, arg2 = expr.args if arg1.shape[0] != 1: arg1 = arg1.T if arg2.shape[1] != 1: arg2 = arg2.T return "%s(%s, %s)" % (self._module_format('numpy.dot'), self._print(arg1), self._print(arg2)) def _print_MatrixSolve(self, expr): return "%s(%s, %s)" % (self._module_format('numpy.linalg.solve'), self._print(expr.matrix), self._print(expr.vector)) def _print_ZeroMatrix(self, expr): return '{}({})'.format(self._module_format('numpy.zeros'), self._print(expr.shape)) def _print_OneMatrix(self, expr): return '{}({})'.format(self._module_format('numpy.ones'), self._print(expr.shape)) def _print_FunctionMatrix(self, expr): from sympy.core.function import Lambda from sympy.abc import i, j lamda = expr.lamda if not isinstance(lamda, Lambda): lamda = Lambda((i, j), lamda(i, j)) return '{}(lambda {}: {}, {})'.format(self._module_format('numpy.fromfunction'), ', '.join(self._print(arg) for arg in lamda.args[0]), self._print(lamda.args[1]), self._print(expr.shape)) def _print_HadamardProduct(self, expr): func = self._module_format('numpy.multiply') return ''.join('{}({}, '.format(func, self._print(arg)) \ for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]), ')' * (len(expr.args) - 1)) def _print_KroneckerProduct(self, expr): func = self._module_format('numpy.kron') return ''.join('{}({}, '.format(func, self._print(arg)) \ for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]), ')' * (len(expr.args) - 1)) def _print_Adjoint(self, expr): return '{}({}({}))'.format( self._module_format('numpy.conjugate'), self._module_format('numpy.transpose'), self._print(expr.args[0])) def _print_DiagonalOf(self, expr): vect = '{}({})'.format( self._module_format('numpy.diag'), self._print(expr.arg)) return '{}({}, (-1, 1))'.format( self._module_format('numpy.reshape'), vect) def _print_DiagMatrix(self, expr): return '{}({})'.format(self._module_format('numpy.diagflat'), self._print(expr.args[0])) def _print_DiagonalMatrix(self, expr): return '{}({}, {}({}, {}))'.format(self._module_format('numpy.multiply'), self._print(expr.arg), self._module_format('numpy.eye'), self._print(expr.shape[0]), self._print(expr.shape[1])) def _print_Piecewise(self, expr): "Piecewise function printer" exprs = '[{0}]'.format(','.join(self._print(arg.expr) for arg in expr.args)) conds = '[{0}]'.format(','.join(self._print(arg.cond) for arg in expr.args)) # If [default_value, True] is a (expr, cond) sequence in a Piecewise object # it will behave the same as passing the 'default' kwarg to select() # *as long as* it is the last element in expr.args. # If this is not the case, it may be triggered prematurely. return '{0}({1}, {2}, default={3})'.format( self._module_format('numpy.select'), conds, exprs, self._print(S.NaN)) def _print_Relational(self, expr): "Relational printer for Equality and Unequality" op = { '==' :'equal', '!=' :'not_equal', '<' :'less', '<=' :'less_equal', '>' :'greater', '>=' :'greater_equal', } if expr.rel_op in op: lhs = self._print(expr.lhs) rhs = self._print(expr.rhs) return '{op}({lhs}, {rhs})'.format(op=self._module_format('numpy.'+op[expr.rel_op]), lhs=lhs, rhs=rhs) return super(NumPyPrinter, self)._print_Relational(expr) def _print_And(self, expr): "Logical And printer" # We have to override LambdaPrinter because it uses Python 'and' keyword. # If LambdaPrinter didn't define it, we could use StrPrinter's # version of the function and add 'logical_and' to NUMPY_TRANSLATIONS. return '{0}.reduce(({1}))'.format(self._module_format('numpy.logical_and'), ','.join(self._print(i) for i in expr.args)) def _print_Or(self, expr): "Logical Or printer" # We have to override LambdaPrinter because it uses Python 'or' keyword. # If LambdaPrinter didn't define it, we could use StrPrinter's # version of the function and add 'logical_or' to NUMPY_TRANSLATIONS. return '{0}.reduce(({1}))'.format(self._module_format('numpy.logical_or'), ','.join(self._print(i) for i in expr.args)) def _print_Not(self, expr): "Logical Not printer" # We have to override LambdaPrinter because it uses Python 'not' keyword. # If LambdaPrinter didn't define it, we would still have to define our # own because StrPrinter doesn't define it. return '{0}({1})'.format(self._module_format('numpy.logical_not'), ','.join(self._print(i) for i in expr.args)) def _print_Pow(self, expr, rational=False): # XXX Workaround for negative integer power error from sympy.core.power import Pow if expr.exp.is_integer and expr.exp.is_negative: expr = Pow(expr.base, expr.exp.evalf(), evaluate=False) return self._hprint_Pow(expr, rational=rational, sqrt='numpy.sqrt') def _print_Min(self, expr): return '{0}(({1}), axis=0)'.format(self._module_format('numpy.amin'), ','.join(self._print(i) for i in expr.args)) def _print_Max(self, expr): return '{0}(({1}), axis=0)'.format(self._module_format('numpy.amax'), ','.join(self._print(i) for i in expr.args)) def _print_arg(self, expr): return "%s(%s)" % (self._module_format('numpy.angle'), self._print(expr.args[0])) def _print_im(self, expr): return "%s(%s)" % (self._module_format('numpy.imag'), self._print(expr.args[0])) def _print_Mod(self, expr): return "%s(%s)" % (self._module_format('numpy.mod'), ', '.join( map(lambda arg: self._print(arg), expr.args))) def _print_re(self, expr): return "%s(%s)" % (self._module_format('numpy.real'), self._print(expr.args[0])) def _print_sinc(self, expr): return "%s(%s)" % (self._module_format('numpy.sinc'), self._print(expr.args[0]/S.Pi)) def _print_MatrixBase(self, expr): func = self.known_functions.get(expr.__class__.__name__, None) if func is None: func = self._module_format('numpy.array') return "%s(%s)" % (func, self._print(expr.tolist())) def _print_Identity(self, expr): shape = expr.shape if all([dim.is_Integer for dim in shape]): return "%s(%s)" % (self._module_format('numpy.eye'), self._print(expr.shape[0])) else: raise NotImplementedError("Symbolic matrix dimensions are not yet supported for identity matrices") def _print_BlockMatrix(self, expr): return '{0}({1})'.format(self._module_format('numpy.block'), self._print(expr.args[0].tolist())) def _print_CodegenArrayTensorProduct(self, expr): array_list = [j for i, arg in enumerate(expr.args) for j in (self._print(arg), "[%i, %i]" % (2*i, 2*i+1))] return "%s(%s)" % (self._module_format('numpy.einsum'), ", ".join(array_list)) def _print_CodegenArrayContraction(self, expr): from sympy.codegen.array_utils import CodegenArrayTensorProduct base = expr.expr contraction_indices = expr.contraction_indices if not contraction_indices: return self._print(base) if isinstance(base, CodegenArrayTensorProduct): counter = 0 d = {j: min(i) for i in contraction_indices for j in i} indices = [] for rank_arg in base.subranks: lindices = [] for i in range(rank_arg): if counter in d: lindices.append(d[counter]) else: lindices.append(counter) counter += 1 indices.append(lindices) elems = ["%s, %s" % (self._print(arg), ind) for arg, ind in zip(base.args, indices)] return "%s(%s)" % ( self._module_format('numpy.einsum'), ", ".join(elems) ) raise NotImplementedError() def _print_CodegenArrayDiagonal(self, expr): diagonal_indices = list(expr.diagonal_indices) if len(diagonal_indices) > 1: # TODO: this should be handled in sympy.codegen.array_utils, # possibly by creating the possibility of unfolding the # CodegenArrayDiagonal object into nested ones. Same reasoning for # the array contraction. raise NotImplementedError if len(diagonal_indices[0]) != 2: raise NotImplementedError return "%s(%s, 0, axis1=%s, axis2=%s)" % ( self._module_format("numpy.diagonal"), self._print(expr.expr), diagonal_indices[0][0], diagonal_indices[0][1], ) def _print_CodegenArrayPermuteDims(self, expr): return "%s(%s, %s)" % ( self._module_format("numpy.transpose"), self._print(expr.expr), self._print(expr.permutation.array_form), ) def _print_CodegenArrayElementwiseAdd(self, expr): return self._expand_fold_binary_op('numpy.add', expr.args) _print_lowergamma = CodePrinter._print_not_supported _print_uppergamma = CodePrinter._print_not_supported _print_fresnelc = CodePrinter._print_not_supported _print_fresnels = CodePrinter._print_not_supported for k in NumPyPrinter._kf: setattr(NumPyPrinter, '_print_%s' % k, _print_known_func) for k in NumPyPrinter._kc: setattr(NumPyPrinter, '_print_%s' % k, _print_known_const) _known_functions_scipy_special = { 'erf': 'erf', 'erfc': 'erfc', 'besselj': 'jv', 'bessely': 'yv', 'besseli': 'iv', 'besselk': 'kv', 'cosm1': 'cosm1', 'factorial': 'factorial', 'gamma': 'gamma', 'loggamma': 'gammaln', 'digamma': 'psi', 'RisingFactorial': 'poch', 'jacobi': 'eval_jacobi', 'gegenbauer': 'eval_gegenbauer', 'chebyshevt': 'eval_chebyt', 'chebyshevu': 'eval_chebyu', 'legendre': 'eval_legendre', 'hermite': 'eval_hermite', 'laguerre': 'eval_laguerre', 'assoc_laguerre': 'eval_genlaguerre', 'beta': 'beta', 'LambertW' : 'lambertw', } _known_constants_scipy_constants = { 'GoldenRatio': 'golden_ratio', 'Pi': 'pi', } class SciPyPrinter(NumPyPrinter): language = "Python with SciPy" _kf = dict(chain( NumPyPrinter._kf.items(), [(k, 'scipy.special.' + v) for k, v in _known_functions_scipy_special.items()] )) _kc =dict(chain( NumPyPrinter._kc.items(), [(k, 'scipy.constants.' + v) for k, v in _known_constants_scipy_constants.items()] )) def _print_SparseMatrix(self, expr): i, j, data = [], [], [] for (r, c), v in expr._smat.items(): i.append(r) j.append(c) data.append(v) return "{name}(({data}, ({i}, {j})), shape={shape})".format( name=self._module_format('scipy.sparse.coo_matrix'), data=data, i=i, j=j, shape=expr.shape ) _print_ImmutableSparseMatrix = _print_SparseMatrix # SciPy's lpmv has a different order of arguments from assoc_legendre def _print_assoc_legendre(self, expr): return "{0}({2}, {1}, {3})".format( self._module_format('scipy.special.lpmv'), self._print(expr.args[0]), self._print(expr.args[1]), self._print(expr.args[2])) def _print_lowergamma(self, expr): return "{0}({2})*{1}({2}, {3})".format( self._module_format('scipy.special.gamma'), self._module_format('scipy.special.gammainc'), self._print(expr.args[0]), self._print(expr.args[1])) def _print_uppergamma(self, expr): return "{0}({2})*{1}({2}, {3})".format( self._module_format('scipy.special.gamma'), self._module_format('scipy.special.gammaincc'), self._print(expr.args[0]), self._print(expr.args[1])) def _print_fresnels(self, expr): return "{0}({1})[0]".format( self._module_format("scipy.special.fresnel"), self._print(expr.args[0])) def _print_fresnelc(self, expr): return "{0}({1})[1]".format( self._module_format("scipy.special.fresnel"), self._print(expr.args[0])) def _print_airyai(self, expr): return "{0}({1})[0]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_airyaiprime(self, expr): return "{0}({1})[1]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_airybi(self, expr): return "{0}({1})[2]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_airybiprime(self, expr): return "{0}({1})[3]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_Integral(self, e): integration_vars, limits = _unpack_integral_limits(e) if len(limits) == 1: # nicer (but not necessary) to prefer quad over nquad for 1D case module_str = self._module_format("scipy.integrate.quad") limit_str = "%s, %s" % tuple(map(self._print, limits[0])) else: module_str = self._module_format("scipy.integrate.nquad") limit_str = "({})".format(", ".join( "(%s, %s)" % tuple(map(self._print, l)) for l in limits)) return "{0}(lambda {1}: {2}, {3})[0]".format( module_str, ", ".join(map(self._print, integration_vars)), self._print(e.args[0]), limit_str) for k in SciPyPrinter._kf: setattr(SciPyPrinter, '_print_%s' % k, _print_known_func) for k in SciPyPrinter._kc: setattr(SciPyPrinter, '_print_%s' % k, _print_known_const) class SymPyPrinter(AbstractPythonCodePrinter): language = "Python with SymPy" def _print_Function(self, expr): mod = expr.func.__module__ or '' return '%s(%s)' % (self._module_format(mod + ('.' if mod else '') + expr.func.__name__), ', '.join(map(lambda arg: self._print(arg), expr.args))) def _print_Pow(self, expr, rational=False): return self._hprint_Pow(expr, rational=rational, sqrt='sympy.sqrt')
851fd902c29dc4c10e464b642801ab80a222f173d1eccac2fcfeaf0b95666472
""" A Printer for generating readable representation of most sympy classes. """ from typing import Any, Dict from sympy.core import S, Rational, Pow, Basic, Mul, Number from sympy.core.mul import _keep_coeff from .printer import Printer, print_function from sympy.printing.precedence import precedence, PRECEDENCE from mpmath.libmp import prec_to_dps, to_str as mlib_to_str from sympy.utilities import default_sort_key class StrPrinter(Printer): printmethod = "_sympystr" _default_settings = { "order": None, "full_prec": "auto", "sympy_integers": False, "abbrev": False, "perm_cyclic": True, "min": None, "max": None, } # type: Dict[str, Any] _relationals = dict() # type: Dict[str, str] def parenthesize(self, item, level, strict=False): if (precedence(item) < level) or ((not strict) and precedence(item) <= level): return "(%s)" % self._print(item) else: return self._print(item) def stringify(self, args, sep, level=0): return sep.join([self.parenthesize(item, level) for item in args]) def emptyPrinter(self, expr): if isinstance(expr, str): return expr elif isinstance(expr, Basic): return repr(expr) else: return str(expr) def _print_Add(self, expr, order=None): terms = self._as_ordered_terms(expr, order=order) PREC = precedence(expr) l = [] for term in terms: t = self._print(term) if t.startswith('-'): sign = "-" t = t[1:] else: sign = "+" if precedence(term) < PREC: l.extend([sign, "(%s)" % t]) else: l.extend([sign, t]) sign = l.pop(0) if sign == '+': sign = "" return sign + ' '.join(l) def _print_BooleanTrue(self, expr): return "True" def _print_BooleanFalse(self, expr): return "False" def _print_Not(self, expr): return '~%s' %(self.parenthesize(expr.args[0],PRECEDENCE["Not"])) def _print_And(self, expr): return self.stringify(expr.args, " & ", PRECEDENCE["BitwiseAnd"]) def _print_Or(self, expr): return self.stringify(expr.args, " | ", PRECEDENCE["BitwiseOr"]) def _print_Xor(self, expr): return self.stringify(expr.args, " ^ ", PRECEDENCE["BitwiseXor"]) def _print_AppliedPredicate(self, expr): return '%s(%s)' % (self._print(expr.func), self._print(expr.arg)) def _print_Basic(self, expr): l = [self._print(o) for o in expr.args] return expr.__class__.__name__ + "(%s)" % ", ".join(l) def _print_BlockMatrix(self, B): if B.blocks.shape == (1, 1): self._print(B.blocks[0, 0]) return self._print(B.blocks) def _print_Catalan(self, expr): return 'Catalan' def _print_ComplexInfinity(self, expr): return 'zoo' def _print_ConditionSet(self, s): args = tuple([self._print(i) for i in (s.sym, s.condition)]) if s.base_set is S.UniversalSet: return 'ConditionSet(%s, %s)' % args args += (self._print(s.base_set),) return 'ConditionSet(%s, %s, %s)' % args def _print_Derivative(self, expr): dexpr = expr.expr dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count] return 'Derivative(%s)' % ", ".join(map(lambda arg: self._print(arg), [dexpr] + dvars)) def _print_dict(self, d): keys = sorted(d.keys(), key=default_sort_key) items = [] for key in keys: item = "%s: %s" % (self._print(key), self._print(d[key])) items.append(item) return "{%s}" % ", ".join(items) def _print_Dict(self, expr): return self._print_dict(expr) def _print_RandomDomain(self, d): if hasattr(d, 'as_boolean'): return 'Domain: ' + self._print(d.as_boolean()) elif hasattr(d, 'set'): return ('Domain: ' + self._print(d.symbols) + ' in ' + self._print(d.set)) else: return 'Domain on ' + self._print(d.symbols) def _print_Dummy(self, expr): return '_' + expr.name def _print_EulerGamma(self, expr): return 'EulerGamma' def _print_Exp1(self, expr): return 'E' def _print_ExprCondPair(self, expr): return '(%s, %s)' % (self._print(expr.expr), self._print(expr.cond)) def _print_Function(self, expr): return expr.func.__name__ + "(%s)" % self.stringify(expr.args, ", ") def _print_GoldenRatio(self, expr): return 'GoldenRatio' def _print_TribonacciConstant(self, expr): return 'TribonacciConstant' def _print_ImaginaryUnit(self, expr): return 'I' def _print_Infinity(self, expr): return 'oo' def _print_Integral(self, expr): def _xab_tostr(xab): if len(xab) == 1: return self._print(xab[0]) else: return self._print((xab[0],) + tuple(xab[1:])) L = ', '.join([_xab_tostr(l) for l in expr.limits]) return 'Integral(%s, %s)' % (self._print(expr.function), L) def _print_Interval(self, i): fin = 'Interval{m}({a}, {b})' a, b, l, r = i.args if a.is_infinite and b.is_infinite: m = '' elif a.is_infinite and not r: m = '' elif b.is_infinite and not l: m = '' elif not l and not r: m = '' elif l and r: m = '.open' elif l: m = '.Lopen' else: m = '.Ropen' return fin.format(**{'a': a, 'b': b, 'm': m}) def _print_AccumulationBounds(self, i): return "AccumBounds(%s, %s)" % (self._print(i.min), self._print(i.max)) def _print_Inverse(self, I): return "%s**(-1)" % self.parenthesize(I.arg, PRECEDENCE["Pow"]) def _print_Lambda(self, obj): expr = obj.expr sig = obj.signature if len(sig) == 1 and sig[0].is_symbol: sig = sig[0] return "Lambda(%s, %s)" % (self._print(sig), self._print(expr)) def _print_LatticeOp(self, expr): args = sorted(expr.args, key=default_sort_key) return expr.func.__name__ + "(%s)" % ", ".join(self._print(arg) for arg in args) def _print_Limit(self, expr): e, z, z0, dir = expr.args if str(dir) == "+": return "Limit(%s, %s, %s)" % tuple(map(self._print, (e, z, z0))) else: return "Limit(%s, %s, %s, dir='%s')" % tuple(map(self._print, (e, z, z0, dir))) def _print_list(self, expr): return "[%s]" % self.stringify(expr, ", ") def _print_MatrixBase(self, expr): return expr._format_str(self) def _print_MatrixElement(self, expr): return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \ + '[%s, %s]' % (self._print(expr.i), self._print(expr.j)) def _print_MatrixSlice(self, expr): def strslice(x, dim): x = list(x) if x[2] == 1: del x[2] if x[0] == 0: x[0] = '' if x[1] == dim: x[1] = '' return ':'.join(map(lambda arg: self._print(arg), x)) return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + '[' + strslice(expr.rowslice, expr.parent.rows) + ', ' + strslice(expr.colslice, expr.parent.cols) + ']') def _print_DeferredVector(self, expr): return expr.name def _print_Mul(self, expr): prec = precedence(expr) # Check for unevaluated Mul. In this case we need to make sure the # identities are visible, multiple Rational factors are not combined # etc so we display in a straight-forward form that fully preserves all # args and their order. args = expr.args if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]): factors = [self.parenthesize(a, prec, strict=False) for a in args] return '*'.join(factors) c, e = expr.as_coeff_Mul() if c < 0: expr = _keep_coeff(-c, e) sign = "-" else: sign = "" a = [] # items in the numerator b = [] # items that are in the denominator (if any) pow_paren = [] # Will collect all pow with more than one base element and exp = -1 if self.order not in ('old', 'none'): args = expr.as_ordered_factors() else: # use make_args in case expr was something like -x -> x args = Mul.make_args(expr) # Gather args for numerator/denominator 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: if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160 pow_paren.append(item) 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) a = a or [S.One] a_str = [self.parenthesize(x, prec, strict=False) for x in a] b_str = [self.parenthesize(x, prec, strict=False) for x in b] # To parenthesize Pow with exp = -1 and having more than one Symbol for item in pow_paren: if item.base in b: b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)] if not b: return sign + '*'.join(a_str) elif len(b) == 1: return sign + '*'.join(a_str) + "/" + b_str[0] else: return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str) def _print_MatMul(self, expr): c, m = expr.as_coeff_mmul() sign = "" if c.is_number: re, im = c.as_real_imag() if im.is_zero and re.is_negative: expr = _keep_coeff(-c, m) sign = "-" elif re.is_zero and im.is_negative: expr = _keep_coeff(-c, m) sign = "-" return sign + '*'.join( [self.parenthesize(arg, precedence(expr)) for arg in expr.args] ) def _print_ElementwiseApplyFunction(self, expr): return "{0}.({1})".format( expr.function, self._print(expr.expr), ) def _print_NaN(self, expr): return 'nan' def _print_NegativeInfinity(self, expr): return '-oo' def _print_Order(self, expr): if not expr.variables or all(p is S.Zero for p in expr.point): if len(expr.variables) <= 1: return 'O(%s)' % self._print(expr.expr) else: return 'O(%s)' % self.stringify((expr.expr,) + expr.variables, ', ', 0) else: return 'O(%s)' % self.stringify(expr.args, ', ', 0) def _print_Ordinal(self, expr): return expr.__str__() def _print_Cycle(self, expr): return expr.__str__() def _print_Permutation(self, expr): from sympy.combinatorics.permutations import Permutation, Cycle from sympy.utilities.exceptions import SymPyDeprecationWarning perm_cyclic = Permutation.print_cyclic if perm_cyclic is not None: SymPyDeprecationWarning( feature="Permutation.print_cyclic = {}".format(perm_cyclic), useinstead="init_printing(perm_cyclic={})" .format(perm_cyclic), issue=15201, deprecated_since_version="1.6").warn() else: perm_cyclic = self._settings.get("perm_cyclic", True) if perm_cyclic: if not expr.size: return '()' # before taking Cycle notation, see if the last element is # a singleton and move it to the head of the string s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):] last = s.rfind('(') if not last == 0 and ',' not in s[last:]: s = s[last:] + s[:last] s = s.replace(',', '') return s else: s = expr.support() if not s: if expr.size < 5: return 'Permutation(%s)' % self._print(expr.array_form) return 'Permutation([], size=%s)' % self._print(expr.size) trim = self._print(expr.array_form[:s[-1] + 1]) + ', size=%s' % self._print(expr.size) use = full = self._print(expr.array_form) if len(trim) < len(full): use = trim return 'Permutation(%s)' % use def _print_Subs(self, obj): expr, old, new = obj.args if len(obj.point) == 1: old = old[0] new = new[0] return "Subs(%s, %s, %s)" % ( self._print(expr), self._print(old), self._print(new)) def _print_TensorIndex(self, expr): return expr._print() def _print_TensorHead(self, expr): return expr._print() def _print_Tensor(self, expr): return expr._print() def _print_TensMul(self, expr): # prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)" sign, args = expr._get_args_for_traditional_printer() return sign + "*".join( [self.parenthesize(arg, precedence(expr)) for arg in args] ) def _print_TensAdd(self, expr): return expr._print() def _print_PermutationGroup(self, expr): p = [' %s' % self._print(a) for a in expr.args] return 'PermutationGroup([\n%s])' % ',\n'.join(p) def _print_Pi(self, expr): return 'pi' def _print_PolyRing(self, ring): return "Polynomial ring in %s over %s with %s order" % \ (", ".join(map(lambda rs: self._print(rs), ring.symbols)), self._print(ring.domain), self._print(ring.order)) def _print_FracField(self, field): return "Rational function field in %s over %s with %s order" % \ (", ".join(map(lambda fs: self._print(fs), field.symbols)), self._print(field.domain), self._print(field.order)) def _print_FreeGroupElement(self, elm): return elm.__str__() def _print_GaussianElement(self, poly): return "(%s + %s*I)" % (poly.x, poly.y) def _print_PolyElement(self, poly): return poly.str(self, PRECEDENCE, "%s**%s", "*") def _print_FracElement(self, frac): if frac.denom == 1: return self._print(frac.numer) else: numer = self.parenthesize(frac.numer, PRECEDENCE["Mul"], strict=True) denom = self.parenthesize(frac.denom, PRECEDENCE["Atom"], strict=True) return numer + "/" + denom def _print_Poly(self, expr): ATOM_PREC = PRECEDENCE["Atom"] - 1 terms, gens = [], [ self.parenthesize(s, ATOM_PREC) for s in expr.gens ] for monom, coeff in expr.terms(): s_monom = [] for i, exp in enumerate(monom): if exp > 0: if exp == 1: s_monom.append(gens[i]) else: s_monom.append(gens[i] + "**%d" % exp) s_monom = "*".join(s_monom) if coeff.is_Add: if s_monom: s_coeff = "(" + self._print(coeff) + ")" else: s_coeff = self._print(coeff) else: if s_monom: if coeff is S.One: terms.extend(['+', s_monom]) continue if coeff is S.NegativeOne: terms.extend(['-', s_monom]) continue s_coeff = self._print(coeff) if not s_monom: s_term = s_coeff else: s_term = s_coeff + "*" + s_monom if s_term.startswith('-'): terms.extend(['-', s_term[1:]]) else: terms.extend(['+', s_term]) if terms[0] in ['-', '+']: modifier = terms.pop(0) if modifier == '-': terms[0] = '-' + terms[0] format = expr.__class__.__name__ + "(%s, %s" from sympy.polys.polyerrors import PolynomialError try: format += ", modulus=%s" % expr.get_modulus() except PolynomialError: format += ", domain='%s'" % expr.get_domain() format += ")" for index, item in enumerate(gens): if len(item) > 2 and (item[:1] == "(" and item[len(item) - 1:] == ")"): gens[index] = item[1:len(item) - 1] return format % (' '.join(terms), ', '.join(gens)) def _print_UniversalSet(self, p): return 'UniversalSet' def _print_AlgebraicNumber(self, expr): if expr.is_aliased: return self._print(expr.as_poly().as_expr()) else: return self._print(expr.as_expr()) def _print_Pow(self, expr, rational=False): """Printing helper function for ``Pow`` Parameters ========== rational : bool, optional If ``True``, it will not attempt printing ``sqrt(x)`` or ``x**S.Half`` as ``sqrt``, and will use ``x**(1/2)`` instead. See examples for additional details Examples ======== >>> from sympy.functions import sqrt >>> from sympy.printing.str import StrPrinter >>> from sympy.abc import x How ``rational`` keyword works with ``sqrt``: >>> printer = StrPrinter() >>> printer._print_Pow(sqrt(x), rational=True) 'x**(1/2)' >>> printer._print_Pow(sqrt(x), rational=False) 'sqrt(x)' >>> printer._print_Pow(1/sqrt(x), rational=True) 'x**(-1/2)' >>> printer._print_Pow(1/sqrt(x), rational=False) '1/sqrt(x)' Notes ===== ``sqrt(x)`` is canonicalized as ``Pow(x, S.Half)`` in SymPy, so there is no need of defining a separate printer for ``sqrt``. Instead, it should be handled here as well. """ PREC = precedence(expr) if expr.exp is S.Half and not rational: return "sqrt(%s)" % self._print(expr.base) if expr.is_commutative: if -expr.exp is S.Half and not rational: # Note: Don't test "expr.exp == -S.Half" here, because that will # match -0.5, which we don't want. return "%s/sqrt(%s)" % tuple(map(lambda arg: self._print(arg), (S.One, expr.base))) if expr.exp is -S.One: # Similarly to the S.Half case, don't test with "==" here. return '%s/%s' % (self._print(S.One), self.parenthesize(expr.base, PREC, strict=False)) e = self.parenthesize(expr.exp, PREC, strict=False) if self.printmethod == '_sympyrepr' and expr.exp.is_Rational and expr.exp.q != 1: # the parenthesized exp should be '(Rational(a, b))' so strip parens, # but just check to be sure. if e.startswith('(Rational'): return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e[1:-1]) return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e) def _print_UnevaluatedExpr(self, expr): return self._print(expr.args[0]) def _print_MatPow(self, expr): PREC = precedence(expr) return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), self.parenthesize(expr.exp, PREC, strict=False)) def _print_Integer(self, expr): if self._settings.get("sympy_integers", False): return "S(%s)" % (expr) return str(expr.p) def _print_Integers(self, expr): return 'Integers' def _print_Naturals(self, expr): return 'Naturals' def _print_Naturals0(self, expr): return 'Naturals0' def _print_Rationals(self, expr): return 'Rationals' def _print_Reals(self, expr): return 'Reals' def _print_Complexes(self, expr): return 'Complexes' def _print_EmptySet(self, expr): return 'EmptySet' def _print_EmptySequence(self, expr): return 'EmptySequence' def _print_int(self, expr): return str(expr) def _print_mpz(self, expr): return str(expr) def _print_Rational(self, expr): if expr.q == 1: return str(expr.p) else: if self._settings.get("sympy_integers", False): return "S(%s)/%s" % (expr.p, expr.q) return "%s/%s" % (expr.p, expr.q) def _print_PythonRational(self, expr): if expr.q == 1: return str(expr.p) else: return "%d/%d" % (expr.p, expr.q) def _print_Fraction(self, expr): if expr.denominator == 1: return str(expr.numerator) else: return "%s/%s" % (expr.numerator, expr.denominator) def _print_mpq(self, expr): if expr.denominator == 1: return str(expr.numerator) else: return "%s/%s" % (expr.numerator, expr.denominator) def _print_Float(self, expr): prec = expr._prec if prec < 5: dps = 0 else: dps = prec_to_dps(expr._prec) if self._settings["full_prec"] is True: strip = False elif self._settings["full_prec"] is False: strip = True elif self._settings["full_prec"] == "auto": strip = self._print_level > 1 low = self._settings["min"] if "min" in self._settings else None high = self._settings["max"] if "max" in self._settings else None rv = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high) if rv.startswith('-.0'): rv = '-0.' + rv[3:] elif rv.startswith('.0'): rv = '0.' + rv[2:] if rv.startswith('+'): # e.g., +inf -> inf rv = rv[1:] return rv def _print_Relational(self, expr): charmap = { "==": "Eq", "!=": "Ne", ":=": "Assignment", '+=': "AddAugmentedAssignment", "-=": "SubAugmentedAssignment", "*=": "MulAugmentedAssignment", "/=": "DivAugmentedAssignment", "%=": "ModAugmentedAssignment", } if expr.rel_op in charmap: return '%s(%s, %s)' % (charmap[expr.rel_op], self._print(expr.lhs), self._print(expr.rhs)) return '%s %s %s' % (self.parenthesize(expr.lhs, precedence(expr)), self._relationals.get(expr.rel_op) or expr.rel_op, self.parenthesize(expr.rhs, precedence(expr))) def _print_ComplexRootOf(self, expr): return "CRootOf(%s, %d)" % (self._print_Add(expr.expr, order='lex'), expr.index) def _print_RootSum(self, expr): args = [self._print_Add(expr.expr, order='lex')] if expr.fun is not S.IdentityFunction: args.append(self._print(expr.fun)) return "RootSum(%s)" % ", ".join(args) def _print_GroebnerBasis(self, basis): cls = basis.__class__.__name__ exprs = [self._print_Add(arg, order=basis.order) for arg in basis.exprs] exprs = "[%s]" % ", ".join(exprs) gens = [ self._print(gen) for gen in basis.gens ] domain = "domain='%s'" % self._print(basis.domain) order = "order='%s'" % self._print(basis.order) args = [exprs] + gens + [domain, order] return "%s(%s)" % (cls, ", ".join(args)) def _print_set(self, s): items = sorted(s, key=default_sort_key) args = ', '.join(self._print(item) for item in items) if not args: return "set()" return '{%s}' % args def _print_frozenset(self, s): if not s: return "frozenset()" return "frozenset(%s)" % self._print_set(s) def _print_Sum(self, expr): def _xab_tostr(xab): if len(xab) == 1: return self._print(xab[0]) else: return self._print((xab[0],) + tuple(xab[1:])) L = ', '.join([_xab_tostr(l) for l in expr.limits]) return 'Sum(%s, %s)' % (self._print(expr.function), L) def _print_Symbol(self, expr): return expr.name _print_MatrixSymbol = _print_Symbol _print_RandomSymbol = _print_Symbol def _print_Identity(self, expr): return "I" def _print_ZeroMatrix(self, expr): return "0" def _print_OneMatrix(self, expr): return "1" def _print_Predicate(self, expr): return "Q.%s" % expr.name def _print_str(self, expr): return str(expr) def _print_tuple(self, expr): if len(expr) == 1: return "(%s,)" % self._print(expr[0]) else: return "(%s)" % self.stringify(expr, ", ") def _print_Tuple(self, expr): return self._print_tuple(expr) def _print_Transpose(self, T): return "%s.T" % self.parenthesize(T.arg, PRECEDENCE["Pow"]) def _print_Uniform(self, expr): return "Uniform(%s, %s)" % (self._print(expr.a), self._print(expr.b)) def _print_Quantity(self, expr): if self._settings.get("abbrev", False): return "%s" % expr.abbrev return "%s" % expr.name def _print_Quaternion(self, expr): s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True) for i in expr.args] a = [s[0]] + [i+"*"+j for i, j in zip(s[1:], "ijk")] return " + ".join(a) def _print_Dimension(self, expr): return str(expr) def _print_Wild(self, expr): return expr.name + '_' def _print_WildFunction(self, expr): return expr.name + '_' def _print_Zero(self, expr): if self._settings.get("sympy_integers", False): return "S(0)" return "0" def _print_DMP(self, p): from sympy.core.sympify import SympifyError try: if p.ring is not None: # TODO incorporate order return self._print(p.ring.to_sympy(p)) except SympifyError: pass cls = p.__class__.__name__ rep = self._print(p.rep) dom = self._print(p.dom) ring = self._print(p.ring) return "%s(%s, %s, %s)" % (cls, rep, dom, ring) def _print_DMF(self, expr): return self._print_DMP(expr) def _print_Object(self, obj): return 'Object("%s")' % obj.name def _print_IdentityMorphism(self, morphism): return 'IdentityMorphism(%s)' % morphism.domain def _print_NamedMorphism(self, morphism): return 'NamedMorphism(%s, %s, "%s")' % \ (morphism.domain, morphism.codomain, morphism.name) def _print_Category(self, category): return 'Category("%s")' % category.name def _print_Manifold(self, manifold): return manifold.name.name def _print_Patch(self, patch): return patch.name.name def _print_CoordSystem(self, coords): return coords.name.name def _print_BaseScalarField(self, field): return field._coord_sys.symbols[field._index].name def _print_BaseVectorField(self, field): return 'e_%s' % field._coord_sys.symbols[field._index].name def _print_Differential(self, diff): field = diff._form_field if hasattr(field, '_coord_sys'): return 'd%s' % field._coord_sys.symbols[field._index].name else: return 'd(%s)' % self._print(field) def _print_Tr(self, expr): #TODO : Handle indices return "%s(%s)" % ("Tr", self._print(expr.args[0])) def _print_Str(self, s): return self._print(s.name) @print_function(StrPrinter) def sstr(expr, **settings): """Returns the expression as a string. For large expressions where speed is a concern, use the setting order='none'. If abbrev=True setting is used then units are printed in abbreviated form. Examples ======== >>> from sympy import symbols, Eq, sstr >>> a, b = symbols('a b') >>> sstr(Eq(a + b, 0)) 'Eq(a + b, 0)' """ p = StrPrinter(settings) s = p.doprint(expr) return s class StrReprPrinter(StrPrinter): """(internal) -- see sstrrepr""" def _print_str(self, s): return repr(s) def _print_Str(self, s): # Str does not to be printed same as str here return "%s(%s)" % (s.__class__.__name__, self._print(s.name)) @print_function(StrReprPrinter) def sstrrepr(expr, **settings): """return expr in mixed str/repr form i.e. strings are returned in repr form with quotes, and everything else is returned in str form. This function could be useful for hooking into sys.displayhook """ p = StrReprPrinter(settings) s = p.doprint(expr) return s
c4538a7f7fee38316a5ccf6e3e469d291b40649fa37ece5e5025de06333441bd
"""Printing subsystem driver SymPy's printing system works the following way: Any expression can be passed to a designated Printer who then is responsible to return an adequate representation of that expression. **The basic concept is the following:** 1. Let the object print itself if it knows how. 2. Take the best fitting method defined in the printer. 3. As fall-back use the emptyPrinter method for the printer. Which Method is Responsible for Printing? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The whole printing process is started by calling ``.doprint(expr)`` on the printer which you want to use. This method looks for an appropriate method which can print the given expression in the given style that the printer defines. While looking for the method, it follows these steps: 1. **Let the object print itself if it knows how.** The printer looks for a specific method in every object. The name of that method depends on the specific printer and is defined under ``Printer.printmethod``. For example, StrPrinter calls ``_sympystr`` and LatexPrinter calls ``_latex``. Look at the documentation of the printer that you want to use. The name of the method is specified there. This was the original way of doing printing in sympy. Every class had its own latex, mathml, str and repr methods, but it turned out that it is hard to produce a high quality printer, if all the methods are spread out that far. Therefore all printing code was combined into the different printers, which works great for built-in sympy objects, but not that good for user defined classes where it is inconvenient to patch the printers. 2. **Take the best fitting method defined in the printer.** The printer loops through expr classes (class + its bases), and tries to dispatch the work to ``_print_<EXPR_CLASS>`` e.g., suppose we have the following class hierarchy:: Basic | Atom | Number | Rational then, for ``expr=Rational(...)``, the Printer will try to call printer methods in the order as shown in the figure below:: p._print(expr) | |-- p._print_Rational(expr) | |-- p._print_Number(expr) | |-- p._print_Atom(expr) | `-- p._print_Basic(expr) if ``._print_Rational`` method exists in the printer, then it is called, and the result is returned back. Otherwise, the printer tries to call ``._print_Number`` and so on. 3. **As a fall-back use the emptyPrinter method for the printer.** As fall-back ``self.emptyPrinter`` will be called with the expression. If not defined in the Printer subclass this will be the same as ``str(expr)``. .. _printer_example: Example of Custom Printer ^^^^^^^^^^^^^^^^^^^^^^^^^ In the example below, we have a printer which prints the derivative of a function in a shorter form. .. code-block:: python from sympy import Symbol from sympy.printing.latex import LatexPrinter, print_latex from sympy.core.function import UndefinedFunction, Function class MyLatexPrinter(LatexPrinter): \"\"\"Print derivative of a function of symbols in a shorter form. \"\"\" def _print_Derivative(self, expr): function, *vars = expr.args if not isinstance(type(function), UndefinedFunction) or \\ not all(isinstance(i, Symbol) for i in vars): return super()._print_Derivative(expr) # If you want the printer to work correctly for nested # expressions then use self._print() instead of str() or latex(). # See the example of nested modulo below in the custom printing # method section. return "{}_{{{}}}".format( self._print(Symbol(function.func.__name__)), ''.join(self._print(i) for i in vars)) def print_my_latex(expr): \"\"\" Most of the printers define their own wrappers for print(). These wrappers usually take printer settings. Our printer does not have any settings. \"\"\" print(MyLatexPrinter().doprint(expr)) y = Symbol("y") x = Symbol("x") f = Function("f") expr = f(x, y).diff(x, y) # Print the expression using the normal latex printer and our custom # printer. print_latex(expr) print_my_latex(expr) The output of the code above is:: \\frac{\\partial^{2}}{\\partial x\\partial y} f{\\left(x,y \\right)} f_{xy} .. _printer_method_example: Example of Custom Printing Method ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In the example below, the latex printing of the modulo operator is modified. This is done by overriding the method ``_latex`` of ``Mod``. >>> from sympy import Symbol, Mod, Integer >>> from sympy.printing.latex import print_latex >>> # Always use printer._print() >>> class ModOp(Mod): ... def _latex(self, printer): ... a, b = [printer._print(i) for i in self.args] ... return r"\\operatorname{Mod}{\\left( %s,%s \\right)}" % (a,b) Comparing the output of our custom operator to the builtin one: >>> x = Symbol('x') >>> m = Symbol('m') >>> print_latex(Mod(x, m)) x\\bmod{m} >>> print_latex(ModOp(x, m)) \\operatorname{Mod}{\\left( x,m \\right)} Common mistakes ~~~~~~~~~~~~~~~ It's important to always use ``self._print(obj)`` to print subcomponents of an expression when customizing a printer. Mistakes include: 1. Using ``self.doprint(obj)`` instead: >>> # This example does not work properly, as only the outermost call may use >>> # doprint. >>> class ModOpModeWrong(Mod): ... def _latex(self, printer): ... a, b = [printer.doprint(i) for i in self.args] ... return r"\\operatorname{Mod}{\\left( %s,%s \\right)}" % (a,b) This fails when the `mode` argument is passed to the printer: >>> print_latex(ModOp(x, m), mode='inline') # ok $\\operatorname{Mod}{\\left( x,m \\right)}$ >>> print_latex(ModOpModeWrong(x, m), mode='inline') # bad $\\operatorname{Mod}{\\left( $x$,$m$ \\right)}$ 2. Using ``str(obj)`` instead: >>> class ModOpNestedWrong(Mod): ... def _latex(self, printer): ... a, b = [str(i) for i in self.args] ... return r"\\operatorname{Mod}{\\left( %s,%s \\right)}" % (a,b) This fails on nested objects: >>> # Nested modulo. >>> print_latex(ModOp(ModOp(x, m), Integer(7))) # ok \\operatorname{Mod}{\\left( \\operatorname{Mod}{\\left( x,m \\right)},7 \\right)} >>> print_latex(ModOpNestedWrong(ModOpNestedWrong(x, m), Integer(7))) # bad \\operatorname{Mod}{\\left( ModOpNestedWrong(x, m),7 \\right)} 3. Using ``LatexPrinter()._print(obj)`` instead. >>> from sympy.printing.latex import LatexPrinter >>> class ModOpSettingsWrong(Mod): ... def _latex(self, printer): ... a, b = [LatexPrinter()._print(i) for i in self.args] ... return r"\\operatorname{Mod}{\\left( %s,%s \\right)}" % (a,b) This causes all the settings to be discarded in the subobjects. As an example, the ``full_prec`` setting which shows floats to full precision is ignored: >>> from sympy import Float >>> print_latex(ModOp(Float(1) * x, m), full_prec=True) # ok \\operatorname{Mod}{\\left( 1.00000000000000 x,m \\right)} >>> print_latex(ModOpSettingsWrong(Float(1) * x, m), full_prec=True) # bad \\operatorname{Mod}{\\left( 1.0 x,m \\right)} """ from typing import Any, Dict, Type import inspect from contextlib import contextmanager from functools import cmp_to_key, update_wrapper from sympy import Basic, Add from sympy.core.core import BasicMeta from sympy.core.function import AppliedUndef, UndefinedFunction, Function @contextmanager def printer_context(printer, **kwargs): original = printer._context.copy() try: printer._context.update(kwargs) yield finally: printer._context = original class Printer(object): """ Generic printer Its job is to provide infrastructure for implementing new printers easily. If you want to define your custom Printer or your custom printing method for your custom class then see the example above: printer_example_ . """ _global_settings = {} # type: Dict[str, Any] _default_settings = {} # type: Dict[str, Any] printmethod = None # type: str @classmethod def _get_initial_settings(cls): settings = cls._default_settings.copy() for key, val in cls._global_settings.items(): if key in cls._default_settings: settings[key] = val return settings def __init__(self, settings=None): self._str = str self._settings = self._get_initial_settings() self._context = dict() # mutable during printing if settings is not None: self._settings.update(settings) if len(self._settings) > len(self._default_settings): for key in self._settings: if key not in self._default_settings: raise TypeError("Unknown setting '%s'." % key) # _print_level is the number of times self._print() was recursively # called. See StrPrinter._print_Float() for an example of usage self._print_level = 0 @classmethod def set_global_settings(cls, **settings): """Set system-wide printing settings. """ for key, val in settings.items(): if val is not None: cls._global_settings[key] = val @property def order(self): if 'order' in self._settings: return self._settings['order'] else: raise AttributeError("No order defined.") def doprint(self, expr): """Returns printer's representation for expr (as a string)""" return self._str(self._print(expr)) def _print(self, expr, **kwargs): """Internal dispatcher Tries the following concepts to print an expression: 1. Let the object print itself if it knows how. 2. Take the best fitting method defined in the printer. 3. As fall-back use the emptyPrinter method for the printer. """ self._print_level += 1 try: # If the printer defines a name for a printing method # (Printer.printmethod) and the object knows for itself how it # should be printed, use that method. if (self.printmethod and hasattr(expr, self.printmethod) and not isinstance(expr, BasicMeta)): return getattr(expr, self.printmethod)(self, **kwargs) # See if the class of expr is known, or if one of its super # classes is known, and use that print function # Exception: ignore the subclasses of Undefined, so that, e.g., # Function('gamma') does not get dispatched to _print_gamma classes = type(expr).__mro__ if AppliedUndef in classes: classes = classes[classes.index(AppliedUndef):] if UndefinedFunction in classes: classes = classes[classes.index(UndefinedFunction):] # Another exception: if someone subclasses a known function, e.g., # gamma, and changes the name, then ignore _print_gamma if Function in classes: i = classes.index(Function) classes = tuple(c for c in classes[:i] if \ c.__name__ == classes[0].__name__ or \ c.__name__.endswith("Base")) + classes[i:] for cls in classes: printmethod = '_print_' + cls.__name__ if hasattr(self, printmethod): return getattr(self, printmethod)(expr, **kwargs) # Unknown object, fall back to the emptyPrinter. return self.emptyPrinter(expr) finally: self._print_level -= 1 def emptyPrinter(self, expr): return str(expr) def _as_ordered_terms(self, expr, order=None): """A compatibility function for ordering terms in Add. """ order = order or self.order if order == 'old': return sorted(Add.make_args(expr), key=cmp_to_key(Basic._compare_pretty)) elif order == 'none': return list(expr.args) else: return expr.as_ordered_terms(order=order) class _PrintFunction: """ Function wrapper to replace ``**settings`` in the signature with printer defaults """ def __init__(self, f, print_cls: Type[Printer]): # find all the non-setting arguments params = list(inspect.signature(f).parameters.values()) assert params.pop(-1).kind == inspect.Parameter.VAR_KEYWORD self.__other_params = params self.__print_cls = print_cls update_wrapper(self, f) def __reduce__(self): # Since this is used as a decorator, it replaces the original function. # The default pickling will try to pickle self.__wrapped__ and fail # because the wrapped function can't be retrieved by name. return self.__wrapped__.__qualname__ def __repr__(self) -> str: return repr(self.__wrapped__) # type:ignore def __call__(self, *args, **kwargs): return self.__wrapped__(*args, **kwargs) @property def __signature__(self) -> inspect.Signature: settings = self.__print_cls._get_initial_settings() return inspect.Signature( parameters=self.__other_params + [ inspect.Parameter(k, inspect.Parameter.KEYWORD_ONLY, default=v) for k, v in settings.items() ], return_annotation=self.__wrapped__.__annotations__.get('return', inspect.Signature.empty) # type:ignore ) def print_function(print_cls): """ A decorator to replace kwargs with the printer settings in __signature__ """ def decorator(f): return _PrintFunction(f, print_cls) return decorator
709c69d446c6bb14264e95874a8b52e8f10a253223a338bf56aea7926df4bef8
from typing import Tuple as tTuple 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 reduce, as_int, default_sort_key, Iterable 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.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 r, i = self.evalf(2).as_real_imag() if not i.is_Number or not 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): 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 refine(self, assumption=True): """See the refine function in sympy.assumptions""" from sympy.assumptions import refine return refine(self, assumption) 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
baa5ad4580142d1f4c623537ff64b6dd6cc272c4559b8634eb70f85bfdcd3b7c
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 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 _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) @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)
7dd7b99984ca7e348799208635885f768ae279d983e2595f389dc40e74882120
from collections import defaultdict from functools import cmp_to_key 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 .compatibility import reduce from .expr import Expr from .parameters import global_parameters # 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): __slots__ = () is_Mul = True _args_type = Expr 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 .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 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
b81b45cf586371761d386eea163f6503761914209dc2c41bd0ce67d8171eeb0e
"""py.test hacks to support XFAIL/XPASS""" from __future__ import print_function, division import sys import functools import os import contextlib import warnings from sympy.core.compatibility import get_function_name 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(object): 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(get_function_name(func)) else: raise Skipped("Timeout") raise XPass(get_function_name(func)) 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) @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)
0a5aa799e21686b17414274c0099d08bd4e88546e1ab901c5a59210fe9b41d4b
""" This is our testing framework. Goals: * it should be compatible with py.test and operate very similarly (or identically) * doesn't require any external dependencies * preferably all the functionality should be in this file only * no magic, just import the test file and execute the test functions, that's it * portable """ from __future__ import print_function, division import os import sys import platform import inspect import traceback import pdb import re import linecache import time from fnmatch import fnmatch from timeit import default_timer as clock import doctest as pdoctest # avoid clashing with our doctest() function from doctest import DocTestFinder, DocTestRunner import random import subprocess import shutil import signal import stat import tempfile import warnings from contextlib import contextmanager from sympy.core.cache import clear_cache from sympy.core.compatibility import (exec_, PY3, unwrap) from sympy.external import import_module IS_WINDOWS = (os.name == 'nt') ON_TRAVIS = os.getenv('TRAVIS_BUILD_NUMBER', None) # emperically generated list of the proportion of time spent running # an even split of tests. This should periodically be regenerated. # A list of [.6, .1, .3] would mean that if the tests are evenly split # into '1/3', '2/3', '3/3', the first split would take 60% of the time, # the second 10% and the third 30%. These lists are normalized to sum # to 1, so [60, 10, 30] has the same behavior as [6, 1, 3] or [.6, .1, .3]. # # This list can be generated with the code: # from time import time # import sympy # import os # os.environ["TRAVIS_BUILD_NUMBER"] = '2' # Mock travis to get more correct densities # delays, num_splits = [], 30 # for i in range(1, num_splits + 1): # tic = time() # sympy.test(split='{}/{}'.format(i, num_splits), time_balance=False) # Add slow=True for slow tests # delays.append(time() - tic) # tot = sum(delays) # print([round(x / tot, 4) for x in delays]) SPLIT_DENSITY = [ 0.0059, 0.0027, 0.0068, 0.0011, 0.0006, 0.0058, 0.0047, 0.0046, 0.004, 0.0257, 0.0017, 0.0026, 0.004, 0.0032, 0.0016, 0.0015, 0.0004, 0.0011, 0.0016, 0.0014, 0.0077, 0.0137, 0.0217, 0.0074, 0.0043, 0.0067, 0.0236, 0.0004, 0.1189, 0.0142, 0.0234, 0.0003, 0.0003, 0.0047, 0.0006, 0.0013, 0.0004, 0.0008, 0.0007, 0.0006, 0.0139, 0.0013, 0.0007, 0.0051, 0.002, 0.0004, 0.0005, 0.0213, 0.0048, 0.0016, 0.0012, 0.0014, 0.0024, 0.0015, 0.0004, 0.0005, 0.0007, 0.011, 0.0062, 0.0015, 0.0021, 0.0049, 0.0006, 0.0006, 0.0011, 0.0006, 0.0019, 0.003, 0.0044, 0.0054, 0.0057, 0.0049, 0.0016, 0.0006, 0.0009, 0.0006, 0.0012, 0.0006, 0.0149, 0.0532, 0.0076, 0.0041, 0.0024, 0.0135, 0.0081, 0.2209, 0.0459, 0.0438, 0.0488, 0.0137, 0.002, 0.0003, 0.0008, 0.0039, 0.0024, 0.0005, 0.0004, 0.003, 0.056, 0.0026] SPLIT_DENSITY_SLOW = [0.0086, 0.0004, 0.0568, 0.0003, 0.0032, 0.0005, 0.0004, 0.0013, 0.0016, 0.0648, 0.0198, 0.1285, 0.098, 0.0005, 0.0064, 0.0003, 0.0004, 0.0026, 0.0007, 0.0051, 0.0089, 0.0024, 0.0033, 0.0057, 0.0005, 0.0003, 0.001, 0.0045, 0.0091, 0.0006, 0.0005, 0.0321, 0.0059, 0.1105, 0.216, 0.1489, 0.0004, 0.0003, 0.0006, 0.0483] class Skipped(Exception): pass class TimeOutError(Exception): pass class DependencyError(Exception): pass # add more flags ?? future_flags = division.compiler_flag def _indent(s, indent=4): """ Add the given number of space characters to the beginning of every non-blank line in ``s``, and return the result. If the string ``s`` is Unicode, it is encoded using the stdout encoding and the ``backslashreplace`` error handler. """ # This regexp matches the start of non-blank lines: return re.sub('(?m)^(?!$)', indent*' ', s) pdoctest._indent = _indent # type: ignore # override reporter to maintain windows and python3 def _report_failure(self, out, test, example, got): """ Report that the given example failed. """ s = self._checker.output_difference(example, got, self.optionflags) s = s.encode('raw_unicode_escape').decode('utf8', 'ignore') out(self._failure_header(test, example) + s) if PY3 and IS_WINDOWS: DocTestRunner.report_failure = _report_failure # type: ignore def convert_to_native_paths(lst): """ Converts a list of '/' separated paths into a list of native (os.sep separated) paths and converts to lowercase if the system is case insensitive. """ newlst = [] for i, rv in enumerate(lst): rv = os.path.join(*rv.split("/")) # on windows the slash after the colon is dropped if sys.platform == "win32": pos = rv.find(':') if pos != -1: if rv[pos + 1] != '\\': rv = rv[:pos + 1] + '\\' + rv[pos + 1:] newlst.append(os.path.normcase(rv)) return newlst def get_sympy_dir(): """ Returns the root sympy directory and set the global value indicating whether the system is case sensitive or not. """ this_file = os.path.abspath(__file__) sympy_dir = os.path.join(os.path.dirname(this_file), "..", "..") sympy_dir = os.path.normpath(sympy_dir) return os.path.normcase(sympy_dir) def setup_pprint(): from sympy import pprint_use_unicode, init_printing import sympy.interactive.printing as interactive_printing # force pprint to be in ascii mode in doctests use_unicode_prev = pprint_use_unicode(False) # hook our nice, hash-stable strprinter init_printing(pretty_print=False) # Prevent init_printing() in doctests from affecting other doctests interactive_printing.NO_GLOBAL = True return use_unicode_prev @contextmanager def raise_on_deprecated(): """Context manager to make DeprecationWarning raise an error This is to catch SymPyDeprecationWarning from library code while running tests and doctests. It is important to use this context manager around each individual test/doctest in case some tests modify the warning filters. """ with warnings.catch_warnings(): warnings.filterwarnings('error', '.*', DeprecationWarning, module='sympy.*') yield def run_in_subprocess_with_hash_randomization( function, function_args=(), function_kwargs=None, command=sys.executable, module='sympy.testing.runtests', force=False): """ Run a function in a Python subprocess with hash randomization enabled. If hash randomization is not supported by the version of Python given, it returns False. Otherwise, it returns the exit value of the command. The function is passed to sys.exit(), so the return value of the function will be the return value. The environment variable PYTHONHASHSEED is used to seed Python's hash randomization. If it is set, this function will return False, because starting a new subprocess is unnecessary in that case. If it is not set, one is set at random, and the tests are run. Note that if this environment variable is set when Python starts, hash randomization is automatically enabled. To force a subprocess to be created even if PYTHONHASHSEED is set, pass ``force=True``. This flag will not force a subprocess in Python versions that do not support hash randomization (see below), because those versions of Python do not support the ``-R`` flag. ``function`` should be a string name of a function that is importable from the module ``module``, like "_test". The default for ``module`` is "sympy.testing.runtests". ``function_args`` and ``function_kwargs`` should be a repr-able tuple and dict, respectively. The default Python command is sys.executable, which is the currently running Python command. This function is necessary because the seed for hash randomization must be set by the environment variable before Python starts. Hence, in order to use a predetermined seed for tests, we must start Python in a separate subprocess. Hash randomization was added in the minor Python versions 2.6.8, 2.7.3, 3.1.5, and 3.2.3, and is enabled by default in all Python versions after and including 3.3.0. Examples ======== >>> from sympy.testing.runtests import ( ... run_in_subprocess_with_hash_randomization) >>> # run the core tests in verbose mode >>> run_in_subprocess_with_hash_randomization("_test", ... function_args=("core",), ... function_kwargs={'verbose': True}) # doctest: +SKIP # Will return 0 if sys.executable supports hash randomization and tests # pass, 1 if they fail, and False if it does not support hash # randomization. """ cwd = get_sympy_dir() # Note, we must return False everywhere, not None, as subprocess.call will # sometimes return None. # First check if the Python version supports hash randomization # If it doesn't have this support, it won't recognize the -R flag p = subprocess.Popen([command, "-RV"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd) p.communicate() if p.returncode != 0: return False hash_seed = os.getenv("PYTHONHASHSEED") if not hash_seed: os.environ["PYTHONHASHSEED"] = str(random.randrange(2**32)) else: if not force: return False function_kwargs = function_kwargs or {} # Now run the command commandstring = ("import sys; from %s import %s;sys.exit(%s(*%s, **%s))" % (module, function, function, repr(function_args), repr(function_kwargs))) try: p = subprocess.Popen([command, "-R", "-c", commandstring], cwd=cwd) p.communicate() except KeyboardInterrupt: p.wait() finally: # Put the environment variable back, so that it reads correctly for # the current Python process. if hash_seed is None: del os.environ["PYTHONHASHSEED"] else: os.environ["PYTHONHASHSEED"] = hash_seed return p.returncode def run_all_tests(test_args=(), test_kwargs=None, doctest_args=(), doctest_kwargs=None, examples_args=(), examples_kwargs=None): """ Run all tests. Right now, this runs the regular tests (bin/test), the doctests (bin/doctest), the examples (examples/all.py), and the sage tests (see sympy/external/tests/test_sage.py). This is what ``setup.py test`` uses. You can pass arguments and keyword arguments to the test functions that support them (for now, test, doctest, and the examples). See the docstrings of those functions for a description of the available options. For example, to run the solvers tests with colors turned off: >>> from sympy.testing.runtests import run_all_tests >>> run_all_tests(test_args=("solvers",), ... test_kwargs={"colors:False"}) # doctest: +SKIP """ cwd = get_sympy_dir() tests_successful = True test_kwargs = test_kwargs or {} doctest_kwargs = doctest_kwargs or {} examples_kwargs = examples_kwargs or {'quiet': True} try: # Regular tests if not test(*test_args, **test_kwargs): # some regular test fails, so set the tests_successful # flag to false and continue running the doctests tests_successful = False # Doctests print() if not doctest(*doctest_args, **doctest_kwargs): tests_successful = False # Examples print() sys.path.append("examples") # examples/all.py from all import run_examples # type: ignore if not run_examples(*examples_args, **examples_kwargs): tests_successful = False # Sage tests if sys.platform != "win32" and not PY3 and os.path.exists("bin/test"): # run Sage tests; Sage currently doesn't support Windows or Python 3 # Only run Sage tests if 'bin/test' is present (it is missing from # our release because everything in the 'bin' directory gets # installed). dev_null = open(os.devnull, 'w') if subprocess.call("sage -v", shell=True, stdout=dev_null, stderr=dev_null) == 0: if subprocess.call("sage -python bin/test " "sympy/external/tests/test_sage.py", shell=True, cwd=cwd) != 0: tests_successful = False if tests_successful: return else: # Return nonzero exit code sys.exit(1) except KeyboardInterrupt: print() print("DO *NOT* COMMIT!") sys.exit(1) def test(*paths, subprocess=True, rerun=0, **kwargs): """ Run tests in the specified test_*.py files. Tests in a particular test_*.py file are run if any of the given strings in ``paths`` matches a part of the test file's path. If ``paths=[]``, tests in all test_*.py files are run. Notes: - If sort=False, tests are run in random order (not default). - Paths can be entered in native system format or in unix, forward-slash format. - Files that are on the blacklist can be tested by providing their path; they are only excluded if no paths are given. **Explanation of test results** ====== =============================================================== Output Meaning ====== =============================================================== . passed F failed X XPassed (expected to fail but passed) f XFAILed (expected to fail and indeed failed) s skipped w slow T timeout (e.g., when ``--timeout`` is used) K KeyboardInterrupt (when running the slow tests with ``--slow``, you can interrupt one of them without killing the test runner) ====== =============================================================== Colors have no additional meaning and are used just to facilitate interpreting the output. Examples ======== >>> import sympy Run all tests: >>> sympy.test() # doctest: +SKIP Run one file: >>> sympy.test("sympy/core/tests/test_basic.py") # doctest: +SKIP >>> sympy.test("_basic") # doctest: +SKIP Run all tests in sympy/functions/ and some particular file: >>> sympy.test("sympy/core/tests/test_basic.py", ... "sympy/functions") # doctest: +SKIP Run all tests in sympy/core and sympy/utilities: >>> sympy.test("/core", "/util") # doctest: +SKIP Run specific test from a file: >>> sympy.test("sympy/core/tests/test_basic.py", ... kw="test_equality") # doctest: +SKIP Run specific test from any file: >>> sympy.test(kw="subs") # doctest: +SKIP Run the tests with verbose mode on: >>> sympy.test(verbose=True) # doctest: +SKIP Don't sort the test output: >>> sympy.test(sort=False) # doctest: +SKIP Turn on post-mortem pdb: >>> sympy.test(pdb=True) # doctest: +SKIP Turn off colors: >>> sympy.test(colors=False) # doctest: +SKIP Force colors, even when the output is not to a terminal (this is useful, e.g., if you are piping to ``less -r`` and you still want colors) >>> sympy.test(force_colors=False) # doctest: +SKIP The traceback verboseness can be set to "short" or "no" (default is "short") >>> sympy.test(tb='no') # doctest: +SKIP The ``split`` option can be passed to split the test run into parts. The split currently only splits the test files, though this may change in the future. ``split`` should be a string of the form 'a/b', which will run part ``a`` of ``b``. For instance, to run the first half of the test suite: >>> sympy.test(split='1/2') # doctest: +SKIP The ``time_balance`` option can be passed in conjunction with ``split``. If ``time_balance=True`` (the default for ``sympy.test``), sympy will attempt to split the tests such that each split takes equal time. This heuristic for balancing is based on pre-recorded test data. >>> sympy.test(split='1/2', time_balance=True) # doctest: +SKIP You can disable running the tests in a separate subprocess using ``subprocess=False``. This is done to support seeding hash randomization, which is enabled by default in the Python versions where it is supported. If subprocess=False, hash randomization is enabled/disabled according to whether it has been enabled or not in the calling Python process. However, even if it is enabled, the seed cannot be printed unless it is called from a new Python process. Hash randomization was added in the minor Python versions 2.6.8, 2.7.3, 3.1.5, and 3.2.3, and is enabled by default in all Python versions after and including 3.3.0. If hash randomization is not supported ``subprocess=False`` is used automatically. >>> sympy.test(subprocess=False) # doctest: +SKIP To set the hash randomization seed, set the environment variable ``PYTHONHASHSEED`` before running the tests. This can be done from within Python using >>> import os >>> os.environ['PYTHONHASHSEED'] = '42' # doctest: +SKIP Or from the command line using $ PYTHONHASHSEED=42 ./bin/test If the seed is not set, a random seed will be chosen. Note that to reproduce the same hash values, you must use both the same seed as well as the same architecture (32-bit vs. 64-bit). """ # count up from 0, do not print 0 print_counter = lambda i : (print("rerun %d" % (rerun-i)) if rerun-i else None) if subprocess: # loop backwards so last i is 0 for i in range(rerun, -1, -1): print_counter(i) ret = run_in_subprocess_with_hash_randomization("_test", function_args=paths, function_kwargs=kwargs) if ret is False: break val = not bool(ret) # exit on the first failure or if done if not val or i == 0: return val # rerun even if hash randomization is not supported for i in range(rerun, -1, -1): print_counter(i) val = not bool(_test(*paths, **kwargs)) if not val or i == 0: return val def _test(*paths, verbose=False, tb="short", kw=None, pdb=False, colors=True, force_colors=False, sort=True, seed=None, timeout=False, fail_on_timeout=False, slow=False, enhance_asserts=False, split=None, time_balance=True, blacklist=('sympy/integrals/rubi/rubi_tests/tests',), fast_threshold=None, slow_threshold=None): """ Internal function that actually runs the tests. All keyword arguments from ``test()`` are passed to this function except for ``subprocess``. Returns 0 if tests passed and 1 if they failed. See the docstring of ``test()`` for more information. """ kw = kw or () # ensure that kw is a tuple if isinstance(kw, str): kw = (kw,) post_mortem = pdb if seed is None: seed = random.randrange(100000000) if ON_TRAVIS and timeout is False: # Travis times out if no activity is seen for 10 minutes. timeout = 595 fail_on_timeout = True if ON_TRAVIS: # pyglet does not work on Travis blacklist = list(blacklist) + ['sympy/plotting/pygletplot/tests'] blacklist = convert_to_native_paths(blacklist) r = PyTestReporter(verbose=verbose, tb=tb, colors=colors, force_colors=force_colors, split=split) t = SymPyTests(r, kw, post_mortem, seed, fast_threshold=fast_threshold, slow_threshold=slow_threshold) test_files = t.get_test_files('sympy') not_blacklisted = [f for f in test_files if not any(b in f for b in blacklist)] if len(paths) == 0: matched = not_blacklisted else: paths = convert_to_native_paths(paths) matched = [] for f in not_blacklisted: basename = os.path.basename(f) for p in paths: if p in f or fnmatch(basename, p): matched.append(f) break density = None if time_balance: if slow: density = SPLIT_DENSITY_SLOW else: density = SPLIT_DENSITY if split: matched = split_list(matched, split, density=density) t._testfiles.extend(matched) return int(not t.test(sort=sort, timeout=timeout, slow=slow, enhance_asserts=enhance_asserts, fail_on_timeout=fail_on_timeout)) def doctest(*paths, subprocess=True, rerun=0, **kwargs): r""" Runs doctests in all \*.py files in the sympy directory which match any of the given strings in ``paths`` or all tests if paths=[]. Notes: - Paths can be entered in native system format or in unix, forward-slash format. - Files that are on the blacklist can be tested by providing their path; they are only excluded if no paths are given. Examples ======== >>> import sympy Run all tests: >>> sympy.doctest() # doctest: +SKIP Run one file: >>> sympy.doctest("sympy/core/basic.py") # doctest: +SKIP >>> sympy.doctest("polynomial.rst") # doctest: +SKIP Run all tests in sympy/functions/ and some particular file: >>> sympy.doctest("/functions", "basic.py") # doctest: +SKIP Run any file having polynomial in its name, doc/src/modules/polynomial.rst, sympy/functions/special/polynomials.py, and sympy/polys/polynomial.py: >>> sympy.doctest("polynomial") # doctest: +SKIP The ``split`` option can be passed to split the test run into parts. The split currently only splits the test files, though this may change in the future. ``split`` should be a string of the form 'a/b', which will run part ``a`` of ``b``. Note that the regular doctests and the Sphinx doctests are split independently. For instance, to run the first half of the test suite: >>> sympy.doctest(split='1/2') # doctest: +SKIP The ``subprocess`` and ``verbose`` options are the same as with the function ``test()``. See the docstring of that function for more information. """ # count up from 0, do not print 0 print_counter = lambda i : (print("rerun %d" % (rerun-i)) if rerun-i else None) if subprocess: # loop backwards so last i is 0 for i in range(rerun, -1, -1): print_counter(i) ret = run_in_subprocess_with_hash_randomization("_doctest", function_args=paths, function_kwargs=kwargs) if ret is False: break val = not bool(ret) # exit on the first failure or if done if not val or i == 0: return val # rerun even if hash randomization is not supported for i in range(rerun, -1, -1): print_counter(i) val = not bool(_doctest(*paths, **kwargs)) if not val or i == 0: return val def _get_doctest_blacklist(): '''Get the default blacklist for the doctests''' blacklist = [] blacklist.extend([ "doc/src/modules/plotting.rst", # generates live plots "doc/src/modules/physics/mechanics/autolev_parser.rst", "sympy/galgebra.py", # no longer part of SymPy "sympy/this.py", # prints text "sympy/physics/gaussopt.py", # raises deprecation warning "sympy/matrices/densearith.py", # raises deprecation warning "sympy/matrices/densesolve.py", # raises deprecation warning "sympy/matrices/densetools.py", # raises deprecation warning "sympy/printing/ccode.py", # backwards compatibility shim, importing it breaks the codegen doctests "sympy/printing/fcode.py", # backwards compatibility shim, importing it breaks the codegen doctests "sympy/printing/cxxcode.py", # backwards compatibility shim, importing it breaks the codegen doctests "sympy/parsing/autolev/_antlr/autolevlexer.py", # generated code "sympy/parsing/autolev/_antlr/autolevparser.py", # generated code "sympy/parsing/autolev/_antlr/autolevlistener.py", # generated code "sympy/parsing/latex/_antlr/latexlexer.py", # generated code "sympy/parsing/latex/_antlr/latexparser.py", # generated code "sympy/integrals/rubi/rubi.py", "sympy/plotting/pygletplot/__init__.py", # crashes on some systems "sympy/plotting/pygletplot/plot.py", # crashes on some systems ]) # autolev parser tests num = 12 for i in range (1, num+1): blacklist.append("sympy/parsing/autolev/test-examples/ruletest" + str(i) + ".py") blacklist.extend(["sympy/parsing/autolev/test-examples/pydy-example-repo/mass_spring_damper.py", "sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py", "sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.py", "sympy/parsing/autolev/test-examples/pydy-example-repo/non_min_pendulum.py"]) if import_module('numpy') is None: blacklist.extend([ "sympy/plotting/experimental_lambdify.py", "sympy/plotting/plot_implicit.py", "examples/advanced/autowrap_integrators.py", "examples/advanced/autowrap_ufuncify.py", "examples/intermediate/sample.py", "examples/intermediate/mplot2d.py", "examples/intermediate/mplot3d.py", "doc/src/modules/numeric-computation.rst" ]) else: if import_module('matplotlib') is None: blacklist.extend([ "examples/intermediate/mplot2d.py", "examples/intermediate/mplot3d.py" ]) else: # Use a non-windowed backend, so that the tests work on Travis import matplotlib matplotlib.use('Agg') if ON_TRAVIS or import_module('pyglet') is None: blacklist.extend(["sympy/plotting/pygletplot"]) if import_module('theano') is None: blacklist.extend([ "sympy/printing/theanocode.py", "doc/src/modules/numeric-computation.rst", ]) if import_module('antlr4') is None: blacklist.extend([ "sympy/parsing/autolev/__init__.py", "sympy/parsing/latex/_parse_latex_antlr.py", ]) if import_module('lfortran') is None: #throws ImportError when lfortran not installed blacklist.extend([ "sympy/parsing/sym_expr.py", ]) # disabled because of doctest failures in asmeurer's bot blacklist.extend([ "sympy/utilities/autowrap.py", "examples/advanced/autowrap_integrators.py", "examples/advanced/autowrap_ufuncify.py" ]) # blacklist these modules until issue 4840 is resolved blacklist.extend([ "sympy/conftest.py", # Python 2.7 issues "sympy/testing/benchmarking.py", ]) # These are deprecated stubs to be removed: blacklist.extend([ "sympy/utilities/benchmarking.py", "sympy/utilities/tmpfiles.py", "sympy/utilities/pytest.py", "sympy/utilities/runtests.py", "sympy/utilities/quality_unicode.py", "sympy/utilities/randtest.py", ]) blacklist = convert_to_native_paths(blacklist) return blacklist def _doctest(*paths, **kwargs): """ Internal function that actually runs the doctests. All keyword arguments from ``doctest()`` are passed to this function except for ``subprocess``. Returns 0 if tests passed and 1 if they failed. See the docstrings of ``doctest()`` and ``test()`` for more information. """ from sympy import pprint_use_unicode normal = kwargs.get("normal", False) verbose = kwargs.get("verbose", False) colors = kwargs.get("colors", True) force_colors = kwargs.get("force_colors", False) blacklist = kwargs.get("blacklist", []) split = kwargs.get('split', None) blacklist.extend(_get_doctest_blacklist()) # Use a non-windowed backend, so that the tests work on Travis if import_module('matplotlib') is not None: import matplotlib matplotlib.use('Agg') # Disable warnings for external modules import sympy.external sympy.external.importtools.WARN_OLD_VERSION = False sympy.external.importtools.WARN_NOT_INSTALLED = False # Disable showing up of plots from sympy.plotting.plot import unset_show unset_show() r = PyTestReporter(verbose, split=split, colors=colors,\ force_colors=force_colors) t = SymPyDocTests(r, normal) test_files = t.get_test_files('sympy') test_files.extend(t.get_test_files('examples', init_only=False)) not_blacklisted = [f for f in test_files if not any(b in f for b in blacklist)] if len(paths) == 0: matched = not_blacklisted else: # take only what was requested...but not blacklisted items # and allow for partial match anywhere or fnmatch of name paths = convert_to_native_paths(paths) matched = [] for f in not_blacklisted: basename = os.path.basename(f) for p in paths: if p in f or fnmatch(basename, p): matched.append(f) break if split: matched = split_list(matched, split) t._testfiles.extend(matched) # run the tests and record the result for this *py portion of the tests if t._testfiles: failed = not t.test() else: failed = False # N.B. # -------------------------------------------------------------------- # Here we test *.rst files at or below doc/src. Code from these must # be self supporting in terms of imports since there is no importing # of necessary modules by doctest.testfile. If you try to pass *.py # files through this they might fail because they will lack the needed # imports and smarter parsing that can be done with source code. # test_files = t.get_test_files('doc/src', '*.rst', init_only=False) test_files.sort() not_blacklisted = [f for f in test_files if not any(b in f for b in blacklist)] if len(paths) == 0: matched = not_blacklisted else: # Take only what was requested as long as it's not on the blacklist. # Paths were already made native in *py tests so don't repeat here. # There's no chance of having a *py file slip through since we # only have *rst files in test_files. matched = [] for f in not_blacklisted: basename = os.path.basename(f) for p in paths: if p in f or fnmatch(basename, p): matched.append(f) break if split: matched = split_list(matched, split) first_report = True for rst_file in matched: if not os.path.isfile(rst_file): continue old_displayhook = sys.displayhook try: use_unicode_prev = setup_pprint() out = sympytestfile( rst_file, module_relative=False, encoding='utf-8', optionflags=pdoctest.ELLIPSIS | pdoctest.NORMALIZE_WHITESPACE | pdoctest.IGNORE_EXCEPTION_DETAIL) finally: # make sure we return to the original displayhook in case some # doctest has changed that sys.displayhook = old_displayhook # The NO_GLOBAL flag overrides the no_global flag to init_printing # if True import sympy.interactive.printing as interactive_printing interactive_printing.NO_GLOBAL = False pprint_use_unicode(use_unicode_prev) rstfailed, tested = out if tested: failed = rstfailed or failed if first_report: first_report = False msg = 'rst doctests start' if not t._testfiles: r.start(msg=msg) else: r.write_center(msg) print() # use as the id, everything past the first 'sympy' file_id = rst_file[rst_file.find('sympy') + len('sympy') + 1:] print(file_id, end=" ") # get at least the name out so it is know who is being tested wid = r.terminal_width - len(file_id) - 1 # update width test_file = '[%s]' % (tested) report = '[%s]' % (rstfailed or 'OK') print(''.join( [test_file, ' '*(wid - len(test_file) - len(report)), report]) ) # the doctests for *py will have printed this message already if there was # a failure, so now only print it if there was intervening reporting by # testing the *rst as evidenced by first_report no longer being True. if not first_report and failed: print() print("DO *NOT* COMMIT!") return int(failed) sp = re.compile(r'([0-9]+)/([1-9][0-9]*)') def split_list(l, split, density=None): """ Splits a list into part a of b split should be a string of the form 'a/b'. For instance, '1/3' would give the split one of three. If the length of the list is not divisible by the number of splits, the last split will have more items. `density` may be specified as a list. If specified, tests will be balanced so that each split has as equal-as-possible amount of mass according to `density`. >>> from sympy.testing.runtests import split_list >>> a = list(range(10)) >>> split_list(a, '1/3') [0, 1, 2] >>> split_list(a, '2/3') [3, 4, 5] >>> split_list(a, '3/3') [6, 7, 8, 9] """ m = sp.match(split) if not m: raise ValueError("split must be a string of the form a/b where a and b are ints") i, t = map(int, m.groups()) if not density: return l[(i - 1)*len(l)//t : i*len(l)//t] # normalize density tot = sum(density) density = [x / tot for x in density] def density_inv(x): """Interpolate the inverse to the cumulative distribution function given by density""" if x <= 0: return 0 if x >= sum(density): return 1 # find the first time the cumulative sum surpasses x # and linearly interpolate cumm = 0 for i, d in enumerate(density): cumm += d if cumm >= x: break frac = (d - (cumm - x)) / d return (i + frac) / len(density) lower_frac = density_inv((i - 1) / t) higher_frac = density_inv(i / t) return l[int(lower_frac*len(l)) : int(higher_frac*len(l))] from collections import namedtuple SymPyTestResults = namedtuple('SymPyTestResults', 'failed attempted') def sympytestfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, parser=pdoctest.DocTestParser(), encoding=None): """ Test examples in the given file. Return (#failures, #tests). Optional keyword arg ``module_relative`` specifies how filenames should be interpreted: - If ``module_relative`` is True (the default), then ``filename`` specifies a module-relative path. By default, this path is relative to the calling module's directory; but if the ``package`` argument is specified, then it is relative to that package. To ensure os-independence, ``filename`` should use "/" characters to separate path segments, and should not be an absolute path (i.e., it may not begin with "/"). - If ``module_relative`` is False, then ``filename`` specifies an os-specific path. The path may be absolute or relative (to the current working directory). Optional keyword arg ``name`` gives the name of the test; by default use the file's basename. Optional keyword argument ``package`` is a Python package or the name of a Python package whose directory should be used as the base directory for a module relative filename. If no package is specified, then the calling module's directory is used as the base directory for module relative filenames. It is an error to specify ``package`` if ``module_relative`` is False. Optional keyword arg ``globs`` gives a dict to be used as the globals when executing examples; by default, use {}. A copy of this dict is actually used for each docstring, so that each docstring's examples start with a clean slate. Optional keyword arg ``extraglobs`` gives a dictionary that should be merged into the globals that are used to execute examples. By default, no extra globals are used. Optional keyword arg ``verbose`` prints lots of stuff if true, prints only failures if false; by default, it's true iff "-v" is in sys.argv. Optional keyword arg ``report`` prints a summary at the end when true, else prints nothing at the end. In verbose mode, the summary is detailed, else very brief (in fact, empty if all tests passed). Optional keyword arg ``optionflags`` or's together module constants, and defaults to 0. Possible values (see the docs for details): - DONT_ACCEPT_TRUE_FOR_1 - DONT_ACCEPT_BLANKLINE - NORMALIZE_WHITESPACE - ELLIPSIS - SKIP - IGNORE_EXCEPTION_DETAIL - REPORT_UDIFF - REPORT_CDIFF - REPORT_NDIFF - REPORT_ONLY_FIRST_FAILURE Optional keyword arg ``raise_on_error`` raises an exception on the first unexpected exception or failure. This allows failures to be post-mortem debugged. Optional keyword arg ``parser`` specifies a DocTestParser (or subclass) that should be used to extract tests from the files. Optional keyword arg ``encoding`` specifies an encoding that should be used to convert the file to unicode. Advanced tomfoolery: testmod runs methods of a local instance of class doctest.Tester, then merges the results into (or creates) global Tester instance doctest.master. Methods of doctest.master can be called directly too, if you want to do something unusual. Passing report=0 to testmod is especially useful then, to delay displaying a summary. Invoke doctest.master.summarize(verbose) when you're done fiddling. """ if package and not module_relative: raise ValueError("Package may only be specified for module-" "relative paths.") # Relativize the path if not PY3: text, filename = pdoctest._load_testfile( filename, package, module_relative) if encoding is not None: text = text.decode(encoding) else: text, filename = pdoctest._load_testfile( filename, package, module_relative, encoding) # If no name was given, then use the file's name. if name is None: name = os.path.basename(filename) # Assemble the globals. if globs is None: globs = {} else: globs = globs.copy() if extraglobs is not None: globs.update(extraglobs) if '__name__' not in globs: globs['__name__'] = '__main__' if raise_on_error: runner = pdoctest.DebugRunner(verbose=verbose, optionflags=optionflags) else: runner = SymPyDocTestRunner(verbose=verbose, optionflags=optionflags) runner._checker = SymPyOutputChecker() # Read the file, convert it to a test, and run it. test = parser.get_doctest(text, globs, name, filename, 0) runner.run(test, compileflags=future_flags) if report: runner.summarize() if pdoctest.master is None: pdoctest.master = runner else: pdoctest.master.merge(runner) return SymPyTestResults(runner.failures, runner.tries) class SymPyTests(object): def __init__(self, reporter, kw="", post_mortem=False, seed=None, fast_threshold=None, slow_threshold=None): self._post_mortem = post_mortem self._kw = kw self._count = 0 self._root_dir = get_sympy_dir() self._reporter = reporter self._reporter.root_dir(self._root_dir) self._testfiles = [] self._seed = seed if seed is not None else random.random() # Defaults in seconds, from human / UX design limits # http://www.nngroup.com/articles/response-times-3-important-limits/ # # These defaults are *NOT* set in stone as we are measuring different # things, so others feel free to come up with a better yardstick :) if fast_threshold: self._fast_threshold = float(fast_threshold) else: self._fast_threshold = 8 if slow_threshold: self._slow_threshold = float(slow_threshold) else: self._slow_threshold = 10 def test(self, sort=False, timeout=False, slow=False, enhance_asserts=False, fail_on_timeout=False): """ Runs the tests returning True if all tests pass, otherwise False. If sort=False run tests in random order. """ if sort: self._testfiles.sort() elif slow: pass else: random.seed(self._seed) random.shuffle(self._testfiles) self._reporter.start(self._seed) for f in self._testfiles: try: self.test_file(f, sort, timeout, slow, enhance_asserts, fail_on_timeout) except KeyboardInterrupt: print(" interrupted by user") self._reporter.finish() raise return self._reporter.finish() def _enhance_asserts(self, source): from ast import (NodeTransformer, Compare, Name, Store, Load, Tuple, Assign, BinOp, Str, Mod, Assert, parse, fix_missing_locations) ops = {"Eq": '==', "NotEq": '!=', "Lt": '<', "LtE": '<=', "Gt": '>', "GtE": '>=', "Is": 'is', "IsNot": 'is not', "In": 'in', "NotIn": 'not in'} class Transform(NodeTransformer): def visit_Assert(self, stmt): if isinstance(stmt.test, Compare): compare = stmt.test values = [compare.left] + compare.comparators names = [ "_%s" % i for i, _ in enumerate(values) ] names_store = [ Name(n, Store()) for n in names ] names_load = [ Name(n, Load()) for n in names ] target = Tuple(names_store, Store()) value = Tuple(values, Load()) assign = Assign([target], value) new_compare = Compare(names_load[0], compare.ops, names_load[1:]) msg_format = "\n%s " + "\n%s ".join([ ops[op.__class__.__name__] for op in compare.ops ]) + "\n%s" msg = BinOp(Str(msg_format), Mod(), Tuple(names_load, Load())) test = Assert(new_compare, msg, lineno=stmt.lineno, col_offset=stmt.col_offset) return [assign, test] else: return stmt tree = parse(source) new_tree = Transform().visit(tree) return fix_missing_locations(new_tree) def test_file(self, filename, sort=True, timeout=False, slow=False, enhance_asserts=False, fail_on_timeout=False): reporter = self._reporter funcs = [] try: gl = {'__file__': filename} try: if PY3: open_file = lambda: open(filename, encoding="utf8") else: open_file = lambda: open(filename) with open_file() as f: source = f.read() if self._kw: for l in source.splitlines(): if l.lstrip().startswith('def '): if any(l.find(k) != -1 for k in self._kw): break else: return if enhance_asserts: try: source = self._enhance_asserts(source) except ImportError: pass code = compile(source, filename, "exec", flags=0, dont_inherit=True) exec_(code, gl) except (SystemExit, KeyboardInterrupt): raise except ImportError: reporter.import_error(filename, sys.exc_info()) return except Exception: reporter.test_exception(sys.exc_info()) clear_cache() self._count += 1 random.seed(self._seed) disabled = gl.get("disabled", False) if not disabled: # we need to filter only those functions that begin with 'test_' # We have to be careful about decorated functions. As long as # the decorator uses functools.wraps, we can detect it. funcs = [] for f in gl: if (f.startswith("test_") and (inspect.isfunction(gl[f]) or inspect.ismethod(gl[f]))): func = gl[f] # Handle multiple decorators while hasattr(func, '__wrapped__'): func = func.__wrapped__ if inspect.getsourcefile(func) == filename: funcs.append(gl[f]) if slow: funcs = [f for f in funcs if getattr(f, '_slow', False)] # Sorting of XFAILed functions isn't fixed yet :-( funcs.sort(key=lambda x: inspect.getsourcelines(x)[1]) i = 0 while i < len(funcs): if inspect.isgeneratorfunction(funcs[i]): # some tests can be generators, that return the actual # test functions. We unpack it below: f = funcs.pop(i) for fg in f(): func = fg[0] args = fg[1:] fgw = lambda: func(*args) funcs.insert(i, fgw) i += 1 else: i += 1 # drop functions that are not selected with the keyword expression: funcs = [x for x in funcs if self.matches(x)] if not funcs: return except Exception: reporter.entering_filename(filename, len(funcs)) raise reporter.entering_filename(filename, len(funcs)) if not sort: random.shuffle(funcs) for f in funcs: start = time.time() reporter.entering_test(f) try: if getattr(f, '_slow', False) and not slow: raise Skipped("Slow") with raise_on_deprecated(): if timeout: self._timeout(f, timeout, fail_on_timeout) else: random.seed(self._seed) f() except KeyboardInterrupt: if getattr(f, '_slow', False): reporter.test_skip("KeyboardInterrupt") else: raise except Exception: if timeout: signal.alarm(0) # Disable the alarm. It could not be handled before. t, v, tr = sys.exc_info() if t is AssertionError: reporter.test_fail((t, v, tr)) if self._post_mortem: pdb.post_mortem(tr) elif t.__name__ == "Skipped": reporter.test_skip(v) elif t.__name__ == "XFail": reporter.test_xfail() elif t.__name__ == "XPass": reporter.test_xpass(v) else: reporter.test_exception((t, v, tr)) if self._post_mortem: pdb.post_mortem(tr) else: reporter.test_pass() taken = time.time() - start if taken > self._slow_threshold: filename = os.path.relpath(filename, reporter._root_dir) reporter.slow_test_functions.append( (filename + "::" + f.__name__, taken)) if getattr(f, '_slow', False) and slow: if taken < self._fast_threshold: filename = os.path.relpath(filename, reporter._root_dir) reporter.fast_test_functions.append( (filename + "::" + f.__name__, taken)) reporter.leaving_filename() def _timeout(self, function, timeout, fail_on_timeout): def callback(x, y): signal.alarm(0) if fail_on_timeout: raise TimeOutError("Timed out after %d seconds" % timeout) else: raise Skipped("Timeout") signal.signal(signal.SIGALRM, callback) signal.alarm(timeout) # Set an alarm with a given timeout function() signal.alarm(0) # Disable the alarm def matches(self, x): """ Does the keyword expression self._kw match "x"? Returns True/False. Always returns True if self._kw is "". """ if not self._kw: return True for kw in self._kw: if x.__name__.find(kw) != -1: return True return False def get_test_files(self, dir, pat='test_*.py'): """ Returns the list of test_*.py (default) files at or below directory ``dir`` relative to the sympy home directory. """ dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0]) g = [] for path, folders, files in os.walk(dir): g.extend([os.path.join(path, f) for f in files if fnmatch(f, pat)]) return sorted([os.path.normcase(gi) for gi in g]) class SymPyDocTests(object): def __init__(self, reporter, normal): self._count = 0 self._root_dir = get_sympy_dir() self._reporter = reporter self._reporter.root_dir(self._root_dir) self._normal = normal self._testfiles = [] def test(self): """ Runs the tests and returns True if all tests pass, otherwise False. """ self._reporter.start() for f in self._testfiles: try: self.test_file(f) except KeyboardInterrupt: print(" interrupted by user") self._reporter.finish() raise return self._reporter.finish() def test_file(self, filename): clear_cache() from sympy.core.compatibility import StringIO import sympy.interactive.printing as interactive_printing from sympy import pprint_use_unicode rel_name = filename[len(self._root_dir) + 1:] dirname, file = os.path.split(filename) module = rel_name.replace(os.sep, '.')[:-3] if rel_name.startswith("examples"): # Examples files do not have __init__.py files, # So we have to temporarily extend sys.path to import them sys.path.insert(0, dirname) module = file[:-3] # remove ".py" try: module = pdoctest._normalize_module(module) tests = SymPyDocTestFinder().find(module) except (SystemExit, KeyboardInterrupt): raise except ImportError: self._reporter.import_error(filename, sys.exc_info()) return finally: if rel_name.startswith("examples"): del sys.path[0] tests = [test for test in tests if len(test.examples) > 0] # By default tests are sorted by alphabetical order by function name. # We sort by line number so one can edit the file sequentially from # bottom to top. However, if there are decorated functions, their line # numbers will be too large and for now one must just search for these # by text and function name. tests.sort(key=lambda x: -x.lineno) if not tests: return self._reporter.entering_filename(filename, len(tests)) for test in tests: assert len(test.examples) != 0 if self._reporter._verbose: self._reporter.write("\n{} ".format(test.name)) # check if there are external dependencies which need to be met if '_doctest_depends_on' in test.globs: try: self._check_dependencies(**test.globs['_doctest_depends_on']) except DependencyError as e: self._reporter.test_skip(v=str(e)) continue runner = SymPyDocTestRunner(optionflags=pdoctest.ELLIPSIS | pdoctest.NORMALIZE_WHITESPACE | pdoctest.IGNORE_EXCEPTION_DETAIL) runner._checker = SymPyOutputChecker() old = sys.stdout new = StringIO() sys.stdout = new # If the testing is normal, the doctests get importing magic to # provide the global namespace. If not normal (the default) then # then must run on their own; all imports must be explicit within # a function's docstring. Once imported that import will be # available to the rest of the tests in a given function's # docstring (unless clear_globs=True below). if not self._normal: test.globs = {} # if this is uncommented then all the test would get is what # comes by default with a "from sympy import *" #exec('from sympy import *') in test.globs test.globs['print_function'] = print_function old_displayhook = sys.displayhook use_unicode_prev = setup_pprint() try: f, t = runner.run(test, compileflags=future_flags, out=new.write, clear_globs=False) except KeyboardInterrupt: raise finally: sys.stdout = old if f > 0: self._reporter.doctest_fail(test.name, new.getvalue()) else: self._reporter.test_pass() sys.displayhook = old_displayhook interactive_printing.NO_GLOBAL = False pprint_use_unicode(use_unicode_prev) self._reporter.leaving_filename() def get_test_files(self, dir, pat='*.py', init_only=True): r""" Returns the list of \*.py files (default) from which docstrings will be tested which are at or below directory ``dir``. By default, only those that have an __init__.py in their parent directory and do not start with ``test_`` will be included. """ def importable(x): """ Checks if given pathname x is an importable module by checking for __init__.py file. Returns True/False. Currently we only test if the __init__.py file exists in the directory with the file "x" (in theory we should also test all the parent dirs). """ init_py = os.path.join(os.path.dirname(x), "__init__.py") return os.path.exists(init_py) dir = os.path.join(self._root_dir, convert_to_native_paths([dir])[0]) g = [] for path, folders, files in os.walk(dir): g.extend([os.path.join(path, f) for f in files if not f.startswith('test_') and fnmatch(f, pat)]) if init_only: # skip files that are not importable (i.e. missing __init__.py) g = [x for x in g if importable(x)] return [os.path.normcase(gi) for gi in g] def _check_dependencies(self, executables=(), modules=(), disable_viewers=(), python_version=(3, 5)): """ Checks if the dependencies for the test are installed. Raises ``DependencyError`` it at least one dependency is not installed. """ for executable in executables: if not shutil.which(executable): raise DependencyError("Could not find %s" % executable) for module in modules: if module == 'matplotlib': matplotlib = import_module( 'matplotlib', import_kwargs={'fromlist': ['pyplot', 'cm', 'collections']}, min_module_version='1.0.0', catch=(RuntimeError,)) if matplotlib is None: raise DependencyError("Could not import matplotlib") else: if not import_module(module): raise DependencyError("Could not import %s" % module) if disable_viewers: tempdir = tempfile.mkdtemp() os.environ['PATH'] = '%s:%s' % (tempdir, os.environ['PATH']) vw = ('#!/usr/bin/env {}\n' 'import sys\n' 'if len(sys.argv) <= 1:\n' ' exit("wrong number of args")\n').format( 'python3' if PY3 else 'python') for viewer in disable_viewers: with open(os.path.join(tempdir, viewer), 'w') as fh: fh.write(vw) # make the file executable os.chmod(os.path.join(tempdir, viewer), stat.S_IREAD | stat.S_IWRITE | stat.S_IXUSR) if python_version: if sys.version_info < python_version: raise DependencyError("Requires Python >= " + '.'.join(map(str, python_version))) if 'pyglet' in modules: # monkey-patch pyglet s.t. it does not open a window during # doctesting import pyglet class DummyWindow(object): def __init__(self, *args, **kwargs): self.has_exit = True self.width = 600 self.height = 400 def set_vsync(self, x): pass def switch_to(self): pass def push_handlers(self, x): pass def close(self): pass pyglet.window.Window = DummyWindow class SymPyDocTestFinder(DocTestFinder): """ A class used to extract the DocTests that are relevant to a given object, from its docstring and the docstrings of its contained objects. Doctests can currently be extracted from the following object types: modules, functions, classes, methods, staticmethods, classmethods, and properties. Modified from doctest's version to look harder for code that appears comes from a different module. For example, the @vectorize decorator makes it look like functions come from multidimensional.py even though their code exists elsewhere. """ def _find(self, tests, obj, name, module, source_lines, globs, seen): """ Find tests for the given object and any contained objects, and add them to ``tests``. """ if self._verbose: print('Finding tests in %s' % name) # If we've already processed this object, then ignore it. if id(obj) in seen: return seen[id(obj)] = 1 # Make sure we don't run doctests for classes outside of sympy, such # as in numpy or scipy. if inspect.isclass(obj): if obj.__module__.split('.')[0] != 'sympy': return # Find a test for this object, and add it to the list of tests. test = self._get_test(obj, name, module, globs, source_lines) if test is not None: tests.append(test) if not self._recurse: return # Look for tests in a module's contained objects. if inspect.ismodule(obj): for rawname, val in obj.__dict__.items(): # Recurse to functions & classes. if inspect.isfunction(val) or inspect.isclass(val): # Make sure we don't run doctests functions or classes # from different modules if val.__module__ != module.__name__: continue assert self._from_module(module, val), \ "%s is not in module %s (rawname %s)" % (val, module, rawname) try: valname = '%s.%s' % (name, rawname) self._find(tests, val, valname, module, source_lines, globs, seen) except KeyboardInterrupt: raise # Look for tests in a module's __test__ dictionary. for valname, val in getattr(obj, '__test__', {}).items(): if not isinstance(valname, str): raise ValueError("SymPyDocTestFinder.find: __test__ keys " "must be strings: %r" % (type(valname),)) if not (inspect.isfunction(val) or inspect.isclass(val) or inspect.ismethod(val) or inspect.ismodule(val) or isinstance(val, str)): raise ValueError("SymPyDocTestFinder.find: __test__ values " "must be strings, functions, methods, " "classes, or modules: %r" % (type(val),)) valname = '%s.__test__.%s' % (name, valname) self._find(tests, val, valname, module, source_lines, globs, seen) # Look for tests in a class's contained objects. if inspect.isclass(obj): for valname, val in obj.__dict__.items(): # Special handling for staticmethod/classmethod. if isinstance(val, staticmethod): val = getattr(obj, valname) if isinstance(val, classmethod): val = getattr(obj, valname).__func__ # Recurse to methods, properties, and nested classes. if ((inspect.isfunction(unwrap(val)) or inspect.isclass(val) or isinstance(val, property)) and self._from_module(module, val)): # Make sure we don't run doctests functions or classes # from different modules if isinstance(val, property): if hasattr(val.fget, '__module__'): if val.fget.__module__ != module.__name__: continue else: if val.__module__ != module.__name__: continue assert self._from_module(module, val), \ "%s is not in module %s (valname %s)" % ( val, module, valname) valname = '%s.%s' % (name, valname) self._find(tests, val, valname, module, source_lines, globs, seen) def _get_test(self, obj, name, module, globs, source_lines): """ Return a DocTest for the given object, if it defines a docstring; otherwise, return None. """ lineno = None # Extract the object's docstring. If it doesn't have one, # then return None (no test for this object). if isinstance(obj, str): # obj is a string in the case for objects in the polys package. # Note that source_lines is a binary string (compiled polys # modules), which can't be handled by _find_lineno so determine # the line number here. docstring = obj matches = re.findall(r"line \d+", name) assert len(matches) == 1, \ "string '%s' does not contain lineno " % name # NOTE: this is not the exact linenumber but its better than no # lineno ;) lineno = int(matches[0][5:]) else: try: if obj.__doc__ is None: docstring = '' else: docstring = obj.__doc__ if not isinstance(docstring, str): docstring = str(docstring) except (TypeError, AttributeError): docstring = '' # Don't bother if the docstring is empty. if self._exclude_empty and not docstring: return None # check that properties have a docstring because _find_lineno # assumes it if isinstance(obj, property): if obj.fget.__doc__ is None: return None # Find the docstring's location in the file. if lineno is None: obj = unwrap(obj) # handling of properties is not implemented in _find_lineno so do # it here if hasattr(obj, 'func_closure') and obj.func_closure is not None: tobj = obj.func_closure[0].cell_contents elif isinstance(obj, property): tobj = obj.fget else: tobj = obj lineno = self._find_lineno(tobj, source_lines) if lineno is None: return None # Return a DocTest for this object. if module is None: filename = None else: filename = getattr(module, '__file__', module.__name__) if filename[-4:] in (".pyc", ".pyo"): filename = filename[:-1] globs['_doctest_depends_on'] = getattr(obj, '_doctest_depends_on', {}) return self._parser.get_doctest(docstring, globs, name, filename, lineno) class SymPyDocTestRunner(DocTestRunner): """ A class used to run DocTest test cases, and accumulate statistics. The ``run`` method is used to process a single DocTest case. It returns a tuple ``(f, t)``, where ``t`` is the number of test cases tried, and ``f`` is the number of test cases that failed. Modified from the doctest version to not reset the sys.displayhook (see issue 5140). See the docstring of the original DocTestRunner for more information. """ def run(self, test, compileflags=None, out=None, clear_globs=True): """ Run the examples in ``test``, and display the results using the writer function ``out``. The examples are run in the namespace ``test.globs``. If ``clear_globs`` is true (the default), then this namespace will be cleared after the test runs, to help with garbage collection. If you would like to examine the namespace after the test completes, then use ``clear_globs=False``. ``compileflags`` gives the set of flags that should be used by the Python compiler when running the examples. If not specified, then it will default to the set of future-import flags that apply to ``globs``. The output of each example is checked using ``SymPyDocTestRunner.check_output``, and the results are formatted by the ``SymPyDocTestRunner.report_*`` methods. """ self.test = test if compileflags is None: compileflags = pdoctest._extract_future_flags(test.globs) save_stdout = sys.stdout if out is None: out = save_stdout.write sys.stdout = self._fakeout # Patch pdb.set_trace to restore sys.stdout during interactive # debugging (so it's not still redirected to self._fakeout). # Note that the interactive output will go to *our* # save_stdout, even if that's not the real sys.stdout; this # allows us to write test cases for the set_trace behavior. save_set_trace = pdb.set_trace self.debugger = pdoctest._OutputRedirectingPdb(save_stdout) self.debugger.reset() pdb.set_trace = self.debugger.set_trace # Patch linecache.getlines, so we can see the example's source # when we're inside the debugger. self.save_linecache_getlines = pdoctest.linecache.getlines linecache.getlines = self.__patched_linecache_getlines # Fail for deprecation warnings with raise_on_deprecated(): try: test.globs['print_function'] = print_function return self.__run(test, compileflags, out) finally: sys.stdout = save_stdout pdb.set_trace = save_set_trace linecache.getlines = self.save_linecache_getlines if clear_globs: test.globs.clear() # We have to override the name mangled methods. monkeypatched_methods = [ 'patched_linecache_getlines', 'run', 'record_outcome' ] for method in monkeypatched_methods: oldname = '_DocTestRunner__' + method newname = '_SymPyDocTestRunner__' + method setattr(SymPyDocTestRunner, newname, getattr(DocTestRunner, oldname)) class SymPyOutputChecker(pdoctest.OutputChecker): """ Compared to the OutputChecker from the stdlib our OutputChecker class supports numerical comparison of floats occurring in the output of the doctest examples """ def __init__(self): # NOTE OutputChecker is an old-style class with no __init__ method, # so we can't call the base class version of __init__ here got_floats = r'(\d+\.\d*|\.\d+)' # floats in the 'want' string may contain ellipses want_floats = got_floats + r'(\.{3})?' front_sep = r'\s|\+|\-|\*|,' back_sep = front_sep + r'|j|e' fbeg = r'^%s(?=%s|$)' % (got_floats, back_sep) fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, got_floats, back_sep) self.num_got_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend)) fbeg = r'^%s(?=%s|$)' % (want_floats, back_sep) fmidend = r'(?<=%s)%s(?=%s|$)' % (front_sep, want_floats, back_sep) self.num_want_rgx = re.compile(r'(%s|%s)' %(fbeg, fmidend)) def check_output(self, want, got, optionflags): """ Return True iff the actual output from an example (`got`) matches the expected output (`want`). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See the documentation for `TestRunner` for more information about option flags. """ # Handle the common case first, for efficiency: # if they're string-identical, always return true. if got == want: return True # TODO parse integers as well ? # Parse floats and compare them. If some of the parsed floats contain # ellipses, skip the comparison. matches = self.num_got_rgx.finditer(got) numbers_got = [match.group(1) for match in matches] # list of strs matches = self.num_want_rgx.finditer(want) numbers_want = [match.group(1) for match in matches] # list of strs if len(numbers_got) != len(numbers_want): return False if len(numbers_got) > 0: nw_ = [] for ng, nw in zip(numbers_got, numbers_want): if '...' in nw: nw_.append(ng) continue else: nw_.append(nw) if abs(float(ng)-float(nw)) > 1e-5: return False got = self.num_got_rgx.sub(r'%s', got) got = got % tuple(nw_) # <BLANKLINE> can be used as a special sequence to signify a # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used. if not (optionflags & pdoctest.DONT_ACCEPT_BLANKLINE): # Replace <BLANKLINE> in want with a blank line. want = re.sub(r'(?m)^%s\s*?$' % re.escape(pdoctest.BLANKLINE_MARKER), '', want) # If a line in got contains only spaces, then remove the # spaces. got = re.sub(r'(?m)^\s*?$', '', got) if got == want: return True # This flag causes doctest to ignore any differences in the # contents of whitespace strings. Note that this can be used # in conjunction with the ELLIPSIS flag. if optionflags & pdoctest.NORMALIZE_WHITESPACE: got = ' '.join(got.split()) want = ' '.join(want.split()) if got == want: return True # The ELLIPSIS flag says to let the sequence "..." in `want` # match any substring in `got`. if optionflags & pdoctest.ELLIPSIS: if pdoctest._ellipsis_match(want, got): return True # We didn't find any match; return false. return False class Reporter(object): """ Parent class for all reporters. """ pass class PyTestReporter(Reporter): """ Py.test like reporter. Should produce output identical to py.test. """ def __init__(self, verbose=False, tb="short", colors=True, force_colors=False, split=None): self._verbose = verbose self._tb_style = tb self._colors = colors self._force_colors = force_colors self._xfailed = 0 self._xpassed = [] self._failed = [] self._failed_doctest = [] self._passed = 0 self._skipped = 0 self._exceptions = [] self._terminal_width = None self._default_width = 80 self._split = split self._active_file = '' self._active_f = None # TODO: Should these be protected? self.slow_test_functions = [] self.fast_test_functions = [] # this tracks the x-position of the cursor (useful for positioning # things on the screen), without the need for any readline library: self._write_pos = 0 self._line_wrap = False def root_dir(self, dir): self._root_dir = dir @property def terminal_width(self): if self._terminal_width is not None: return self._terminal_width def findout_terminal_width(): if sys.platform == "win32": # Windows support is based on: # # http://code.activestate.com/recipes/ # 440694-determine-size-of-console-window-on-windows/ from ctypes import windll, create_string_buffer h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) if res: import struct (_, _, _, _, _, left, _, right, _, _, _) = \ struct.unpack("hhhhHhhhhhh", csbi.raw) return right - left else: return self._default_width if hasattr(sys.stdout, 'isatty') and not sys.stdout.isatty(): return self._default_width # leave PIPEs alone try: process = subprocess.Popen(['stty', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = process.stdout.read() if PY3: stdout = stdout.decode("utf-8") except (OSError, IOError): pass else: # We support the following output formats from stty: # # 1) Linux -> columns 80 # 2) OS X -> 80 columns # 3) Solaris -> columns = 80 re_linux = r"columns\s+(?P<columns>\d+);" re_osx = r"(?P<columns>\d+)\s*columns;" re_solaris = r"columns\s+=\s+(?P<columns>\d+);" for regex in (re_linux, re_osx, re_solaris): match = re.search(regex, stdout) if match is not None: columns = match.group('columns') try: width = int(columns) except ValueError: pass if width != 0: return width return self._default_width width = findout_terminal_width() self._terminal_width = width return width def write(self, text, color="", align="left", width=None, force_colors=False): """ Prints a text on the screen. It uses sys.stdout.write(), so no readline library is necessary. Parameters ========== color : choose from the colors below, "" means default color align : "left"/"right", "left" is a normal print, "right" is aligned on the right-hand side of the screen, filled with spaces if necessary width : the screen width """ color_templates = ( ("Black", "0;30"), ("Red", "0;31"), ("Green", "0;32"), ("Brown", "0;33"), ("Blue", "0;34"), ("Purple", "0;35"), ("Cyan", "0;36"), ("LightGray", "0;37"), ("DarkGray", "1;30"), ("LightRed", "1;31"), ("LightGreen", "1;32"), ("Yellow", "1;33"), ("LightBlue", "1;34"), ("LightPurple", "1;35"), ("LightCyan", "1;36"), ("White", "1;37"), ) colors = {} for name, value in color_templates: colors[name] = value c_normal = '\033[0m' c_color = '\033[%sm' if width is None: width = self.terminal_width if align == "right": if self._write_pos + len(text) > width: # we don't fit on the current line, create a new line self.write("\n") self.write(" "*(width - self._write_pos - len(text))) if not self._force_colors and hasattr(sys.stdout, 'isatty') and not \ sys.stdout.isatty(): # the stdout is not a terminal, this for example happens if the # output is piped to less, e.g. "bin/test | less". In this case, # the terminal control sequences would be printed verbatim, so # don't use any colors. color = "" elif sys.platform == "win32": # Windows consoles don't support ANSI escape sequences color = "" elif not self._colors: color = "" if self._line_wrap: if text[0] != "\n": sys.stdout.write("\n") # Avoid UnicodeEncodeError when printing out test failures if PY3 and IS_WINDOWS: text = text.encode('raw_unicode_escape').decode('utf8', 'ignore') elif PY3 and not sys.stdout.encoding.lower().startswith('utf'): text = text.encode(sys.stdout.encoding, 'backslashreplace' ).decode(sys.stdout.encoding) if color == "": sys.stdout.write(text) else: sys.stdout.write("%s%s%s" % (c_color % colors[color], text, c_normal)) sys.stdout.flush() l = text.rfind("\n") if l == -1: self._write_pos += len(text) else: self._write_pos = len(text) - l - 1 self._line_wrap = self._write_pos >= width self._write_pos %= width def write_center(self, text, delim="="): width = self.terminal_width if text != "": text = " %s " % text idx = (width - len(text)) // 2 t = delim*idx + text + delim*(width - idx - len(text)) self.write(t + "\n") def write_exception(self, e, val, tb): # remove the first item, as that is always runtests.py tb = tb.tb_next t = traceback.format_exception(e, val, tb) self.write("".join(t)) def start(self, seed=None, msg="test process starts"): self.write_center(msg) executable = sys.executable v = tuple(sys.version_info) python_version = "%s.%s.%s-%s-%s" % v implementation = platform.python_implementation() if implementation == 'PyPy': implementation += " %s.%s.%s-%s-%s" % sys.pypy_version_info self.write("executable: %s (%s) [%s]\n" % (executable, python_version, implementation)) from sympy.utilities.misc import ARCH self.write("architecture: %s\n" % ARCH) from sympy.core.cache import USE_CACHE self.write("cache: %s\n" % USE_CACHE) from sympy.core.compatibility import GROUND_TYPES, HAS_GMPY version = '' if GROUND_TYPES =='gmpy': if HAS_GMPY == 1: import gmpy elif HAS_GMPY == 2: import gmpy2 as gmpy version = gmpy.version() self.write("ground types: %s %s\n" % (GROUND_TYPES, version)) numpy = import_module('numpy') self.write("numpy: %s\n" % (None if not numpy else numpy.__version__)) if seed is not None: self.write("random seed: %d\n" % seed) from sympy.utilities.misc import HASH_RANDOMIZATION self.write("hash randomization: ") hash_seed = os.getenv("PYTHONHASHSEED") or '0' if HASH_RANDOMIZATION and (hash_seed == "random" or int(hash_seed)): self.write("on (PYTHONHASHSEED=%s)\n" % hash_seed) else: self.write("off\n") if self._split: self.write("split: %s\n" % self._split) self.write('\n') self._t_start = clock() def finish(self): self._t_end = clock() self.write("\n") global text, linelen text = "tests finished: %d passed, " % self._passed linelen = len(text) def add_text(mytext): global text, linelen """Break new text if too long.""" if linelen + len(mytext) > self.terminal_width: text += '\n' linelen = 0 text += mytext linelen += len(mytext) if len(self._failed) > 0: add_text("%d failed, " % len(self._failed)) if len(self._failed_doctest) > 0: add_text("%d failed, " % len(self._failed_doctest)) if self._skipped > 0: add_text("%d skipped, " % self._skipped) if self._xfailed > 0: add_text("%d expected to fail, " % self._xfailed) if len(self._xpassed) > 0: add_text("%d expected to fail but passed, " % len(self._xpassed)) if len(self._exceptions) > 0: add_text("%d exceptions, " % len(self._exceptions)) add_text("in %.2f seconds" % (self._t_end - self._t_start)) if self.slow_test_functions: self.write_center('slowest tests', '_') sorted_slow = sorted(self.slow_test_functions, key=lambda r: r[1]) for slow_func_name, taken in sorted_slow: print('%s - Took %.3f seconds' % (slow_func_name, taken)) if self.fast_test_functions: self.write_center('unexpectedly fast tests', '_') sorted_fast = sorted(self.fast_test_functions, key=lambda r: r[1]) for fast_func_name, taken in sorted_fast: print('%s - Took %.3f seconds' % (fast_func_name, taken)) if len(self._xpassed) > 0: self.write_center("xpassed tests", "_") for e in self._xpassed: self.write("%s: %s\n" % (e[0], e[1])) self.write("\n") if self._tb_style != "no" and len(self._exceptions) > 0: for e in self._exceptions: filename, f, (t, val, tb) = e self.write_center("", "_") if f is None: s = "%s" % filename else: s = "%s:%s" % (filename, f.__name__) self.write_center(s, "_") self.write_exception(t, val, tb) self.write("\n") if self._tb_style != "no" and len(self._failed) > 0: for e in self._failed: filename, f, (t, val, tb) = e self.write_center("", "_") self.write_center("%s:%s" % (filename, f.__name__), "_") self.write_exception(t, val, tb) self.write("\n") if self._tb_style != "no" and len(self._failed_doctest) > 0: for e in self._failed_doctest: filename, msg = e self.write_center("", "_") self.write_center("%s" % filename, "_") self.write(msg) self.write("\n") self.write_center(text) ok = len(self._failed) == 0 and len(self._exceptions) == 0 and \ len(self._failed_doctest) == 0 if not ok: self.write("DO *NOT* COMMIT!\n") return ok def entering_filename(self, filename, n): rel_name = filename[len(self._root_dir) + 1:] self._active_file = rel_name self._active_file_error = False self.write(rel_name) self.write("[%d] " % n) def leaving_filename(self): self.write(" ") if self._active_file_error: self.write("[FAIL]", "Red", align="right") else: self.write("[OK]", "Green", align="right") self.write("\n") if self._verbose: self.write("\n") def entering_test(self, f): self._active_f = f if self._verbose: self.write("\n" + f.__name__ + " ") def test_xfail(self): self._xfailed += 1 self.write("f", "Green") def test_xpass(self, v): message = str(v) self._xpassed.append((self._active_file, message)) self.write("X", "Green") def test_fail(self, exc_info): self._failed.append((self._active_file, self._active_f, exc_info)) self.write("F", "Red") self._active_file_error = True def doctest_fail(self, name, error_msg): # the first line contains "******", remove it: error_msg = "\n".join(error_msg.split("\n")[1:]) self._failed_doctest.append((name, error_msg)) self.write("F", "Red") self._active_file_error = True def test_pass(self, char="."): self._passed += 1 if self._verbose: self.write("ok", "Green") else: self.write(char, "Green") def test_skip(self, v=None): char = "s" self._skipped += 1 if v is not None: message = str(v) if message == "KeyboardInterrupt": char = "K" elif message == "Timeout": char = "T" elif message == "Slow": char = "w" if self._verbose: if v is not None: self.write(message + ' ', "Blue") else: self.write(" - ", "Blue") self.write(char, "Blue") def test_exception(self, exc_info): self._exceptions.append((self._active_file, self._active_f, exc_info)) if exc_info[0] is TimeOutError: self.write("T", "Red") else: self.write("E", "Red") self._active_file_error = True def import_error(self, filename, exc_info): self._exceptions.append((filename, None, exc_info)) rel_name = filename[len(self._root_dir) + 1:] self.write(rel_name) self.write("[?] Failed to import", "Red") self.write(" ") self.write("[FAIL]", "Red", align="right") self.write("\n")
387952744c4c8d7e6c54ebc39180d6a926ae7347bd8c324dabe6bfe9b4ada3b9
r"""Module that defines indexed objects The classes ``IndexedBase``, ``Indexed``, and ``Idx`` represent a matrix element ``M[i, j]`` as in the following diagram:: 1) The Indexed class represents the entire indexed object. | ___|___ ' ' M[i, j] / \__\______ | | | | | 2) The Idx class represents indices; each Idx can | optionally contain information about its range. | 3) IndexedBase represents the 'stem' of an indexed object, here `M`. The stem used by itself is usually taken to represent the entire array. There can be any number of indices on an Indexed object. No transformation properties are implemented in these Base objects, but implicit contraction of repeated indices is supported. Note that the support for complicated (i.e. non-atomic) integer expressions as indices is limited. (This should be improved in future releases.) Examples ======== To express the above matrix element example you would write: >>> from sympy import symbols, IndexedBase, Idx >>> M = IndexedBase('M') >>> i, j = symbols('i j', cls=Idx) >>> M[i, j] M[i, j] Repeated indices in a product implies a summation, so to express a matrix-vector product in terms of Indexed objects: >>> x = IndexedBase('x') >>> M[i, j]*x[j] M[i, j]*x[j] If the indexed objects will be converted to component based arrays, e.g. with the code printers or the autowrap framework, you also need to provide (symbolic or numerical) dimensions. This can be done by passing an optional shape parameter to IndexedBase upon construction: >>> dim1, dim2 = symbols('dim1 dim2', integer=True) >>> A = IndexedBase('A', shape=(dim1, 2*dim1, dim2)) >>> A.shape (dim1, 2*dim1, dim2) >>> A[i, j, 3].shape (dim1, 2*dim1, dim2) If an IndexedBase object has no shape information, it is assumed that the array is as large as the ranges of its indices: >>> n, m = symbols('n m', integer=True) >>> i = Idx('i', m) >>> j = Idx('j', n) >>> M[i, j].shape (m, n) >>> M[i, j].ranges [(0, m - 1), (0, n - 1)] The above can be compared with the following: >>> A[i, 2, j].shape (dim1, 2*dim1, dim2) >>> A[i, 2, j].ranges [(0, m - 1), None, (0, n - 1)] To analyze the structure of indexed expressions, you can use the methods get_indices() and get_contraction_structure(): >>> from sympy.tensor import get_indices, get_contraction_structure >>> get_indices(A[i, j, j]) ({i}, {}) >>> get_contraction_structure(A[i, j, j]) {(j,): {A[i, j, j]}} See the appropriate docstrings for a detailed explanation of the output. """ # TODO: (some ideas for improvement) # # o test and guarantee numpy compatibility # - implement full support for broadcasting # - strided arrays # # o more functions to analyze indexed expressions # - identify standard constructs, e.g matrix-vector product in a subexpression # # o functions to generate component based arrays (numpy and sympy.Matrix) # - generate a single array directly from Indexed # - convert simple sub-expressions # # o sophisticated indexing (possibly in subclasses to preserve simplicity) # - Idx with range smaller than dimension of Indexed # - Idx with stepsize != 1 # - Idx with step determined by function call from __future__ import print_function, division from sympy import Number from sympy.core.assumptions import StdFactKB from sympy.core import Expr, Tuple, sympify, S from sympy.core.symbol import _filter_assumptions, Symbol from sympy.core.compatibility import (is_sequence, NotIterable, Iterable) from sympy.core.logic import fuzzy_bool, fuzzy_not from sympy.core.sympify import _sympify from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.multipledispatch import dispatch class IndexException(Exception): pass class Indexed(Expr): """Represents a mathematical object with indices. >>> from sympy import Indexed, IndexedBase, Idx, symbols >>> i, j = symbols('i j', cls=Idx) >>> Indexed('A', i, j) A[i, j] It is recommended that ``Indexed`` objects be created by indexing ``IndexedBase``: ``IndexedBase('A')[i, j]`` instead of ``Indexed(IndexedBase('A'), i, j)``. >>> A = IndexedBase('A') >>> a_ij = A[i, j] # Prefer this, >>> b_ij = Indexed(A, i, j) # over this. >>> a_ij == b_ij True """ is_commutative = True is_Indexed = True is_symbol = True is_Atom = True def __new__(cls, base, *args, **kw_args): from sympy.utilities.misc import filldedent from sympy.tensor.array.ndim_array import NDimArray from sympy.matrices.matrices import MatrixBase if not args: raise IndexException("Indexed needs at least one index.") if isinstance(base, (str, Symbol)): base = IndexedBase(base) elif not hasattr(base, '__getitem__') and not isinstance(base, IndexedBase): raise TypeError(filldedent(""" The base can only be replaced with a string, Symbol, IndexedBase or an object with a method for getting items (i.e. an object with a `__getitem__` method). """)) args = list(map(sympify, args)) if isinstance(base, (NDimArray, Iterable, Tuple, MatrixBase)) and all([i.is_number for i in args]): if len(args) == 1: return base[args[0]] else: return base[args] obj = Expr.__new__(cls, base, *args, **kw_args) try: IndexedBase._set_assumptions(obj, base.assumptions0) except AttributeError: IndexedBase._set_assumptions(obj, {}) return obj def _hashable_content(self): return super(Indexed, self)._hashable_content() + tuple(sorted(self.assumptions0.items())) @property def name(self): return str(self) @property def _diff_wrt(self): """Allow derivatives with respect to an ``Indexed`` object.""" return True def _eval_derivative(self, wrt): from sympy.tensor.array.ndim_array import NDimArray if isinstance(wrt, Indexed) and wrt.base == self.base: if len(self.indices) != len(wrt.indices): msg = "Different # of indices: d({!s})/d({!s})".format(self, wrt) raise IndexException(msg) result = S.One for index1, index2 in zip(self.indices, wrt.indices): result *= KroneckerDelta(index1, index2) return result elif isinstance(self.base, NDimArray): from sympy.tensor.array import derive_by_array return Indexed(derive_by_array(self.base, wrt), *self.args[1:]) else: if Tuple(self.indices).has(wrt): return S.NaN return S.Zero @property def assumptions0(self): return {k: v for k, v in self._assumptions.items() if v is not None} @property def base(self): """Returns the ``IndexedBase`` of the ``Indexed`` object. Examples ======== >>> from sympy import Indexed, IndexedBase, Idx, symbols >>> i, j = symbols('i j', cls=Idx) >>> Indexed('A', i, j).base A >>> B = IndexedBase('B') >>> B == B[i, j].base True """ return self.args[0] @property def indices(self): """ Returns the indices of the ``Indexed`` object. Examples ======== >>> from sympy import Indexed, Idx, symbols >>> i, j = symbols('i j', cls=Idx) >>> Indexed('A', i, j).indices (i, j) """ return self.args[1:] @property def rank(self): """ Returns the rank of the ``Indexed`` object. Examples ======== >>> from sympy import Indexed, Idx, symbols >>> i, j, k, l, m = symbols('i:m', cls=Idx) >>> Indexed('A', i, j).rank 2 >>> q = Indexed('A', i, j, k, l, m) >>> q.rank 5 >>> q.rank == len(q.indices) True """ return len(self.args) - 1 @property def shape(self): """Returns a list with dimensions of each index. Dimensions is a property of the array, not of the indices. Still, if the ``IndexedBase`` does not define a shape attribute, it is assumed that the ranges of the indices correspond to the shape of the array. >>> from sympy import IndexedBase, Idx, symbols >>> n, m = symbols('n m', integer=True) >>> i = Idx('i', m) >>> j = Idx('j', m) >>> A = IndexedBase('A', shape=(n, n)) >>> B = IndexedBase('B') >>> A[i, j].shape (n, n) >>> B[i, j].shape (m, m) """ from sympy.utilities.misc import filldedent if self.base.shape: return self.base.shape sizes = [] for i in self.indices: upper = getattr(i, 'upper', None) lower = getattr(i, 'lower', None) if None in (upper, lower): raise IndexException(filldedent(""" Range is not defined for all indices in: %s""" % self)) try: size = upper - lower + 1 except TypeError: raise IndexException(filldedent(""" Shape cannot be inferred from Idx with undefined range: %s""" % self)) sizes.append(size) return Tuple(*sizes) @property def ranges(self): """Returns a list of tuples with lower and upper range of each index. If an index does not define the data members upper and lower, the corresponding slot in the list contains ``None`` instead of a tuple. Examples ======== >>> from sympy import Indexed,Idx, symbols >>> Indexed('A', Idx('i', 2), Idx('j', 4), Idx('k', 8)).ranges [(0, 1), (0, 3), (0, 7)] >>> Indexed('A', Idx('i', 3), Idx('j', 3), Idx('k', 3)).ranges [(0, 2), (0, 2), (0, 2)] >>> x, y, z = symbols('x y z', integer=True) >>> Indexed('A', x, y, z).ranges [None, None, None] """ ranges = [] for i in self.indices: sentinel = object() upper = getattr(i, 'upper', sentinel) lower = getattr(i, 'lower', sentinel) if sentinel not in (upper, lower): ranges.append(Tuple(lower, upper)) else: ranges.append(None) return ranges def _sympystr(self, p): indices = list(map(p.doprint, self.indices)) return "%s[%s]" % (p.doprint(self.base), ", ".join(indices)) @property def free_symbols(self): base_free_symbols = self.base.free_symbols indices_free_symbols = { fs for i in self.indices for fs in i.free_symbols} if base_free_symbols: return {self} | base_free_symbols | indices_free_symbols else: return indices_free_symbols @property def expr_free_symbols(self): return {self} class IndexedBase(Expr, NotIterable): """Represent the base or stem of an indexed object The IndexedBase class represent an array that contains elements. The main purpose of this class is to allow the convenient creation of objects of the Indexed class. The __getitem__ method of IndexedBase returns an instance of Indexed. Alone, without indices, the IndexedBase class can be used as a notation for e.g. matrix equations, resembling what you could do with the Symbol class. But, the IndexedBase class adds functionality that is not available for Symbol instances: - An IndexedBase object can optionally store shape information. This can be used in to check array conformance and conditions for numpy broadcasting. (TODO) - An IndexedBase object implements syntactic sugar that allows easy symbolic representation of array operations, using implicit summation of repeated indices. - The IndexedBase object symbolizes a mathematical structure equivalent to arrays, and is recognized as such for code generation and automatic compilation and wrapping. >>> from sympy.tensor import IndexedBase, Idx >>> from sympy import symbols >>> A = IndexedBase('A'); A A >>> type(A) <class 'sympy.tensor.indexed.IndexedBase'> When an IndexedBase object receives indices, it returns an array with named axes, represented by an Indexed object: >>> i, j = symbols('i j', integer=True) >>> A[i, j, 2] A[i, j, 2] >>> type(A[i, j, 2]) <class 'sympy.tensor.indexed.Indexed'> The IndexedBase constructor takes an optional shape argument. If given, it overrides any shape information in the indices. (But not the index ranges!) >>> m, n, o, p = symbols('m n o p', integer=True) >>> i = Idx('i', m) >>> j = Idx('j', n) >>> A[i, j].shape (m, n) >>> B = IndexedBase('B', shape=(o, p)) >>> B[i, j].shape (o, p) Assumptions can be specified with keyword arguments the same way as for Symbol: >>> A_real = IndexedBase('A', real=True) >>> A_real.is_real True >>> A != A_real True Assumptions can also be inherited if a Symbol is used to initialize the IndexedBase: >>> I = symbols('I', integer=True) >>> C_inherit = IndexedBase(I) >>> C_explicit = IndexedBase('I', integer=True) >>> C_inherit == C_explicit True """ is_commutative = True is_symbol = True is_Atom = True @staticmethod def _set_assumptions(obj, assumptions): """Set assumptions on obj, making sure to apply consistent values.""" tmp_asm_copy = assumptions.copy() is_commutative = fuzzy_bool(assumptions.get('commutative', True)) assumptions['commutative'] = is_commutative obj._assumptions = StdFactKB(assumptions) obj._assumptions._generator = tmp_asm_copy # Issue #8873 def __new__(cls, label, shape=None, *, offset=S.Zero, strides=None, **kw_args): from sympy import MatrixBase, NDimArray assumptions, kw_args = _filter_assumptions(kw_args) if isinstance(label, str): label = Symbol(label, **assumptions) elif isinstance(label, Symbol): assumptions = label._merge(assumptions) elif isinstance(label, (MatrixBase, NDimArray)): return label elif isinstance(label, Iterable): return _sympify(label) else: label = _sympify(label) if is_sequence(shape): shape = Tuple(*shape) elif shape is not None: shape = Tuple(shape) if shape is not None: obj = Expr.__new__(cls, label, shape) else: obj = Expr.__new__(cls, label) obj._shape = shape obj._offset = offset obj._strides = strides obj._name = str(label) IndexedBase._set_assumptions(obj, assumptions) return obj @property def name(self): return self._name def _hashable_content(self): return super(IndexedBase, self)._hashable_content() + tuple(sorted(self.assumptions0.items())) @property def assumptions0(self): return {k: v for k, v in self._assumptions.items() if v is not None} def __getitem__(self, indices, **kw_args): if is_sequence(indices): # Special case needed because M[*my_tuple] is a syntax error. if self.shape and len(self.shape) != len(indices): raise IndexException("Rank mismatch.") return Indexed(self, *indices, **kw_args) else: if self.shape and len(self.shape) != 1: raise IndexException("Rank mismatch.") return Indexed(self, indices, **kw_args) @property def shape(self): """Returns the shape of the ``IndexedBase`` object. Examples ======== >>> from sympy import IndexedBase, Idx >>> from sympy.abc import x, y >>> IndexedBase('A', shape=(x, y)).shape (x, y) Note: If the shape of the ``IndexedBase`` is specified, it will override any shape information given by the indices. >>> A = IndexedBase('A', shape=(x, y)) >>> B = IndexedBase('B') >>> i = Idx('i', 2) >>> j = Idx('j', 1) >>> A[i, j].shape (x, y) >>> B[i, j].shape (2, 1) """ return self._shape @property def strides(self): """Returns the strided scheme for the ``IndexedBase`` object. Normally this is a tuple denoting the number of steps to take in the respective dimension when traversing an array. For code generation purposes strides='C' and strides='F' can also be used. strides='C' would mean that code printer would unroll in row-major order and 'F' means unroll in column major order. """ return self._strides @property def offset(self): """Returns the offset for the ``IndexedBase`` object. This is the value added to the resulting index when the 2D Indexed object is unrolled to a 1D form. Used in code generation. Examples ========== >>> from sympy.printing import ccode >>> from sympy.tensor import IndexedBase, Idx >>> from sympy import symbols >>> l, m, n, o = symbols('l m n o', integer=True) >>> A = IndexedBase('A', strides=(l, m, n), offset=o) >>> i, j, k = map(Idx, 'ijk') >>> ccode(A[i, j, k]) 'A[l*i + m*j + n*k + o]' """ return self._offset @property def label(self): """Returns the label of the ``IndexedBase`` object. Examples ======== >>> from sympy import IndexedBase >>> from sympy.abc import x, y >>> IndexedBase('A', shape=(x, y)).label A """ return self.args[0] def _sympystr(self, p): return p.doprint(self.label) class Idx(Expr): """Represents an integer index as an ``Integer`` or integer expression. There are a number of ways to create an ``Idx`` object. The constructor takes two arguments: ``label`` An integer or a symbol that labels the index. ``range`` Optionally you can specify a range as either * ``Symbol`` or integer: This is interpreted as a dimension. Lower and upper bounds are set to ``0`` and ``range - 1``, respectively. * ``tuple``: The two elements are interpreted as the lower and upper bounds of the range, respectively. Note: bounds of the range are assumed to be either integer or infinite (oo and -oo are allowed to specify an unbounded range). If ``n`` is given as a bound, then ``n.is_integer`` must not return false. For convenience, if the label is given as a string it is automatically converted to an integer symbol. (Note: this conversion is not done for range or dimension arguments.) Examples ======== >>> from sympy import Idx, symbols, oo >>> n, i, L, U = symbols('n i L U', integer=True) If a string is given for the label an integer ``Symbol`` is created and the bounds are both ``None``: >>> idx = Idx('qwerty'); idx qwerty >>> idx.lower, idx.upper (None, None) Both upper and lower bounds can be specified: >>> idx = Idx(i, (L, U)); idx i >>> idx.lower, idx.upper (L, U) When only a single bound is given it is interpreted as the dimension and the lower bound defaults to 0: >>> idx = Idx(i, n); idx.lower, idx.upper (0, n - 1) >>> idx = Idx(i, 4); idx.lower, idx.upper (0, 3) >>> idx = Idx(i, oo); idx.lower, idx.upper (0, oo) """ is_integer = True is_finite = True is_real = True is_symbol = True is_Atom = True _diff_wrt = True def __new__(cls, label, range=None, **kw_args): from sympy.utilities.misc import filldedent if isinstance(label, str): label = Symbol(label, integer=True) label, range = list(map(sympify, (label, range))) if label.is_Number: if not label.is_integer: raise TypeError("Index is not an integer number.") return label if not label.is_integer: raise TypeError("Idx object requires an integer label.") elif is_sequence(range): if len(range) != 2: raise ValueError(filldedent(""" Idx range tuple must have length 2, but got %s""" % len(range))) for bound in range: if (bound.is_integer is False and bound is not S.Infinity and bound is not S.NegativeInfinity): raise TypeError("Idx object requires integer bounds.") args = label, Tuple(*range) elif isinstance(range, Expr): if range is not S.Infinity and fuzzy_not(range.is_integer): raise TypeError("Idx object requires an integer dimension.") args = label, Tuple(0, range - 1) elif range: raise TypeError(filldedent(""" The range must be an ordered iterable or integer SymPy expression.""")) else: args = label, obj = Expr.__new__(cls, *args, **kw_args) obj._assumptions["finite"] = True obj._assumptions["real"] = True return obj @property def label(self): """Returns the label (Integer or integer expression) of the Idx object. Examples ======== >>> from sympy import Idx, Symbol >>> x = Symbol('x', integer=True) >>> Idx(x).label x >>> j = Symbol('j', integer=True) >>> Idx(j).label j >>> Idx(j + 1).label j + 1 """ return self.args[0] @property def lower(self): """Returns the lower bound of the ``Idx``. Examples ======== >>> from sympy import Idx >>> Idx('j', 2).lower 0 >>> Idx('j', 5).lower 0 >>> Idx('j').lower is None True """ try: return self.args[1][0] except IndexError: return @property def upper(self): """Returns the upper bound of the ``Idx``. Examples ======== >>> from sympy import Idx >>> Idx('j', 2).upper 1 >>> Idx('j', 5).upper 4 >>> Idx('j').upper is None True """ try: return self.args[1][1] except IndexError: return def _sympystr(self, p): return p.doprint(self.label) @property def name(self): return self.label.name if self.label.is_Symbol else str(self.label) @property def free_symbols(self): return {self} @dispatch(Idx, Idx) def _eval_is_ge(lhs, rhs): # noqa:F811 other_upper = rhs if rhs.upper is None else rhs.upper other_lower = rhs if rhs.lower is None else rhs.lower if lhs.lower is not None and (lhs.lower >= other_upper) == True: return True if lhs.upper is not None and (lhs.upper < other_lower) == True: return False return None @dispatch(Idx, Number) # type:ignore def _eval_is_ge(lhs, rhs): # noqa:F811 other_upper = rhs other_lower = rhs if lhs.lower is not None and (lhs.lower >= other_upper) == True: return True if lhs.upper is not None and (lhs.upper < other_lower) == True: return False return None @dispatch(Number, Idx) # type:ignore def _eval_is_ge(lhs, rhs): # noqa:F811 other_upper = lhs other_lower = lhs if rhs.upper is not None and (rhs.upper <= other_lower) == True: return True if rhs.lower is not None and (rhs.lower > other_upper) == True: return False return None
9812267d40fa1186e189be83343995a4a6a382c118775570e9a29e3c1b5c7e58
from __future__ import division, print_function from contextlib import contextmanager from threading import local from sympy.core.function import expand_mul from sympy.simplify.simplify import dotprodsimp as _dotprodsimp class DotProdSimpState(local): def __init__(self): self.state = None _dotprodsimp_state = DotProdSimpState() @contextmanager def dotprodsimp(x): old = _dotprodsimp_state.state try: _dotprodsimp_state.state = x yield finally: _dotprodsimp_state.state = old def _get_intermediate_simp(deffunc=lambda x: x, offfunc=lambda x: x, onfunc=_dotprodsimp, dotprodsimp=None): """Support function for controlling intermediate simplification. Returns a simplification function according to the global setting of dotprodsimp operation. ``deffunc`` - Function to be used by default. ``offfunc`` - Function to be used if dotprodsimp has been turned off. ``onfunc`` - Function to be used if dotprodsimp has been turned on. ``dotprodsimp`` - True, False or None. Will be overriden by global _dotprodsimp_state.state if that is not None. """ if dotprodsimp is False or _dotprodsimp_state.state is False: return offfunc if dotprodsimp is True or _dotprodsimp_state.state is True: return onfunc return deffunc # None, None def _get_intermediate_simp_bool(default=False, dotprodsimp=None): """Same as ``_get_intermediate_simp`` but returns bools instead of functions by default.""" return _get_intermediate_simp(default, False, True, dotprodsimp) def _iszero(x): """Returns True if x is zero.""" return getattr(x, 'is_zero', None) def _is_zero_after_expand_mul(x): """Tests by expand_mul only, suitable for polynomials and rational functions.""" return expand_mul(x) == 0
e86323dda9368342abed48017df152a6507a2016f0d00aaef1d5b4fb42a8a225
""" Basic methods common to all matrices to be used when creating more advanced matrices (e.g., matrices over rings, etc.). """ from sympy.core.logic import FuzzyBool from collections import defaultdict from inspect import isfunction from sympy.assumptions.refine import refine from sympy.core import SympifyError, Add from sympy.core.basic import Atom from sympy.core.compatibility import ( Iterable, as_int, is_sequence, reduce) from sympy.core.decorators import call_highest_priority 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)) 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__))
97ce76e3f0e6737f968bd1b93679085e2f3b253f4cd5607a898d71c2a7e97a9a
import random from sympy.core import SympifyError, Add from sympy.core.basic import Basic from sympy.core.compatibility import is_sequence, reduce from sympy.core.expr import Expr from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.functions.elementary.trigonometric import cos, sin from sympy.matrices.common import \ a2idx, classof, ShapeError from sympy.matrices.matrices import MatrixBase from sympy.simplify.simplify import simplify as _simplify from sympy.utilities.decorator import doctest_depends_on from sympy.utilities.misc import filldedent from .decompositions import _cholesky, _LDLdecomposition from .solvers import _lower_triangular_solve, _upper_triangular_solve def _iszero(x): """Returns True if x is zero.""" return x.is_zero def _compare_sequence(a, b): """Compares the elements of a list/tuple `a` and a list/tuple `b`. `_compare_sequence((1,2), [1, 2])` is True, whereas `(1,2) == [1, 2]` is False""" if type(a) is type(b): # if they are the same type, compare directly return a == b # there is no overhead for calling `tuple` on a # tuple return tuple(a) == tuple(b) class DenseMatrix(MatrixBase): is_MatrixExpr = False # type: bool _op_priority = 10.01 _class_priority = 4 def __eq__(self, other): other = sympify(other) self_shape = getattr(self, 'shape', None) other_shape = getattr(other, 'shape', None) if None in (self_shape, other_shape): return False if self_shape != other_shape: return False if isinstance(other, Matrix): return _compare_sequence(self._mat, other._mat) elif isinstance(other, MatrixBase): return _compare_sequence(self._mat, Matrix(other)._mat) def __getitem__(self, key): """Return portion of self defined by key. If the key involves a slice then a list will be returned (if key is a single slice) or a matrix (if key was a tuple involving a slice). Examples ======== >>> from sympy import Matrix, I >>> m = Matrix([ ... [1, 2 + I], ... [3, 4 ]]) If the key is a tuple that doesn't involve a slice then that element is returned: >>> m[1, 0] 3 When a tuple key involves a slice, a matrix is returned. Here, the first column is selected (all rows, column 0): >>> m[:, 0] Matrix([ [1], [3]]) If the slice is not a tuple then it selects from the underlying list of elements that are arranged in row order and a list is returned if a slice is involved: >>> m[0] 1 >>> m[::2] [1, 3] """ if isinstance(key, tuple): i, j = key try: i, j = self.key2ij(key) return self._mat[i*self.cols + j] except (TypeError, IndexError): if (isinstance(i, Expr) and not i.is_number) or (isinstance(j, Expr) and not j.is_number): if ((j < 0) is True) or ((j >= self.shape[1]) is True) or\ ((i < 0) is True) or ((i >= self.shape[0]) is True): raise ValueError("index out of boundary") from sympy.matrices.expressions.matexpr import MatrixElement return MatrixElement(self, i, j) if isinstance(i, slice): i = range(self.rows)[i] elif is_sequence(i): pass else: i = [i] if isinstance(j, slice): j = range(self.cols)[j] elif is_sequence(j): pass else: j = [j] return self.extract(i, j) else: # row-wise decomposition of matrix if isinstance(key, slice): return self._mat[key] return self._mat[a2idx(key)] def __setitem__(self, key, value): raise NotImplementedError() def _eval_add(self, other): # we assume both arguments are dense matrices since # sparse matrices have a higher priority mat = [a + b for a,b in zip(self._mat, other._mat)] return classof(self, other)._new(self.rows, self.cols, mat, copy=False) def _eval_extract(self, rowsList, colsList): mat = self._mat cols = self.cols indices = (i * cols + j for i in rowsList for j in colsList) return self._new(len(rowsList), len(colsList), list(mat[i] for i in indices), copy=False) def _eval_matrix_mul(self, other): other_len = other.rows*other.cols new_len = self.rows*other.cols new_mat = [self.zero]*new_len # if we multiply an n x 0 with a 0 x m, the # expected behavior is to produce an n x m matrix of zeros if self.cols != 0 and other.rows != 0: self_cols = self.cols mat = self._mat other_mat = other._mat for i in range(new_len): row, col = i // other.cols, i % other.cols row_indices = range(self_cols*row, self_cols*(row+1)) col_indices = range(col, other_len, other.cols) vec = [mat[a]*other_mat[b] for a, b in zip(row_indices, col_indices)] try: new_mat[i] = Add(*vec) except (TypeError, SympifyError): # Some matrices don't work with `sum` or `Add` # They don't work with `sum` because `sum` tries to add `0` # Fall back to a safe way to multiply if the `Add` fails. new_mat[i] = reduce(lambda a, b: a + b, vec) return classof(self, other)._new(self.rows, other.cols, new_mat, copy=False) def _eval_matrix_mul_elementwise(self, other): mat = [a*b for a,b in zip(self._mat, other._mat)] return classof(self, other)._new(self.rows, self.cols, mat, copy=False) def _eval_inverse(self, **kwargs): return self.inv(method=kwargs.get('method', 'GE'), iszerofunc=kwargs.get('iszerofunc', _iszero), try_block_diag=kwargs.get('try_block_diag', False)) def _eval_scalar_mul(self, other): mat = [other*a for a in self._mat] return self._new(self.rows, self.cols, mat, copy=False) def _eval_scalar_rmul(self, other): mat = [a*other for a in self._mat] return self._new(self.rows, self.cols, mat, copy=False) def _eval_tolist(self): mat = list(self._mat) cols = self.cols return [mat[i*cols:(i + 1)*cols] for i in range(self.rows)] def as_immutable(self): """Returns an Immutable version of this Matrix """ from .immutable import ImmutableDenseMatrix as cls if self.rows and self.cols: return cls._new(self.tolist()) return cls._new(self.rows, self.cols, []) def as_mutable(self): """Returns a mutable version of this matrix Examples ======== >>> from sympy import ImmutableMatrix >>> X = ImmutableMatrix([[1, 2], [3, 4]]) >>> Y = X.as_mutable() >>> Y[1, 1] = 5 # Can set values in Y >>> Y Matrix([ [1, 2], [3, 5]]) """ return Matrix(self) def equals(self, other, failing_expression=False): """Applies ``equals`` to corresponding elements of the matrices, trying to prove that the elements are equivalent, returning True if they are, False if any pair is not, and None (or the first failing expression if failing_expression is True) if it cannot be decided if the expressions are equivalent or not. This is, in general, an expensive operation. Examples ======== >>> from sympy.matrices import Matrix >>> from sympy.abc import x >>> A = Matrix([x*(x - 1), 0]) >>> B = Matrix([x**2 - x, 0]) >>> A == B False >>> A.simplify() == B.simplify() True >>> A.equals(B) True >>> A.equals(2) False See Also ======== sympy.core.expr.Expr.equals """ self_shape = getattr(self, 'shape', None) other_shape = getattr(other, 'shape', None) if None in (self_shape, other_shape): return False if self_shape != other_shape: return False rv = True for i in range(self.rows): for j in range(self.cols): ans = self[i, j].equals(other[i, j], failing_expression) if ans is False: return False elif ans is not True and rv is True: rv = ans return rv def cholesky(self, hermitian=True): return _cholesky(self, hermitian=hermitian) def LDLdecomposition(self, hermitian=True): return _LDLdecomposition(self, hermitian=hermitian) def lower_triangular_solve(self, rhs): return _lower_triangular_solve(self, rhs) def upper_triangular_solve(self, rhs): return _upper_triangular_solve(self, rhs) cholesky.__doc__ = _cholesky.__doc__ LDLdecomposition.__doc__ = _LDLdecomposition.__doc__ lower_triangular_solve.__doc__ = _lower_triangular_solve.__doc__ upper_triangular_solve.__doc__ = _upper_triangular_solve.__doc__ def _force_mutable(x): """Return a matrix as a Matrix, otherwise return x.""" if getattr(x, 'is_Matrix', False): return x.as_mutable() elif isinstance(x, Basic): return x elif hasattr(x, '__array__'): a = x.__array__() if len(a.shape) == 0: return sympify(a) return Matrix(x) return x class MutableDenseMatrix(DenseMatrix, MatrixBase): __hash__ = None # type: ignore def __new__(cls, *args, **kwargs): return cls._new(*args, **kwargs) @classmethod def _new(cls, *args, copy=True, **kwargs): if copy is False: # The input was rows, cols, [list]. # It should be used directly without creating a copy. if len(args) != 3: raise TypeError("'copy=False' requires a matrix be initialized as rows,cols,[list]") rows, cols, flat_list = args else: rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs) flat_list = list(flat_list) # create a shallow copy self = object.__new__(cls) self.rows = rows self.cols = cols self._mat = flat_list return self def __setitem__(self, key, value): """ Examples ======== >>> from sympy import Matrix, I, zeros, ones >>> m = Matrix(((1, 2+I), (3, 4))) >>> m Matrix([ [1, 2 + I], [3, 4]]) >>> m[1, 0] = 9 >>> m Matrix([ [1, 2 + I], [9, 4]]) >>> m[1, 0] = [[0, 1]] To replace row r you assign to position r*m where m is the number of columns: >>> M = zeros(4) >>> m = M.cols >>> M[3*m] = ones(1, m)*2; M Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 2, 2]]) And to replace column c you can assign to position c: >>> M[2] = ones(m, 1)*4; M Matrix([ [0, 0, 4, 0], [0, 0, 4, 0], [0, 0, 4, 0], [2, 2, 4, 2]]) """ rv = self._setitem(key, value) if rv is not None: i, j, value = rv self._mat[i*self.cols + j] = value def as_mutable(self): return self.copy() def _eval_col_del(self, col): for j in range(self.rows-1, -1, -1): del self._mat[col + j*self.cols] self.cols -= 1 def _eval_row_del(self, row): del self._mat[row*self.cols: (row+1)*self.cols] self.rows -= 1 def col_op(self, j, f): """In-place operation on col j using two-arg functor whose args are interpreted as (self[i, j], i). Examples ======== >>> from sympy.matrices import eye >>> M = eye(3) >>> M.col_op(1, lambda v, i: v + 2*M[i, 0]); M Matrix([ [1, 2, 0], [0, 1, 0], [0, 0, 1]]) See Also ======== col row_op """ self._mat[j::self.cols] = [f(*t) for t in list(zip(self._mat[j::self.cols], list(range(self.rows))))] def col_swap(self, i, j): """Swap the two given columns of the matrix in-place. Examples ======== >>> from sympy.matrices import Matrix >>> M = Matrix([[1, 0], [1, 0]]) >>> M Matrix([ [1, 0], [1, 0]]) >>> M.col_swap(0, 1) >>> M Matrix([ [0, 1], [0, 1]]) See Also ======== col row_swap """ for k in range(0, self.rows): self[k, i], self[k, j] = self[k, j], self[k, i] def copyin_list(self, key, value): """Copy in elements from a list. Parameters ========== key : slice The section of this matrix to replace. value : iterable The iterable to copy values from. Examples ======== >>> from sympy.matrices import eye >>> I = eye(3) >>> I[:2, 0] = [1, 2] # col >>> I Matrix([ [1, 0, 0], [2, 1, 0], [0, 0, 1]]) >>> I[1, :2] = [[3, 4]] >>> I Matrix([ [1, 0, 0], [3, 4, 0], [0, 0, 1]]) See Also ======== copyin_matrix """ if not is_sequence(value): raise TypeError("`value` must be an ordered iterable, not %s." % type(value)) return self.copyin_matrix(key, Matrix(value)) def copyin_matrix(self, key, value): """Copy in values from a matrix into the given bounds. Parameters ========== key : slice The section of this matrix to replace. value : Matrix The matrix to copy values from. Examples ======== >>> from sympy.matrices import Matrix, eye >>> M = Matrix([[0, 1], [2, 3], [4, 5]]) >>> I = eye(3) >>> I[:3, :2] = M >>> I Matrix([ [0, 1, 0], [2, 3, 0], [4, 5, 1]]) >>> I[0, 1] = M >>> I Matrix([ [0, 0, 1], [2, 2, 3], [4, 4, 5]]) See Also ======== copyin_list """ rlo, rhi, clo, chi = self.key2bounds(key) shape = value.shape dr, dc = rhi - rlo, chi - clo if shape != (dr, dc): raise ShapeError(filldedent("The Matrix `value` doesn't have the " "same dimensions " "as the in sub-Matrix given by `key`.")) for i in range(value.rows): for j in range(value.cols): self[i + rlo, j + clo] = value[i, j] def fill(self, value): """Fill the matrix with the scalar value. See Also ======== zeros ones """ self._mat = [value]*len(self) def row_op(self, i, f): """In-place operation on row ``i`` using two-arg functor whose args are interpreted as ``(self[i, j], j)``. Examples ======== >>> from sympy.matrices import eye >>> M = eye(3) >>> M.row_op(1, lambda v, j: v + 2*M[0, j]); M Matrix([ [1, 0, 0], [2, 1, 0], [0, 0, 1]]) See Also ======== row zip_row_op col_op """ i0 = i*self.cols ri = self._mat[i0: i0 + self.cols] self._mat[i0: i0 + self.cols] = [f(x, j) for x, j in zip(ri, list(range(self.cols)))] def row_swap(self, i, j): """Swap the two given rows of the matrix in-place. Examples ======== >>> from sympy.matrices import Matrix >>> M = Matrix([[0, 1], [1, 0]]) >>> M Matrix([ [0, 1], [1, 0]]) >>> M.row_swap(0, 1) >>> M Matrix([ [1, 0], [0, 1]]) See Also ======== row col_swap """ for k in range(0, self.cols): self[i, k], self[j, k] = self[j, k], self[i, k] def simplify(self, **kwargs): """Applies simplify to the elements of a matrix in place. This is a shortcut for M.applyfunc(lambda x: simplify(x, ratio, measure)) See Also ======== sympy.simplify.simplify.simplify """ for i in range(len(self._mat)): self._mat[i] = _simplify(self._mat[i], **kwargs) def zip_row_op(self, i, k, f): """In-place operation on row ``i`` using two-arg functor whose args are interpreted as ``(self[i, j], self[k, j])``. Examples ======== >>> from sympy.matrices import eye >>> M = eye(3) >>> M.zip_row_op(1, 0, lambda v, u: v + 2*u); M Matrix([ [1, 0, 0], [2, 1, 0], [0, 0, 1]]) See Also ======== row row_op col_op """ i0 = i*self.cols k0 = k*self.cols ri = self._mat[i0: i0 + self.cols] rk = self._mat[k0: k0 + self.cols] self._mat[i0: i0 + self.cols] = [f(x, y) for x, y in zip(ri, rk)] is_zero = False MutableMatrix = Matrix = MutableDenseMatrix ########### # Numpy Utility Functions: # list2numpy, matrix2numpy, symmarray, rot_axis[123] ########### def list2numpy(l, dtype=object): # pragma: no cover """Converts python list of SymPy expressions to a NumPy array. See Also ======== matrix2numpy """ from numpy import empty a = empty(len(l), dtype) for i, s in enumerate(l): a[i] = s return a def matrix2numpy(m, dtype=object): # pragma: no cover """Converts SymPy's matrix to a NumPy array. See Also ======== list2numpy """ from numpy import empty a = empty(m.shape, dtype) for i in range(m.rows): for j in range(m.cols): a[i, j] = m[i, j] return a def rot_axis3(theta): """Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis. Examples ======== >>> from sympy import pi >>> from sympy.matrices import rot_axis3 A rotation of pi/3 (60 degrees): >>> theta = pi/3 >>> rot_axis3(theta) Matrix([ [ 1/2, sqrt(3)/2, 0], [-sqrt(3)/2, 1/2, 0], [ 0, 0, 1]]) If we rotate by pi/2 (90 degrees): >>> rot_axis3(pi/2) Matrix([ [ 0, 1, 0], [-1, 0, 0], [ 0, 0, 1]]) See Also ======== rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis """ ct = cos(theta) st = sin(theta) lil = ((ct, st, 0), (-st, ct, 0), (0, 0, 1)) return Matrix(lil) def rot_axis2(theta): """Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis. Examples ======== >>> from sympy import pi >>> from sympy.matrices import rot_axis2 A rotation of pi/3 (60 degrees): >>> theta = pi/3 >>> rot_axis2(theta) Matrix([ [ 1/2, 0, -sqrt(3)/2], [ 0, 1, 0], [sqrt(3)/2, 0, 1/2]]) If we rotate by pi/2 (90 degrees): >>> rot_axis2(pi/2) Matrix([ [0, 0, -1], [0, 1, 0], [1, 0, 0]]) See Also ======== rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis """ ct = cos(theta) st = sin(theta) lil = ((ct, 0, -st), (0, 1, 0), (st, 0, ct)) return Matrix(lil) def rot_axis1(theta): """Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis. Examples ======== >>> from sympy import pi >>> from sympy.matrices import rot_axis1 A rotation of pi/3 (60 degrees): >>> theta = pi/3 >>> rot_axis1(theta) Matrix([ [1, 0, 0], [0, 1/2, sqrt(3)/2], [0, -sqrt(3)/2, 1/2]]) If we rotate by pi/2 (90 degrees): >>> rot_axis1(pi/2) Matrix([ [1, 0, 0], [0, 0, 1], [0, -1, 0]]) See Also ======== rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis """ ct = cos(theta) st = sin(theta) lil = ((1, 0, 0), (0, ct, st), (0, -st, ct)) return Matrix(lil) @doctest_depends_on(modules=('numpy',)) def symarray(prefix, shape, **kwargs): # pragma: no cover r"""Create a numpy ndarray of symbols (as an object array). The created symbols are named ``prefix_i1_i2_``... You should thus provide a non-empty prefix if you want your symbols to be unique for different output arrays, as SymPy symbols with identical names are the same object. Parameters ---------- prefix : string A prefix prepended to the name of every symbol. shape : int or tuple Shape of the created array. If an int, the array is one-dimensional; for more than one dimension the shape must be a tuple. \*\*kwargs : dict keyword arguments passed on to Symbol Examples ======== These doctests require numpy. >>> from sympy import symarray >>> symarray('', 3) [_0 _1 _2] If you want multiple symarrays to contain distinct symbols, you *must* provide unique prefixes: >>> a = symarray('', 3) >>> b = symarray('', 3) >>> a[0] == b[0] True >>> a = symarray('a', 3) >>> b = symarray('b', 3) >>> a[0] == b[0] False Creating symarrays with a prefix: >>> symarray('a', 3) [a_0 a_1 a_2] For more than one dimension, the shape must be given as a tuple: >>> symarray('a', (2, 3)) [[a_0_0 a_0_1 a_0_2] [a_1_0 a_1_1 a_1_2]] >>> symarray('a', (2, 3, 2)) [[[a_0_0_0 a_0_0_1] [a_0_1_0 a_0_1_1] [a_0_2_0 a_0_2_1]] <BLANKLINE> [[a_1_0_0 a_1_0_1] [a_1_1_0 a_1_1_1] [a_1_2_0 a_1_2_1]]] For setting assumptions of the underlying Symbols: >>> [s.is_real for s in symarray('a', 2, real=True)] [True, True] """ from numpy import empty, ndindex arr = empty(shape, dtype=object) for index in ndindex(shape): arr[index] = Symbol('%s_%s' % (prefix, '_'.join(map(str, index))), **kwargs) return arr ############### # Functions ############### def casoratian(seqs, n, zero=True): """Given linear difference operator L of order 'k' and homogeneous equation Ly = 0 we want to compute kernel of L, which is a set of 'k' sequences: a(n), b(n), ... z(n). Solutions of L are linearly independent iff their Casoratian, denoted as C(a, b, ..., z), do not vanish for n = 0. Casoratian is defined by k x k determinant:: + a(n) b(n) . . . z(n) + | a(n+1) b(n+1) . . . z(n+1) | | . . . . | | . . . . | | . . . . | + a(n+k-1) b(n+k-1) . . . z(n+k-1) + It proves very useful in rsolve_hyper() where it is applied to a generating set of a recurrence to factor out linearly dependent solutions and return a basis: >>> from sympy import Symbol, casoratian, factorial >>> n = Symbol('n', integer=True) Exponential and factorial are linearly independent: >>> casoratian([2**n, factorial(n)], n) != 0 True """ seqs = list(map(sympify, seqs)) if not zero: f = lambda i, j: seqs[j].subs(n, n + i) else: f = lambda i, j: seqs[j].subs(n, i) k = len(seqs) return Matrix(k, k, f).det() def eye(*args, **kwargs): """Create square identity matrix n x n See Also ======== diag zeros ones """ return Matrix.eye(*args, **kwargs) def diag(*values, strict=True, unpack=False, **kwargs): """Returns a matrix with the provided values placed on the diagonal. If non-square matrices are included, they will produce a block-diagonal matrix. Examples ======== This version of diag is a thin wrapper to Matrix.diag that differs in that it treats all lists like matrices -- even when a single list is given. If this is not desired, either put a `*` before the list or set `unpack=True`. >>> from sympy import diag >>> diag([1, 2, 3], unpack=True) # = diag(1,2,3) or diag(*[1,2,3]) Matrix([ [1, 0, 0], [0, 2, 0], [0, 0, 3]]) >>> diag([1, 2, 3]) # a column vector Matrix([ [1], [2], [3]]) See Also ======== .common.MatrixCommon.eye .common.MatrixCommon.diagonal - to extract a diagonal .common.MatrixCommon.diag .expressions.blockmatrix.BlockMatrix """ return Matrix.diag(*values, strict=strict, unpack=unpack, **kwargs) def GramSchmidt(vlist, orthonormal=False): """Apply the Gram-Schmidt process to a set of vectors. Parameters ========== vlist : List of Matrix Vectors to be orthogonalized for. orthonormal : Bool, optional If true, return an orthonormal basis. Returns ======= vlist : List of Matrix Orthogonalized vectors Notes ===== This routine is mostly duplicate from ``Matrix.orthogonalize``, except for some difference that this always raises error when linearly dependent vectors are found, and the keyword ``normalize`` has been named as ``orthonormal`` in this function. See Also ======== .matrices.MatrixSubspaces.orthogonalize References ========== .. [1] https://en.wikipedia.org/wiki/Gram%E2%80%93Schmidt_process """ return MutableDenseMatrix.orthogonalize( *vlist, normalize=orthonormal, rankcheck=True ) def hessian(f, varlist, constraints=[]): """Compute Hessian matrix for a function f wrt parameters in varlist which may be given as a sequence or a row/column vector. A list of constraints may optionally be given. Examples ======== >>> from sympy import Function, hessian, pprint >>> from sympy.abc import x, y >>> f = Function('f')(x, y) >>> g1 = Function('g')(x, y) >>> g2 = x**2 + 3*y >>> pprint(hessian(f, (x, y), [g1, g2])) [ d d ] [ 0 0 --(g(x, y)) --(g(x, y)) ] [ dx dy ] [ ] [ 0 0 2*x 3 ] [ ] [ 2 2 ] [d d d ] [--(g(x, y)) 2*x ---(f(x, y)) -----(f(x, y))] [dx 2 dy dx ] [ dx ] [ ] [ 2 2 ] [d d d ] [--(g(x, y)) 3 -----(f(x, y)) ---(f(x, y)) ] [dy dy dx 2 ] [ dy ] References ========== https://en.wikipedia.org/wiki/Hessian_matrix See Also ======== sympy.matrices.matrices.MatrixCalculus.jacobian wronskian """ # f is the expression representing a function f, return regular matrix if isinstance(varlist, MatrixBase): if 1 not in varlist.shape: raise ShapeError("`varlist` must be a column or row vector.") if varlist.cols == 1: varlist = varlist.T varlist = varlist.tolist()[0] if is_sequence(varlist): n = len(varlist) if not n: raise ShapeError("`len(varlist)` must not be zero.") else: raise ValueError("Improper variable list in hessian function") if not getattr(f, 'diff'): # check differentiability raise ValueError("Function `f` (%s) is not differentiable" % f) m = len(constraints) N = m + n out = zeros(N) for k, g in enumerate(constraints): if not getattr(g, 'diff'): # check differentiability raise ValueError("Function `f` (%s) is not differentiable" % f) for i in range(n): out[k, i + m] = g.diff(varlist[i]) for i in range(n): for j in range(i, n): out[i + m, j + m] = f.diff(varlist[i]).diff(varlist[j]) for i in range(N): for j in range(i + 1, N): out[j, i] = out[i, j] return out def jordan_cell(eigenval, n): """ Create a Jordan block: Examples ======== >>> from sympy.matrices import jordan_cell >>> from sympy.abc import x >>> jordan_cell(x, 4) Matrix([ [x, 1, 0, 0], [0, x, 1, 0], [0, 0, x, 1], [0, 0, 0, x]]) """ return Matrix.jordan_block(size=n, eigenvalue=eigenval) def matrix_multiply_elementwise(A, B): """Return the Hadamard product (elementwise product) of A and B >>> from sympy.matrices import matrix_multiply_elementwise >>> from sympy.matrices import Matrix >>> A = Matrix([[0, 1, 2], [3, 4, 5]]) >>> B = Matrix([[1, 10, 100], [100, 10, 1]]) >>> matrix_multiply_elementwise(A, B) Matrix([ [ 0, 10, 200], [300, 40, 5]]) See Also ======== sympy.matrices.common.MatrixCommon.__mul__ """ return A.multiply_elementwise(B) def ones(*args, **kwargs): """Returns a matrix of ones with ``rows`` rows and ``cols`` columns; if ``cols`` is omitted a square matrix will be returned. See Also ======== zeros eye diag """ if 'c' in kwargs: kwargs['cols'] = kwargs.pop('c') return Matrix.ones(*args, **kwargs) def randMatrix(r, c=None, min=0, max=99, seed=None, symmetric=False, percent=100, prng=None): """Create random matrix with dimensions ``r`` x ``c``. If ``c`` is omitted the matrix will be square. If ``symmetric`` is True the matrix must be square. If ``percent`` is less than 100 then only approximately the given percentage of elements will be non-zero. The pseudo-random number generator used to generate matrix is chosen in the following way. * If ``prng`` is supplied, it will be used as random number generator. It should be an instance of ``random.Random``, or at least have ``randint`` and ``shuffle`` methods with same signatures. * if ``prng`` is not supplied but ``seed`` is supplied, then new ``random.Random`` with given ``seed`` will be created; * otherwise, a new ``random.Random`` with default seed will be used. Examples ======== >>> from sympy.matrices import randMatrix >>> randMatrix(3) # doctest:+SKIP [25, 45, 27] [44, 54, 9] [23, 96, 46] >>> randMatrix(3, 2) # doctest:+SKIP [87, 29] [23, 37] [90, 26] >>> randMatrix(3, 3, 0, 2) # doctest:+SKIP [0, 2, 0] [2, 0, 1] [0, 0, 1] >>> randMatrix(3, symmetric=True) # doctest:+SKIP [85, 26, 29] [26, 71, 43] [29, 43, 57] >>> A = randMatrix(3, seed=1) >>> B = randMatrix(3, seed=2) >>> A == B False >>> A == randMatrix(3, seed=1) True >>> randMatrix(3, symmetric=True, percent=50) # doctest:+SKIP [77, 70, 0], [70, 0, 0], [ 0, 0, 88] """ if c is None: c = r # Note that ``Random()`` is equivalent to ``Random(None)`` prng = prng or random.Random(seed) if not symmetric: m = Matrix._new(r, c, lambda i, j: prng.randint(min, max)) if percent == 100: return m z = int(r*c*(100 - percent) // 100) m._mat[:z] = [S.Zero]*z prng.shuffle(m._mat) return m # Symmetric case if r != c: raise ValueError('For symmetric matrices, r must equal c, but %i != %i' % (r, c)) m = zeros(r) ij = [(i, j) for i in range(r) for j in range(i, r)] if percent != 100: ij = prng.sample(ij, int(len(ij)*percent // 100)) for i, j in ij: value = prng.randint(min, max) m[i, j] = m[j, i] = value return m def wronskian(functions, var, method='bareiss'): """ Compute Wronskian for [] of functions :: | f1 f2 ... fn | | f1' f2' ... fn' | | . . . . | W(f1, ..., fn) = | . . . . | | . . . . | | (n) (n) (n) | | D (f1) D (f2) ... D (fn) | see: https://en.wikipedia.org/wiki/Wronskian See Also ======== sympy.matrices.matrices.MatrixCalculus.jacobian hessian """ for index in range(0, len(functions)): functions[index] = sympify(functions[index]) n = len(functions) if n == 0: return 1 W = Matrix(n, n, lambda i, j: functions[i].diff(var, j)) return W.det(method) def zeros(*args, **kwargs): """Returns a matrix of zeros with ``rows`` rows and ``cols`` columns; if ``cols`` is omitted a square matrix will be returned. See Also ======== ones eye diag """ if 'c' in kwargs: kwargs['cols'] = kwargs.pop('c') return Matrix.zeros(*args, **kwargs)
08b1c65d54b3942602af91ef8d580056ea6df5a72268fccf96567066dfbf48b4
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.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) from .utilities import _iszero, _is_zero_after_expand_mul from .determinant import ( _find_reasonable_pivot, _find_reasonable_pivot_naive, _adjugate, _charpoly, _cofactor, _cofactor_matrix, _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, _QRdecomposition) 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 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__ 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') 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 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 QRdecomposition(self): return _QRdecomposition(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__ QRdecomposition.__doc__ = _QRdecomposition.__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)
f5eb6c6963b647af8592e49fca56b104f44fd3f66c8cd619c81770b2bd428df2
"""Plotting module for Sympy. A plot is represented by the ``Plot`` class that contains a reference to the backend and a list of the data series to be plotted. The data series are instances of classes meant to simplify getting points and meshes from sympy expressions. ``plot_backends`` is a dictionary with all the backends. This module gives only the essential. For all the fancy stuff use directly the backend. You can get the backend wrapper for every plot from the ``_backend`` attribute. Moreover the data series classes have various useful methods like ``get_points``, ``get_segments``, ``get_meshes``, etc, that may be useful if you wish to use another plotting library. Especially if you need publication ready graphs and this module is not enough for you - just get the ``_backend`` attribute and add whatever you want directly to it. In the case of matplotlib (the common way to graph data in python) just copy ``_backend.fig`` which is the figure and ``_backend.ax`` which is the axis and work on them as you would on any other matplotlib object. Simplicity of code takes much greater importance than performance. Don't use it if you care at all about performance. A new backend instance is initialized every time you call ``show()`` and the old one is left to the garbage collector. """ import warnings from sympy import sympify, Expr, Tuple, Dummy, Symbol from sympy.external import import_module from sympy.core.function import arity from sympy.core.compatibility import Callable from sympy.utilities.iterables import is_sequence from .experimental_lambdify import (vectorized_lambdify, lambdify) # N.B. # When changing the minimum module version for matplotlib, please change # the same in the `SymPyDocTestFinder`` in `sympy/testing/runtests.py` # Backend specific imports - textplot from sympy.plotting.textplot import textplot # Global variable # Set to False when running tests / doctests so that the plots don't show. _show = True def unset_show(): """ Disable show(). For use in the tests. """ global _show _show = False ############################################################################## # The public interface ############################################################################## class Plot: """The central class of the plotting module. For interactive work the function ``plot`` is better suited. This class permits the plotting of sympy expressions using numerous backends (matplotlib, textplot, the old pyglet module for sympy, Google charts api, etc). The figure can contain an arbitrary number of plots of sympy expressions, lists of coordinates of points, etc. Plot has a private attribute _series that contains all data series to be plotted (expressions for lines or surfaces, lists of points, etc (all subclasses of BaseSeries)). Those data series are instances of classes not imported by ``from sympy import *``. The customization of the figure is on two levels. Global options that concern the figure as a whole (eg title, xlabel, scale, etc) and per-data series options (eg name) and aesthetics (eg. color, point shape, line type, etc.). The difference between options and aesthetics is that an aesthetic can be a function of the coordinates (or parameters in a parametric plot). The supported values for an aesthetic are: - None (the backend uses default values) - a constant - a function of one variable (the first coordinate or parameter) - a function of two variables (the first and second coordinate or parameters) - a function of three variables (only in nonparametric 3D plots) Their implementation depends on the backend so they may not work in some backends. If the plot is parametric and the arity of the aesthetic function permits it the aesthetic is calculated over parameters and not over coordinates. If the arity does not permit calculation over parameters the calculation is done over coordinates. Only cartesian coordinates are supported for the moment, but you can use the parametric plots to plot in polar, spherical and cylindrical coordinates. The arguments for the constructor Plot must be subclasses of BaseSeries. Any global option can be specified as a keyword argument. The global options for a figure are: - title : str - xlabel : str - ylabel : str - legend : bool - xscale : {'linear', 'log'} - yscale : {'linear', 'log'} - axis : bool - axis_center : tuple of two floats or {'center', 'auto'} - xlim : tuple of two floats - ylim : tuple of two floats - aspect_ratio : tuple of two floats or {'auto'} - autoscale : bool - margin : float in [0, 1] - backend : {'default', 'matplotlib', 'text'} or a subclass of BaseBackend - size : optional tuple of two floats, (width, height); default: None The per data series options and aesthetics are: There are none in the base series. See below for options for subclasses. Some data series support additional aesthetics or options: ListSeries, LineOver1DRangeSeries, Parametric2DLineSeries, Parametric3DLineSeries support the following: Aesthetics: - line_color : function which returns a float. options: - label : str - steps : bool - integers_only : bool SurfaceOver2DRangeSeries, ParametricSurfaceSeries support the following: aesthetics: - surface_color : function which returns a float. """ def __init__(self, *args, title=None, xlabel=None, ylabel=None, aspect_ratio='auto', xlim=None, ylim=None, axis_center='auto', axis=True, xscale='linear', yscale='linear', legend=False, autoscale=True, margin=0, annotations=None, markers=None, rectangles=None, fill=None, backend='default', size=None, **kwargs): super().__init__() # Options for the graph as a whole. # The possible values for each option are described in the docstring of # Plot. They are based purely on convention, no checking is done. self.title = title self.xlabel = xlabel self.ylabel = ylabel self.aspect_ratio = aspect_ratio self.axis_center = axis_center self.axis = axis self.xscale = xscale self.yscale = yscale self.legend = legend self.autoscale = autoscale self.margin = margin self.annotations = annotations self.markers = markers self.rectangles = rectangles self.fill = fill # Contains the data objects to be plotted. The backend should be smart # enough to iterate over this list. self._series = [] self._series.extend(args) # The backend type. On every show() a new backend instance is created # in self._backend which is tightly coupled to the Plot instance # (thanks to the parent attribute of the backend). if isinstance(backend, str): self.backend = plot_backends[backend] elif (type(backend) == type) and issubclass(backend, BaseBackend): self.backend = backend else: raise TypeError( "backend must be either a string or a subclass of BaseBackend") is_real = \ lambda lim: all(getattr(i, 'is_real', True) for i in lim) is_finite = \ lambda lim: all(getattr(i, 'is_finite', True) for i in lim) # reduce code repetition def check_and_set(t_name, t): if t: if not is_real(t): raise ValueError( "All numbers from {}={} must be real".format(t_name, t)) if not is_finite(t): raise ValueError( "All numbers from {}={} must be finite".format(t_name, t)) setattr(self, t_name, (float(t[0]), float(t[1]))) self.xlim = None check_and_set("xlim", xlim) self.ylim = None check_and_set("ylim", ylim) self.size = None check_and_set("size", size) def show(self): # TODO move this to the backend (also for save) if hasattr(self, '_backend'): self._backend.close() self._backend = self.backend(self) self._backend.show() def save(self, path): if hasattr(self, '_backend'): self._backend.close() self._backend = self.backend(self) self._backend.save(path) def __str__(self): series_strs = [('[%d]: ' % i) + str(s) for i, s in enumerate(self._series)] return 'Plot object containing:\n' + '\n'.join(series_strs) def __getitem__(self, index): return self._series[index] def __setitem__(self, index, *args): if len(args) == 1 and isinstance(args[0], BaseSeries): self._series[index] = args def __delitem__(self, index): del self._series[index] def append(self, arg): """Adds an element from a plot's series to an existing plot. Examples ======== Consider two ``Plot`` objects, ``p1`` and ``p2``. To add the second plot's first series object to the first, use the ``append`` method, like so: .. plot:: :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.plotting import plot >>> x = symbols('x') >>> p1 = plot(x*x, show=False) >>> p2 = plot(x, show=False) >>> p1.append(p2[0]) >>> p1 Plot object containing: [0]: cartesian line: x**2 for x over (-10.0, 10.0) [1]: cartesian line: x for x over (-10.0, 10.0) >>> p1.show() See Also ======== extend """ if isinstance(arg, BaseSeries): self._series.append(arg) else: raise TypeError('Must specify element of plot to append.') def extend(self, arg): """Adds all series from another plot. Examples ======== Consider two ``Plot`` objects, ``p1`` and ``p2``. To add the second plot to the first, use the ``extend`` method, like so: .. plot:: :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.plotting import plot >>> x = symbols('x') >>> p1 = plot(x**2, show=False) >>> p2 = plot(x, -x, show=False) >>> p1.extend(p2) >>> p1 Plot object containing: [0]: cartesian line: x**2 for x over (-10.0, 10.0) [1]: cartesian line: x for x over (-10.0, 10.0) [2]: cartesian line: -x for x over (-10.0, 10.0) >>> p1.show() """ if isinstance(arg, Plot): self._series.extend(arg._series) elif is_sequence(arg): self._series.extend(arg) else: raise TypeError('Expecting Plot or sequence of BaseSeries') class PlotGrid: """This class helps to plot subplots from already created sympy plots in a single figure. Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.plotting import plot, plot3d, PlotGrid >>> x, y = symbols('x, y') >>> p1 = plot(x, x**2, x**3, (x, -5, 5)) >>> p2 = plot((x**2, (x, -6, 6)), (x, (x, -5, 5))) >>> p3 = plot(x**3, (x, -5, 5)) >>> p4 = plot3d(x*y, (x, -5, 5), (y, -5, 5)) Plotting vertically in a single line: .. plot:: :context: close-figs :format: doctest :include-source: True >>> PlotGrid(2, 1 , p1, p2) PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: x for x over (-5.0, 5.0) [1]: cartesian line: x**2 for x over (-5.0, 5.0) [2]: cartesian line: x**3 for x over (-5.0, 5.0) Plot[1]:Plot object containing: [0]: cartesian line: x**2 for x over (-6.0, 6.0) [1]: cartesian line: x for x over (-5.0, 5.0) Plotting horizontally in a single line: .. plot:: :context: close-figs :format: doctest :include-source: True >>> PlotGrid(1, 3 , p2, p3, p4) PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: x**2 for x over (-6.0, 6.0) [1]: cartesian line: x for x over (-5.0, 5.0) Plot[1]:Plot object containing: [0]: cartesian line: x**3 for x over (-5.0, 5.0) Plot[2]:Plot object containing: [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0) Plotting in a grid form: .. plot:: :context: close-figs :format: doctest :include-source: True >>> PlotGrid(2, 2, p1, p2 ,p3, p4) PlotGrid object containing: Plot[0]:Plot object containing: [0]: cartesian line: x for x over (-5.0, 5.0) [1]: cartesian line: x**2 for x over (-5.0, 5.0) [2]: cartesian line: x**3 for x over (-5.0, 5.0) Plot[1]:Plot object containing: [0]: cartesian line: x**2 for x over (-6.0, 6.0) [1]: cartesian line: x for x over (-5.0, 5.0) Plot[2]:Plot object containing: [0]: cartesian line: x**3 for x over (-5.0, 5.0) Plot[3]:Plot object containing: [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0) """ def __init__(self, nrows, ncolumns, *args, show=True, size=None, **kwargs): """ Parameters ========== nrows : The number of rows that should be in the grid of the required subplot ncolumns : The number of columns that should be in the grid of the required subplot nrows and ncolumns together define the required grid Arguments ========= A list of predefined plot objects entered in a row-wise sequence i.e. plot objects which are to be in the top row of the required grid are written first, then the second row objects and so on Keyword arguments ================= show : Boolean The default value is set to ``True``. Set show to ``False`` and the function will not display the subplot. The returned instance of the ``PlotGrid`` class can then be used to save or display the plot by calling the ``save()`` and ``show()`` methods respectively. size : (float, float), optional A tuple in the form (width, height) in inches to specify the size of the overall figure. The default value is set to ``None``, meaning the size will be set by the default backend. """ self.nrows = nrows self.ncolumns = ncolumns self._series = [] self.args = args for arg in args: self._series.append(arg._series) self.backend = DefaultBackend self.size = size if show: self.show() def show(self): if hasattr(self, '_backend'): self._backend.close() self._backend = self.backend(self) self._backend.show() def save(self, path): if hasattr(self, '_backend'): self._backend.close() self._backend = self.backend(self) self._backend.save(path) def __str__(self): plot_strs = [('Plot[%d]:' % i) + str(plot) for i, plot in enumerate(self.args)] return 'PlotGrid object containing:\n' + '\n'.join(plot_strs) ############################################################################## # Data Series ############################################################################## #TODO more general way to calculate aesthetics (see get_color_array) ### The base class for all series class BaseSeries: """Base class for the data objects containing stuff to be plotted. The backend should check if it supports the data series that it's given. (eg TextBackend supports only LineOver1DRange). It's the backend responsibility to know how to use the class of data series that it's given. Some data series classes are grouped (using a class attribute like is_2Dline) according to the api they present (based only on convention). The backend is not obliged to use that api (eg. The LineOver1DRange belongs to the is_2Dline group and presents the get_points method, but the TextBackend does not use the get_points method). """ # Some flags follow. The rationale for using flags instead of checking base # classes is that setting multiple flags is simpler than multiple # inheritance. is_2Dline = False # Some of the backends expect: # - get_points returning 1D np.arrays list_x, list_y # - get_segments returning np.array (done in Line2DBaseSeries) # - get_color_array returning 1D np.array (done in Line2DBaseSeries) # with the colors calculated at the points from get_points is_3Dline = False # Some of the backends expect: # - get_points returning 1D np.arrays list_x, list_y, list_y # - get_segments returning np.array (done in Line2DBaseSeries) # - get_color_array returning 1D np.array (done in Line2DBaseSeries) # with the colors calculated at the points from get_points is_3Dsurface = False # Some of the backends expect: # - get_meshes returning mesh_x, mesh_y, mesh_z (2D np.arrays) # - get_points an alias for get_meshes is_contour = False # Some of the backends expect: # - get_meshes returning mesh_x, mesh_y, mesh_z (2D np.arrays) # - get_points an alias for get_meshes is_implicit = False # Some of the backends expect: # - get_meshes returning mesh_x (1D array), mesh_y(1D array, # mesh_z (2D np.arrays) # - get_points an alias for get_meshes # Different from is_contour as the colormap in backend will be # different is_parametric = False # The calculation of aesthetics expects: # - get_parameter_points returning one or two np.arrays (1D or 2D) # used for calculation aesthetics def __init__(self): super().__init__() @property def is_3D(self): flags3D = [ self.is_3Dline, self.is_3Dsurface ] return any(flags3D) @property def is_line(self): flagslines = [ self.is_2Dline, self.is_3Dline ] return any(flagslines) ### 2D lines class Line2DBaseSeries(BaseSeries): """A base class for 2D lines. - adding the label, steps and only_integers options - making is_2Dline true - defining get_segments and get_color_array """ is_2Dline = True _dim = 2 def __init__(self): super().__init__() self.label = None self.steps = False self.only_integers = False self.line_color = None def get_segments(self): np = import_module('numpy') points = self.get_points() if self.steps is True: x = np.array((points[0], points[0])).T.flatten()[1:] y = np.array((points[1], points[1])).T.flatten()[:-1] points = (x, y) points = np.ma.array(points).T.reshape(-1, 1, self._dim) return np.ma.concatenate([points[:-1], points[1:]], axis=1) def get_color_array(self): np = import_module('numpy') c = self.line_color if hasattr(c, '__call__'): f = np.vectorize(c) nargs = arity(c) if nargs == 1 and self.is_parametric: x = self.get_parameter_points() return f(centers_of_segments(x)) else: variables = list(map(centers_of_segments, self.get_points())) if nargs == 1: return f(variables[0]) elif nargs == 2: return f(*variables[:2]) else: # only if the line is 3D (otherwise raises an error) return f(*variables) else: return c*np.ones(self.nb_of_points) class List2DSeries(Line2DBaseSeries): """Representation for a line consisting of list of points.""" def __init__(self, list_x, list_y): np = import_module('numpy') super().__init__() self.list_x = np.array(list_x) self.list_y = np.array(list_y) self.label = 'list' def __str__(self): return 'list plot' def get_points(self): return (self.list_x, self.list_y) class LineOver1DRangeSeries(Line2DBaseSeries): """Representation for a line consisting of a SymPy expression over a range.""" def __init__(self, expr, var_start_end, **kwargs): super().__init__() self.expr = sympify(expr) self.label = kwargs.get('label', None) or str(self.expr) self.var = sympify(var_start_end[0]) self.start = float(var_start_end[1]) self.end = float(var_start_end[2]) self.nb_of_points = kwargs.get('nb_of_points', 300) self.adaptive = kwargs.get('adaptive', True) self.depth = kwargs.get('depth', 12) self.line_color = kwargs.get('line_color', None) self.xscale = kwargs.get('xscale', 'linear') def __str__(self): return 'cartesian line: %s for %s over %s' % ( str(self.expr), str(self.var), str((self.start, self.end))) def get_segments(self): """ Adaptively gets segments for plotting. The adaptive sampling is done by recursively checking if three points are almost collinear. If they are not collinear, then more points are added between those points. References ========== .. [1] Adaptive polygonal approximation of parametric curves, Luiz Henrique de Figueiredo. """ if self.only_integers or not self.adaptive: return super().get_segments() else: f = lambdify([self.var], self.expr) list_segments = [] np = import_module('numpy') def sample(p, q, depth): """ Samples recursively if three points are almost collinear. For depth < 6, points are added irrespective of whether they satisfy the collinearity condition or not. The maximum depth allowed is 12. """ # Randomly sample to avoid aliasing. random = 0.45 + np.random.rand() * 0.1 if self.xscale == 'log': xnew = 10**(np.log10(p[0]) + random * (np.log10(q[0]) - np.log10(p[0]))) else: xnew = p[0] + random * (q[0] - p[0]) ynew = f(xnew) new_point = np.array([xnew, ynew]) # Maximum depth if depth > self.depth: list_segments.append([p, q]) # Sample irrespective of whether the line is flat till the # depth of 6. We are not using linspace to avoid aliasing. elif depth < 6: sample(p, new_point, depth + 1) sample(new_point, q, depth + 1) # Sample ten points if complex values are encountered # at both ends. If there is a real value in between, then # sample those points further. elif p[1] is None and q[1] is None: if self.xscale == 'log': xarray = np.logspace(p[0], q[0], 10) else: xarray = np.linspace(p[0], q[0], 10) yarray = list(map(f, xarray)) if any(y is not None for y in yarray): for i in range(len(yarray) - 1): if yarray[i] is not None or yarray[i + 1] is not None: sample([xarray[i], yarray[i]], [xarray[i + 1], yarray[i + 1]], depth + 1) # Sample further if one of the end points in None (i.e. a # complex value) or the three points are not almost collinear. elif (p[1] is None or q[1] is None or new_point[1] is None or not flat(p, new_point, q)): sample(p, new_point, depth + 1) sample(new_point, q, depth + 1) else: list_segments.append([p, q]) f_start = f(self.start) f_end = f(self.end) sample(np.array([self.start, f_start]), np.array([self.end, f_end]), 0) return list_segments def get_points(self): np = import_module('numpy') if self.only_integers is True: if self.xscale == 'log': list_x = np.logspace(int(self.start), int(self.end), num=int(self.end) - int(self.start) + 1) else: list_x = np.linspace(int(self.start), int(self.end), num=int(self.end) - int(self.start) + 1) else: if self.xscale == 'log': list_x = np.logspace(self.start, self.end, num=self.nb_of_points) else: list_x = np.linspace(self.start, self.end, num=self.nb_of_points) f = vectorized_lambdify([self.var], self.expr) list_y = f(list_x) return (list_x, list_y) class Parametric2DLineSeries(Line2DBaseSeries): """Representation for a line consisting of two parametric sympy expressions over a range.""" is_parametric = True def __init__(self, expr_x, expr_y, var_start_end, **kwargs): super().__init__() self.expr_x = sympify(expr_x) self.expr_y = sympify(expr_y) self.label = kwargs.get('label', None) or \ "(%s, %s)" % (str(self.expr_x), str(self.expr_y)) self.var = sympify(var_start_end[0]) self.start = float(var_start_end[1]) self.end = float(var_start_end[2]) self.nb_of_points = kwargs.get('nb_of_points', 300) self.adaptive = kwargs.get('adaptive', True) self.depth = kwargs.get('depth', 12) self.line_color = kwargs.get('line_color', None) def __str__(self): return 'parametric cartesian line: (%s, %s) for %s over %s' % ( str(self.expr_x), str(self.expr_y), str(self.var), str((self.start, self.end))) def get_parameter_points(self): np = import_module('numpy') return np.linspace(self.start, self.end, num=self.nb_of_points) def get_points(self): param = self.get_parameter_points() fx = vectorized_lambdify([self.var], self.expr_x) fy = vectorized_lambdify([self.var], self.expr_y) list_x = fx(param) list_y = fy(param) return (list_x, list_y) def get_segments(self): """ Adaptively gets segments for plotting. The adaptive sampling is done by recursively checking if three points are almost collinear. If they are not collinear, then more points are added between those points. References ========== [1] Adaptive polygonal approximation of parametric curves, Luiz Henrique de Figueiredo. """ if not self.adaptive: return super().get_segments() f_x = lambdify([self.var], self.expr_x) f_y = lambdify([self.var], self.expr_y) list_segments = [] def sample(param_p, param_q, p, q, depth): """ Samples recursively if three points are almost collinear. For depth < 6, points are added irrespective of whether they satisfy the collinearity condition or not. The maximum depth allowed is 12. """ # Randomly sample to avoid aliasing. np = import_module('numpy') random = 0.45 + np.random.rand() * 0.1 param_new = param_p + random * (param_q - param_p) xnew = f_x(param_new) ynew = f_y(param_new) new_point = np.array([xnew, ynew]) # Maximum depth if depth > self.depth: list_segments.append([p, q]) # Sample irrespective of whether the line is flat till the # depth of 6. We are not using linspace to avoid aliasing. elif depth < 6: sample(param_p, param_new, p, new_point, depth + 1) sample(param_new, param_q, new_point, q, depth + 1) # Sample ten points if complex values are encountered # at both ends. If there is a real value in between, then # sample those points further. elif ((p[0] is None and q[1] is None) or (p[1] is None and q[1] is None)): param_array = np.linspace(param_p, param_q, 10) x_array = list(map(f_x, param_array)) y_array = list(map(f_y, param_array)) if any(x is not None and y is not None for x, y in zip(x_array, y_array)): for i in range(len(y_array) - 1): if ((x_array[i] is not None and y_array[i] is not None) or (x_array[i + 1] is not None and y_array[i + 1] is not None)): point_a = [x_array[i], y_array[i]] point_b = [x_array[i + 1], y_array[i + 1]] sample(param_array[i], param_array[i], point_a, point_b, depth + 1) # Sample further if one of the end points in None (i.e. a complex # value) or the three points are not almost collinear. elif (p[0] is None or p[1] is None or q[1] is None or q[0] is None or not flat(p, new_point, q)): sample(param_p, param_new, p, new_point, depth + 1) sample(param_new, param_q, new_point, q, depth + 1) else: list_segments.append([p, q]) f_start_x = f_x(self.start) f_start_y = f_y(self.start) start = [f_start_x, f_start_y] f_end_x = f_x(self.end) f_end_y = f_y(self.end) end = [f_end_x, f_end_y] sample(self.start, self.end, start, end, 0) return list_segments ### 3D lines class Line3DBaseSeries(Line2DBaseSeries): """A base class for 3D lines. Most of the stuff is derived from Line2DBaseSeries.""" is_2Dline = False is_3Dline = True _dim = 3 def __init__(self): super().__init__() class Parametric3DLineSeries(Line3DBaseSeries): """Representation for a 3D line consisting of two parametric sympy expressions and a range.""" def __init__(self, expr_x, expr_y, expr_z, var_start_end, **kwargs): super().__init__() self.expr_x = sympify(expr_x) self.expr_y = sympify(expr_y) self.expr_z = sympify(expr_z) self.label = kwargs.get('label', None) or \ "(%s, %s)" % (str(self.expr_x), str(self.expr_y)) self.var = sympify(var_start_end[0]) self.start = float(var_start_end[1]) self.end = float(var_start_end[2]) self.nb_of_points = kwargs.get('nb_of_points', 300) self.line_color = kwargs.get('line_color', None) def __str__(self): return '3D parametric cartesian line: (%s, %s, %s) for %s over %s' % ( str(self.expr_x), str(self.expr_y), str(self.expr_z), str(self.var), str((self.start, self.end))) def get_parameter_points(self): np = import_module('numpy') return np.linspace(self.start, self.end, num=self.nb_of_points) def get_points(self): np = import_module('numpy') param = self.get_parameter_points() fx = vectorized_lambdify([self.var], self.expr_x) fy = vectorized_lambdify([self.var], self.expr_y) fz = vectorized_lambdify([self.var], self.expr_z) list_x = fx(param) list_y = fy(param) list_z = fz(param) list_x = np.array(list_x, dtype=np.float64) list_y = np.array(list_y, dtype=np.float64) list_z = np.array(list_z, dtype=np.float64) list_x = np.ma.masked_invalid(list_x) list_y = np.ma.masked_invalid(list_y) list_z = np.ma.masked_invalid(list_z) self._xlim = (np.amin(list_x), np.amax(list_x)) self._ylim = (np.amin(list_y), np.amax(list_y)) self._zlim = (np.amin(list_z), np.amax(list_z)) return list_x, list_y, list_z ### Surfaces class SurfaceBaseSeries(BaseSeries): """A base class for 3D surfaces.""" is_3Dsurface = True def __init__(self): super().__init__() self.surface_color = None def get_color_array(self): np = import_module('numpy') c = self.surface_color if isinstance(c, Callable): f = np.vectorize(c) nargs = arity(c) if self.is_parametric: variables = list(map(centers_of_faces, self.get_parameter_meshes())) if nargs == 1: return f(variables[0]) elif nargs == 2: return f(*variables) variables = list(map(centers_of_faces, self.get_meshes())) if nargs == 1: return f(variables[0]) elif nargs == 2: return f(*variables[:2]) else: return f(*variables) else: return c*np.ones(self.nb_of_points) class SurfaceOver2DRangeSeries(SurfaceBaseSeries): """Representation for a 3D surface consisting of a sympy expression and 2D range.""" def __init__(self, expr, var_start_end_x, var_start_end_y, **kwargs): super().__init__() self.expr = sympify(expr) self.var_x = sympify(var_start_end_x[0]) self.start_x = float(var_start_end_x[1]) self.end_x = float(var_start_end_x[2]) self.var_y = sympify(var_start_end_y[0]) self.start_y = float(var_start_end_y[1]) self.end_y = float(var_start_end_y[2]) self.nb_of_points_x = kwargs.get('nb_of_points_x', 50) self.nb_of_points_y = kwargs.get('nb_of_points_y', 50) self.surface_color = kwargs.get('surface_color', None) self._xlim = (self.start_x, self.end_x) self._ylim = (self.start_y, self.end_y) def __str__(self): return ('cartesian surface: %s for' ' %s over %s and %s over %s') % ( str(self.expr), str(self.var_x), str((self.start_x, self.end_x)), str(self.var_y), str((self.start_y, self.end_y))) def get_meshes(self): np = import_module('numpy') mesh_x, mesh_y = np.meshgrid(np.linspace(self.start_x, self.end_x, num=self.nb_of_points_x), np.linspace(self.start_y, self.end_y, num=self.nb_of_points_y)) f = vectorized_lambdify((self.var_x, self.var_y), self.expr) mesh_z = f(mesh_x, mesh_y) mesh_z = np.array(mesh_z, dtype=np.float64) mesh_z = np.ma.masked_invalid(mesh_z) self._zlim = (np.amin(mesh_z), np.amax(mesh_z)) return mesh_x, mesh_y, mesh_z class ParametricSurfaceSeries(SurfaceBaseSeries): """Representation for a 3D surface consisting of three parametric sympy expressions and a range.""" is_parametric = True def __init__( self, expr_x, expr_y, expr_z, var_start_end_u, var_start_end_v, **kwargs): super().__init__() self.expr_x = sympify(expr_x) self.expr_y = sympify(expr_y) self.expr_z = sympify(expr_z) self.var_u = sympify(var_start_end_u[0]) self.start_u = float(var_start_end_u[1]) self.end_u = float(var_start_end_u[2]) self.var_v = sympify(var_start_end_v[0]) self.start_v = float(var_start_end_v[1]) self.end_v = float(var_start_end_v[2]) self.nb_of_points_u = kwargs.get('nb_of_points_u', 50) self.nb_of_points_v = kwargs.get('nb_of_points_v', 50) self.surface_color = kwargs.get('surface_color', None) def __str__(self): return ('parametric cartesian surface: (%s, %s, %s) for' ' %s over %s and %s over %s') % ( str(self.expr_x), str(self.expr_y), str(self.expr_z), str(self.var_u), str((self.start_u, self.end_u)), str(self.var_v), str((self.start_v, self.end_v))) def get_parameter_meshes(self): np = import_module('numpy') return np.meshgrid(np.linspace(self.start_u, self.end_u, num=self.nb_of_points_u), np.linspace(self.start_v, self.end_v, num=self.nb_of_points_v)) def get_meshes(self): np = import_module('numpy') mesh_u, mesh_v = self.get_parameter_meshes() fx = vectorized_lambdify((self.var_u, self.var_v), self.expr_x) fy = vectorized_lambdify((self.var_u, self.var_v), self.expr_y) fz = vectorized_lambdify((self.var_u, self.var_v), self.expr_z) mesh_x = fx(mesh_u, mesh_v) mesh_y = fy(mesh_u, mesh_v) mesh_z = fz(mesh_u, mesh_v) mesh_x = np.array(mesh_x, dtype=np.float64) mesh_y = np.array(mesh_y, dtype=np.float64) mesh_z = np.array(mesh_z, dtype=np.float64) mesh_x = np.ma.masked_invalid(mesh_x) mesh_y = np.ma.masked_invalid(mesh_y) mesh_z = np.ma.masked_invalid(mesh_z) self._xlim = (np.amin(mesh_x), np.amax(mesh_x)) self._ylim = (np.amin(mesh_y), np.amax(mesh_y)) self._zlim = (np.amin(mesh_z), np.amax(mesh_z)) return mesh_x, mesh_y, mesh_z ### Contours class ContourSeries(BaseSeries): """Representation for a contour plot.""" # The code is mostly repetition of SurfaceOver2DRange. # Presently used in contour_plot function is_contour = True def __init__(self, expr, var_start_end_x, var_start_end_y): super().__init__() self.nb_of_points_x = 50 self.nb_of_points_y = 50 self.expr = sympify(expr) self.var_x = sympify(var_start_end_x[0]) self.start_x = float(var_start_end_x[1]) self.end_x = float(var_start_end_x[2]) self.var_y = sympify(var_start_end_y[0]) self.start_y = float(var_start_end_y[1]) self.end_y = float(var_start_end_y[2]) self.get_points = self.get_meshes self._xlim = (self.start_x, self.end_x) self._ylim = (self.start_y, self.end_y) def __str__(self): return ('contour: %s for ' '%s over %s and %s over %s') % ( str(self.expr), str(self.var_x), str((self.start_x, self.end_x)), str(self.var_y), str((self.start_y, self.end_y))) def get_meshes(self): np = import_module('numpy') mesh_x, mesh_y = np.meshgrid(np.linspace(self.start_x, self.end_x, num=self.nb_of_points_x), np.linspace(self.start_y, self.end_y, num=self.nb_of_points_y)) f = vectorized_lambdify((self.var_x, self.var_y), self.expr) return (mesh_x, mesh_y, f(mesh_x, mesh_y)) ############################################################################## # Backends ############################################################################## class BaseBackend(object): """Base class for all backends. A backend represents the plotting library, which implements the necessary functionalities in order to use SymPy plotting functions. How the plotting module works: 1. Whenever a plotting function is called, the provided expressions are processed and a list of instances of the `BaseSeries` class is created, containing the necessary information to plot the expressions (eg the expression, ranges, series name, ...). Eventually, these objects will generate the numerical data to be plotted. 2. A Plot object is instantiated, which stores the list of series and the main attributes of the plot (eg axis labels, title, ...). 3. When the "show" command is executed, a new backend is instantiated, which loops through each series object to generate and plot the numerical data. The backend is also going to set the axis labels, title, ..., according to the values stored in the Plot instance. The backend should check if it supports the data series that it's given (eg TextBackend supports only LineOver1DRange). It's the backend responsibility to know how to use the class of data series that it's given. Note that the current implementation of the `*Series` classes is "matplotlib-centric": the numerical data returned by the `get_points` and `get_meshes` methods is meant to be used directly by Matplotlib. Therefore, the new backend will have to pre-process the numerical data to make it compatible with the chosen plotting library. Keep in mind that future SymPy versions may improve the `*Series` classes in order to return numerical data "non-matplotlib-centric", hence if you code a new backend you have the responsibility to check if its working on each SymPy release. Please, explore the `MatplotlibBackend` source code to understand how a backend should be coded. Methods ======= In order to be used by SymPy plotting functions, a backend must implement the following methods: * `show(self)`: used to loop over the data series, generate the numerical data, plot it and set the axis labels, title, ... * save(self, path): used to save the current plot to the specified file path. * close(self): used to close the current plot backend (note: some plotting library doesn't support this functionality. In that case, just raise a warning). See also ======== MatplotlibBackend """ def __init__(self, parent): super(BaseBackend, self).__init__() self.parent = parent def show(self): raise NotImplementedError def save(self, path): raise NotImplementedError def close(self): raise NotImplementedError # Don't have to check for the success of importing matplotlib in each case; # we will only be using this backend if we can successfully import matploblib class MatplotlibBackend(BaseBackend): """ This class implements the functionalities to use Matplotlib with SymPy plotting functions. """ def __init__(self, parent): super().__init__(parent) self.matplotlib = import_module('matplotlib', import_kwargs={'fromlist': ['pyplot', 'cm', 'collections']}, min_module_version='1.1.0', catch=(RuntimeError,)) self.plt = self.matplotlib.pyplot self.cm = self.matplotlib.cm self.LineCollection = self.matplotlib.collections.LineCollection aspect = getattr(self.parent, 'aspect_ratio', 'auto') if aspect != 'auto': aspect = float(aspect[1]) / aspect[0] if isinstance(self.parent, Plot): nrows, ncolumns = 1, 1 series_list = [self.parent._series] elif isinstance(self.parent, PlotGrid): nrows, ncolumns = self.parent.nrows, self.parent.ncolumns series_list = self.parent._series self.ax = [] self.fig = self.plt.figure(figsize=parent.size) for i, series in enumerate(series_list): are_3D = [s.is_3D for s in series] if any(are_3D) and not all(are_3D): raise ValueError('The matplotlib backend can not mix 2D and 3D.') elif all(are_3D): # mpl_toolkits.mplot3d is necessary for # projection='3d' mpl_toolkits = import_module('mpl_toolkits', # noqa import_kwargs={'fromlist': ['mplot3d']}) self.ax.append(self.fig.add_subplot(nrows, ncolumns, i + 1, projection='3d', aspect=aspect)) elif not any(are_3D): self.ax.append(self.fig.add_subplot(nrows, ncolumns, i + 1, aspect=aspect)) self.ax[i].spines['left'].set_position('zero') self.ax[i].spines['right'].set_color('none') self.ax[i].spines['bottom'].set_position('zero') self.ax[i].spines['top'].set_color('none') self.ax[i].xaxis.set_ticks_position('bottom') self.ax[i].yaxis.set_ticks_position('left') def _process_series(self, series, ax, parent): np = import_module('numpy') mpl_toolkits = import_module( 'mpl_toolkits', import_kwargs={'fromlist': ['mplot3d']}) # XXX Workaround for matplotlib issue # https://github.com/matplotlib/matplotlib/issues/17130 xlims, ylims, zlims = [], [], [] for s in series: # Create the collections if s.is_2Dline: collection = self.LineCollection(s.get_segments()) ax.add_collection(collection) elif s.is_contour: ax.contour(*s.get_meshes()) elif s.is_3Dline: # TODO too complicated, I blame matplotlib art3d = mpl_toolkits.mplot3d.art3d collection = art3d.Line3DCollection(s.get_segments()) ax.add_collection(collection) x, y, z = s.get_points() xlims.append(s._xlim) ylims.append(s._ylim) zlims.append(s._zlim) elif s.is_3Dsurface: x, y, z = s.get_meshes() collection = ax.plot_surface(x, y, z, cmap=getattr(self.cm, 'viridis', self.cm.jet), rstride=1, cstride=1, linewidth=0.1) xlims.append(s._xlim) ylims.append(s._ylim) zlims.append(s._zlim) elif s.is_implicit: points = s.get_raster() if len(points) == 2: # interval math plotting x, y = _matplotlib_list(points[0]) ax.fill(x, y, facecolor=s.line_color, edgecolor='None') else: # use contourf or contour depending on whether it is # an inequality or equality. # XXX: ``contour`` plots multiple lines. Should be fixed. ListedColormap = self.matplotlib.colors.ListedColormap colormap = ListedColormap(["white", s.line_color]) xarray, yarray, zarray, plot_type = points if plot_type == 'contour': ax.contour(xarray, yarray, zarray, cmap=colormap) else: ax.contourf(xarray, yarray, zarray, cmap=colormap) else: raise NotImplementedError( '{} is not supported in the sympy plotting module ' 'with matplotlib backend. Please report this issue.' .format(ax)) # Customise the collections with the corresponding per-series # options. if hasattr(s, 'label'): collection.set_label(s.label) if s.is_line and s.line_color: if isinstance(s.line_color, (float, int)) or isinstance(s.line_color, Callable): color_array = s.get_color_array() collection.set_array(color_array) else: collection.set_color(s.line_color) if s.is_3Dsurface and s.surface_color: if self.matplotlib.__version__ < "1.2.0": # TODO in the distant future remove this check warnings.warn('The version of matplotlib is too old to use surface coloring.') elif isinstance(s.surface_color, (float, int)) or isinstance(s.surface_color, Callable): color_array = s.get_color_array() color_array = color_array.reshape(color_array.size) collection.set_array(color_array) else: collection.set_color(s.surface_color) Axes3D = mpl_toolkits.mplot3d.Axes3D if not isinstance(ax, Axes3D): ax.autoscale_view( scalex=ax.get_autoscalex_on(), scaley=ax.get_autoscaley_on()) else: # XXX Workaround for matplotlib issue # https://github.com/matplotlib/matplotlib/issues/17130 if xlims: xlims = np.array(xlims) xlim = (np.amin(xlims[:, 0]), np.amax(xlims[:, 1])) ax.set_xlim(xlim) else: ax.set_xlim([0, 1]) if ylims: ylims = np.array(ylims) ylim = (np.amin(ylims[:, 0]), np.amax(ylims[:, 1])) ax.set_ylim(ylim) else: ax.set_ylim([0, 1]) if zlims: zlims = np.array(zlims) zlim = (np.amin(zlims[:, 0]), np.amax(zlims[:, 1])) ax.set_zlim(zlim) else: ax.set_zlim([0, 1]) # Set global options. # TODO The 3D stuff # XXX The order of those is important. if parent.xscale and not isinstance(ax, Axes3D): ax.set_xscale(parent.xscale) if parent.yscale and not isinstance(ax, Axes3D): ax.set_yscale(parent.yscale) if not isinstance(ax, Axes3D) or self.matplotlib.__version__ >= '1.2.0': # XXX in the distant future remove this check ax.set_autoscale_on(parent.autoscale) if parent.axis_center: val = parent.axis_center if isinstance(ax, Axes3D): pass elif val == 'center': ax.spines['left'].set_position('center') ax.spines['bottom'].set_position('center') elif val == 'auto': xl, xh = ax.get_xlim() yl, yh = ax.get_ylim() pos_left = ('data', 0) if xl*xh <= 0 else 'center' pos_bottom = ('data', 0) if yl*yh <= 0 else 'center' ax.spines['left'].set_position(pos_left) ax.spines['bottom'].set_position(pos_bottom) else: ax.spines['left'].set_position(('data', val[0])) ax.spines['bottom'].set_position(('data', val[1])) if not parent.axis: ax.set_axis_off() if parent.legend: if ax.legend(): ax.legend_.set_visible(parent.legend) if parent.margin: ax.set_xmargin(parent.margin) ax.set_ymargin(parent.margin) if parent.title: ax.set_title(parent.title) if parent.xlabel: ax.set_xlabel(parent.xlabel, position=(1, 0)) if parent.ylabel: ax.set_ylabel(parent.ylabel, position=(0, 1)) if parent.annotations: for a in parent.annotations: ax.annotate(**a) if parent.markers: for marker in parent.markers: # make a copy of the marker dictionary # so that it doesn't get altered m = marker.copy() args = m.pop('args') ax.plot(*args, **m) if parent.rectangles: for r in parent.rectangles: rect = self.matplotlib.patches.Rectangle(**r) ax.add_patch(rect) if parent.fill: ax.fill_between(**parent.fill) # xlim and ylim shoulld always be set at last so that plot limits # doesn't get altered during the process. if parent.xlim: ax.set_xlim(parent.xlim) if parent.ylim: ax.set_ylim(parent.ylim) def process_series(self): """ Iterates over every ``Plot`` object and further calls _process_series() """ parent = self.parent if isinstance(parent, Plot): series_list = [parent._series] else: series_list = parent._series for i, (series, ax) in enumerate(zip(series_list, self.ax)): if isinstance(self.parent, PlotGrid): parent = self.parent.args[i] self._process_series(series, ax, parent) def show(self): self.process_series() #TODO after fixing https://github.com/ipython/ipython/issues/1255 # you can uncomment the next line and remove the pyplot.show() call #self.fig.show() if _show: self.fig.tight_layout() self.plt.show() else: self.close() def save(self, path): self.process_series() self.fig.savefig(path) def close(self): self.plt.close(self.fig) class TextBackend(BaseBackend): def __init__(self, parent): super().__init__(parent) def show(self): if not _show: return if len(self.parent._series) != 1: raise ValueError( 'The TextBackend supports only one graph per Plot.') elif not isinstance(self.parent._series[0], LineOver1DRangeSeries): raise ValueError( 'The TextBackend supports only expressions over a 1D range') else: ser = self.parent._series[0] textplot(ser.expr, ser.start, ser.end) def close(self): pass class DefaultBackend(BaseBackend): def __new__(cls, parent): matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) if matplotlib: return MatplotlibBackend(parent) else: return TextBackend(parent) plot_backends = { 'matplotlib': MatplotlibBackend, 'text': TextBackend, 'default': DefaultBackend } ############################################################################## # Finding the centers of line segments or mesh faces ############################################################################## def centers_of_segments(array): np = import_module('numpy') return np.mean(np.vstack((array[:-1], array[1:])), 0) def centers_of_faces(array): np = import_module('numpy') return np.mean(np.dstack((array[:-1, :-1], array[1:, :-1], array[:-1, 1:], array[:-1, :-1], )), 2) def flat(x, y, z, eps=1e-3): """Checks whether three points are almost collinear""" np = import_module('numpy') # Workaround plotting piecewise (#8577): # workaround for `lambdify` in `.experimental_lambdify` fails # to return numerical values in some cases. Lower-level fix # in `lambdify` is possible. vector_a = (x - y).astype(np.float) vector_b = (z - y).astype(np.float) dot_product = np.dot(vector_a, vector_b) vector_a_norm = np.linalg.norm(vector_a) vector_b_norm = np.linalg.norm(vector_b) cos_theta = dot_product / (vector_a_norm * vector_b_norm) return abs(cos_theta + 1) < eps def _matplotlib_list(interval_list): """ Returns lists for matplotlib ``fill`` command from a list of bounding rectangular intervals """ xlist = [] ylist = [] if len(interval_list): for intervals in interval_list: intervalx = intervals[0] intervaly = intervals[1] xlist.extend([intervalx.start, intervalx.start, intervalx.end, intervalx.end, None]) ylist.extend([intervaly.start, intervaly.end, intervaly.end, intervaly.start, None]) else: #XXX Ugly hack. Matplotlib does not accept empty lists for ``fill`` xlist.extend([None, None, None, None]) ylist.extend([None, None, None, None]) return xlist, ylist ####New API for plotting module #### # TODO: Add color arrays for plots. # TODO: Add more plotting options for 3d plots. # TODO: Adaptive sampling for 3D plots. def plot(*args, show=True, **kwargs): """Plots a function of a single variable as a curve. Parameters ========== args The first argument is the expression representing the function of single variable to be plotted. The last argument is a 3-tuple denoting the range of the free variable. e.g. ``(x, 0, 5)`` Typical usage examples are in the followings: - Plotting a single expression with a single range. ``plot(expr, range, **kwargs)`` - Plotting a single expression with the default range (-10, 10). ``plot(expr, **kwargs)`` - Plotting multiple expressions with a single range. ``plot(expr1, expr2, ..., range, **kwargs)`` - Plotting multiple expressions with multiple ranges. ``plot((expr1, range1), (expr2, range2), ..., **kwargs)`` It is best practice to specify range explicitly because default range may change in the future if a more advanced default range detection algorithm is implemented. show : bool, optional The default value is set to ``True``. Set show to ``False`` and the function will not display the plot. The returned instance of the ``Plot`` class can then be used to save or display the plot by calling the ``save()`` and ``show()`` methods respectively. line_color : float, optional Specifies the color for the plot. See ``Plot`` to see how to set color for the plots. If there are multiple plots, then the same series series are applied to all the plots. If you want to set these options separately, you can index the ``Plot`` object returned and set it. title : str, optional Title of the plot. It is set to the latex representation of the expression, if the plot has only one expression. label : str, optional The label of the expression in the plot. It will be used when called with ``legend``. Default is the name of the expression. e.g. ``sin(x)`` xlabel : str, optional Label for the x-axis. ylabel : str, optional Label for the y-axis. xscale : 'linear' or 'log', optional Sets the scaling of the x-axis. yscale : 'linear' or 'log', optional Sets the scaling of the y-axis. axis_center : (float, float), optional Tuple of two floats denoting the coordinates of the center or {'center', 'auto'} xlim : (float, float), optional Denotes the x-axis limits, ``(min, max)```. ylim : (float, float), optional Denotes the y-axis limits, ``(min, max)```. annotations : list, optional A list of dictionaries specifying the type of annotation required. The keys in the dictionary should be equivalent to the arguments of the matplotlib's annotate() function. markers : list, optional A list of dictionaries specifying the type the markers required. The keys in the dictionary should be equivalent to the arguments of the matplotlib's plot() function along with the marker related keyworded arguments. rectangles : list, optional A list of dictionaries specifying the dimensions of the rectangles to be plotted. The keys in the dictionary should be equivalent to the arguments of the matplotlib's patches.Rectangle class. fill : dict, optional A dictionary specifying the type of color filling required in the plot. The keys in the dictionary should be equivalent to the arguments of the matplotlib's fill_between() function. adaptive : bool, optional The default value is set to ``True``. Set adaptive to ``False`` and specify ``nb_of_points`` if uniform sampling is required. The plotting uses an adaptive algorithm which samples recursively to accurately plot. The adaptive algorithm uses a random point near the midpoint of two points that has to be further sampled. Hence the same plots can appear slightly different. depth : int, optional Recursion depth of the adaptive algorithm. A depth of value ``n`` samples a maximum of `2^{n}` points. If the ``adaptive`` flag is set to ``False``, this will be ignored. nb_of_points : int, optional Used when the ``adaptive`` is set to ``False``. The function is uniformly sampled at ``nb_of_points`` number of points. If the ``adaptive`` flag is set to ``True``, this will be ignored. size : (float, float), optional A tuple in the form (width, height) in inches to specify the size of the overall figure. The default value is set to ``None``, meaning the size will be set by the default backend. Examples ======== .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.plotting import plot >>> x = symbols('x') Single Plot .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot(x**2, (x, -5, 5)) Plot object containing: [0]: cartesian line: x**2 for x over (-5.0, 5.0) Multiple plots with single range. .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot(x, x**2, x**3, (x, -5, 5)) Plot object containing: [0]: cartesian line: x for x over (-5.0, 5.0) [1]: cartesian line: x**2 for x over (-5.0, 5.0) [2]: cartesian line: x**3 for x over (-5.0, 5.0) Multiple plots with different ranges. .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot((x**2, (x, -6, 6)), (x, (x, -5, 5))) Plot object containing: [0]: cartesian line: x**2 for x over (-6.0, 6.0) [1]: cartesian line: x for x over (-5.0, 5.0) No adaptive sampling. .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot(x**2, adaptive=False, nb_of_points=400) Plot object containing: [0]: cartesian line: x**2 for x over (-10.0, 10.0) See Also ======== Plot, LineOver1DRangeSeries """ args = list(map(sympify, args)) free = set() for a in args: if isinstance(a, Expr): free |= a.free_symbols if len(free) > 1: raise ValueError( 'The same variable should be used in all ' 'univariate expressions being plotted.') x = free.pop() if free else Symbol('x') kwargs.setdefault('xlabel', x.name) kwargs.setdefault('ylabel', 'f(%s)' % x.name) series = [] plot_expr = check_arguments(args, 1, 1) series = [LineOver1DRangeSeries(*arg, **kwargs) for arg in plot_expr] plots = Plot(*series, **kwargs) if show: plots.show() return plots def plot_parametric(*args, show=True, **kwargs): """ Plots a 2D parametric curve. Parameters ========== args Common specifications are: - Plotting a single parametric curve with a range ``plot_parametric((expr_x, expr_y), range)`` - Plotting multiple parametric curves with the same range ``plot_parametric((expr_x, expr_y), ..., range)`` - Plotting multiple parametric curves with different ranges ``plot_parametric((expr_x, expr_y, range), ...)`` ``expr_x`` is the expression representing $x$ component of the parametric function. ``expr_y`` is the expression representing $y$ component of the parametric function. ``range`` is a 3-tuple denoting the parameter symbol, start and stop. For example, ``(u, 0, 5)``. If the range is not specified, then a default range of (-10, 10) is used. However, if the arguments are specified as ``(expr_x, expr_y, range), ...``, you must specify the ranges for each expressions manually. Default range may change in the future if a more advanced algorithm is implemented. adaptive : bool, optional Specifies whether to use the adaptive sampling or not. The default value is set to ``True``. Set adaptive to ``False`` and specify ``nb_of_points`` if uniform sampling is required. depth : int, optional The recursion depth of the adaptive algorithm. A depth of value $n$ samples a maximum of $2^n$ points. nb_of_points : int, optional Used when the ``adaptive`` flag is set to ``False``. Specifies the number of the points used for the uniform sampling. line_color : function A function which returns a float. Specifies the color of the plot. See :class:`Plot` for more details. label : str, optional The label of the expression in the plot. It will be used when called with ``legend``. Default is the name of the expression. e.g. ``sin(x)`` xlabel : str, optional Label for the x-axis. ylabel : str, optional Label for the y-axis. xscale : 'linear' or 'log', optional Sets the scaling of the x-axis. yscale : 'linear' or 'log', optional Sets the scaling of the y-axis. axis_center : (float, float), optional Tuple of two floats denoting the coordinates of the center or {'center', 'auto'} xlim : (float, float), optional Denotes the x-axis limits, ``(min, max)```. ylim : (float, float), optional Denotes the y-axis limits, ``(min, max)```. size : (float, float), optional A tuple in the form (width, height) in inches to specify the size of the overall figure. The default value is set to ``None``, meaning the size will be set by the default backend. Examples ======== .. plot:: :context: reset :format: doctest :include-source: True >>> from sympy import symbols, cos, sin >>> from sympy.plotting import plot_parametric >>> u = symbols('u') A parametric plot with a single expression: .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot_parametric((cos(u), sin(u)), (u, -5, 5)) Plot object containing: [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0) A parametric plot with multiple expressions with the same range: .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot_parametric((cos(u), sin(u)), (u, cos(u)), (u, -10, 10)) Plot object containing: [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-10.0, 10.0) [1]: parametric cartesian line: (u, cos(u)) for u over (-10.0, 10.0) A parametric plot with multiple expressions with different ranges for each curve: .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot_parametric((cos(u), sin(u), (u, -5, 5)), ... (cos(u), u, (u, -5, 5))) Plot object containing: [0]: parametric cartesian line: (cos(u), sin(u)) for u over (-5.0, 5.0) [1]: parametric cartesian line: (cos(u), u) for u over (-5.0, 5.0) Notes ===== The plotting uses an adaptive algorithm which samples recursively to accurately plot the curve. The adaptive algorithm uses a random point near the midpoint of two points that has to be further sampled. Hence, repeating the same plot command can give slightly different results because of the random sampling. If there are multiple plots, then the same optional arguments are applied to all the plots drawn in the same canvas. If you want to set these options separately, you can index the returned ``Plot`` object and set it. For example, when you specify ``line_color`` once, it would be applied simultaneously to both series. .. plot:: :context: close-figs :format: doctest :include-source: True >>> from sympy import pi >>> expr1 = (u, cos(2*pi*u)/2 + 1/2) >>> expr2 = (u, sin(2*pi*u)/2 + 1/2) >>> p = plot_parametric(expr1, expr2, (u, 0, 1), line_color='blue') If you want to specify the line color for the specific series, you should index each item and apply the property manually. .. plot:: :context: close-figs :format: doctest :include-source: True >>> p[0].line_color = 'red' >>> p.show() See Also ======== Plot, Parametric2DLineSeries """ args = list(map(sympify, args)) series = [] plot_expr = check_arguments(args, 2, 1) series = [Parametric2DLineSeries(*arg, **kwargs) for arg in plot_expr] plots = Plot(*series, **kwargs) if show: plots.show() return plots def plot3d_parametric_line(*args, show=True, **kwargs): """ Plots a 3D parametric line plot. Usage ===== Single plot: ``plot3d_parametric_line(expr_x, expr_y, expr_z, range, **kwargs)`` If the range is not specified, then a default range of (-10, 10) is used. Multiple plots. ``plot3d_parametric_line((expr_x, expr_y, expr_z, range), ..., **kwargs)`` Ranges have to be specified for every expression. Default range may change in the future if a more advanced default range detection algorithm is implemented. Arguments ========= ``expr_x`` : Expression representing the function along x. ``expr_y`` : Expression representing the function along y. ``expr_z`` : Expression representing the function along z. ``range``: ``(u, 0, 5)``, A 3-tuple denoting the range of the parameter variable. Keyword Arguments ================= Arguments for ``Parametric3DLineSeries`` class. ``nb_of_points``: The range is uniformly sampled at ``nb_of_points`` number of points. Aesthetics: ``line_color``: function which returns a float. Specifies the color for the plot. See ``sympy.plotting.Plot`` for more details. ``label``: str The label to the plot. It will be used when called with ``legend=True`` to denote the function with the given label in the plot. If there are multiple plots, then the same series arguments are applied to all the plots. If you want to set these options separately, you can index the returned ``Plot`` object and set it. Arguments for ``Plot`` class. ``title`` : str. Title of the plot. ``size`` : (float, float), optional A tuple in the form (width, height) in inches to specify the size of the overall figure. The default value is set to ``None``, meaning the size will be set by the default backend. Examples ======== .. plot:: :context: reset :format: doctest :include-source: True >>> from sympy import symbols, cos, sin >>> from sympy.plotting import plot3d_parametric_line >>> u = symbols('u') Single plot. .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot3d_parametric_line(cos(u), sin(u), u, (u, -5, 5)) Plot object containing: [0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0) Multiple plots. .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot3d_parametric_line((cos(u), sin(u), u, (u, -5, 5)), ... (sin(u), u**2, u, (u, -5, 5))) Plot object containing: [0]: 3D parametric cartesian line: (cos(u), sin(u), u) for u over (-5.0, 5.0) [1]: 3D parametric cartesian line: (sin(u), u**2, u) for u over (-5.0, 5.0) See Also ======== Plot, Parametric3DLineSeries """ args = list(map(sympify, args)) series = [] plot_expr = check_arguments(args, 3, 1) series = [Parametric3DLineSeries(*arg, **kwargs) for arg in plot_expr] plots = Plot(*series, **kwargs) if show: plots.show() return plots def plot3d(*args, show=True, **kwargs): """ Plots a 3D surface plot. Usage ===== Single plot ``plot3d(expr, range_x, range_y, **kwargs)`` If the ranges are not specified, then a default range of (-10, 10) is used. Multiple plot with the same range. ``plot3d(expr1, expr2, range_x, range_y, **kwargs)`` If the ranges are not specified, then a default range of (-10, 10) is used. Multiple plots with different ranges. ``plot3d((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)`` Ranges have to be specified for every expression. Default range may change in the future if a more advanced default range detection algorithm is implemented. Arguments ========= ``expr`` : Expression representing the function along x. ``range_x``: (x, 0, 5), A 3-tuple denoting the range of the x variable. ``range_y``: (y, 0, 5), A 3-tuple denoting the range of the y variable. Keyword Arguments ================= Arguments for ``SurfaceOver2DRangeSeries`` class: ``nb_of_points_x``: int. The x range is sampled uniformly at ``nb_of_points_x`` of points. ``nb_of_points_y``: int. The y range is sampled uniformly at ``nb_of_points_y`` of points. Aesthetics: ``surface_color``: Function which returns a float. Specifies the color for the surface of the plot. See ``sympy.plotting.Plot`` for more details. If there are multiple plots, then the same series arguments are applied to all the plots. If you want to set these options separately, you can index the returned ``Plot`` object and set it. Arguments for ``Plot`` class: ``title`` : str. Title of the plot. ``size`` : (float, float), optional A tuple in the form (width, height) in inches to specify the size of the overall figure. The default value is set to ``None``, meaning the size will be set by the default backend. Examples ======== .. plot:: :context: reset :format: doctest :include-source: True >>> from sympy import symbols >>> from sympy.plotting import plot3d >>> x, y = symbols('x y') Single plot .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot3d(x*y, (x, -5, 5), (y, -5, 5)) Plot object containing: [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0) Multiple plots with same range .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot3d(x*y, -x*y, (x, -5, 5), (y, -5, 5)) Plot object containing: [0]: cartesian surface: x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0) [1]: cartesian surface: -x*y for x over (-5.0, 5.0) and y over (-5.0, 5.0) Multiple plots with different ranges. .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot3d((x**2 + y**2, (x, -5, 5), (y, -5, 5)), ... (x*y, (x, -3, 3), (y, -3, 3))) Plot object containing: [0]: cartesian surface: x**2 + y**2 for x over (-5.0, 5.0) and y over (-5.0, 5.0) [1]: cartesian surface: x*y for x over (-3.0, 3.0) and y over (-3.0, 3.0) See Also ======== Plot, SurfaceOver2DRangeSeries """ args = list(map(sympify, args)) series = [] plot_expr = check_arguments(args, 1, 2) series = [SurfaceOver2DRangeSeries(*arg, **kwargs) for arg in plot_expr] plots = Plot(*series, **kwargs) if show: plots.show() return plots def plot3d_parametric_surface(*args, show=True, **kwargs): """ Plots a 3D parametric surface plot. Usage ===== Single plot. ``plot3d_parametric_surface(expr_x, expr_y, expr_z, range_u, range_v, **kwargs)`` If the ranges is not specified, then a default range of (-10, 10) is used. Multiple plots. ``plot3d_parametric_surface((expr_x, expr_y, expr_z, range_u, range_v), ..., **kwargs)`` Ranges have to be specified for every expression. Default range may change in the future if a more advanced default range detection algorithm is implemented. Arguments ========= ``expr_x``: Expression representing the function along ``x``. ``expr_y``: Expression representing the function along ``y``. ``expr_z``: Expression representing the function along ``z``. ``range_u``: ``(u, 0, 5)``, A 3-tuple denoting the range of the ``u`` variable. ``range_v``: ``(v, 0, 5)``, A 3-tuple denoting the range of the v variable. Keyword Arguments ================= Arguments for ``ParametricSurfaceSeries`` class: ``nb_of_points_u``: int. The ``u`` range is sampled uniformly at ``nb_of_points_v`` of points ``nb_of_points_y``: int. The ``v`` range is sampled uniformly at ``nb_of_points_y`` of points Aesthetics: ``surface_color``: Function which returns a float. Specifies the color for the surface of the plot. See ``sympy.plotting.Plot`` for more details. If there are multiple plots, then the same series arguments are applied for all the plots. If you want to set these options separately, you can index the returned ``Plot`` object and set it. Arguments for ``Plot`` class: ``title`` : str. Title of the plot. ``size`` : (float, float), optional A tuple in the form (width, height) in inches to specify the size of the overall figure. The default value is set to ``None``, meaning the size will be set by the default backend. Examples ======== .. plot:: :context: reset :format: doctest :include-source: True >>> from sympy import symbols, cos, sin >>> from sympy.plotting import plot3d_parametric_surface >>> u, v = symbols('u v') Single plot. .. plot:: :context: close-figs :format: doctest :include-source: True >>> plot3d_parametric_surface(cos(u + v), sin(u - v), u - v, ... (u, -5, 5), (v, -5, 5)) Plot object containing: [0]: parametric cartesian surface: (cos(u + v), sin(u - v), u - v) for u over (-5.0, 5.0) and v over (-5.0, 5.0) See Also ======== Plot, ParametricSurfaceSeries """ args = list(map(sympify, args)) series = [] plot_expr = check_arguments(args, 3, 2) series = [ParametricSurfaceSeries(*arg, **kwargs) for arg in plot_expr] plots = Plot(*series, **kwargs) if show: plots.show() return plots def plot_contour(*args, show=True, **kwargs): """ Draws contour plot of a function Usage ===== Single plot ``plot_contour(expr, range_x, range_y, **kwargs)`` If the ranges are not specified, then a default range of (-10, 10) is used. Multiple plot with the same range. ``plot_contour(expr1, expr2, range_x, range_y, **kwargs)`` If the ranges are not specified, then a default range of (-10, 10) is used. Multiple plots with different ranges. ``plot_contour((expr1, range_x, range_y), (expr2, range_x, range_y), ..., **kwargs)`` Ranges have to be specified for every expression. Default range may change in the future if a more advanced default range detection algorithm is implemented. Arguments ========= ``expr`` : Expression representing the function along x. ``range_x``: (x, 0, 5), A 3-tuple denoting the range of the x variable. ``range_y``: (y, 0, 5), A 3-tuple denoting the range of the y variable. Keyword Arguments ================= Arguments for ``ContourSeries`` class: ``nb_of_points_x``: int. The x range is sampled uniformly at ``nb_of_points_x`` of points. ``nb_of_points_y``: int. The y range is sampled uniformly at ``nb_of_points_y`` of points. Aesthetics: ``surface_color``: Function which returns a float. Specifies the color for the surface of the plot. See ``sympy.plotting.Plot`` for more details. If there are multiple plots, then the same series arguments are applied to all the plots. If you want to set these options separately, you can index the returned ``Plot`` object and set it. Arguments for ``Plot`` class: ``title`` : str. Title of the plot. ``size`` : (float, float), optional A tuple in the form (width, height) in inches to specify the size of the overall figure. The default value is set to ``None``, meaning the size will be set by the default backend. See Also ======== Plot, ContourSeries """ args = list(map(sympify, args)) plot_expr = check_arguments(args, 1, 2) series = [ContourSeries(*arg) for arg in plot_expr] plot_contours = Plot(*series, **kwargs) if len(plot_expr[0].free_symbols) > 2: raise ValueError('Contour Plot cannot Plot for more than two variables.') if show: plot_contours.show() return plot_contours def check_arguments(args, expr_len, nb_of_free_symbols): """ Checks the arguments and converts into tuples of the form (exprs, ranges) Examples ======== .. plot:: :context: reset :format: doctest :include-source: True >>> from sympy import cos, sin, symbols >>> from sympy.plotting.plot import check_arguments >>> x = symbols('x') >>> check_arguments([cos(x), sin(x)], 2, 1) [(cos(x), sin(x), (x, -10, 10))] >>> check_arguments([x, x**2], 1, 1) [(x, (x, -10, 10)), (x**2, (x, -10, 10))] """ if not args: return [] if expr_len > 1 and isinstance(args[0], Expr): # Multiple expressions same range. # The arguments are tuples when the expression length is # greater than 1. if len(args) < expr_len: raise ValueError("len(args) should not be less than expr_len") for i in range(len(args)): if isinstance(args[i], Tuple): break else: i = len(args) + 1 exprs = Tuple(*args[:i]) free_symbols = list(set().union(*[e.free_symbols for e in exprs])) if len(args) == expr_len + nb_of_free_symbols: #Ranges given plots = [exprs + Tuple(*args[expr_len:])] else: default_range = Tuple(-10, 10) ranges = [] for symbol in free_symbols: ranges.append(Tuple(symbol) + default_range) for i in range(len(free_symbols) - nb_of_free_symbols): ranges.append(Tuple(Dummy()) + default_range) plots = [exprs + Tuple(*ranges)] return plots if isinstance(args[0], Expr) or (isinstance(args[0], Tuple) and len(args[0]) == expr_len and expr_len != 3): # Cannot handle expressions with number of expression = 3. It is # not possible to differentiate between expressions and ranges. #Series of plots with same range for i in range(len(args)): if isinstance(args[i], Tuple) and len(args[i]) != expr_len: break if not isinstance(args[i], Tuple): args[i] = Tuple(args[i]) else: i = len(args) + 1 exprs = args[:i] assert all(isinstance(e, Expr) for expr in exprs for e in expr) free_symbols = list(set().union(*[e.free_symbols for expr in exprs for e in expr])) if len(free_symbols) > nb_of_free_symbols: raise ValueError("The number of free_symbols in the expression " "is greater than %d" % nb_of_free_symbols) if len(args) == i + nb_of_free_symbols and isinstance(args[i], Tuple): ranges = Tuple(*[range_expr for range_expr in args[ i:i + nb_of_free_symbols]]) plots = [expr + ranges for expr in exprs] return plots else: # Use default ranges. default_range = Tuple(-10, 10) ranges = [] for symbol in free_symbols: ranges.append(Tuple(symbol) + default_range) for i in range(nb_of_free_symbols - len(free_symbols)): ranges.append(Tuple(Dummy()) + default_range) ranges = Tuple(*ranges) plots = [expr + ranges for expr in exprs] return plots elif isinstance(args[0], Tuple) and len(args[0]) == expr_len + nb_of_free_symbols: # Multiple plots with different ranges. for arg in args: for i in range(expr_len): if not isinstance(arg[i], Expr): raise ValueError("Expected an expression, given %s" % str(arg[i])) for i in range(nb_of_free_symbols): if not len(arg[i + expr_len]) == 3: raise ValueError("The ranges should be a tuple of " "length 3, got %s" % str(arg[i + expr_len])) return args
b8f861e47a4c0bd731efcc998a74a2ae1d0f4953676391bc24d3fceab12f17c4
from sympy import (S, Symbol, Interval, exp, Or, symbols, Eq, cos, And, Tuple, integrate, oo, sin, Sum, Basic, Indexed, DiracDelta, Lambda, log, pi, FallingFactorial, Rational, Matrix) from sympy.stats import (Die, Normal, Exponential, FiniteRV, P, E, H, variance, density, given, independent, dependent, where, pspace, GaussianUnitaryEnsemble, random_symbols, sample, Geometric, factorial_moment, Binomial, Hypergeometric, DiscreteUniform, Poisson, characteristic_function, moment_generating_function, BernoulliProcess, Variance, Expectation, Probability, Covariance, covariance) from sympy.stats.rv import (IndependentProductPSpace, rs_swap, Density, NamedArgsMixin, RandomSymbol, sample_iter, PSpace, is_random, RandomIndexedSymbol, RandomMatrixSymbol) from sympy.testing.pytest import raises, skip, XFAIL, ignore_warnings from sympy.external import import_module from sympy.core.numbers import comp from sympy.stats.frv_types import BernoulliDistribution def test_where(): X, Y = Die('X'), Die('Y') Z = Normal('Z', 0, 1) assert where(Z**2 <= 1).set == Interval(-1, 1) assert where(Z**2 <= 1).as_boolean() == Interval(-1, 1).as_relational(Z.symbol) assert where(And(X > Y, Y > 4)).as_boolean() == And( Eq(X.symbol, 6), Eq(Y.symbol, 5)) assert len(where(X < 3).set) == 2 assert 1 in where(X < 3).set X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) assert where(And(X**2 <= 1, X >= 0)).set == Interval(0, 1) XX = given(X, And(X**2 <= 1, X >= 0)) assert XX.pspace.domain.set == Interval(0, 1) assert XX.pspace.domain.as_boolean() == \ And(0 <= X.symbol, X.symbol**2 <= 1, -oo < X.symbol, X.symbol < oo) with raises(TypeError): XX = given(X, X + 3) def test_random_symbols(): X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) assert set(random_symbols(2*X + 1)) == {X} assert set(random_symbols(2*X + Y)) == {X, Y} assert set(random_symbols(2*X + Y.symbol)) == {X} assert set(random_symbols(2)) == set() def test_characteristic_function(): # Imports I from sympy from sympy import I X = Normal('X',0,1) Y = DiscreteUniform('Y', [1,2,7]) Z = Poisson('Z', 2) t = symbols('_t') P = Lambda(t, exp(-t**2/2)) Q = Lambda(t, exp(7*t*I)/3 + exp(2*t*I)/3 + exp(t*I)/3) R = Lambda(t, exp(2 * exp(t*I) - 2)) assert characteristic_function(X).dummy_eq(P) assert characteristic_function(Y).dummy_eq(Q) assert characteristic_function(Z).dummy_eq(R) def test_moment_generating_function(): X = Normal('X',0,1) Y = DiscreteUniform('Y', [1,2,7]) Z = Poisson('Z', 2) t = symbols('_t') P = Lambda(t, exp(t**2/2)) Q = Lambda(t, (exp(7*t)/3 + exp(2*t)/3 + exp(t)/3)) R = Lambda(t, exp(2 * exp(t) - 2)) assert moment_generating_function(X).dummy_eq(P) assert moment_generating_function(Y).dummy_eq(Q) assert moment_generating_function(Z).dummy_eq(R) def test_sample_iter(): X = Normal('X',0,1) Y = DiscreteUniform('Y', [1, 2, 7]) Z = Poisson('Z', 2) scipy = import_module('scipy') if not scipy: skip('Scipy is not installed. Abort tests') expr = X**2 + 3 iterator = sample_iter(expr) expr2 = Y**2 + 5*Y + 4 iterator2 = sample_iter(expr2) expr3 = Z**3 + 4 iterator3 = sample_iter(expr3) def is_iterator(obj): if ( hasattr(obj, '__iter__') and (hasattr(obj, 'next') or hasattr(obj, '__next__')) and callable(obj.__iter__) and obj.__iter__() is obj ): return True else: return False assert is_iterator(iterator) assert is_iterator(iterator2) assert is_iterator(iterator3) U = Normal('U', -1, 1) itr_inf_1 = sample_iter(U, seed=0) itr_inf_2 = sample_iter(U, seed=0) for _ in range(10): assert next(itr_inf_1) == next(itr_inf_2) def test_pspace(): X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) x = Symbol('x') raises(ValueError, lambda: pspace(5 + 3)) raises(ValueError, lambda: pspace(x < 1)) assert pspace(X) == X.pspace assert pspace(2*X + 1) == X.pspace assert pspace(2*X + Y) == IndependentProductPSpace(Y.pspace, X.pspace) def test_rs_swap(): X = Normal('x', 0, 1) Y = Exponential('y', 1) XX = Normal('x', 0, 2) YY = Normal('y', 0, 3) expr = 2*X + Y assert expr.subs(rs_swap((X, Y), (YY, XX))) == 2*XX + YY def test_RandomSymbol(): X = Normal('x', 0, 1) Y = Normal('x', 0, 2) assert X.symbol == Y.symbol assert X != Y assert X.name == X.symbol.name X = Normal('lambda', 0, 1) # make sure we can use protected terms X = Normal('Lambda', 0, 1) # make sure we can use SymPy terms def test_RandomSymbol_diff(): X = Normal('x', 0, 1) assert (2*X).diff(X) def test_random_symbol_no_pspace(): x = RandomSymbol(Symbol('x')) assert x.pspace == PSpace() def test_overlap(): X = Normal('x', 0, 1) Y = Normal('x', 0, 2) raises(ValueError, lambda: P(X > Y)) def test_IndependentProductPSpace(): X = Normal('X', 0, 1) Y = Normal('Y', 0, 1) px = X.pspace py = Y.pspace assert pspace(X + Y) == IndependentProductPSpace(px, py) assert pspace(X + Y) == IndependentProductPSpace(py, px) def test_E(): assert E(5) == 5 def test_H(): X = Normal('X', 0, 1) D = Die('D', sides = 4) G = Geometric('G', 0.5) assert H(X, X > 0) == -log(2)/2 + S.Half + log(pi)/2 assert H(D, D > 2) == log(2) assert comp(H(G).evalf().round(2), 1.39) def test_Sample(): X = Die('X', 6) Y = Normal('Y', 0, 1) z = Symbol('z', integer=True) scipy = import_module('scipy') if not scipy: skip('Scipy is not installed. Abort tests') with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed assert next(sample(X)) in [1, 2, 3, 4, 5, 6] assert isinstance(next(sample(X + Y)), float) assert P(X + Y > 0, Y < 0, numsamples=10).is_number assert E(X + Y, numsamples=10).is_number assert E(X**2 + Y, numsamples=10).is_number assert E((X + Y)**2, numsamples=10).is_number assert variance(X + Y, numsamples=10).is_number raises(TypeError, lambda: P(Y > z, numsamples=5)) assert P(sin(Y) <= 1, numsamples=10) == 1 assert P(sin(Y) <= 1, cos(Y) < 1, numsamples=10) == 1 assert all(i in range(1, 7) for i in density(X, numsamples=10)) assert all(i in range(4, 7) for i in density(X, X>3, numsamples=10)) @XFAIL def test_samplingE(): scipy = import_module('scipy') if not scipy: skip('Scipy is not installed. Abort tests') Y = Normal('Y', 0, 1) z = Symbol('z', integer=True) assert E(Sum(1/z**Y, (z, 1, oo)), Y > 2, numsamples=3).is_number def test_given(): X = Normal('X', 0, 1) Y = Normal('Y', 0, 1) A = given(X, True) B = given(X, Y > 2) assert X == A == B def test_factorial_moment(): X = Poisson('X', 2) Y = Binomial('Y', 2, S.Half) Z = Hypergeometric('Z', 4, 2, 2) assert factorial_moment(X, 2) == 4 assert factorial_moment(Y, 2) == S.Half assert factorial_moment(Z, 2) == Rational(1, 3) x, y, z, l = symbols('x y z l') Y = Binomial('Y', 2, y) Z = Hypergeometric('Z', 10, 2, 3) assert factorial_moment(Y, l) == y**2*FallingFactorial( 2, l) + 2*y*(1 - y)*FallingFactorial(1, l) + (1 - y)**2*\ FallingFactorial(0, l) assert factorial_moment(Z, l) == 7*FallingFactorial(0, l)/\ 15 + 7*FallingFactorial(1, l)/15 + FallingFactorial(2, l)/15 def test_dependence(): X, Y = Die('X'), Die('Y') assert independent(X, 2*Y) assert not dependent(X, 2*Y) X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) assert independent(X, Y) assert dependent(X, 2*X) # Create a dependency XX, YY = given(Tuple(X, Y), Eq(X + Y, 3)) assert dependent(XX, YY) def test_dependent_finite(): X, Y = Die('X'), Die('Y') # Dependence testing requires symbolic conditions which currently break # finite random variables assert dependent(X, Y + X) XX, YY = given(Tuple(X, Y), X + Y > 5) # Create a dependency assert dependent(XX, YY) def test_normality(): X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) x = Symbol('x', real=True, finite=True) z = Symbol('z', real=True, finite=True) dens = density(X - Y, Eq(X + Y, z)) assert integrate(dens(x), (x, -oo, oo)) == 1 def test_Density(): X = Die('X', 6) d = Density(X) assert d.doit() == density(X) def test_NamedArgsMixin(): class Foo(Basic, NamedArgsMixin): _argnames = 'foo', 'bar' a = Foo(1, 2) assert a.foo == 1 assert a.bar == 2 raises(AttributeError, lambda: a.baz) class Bar(Basic, NamedArgsMixin): pass raises(AttributeError, lambda: Bar(1, 2).foo) def test_density_constant(): assert density(3)(2) == 0 assert density(3)(3) == DiracDelta(0) def test_real(): x = Normal('x', 0, 1) assert x.is_real def test_issue_10052(): X = Exponential('X', 3) assert P(X < oo) == 1 assert P(X > oo) == 0 assert P(X < 2, X > oo) == 0 assert P(X < oo, X > oo) == 0 assert P(X < oo, X > 2) == 1 assert P(X < 3, X == 2) == 0 raises(ValueError, lambda: P(1)) raises(ValueError, lambda: P(X < 1, 2)) def test_issue_11934(): density = {0: .5, 1: .5} X = FiniteRV('X', density) assert E(X) == 0.5 assert P( X>= 2) == 0 def test_issue_8129(): X = Exponential('X', 4) assert P(X >= X) == 1 assert P(X > X) == 0 assert P(X > X+1) == 0 def test_issue_12237(): X = Normal('X', 0, 1) Y = Normal('Y', 0, 1) U = P(X > 0, X) V = P(Y < 0, X) W = P(X + Y > 0, X) assert W == P(X + Y > 0, X) assert U == BernoulliDistribution(S.Half, S.Zero, S.One) assert V == S.Half def test_is_random(): X = Normal('X', 0, 1) Y = Normal('Y', 0, 1) a, b = symbols('a, b') G = GaussianUnitaryEnsemble('U', 2) B = BernoulliProcess('B', 0.9) assert not is_random(a) assert not is_random(a + b) assert not is_random(a * b) assert not is_random(Matrix([a**2, b**2])) assert is_random(X) assert is_random(X**2 + Y) assert is_random(Y + b**2) assert is_random(Y > 5) assert is_random(B[3] < 1) assert is_random(G) assert is_random(X * Y * B[1]) assert is_random(Matrix([[X, B[2]], [G, Y]])) assert is_random(Eq(X, 4)) def test_issue_12283(): x = symbols('x') X = RandomSymbol(x) Y = RandomSymbol('Y') Z = RandomMatrixSymbol('Z', 2, 1) W = RandomMatrixSymbol('W', 2, 1) RI = RandomIndexedSymbol(Indexed('RI', 3)) assert pspace(Z) == PSpace() assert pspace(RI) == PSpace() assert pspace(X) == PSpace() assert E(X) == Expectation(X) assert P(Y > 3) == Probability(Y > 3) assert variance(X) == Variance(X) assert variance(RI) == Variance(RI) assert covariance(X, Y) == Covariance(X, Y) assert covariance(W, Z) == Covariance(W, Z) def test_issue_6810(): X = Die('X', 6) Y = Normal('Y', 0, 1) assert P(Eq(X, 2)) == S(1)/6 assert P(Eq(Y, 0)) == 0 assert P(Or(X > 2, X < 3)) == 1 assert P(And(X > 3, X > 2)) == S(1)/2
a4e09cc339aff3feb28a872ac2075f4120cfef498380b93b65e26ddc35f562fa
from sympy import (S, symbols, FiniteSet, Eq, Matrix, MatrixSymbol, Float, And, ImmutableMatrix, Ne, Lt, Gt, exp, Not, Rational, Lambda, erf, Piecewise, factorial, Interval, oo, Contains, sqrt, pi, ceiling, gamma, lowergamma, Sum, Range, Tuple, ImmutableDenseMatrix, Symbol) from sympy.stats import (DiscreteMarkovChain, P, TransitionMatrixOf, E, StochasticStateSpaceOf, variance, ContinuousMarkovChain, BernoulliProcess, PoissonProcess, WienerProcess, GammaProcess, sample_stochastic_process) from sympy.stats.joint_rv import JointDistribution from sympy.stats.joint_rv_types import JointDistributionHandmade from sympy.stats.rv import RandomIndexedSymbol from sympy.stats.symbolic_probability import Probability, Expectation from sympy.testing.pytest import raises, skip, ignore_warnings from sympy.external import import_module from sympy.stats.frv_types import BernoulliDistribution from sympy.stats.drv_types import PoissonDistribution from sympy.stats.crv_types import NormalDistribution, GammaDistribution from sympy.core.symbol import Str def test_DiscreteMarkovChain(): # pass only the name X = DiscreteMarkovChain("X") assert isinstance(X.state_space, Range) assert X.index_set == S.Naturals0 assert isinstance(X.transition_probabilities, MatrixSymbol) t = symbols('t', positive=True, integer=True) assert isinstance(X[t], RandomIndexedSymbol) assert E(X[0]) == Expectation(X[0]) raises(TypeError, lambda: DiscreteMarkovChain(1)) raises(NotImplementedError, lambda: X(t)) nz = Symbol('n', integer=True) TZ = MatrixSymbol('M', nz, nz) SZ = Range(nz) YZ = DiscreteMarkovChain('Y', SZ, TZ) assert P(Eq(YZ[2], 1), Eq(YZ[1], 0)) == TZ[0, 1] raises(ValueError, lambda: sample_stochastic_process(t)) raises(ValueError, lambda: next(sample_stochastic_process(X))) # pass name and state_space # any hashable object should be a valid state # states should be valid as a tuple/set/list/Tuple/Range sym, rainy, cloudy, sunny = symbols('a Rainy Cloudy Sunny', real=True) state_spaces = [(1, 2, 3), [Str('Hello'), sym, DiscreteMarkovChain], Tuple(1, exp(sym), Str('World'), sympify=False), Range(-1, 5, 2), [rainy, cloudy, sunny]] chains = [DiscreteMarkovChain("Y", state_space) for state_space in state_spaces] for i, Y in enumerate(chains): assert isinstance(Y.transition_probabilities, MatrixSymbol) assert Y.state_space == state_spaces[i] or Y.state_space == FiniteSet(*state_spaces[i]) assert Y.number_of_states == 3 with ignore_warnings(UserWarning): # TODO: Restore tests once warnings are removed assert P(Eq(Y[2], 1), Eq(Y[0], 2), evaluate=False) == Probability(Eq(Y[2], 1), Eq(Y[0], 2)) assert E(Y[0]) == Expectation(Y[0]) raises(ValueError, lambda: next(sample_stochastic_process(Y))) raises(TypeError, lambda: DiscreteMarkovChain("Y", dict((1, 1)))) Y = DiscreteMarkovChain("Y", Range(1, t, 2)) assert Y.number_of_states == ceiling((t-1)/2) # pass name and transition_probabilities chains = [DiscreteMarkovChain("Y", trans_probs=Matrix([[]])), DiscreteMarkovChain("Y", trans_probs=Matrix([[0, 1], [1, 0]])), DiscreteMarkovChain("Y", trans_probs=Matrix([[pi, 1-pi], [sym, 1-sym]]))] for Z in chains: assert Z.number_of_states == Z.transition_probabilities.shape[0] assert isinstance(Z.transition_probabilities, ImmutableDenseMatrix) # pass name, state_space and transition_probabilities T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]]) TS = MatrixSymbol('T', 3, 3) Y = DiscreteMarkovChain("Y", [0, 1, 2], T) YS = DiscreteMarkovChain("Y", ['One', 'Two', 3], TS) assert YS._transient2transient() == None assert YS._transient2absorbing() == None assert Y.joint_distribution(1, Y[2], 3) == JointDistribution(Y[1], Y[2], Y[3]) raises(ValueError, lambda: Y.joint_distribution(Y[1].symbol, Y[2].symbol)) assert P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2) == Float(0.36, 2) assert (P(Eq(YS[3], 2), Eq(YS[1], 1)) - (TS[0, 2]*TS[1, 0] + TS[1, 1]*TS[1, 2] + TS[1, 2]*TS[2, 2])).simplify() == 0 assert P(Eq(YS[1], 1), Eq(YS[2], 2)) == Probability(Eq(YS[1], 1)) assert P(Eq(YS[3], 3), Eq(YS[1], 1)) == TS[0, 2]*TS[1, 0] + TS[1, 1]*TS[1, 2] + TS[1, 2]*TS[2, 2] TO = Matrix([[0.25, 0.75, 0],[0, 0.25, 0.75],[0.75, 0, 0.25]]) assert P(Eq(Y[3], 2), Eq(Y[1], 1) & TransitionMatrixOf(Y, TO)).round(3) == Float(0.375, 3) with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed assert E(Y[3], evaluate=False) == Expectation(Y[3]) assert E(Y[3], Eq(Y[2], 1)).round(2) == Float(1.1, 3) TSO = MatrixSymbol('T', 4, 4) raises(ValueError, lambda: str(P(Eq(YS[3], 2), Eq(YS[1], 1) & TransitionMatrixOf(YS, TSO)))) raises(TypeError, lambda: DiscreteMarkovChain("Z", [0, 1, 2], symbols('M'))) raises(ValueError, lambda: DiscreteMarkovChain("Z", [0, 1, 2], MatrixSymbol('T', 3, 4))) raises(ValueError, lambda: E(Y[3], Eq(Y[2], 6))) raises(ValueError, lambda: E(Y[2], Eq(Y[3], 1))) # extended tests for probability queries TO1 = Matrix([[Rational(1, 4), Rational(3, 4), 0],[Rational(1, 3), Rational(1, 3), Rational(1, 3)],[0, Rational(1, 4), Rational(3, 4)]]) assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)), Eq(Probability(Eq(Y[0], 0)), Rational(1, 4)) & TransitionMatrixOf(Y, TO1)) == Rational(1, 16) assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)), TransitionMatrixOf(Y, TO1)) == \ Probability(Eq(Y[0], 0))/4 assert P(Lt(X[1], 2) & Gt(X[1], 0), Eq(X[0], 2) & StochasticStateSpaceOf(X, [0, 1, 2]) & TransitionMatrixOf(X, TO1)) == Rational(1, 4) assert P(Lt(X[1], 2) & Gt(X[1], 0), Eq(X[0], 2) & StochasticStateSpaceOf(X, [None, 'None', 1]) & TransitionMatrixOf(X, TO1)) == Rational(1, 4) assert P(Ne(X[1], 2) & Ne(X[1], 1), Eq(X[0], 2) & StochasticStateSpaceOf(X, [0, 1, 2]) & TransitionMatrixOf(X, TO1)) is S.Zero assert P(Ne(X[1], 2) & Ne(X[1], 1), Eq(X[0], 2) & StochasticStateSpaceOf(X, [None, 'None', 1]) & TransitionMatrixOf(X, TO1)) is S.Zero assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)), Eq(Y[1], 1)) == 0.1*Probability(Eq(Y[0], 0)) # testing properties of Markov chain TO2 = Matrix([[S.One, 0, 0],[Rational(1, 3), Rational(1, 3), Rational(1, 3)],[0, Rational(1, 4), Rational(3, 4)]]) TO3 = Matrix([[Rational(1, 4), Rational(3, 4), 0],[Rational(1, 3), Rational(1, 3), Rational(1, 3)],[0, Rational(1, 4), Rational(3, 4)]]) Y2 = DiscreteMarkovChain('Y', trans_probs=TO2) Y3 = DiscreteMarkovChain('Y', trans_probs=TO3) assert Y3._transient2absorbing() == None raises (ValueError, lambda: Y3.fundamental_matrix()) assert Y2.is_absorbing_chain() == True assert Y3.is_absorbing_chain() == False TO4 = Matrix([[Rational(1, 5), Rational(2, 5), Rational(2, 5)], [Rational(1, 10), S.Half, Rational(2, 5)], [Rational(3, 5), Rational(3, 10), Rational(1, 10)]]) Y4 = DiscreteMarkovChain('Y', trans_probs=TO4) w = ImmutableMatrix([[Rational(11, 39), Rational(16, 39), Rational(4, 13)]]) assert Y4.limiting_distribution == w assert Y4.is_regular() == True TS1 = MatrixSymbol('T', 3, 3) Y5 = DiscreteMarkovChain('Y', trans_probs=TS1) assert Y5.limiting_distribution(w, TO4).doit() == True assert Y5.stationary_distribution(condition_set=True).subs(TS1, TO4).contains(w).doit() == S.true TO6 = Matrix([[S.One, 0, 0, 0, 0],[S.Half, 0, S.Half, 0, 0],[0, S.Half, 0, S.Half, 0], [0, 0, S.Half, 0, S.Half], [0, 0, 0, 0, 1]]) Y6 = DiscreteMarkovChain('Y', trans_probs=TO6) assert Y6._transient2absorbing() == ImmutableMatrix([[S.Half, 0], [0, 0], [0, S.Half]]) assert Y6._transient2transient() == ImmutableMatrix([[0, S.Half, 0], [S.Half, 0, S.Half], [0, S.Half, 0]]) assert Y6.fundamental_matrix() == ImmutableMatrix([[Rational(3, 2), S.One, S.Half], [S.One, S(2), S.One], [S.Half, S.One, Rational(3, 2)]]) assert Y6.absorbing_probabilities() == ImmutableMatrix([[Rational(3, 4), Rational(1, 4)], [S.Half, S.Half], [Rational(1, 4), Rational(3, 4)]]) # test for zero-sized matrix functionality X = DiscreteMarkovChain('X', trans_probs=Matrix([[]])) assert X.number_of_states == 0 assert X.stationary_distribution() == Matrix([[]]) # test communication_class # see https://drive.google.com/drive/folders/1HbxLlwwn2b3U8Lj7eb_ASIUb5vYaNIjg?usp=sharing # tutorial 2.pdf TO7 = Matrix([[0, 5, 5, 0, 0], [0, 0, 0, 10, 0], [5, 0, 5, 0, 0], [0, 10, 0, 0, 0], [0, 3, 0, 3, 4]])/10 Y7 = DiscreteMarkovChain('Y', trans_probs=TO7) tuples = Y7.communication_classes() classes, recurrence, periods = list(zip(*tuples)) assert classes == ([1, 3], [0, 2], [4]) assert recurrence == (True, False, False) assert periods == (2, 1, 1) TO8 = Matrix([[0, 0, 0, 10, 0, 0], [5, 0, 5, 0, 0, 0], [0, 4, 0, 0, 0, 6], [10, 0, 0, 0, 0, 0], [0, 10, 0, 0, 0, 0], [0, 0, 0, 5, 5, 0]])/10 Y8 = DiscreteMarkovChain('Y', trans_probs=TO8) tuples = Y8.communication_classes() classes, recurrence, periods = list(zip(*tuples)) assert classes == ([0, 3], [1, 2, 5, 4]) assert recurrence == (True, False) assert periods == (2, 2) TO9 = Matrix([[2, 0, 0, 3, 0, 0, 3, 2, 0, 0], [0, 10, 0, 0, 0, 0, 0, 0, 0, 0], [0, 2, 2, 0, 0, 0, 0, 0, 3, 3], [0, 0, 0, 3, 0, 0, 6, 1, 0, 0], [0, 0, 0, 0, 5, 5, 0, 0, 0, 0], [0, 0, 0, 0, 0, 10, 0, 0, 0, 0], [4, 0, 0, 5, 0, 0, 1, 0, 0, 0], [2, 0, 0, 4, 0, 0, 2, 2, 0, 0], [3, 0, 1, 0, 0, 0, 0, 0, 4, 2], [0, 0, 4, 0, 0, 0, 0, 0, 3, 3]])/10 Y9 = DiscreteMarkovChain('Y', trans_probs=TO9) tuples = Y9.communication_classes() classes, recurrence, periods = list(zip(*tuples)) assert classes == ([0, 3, 6, 7], [1], [2, 8, 9], [5], [4]) assert recurrence == (True, True, False, True, False) assert periods == (1, 1, 1, 1, 1) # test custom state space Y10 = DiscreteMarkovChain('Y', [1, 2, 3], TO2) tuples = Y10.communication_classes() classes, recurrence, periods = list(zip(*tuples)) assert classes == ([1], [2, 3]) assert recurrence == (True, False) assert periods == (1, 1) # testing miscellaneous queries T = Matrix([[S.Half, Rational(1, 4), Rational(1, 4)], [Rational(1, 3), 0, Rational(2, 3)], [S.Half, S.Half, 0]]) X = DiscreteMarkovChain('X', [0, 1, 2], T) assert P(Eq(X[1], 2) & Eq(X[2], 1) & Eq(X[3], 0), Eq(P(Eq(X[1], 0)), Rational(1, 4)) & Eq(P(Eq(X[1], 1)), Rational(1, 4))) == Rational(1, 12) assert P(Eq(X[2], 1) | Eq(X[2], 2), Eq(X[1], 1)) == Rational(2, 3) assert P(Eq(X[2], 1) & Eq(X[2], 2), Eq(X[1], 1)) is S.Zero assert P(Ne(X[2], 2), Eq(X[1], 1)) == Rational(1, 3) assert E(X[1]**2, Eq(X[0], 1)) == Rational(8, 3) assert variance(X[1], Eq(X[0], 1)) == Rational(8, 9) raises(ValueError, lambda: E(X[1], Eq(X[2], 1))) raises(ValueError, lambda: DiscreteMarkovChain('X', [0, 1], T)) # testing miscellaneous queries with different state space X = DiscreteMarkovChain('X', ['A', 'B', 'C'], T) assert P(Eq(X[1], 2) & Eq(X[2], 1) & Eq(X[3], 0), Eq(P(Eq(X[1], 0)), Rational(1, 4)) & Eq(P(Eq(X[1], 1)), Rational(1, 4))) == Rational(1, 12) assert P(Eq(X[2], 1) | Eq(X[2], 2), Eq(X[1], 1)) == Rational(2, 3) assert P(Eq(X[2], 1) & Eq(X[2], 2), Eq(X[1], 1)) is S.Zero assert P(Ne(X[2], 2), Eq(X[1], 1)) == Rational(1, 3) a = X.state_space.args[0] c = X.state_space.args[2] assert (E(X[1] ** 2, Eq(X[0], 1)) - (a**2/3 + 2*c**2/3)).simplify() == 0 assert (variance(X[1], Eq(X[0], 1)) - (2*(-a/3 + c/3)**2/3 + (2*a/3 - 2*c/3)**2/3)).simplify() == 0 raises(ValueError, lambda: E(X[1], Eq(X[2], 1))) def test_sample_stochastic_process(): if not import_module('scipy'): skip('SciPy Not installed. Skip sampling tests') import random random.seed(0) numpy = import_module('numpy') if numpy: numpy.random.seed(0) # scipy uses numpy to sample so to set its seed T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]]) Y = DiscreteMarkovChain("Y", [0, 1, 2], T) for samps in range(10): assert next(sample_stochastic_process(Y)) in Y.state_space Z = DiscreteMarkovChain("Z", ['1', 1, 0], T) for samps in range(10): assert next(sample_stochastic_process(Z)) in Z.state_space T = Matrix([[S.Half, Rational(1, 4), Rational(1, 4)], [Rational(1, 3), 0, Rational(2, 3)], [S.Half, S.Half, 0]]) X = DiscreteMarkovChain('X', [0, 1, 2], T) for samps in range(10): assert next(sample_stochastic_process(X)) in X.state_space W = DiscreteMarkovChain('W', [1, pi, oo], T) for samps in range(10): assert next(sample_stochastic_process(W)) in W.state_space def test_ContinuousMarkovChain(): T1 = Matrix([[S(-2), S(2), S.Zero], [S.Zero, S.NegativeOne, S.One], [Rational(3, 2), Rational(3, 2), S(-3)]]) C1 = ContinuousMarkovChain('C', [0, 1, 2], T1) assert C1.limiting_distribution() == ImmutableMatrix([[Rational(3, 19), Rational(12, 19), Rational(4, 19)]]) T2 = Matrix([[-S.One, S.One, S.Zero], [S.One, -S.One, S.Zero], [S.Zero, S.One, -S.One]]) C2 = ContinuousMarkovChain('C', [0, 1, 2], T2) A, t = C2.generator_matrix, symbols('t', positive=True) assert C2.transition_probabilities(A)(t) == Matrix([[S.Half + exp(-2*t)/2, S.Half - exp(-2*t)/2, 0], [S.Half - exp(-2*t)/2, S.Half + exp(-2*t)/2, 0], [S.Half - exp(-t) + exp(-2*t)/2, S.Half - exp(-2*t)/2, exp(-t)]]) with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed assert P(Eq(C2(1), 1), Eq(C2(0), 1), evaluate=False) == Probability(Eq(C2(1), 1), Eq(C2(0), 1)) assert P(Eq(C2(1), 1), Eq(C2(0), 1)) == exp(-2)/2 + S.Half assert P(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 1), Eq(P(Eq(C2(1), 0)), S.Half)) == (Rational(1, 4) - exp(-2)/4)*(exp(-2)/2 + S.Half) assert P(Not(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)) | (Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)), Eq(P(Eq(C2(1), 0)), Rational(1, 4)) & Eq(P(Eq(C2(1), 1)), Rational(1, 4))) is S.One assert E(C2(Rational(3, 2)), Eq(C2(0), 2)) == -exp(-3)/2 + 2*exp(Rational(-3, 2)) + S.Half assert variance(C2(Rational(3, 2)), Eq(C2(0), 1)) == ((S.Half - exp(-3)/2)**2*(exp(-3)/2 + S.Half) + (Rational(-1, 2) - exp(-3)/2)**2*(S.Half - exp(-3)/2)) raises(KeyError, lambda: P(Eq(C2(1), 0), Eq(P(Eq(C2(1), 1)), S.Half))) assert P(Eq(C2(1), 0), Eq(P(Eq(C2(5), 1)), S.Half)) == Probability(Eq(C2(1), 0)) TS1 = MatrixSymbol('G', 3, 3) CS1 = ContinuousMarkovChain('C', [0, 1, 2], TS1) A = CS1.generator_matrix assert CS1.transition_probabilities(A)(t) == exp(t*A) C3 = ContinuousMarkovChain('C', [Symbol('0'), Symbol('1'), Symbol('2')], T2) assert P(Eq(C3(1), 1), Eq(C3(0), 1)) == exp(-2)/2 + S.Half assert P(Eq(C3(1), Symbol('1')), Eq(C3(0), Symbol('1'))) == exp(-2)/2 + S.Half def test_BernoulliProcess(): B = BernoulliProcess("B", p=0.6, success=1, failure=0) assert B.state_space == FiniteSet(0, 1) assert B.index_set == S.Naturals0 assert B.success == 1 assert B.failure == 0 X = BernoulliProcess("X", p=Rational(1,3), success='H', failure='T') assert X.state_space == FiniteSet('H', 'T') H, T = symbols("H,T") assert E(X[1]+X[2]*X[3]) == H**2/9 + 4*H*T/9 + H/3 + 4*T**2/9 + 2*T/3 t, x = symbols('t, x', positive=True, integer=True) assert isinstance(B[t], RandomIndexedSymbol) raises(ValueError, lambda: BernoulliProcess("X", p=1.1, success=1, failure=0)) raises(NotImplementedError, lambda: B(t)) raises(IndexError, lambda: B[-3]) assert B.joint_distribution(B[3], B[9]) == JointDistributionHandmade(Lambda((B[3], B[9]), Piecewise((0.6, Eq(B[3], 1)), (0.4, Eq(B[3], 0)), (0, True)) *Piecewise((0.6, Eq(B[9], 1)), (0.4, Eq(B[9], 0)), (0, True)))) assert B.joint_distribution(2, B[4]) == JointDistributionHandmade(Lambda((B[2], B[4]), Piecewise((0.6, Eq(B[2], 1)), (0.4, Eq(B[2], 0)), (0, True)) *Piecewise((0.6, Eq(B[4], 1)), (0.4, Eq(B[4], 0)), (0, True)))) # Test for the sum distribution of Bernoulli Process RVs Y = B[1] + B[2] + B[3] assert P(Eq(Y, 0)).round(2) == Float(0.06, 1) assert P(Eq(Y, 2)).round(2) == Float(0.43, 2) assert P(Eq(Y, 4)).round(2) == 0 assert P(Gt(Y, 1)).round(2) == Float(0.65, 2) # Test for independency of each Random Indexed variable assert P(Eq(B[1], 0) & Eq(B[2], 1) & Eq(B[3], 0) & Eq(B[4], 1)).round(2) == Float(0.06, 1) assert E(2 * B[1] + B[2]).round(2) == Float(1.80, 3) assert E(2 * B[1] + B[2] + 5).round(2) == Float(6.80, 3) assert E(B[2] * B[4] + B[10]).round(2) == Float(0.96, 2) assert E(B[2] > 0, Eq(B[1],1) & Eq(B[2],1)).round(2) == Float(0.60,2) assert E(B[1]) == 0.6 assert P(B[1] > 0).round(2) == Float(0.60, 2) assert P(B[1] < 1).round(2) == Float(0.40, 2) assert P(B[1] > 0, B[2] <= 1).round(2) == Float(0.60, 2) assert P(B[12] * B[5] > 0).round(2) == Float(0.36, 2) assert P(B[12] * B[5] > 0, B[4] < 1).round(2) == Float(0.36, 2) assert P(Eq(B[2], 1), B[2] > 0) == 1 assert P(Eq(B[5], 3)) == 0 assert P(Eq(B[1], 1), B[1] < 0) == 0 assert P(B[2] > 0, Eq(B[2], 1)) == 1 assert P(B[2] < 0, Eq(B[2], 1)) == 0 assert P(B[2] > 0, B[2]==7) == 0 assert P(B[5] > 0, B[5]) == BernoulliDistribution(0.6, 0, 1) raises(ValueError, lambda: P(3)) raises(ValueError, lambda: P(B[3] > 0, 3)) # test issue 19456 expr = Sum(B[t], (t, 0, 4)) expr2 = Sum(B[t], (t, 1, 3)) expr3 = Sum(B[t]**2, (t, 1, 3)) assert expr.doit() == B[0] + B[1] + B[2] + B[3] + B[4] assert expr2.doit() == Y assert expr3.doit() == B[1]**2 + B[2]**2 + B[3]**2 assert B[2*t].free_symbols == {B[2*t], t} assert B[4].free_symbols == {B[4]} assert B[x*t].free_symbols == {B[x*t], x, t} def test_PoissonProcess(): X = PoissonProcess("X", 3) assert X.state_space == S.Naturals0 assert X.index_set == Interval(0, oo) assert X.lamda == 3 t, d, x, y = symbols('t d x y', positive=True) assert isinstance(X(t), RandomIndexedSymbol) assert X.distribution(X(t)) == PoissonDistribution(3*t) raises(ValueError, lambda: PoissonProcess("X", -1)) raises(NotImplementedError, lambda: X[t]) raises(IndexError, lambda: X(-5)) assert X.joint_distribution(X(2), X(3)) == JointDistributionHandmade(Lambda((X(2), X(3)), 6**X(2)*9**X(3)*exp(-15)/(factorial(X(2))*factorial(X(3))))) assert X.joint_distribution(4, 6) == JointDistributionHandmade(Lambda((X(4), X(6)), 12**X(4)*18**X(6)*exp(-30)/(factorial(X(4))*factorial(X(6))))) assert P(X(t) < 1) == exp(-3*t) assert P(Eq(X(t), 0), Contains(t, Interval.Lopen(3, 5))) == exp(-6) # exp(-2*lamda) res = P(Eq(X(t), 1), Contains(t, Interval.Lopen(3, 4))) assert res == 3*exp(-3) # Equivalent to P(Eq(X(t), 1))**4 because of non-overlapping intervals assert P(Eq(X(t), 1) & Eq(X(d), 1) & Eq(X(x), 1) & Eq(X(y), 1), Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2)) & Contains(x, Interval.Lopen(2, 3)) & Contains(y, Interval.Lopen(3, 4))) == res**4 # Return Probability because of overlapping intervals assert P(Eq(X(t), 2) & Eq(X(d), 3), Contains(t, Interval.Lopen(0, 2)) & Contains(d, Interval.Ropen(2, 4))) == \ Probability(Eq(X(d), 3) & Eq(X(t), 2), Contains(t, Interval.Lopen(0, 2)) & Contains(d, Interval.Ropen(2, 4))) raises(ValueError, lambda: P(Eq(X(t), 2) & Eq(X(d), 3), Contains(t, Interval.Lopen(0, 4)) & Contains(d, Interval.Lopen(3, oo)))) # no bound on d assert P(Eq(X(3), 2)) == 81*exp(-9)/2 assert P(Eq(X(t), 2), Contains(t, Interval.Lopen(0, 5))) == 225*exp(-15)/2 # Check that probability works correctly by adding it to 1 res1 = P(X(t) <= 3, Contains(t, Interval.Lopen(0, 5))) res2 = P(X(t) > 3, Contains(t, Interval.Lopen(0, 5))) assert res1 == 691*exp(-15) assert (res1 + res2).simplify() == 1 # Check Not and Or assert P(Not(Eq(X(t), 2) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) & \ Contains(d, Interval.Lopen(7, 8))).simplify() == -18*exp(-6) + 234*exp(-9) + 1 assert P(Eq(X(t), 2) | Ne(X(t), 4), Contains(t, Interval.Ropen(2, 4))) == 1 - 36*exp(-6) raises(ValueError, lambda: P(X(t) > 2, X(t) + X(d))) assert E(X(t)) == 3*t # property of the distribution at a given timestamp assert E(X(t)**2 + X(d)*2 + X(y)**3, Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2)) & Contains(y, Interval.Ropen(3, 4))) == 75 assert E(X(t)**2, Contains(t, Interval.Lopen(0, 1))) == 12 assert E(x*(X(t) + X(d))*(X(t)**2+X(d)**2), Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Ropen(1, 2))) == \ Expectation(x*(X(d) + X(t))*(X(d)**2 + X(t)**2), Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Ropen(1, 2))) # Value Error because of infinite time bound raises(ValueError, lambda: E(X(t)**3, Contains(t, Interval.Lopen(1, oo)))) # Equivalent to E(X(t)**2) - E(X(d)**2) == E(X(1)**2) - E(X(1)**2) == 0 assert E((X(t) + X(d))*(X(t) - X(d)), Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2))) == 0 assert E(X(2) + x*E(X(5))) == 15*x + 6 assert E(x*X(1) + y) == 3*x + y assert P(Eq(X(1), 2) & Eq(X(t), 3), Contains(t, Interval.Lopen(1, 2))) == 81*exp(-6)/4 Y = PoissonProcess("Y", 6) Z = X + Y assert Z.lamda == X.lamda + Y.lamda == 9 raises(ValueError, lambda: X + 5) # should be added be only PoissonProcess instance N, M = Z.split(4, 5) assert N.lamda == 4 assert M.lamda == 5 raises(ValueError, lambda: Z.split(3, 2)) # 2+3 != 9 raises(ValueError, lambda :P(Eq(X(t), 0), Contains(t, Interval.Lopen(1, 3)) & Eq(X(1), 0))) # check if it handles queries with two random variables in one args res1 = P(Eq(N(3), N(5))) assert res1 == P(Eq(N(t), 0), Contains(t, Interval(3, 5))) res2 = P(N(3) > N(1)) assert res2 == P((N(t) > 0), Contains(t, Interval(1, 3))) assert P(N(3) < N(1)) == 0 # condition is not possible res3 = P(N(3) <= N(1)) # holds only for Eq(N(3), N(1)) assert res3 == P(Eq(N(t), 0), Contains(t, Interval(1, 3))) # tests from https://www.probabilitycourse.com/chapter11/11_1_2_basic_concepts_of_the_poisson_process.php X = PoissonProcess('X', 10) # 11.1 assert P(Eq(X(S(1)/3), 3) & Eq(X(1), 10)) == exp(-10)*Rational(8000000000, 11160261) assert P(Eq(X(1), 1), Eq(X(S(1)/3), 3)) == 0 assert P(Eq(X(1), 10), Eq(X(S(1)/3), 3)) == P(Eq(X(S(2)/3), 7)) X = PoissonProcess('X', 2) # 11.2 assert P(X(S(1)/2) < 1) == exp(-1) assert P(X(3) < 1, Eq(X(1), 0)) == exp(-4) assert P(Eq(X(4), 3), Eq(X(2), 3)) == exp(-4) X = PoissonProcess('X', 3) assert P(Eq(X(2), 5) & Eq(X(1), 2)) == Rational(81, 4)*exp(-6) # check few properties assert P(X(2) <= 3, X(1)>=1) == 3*P(Eq(X(1), 0)) + 2*P(Eq(X(1), 1)) + P(Eq(X(1), 2)) assert P(X(2) <= 3, X(1) > 1) == 2*P(Eq(X(1), 0)) + 1*P(Eq(X(1), 1)) assert P(Eq(X(2), 5) & Eq(X(1), 2)) == P(Eq(X(1), 3))*P(Eq(X(1), 2)) assert P(Eq(X(3), 4), Eq(X(1), 3)) == P(Eq(X(2), 1)) def test_WienerProcess(): X = WienerProcess("X") assert X.state_space == S.Reals assert X.index_set == Interval(0, oo) t, d, x, y = symbols('t d x y', positive=True) assert isinstance(X(t), RandomIndexedSymbol) assert X.distribution(X(t)) == NormalDistribution(0, sqrt(t)) raises(ValueError, lambda: PoissonProcess("X", -1)) raises(NotImplementedError, lambda: X[t]) raises(IndexError, lambda: X(-2)) assert X.joint_distribution(X(2), X(3)) == JointDistributionHandmade( Lambda((X(2), X(3)), sqrt(6)*exp(-X(2)**2/4)*exp(-X(3)**2/6)/(12*pi))) assert X.joint_distribution(4, 6) == JointDistributionHandmade( Lambda((X(4), X(6)), sqrt(6)*exp(-X(4)**2/8)*exp(-X(6)**2/12)/(24*pi))) assert P(X(t) < 3).simplify() == erf(3*sqrt(2)/(2*sqrt(t)))/2 + S(1)/2 assert P(X(t) > 2, Contains(t, Interval.Lopen(3, 7))).simplify() == S(1)/2 -\ erf(sqrt(2)/2)/2 # Equivalent to P(X(1)>1)**4 assert P((X(t) > 4) & (X(d) > 3) & (X(x) > 2) & (X(y) > 1), Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2)) & Contains(x, Interval.Lopen(2, 3)) & Contains(y, Interval.Lopen(3, 4))).simplify() ==\ (1 - erf(sqrt(2)/2))*(1 - erf(sqrt(2)))*(1 - erf(3*sqrt(2)/2))*(1 - erf(2*sqrt(2)))/16 # Contains an overlapping interval so, return Probability assert P((X(t)< 2) & (X(d)> 3), Contains(t, Interval.Lopen(0, 2)) & Contains(d, Interval.Ropen(2, 4))) == Probability((X(d) > 3) & (X(t) < 2), Contains(d, Interval.Ropen(2, 4)) & Contains(t, Interval.Lopen(0, 2))) assert str(P(Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) & Contains(d, Interval.Lopen(7, 8))).simplify()) == \ '-(1 - erf(3*sqrt(2)/2))*(2 - erfc(5/2))/4 + 1' # Distribution has mean 0 at each timestamp assert E(X(t)) == 0 assert E(x*(X(t) + X(d))*(X(t)**2+X(d)**2), Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Ropen(1, 2))) == Expectation(x*(X(d) + X(t))*(X(d)**2 + X(t)**2), Contains(d, Interval.Ropen(1, 2)) & Contains(t, Interval.Lopen(0, 1))) assert E(X(t) + x*E(X(3))) == 0 def test_GammaProcess_symbolic(): t, d, x, y, g, l = symbols('t d x y g l', positive=True) X = GammaProcess("X", l, g) raises(NotImplementedError, lambda: X[t]) raises(IndexError, lambda: X(-1)) assert isinstance(X(t), RandomIndexedSymbol) assert X.state_space == Interval(0, oo) assert X.distribution(X(t)) == GammaDistribution(g*t, 1/l) assert X.joint_distribution(5, X(3)) == JointDistributionHandmade(Lambda( (X(5), X(3)), l**(8*g)*exp(-l*X(3))*exp(-l*X(5))*X(3)**(3*g - 1)*X(5)**(5*g - 1)/(gamma(3*g)*gamma(5*g)))) # property of the gamma process at any given timestamp assert E(X(t)) == g*t/l assert variance(X(t)).simplify() == g*t/l**2 # Equivalent to E(2*X(1)) + E(X(1)**2) + E(X(1)**3), where E(X(1)) == g/l assert E(X(t)**2 + X(d)*2 + X(y)**3, Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2)) & Contains(y, Interval.Ropen(3, 4))) == \ 2*g/l + (g**2 + g)/l**2 + (g**3 + 3*g**2 + 2*g)/l**3 assert P(X(t) > 3, Contains(t, Interval.Lopen(3, 4))).simplify() == \ 1 - lowergamma(g, 3*l)/gamma(g) # equivalent to P(X(1)>3) def test_GammaProcess_numeric(): t, d, x, y = symbols('t d x y', positive=True) X = GammaProcess("X", 1, 2) assert X.state_space == Interval(0, oo) assert X.index_set == Interval(0, oo) assert X.lamda == 1 assert X.gamma == 2 raises(ValueError, lambda: GammaProcess("X", -1, 2)) raises(ValueError, lambda: GammaProcess("X", 0, -2)) raises(ValueError, lambda: GammaProcess("X", -1, -2)) # all are independent because of non-overlapping intervals assert P((X(t) > 4) & (X(d) > 3) & (X(x) > 2) & (X(y) > 1), Contains(t, Interval.Lopen(0, 1)) & Contains(d, Interval.Lopen(1, 2)) & Contains(x, Interval.Lopen(2, 3)) & Contains(y, Interval.Lopen(3, 4))).simplify() == \ 120*exp(-10) # Check working with Not and Or assert P(Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) & Contains(d, Interval.Lopen(7, 8))).simplify() == -4*exp(-3) + 472*exp(-8)/3 + 1 assert P((X(t) > 2) | (X(t) < 4), Contains(t, Interval.Ropen(1, 4))).simplify() == \ -643*exp(-4)/15 + 109*exp(-2)/15 + 1 assert E(X(t)) == 2*t # E(X(t)) == gamma*t/l assert E(X(2) + x*E(X(5))) == 10*x + 4
5782bb12acd765b8ccf8866ae756675e5ba29d86019073e7e881e29f06da9169
from sympy import E as e from sympy import (Symbol, Abs, exp, expint, S, pi, simplify, Interval, erf, erfc, Ne, EulerGamma, Eq, log, lowergamma, uppergamma, symbols, sqrt, And, gamma, beta, Piecewise, Integral, sin, cos, tan, sinh, cosh, besseli, floor, expand_func, Rational, I, re, Lambda, asin, im, lambdify, hyper, diff, Or, Mul, sign, Dummy, Sum, factorial, binomial, erfi, besselj, besselk) from sympy.external import import_module from sympy.functions.special.error_functions import erfinv from sympy.functions.special.hyper import meijerg from sympy.sets.sets import Intersection, FiniteSet from sympy.stats import (P, E, where, density, variance, covariance, skewness, kurtosis, median, given, pspace, cdf, characteristic_function, moment_generating_function, ContinuousRV, sample, Arcsin, Benini, Beta, BetaNoncentral, BetaPrime, Cauchy, Chi, ChiSquared, ChiNoncentral, Dagum, Erlang, ExGaussian, Exponential, ExponentialPower, FDistribution, FisherZ, Frechet, Gamma, GammaInverse, Gompertz, Gumbel, Kumaraswamy, Laplace, Levy, Logistic, LogLogistic, LogNormal, Maxwell, Moyal, Nakagami, Normal, GaussianInverse, Pareto, PowerFunction, QuadraticU, RaisedCosine, Rayleigh, Reciprocal, ShiftedGompertz, StudentT, Trapezoidal, Triangular, Uniform, UniformSum, VonMises, Weibull, coskewness, WignerSemicircle, Wald, correlation, moment, cmoment, smoment, quantile, Lomax, BoundedPareto) from sympy.stats.crv_types import NormalDistribution, ExponentialDistribution, ContinuousDistributionHandmade from sympy.stats.joint_rv_types import MultivariateLaplaceDistribution, MultivariateNormalDistribution from sympy.stats.crv import SingleContinuousPSpace, SingleContinuousDomain from sympy.stats.compound_rv import CompoundPSpace from sympy.stats.symbolic_probability import Probability from sympy.testing.pytest import raises, XFAIL, slow, skip, ignore_warnings from sympy.testing.randtest import verify_numerically as tn oo = S.Infinity x, y, z = map(Symbol, 'xyz') def test_single_normal(): mu = Symbol('mu', real=True) sigma = Symbol('sigma', positive=True) X = Normal('x', 0, 1) Y = X*sigma + mu assert E(Y) == mu assert variance(Y) == sigma**2 pdf = density(Y) x = Symbol('x', real=True) assert (pdf(x) == 2**S.Half*exp(-(x - mu)**2/(2*sigma**2))/(2*pi**S.Half*sigma)) assert P(X**2 < 1) == erf(2**S.Half/2) assert quantile(Y)(x) == Intersection(S.Reals, FiniteSet(sqrt(2)*sigma*(sqrt(2)*mu/(2*sigma) + erfinv(2*x - 1)))) assert E(X, Eq(X, mu)) == mu assert median(X) == FiniteSet(0) # issue 8248 assert X.pspace.compute_expectation(1).doit() == 1 def test_conditional_1d(): X = Normal('x', 0, 1) Y = given(X, X >= 0) z = Symbol('z') assert density(Y)(z) == 2 * density(X)(z) assert Y.pspace.domain.set == Interval(0, oo) assert E(Y) == sqrt(2) / sqrt(pi) assert E(X**2) == E(Y**2) def test_ContinuousDomain(): X = Normal('x', 0, 1) assert where(X**2 <= 1).set == Interval(-1, 1) assert where(X**2 <= 1).symbol == X.symbol where(And(X**2 <= 1, X >= 0)).set == Interval(0, 1) raises(ValueError, lambda: where(sin(X) > 1)) Y = given(X, X >= 0) assert Y.pspace.domain.set == Interval(0, oo) @slow def test_multiple_normal(): X, Y = Normal('x', 0, 1), Normal('y', 0, 1) p = Symbol("p", positive=True) assert E(X + Y) == 0 assert variance(X + Y) == 2 assert variance(X + X) == 4 assert covariance(X, Y) == 0 assert covariance(2*X + Y, -X) == -2*variance(X) assert skewness(X) == 0 assert skewness(X + Y) == 0 assert kurtosis(X) == 3 assert kurtosis(X+Y) == 3 assert correlation(X, Y) == 0 assert correlation(X, X + Y) == correlation(X, X - Y) assert moment(X, 2) == 1 assert cmoment(X, 3) == 0 assert moment(X + Y, 4) == 12 assert cmoment(X, 2) == variance(X) assert smoment(X*X, 2) == 1 assert smoment(X + Y, 3) == skewness(X + Y) assert smoment(X + Y, 4) == kurtosis(X + Y) assert E(X, Eq(X + Y, 0)) == 0 assert variance(X, Eq(X + Y, 0)) == S.Half assert quantile(X)(p) == sqrt(2)*erfinv(2*p - S.One) def test_symbolic(): mu1, mu2 = symbols('mu1 mu2', real=True) s1, s2 = symbols('sigma1 sigma2', positive=True) rate = Symbol('lambda', positive=True) X = Normal('x', mu1, s1) Y = Normal('y', mu2, s2) Z = Exponential('z', rate) a, b, c = symbols('a b c', real=True) assert E(X) == mu1 assert E(X + Y) == mu1 + mu2 assert E(a*X + b) == a*E(X) + b assert variance(X) == s1**2 assert variance(X + a*Y + b) == variance(X) + a**2*variance(Y) assert E(Z) == 1/rate assert E(a*Z + b) == a*E(Z) + b assert E(X + a*Z + b) == mu1 + a/rate + b assert median(X) == FiniteSet(mu1) def test_cdf(): X = Normal('x', 0, 1) d = cdf(X) assert P(X < 1) == d(1).rewrite(erfc) assert d(0) == S.Half d = cdf(X, X > 0) # given X>0 assert d(0) == 0 Y = Exponential('y', 10) d = cdf(Y) assert d(-5) == 0 assert P(Y > 3) == 1 - d(3) raises(ValueError, lambda: cdf(X + Y)) Z = Exponential('z', 1) f = cdf(Z) assert f(z) == Piecewise((1 - exp(-z), z >= 0), (0, True)) def test_characteristic_function(): X = Uniform('x', 0, 1) cf = characteristic_function(X) assert cf(1) == -I*(-1 + exp(I)) Y = Normal('y', 1, 1) cf = characteristic_function(Y) assert cf(0) == 1 assert cf(1) == exp(I - S.Half) Z = Exponential('z', 5) cf = characteristic_function(Z) assert cf(0) == 1 assert cf(1).expand() == Rational(25, 26) + I*Rational(5, 26) X = GaussianInverse('x', 1, 1) cf = characteristic_function(X) assert cf(0) == 1 assert cf(1) == exp(1 - sqrt(1 - 2*I)) X = ExGaussian('x', 0, 1, 1) cf = characteristic_function(X) assert cf(0) == 1 assert cf(1) == (1 + I)*exp(Rational(-1, 2))/2 L = Levy('x', 0, 1) cf = characteristic_function(L) assert cf(0) == 1 assert cf(1) == exp(-sqrt(2)*sqrt(-I)) def test_moment_generating_function(): t = symbols('t', positive=True) # Symbolic tests a, b, c = symbols('a b c') mgf = moment_generating_function(Beta('x', a, b))(t) assert mgf == hyper((a,), (a + b,), t) mgf = moment_generating_function(Chi('x', a))(t) assert mgf == sqrt(2)*t*gamma(a/2 + S.Half)*\ hyper((a/2 + S.Half,), (Rational(3, 2),), t**2/2)/gamma(a/2) +\ hyper((a/2,), (S.Half,), t**2/2) mgf = moment_generating_function(ChiSquared('x', a))(t) assert mgf == (1 - 2*t)**(-a/2) mgf = moment_generating_function(Erlang('x', a, b))(t) assert mgf == (1 - t/b)**(-a) mgf = moment_generating_function(ExGaussian("x", a, b, c))(t) assert mgf == exp(a*t + b**2*t**2/2)/(1 - t/c) mgf = moment_generating_function(Exponential('x', a))(t) assert mgf == a/(a - t) mgf = moment_generating_function(Gamma('x', a, b))(t) assert mgf == (-b*t + 1)**(-a) mgf = moment_generating_function(Gumbel('x', a, b))(t) assert mgf == exp(b*t)*gamma(-a*t + 1) mgf = moment_generating_function(Gompertz('x', a, b))(t) assert mgf == b*exp(b)*expint(t/a, b) mgf = moment_generating_function(Laplace('x', a, b))(t) assert mgf == exp(a*t)/(-b**2*t**2 + 1) mgf = moment_generating_function(Logistic('x', a, b))(t) assert mgf == exp(a*t)*beta(-b*t + 1, b*t + 1) mgf = moment_generating_function(Normal('x', a, b))(t) assert mgf == exp(a*t + b**2*t**2/2) mgf = moment_generating_function(Pareto('x', a, b))(t) assert mgf == b*(-a*t)**b*uppergamma(-b, -a*t) mgf = moment_generating_function(QuadraticU('x', a, b))(t) assert str(mgf) == ("(3*(t*(-4*b + (a + b)**2) + 4)*exp(b*t) - " "3*(t*(a**2 + 2*a*(b - 2) + b**2) + 4)*exp(a*t))/(t**2*(a - b)**3)") mgf = moment_generating_function(RaisedCosine('x', a, b))(t) assert mgf == pi**2*exp(a*t)*sinh(b*t)/(b*t*(b**2*t**2 + pi**2)) mgf = moment_generating_function(Rayleigh('x', a))(t) assert mgf == sqrt(2)*sqrt(pi)*a*t*(erf(sqrt(2)*a*t/2) + 1)\ *exp(a**2*t**2/2)/2 + 1 mgf = moment_generating_function(Triangular('x', a, b, c))(t) assert str(mgf) == ("(-2*(-a + b)*exp(c*t) + 2*(-a + c)*exp(b*t) + " "2*(b - c)*exp(a*t))/(t**2*(-a + b)*(-a + c)*(b - c))") mgf = moment_generating_function(Uniform('x', a, b))(t) assert mgf == (-exp(a*t) + exp(b*t))/(t*(-a + b)) mgf = moment_generating_function(UniformSum('x', a))(t) assert mgf == ((exp(t) - 1)/t)**a mgf = moment_generating_function(WignerSemicircle('x', a))(t) assert mgf == 2*besseli(1, a*t)/(a*t) # Numeric tests mgf = moment_generating_function(Beta('x', 1, 1))(t) assert mgf.diff(t).subs(t, 1) == hyper((2,), (3,), 1)/2 mgf = moment_generating_function(Chi('x', 1))(t) assert mgf.diff(t).subs(t, 1) == sqrt(2)*hyper((1,), (Rational(3, 2),), S.Half )/sqrt(pi) + hyper((Rational(3, 2),), (Rational(3, 2),), S.Half) + 2*sqrt(2)*hyper((2,), (Rational(5, 2),), S.Half)/(3*sqrt(pi)) mgf = moment_generating_function(ChiSquared('x', 1))(t) assert mgf.diff(t).subs(t, 1) == I mgf = moment_generating_function(Erlang('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == 1 mgf = moment_generating_function(ExGaussian("x", 0, 1, 1))(t) assert mgf.diff(t).subs(t, 2) == -exp(2) mgf = moment_generating_function(Exponential('x', 1))(t) assert mgf.diff(t).subs(t, 0) == 1 mgf = moment_generating_function(Gamma('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == 1 mgf = moment_generating_function(Gumbel('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == EulerGamma + 1 mgf = moment_generating_function(Gompertz('x', 1, 1))(t) assert mgf.diff(t).subs(t, 1) == -e*meijerg(((), (1, 1)), ((0, 0, 0), ()), 1) mgf = moment_generating_function(Laplace('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == 1 mgf = moment_generating_function(Logistic('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == beta(1, 1) mgf = moment_generating_function(Normal('x', 0, 1))(t) assert mgf.diff(t).subs(t, 1) == exp(S.Half) mgf = moment_generating_function(Pareto('x', 1, 1))(t) assert mgf.diff(t).subs(t, 0) == expint(1, 0) mgf = moment_generating_function(QuadraticU('x', 1, 2))(t) assert mgf.diff(t).subs(t, 1) == -12*e - 3*exp(2) mgf = moment_generating_function(RaisedCosine('x', 1, 1))(t) assert mgf.diff(t).subs(t, 1) == -2*e*pi**2*sinh(1)/\ (1 + pi**2)**2 + e*pi**2*cosh(1)/(1 + pi**2) mgf = moment_generating_function(Rayleigh('x', 1))(t) assert mgf.diff(t).subs(t, 0) == sqrt(2)*sqrt(pi)/2 mgf = moment_generating_function(Triangular('x', 1, 3, 2))(t) assert mgf.diff(t).subs(t, 1) == -e + exp(3) mgf = moment_generating_function(Uniform('x', 0, 1))(t) assert mgf.diff(t).subs(t, 1) == 1 mgf = moment_generating_function(UniformSum('x', 1))(t) assert mgf.diff(t).subs(t, 1) == 1 mgf = moment_generating_function(WignerSemicircle('x', 1))(t) assert mgf.diff(t).subs(t, 1) == -2*besseli(1, 1) + besseli(2, 1) +\ besseli(0, 1) def test_sample_continuous(): Z = ContinuousRV(z, exp(-z), set=Interval(0, oo)) assert density(Z)(-1) == 0 scipy = import_module('scipy') if not scipy: skip('Scipy is not installed. Abort tests') with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed assert next(sample(Z)) in Z.pspace.domain.set sym, val = list(Z.pspace.sample().items())[0] assert sym == Z and val in Interval(0, oo) 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 def test_ContinuousRV(): pdf = sqrt(2)*exp(-x**2/2)/(2*sqrt(pi)) # Normal distribution # X and Y should be equivalent X = ContinuousRV(x, pdf, check=True) Y = Normal('y', 0, 1) assert variance(X) == variance(Y) assert P(X > 0) == P(Y > 0) Z = ContinuousRV(z, exp(-z), set=Interval(0, oo)) assert Z.pspace.domain.set == Interval(0, oo) assert E(Z) == 1 assert P(Z > 5) == exp(-5) raises(ValueError, lambda: ContinuousRV(z, exp(-z), set=Interval(0, 10), check=True)) # the correct pdf for Gamma(k, theta) but the integral in `check` # integrates to something equivalent to 1 and not to 1 exactly _x, k, theta = symbols("x k theta", positive=True) pdf = 1/(gamma(k)*theta**k)*_x**(k-1)*exp(-_x/theta) X = ContinuousRV(_x, pdf, set=Interval(0, oo)) Y = Gamma('y', k, theta) assert (E(X) - E(Y)).simplify() == 0 assert (variance(X) - variance(Y)).simplify() == 0 def test_arcsin(): a = Symbol("a", real=True) b = Symbol("b", real=True) X = Arcsin('x', a, b) assert density(X)(x) == 1/(pi*sqrt((-x + b)*(x - a))) assert cdf(X)(x) == Piecewise((0, a > x), (2*asin(sqrt((-a + x)/(-a + b)))/pi, b >= x), (1, True)) assert pspace(X).domain.set == Interval(a, b) def test_benini(): alpha = Symbol("alpha", positive=True) beta = Symbol("beta", positive=True) sigma = Symbol("sigma", positive=True) X = Benini('x', alpha, beta, sigma) assert density(X)(x) == ((alpha/x + 2*beta*log(x/sigma)/x) *exp(-alpha*log(x/sigma) - beta*log(x/sigma)**2)) assert pspace(X).domain.set == Interval(sigma, oo) raises(NotImplementedError, lambda: moment_generating_function(X)) alpha = Symbol("alpha", nonpositive=True) raises(ValueError, lambda: Benini('x', alpha, beta, sigma)) beta = Symbol("beta", nonpositive=True) raises(ValueError, lambda: Benini('x', alpha, beta, sigma)) alpha = Symbol("alpha", positive=True) raises(ValueError, lambda: Benini('x', alpha, beta, sigma)) beta = Symbol("beta", positive=True) sigma = Symbol("sigma", nonpositive=True) raises(ValueError, lambda: Benini('x', alpha, beta, sigma)) def test_beta(): a, b = symbols('alpha beta', positive=True) B = Beta('x', a, b) assert pspace(B).domain.set == Interval(0, 1) assert characteristic_function(B)(x) == hyper((a,), (a + b,), I*x) assert density(B)(x) == x**(a - 1)*(1 - x)**(b - 1)/beta(a, b) assert simplify(E(B)) == a / (a + b) assert simplify(variance(B)) == a*b / (a**3 + 3*a**2*b + a**2 + 3*a*b**2 + 2*a*b + b**3 + b**2) # Full symbolic solution is too much, test with numeric version a, b = 1, 2 B = Beta('x', a, b) assert expand_func(E(B)) == a / S(a + b) assert expand_func(variance(B)) == (a*b) / S((a + b)**2 * (a + b + 1)) assert median(B) == FiniteSet(1 - 1/sqrt(2)) def test_beta_noncentral(): a, b = symbols('a b', positive=True) c = Symbol('c', nonnegative=True) _k = Dummy('k') X = BetaNoncentral('x', a, b, c) assert pspace(X).domain.set == Interval(0, 1) dens = density(X) z = Symbol('z') res = Sum( z**(_k + a - 1)*(c/2)**_k*(1 - z)**(b - 1)*exp(-c/2)/ (beta(_k + a, b)*factorial(_k)), (_k, 0, oo)) assert dens(z).dummy_eq(res) # BetaCentral should not raise if the assumptions # on the symbols can not be determined a, b, c = symbols('a b c') assert BetaNoncentral('x', a, b, c) a = Symbol('a', positive=False, real=True) raises(ValueError, lambda: BetaNoncentral('x', a, b, c)) a = Symbol('a', positive=True) b = Symbol('b', positive=False, real=True) raises(ValueError, lambda: BetaNoncentral('x', a, b, c)) a = Symbol('a', positive=True) b = Symbol('b', positive=True) c = Symbol('c', nonnegative=False, real=True) raises(ValueError, lambda: BetaNoncentral('x', a, b, c)) def test_betaprime(): alpha = Symbol("alpha", positive=True) betap = Symbol("beta", positive=True) X = BetaPrime('x', alpha, betap) assert density(X)(x) == x**(alpha - 1)*(x + 1)**(-alpha - betap)/beta(alpha, betap) alpha = Symbol("alpha", nonpositive=True) raises(ValueError, lambda: BetaPrime('x', alpha, betap)) alpha = Symbol("alpha", positive=True) betap = Symbol("beta", nonpositive=True) raises(ValueError, lambda: BetaPrime('x', alpha, betap)) X = BetaPrime('x', 1, 1) assert median(X) == FiniteSet(1) def test_BoundedPareto(): L, H = symbols('L, H', negative=True) raises(ValueError, lambda: BoundedPareto('X', 1, L, H)) L, H = symbols('L, H', real=False) raises(ValueError, lambda: BoundedPareto('X', 1, L, H)) L, H = symbols('L, H', positive=True) raises(ValueError, lambda: BoundedPareto('X', -1, L, H)) X = BoundedPareto('X', 2, L, H) assert X.pspace.domain.set == Interval(L, H) assert density(X)(x) == 2*L**2/(x**3*(1 - L**2/H**2)) assert cdf(X)(x) == Piecewise((-H**2*L**2/(x**2*(H**2 - L**2)) \ + H**2/(H**2 - L**2), L <= x), (0, True)) assert E(X).simplify() == 2*H*L/(H + L) X = BoundedPareto('X', 1, 2, 4) assert E(X).simplify() == log(16) assert median(X) == FiniteSet(Rational(8, 3)) assert variance(X).simplify() == 8 - 16*log(2)**2 def test_cauchy(): x0 = Symbol("x0", real=True) gamma = Symbol("gamma", positive=True) p = Symbol("p", positive=True) X = Cauchy('x', x0, gamma) # Tests the characteristic function assert characteristic_function(X)(x) == exp(-gamma*Abs(x) + I*x*x0) raises(NotImplementedError, lambda: moment_generating_function(X)) assert density(X)(x) == 1/(pi*gamma*(1 + (x - x0)**2/gamma**2)) assert diff(cdf(X)(x), x) == density(X)(x) assert quantile(X)(p) == gamma*tan(pi*(p - S.Half)) + x0 x1 = Symbol("x1", real=False) raises(ValueError, lambda: Cauchy('x', x1, gamma)) gamma = Symbol("gamma", nonpositive=True) raises(ValueError, lambda: Cauchy('x', x0, gamma)) assert median(X) == FiniteSet(x0) def test_chi(): from sympy import I k = Symbol("k", integer=True) X = Chi('x', k) assert density(X)(x) == 2**(-k/2 + 1)*x**(k - 1)*exp(-x**2/2)/gamma(k/2) # Tests the characteristic function assert characteristic_function(X)(x) == sqrt(2)*I*x*gamma(k/2 + S(1)/2)*hyper((k/2 + S(1)/2,), (S(3)/2,), -x**2/2)/gamma(k/2) + hyper((k/2,), (S(1)/2,), -x**2/2) # Tests the moment generating function assert moment_generating_function(X)(x) == sqrt(2)*x*gamma(k/2 + S(1)/2)*hyper((k/2 + S(1)/2,), (S(3)/2,), x**2/2)/gamma(k/2) + hyper((k/2,), (S(1)/2,), x**2/2) k = Symbol("k", integer=True, positive=False) raises(ValueError, lambda: Chi('x', k)) k = Symbol("k", integer=False, positive=True) raises(ValueError, lambda: Chi('x', k)) def test_chi_noncentral(): k = Symbol("k", integer=True) l = Symbol("l") X = ChiNoncentral("x", k, l) assert density(X)(x) == (x**k*l*(x*l)**(-k/2)* exp(-x**2/2 - l**2/2)*besseli(k/2 - 1, x*l)) k = Symbol("k", integer=True, positive=False) raises(ValueError, lambda: ChiNoncentral('x', k, l)) k = Symbol("k", integer=True, positive=True) l = Symbol("l", nonpositive=True) raises(ValueError, lambda: ChiNoncentral('x', k, l)) k = Symbol("k", integer=False) l = Symbol("l", positive=True) raises(ValueError, lambda: ChiNoncentral('x', k, l)) def test_chi_squared(): k = Symbol("k", integer=True) X = ChiSquared('x', k) # Tests the characteristic function assert characteristic_function(X)(x) == ((-2*I*x + 1)**(-k/2)) assert density(X)(x) == 2**(-k/2)*x**(k/2 - 1)*exp(-x/2)/gamma(k/2) assert cdf(X)(x) == Piecewise((lowergamma(k/2, x/2)/gamma(k/2), x >= 0), (0, True)) assert E(X) == k assert variance(X) == 2*k X = ChiSquared('x', 15) assert cdf(X)(3) == -14873*sqrt(6)*exp(Rational(-3, 2))/(5005*sqrt(pi)) + erf(sqrt(6)/2) k = Symbol("k", integer=True, positive=False) raises(ValueError, lambda: ChiSquared('x', k)) k = Symbol("k", integer=False, positive=True) raises(ValueError, lambda: ChiSquared('x', k)) def test_dagum(): p = Symbol("p", positive=True) b = Symbol("b", positive=True) a = Symbol("a", positive=True) X = Dagum('x', p, a, b) assert density(X)(x) == a*p*(x/b)**(a*p)*((x/b)**a + 1)**(-p - 1)/x assert cdf(X)(x) == Piecewise(((1 + (x/b)**(-a))**(-p), x >= 0), (0, True)) p = Symbol("p", nonpositive=True) raises(ValueError, lambda: Dagum('x', p, a, b)) p = Symbol("p", positive=True) b = Symbol("b", nonpositive=True) raises(ValueError, lambda: Dagum('x', p, a, b)) b = Symbol("b", positive=True) a = Symbol("a", nonpositive=True) raises(ValueError, lambda: Dagum('x', p, a, b)) X = Dagum('x', 1 , 1, 1) assert median(X) == FiniteSet(1) def test_erlang(): k = Symbol("k", integer=True, positive=True) l = Symbol("l", positive=True) X = Erlang("x", k, l) assert density(X)(x) == x**(k - 1)*l**k*exp(-x*l)/gamma(k) assert cdf(X)(x) == Piecewise((lowergamma(k, l*x)/gamma(k), x > 0), (0, True)) def test_exgaussian(): m, z = symbols("m, z") s, l = symbols("s, l", positive=True) X = ExGaussian("x", m, s, l) assert density(X)(z) == l*exp(l*(l*s**2 + 2*m - 2*z)/2) *\ erfc(sqrt(2)*(l*s**2 + m - z)/(2*s))/2 # Note: actual_output simplifies to expected_output. # Ideally cdf(X)(z) would return expected_output # expected_output = (erf(sqrt(2)*(l*s**2 + m - z)/(2*s)) - 1)*exp(l*(l*s**2 + 2*m - 2*z)/2)/2 - erf(sqrt(2)*(m - z)/(2*s))/2 + S.Half u = l*(z - m) v = l*s GaussianCDF1 = cdf(Normal('x', 0, v))(u) GaussianCDF2 = cdf(Normal('x', v**2, v))(u) actual_output = GaussianCDF1 - exp(-u + (v**2/2) + log(GaussianCDF2)) assert cdf(X)(z) == actual_output # assert simplify(actual_output) == expected_output assert variance(X).expand() == s**2 + l**(-2) assert skewness(X).expand() == 2/(l**3*s**2*sqrt(s**2 + l**(-2)) + l * sqrt(s**2 + l**(-2))) def test_exponential(): rate = Symbol('lambda', positive=True) X = Exponential('x', rate) p = Symbol("p", positive=True, real=True, finite=True) assert E(X) == 1/rate assert variance(X) == 1/rate**2 assert skewness(X) == 2 assert skewness(X) == smoment(X, 3) assert kurtosis(X) == 9 assert kurtosis(X) == smoment(X, 4) assert smoment(2*X, 4) == smoment(X, 4) assert moment(X, 3) == 3*2*1/rate**3 assert P(X > 0) is S.One assert P(X > 1) == exp(-rate) assert P(X > 10) == exp(-10*rate) assert quantile(X)(p) == -log(1-p)/rate assert where(X <= 1).set == Interval(0, 1) Y = Exponential('y', 1) assert median(Y) == FiniteSet(log(2)) #Test issue 9970 z = Dummy('z') assert P(X > z) == exp(-z*rate) assert P(X < z) == 0 #Test issue 10076 (Distribution with interval(0,oo)) x = Symbol('x') _z = Dummy('_z') b = SingleContinuousPSpace(x, ExponentialDistribution(2)) with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed expected1 = Integral(2*exp(-2*_z), (_z, 3, oo)) assert b.probability(x > 3, evaluate=False).rewrite(Integral).dummy_eq(expected1) expected2 = Integral(2*exp(-2*_z), (_z, 0, 4)) assert b.probability(x < 4, evaluate=False).rewrite(Integral).dummy_eq(expected2) Y = Exponential('y', 2*rate) assert coskewness(X, X, X) == skewness(X) assert coskewness(X, Y + rate*X, Y + 2*rate*X) == \ 4/(sqrt(1 + 1/(4*rate**2))*sqrt(4 + 1/(4*rate**2))) assert coskewness(X + 2*Y, Y + X, Y + 2*X, X > 3) == \ sqrt(170)*Rational(9, 85) def test_exponential_power(): mu = Symbol('mu') z = Symbol('z') alpha = Symbol('alpha', positive=True) beta = Symbol('beta', positive=True) X = ExponentialPower('x', mu, alpha, beta) assert density(X)(z) == beta*exp(-(Abs(mu - z)/alpha) ** beta)/(2*alpha*gamma(1/beta)) assert cdf(X)(z) == S.Half + lowergamma(1/beta, (Abs(mu - z)/alpha)**beta)*sign(-mu + z)/\ (2*gamma(1/beta)) def test_f_distribution(): d1 = Symbol("d1", positive=True) d2 = Symbol("d2", positive=True) X = FDistribution("x", d1, d2) assert density(X)(x) == (d2**(d2/2)*sqrt((d1*x)**d1*(d1*x + d2)**(-d1 - d2)) /(x*beta(d1/2, d2/2))) raises(NotImplementedError, lambda: moment_generating_function(X)) d1 = Symbol("d1", nonpositive=True) raises(ValueError, lambda: FDistribution('x', d1, d1)) d1 = Symbol("d1", positive=True, integer=False) raises(ValueError, lambda: FDistribution('x', d1, d1)) d1 = Symbol("d1", positive=True) d2 = Symbol("d2", nonpositive=True) raises(ValueError, lambda: FDistribution('x', d1, d2)) d2 = Symbol("d2", positive=True, integer=False) raises(ValueError, lambda: FDistribution('x', d1, d2)) def test_fisher_z(): d1 = Symbol("d1", positive=True) d2 = Symbol("d2", positive=True) X = FisherZ("x", d1, d2) assert density(X)(x) == (2*d1**(d1/2)*d2**(d2/2)*(d1*exp(2*x) + d2) **(-d1/2 - d2/2)*exp(d1*x)/beta(d1/2, d2/2)) def test_frechet(): a = Symbol("a", positive=True) s = Symbol("s", positive=True) m = Symbol("m", real=True) X = Frechet("x", a, s=s, m=m) assert density(X)(x) == a*((x - m)/s)**(-a - 1)*exp(-((x - m)/s)**(-a))/s assert cdf(X)(x) == Piecewise((exp(-((-m + x)/s)**(-a)), m <= x), (0, True)) @slow def test_gamma(): k = Symbol("k", positive=True) theta = Symbol("theta", positive=True) X = Gamma('x', k, theta) # Tests characteristic function assert characteristic_function(X)(x) == ((-I*theta*x + 1)**(-k)) assert density(X)(x) == x**(k - 1)*theta**(-k)*exp(-x/theta)/gamma(k) assert cdf(X, meijerg=True)(z) == Piecewise( (-k*lowergamma(k, 0)/gamma(k + 1) + k*lowergamma(k, z/theta)/gamma(k + 1), z >= 0), (0, True)) # assert simplify(variance(X)) == k*theta**2 # handled numerically below assert E(X) == moment(X, 1) k, theta = symbols('k theta', positive=True) X = Gamma('x', k, theta) assert E(X) == k*theta assert variance(X) == k*theta**2 assert skewness(X).expand() == 2/sqrt(k) assert kurtosis(X).expand() == 3 + 6/k Y = Gamma('y', 2*k, 3*theta) assert coskewness(X, theta*X + Y, k*X + Y).simplify() == \ 2*531441**(-k)*sqrt(k)*theta*(3*3**(12*k) - 2*531441**k) \ /(sqrt(k**2 + 18)*sqrt(theta**2 + 18)) def test_gamma_inverse(): a = Symbol("a", positive=True) b = Symbol("b", positive=True) X = GammaInverse("x", a, b) assert density(X)(x) == x**(-a - 1)*b**a*exp(-b/x)/gamma(a) assert cdf(X)(x) == Piecewise((uppergamma(a, b/x)/gamma(a), x > 0), (0, True)) assert characteristic_function(X)(x) == 2 * (-I*b*x)**(a/2) \ * besselk(a, 2*sqrt(b)*sqrt(-I*x))/gamma(a) raises(NotImplementedError, lambda: moment_generating_function(X)) def test_sampling_gamma_inverse(): scipy = import_module('scipy') if not scipy: skip('Scipy not installed. Abort tests for sampling of gamma inverse.') X = GammaInverse("x", 1, 1) with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed assert next(sample(X)) in X.pspace.domain.set def test_gompertz(): b = Symbol("b", positive=True) eta = Symbol("eta", positive=True) X = Gompertz("x", b, eta) assert density(X)(x) == b*eta*exp(eta)*exp(b*x)*exp(-eta*exp(b*x)) assert cdf(X)(x) == 1 - exp(eta)*exp(-eta*exp(b*x)) assert diff(cdf(X)(x), x) == density(X)(x) def test_gumbel(): beta = Symbol("beta", positive=True) mu = Symbol("mu") x = Symbol("x") y = Symbol("y") X = Gumbel("x", beta, mu) Y = Gumbel("y", beta, mu, minimum=True) assert density(X)(x).expand() == \ exp(mu/beta)*exp(-x/beta)*exp(-exp(mu/beta)*exp(-x/beta))/beta assert density(Y)(y).expand() == \ exp(-mu/beta)*exp(y/beta)*exp(-exp(-mu/beta)*exp(y/beta))/beta assert cdf(X)(x).expand() == \ exp(-exp(mu/beta)*exp(-x/beta)) assert characteristic_function(X)(x) == exp(I*mu*x)*gamma(-I*beta*x + 1) def test_kumaraswamy(): a = Symbol("a", positive=True) b = Symbol("b", positive=True) X = Kumaraswamy("x", a, b) assert density(X)(x) == x**(a - 1)*a*b*(-x**a + 1)**(b - 1) assert cdf(X)(x) == Piecewise((0, x < 0), (-(-x**a + 1)**b + 1, x <= 1), (1, True)) def test_laplace(): mu = Symbol("mu") b = Symbol("b", positive=True) X = Laplace('x', mu, b) #Tests characteristic_function assert characteristic_function(X)(x) == (exp(I*mu*x)/(b**2*x**2 + 1)) assert density(X)(x) == exp(-Abs(x - mu)/b)/(2*b) assert cdf(X)(x) == Piecewise((exp((-mu + x)/b)/2, mu > x), (-exp((mu - x)/b)/2 + 1, True)) X = Laplace('x', [1, 2], [[1, 0], [0, 1]]) assert isinstance(pspace(X).distribution, MultivariateLaplaceDistribution) def test_levy(): mu = Symbol("mu", real=True) c = Symbol("c", positive=True) X = Levy('x', mu, c) assert X.pspace.domain.set == Interval(mu, oo) assert density(X)(x) == sqrt(c/(2*pi))*exp(-c/(2*(x - mu)))/((x - mu)**(S.One + S.Half)) assert cdf(X)(x) == erfc(sqrt(c/(2*(x - mu)))) raises(NotImplementedError, lambda: moment_generating_function(X)) mu = Symbol("mu", real=False) raises(ValueError, lambda: Levy('x',mu,c)) c = Symbol("c", nonpositive=True) raises(ValueError, lambda: Levy('x',mu,c)) mu = Symbol("mu", real=True) raises(ValueError, lambda: Levy('x',mu,c)) def test_logistic(): mu = Symbol("mu", real=True) s = Symbol("s", positive=True) p = Symbol("p", positive=True) X = Logistic('x', mu, s) #Tests characteristics_function assert characteristic_function(X)(x) == \ (Piecewise((pi*s*x*exp(I*mu*x)/sinh(pi*s*x), Ne(x, 0)), (1, True))) assert density(X)(x) == exp((-x + mu)/s)/(s*(exp((-x + mu)/s) + 1)**2) assert cdf(X)(x) == 1/(exp((mu - x)/s) + 1) assert quantile(X)(p) == mu - s*log(-S.One + 1/p) def test_loglogistic(): a, b = symbols('a b') assert LogLogistic('x', a, b) a = Symbol('a', negative=True) b = Symbol('b', positive=True) raises(ValueError, lambda: LogLogistic('x', a, b)) a = Symbol('a', positive=True) b = Symbol('b', negative=True) raises(ValueError, lambda: LogLogistic('x', a, b)) a, b, z, p = symbols('a b z p', positive=True) X = LogLogistic('x', a, b) assert density(X)(z) == b*(z/a)**(b - 1)/(a*((z/a)**b + 1)**2) assert cdf(X)(z) == 1/(1 + (z/a)**(-b)) assert quantile(X)(p) == a*(p/(1 - p))**(1/b) # Expectation assert E(X) == Piecewise((S.NaN, b <= 1), (pi*a/(b*sin(pi/b)), True)) b = symbols('b', prime=True) # b > 1 X = LogLogistic('x', a, b) assert E(X) == pi*a/(b*sin(pi/b)) X = LogLogistic('x', 1, 2) assert median(X) == FiniteSet(1) def test_lognormal(): mean = Symbol('mu', real=True) std = Symbol('sigma', positive=True) X = LogNormal('x', mean, std) # The sympy integrator can't do this too well #assert E(X) == exp(mean+std**2/2) #assert variance(X) == (exp(std**2)-1) * exp(2*mean + std**2) # Right now, only density function and sampling works scipy = import_module('scipy') if not scipy: skip('Scipy is not installed. Abort tests') with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed for i in range(3): X = LogNormal('x', i, 1) assert next(sample(X)) in X.pspace.domain.set size = 5 with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed samps = next(sample(X, size=size)) for samp in samps: assert samp in X.pspace.domain.set # The sympy integrator can't do this too well #assert E(X) == raises(NotImplementedError, lambda: moment_generating_function(X)) mu = Symbol("mu", real=True) sigma = Symbol("sigma", positive=True) X = LogNormal('x', mu, sigma) assert density(X)(x) == (sqrt(2)*exp(-(-mu + log(x))**2 /(2*sigma**2))/(2*x*sqrt(pi)*sigma)) # Tests cdf assert cdf(X)(x) == Piecewise( (erf(sqrt(2)*(-mu + log(x))/(2*sigma))/2 + S(1)/2, x > 0), (0, True)) X = LogNormal('x', 0, 1) # Mean 0, standard deviation 1 assert density(X)(x) == sqrt(2)*exp(-log(x)**2/2)/(2*x*sqrt(pi)) def test_Lomax(): a, l = symbols('a, l', negative=True) raises(ValueError, lambda: Lomax('X', a , l)) a, l = symbols('a, l', real=False) raises(ValueError, lambda: Lomax('X', a , l)) a, l = symbols('a, l', positive=True) X = Lomax('X', a, l) assert X.pspace.domain.set == Interval(0, oo) assert density(X)(x) == a*(1 + x/l)**(-a - 1)/l assert cdf(X)(x) == Piecewise((1 - (1 + x/l)**(-a), x >= 0), (0, True)) a = 3 X = Lomax('X', a, l) assert E(X) == l/2 assert median(X) == FiniteSet(l*(-1 + 2**Rational(1, 3))) assert variance(X) == 3*l**2/4 def test_maxwell(): a = Symbol("a", positive=True) X = Maxwell('x', a) assert density(X)(x) == (sqrt(2)*x**2*exp(-x**2/(2*a**2))/ (sqrt(pi)*a**3)) assert E(X) == 2*sqrt(2)*a/sqrt(pi) assert variance(X) == -8*a**2/pi + 3*a**2 assert cdf(X)(x) == erf(sqrt(2)*x/(2*a)) - sqrt(2)*x*exp(-x**2/(2*a**2))/(sqrt(pi)*a) assert diff(cdf(X)(x), x) == density(X)(x) def test_Moyal(): mu = Symbol('mu',real=False) sigma = Symbol('sigma', real=True, positive=True) raises(ValueError, lambda: Moyal('M',mu, sigma)) mu = Symbol('mu', real=True) sigma = Symbol('sigma', real=True, negative=True) raises(ValueError, lambda: Moyal('M',mu, sigma)) sigma = Symbol('sigma', real=True, positive=True) M = Moyal('M', mu, sigma) assert density(M)(z) == sqrt(2)*exp(-exp((mu - z)/sigma)/2 - (-mu + z)/(2*sigma))/(2*sqrt(pi)*sigma) assert cdf(M)(z).simplify() == 1 - erf(sqrt(2)*exp((mu - z)/(2*sigma))/2) assert characteristic_function(M)(z) == 2**(-I*sigma*z)*exp(I*mu*z) \ *gamma(-I*sigma*z + Rational(1, 2))/sqrt(pi) assert E(M) == mu + EulerGamma*sigma + sigma*log(2) assert moment_generating_function(M)(z) == 2**(-sigma*z)*exp(mu*z) \ *gamma(-sigma*z + Rational(1, 2))/sqrt(pi) def test_nakagami(): mu = Symbol("mu", positive=True) omega = Symbol("omega", positive=True) X = Nakagami('x', mu, omega) assert density(X)(x) == (2*x**(2*mu - 1)*mu**mu*omega**(-mu) *exp(-x**2*mu/omega)/gamma(mu)) assert simplify(E(X)) == (sqrt(mu)*sqrt(omega) *gamma(mu + S.Half)/gamma(mu + 1)) assert simplify(variance(X)) == ( omega - omega*gamma(mu + S.Half)**2/(gamma(mu)*gamma(mu + 1))) assert cdf(X)(x) == Piecewise( (lowergamma(mu, mu*x**2/omega)/gamma(mu), x > 0), (0, True)) X = Nakagami('x',1 ,1) assert median(X) == FiniteSet(sqrt(log(2))) def test_gaussian_inverse(): # test for symbolic parameters a, b = symbols('a b') assert GaussianInverse('x', a, b) # Inverse Gaussian distribution is also known as Wald distribution # `GaussianInverse` can also be referred by the name `Wald` a, b, z = symbols('a b z') X = Wald('x', a, b) assert density(X)(z) == sqrt(2)*sqrt(b/z**3)*exp(-b*(-a + z)**2/(2*a**2*z))/(2*sqrt(pi)) a, b = symbols('a b', positive=True) z = Symbol('z', positive=True) X = GaussianInverse('x', a, b) assert density(X)(z) == sqrt(2)*sqrt(b)*sqrt(z**(-3))*exp(-b*(-a + z)**2/(2*a**2*z))/(2*sqrt(pi)) assert E(X) == a assert variance(X).expand() == a**3/b assert cdf(X)(z) == (S.Half - erf(sqrt(2)*sqrt(b)*(1 + z/a)/(2*sqrt(z)))/2)*exp(2*b/a) +\ erf(sqrt(2)*sqrt(b)*(-1 + z/a)/(2*sqrt(z)))/2 + S.Half a = symbols('a', nonpositive=True) raises(ValueError, lambda: GaussianInverse('x', a, b)) a = symbols('a', positive=True) b = symbols('b', nonpositive=True) raises(ValueError, lambda: GaussianInverse('x', a, b)) def test_sampling_gaussian_inverse(): scipy = import_module('scipy') if not scipy: skip('Scipy not installed. Abort tests for sampling of Gaussian inverse.') X = GaussianInverse("x", 1, 1) with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed assert next(sample(X, library='scipy')) in X.pspace.domain.set def test_pareto(): xm, beta = symbols('xm beta', positive=True) alpha = beta + 5 X = Pareto('x', xm, alpha) dens = density(X) #Tests cdf function assert cdf(X)(x) == \ Piecewise((-x**(-beta - 5)*xm**(beta + 5) + 1, x >= xm), (0, True)) #Tests characteristic_function assert characteristic_function(X)(x) == \ ((-I*x*xm)**(beta + 5)*(beta + 5)*uppergamma(-beta - 5, -I*x*xm)) assert dens(x) == x**(-(alpha + 1))*xm**(alpha)*(alpha) assert simplify(E(X)) == alpha*xm/(alpha-1) # computation of taylor series for MGF still too slow #assert simplify(variance(X)) == xm**2*alpha / ((alpha-1)**2*(alpha-2)) def test_pareto_numeric(): xm, beta = 3, 2 alpha = beta + 5 X = Pareto('x', xm, alpha) assert E(X) == alpha*xm/S(alpha - 1) assert variance(X) == xm**2*alpha / S((alpha - 1)**2*(alpha - 2)) assert median(X) == FiniteSet(3*2**Rational(1, 7)) # Skewness tests too slow. Try shortcutting function? def test_PowerFunction(): alpha = Symbol("alpha", nonpositive=True) a, b = symbols('a, b', real=True) raises (ValueError, lambda: PowerFunction('x', alpha, a, b)) a, b = symbols('a, b', real=False) raises (ValueError, lambda: PowerFunction('x', alpha, a, b)) alpha = Symbol("alpha", positive=True) a, b = symbols('a, b', real=True) raises (ValueError, lambda: PowerFunction('x', alpha, 5, 2)) X = PowerFunction('X', 2, a, b) assert density(X)(z) == (-2*a + 2*z)/(-a + b)**2 assert cdf(X)(z) == Piecewise((a**2/(a**2 - 2*a*b + b**2) - 2*a*z/(a**2 - 2*a*b + b**2) + z**2/(a**2 - 2*a*b + b**2), a <= z), (0, True)) X = PowerFunction('X', 2, 0, 1) assert density(X)(z) == 2*z assert cdf(X)(z) == Piecewise((z**2, z >= 0), (0,True)) assert E(X) == Rational(2,3) assert P(X < 0) == 0 assert P(X < 1) == 1 assert median(X) == FiniteSet(1/sqrt(2)) def test_raised_cosine(): mu = Symbol("mu", real=True) s = Symbol("s", positive=True) X = RaisedCosine("x", mu, s) assert pspace(X).domain.set == Interval(mu - s, mu + s) #Tests characteristics_function assert characteristic_function(X)(x) == \ Piecewise((exp(-I*pi*mu/s)/2, Eq(x, -pi/s)), (exp(I*pi*mu/s)/2, Eq(x, pi/s)), (pi**2*exp(I*mu*x)*sin(s*x)/(s*x*(-s**2*x**2 + pi**2)), True)) assert density(X)(x) == (Piecewise(((cos(pi*(x - mu)/s) + 1)/(2*s), And(x <= mu + s, mu - s <= x)), (0, True))) def test_rayleigh(): sigma = Symbol("sigma", positive=True) X = Rayleigh('x', sigma) #Tests characteristic_function assert characteristic_function(X)(x) == (-sqrt(2)*sqrt(pi)*sigma*x*(erfi(sqrt(2)*sigma*x/2) - I)*exp(-sigma**2*x**2/2)/2 + 1) assert density(X)(x) == x*exp(-x**2/(2*sigma**2))/sigma**2 assert E(X) == sqrt(2)*sqrt(pi)*sigma/2 assert variance(X) == -pi*sigma**2/2 + 2*sigma**2 assert cdf(X)(x) == 1 - exp(-x**2/(2*sigma**2)) assert diff(cdf(X)(x), x) == density(X)(x) def test_reciprocal(): a = Symbol("a", real=True) b = Symbol("b", real=True) X = Reciprocal('x', a, b) assert density(X)(x) == 1/(x*(-log(a) + log(b))) assert cdf(X)(x) == Piecewise((log(a)/(log(a) - log(b)) - log(x)/(log(a) - log(b)), a <= x), (0, True)) X = Reciprocal('x', 5, 30) assert E(X) == 25/(log(30) - log(5)) assert P(X < 4) == S.Zero assert P(X < 20) == log(20) / (log(30) - log(5)) - log(5) / (log(30) - log(5)) assert cdf(X)(10) == log(10) / (log(30) - log(5)) - log(5) / (log(30) - log(5)) a = symbols('a', nonpositive=True) raises(ValueError, lambda: Reciprocal('x', a, b)) a = symbols('a', positive=True) b = symbols('b', positive=True) raises(ValueError, lambda: Reciprocal('x', a + b, a)) def test_shiftedgompertz(): b = Symbol("b", positive=True) eta = Symbol("eta", positive=True) X = ShiftedGompertz("x", b, eta) assert density(X)(x) == b*(eta*(1 - exp(-b*x)) + 1)*exp(-b*x)*exp(-eta*exp(-b*x)) def test_studentt(): nu = Symbol("nu", positive=True) X = StudentT('x', nu) assert density(X)(x) == (1 + x**2/nu)**(-nu/2 - S.Half)/(sqrt(nu)*beta(S.Half, nu/2)) assert cdf(X)(x) == S.Half + x*gamma(nu/2 + S.Half)*hyper((S.Half, nu/2 + S.Half), (Rational(3, 2),), -x**2/nu)/(sqrt(pi)*sqrt(nu)*gamma(nu/2)) raises(NotImplementedError, lambda: moment_generating_function(X)) def test_trapezoidal(): a = Symbol("a", real=True) b = Symbol("b", real=True) c = Symbol("c", real=True) d = Symbol("d", real=True) X = Trapezoidal('x', a, b, c, d) assert density(X)(x) == Piecewise(((-2*a + 2*x)/((-a + b)*(-a - b + c + d)), (a <= x) & (x < b)), (2/(-a - b + c + d), (b <= x) & (x < c)), ((2*d - 2*x)/((-c + d)*(-a - b + c + d)), (c <= x) & (x <= d)), (0, True)) X = Trapezoidal('x', 0, 1, 2, 3) assert E(X) == Rational(3, 2) assert variance(X) == Rational(5, 12) assert P(X < 2) == Rational(3, 4) assert median(X) == FiniteSet(Rational(3, 2)) def test_triangular(): a = Symbol("a") b = Symbol("b") c = Symbol("c") X = Triangular('x', a, b, c) assert pspace(X).domain.set == Interval(a, b) assert str(density(X)(x)) == ("Piecewise(((-2*a + 2*x)/((-a + b)*(-a + c)), (a <= x) & (c > x)), " "(2/(-a + b), Eq(c, x)), ((2*b - 2*x)/((-a + b)*(b - c)), (b >= x) & (c < x)), (0, True))") #Tests moment_generating_function assert moment_generating_function(X)(x).expand() == \ ((-2*(-a + b)*exp(c*x) + 2*(-a + c)*exp(b*x) + 2*(b - c)*exp(a*x))/(x**2*(-a + b)*(-a + c)*(b - c))).expand() assert str(characteristic_function(X)(x)) == \ '(2*(-a + b)*exp(I*c*x) - 2*(-a + c)*exp(I*b*x) - 2*(b - c)*exp(I*a*x))/(x**2*(-a + b)*(-a + c)*(b - c))' def test_quadratic_u(): a = Symbol("a", real=True) b = Symbol("b", real=True) X = QuadraticU("x", a, b) Y = QuadraticU("x", 1, 2) assert pspace(X).domain.set == Interval(a, b) # Tests _moment_generating_function assert moment_generating_function(Y)(1) == -15*exp(2) + 27*exp(1) assert moment_generating_function(Y)(2) == -9*exp(4)/2 + 21*exp(2)/2 assert characteristic_function(Y)(1) == 3*I*(-1 + 4*I)*exp(I*exp(2*I)) assert density(X)(x) == (Piecewise((12*(x - a/2 - b/2)**2/(-a + b)**3, And(x <= b, a <= x)), (0, True))) def test_uniform(): l = Symbol('l', real=True) w = Symbol('w', positive=True) X = Uniform('x', l, l + w) assert E(X) == l + w/2 assert variance(X).expand() == w**2/12 # With numbers all is well X = Uniform('x', 3, 5) assert P(X < 3) == 0 and P(X > 5) == 0 assert P(X < 4) == P(X > 4) == S.Half assert median(X) == FiniteSet(4) z = Symbol('z') p = density(X)(z) assert p.subs(z, 3.7) == S.Half assert p.subs(z, -1) == 0 assert p.subs(z, 6) == 0 c = cdf(X) assert c(2) == 0 and c(3) == 0 assert c(Rational(7, 2)) == Rational(1, 4) assert c(5) == 1 and c(6) == 1 @XFAIL def test_uniform_P(): """ This stopped working because SingleContinuousPSpace.compute_density no longer calls integrate on a DiracDelta but rather just solves directly. integrate used to call UniformDistribution.expectation which special-cased subsed out the Min and Max terms that Uniform produces I decided to regress on this class for general cleanliness (and I suspect speed) of the algorithm. """ l = Symbol('l', real=True) w = Symbol('w', positive=True) X = Uniform('x', l, l + w) assert P(X < l) == 0 and P(X > l + w) == 0 def test_uniformsum(): n = Symbol("n", integer=True) _k = Dummy("k") x = Symbol("x") X = UniformSum('x', n) res = Sum((-1)**_k*(-_k + x)**(n - 1)*binomial(n, _k), (_k, 0, floor(x)))/factorial(n - 1) assert density(X)(x).dummy_eq(res) #Tests set functions assert X.pspace.domain.set == Interval(0, n) #Tests the characteristic_function assert characteristic_function(X)(x) == (-I*(exp(I*x) - 1)/x)**n #Tests the moment_generating_function assert moment_generating_function(X)(x) == ((exp(x) - 1)/x)**n def test_von_mises(): mu = Symbol("mu") k = Symbol("k", positive=True) X = VonMises("x", mu, k) assert density(X)(x) == exp(k*cos(x - mu))/(2*pi*besseli(0, k)) def test_weibull(): a, b = symbols('a b', positive=True) # FIXME: simplify(E(X)) seems to hang without extended_positive=True # On a Linux machine this had a rapid memory leak... # a, b = symbols('a b', positive=True) X = Weibull('x', a, b) assert E(X).expand() == a * gamma(1 + 1/b) assert variance(X).expand() == (a**2 * gamma(1 + 2/b) - E(X)**2).expand() assert simplify(skewness(X)) == (2*gamma(1 + 1/b)**3 - 3*gamma(1 + 1/b)*gamma(1 + 2/b) + gamma(1 + 3/b))/(-gamma(1 + 1/b)**2 + gamma(1 + 2/b))**Rational(3, 2) assert simplify(kurtosis(X)) == (-3*gamma(1 + 1/b)**4 +\ 6*gamma(1 + 1/b)**2*gamma(1 + 2/b) - 4*gamma(1 + 1/b)*gamma(1 + 3/b) + gamma(1 + 4/b))/(gamma(1 + 1/b)**2 - gamma(1 + 2/b))**2 def test_weibull_numeric(): # Test for integers and rationals a = 1 bvals = [S.Half, 1, Rational(3, 2), 5] for b in bvals: X = Weibull('x', a, b) assert simplify(E(X)) == expand_func(a * gamma(1 + 1/S(b))) assert simplify(variance(X)) == simplify( a**2 * gamma(1 + 2/S(b)) - E(X)**2) # Not testing Skew... it's slow with int/frac values > 3/2 def test_wignersemicircle(): R = Symbol("R", positive=True) X = WignerSemicircle('x', R) assert pspace(X).domain.set == Interval(-R, R) assert density(X)(x) == 2*sqrt(-x**2 + R**2)/(pi*R**2) assert E(X) == 0 #Tests ChiNoncentralDistribution assert characteristic_function(X)(x) == \ Piecewise((2*besselj(1, R*x)/(R*x), Ne(x, 0)), (1, True)) def test_prefab_sampling(): scipy = import_module('scipy') if not scipy: skip('Scipy is not installed. Abort tests') N = Normal('X', 0, 1) L = LogNormal('L', 0, 1) E = Exponential('Ex', 1) P = Pareto('P', 1, 3) W = Weibull('W', 1, 1) U = Uniform('U', 0, 1) B = Beta('B', 2, 5) G = Gamma('G', 1, 3) variables = [N, L, E, P, W, U, B, G] niter = 10 size = 5 with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed for var in variables: for _ in range(niter): assert next(sample(var)) in var.pspace.domain.set samps = next(sample(var, size=size)) for samp in samps: assert samp in var.pspace.domain.set def test_input_value_assertions(): a, b = symbols('a b') p, q = symbols('p q', positive=True) m, n = symbols('m n', positive=False, real=True) raises(ValueError, lambda: Normal('x', 3, 0)) raises(ValueError, lambda: Normal('x', m, n)) Normal('X', a, p) # No error raised raises(ValueError, lambda: Exponential('x', m)) Exponential('Ex', p) # No error raised for fn in [Pareto, Weibull, Beta, Gamma]: raises(ValueError, lambda: fn('x', m, p)) raises(ValueError, lambda: fn('x', p, n)) fn('x', p, q) # No error raised def test_unevaluated(): X = Normal('x', 0, 1) k = Dummy('k') expr1 = Integral(sqrt(2)*k*exp(-k**2/2)/(2*sqrt(pi)), (k, -oo, oo)) expr2 = Integral(sqrt(2)*exp(-k**2/2)/(2*sqrt(pi)), (k, 0, oo)) with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed assert E(X, evaluate=False).rewrite(Integral).dummy_eq(expr1) assert E(X + 1, evaluate=False).rewrite(Integral).dummy_eq(expr1 + 1) assert P(X > 0, evaluate=False).rewrite(Integral).dummy_eq(expr2) assert P(X > 0, X**2 < 1) == S.Half def test_probability_unevaluated(): T = Normal('T', 30, 3) with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed assert type(P(T > 33, evaluate=False)) == Probability def test_density_unevaluated(): X = Normal('X', 0, 1) Y = Normal('Y', 0, 2) assert isinstance(density(X+Y, evaluate=False)(z), Integral) def test_NormalDistribution(): nd = NormalDistribution(0, 1) x = Symbol('x') assert nd.cdf(x) == erf(sqrt(2)*x/2)/2 + S.Half assert nd.expectation(1, x) == 1 assert nd.expectation(x, x) == 0 assert nd.expectation(x**2, x) == 1 #Test issue 10076 a = SingleContinuousPSpace(x, NormalDistribution(2, 4)) _z = Dummy('_z') expected1 = Integral(sqrt(2)*exp(-(_z - 2)**2/32)/(8*sqrt(pi)),(_z, -oo, 1)) assert a.probability(x < 1, evaluate=False).dummy_eq(expected1) is True expected2 = Integral(sqrt(2)*exp(-(_z - 2)**2/32)/(8*sqrt(pi)),(_z, 1, oo)) assert a.probability(x > 1, evaluate=False).dummy_eq(expected2) is True b = SingleContinuousPSpace(x, NormalDistribution(1, 9)) expected3 = Integral(sqrt(2)*exp(-(_z - 1)**2/162)/(18*sqrt(pi)),(_z, 6, oo)) assert b.probability(x > 6, evaluate=False).dummy_eq(expected3) is True expected4 = Integral(sqrt(2)*exp(-(_z - 1)**2/162)/(18*sqrt(pi)),(_z, -oo, 6)) assert b.probability(x < 6, evaluate=False).dummy_eq(expected4) is True def test_random_parameters(): mu = Normal('mu', 2, 3) meas = Normal('T', mu, 1) assert density(meas, evaluate=False)(z) assert isinstance(pspace(meas), CompoundPSpace) X = Normal('x', [1, 2], [[1, 0], [0, 1]]) assert isinstance(pspace(X).distribution, MultivariateNormalDistribution) assert density(meas)(z).simplify() == sqrt(5)*exp(-z**2/20 + z/5 - S(1)/5)/(10*sqrt(pi)) def test_random_parameters_given(): mu = Normal('mu', 2, 3) meas = Normal('T', mu, 1) assert given(meas, Eq(mu, 5)) == Normal('T', 5, 1) def test_conjugate_priors(): mu = Normal('mu', 2, 3) x = Normal('x', mu, 1) assert isinstance(simplify(density(mu, Eq(x, y), evaluate=False)(z)), Mul) def test_difficult_univariate(): """ Since using solve in place of deltaintegrate we're able to perform substantially more complex density computations on single continuous random variables """ x = Normal('x', 0, 1) assert density(x**3) assert density(exp(x**2)) assert density(log(x)) def test_issue_10003(): X = Exponential('x', 3) G = Gamma('g', 1, 2) assert P(X < -1) is S.Zero assert P(G < -1) is S.Zero @slow def test_precomputed_cdf(): x = symbols("x", real=True) mu = symbols("mu", real=True) sigma, xm, alpha = symbols("sigma xm alpha", positive=True) n = symbols("n", integer=True, positive=True) distribs = [ Normal("X", mu, sigma), Pareto("P", xm, alpha), ChiSquared("C", n), Exponential("E", sigma), # LogNormal("L", mu, sigma), ] for X in distribs: compdiff = cdf(X)(x) - simplify(X.pspace.density.compute_cdf()(x)) compdiff = simplify(compdiff.rewrite(erfc)) assert compdiff == 0 @slow def test_precomputed_characteristic_functions(): import mpmath def test_cf(dist, support_lower_limit, support_upper_limit): pdf = density(dist) t = Symbol('t') # first function is the hardcoded CF of the distribution cf1 = lambdify([t], characteristic_function(dist)(t), 'mpmath') # second function is the Fourier transform of the density function f = lambdify([x, t], pdf(x)*exp(I*x*t), 'mpmath') cf2 = lambda t: mpmath.quad(lambda x: f(x, t), [support_lower_limit, support_upper_limit], maxdegree=10) # compare the two functions at various points for test_point in [2, 5, 8, 11]: n1 = cf1(test_point) n2 = cf2(test_point) assert abs(re(n1) - re(n2)) < 1e-12 assert abs(im(n1) - im(n2)) < 1e-12 test_cf(Beta('b', 1, 2), 0, 1) test_cf(Chi('c', 3), 0, mpmath.inf) test_cf(ChiSquared('c', 2), 0, mpmath.inf) test_cf(Exponential('e', 6), 0, mpmath.inf) test_cf(Logistic('l', 1, 2), -mpmath.inf, mpmath.inf) test_cf(Normal('n', -1, 5), -mpmath.inf, mpmath.inf) test_cf(RaisedCosine('r', 3, 1), 2, 4) test_cf(Rayleigh('r', 0.5), 0, mpmath.inf) test_cf(Uniform('u', -1, 1), -1, 1) test_cf(WignerSemicircle('w', 3), -3, 3) def test_long_precomputed_cdf(): x = symbols("x", real=True) distribs = [ Arcsin("A", -5, 9), Dagum("D", 4, 10, 3), Erlang("E", 14, 5), Frechet("F", 2, 6, -3), Gamma("G", 2, 7), GammaInverse("GI", 3, 5), Kumaraswamy("K", 6, 8), Laplace("LA", -5, 4), Logistic("L", -6, 7), Nakagami("N", 2, 7), StudentT("S", 4) ] for distr in distribs: for _ in range(5): assert tn(diff(cdf(distr)(x), x), density(distr)(x), x, a=0, b=0, c=1, d=0) US = UniformSum("US", 5) pdf01 = density(US)(x).subs(floor(x), 0).doit() # pdf on (0, 1) cdf01 = cdf(US, evaluate=False)(x).subs(floor(x), 0).doit() # cdf on (0, 1) assert tn(diff(cdf01, x), pdf01, x, a=0, b=0, c=1, d=0) def test_issue_13324(): X = Uniform('X', 0, 1) assert E(X, X > S.Half) == Rational(3, 4) assert E(X, X > 0) == S.Half def test_FiniteSet_prob(): E = Exponential('E', 3) N = Normal('N', 5, 7) assert P(Eq(E, 1)) is S.Zero assert P(Eq(N, 2)) is S.Zero assert P(Eq(N, x)) is S.Zero def test_prob_neq(): E = Exponential('E', 4) X = ChiSquared('X', 4) assert P(Ne(E, 2)) == 1 assert P(Ne(X, 4)) == 1 assert P(Ne(X, 4)) == 1 assert P(Ne(X, 5)) == 1 assert P(Ne(E, x)) == 1 def test_union(): N = Normal('N', 3, 2) assert simplify(P(N**2 - N > 2)) == \ -erf(sqrt(2))/2 - erfc(sqrt(2)/4)/2 + Rational(3, 2) assert simplify(P(N**2 - 4 > 0)) == \ -erf(5*sqrt(2)/4)/2 - erfc(sqrt(2)/4)/2 + Rational(3, 2) def test_Or(): N = Normal('N', 0, 1) assert simplify(P(Or(N > 2, N < 1))) == \ -erf(sqrt(2))/2 - erfc(sqrt(2)/2)/2 + Rational(3, 2) assert P(Or(N < 0, N < 1)) == P(N < 1) assert P(Or(N > 0, N < 0)) == 1 def test_conditional_eq(): E = Exponential('E', 1) assert P(Eq(E, 1), Eq(E, 1)) == 1 assert P(Eq(E, 1), Eq(E, 2)) == 0 assert P(E > 1, Eq(E, 2)) == 1 assert P(E < 1, Eq(E, 2)) == 0 def test_ContinuousDistributionHandmade(): x = Symbol('x') z = Dummy('z') dens = Lambda(x, Piecewise((S.Half, (0<=x)&(x<1)), (0, (x>=1)&(x<2)), (S.Half, (x>=2)&(x<3)), (0, True))) dens = ContinuousDistributionHandmade(dens, set=Interval(0, 3)) space = SingleContinuousPSpace(z, dens) assert dens.pdf == Lambda(x, Piecewise((1/2, (x >= 0) & (x < 1)), (0, (x >= 1) & (x < 2)), (1/2, (x >= 2) & (x < 3)), (0, True))) assert median(space.value) == Interval(1, 2) assert E(space.value) == Rational(3, 2) assert variance(space.value) == Rational(13, 12) def test_sample_numpy(): distribs_numpy = [ Beta("B", 1, 1), Normal("N", 0, 1), Gamma("G", 2, 7), Exponential("E", 2), LogNormal("LN", 0, 1), Pareto("P", 1, 1), ChiSquared("CS", 2), Uniform("U", 0, 1) ] size = 3 numpy = import_module('numpy') if not numpy: skip('Numpy is not installed. Abort tests for _sample_numpy.') else: with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed for X in distribs_numpy: samps = next(sample(X, size=size, library='numpy')) for sam in samps: assert sam in X.pspace.domain.set raises(NotImplementedError, lambda: next(sample(Chi("C", 1), library='numpy'))) raises(NotImplementedError, lambda: Chi("C", 1).pspace.distribution.sample(library='tensorflow')) def test_sample_scipy(): distribs_scipy = [ Beta("B", 1, 1), BetaPrime("BP", 1, 1), Cauchy("C", 1, 1), Chi("C", 1), Normal("N", 0, 1), Gamma("G", 2, 7), GammaInverse("GI", 1, 1), GaussianInverse("GUI", 1, 1), Exponential("E", 2), LogNormal("LN", 0, 1), Pareto("P", 1, 1), StudentT("S", 2), ChiSquared("CS", 2), Uniform("U", 0, 1) ] size = 3 numsamples = 5 scipy = import_module('scipy') if not scipy: skip('Scipy is not installed. Abort tests for _sample_scipy.') else: with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed g_sample = list(sample(Gamma("G", 2, 7), size=size, numsamples=numsamples)) assert len(g_sample) == numsamples for X in distribs_scipy: samps = next(sample(X, size=size, library='scipy')) samps2 = next(sample(X, size=(2, 2), library='scipy')) for sam in samps: assert sam in X.pspace.domain.set for i in range(2): for j in range(2): assert samps2[i][j] in X.pspace.domain.set def test_sample_pymc3(): distribs_pymc3 = [ Beta("B", 1, 1), Cauchy("C", 1, 1), Normal("N", 0, 1), Gamma("G", 2, 7), GaussianInverse("GI", 1, 1), Exponential("E", 2), LogNormal("LN", 0, 1), Pareto("P", 1, 1), ChiSquared("CS", 2), Uniform("U", 0, 1) ] size = 3 pymc3 = import_module('pymc3') if not pymc3: skip('PyMC3 is not installed. Abort tests for _sample_pymc3.') else: with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed for X in distribs_pymc3: samps = next(sample(X, size=size, library='pymc3')) for sam in samps: assert sam in X.pspace.domain.set raises(NotImplementedError, lambda: next(sample(Chi("C", 1), library='pymc3'))) def test_issue_16318(): #test compute_expectation function of the SingleContinuousDomain N = SingleContinuousDomain(x, Interval(0, 1)) raises (ValueError, lambda: SingleContinuousDomain.compute_expectation(N, x+1, {x, y}))
f9b2d2770ddc5a6acd6d083e05773b7256a35d03672f94cc203dfe6fe603e0b1
from __future__ import print_function, division 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
17a24db75385753e06eb916d3d6eddf15f8f6061f6d90e576369413e39b1c700
from sympy.core.add import Add from sympy.core.assumptions import check_assumptions from sympy.core.containers import Tuple from sympy.core.compatibility import as_int, is_sequence, ordered from sympy.core.exprtools import factor_terms from sympy.core.function import _mexpand from sympy.core.mul import Mul from sympy.core.numbers import Rational from sympy.core.numbers import igcdex, ilcm, igcd from sympy.core.power import integer_nthroot, isqrt from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import Symbol, symbols from sympy.core.sympify import _sympify from sympy.functions.elementary.complexes import sign from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt from sympy.matrices.dense import MutableDenseMatrix as Matrix from sympy.ntheory.factor_ import ( divisors, factorint, multiplicity, perfect_power) from sympy.ntheory.generate import nextprime from sympy.ntheory.primetest import is_square, isprime from sympy.ntheory.residue_ntheory import sqrt_mod from sympy.polys.polyerrors import GeneratorsNeeded from sympy.polys.polytools import Poly, factor_list from sympy.simplify.simplify import signsimp from sympy.solvers.solveset import solveset_real from sympy.utilities import default_sort_key, numbered_symbols from sympy.utilities.misc import filldedent # these are imported with 'from sympy.solvers.diophantine import * __all__ = ['diophantine', 'classify_diop'] class DiophantineSolutionSet(set): """ Container for a set of solutions to a particular diophantine equation. The base representation is a set of tuples representing each of the solutions. Parameters ========== symbols : list List of free symbols in the original equation. parameters: list (optional) List of parameters to be used in the solution. Examples ======== Adding solutions: >>> from sympy.solvers.diophantine.diophantine import DiophantineSolutionSet >>> from sympy.abc import x, y, t, u >>> s1 = DiophantineSolutionSet([x, y], [t, u]) >>> s1 set() >>> s1.add((2, 3)) >>> s1.add((-1, u)) >>> s1 {(-1, u), (2, 3)} >>> s2 = DiophantineSolutionSet([x, y], [t, u]) >>> s2.add((3, 4)) >>> s1.update(*s2) >>> s1 {(-1, u), (2, 3), (3, 4)} Conversion of solutions into dicts: >>> list(s1.dict_iterator()) [{x: -1, y: u}, {x: 2, y: 3}, {x: 3, y: 4}] Substituting values: >>> s3 = DiophantineSolutionSet([x, y], [t, u]) >>> s3.add((t**2, t + u)) >>> s3 {(t**2, t + u)} >>> s3.subs({t: 2, u: 3}) {(4, 5)} >>> s3.subs(t, -1) {(1, u - 1)} >>> s3.subs(t, 3) {(9, u + 3)} Evaluation at specific values. Positional arguments are given in the same order as the parameters: >>> s3(-2, 3) {(4, 1)} >>> s3(5) {(25, u + 5)} >>> s3(None, 2) {(t**2, t + 2)} """ def __init__(self, symbols_seq, parameters=None): super().__init__() if not is_sequence(symbols_seq): raise ValueError("Symbols must be given as a sequence.") self.symbols = tuple(symbols_seq) if parameters is None: self.parameters = symbols('%s1:%i' % ('t', len(self.symbols) + 1), integer=True) else: self.parameters = tuple(parameters) def add(self, solution): if len(solution) != len(self.symbols): raise ValueError("Solution should have a length of %s, not %s" % (len(self.symbols), len(solution))) super(DiophantineSolutionSet, self).add(Tuple(*solution)) def update(self, *solutions): for solution in solutions: self.add(solution) def dict_iterator(self): for solution in ordered(self): yield dict(zip(self.symbols, solution)) def subs(self, *args, **kwargs): result = DiophantineSolutionSet(self.symbols, self.parameters) for solution in self: result.add(solution.subs(*args, **kwargs)) return result def __call__(self, *args): if len(args) > len(self.parameters): raise ValueError("Evaluation should have at most %s values, not %s" % (len(self.parameters), len(args))) return self.subs(zip(self.parameters, args)) class DiophantineEquationType: """ Internal representation of a particular diophantine equation type. Parameters ========== equation The diophantine equation that is being solved. free_symbols: list (optional) The symbols being solved for. Attributes ========== total_degree The maximum of the degrees of all terms in the equation homogeneous Does the equation contain a term of degree 0 homogeneous_order Does the equation contain any coefficient that is in the symbols being solved for dimension The number of symbols being solved for """ name = None # type: str def __init__(self, equation, free_symbols=None): self.equation = _sympify(equation).expand(force=True) if free_symbols is not None: self.free_symbols = free_symbols else: self.free_symbols = list(self.equation.free_symbols) if not self.free_symbols: raise ValueError('equation should have 1 or more free symbols') self.free_symbols.sort(key=default_sort_key) self.coeff = self.equation.as_coefficients_dict() if not all(_is_int(c) for c in self.coeff.values()): raise TypeError("Coefficients should be Integers") self.total_degree = Poly(self.equation).total_degree() self.homogeneous = 1 not in self.coeff self.homogeneous_order = not (set(self.coeff) & set(self.free_symbols)) self.dimension = len(self.free_symbols) def matches(self): """ Determine whether the given equation can be matched to the particular equation type. """ return False class Univariate(DiophantineEquationType): name = 'univariate' def matches(self): return self.dimension == 1 class Linear(DiophantineEquationType): name = 'linear' def matches(self): return self.total_degree == 1 class BinaryQuadratic(DiophantineEquationType): name = 'binary_quadratic' def matches(self): return self.total_degree == 2 and self.dimension == 2 class InhomogeneousTernaryQuadratic(DiophantineEquationType): name = 'inhomogeneous_ternary_quadratic' def matches(self): if not (self.total_degree == 2 and self.dimension == 3): return False if not self.homogeneous: return False return not self.homogeneous_order class HomogeneousTernaryQuadraticNormal(DiophantineEquationType): name = 'homogeneous_ternary_quadratic_normal' def matches(self): if not (self.total_degree == 2 and self.dimension == 3): return False if not self.homogeneous: return False if not self.homogeneous_order: return False nonzero = [k for k in self.coeff if self.coeff[k]] return len(nonzero) == 3 and all(i**2 in nonzero for i in self.free_symbols) class HomogeneousTernaryQuadratic(DiophantineEquationType): name = 'homogeneous_ternary_quadratic' def matches(self): if not (self.total_degree == 2 and self.dimension == 3): return False if not self.homogeneous: return False if not self.homogeneous_order: return False nonzero = [k for k in self.coeff if self.coeff[k]] return not (len(nonzero) == 3 and all(i**2 in nonzero for i in self.free_symbols)) class InhomogeneousGeneralQuadratic(DiophantineEquationType): name = 'inhomogeneous_general_quadratic' def matches(self): if not (self.total_degree == 2 and self.dimension >= 3): return False if not self.homogeneous_order: return True else: # there may be Pow keys like x**2 or Mul keys like x*y if any(k.is_Mul for k in self.coeff): # cross terms return not self.homogeneous return False class HomogeneousGeneralQuadratic(DiophantineEquationType): name = 'homogeneous_general_quadratic' def matches(self): if not (self.total_degree == 2 and self.dimension >= 3): return False if not self.homogeneous_order: return False else: # there may be Pow keys like x**2 or Mul keys like x*y if any(k.is_Mul for k in self.coeff): # cross terms return self.homogeneous return False class GeneralSumOfSquares(DiophantineEquationType): name = 'general_sum_of_squares' def matches(self): if not (self.total_degree == 2 and self.dimension >= 3): return False if not self.homogeneous_order: return False if any(k.is_Mul for k in self.coeff): return False return all(self.coeff[k] == 1 for k in self.coeff if k != 1) class GeneralPythagorean(DiophantineEquationType): name = 'general_pythagorean' def matches(self): if not (self.total_degree == 2 and self.dimension >= 3): return False if not self.homogeneous_order: return False if any(k.is_Mul for k in self.coeff): return False if all(self.coeff[k] == 1 for k in self.coeff if k != 1): return False if not all(is_square(abs(self.coeff[k])) for k in self.coeff): return False # all but one has the same sign # e.g. 4*x**2 + y**2 - 4*z**2 return abs(sum(sign(self.coeff[k]) for k in self.coeff)) == self.dimension - 2 class CubicThue(DiophantineEquationType): name = 'cubic_thue' def matches(self): return self.total_degree == 3 and self.dimension == 2 class GeneralSumOfEvenPowers(DiophantineEquationType): name = 'general_sum_of_even_powers' def matches(self): if not self.total_degree > 3: return False if self.total_degree % 2 != 0: return False if not all(k.is_Pow and k.exp == self.total_degree for k in self.coeff if k != 1): return False return all(self.coeff[k] == 1 for k in self.coeff if k != 1) # these types are known (but not necessarily handled) # note that order is important here (in the current solver state) all_diop_classes = [ Linear, Univariate, BinaryQuadratic, InhomogeneousTernaryQuadratic, HomogeneousTernaryQuadraticNormal, HomogeneousTernaryQuadratic, InhomogeneousGeneralQuadratic, HomogeneousGeneralQuadratic, GeneralSumOfSquares, GeneralPythagorean, CubicThue, GeneralSumOfEvenPowers, ] diop_known = set([diop_class.name for diop_class in all_diop_classes]) def _is_int(i): try: as_int(i) return True except ValueError: pass def _sorted_tuple(*i): return tuple(sorted(i)) def _remove_gcd(*x): try: g = igcd(*x) except ValueError: fx = list(filter(None, x)) if len(fx) < 2: return x g = igcd(*[i.as_content_primitive()[0] for i in fx]) except TypeError: raise TypeError('_remove_gcd(a,b,c) or _remove_gcd(*container)') if g == 1: return x return tuple([i//g for i in x]) def _rational_pq(a, b): # return `(numer, denom)` for a/b; sign in numer and gcd removed return _remove_gcd(sign(b)*a, abs(b)) def _nint_or_floor(p, q): # return nearest int to p/q; in case of tie return floor(p/q) w, r = divmod(p, q) if abs(r) <= abs(q)//2: return w return w + 1 def _odd(i): return i % 2 != 0 def _even(i): return i % 2 == 0 def diophantine(eq, param=symbols("t", integer=True), syms=None, permute=False): """ Simplify the solution procedure of diophantine equation ``eq`` by converting it into a product of terms which should equal zero. For example, when solving, `x^2 - y^2 = 0` this is treated as `(x + y)(x - y) = 0` and `x + y = 0` and `x - y = 0` are solved independently and combined. Each term is solved by calling ``diop_solve()``. (Although it is possible to call ``diop_solve()`` directly, one must be careful to pass an equation in the correct form and to interpret the output correctly; ``diophantine()`` is the public-facing function to use in general.) Output of ``diophantine()`` is a set of tuples. The elements of the tuple are the solutions for each variable in the equation and are arranged according to the alphabetic ordering of the variables. e.g. For an equation with two variables, `a` and `b`, the first element of the tuple is the solution for `a` and the second for `b`. Usage ===== ``diophantine(eq, t, syms)``: Solve the diophantine equation ``eq``. ``t`` is the optional parameter to be used by ``diop_solve()``. ``syms`` is an optional list of symbols which determines the order of the elements in the returned tuple. By default, only the base solution is returned. If ``permute`` is set to True then permutations of the base solution and/or permutations of the signs of the values will be returned when applicable. >>> from sympy.solvers.diophantine import diophantine >>> from sympy.abc import a, b >>> eq = a**4 + b**4 - (2**4 + 3**4) >>> diophantine(eq) {(2, 3)} >>> diophantine(eq, permute=True) {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)} Details ======= ``eq`` should be an expression which is assumed to be zero. ``t`` is the parameter to be used in the solution. Examples ======== >>> from sympy.abc import x, y, z >>> diophantine(x**2 - y**2) {(t_0, -t_0), (t_0, t_0)} >>> diophantine(x*(2*x + 3*y - z)) {(0, n1, n2), (t_0, t_1, 2*t_0 + 3*t_1)} >>> diophantine(x**2 + 3*x*y + 4*x) {(0, n1), (3*t_0 - 4, -t_0)} See Also ======== diop_solve() sympy.utilities.iterables.permute_signs sympy.utilities.iterables.signed_permutations """ from sympy.utilities.iterables import ( subsets, permute_signs, signed_permutations) eq = _sympify(eq) if isinstance(eq, Eq): eq = eq.lhs - eq.rhs try: var = list(eq.expand(force=True).free_symbols) var.sort(key=default_sort_key) if syms: if not is_sequence(syms): raise TypeError( 'syms should be given as a sequence, e.g. a list') syms = [i for i in syms if i in var] if syms != var: dict_sym_index = dict(zip(syms, range(len(syms)))) return {tuple([t[dict_sym_index[i]] for i in var]) for t in diophantine(eq, param, permute=permute)} n, d = eq.as_numer_denom() if n.is_number: return set() if not d.is_number: dsol = diophantine(d) good = diophantine(n) - dsol return {s for s in good if _mexpand(d.subs(zip(var, s)))} else: eq = n eq = factor_terms(eq) assert not eq.is_number eq = eq.as_independent(*var, as_Add=False)[1] p = Poly(eq) assert not any(g.is_number for g in p.gens) eq = p.as_expr() assert eq.is_polynomial() except (GeneratorsNeeded, AssertionError): raise TypeError(filldedent(''' Equation should be a polynomial with Rational coefficients.''')) # permute only sign do_permute_signs = False # permute sign and values do_permute_signs_var = False # permute few signs permute_few_signs = False try: # if we know that factoring should not be attempted, skip # the factoring step v, c, t = classify_diop(eq) # check for permute sign if permute: len_var = len(v) permute_signs_for = [ GeneralSumOfSquares.name, GeneralSumOfEvenPowers.name] permute_signs_check = [ HomogeneousTernaryQuadratic.name, HomogeneousTernaryQuadraticNormal.name, BinaryQuadratic.name] if t in permute_signs_for: do_permute_signs_var = True elif t in permute_signs_check: # if all the variables in eq have even powers # then do_permute_sign = True if len_var == 3: var_mul = list(subsets(v, 2)) # here var_mul is like [(x, y), (x, z), (y, z)] xy_coeff = True x_coeff = True var1_mul_var2 = map(lambda a: a[0]*a[1], var_mul) # if coeff(y*z), coeff(y*x), coeff(x*z) is not 0 then # `xy_coeff` => True and do_permute_sign => False. # Means no permuted solution. for v1_mul_v2 in var1_mul_var2: try: coeff = c[v1_mul_v2] except KeyError: coeff = 0 xy_coeff = bool(xy_coeff) and bool(coeff) var_mul = list(subsets(v, 1)) # here var_mul is like [(x,), (y, )] for v1 in var_mul: try: coeff = c[v1[0]] except KeyError: coeff = 0 x_coeff = bool(x_coeff) and bool(coeff) if not any([xy_coeff, x_coeff]): # means only x**2, y**2, z**2, const is present do_permute_signs = True elif not x_coeff: permute_few_signs = True elif len_var == 2: var_mul = list(subsets(v, 2)) # here var_mul is like [(x, y)] xy_coeff = True x_coeff = True var1_mul_var2 = map(lambda x: x[0]*x[1], var_mul) for v1_mul_v2 in var1_mul_var2: try: coeff = c[v1_mul_v2] except KeyError: coeff = 0 xy_coeff = bool(xy_coeff) and bool(coeff) var_mul = list(subsets(v, 1)) # here var_mul is like [(x,), (y, )] for v1 in var_mul: try: coeff = c[v1[0]] except KeyError: coeff = 0 x_coeff = bool(x_coeff) and bool(coeff) if not any([xy_coeff, x_coeff]): # means only x**2, y**2 and const is present # so we can get more soln by permuting this soln. do_permute_signs = True elif not x_coeff: # when coeff(x), coeff(y) is not present then signs of # x, y can be permuted such that their sign are same # as sign of x*y. # e.g 1. (x_val,y_val)=> (x_val,y_val), (-x_val,-y_val) # 2. (-x_vall, y_val)=> (-x_val,y_val), (x_val,-y_val) permute_few_signs = True if t == 'general_sum_of_squares': # trying to factor such expressions will sometimes hang terms = [(eq, 1)] else: raise TypeError except (TypeError, NotImplementedError): fl = factor_list(eq) if fl[0].is_Rational and fl[0] != 1: return diophantine(eq/fl[0], param=param, syms=syms, permute=permute) terms = fl[1] sols = set([]) for term in terms: base, _ = term var_t, _, eq_type = classify_diop(base, _dict=False) _, base = signsimp(base, evaluate=False).as_coeff_Mul() solution = diop_solve(base, param) if eq_type in [ Linear.name, HomogeneousTernaryQuadratic.name, HomogeneousTernaryQuadraticNormal.name, GeneralPythagorean.name]: sols.add(merge_solution(var, var_t, solution)) elif eq_type in [ BinaryQuadratic.name, GeneralSumOfSquares.name, GeneralSumOfEvenPowers.name, Univariate.name]: for sol in solution: sols.add(merge_solution(var, var_t, sol)) else: raise NotImplementedError('unhandled type: %s' % eq_type) # remove null merge results if () in sols: sols.remove(()) null = tuple([0]*len(var)) # if there is no solution, return trivial solution if not sols and eq.subs(zip(var, null)).is_zero: sols.add(null) final_soln = set([]) for sol in sols: if all(_is_int(s) for s in sol): if do_permute_signs: permuted_sign = set(permute_signs(sol)) final_soln.update(permuted_sign) elif permute_few_signs: lst = list(permute_signs(sol)) lst = list(filter(lambda x: x[0]*x[1] == sol[1]*sol[0], lst)) permuted_sign = set(lst) final_soln.update(permuted_sign) elif do_permute_signs_var: permuted_sign_var = set(signed_permutations(sol)) final_soln.update(permuted_sign_var) else: final_soln.add(sol) else: final_soln.add(sol) return final_soln def merge_solution(var, var_t, solution): """ This is used to construct the full solution from the solutions of sub equations. For example when solving the equation `(x - y)(x^2 + y^2 - z^2) = 0`, solutions for each of the equations `x - y = 0` and `x^2 + y^2 - z^2` are found independently. Solutions for `x - y = 0` are `(x, y) = (t, t)`. But we should introduce a value for z when we output the solution for the original equation. This function converts `(t, t)` into `(t, t, n_{1})` where `n_{1}` is an integer parameter. """ sol = [] if None in solution: return () solution = iter(solution) params = numbered_symbols("n", integer=True, start=1) for v in var: if v in var_t: sol.append(next(solution)) else: sol.append(next(params)) for val, symb in zip(sol, var): if check_assumptions(val, **symb.assumptions0) is False: return tuple() return tuple(sol) def diop_solve(eq, param=symbols("t", integer=True)): """ Solves the diophantine equation ``eq``. Unlike ``diophantine()``, factoring of ``eq`` is not attempted. Uses ``classify_diop()`` to determine the type of the equation and calls the appropriate solver function. Use of ``diophantine()`` is recommended over other helper functions. ``diop_solve()`` can return either a set or a tuple depending on the nature of the equation. Usage ===== ``diop_solve(eq, t)``: Solve diophantine equation, ``eq`` using ``t`` as a parameter if needed. Details ======= ``eq`` should be an expression which is assumed to be zero. ``t`` is a parameter to be used in the solution. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_solve >>> from sympy.abc import x, y, z, w >>> diop_solve(2*x + 3*y - 5) (3*t_0 - 5, 5 - 2*t_0) >>> diop_solve(4*x + 3*y - 4*z + 5) (t_0, 8*t_0 + 4*t_1 + 5, 7*t_0 + 3*t_1 + 5) >>> diop_solve(x + 3*y - 4*z + w - 6) (t_0, t_0 + t_1, 6*t_0 + 5*t_1 + 4*t_2 - 6, 5*t_0 + 4*t_1 + 3*t_2 - 6) >>> diop_solve(x**2 + y**2 - 5) {(-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)} See Also ======== diophantine() """ var, coeff, eq_type = classify_diop(eq, _dict=False) if eq_type == Linear.name: return diop_linear(eq, param) elif eq_type == BinaryQuadratic.name: return diop_quadratic(eq, param) elif eq_type == HomogeneousTernaryQuadratic.name: return diop_ternary_quadratic(eq, parameterize=True) elif eq_type == HomogeneousTernaryQuadraticNormal.name: return diop_ternary_quadratic_normal(eq, parameterize=True) elif eq_type == GeneralPythagorean.name: return diop_general_pythagorean(eq, param) elif eq_type == Univariate.name: return diop_univariate(eq) elif eq_type == GeneralSumOfSquares.name: return diop_general_sum_of_squares(eq, limit=S.Infinity) elif eq_type == GeneralSumOfEvenPowers.name: return diop_general_sum_of_even_powers(eq, limit=S.Infinity) if eq_type is not None and eq_type not in diop_known: raise ValueError(filldedent(''' Alhough this type of equation was identified, it is not yet handled. It should, however, be listed in `diop_known` at the top of this file. Developers should see comments at the end of `classify_diop`. ''')) # pragma: no cover else: raise NotImplementedError( 'No solver has been written for %s.' % eq_type) def classify_diop(eq, _dict=True): # docstring supplied externally matched = False diop_type = None for diop_class in all_diop_classes: diop_type = diop_class(eq) if diop_type.matches(): matched = True break if matched: return diop_type.free_symbols, dict(diop_type.coeff) if _dict else diop_type.coeff, diop_type.name # new diop type instructions # -------------------------- # if this error raises and the equation *can* be classified, # * it should be identified in the if-block above # * the type should be added to the diop_known # if a solver can be written for it, # * a dedicated handler should be written (e.g. diop_linear) # * it should be passed to that handler in diop_solve raise NotImplementedError(filldedent(''' This equation is not yet recognized or else has not been simplified sufficiently to put it in a form recognized by diop_classify().''')) classify_diop.func_doc = ( # type: ignore ''' Helper routine used by diop_solve() to find information about ``eq``. Returns a tuple containing the type of the diophantine equation along with the variables (free symbols) and their coefficients. Variables are returned as a list and coefficients are returned as a dict with the key being the respective term and the constant term is keyed to 1. The type is one of the following: * %s Usage ===== ``classify_diop(eq)``: Return variables, coefficients and type of the ``eq``. Details ======= ``eq`` should be an expression which is assumed to be zero. ``_dict`` is for internal use: when True (default) a dict is returned, otherwise a defaultdict which supplies 0 for missing keys is returned. Examples ======== >>> from sympy.solvers.diophantine import classify_diop >>> from sympy.abc import x, y, z, w, t >>> classify_diop(4*x + 6*y - 4) ([x, y], {1: -4, x: 4, y: 6}, 'linear') >>> classify_diop(x + 3*y -4*z + 5) ([x, y, z], {1: 5, x: 1, y: 3, z: -4}, 'linear') >>> classify_diop(x**2 + y**2 - x*y + x + 5) ([x, y], {1: 5, x: 1, x**2: 1, y**2: 1, x*y: -1}, 'binary_quadratic') ''' % ('\n * '.join(sorted(diop_known)))) def diop_linear(eq, param=symbols("t", integer=True)): """ Solves linear diophantine equations. A linear diophantine equation is an equation of the form `a_{1}x_{1} + a_{2}x_{2} + .. + a_{n}x_{n} = 0` where `a_{1}, a_{2}, ..a_{n}` are integer constants and `x_{1}, x_{2}, ..x_{n}` are integer variables. Usage ===== ``diop_linear(eq)``: Returns a tuple containing solutions to the diophantine equation ``eq``. Values in the tuple is arranged in the same order as the sorted variables. Details ======= ``eq`` is a linear diophantine equation which is assumed to be zero. ``param`` is the parameter to be used in the solution. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_linear >>> from sympy.abc import x, y, z >>> diop_linear(2*x - 3*y - 5) # solves equation 2*x - 3*y - 5 == 0 (3*t_0 - 5, 2*t_0 - 5) Here x = -3*t_0 - 5 and y = -2*t_0 - 5 >>> diop_linear(2*x - 3*y - 4*z -3) (t_0, 2*t_0 + 4*t_1 + 3, -t_0 - 3*t_1 - 3) See Also ======== diop_quadratic(), diop_ternary_quadratic(), diop_general_pythagorean(), diop_general_sum_of_squares() """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == Linear.name: result = _diop_linear(var, coeff, param) if param is None: result = result(*[0]*len(result.parameters)) if len(result) > 0: return list(result)[0] else: return tuple([None] * len(result.parameters)) def _diop_linear(var, coeff, param): """ Solves diophantine equations of the form: a_0*x_0 + a_1*x_1 + ... + a_n*x_n == c Note that no solution exists if gcd(a_0, ..., a_n) doesn't divide c. """ if 1 in coeff: # negate coeff[] because input is of the form: ax + by + c == 0 # but is used as: ax + by == -c c = -coeff[1] else: c = 0 # Some solutions will have multiple free variables in their solutions. if param is None: params = [symbols('t')]*len(var) else: temp = str(param) + "_%i" params = [symbols(temp % i, integer=True) for i in range(len(var))] result = DiophantineSolutionSet(var, params) if len(var) == 1: q, r = divmod(c, coeff[var[0]]) if not r: result.add((q,)) return result else: return result ''' base_solution_linear() can solve diophantine equations of the form: a*x + b*y == c We break down multivariate linear diophantine equations into a series of bivariate linear diophantine equations which can then be solved individually by base_solution_linear(). Consider the following: a_0*x_0 + a_1*x_1 + a_2*x_2 == c which can be re-written as: a_0*x_0 + g_0*y_0 == c where g_0 == gcd(a_1, a_2) and y == (a_1*x_1)/g_0 + (a_2*x_2)/g_0 This leaves us with two binary linear diophantine equations. For the first equation: a == a_0 b == g_0 c == c For the second: a == a_1/g_0 b == a_2/g_0 c == the solution we find for y_0 in the first equation. The arrays A and B are the arrays of integers used for 'a' and 'b' in each of the n-1 bivariate equations we solve. ''' A = [coeff[v] for v in var] B = [] if len(var) > 2: B.append(igcd(A[-2], A[-1])) A[-2] = A[-2] // B[0] A[-1] = A[-1] // B[0] for i in range(len(A) - 3, 0, -1): gcd = igcd(B[0], A[i]) B[0] = B[0] // gcd A[i] = A[i] // gcd B.insert(0, gcd) B.append(A[-1]) ''' Consider the trivariate linear equation: 4*x_0 + 6*x_1 + 3*x_2 == 2 This can be re-written as: 4*x_0 + 3*y_0 == 2 where y_0 == 2*x_1 + x_2 (Note that gcd(3, 6) == 3) The complete integral solution to this equation is: x_0 == 2 + 3*t_0 y_0 == -2 - 4*t_0 where 't_0' is any integer. Now that we have a solution for 'x_0', find 'x_1' and 'x_2': 2*x_1 + x_2 == -2 - 4*t_0 We can then solve for '-2' and '-4' independently, and combine the results: 2*x_1a + x_2a == -2 x_1a == 0 + t_0 x_2a == -2 - 2*t_0 2*x_1b + x_2b == -4*t_0 x_1b == 0*t_0 + t_1 x_2b == -4*t_0 - 2*t_1 ==> x_1 == t_0 + t_1 x_2 == -2 - 6*t_0 - 2*t_1 where 't_0' and 't_1' are any integers. Note that: 4*(2 + 3*t_0) + 6*(t_0 + t_1) + 3*(-2 - 6*t_0 - 2*t_1) == 2 for any integral values of 't_0', 't_1'; as required. This method is generalised for many variables, below. ''' solutions = [] for i in range(len(B)): tot_x, tot_y = [], [] for j, arg in enumerate(Add.make_args(c)): if arg.is_Integer: # example: 5 -> k = 5 k, p = arg, S.One pnew = params[0] else: # arg is a Mul or Symbol # example: 3*t_1 -> k = 3 # example: t_0 -> k = 1 k, p = arg.as_coeff_Mul() pnew = params[params.index(p) + 1] sol = sol_x, sol_y = base_solution_linear(k, A[i], B[i], pnew) if p is S.One: if None in sol: return result else: # convert a + b*pnew -> a*p + b*pnew if isinstance(sol_x, Add): sol_x = sol_x.args[0]*p + sol_x.args[1] if isinstance(sol_y, Add): sol_y = sol_y.args[0]*p + sol_y.args[1] tot_x.append(sol_x) tot_y.append(sol_y) solutions.append(Add(*tot_x)) c = Add(*tot_y) solutions.append(c) if param is None: # just keep the additive constant (i.e. replace t with 0) solutions = [i.as_coeff_Add()[0] for i in solutions] result.add(solutions) return result def base_solution_linear(c, a, b, t=None): """ Return the base solution for the linear equation, `ax + by = c`. Used by ``diop_linear()`` to find the base solution of a linear Diophantine equation. If ``t`` is given then the parametrized solution is returned. Usage ===== ``base_solution_linear(c, a, b, t)``: ``a``, ``b``, ``c`` are coefficients in `ax + by = c` and ``t`` is the parameter to be used in the solution. Examples ======== >>> from sympy.solvers.diophantine.diophantine import base_solution_linear >>> from sympy.abc import t >>> base_solution_linear(5, 2, 3) # equation 2*x + 3*y = 5 (-5, 5) >>> base_solution_linear(0, 5, 7) # equation 5*x + 7*y = 0 (0, 0) >>> base_solution_linear(5, 2, 3, t) # equation 2*x + 3*y = 5 (3*t - 5, 5 - 2*t) >>> base_solution_linear(0, 5, 7, t) # equation 5*x + 7*y = 0 (7*t, -5*t) """ a, b, c = _remove_gcd(a, b, c) if c == 0: if t is not None: if b < 0: t = -t return (b*t , -a*t) else: return (0, 0) else: x0, y0, d = igcdex(abs(a), abs(b)) x0 *= sign(a) y0 *= sign(b) if divisible(c, d): if t is not None: if b < 0: t = -t return (c*x0 + b*t, c*y0 - a*t) else: return (c*x0, c*y0) else: return (None, None) def diop_univariate(eq): """ Solves a univariate diophantine equations. A univariate diophantine equation is an equation of the form `a_{0} + a_{1}x + a_{2}x^2 + .. + a_{n}x^n = 0` where `a_{1}, a_{2}, ..a_{n}` are integer constants and `x` is an integer variable. Usage ===== ``diop_univariate(eq)``: Returns a set containing solutions to the diophantine equation ``eq``. Details ======= ``eq`` is a univariate diophantine equation which is assumed to be zero. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_univariate >>> from sympy.abc import x >>> diop_univariate((x - 2)*(x - 3)**2) # solves equation (x - 2)*(x - 3)**2 == 0 {(2,), (3,)} """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == Univariate.name: return set([(int(i),) for i in solveset_real( eq, var[0]).intersect(S.Integers)]) def divisible(a, b): """ Returns `True` if ``a`` is divisible by ``b`` and `False` otherwise. """ return not a % b def diop_quadratic(eq, param=symbols("t", integer=True)): """ Solves quadratic diophantine equations. i.e. equations of the form `Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0`. Returns a set containing the tuples `(x, y)` which contains the solutions. If there are no solutions then `(None, None)` is returned. Usage ===== ``diop_quadratic(eq, param)``: ``eq`` is a quadratic binary diophantine equation. ``param`` is used to indicate the parameter to be used in the solution. Details ======= ``eq`` should be an expression which is assumed to be zero. ``param`` is a parameter to be used in the solution. Examples ======== >>> from sympy.abc import x, y, t >>> from sympy.solvers.diophantine.diophantine import diop_quadratic >>> diop_quadratic(x**2 + y**2 + 2*x + 2*y + 2, t) {(-1, -1)} References ========== .. [1] Methods to solve Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0, [online], Available: http://www.alpertron.com.ar/METHODS.HTM .. [2] Solving the equation ax^2+ bxy + cy^2 + dx + ey + f= 0, [online], Available: http://www.jpr2718.org/ax2p.pdf See Also ======== diop_linear(), diop_ternary_quadratic(), diop_general_sum_of_squares(), diop_general_pythagorean() """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == BinaryQuadratic.name: return set(_diop_quadratic(var, coeff, param)) def _diop_quadratic(var, coeff, t): u = Symbol('u', integer=True) x, y = var A = coeff[x**2] B = coeff[x*y] C = coeff[y**2] D = coeff[x] E = coeff[y] F = coeff[S.One] A, B, C, D, E, F = [as_int(i) for i in _remove_gcd(A, B, C, D, E, F)] # (1) Simple-Hyperbolic case: A = C = 0, B != 0 # In this case equation can be converted to (Bx + E)(By + D) = DE - BF # We consider two cases; DE - BF = 0 and DE - BF != 0 # More details, http://www.alpertron.com.ar/METHODS.HTM#SHyperb result = DiophantineSolutionSet(var, [t, u]) discr = B**2 - 4*A*C if A == 0 and C == 0 and B != 0: if D*E - B*F == 0: q, r = divmod(E, B) if not r: result.add((-q, t)) q, r = divmod(D, B) if not r: result.add((t, -q)) else: div = divisors(D*E - B*F) div = div + [-term for term in div] for d in div: x0, r = divmod(d - E, B) if not r: q, r = divmod(D*E - B*F, d) if not r: y0, r = divmod(q - D, B) if not r: result.add((x0, y0)) # (2) Parabolic case: B**2 - 4*A*C = 0 # There are two subcases to be considered in this case. # sqrt(c)D - sqrt(a)E = 0 and sqrt(c)D - sqrt(a)E != 0 # More Details, http://www.alpertron.com.ar/METHODS.HTM#Parabol elif discr == 0: if A == 0: s = _diop_quadratic([y, x], coeff, t) for soln in s: result.add((soln[1], soln[0])) else: g = sign(A)*igcd(A, C) a = A // g c = C // g e = sign(B/A) sqa = isqrt(a) sqc = isqrt(c) _c = e*sqc*D - sqa*E if not _c: z = symbols("z", real=True) eq = sqa*g*z**2 + D*z + sqa*F roots = solveset_real(eq, z).intersect(S.Integers) for root in roots: ans = diop_solve(sqa*x + e*sqc*y - root) result.add((ans[0], ans[1])) elif _is_int(c): solve_x = lambda u: -e*sqc*g*_c*t**2 - (E + 2*e*sqc*g*u)*t\ - (e*sqc*g*u**2 + E*u + e*sqc*F) // _c solve_y = lambda u: sqa*g*_c*t**2 + (D + 2*sqa*g*u)*t \ + (sqa*g*u**2 + D*u + sqa*F) // _c for z0 in range(0, abs(_c)): # Check if the coefficients of y and x obtained are integers or not if (divisible(sqa*g*z0**2 + D*z0 + sqa*F, _c) and divisible(e*sqc*g*z0**2 + E*z0 + e*sqc*F, _c)): result.add((solve_x(z0), solve_y(z0))) # (3) Method used when B**2 - 4*A*C is a square, is described in p. 6 of the below paper # by John P. Robertson. # http://www.jpr2718.org/ax2p.pdf elif is_square(discr): if A != 0: r = sqrt(discr) u, v = symbols("u, v", integer=True) eq = _mexpand( 4*A*r*u*v + 4*A*D*(B*v + r*u + r*v - B*u) + 2*A*4*A*E*(u - v) + 4*A*r*4*A*F) solution = diop_solve(eq, t) for s0, t0 in solution: num = B*t0 + r*s0 + r*t0 - B*s0 x_0 = S(num)/(4*A*r) y_0 = S(s0 - t0)/(2*r) if isinstance(s0, Symbol) or isinstance(t0, Symbol): if check_param(x_0, y_0, 4*A*r, t) != (None, None): ans = check_param(x_0, y_0, 4*A*r, t) result.add((ans[0], ans[1])) elif x_0.is_Integer and y_0.is_Integer: if is_solution_quad(var, coeff, x_0, y_0): result.add((x_0, y_0)) else: s = _diop_quadratic(var[::-1], coeff, t) # Interchange x and y while s: result.add(s.pop()[::-1]) # and solution <--------+ # (4) B**2 - 4*A*C > 0 and B**2 - 4*A*C not a square or B**2 - 4*A*C < 0 else: P, Q = _transformation_to_DN(var, coeff) D, N = _find_DN(var, coeff) solns_pell = diop_DN(D, N) if D < 0: for x0, y0 in solns_pell: for x in [-x0, x0]: for y in [-y0, y0]: s = P*Matrix([x, y]) + Q try: result.add([as_int(_) for _ in s]) except ValueError: pass else: # In this case equation can be transformed into a Pell equation solns_pell = set(solns_pell) for X, Y in list(solns_pell): solns_pell.add((-X, -Y)) a = diop_DN(D, 1) T = a[0][0] U = a[0][1] if all(_is_int(_) for _ in P[:4] + Q[:2]): for r, s in solns_pell: _a = (r + s*sqrt(D))*(T + U*sqrt(D))**t _b = (r - s*sqrt(D))*(T - U*sqrt(D))**t x_n = _mexpand(S(_a + _b)/2) y_n = _mexpand(S(_a - _b)/(2*sqrt(D))) s = P*Matrix([x_n, y_n]) + Q result.add(s) else: L = ilcm(*[_.q for _ in P[:4] + Q[:2]]) k = 1 T_k = T U_k = U while (T_k - 1) % L != 0 or U_k % L != 0: T_k, U_k = T_k*T + D*U_k*U, T_k*U + U_k*T k += 1 for X, Y in solns_pell: for i in range(k): if all(_is_int(_) for _ in P*Matrix([X, Y]) + Q): _a = (X + sqrt(D)*Y)*(T_k + sqrt(D)*U_k)**t _b = (X - sqrt(D)*Y)*(T_k - sqrt(D)*U_k)**t Xt = S(_a + _b)/2 Yt = S(_a - _b)/(2*sqrt(D)) s = P*Matrix([Xt, Yt]) + Q result.add(s) X, Y = X*T + D*U*Y, X*U + Y*T return result def is_solution_quad(var, coeff, u, v): """ Check whether `(u, v)` is solution to the quadratic binary diophantine equation with the variable list ``var`` and coefficient dictionary ``coeff``. Not intended for use by normal users. """ reps = dict(zip(var, (u, v))) eq = Add(*[j*i.xreplace(reps) for i, j in coeff.items()]) return _mexpand(eq) == 0 def diop_DN(D, N, t=symbols("t", integer=True)): """ Solves the equation `x^2 - Dy^2 = N`. Mainly concerned with the case `D > 0, D` is not a perfect square, which is the same as the generalized Pell equation. The LMM algorithm [1]_ is used to solve this equation. Returns one solution tuple, (`x, y)` for each class of the solutions. Other solutions of the class can be constructed according to the values of ``D`` and ``N``. Usage ===== ``diop_DN(D, N, t)``: D and N are integers as in `x^2 - Dy^2 = N` and ``t`` is the parameter to be used in the solutions. Details ======= ``D`` and ``N`` correspond to D and N in the equation. ``t`` is the parameter to be used in the solutions. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_DN >>> diop_DN(13, -4) # Solves equation x**2 - 13*y**2 = -4 [(3, 1), (393, 109), (36, 10)] The output can be interpreted as follows: There are three fundamental solutions to the equation `x^2 - 13y^2 = -4` given by (3, 1), (393, 109) and (36, 10). Each tuple is in the form (x, y), i.e. solution (3, 1) means that `x = 3` and `y = 1`. >>> diop_DN(986, 1) # Solves equation x**2 - 986*y**2 = 1 [(49299, 1570)] See Also ======== find_DN(), diop_bf_DN() References ========== .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004, Pages 16 - 17. [online], Available: http://www.jpr2718.org/pell.pdf """ if D < 0: if N == 0: return [(0, 0)] elif N < 0: return [] elif N > 0: sol = [] for d in divisors(square_factor(N)): sols = cornacchia(1, -D, N // d**2) if sols: for x, y in sols: sol.append((d*x, d*y)) if D == -1: sol.append((d*y, d*x)) return sol elif D == 0: if N < 0: return [] if N == 0: return [(0, t)] sN, _exact = integer_nthroot(N, 2) if _exact: return [(sN, t)] else: return [] else: # D > 0 sD, _exact = integer_nthroot(D, 2) if _exact: if N == 0: return [(sD*t, t)] else: sol = [] for y in range(floor(sign(N)*(N - 1)/(2*sD)) + 1): try: sq, _exact = integer_nthroot(D*y**2 + N, 2) except ValueError: _exact = False if _exact: sol.append((sq, y)) return sol elif 1 < N**2 < D: # It is much faster to call `_special_diop_DN`. return _special_diop_DN(D, N) else: if N == 0: return [(0, 0)] elif abs(N) == 1: pqa = PQa(0, 1, D) j = 0 G = [] B = [] for i in pqa: a = i[2] G.append(i[5]) B.append(i[4]) if j != 0 and a == 2*sD: break j = j + 1 if _odd(j): if N == -1: x = G[j - 1] y = B[j - 1] else: count = j while count < 2*j - 1: i = next(pqa) G.append(i[5]) B.append(i[4]) count += 1 x = G[count] y = B[count] else: if N == 1: x = G[j - 1] y = B[j - 1] else: return [] return [(x, y)] else: fs = [] sol = [] div = divisors(N) for d in div: if divisible(N, d**2): fs.append(d) for f in fs: m = N // f**2 zs = sqrt_mod(D, abs(m), all_roots=True) zs = [i for i in zs if i <= abs(m) // 2 ] if abs(m) != 2: zs = zs + [-i for i in zs if i] # omit dupl 0 for z in zs: pqa = PQa(z, abs(m), D) j = 0 G = [] B = [] for i in pqa: G.append(i[5]) B.append(i[4]) if j != 0 and abs(i[1]) == 1: r = G[j-1] s = B[j-1] if r**2 - D*s**2 == m: sol.append((f*r, f*s)) elif diop_DN(D, -1) != []: a = diop_DN(D, -1) sol.append((f*(r*a[0][0] + a[0][1]*s*D), f*(r*a[0][1] + s*a[0][0]))) break j = j + 1 if j == length(z, abs(m), D): break return sol def _special_diop_DN(D, N): """ Solves the equation `x^2 - Dy^2 = N` for the special case where `1 < N**2 < D` and `D` is not a perfect square. It is better to call `diop_DN` rather than this function, as the former checks the condition `1 < N**2 < D`, and calls the latter only if appropriate. Usage ===== WARNING: Internal method. Do not call directly! ``_special_diop_DN(D, N)``: D and N are integers as in `x^2 - Dy^2 = N`. Details ======= ``D`` and ``N`` correspond to D and N in the equation. Examples ======== >>> from sympy.solvers.diophantine.diophantine import _special_diop_DN >>> _special_diop_DN(13, -3) # Solves equation x**2 - 13*y**2 = -3 [(7, 2), (137, 38)] The output can be interpreted as follows: There are two fundamental solutions to the equation `x^2 - 13y^2 = -3` given by (7, 2) and (137, 38). Each tuple is in the form (x, y), i.e. solution (7, 2) means that `x = 7` and `y = 2`. >>> _special_diop_DN(2445, -20) # Solves equation x**2 - 2445*y**2 = -20 [(445, 9), (17625560, 356454), (698095554475, 14118073569)] See Also ======== diop_DN() References ========== .. [1] Section 4.4.4 of the following book: Quadratic Diophantine Equations, T. Andreescu and D. Andrica, Springer, 2015. """ # The following assertion was removed for efficiency, with the understanding # that this method is not called directly. The parent method, `diop_DN` # is responsible for performing the appropriate checks. # # assert (1 < N**2 < D) and (not integer_nthroot(D, 2)[1]) sqrt_D = sqrt(D) F = [(N, 1)] f = 2 while True: f2 = f**2 if f2 > abs(N): break n, r = divmod(N, f2) if r == 0: F.append((n, f)) f += 1 P = 0 Q = 1 G0, G1 = 0, 1 B0, B1 = 1, 0 solutions = [] i = 0 while True: a = floor((P + sqrt_D) / Q) P = a*Q - P Q = (D - P**2) // Q G2 = a*G1 + G0 B2 = a*B1 + B0 for n, f in F: if G2**2 - D*B2**2 == n: solutions.append((f*G2, f*B2)) i += 1 if Q == 1 and i % 2 == 0: break G0, G1 = G1, G2 B0, B1 = B1, B2 return solutions def cornacchia(a, b, m): r""" Solves `ax^2 + by^2 = m` where `\gcd(a, b) = 1 = gcd(a, m)` and `a, b > 0`. Uses the algorithm due to Cornacchia. The method only finds primitive solutions, i.e. ones with `\gcd(x, y) = 1`. So this method can't be used to find the solutions of `x^2 + y^2 = 20` since the only solution to former is `(x, y) = (4, 2)` and it is not primitive. When `a = b`, only the solutions with `x \leq y` are found. For more details, see the References. Examples ======== >>> from sympy.solvers.diophantine.diophantine import cornacchia >>> cornacchia(2, 3, 35) # equation 2x**2 + 3y**2 = 35 {(2, 3), (4, 1)} >>> cornacchia(1, 1, 25) # equation x**2 + y**2 = 25 {(4, 3)} References =========== .. [1] A. Nitaj, "L'algorithme de Cornacchia" .. [2] Solving the diophantine equation ax**2 + by**2 = m by Cornacchia's method, [online], Available: http://www.numbertheory.org/php/cornacchia.html See Also ======== sympy.utilities.iterables.signed_permutations """ sols = set() a1 = igcdex(a, m)[0] v = sqrt_mod(-b*a1, m, all_roots=True) if not v: return None for t in v: if t < m // 2: continue u, r = t, m while True: u, r = r, u % r if a*r**2 < m: break m1 = m - a*r**2 if m1 % b == 0: m1 = m1 // b s, _exact = integer_nthroot(m1, 2) if _exact: if a == b and r < s: r, s = s, r sols.add((int(r), int(s))) return sols def PQa(P_0, Q_0, D): r""" Returns useful information needed to solve the Pell equation. There are six sequences of integers defined related to the continued fraction representation of `\\frac{P + \sqrt{D}}{Q}`, namely {`P_{i}`}, {`Q_{i}`}, {`a_{i}`},{`A_{i}`}, {`B_{i}`}, {`G_{i}`}. ``PQa()`` Returns these values as a 6-tuple in the same order as mentioned above. Refer [1]_ for more detailed information. Usage ===== ``PQa(P_0, Q_0, D)``: ``P_0``, ``Q_0`` and ``D`` are integers corresponding to `P_{0}`, `Q_{0}` and `D` in the continued fraction `\\frac{P_{0} + \sqrt{D}}{Q_{0}}`. Also it's assumed that `P_{0}^2 == D mod(|Q_{0}|)` and `D` is square free. Examples ======== >>> from sympy.solvers.diophantine.diophantine import PQa >>> pqa = PQa(13, 4, 5) # (13 + sqrt(5))/4 >>> next(pqa) # (P_0, Q_0, a_0, A_0, B_0, G_0) (13, 4, 3, 3, 1, -1) >>> next(pqa) # (P_1, Q_1, a_1, A_1, B_1, G_1) (-1, 1, 1, 4, 1, 3) References ========== .. [1] Solving the generalized Pell equation x^2 - Dy^2 = N, John P. Robertson, July 31, 2004, Pages 4 - 8. http://www.jpr2718.org/pell.pdf """ A_i_2 = B_i_1 = 0 A_i_1 = B_i_2 = 1 G_i_2 = -P_0 G_i_1 = Q_0 P_i = P_0 Q_i = Q_0 while True: a_i = floor((P_i + sqrt(D))/Q_i) A_i = a_i*A_i_1 + A_i_2 B_i = a_i*B_i_1 + B_i_2 G_i = a_i*G_i_1 + G_i_2 yield P_i, Q_i, a_i, A_i, B_i, G_i A_i_1, A_i_2 = A_i, A_i_1 B_i_1, B_i_2 = B_i, B_i_1 G_i_1, G_i_2 = G_i, G_i_1 P_i = a_i*Q_i - P_i Q_i = (D - P_i**2)/Q_i def diop_bf_DN(D, N, t=symbols("t", integer=True)): r""" Uses brute force to solve the equation, `x^2 - Dy^2 = N`. Mainly concerned with the generalized Pell equation which is the case when `D > 0, D` is not a perfect square. For more information on the case refer [1]_. Let `(t, u)` be the minimal positive solution of the equation `x^2 - Dy^2 = 1`. Then this method requires `\sqrt{\\frac{\mid N \mid (t \pm 1)}{2D}}` to be small. Usage ===== ``diop_bf_DN(D, N, t)``: ``D`` and ``N`` are coefficients in `x^2 - Dy^2 = N` and ``t`` is the parameter to be used in the solutions. Details ======= ``D`` and ``N`` correspond to D and N in the equation. ``t`` is the parameter to be used in the solutions. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_bf_DN >>> diop_bf_DN(13, -4) [(3, 1), (-3, 1), (36, 10)] >>> diop_bf_DN(986, 1) [(49299, 1570)] See Also ======== diop_DN() References ========== .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004, Page 15. http://www.jpr2718.org/pell.pdf """ D = as_int(D) N = as_int(N) sol = [] a = diop_DN(D, 1) u = a[0][0] if abs(N) == 1: return diop_DN(D, N) elif N > 1: L1 = 0 L2 = integer_nthroot(int(N*(u - 1)/(2*D)), 2)[0] + 1 elif N < -1: L1, _exact = integer_nthroot(-int(N/D), 2) if not _exact: L1 += 1 L2 = integer_nthroot(-int(N*(u + 1)/(2*D)), 2)[0] + 1 else: # N = 0 if D < 0: return [(0, 0)] elif D == 0: return [(0, t)] else: sD, _exact = integer_nthroot(D, 2) if _exact: return [(sD*t, t), (-sD*t, t)] else: return [(0, 0)] for y in range(L1, L2): try: x, _exact = integer_nthroot(N + D*y**2, 2) except ValueError: _exact = False if _exact: sol.append((x, y)) if not equivalent(x, y, -x, y, D, N): sol.append((-x, y)) return sol def equivalent(u, v, r, s, D, N): """ Returns True if two solutions `(u, v)` and `(r, s)` of `x^2 - Dy^2 = N` belongs to the same equivalence class and False otherwise. Two solutions `(u, v)` and `(r, s)` to the above equation fall to the same equivalence class iff both `(ur - Dvs)` and `(us - vr)` are divisible by `N`. See reference [1]_. No test is performed to test whether `(u, v)` and `(r, s)` are actually solutions to the equation. User should take care of this. Usage ===== ``equivalent(u, v, r, s, D, N)``: `(u, v)` and `(r, s)` are two solutions of the equation `x^2 - Dy^2 = N` and all parameters involved are integers. Examples ======== >>> from sympy.solvers.diophantine.diophantine import equivalent >>> equivalent(18, 5, -18, -5, 13, -1) True >>> equivalent(3, 1, -18, 393, 109, -4) False References ========== .. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004, Page 12. http://www.jpr2718.org/pell.pdf """ return divisible(u*r - D*v*s, N) and divisible(u*s - v*r, N) def length(P, Q, D): r""" Returns the (length of aperiodic part + length of periodic part) of continued fraction representation of `\\frac{P + \sqrt{D}}{Q}`. It is important to remember that this does NOT return the length of the periodic part but the sum of the lengths of the two parts as mentioned above. Usage ===== ``length(P, Q, D)``: ``P``, ``Q`` and ``D`` are integers corresponding to the continued fraction `\\frac{P + \sqrt{D}}{Q}`. Details ======= ``P``, ``D`` and ``Q`` corresponds to P, D and Q in the continued fraction, `\\frac{P + \sqrt{D}}{Q}`. Examples ======== >>> from sympy.solvers.diophantine.diophantine import length >>> length(-2 , 4, 5) # (-2 + sqrt(5))/4 3 >>> length(-5, 4, 17) # (-5 + sqrt(17))/4 4 See Also ======== sympy.ntheory.continued_fraction.continued_fraction_periodic """ from sympy.ntheory.continued_fraction import continued_fraction_periodic v = continued_fraction_periodic(P, Q, D) if type(v[-1]) is list: rpt = len(v[-1]) nonrpt = len(v) - 1 else: rpt = 0 nonrpt = len(v) return rpt + nonrpt def transformation_to_DN(eq): """ This function transforms general quadratic, `ax^2 + bxy + cy^2 + dx + ey + f = 0` to more easy to deal with `X^2 - DY^2 = N` form. This is used to solve the general quadratic equation by transforming it to the latter form. Refer [1]_ for more detailed information on the transformation. This function returns a tuple (A, B) where A is a 2 X 2 matrix and B is a 2 X 1 matrix such that, Transpose([x y]) = A * Transpose([X Y]) + B Usage ===== ``transformation_to_DN(eq)``: where ``eq`` is the quadratic to be transformed. Examples ======== >>> from sympy.abc import x, y >>> from sympy.solvers.diophantine.diophantine import transformation_to_DN >>> A, B = transformation_to_DN(x**2 - 3*x*y - y**2 - 2*y + 1) >>> A Matrix([ [1/26, 3/26], [ 0, 1/13]]) >>> B Matrix([ [-6/13], [-4/13]]) A, B returned are such that Transpose((x y)) = A * Transpose((X Y)) + B. Substituting these values for `x` and `y` and a bit of simplifying work will give an equation of the form `x^2 - Dy^2 = N`. >>> from sympy.abc import X, Y >>> from sympy import Matrix, simplify >>> u = (A*Matrix([X, Y]) + B)[0] # Transformation for x >>> u X/26 + 3*Y/26 - 6/13 >>> v = (A*Matrix([X, Y]) + B)[1] # Transformation for y >>> v Y/13 - 4/13 Next we will substitute these formulas for `x` and `y` and do ``simplify()``. >>> eq = simplify((x**2 - 3*x*y - y**2 - 2*y + 1).subs(zip((x, y), (u, v)))) >>> eq X**2/676 - Y**2/52 + 17/13 By multiplying the denominator appropriately, we can get a Pell equation in the standard form. >>> eq * 676 X**2 - 13*Y**2 + 884 If only the final equation is needed, ``find_DN()`` can be used. See Also ======== find_DN() References ========== .. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0, John P.Robertson, May 8, 2003, Page 7 - 11. http://www.jpr2718.org/ax2p.pdf """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == BinaryQuadratic.name: return _transformation_to_DN(var, coeff) def _transformation_to_DN(var, coeff): x, y = var a = coeff[x**2] b = coeff[x*y] c = coeff[y**2] d = coeff[x] e = coeff[y] f = coeff[1] a, b, c, d, e, f = [as_int(i) for i in _remove_gcd(a, b, c, d, e, f)] X, Y = symbols("X, Y", integer=True) if b: B, C = _rational_pq(2*a, b) A, T = _rational_pq(a, B**2) # eq_1 = A*B*X**2 + B*(c*T - A*C**2)*Y**2 + d*T*X + (B*e*T - d*T*C)*Y + f*T*B coeff = {X**2: A*B, X*Y: 0, Y**2: B*(c*T - A*C**2), X: d*T, Y: B*e*T - d*T*C, 1: f*T*B} A_0, B_0 = _transformation_to_DN([X, Y], coeff) return Matrix(2, 2, [S.One/B, -S(C)/B, 0, 1])*A_0, Matrix(2, 2, [S.One/B, -S(C)/B, 0, 1])*B_0 else: if d: B, C = _rational_pq(2*a, d) A, T = _rational_pq(a, B**2) # eq_2 = A*X**2 + c*T*Y**2 + e*T*Y + f*T - A*C**2 coeff = {X**2: A, X*Y: 0, Y**2: c*T, X: 0, Y: e*T, 1: f*T - A*C**2} A_0, B_0 = _transformation_to_DN([X, Y], coeff) return Matrix(2, 2, [S.One/B, 0, 0, 1])*A_0, Matrix(2, 2, [S.One/B, 0, 0, 1])*B_0 + Matrix([-S(C)/B, 0]) else: if e: B, C = _rational_pq(2*c, e) A, T = _rational_pq(c, B**2) # eq_3 = a*T*X**2 + A*Y**2 + f*T - A*C**2 coeff = {X**2: a*T, X*Y: 0, Y**2: A, X: 0, Y: 0, 1: f*T - A*C**2} A_0, B_0 = _transformation_to_DN([X, Y], coeff) return Matrix(2, 2, [1, 0, 0, S.One/B])*A_0, Matrix(2, 2, [1, 0, 0, S.One/B])*B_0 + Matrix([0, -S(C)/B]) else: # TODO: pre-simplification: Not necessary but may simplify # the equation. return Matrix(2, 2, [S.One/a, 0, 0, 1]), Matrix([0, 0]) def find_DN(eq): """ This function returns a tuple, `(D, N)` of the simplified form, `x^2 - Dy^2 = N`, corresponding to the general quadratic, `ax^2 + bxy + cy^2 + dx + ey + f = 0`. Solving the general quadratic is then equivalent to solving the equation `X^2 - DY^2 = N` and transforming the solutions by using the transformation matrices returned by ``transformation_to_DN()``. Usage ===== ``find_DN(eq)``: where ``eq`` is the quadratic to be transformed. Examples ======== >>> from sympy.abc import x, y >>> from sympy.solvers.diophantine.diophantine import find_DN >>> find_DN(x**2 - 3*x*y - y**2 - 2*y + 1) (13, -884) Interpretation of the output is that we get `X^2 -13Y^2 = -884` after transforming `x^2 - 3xy - y^2 - 2y + 1` using the transformation returned by ``transformation_to_DN()``. See Also ======== transformation_to_DN() References ========== .. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0, John P.Robertson, May 8, 2003, Page 7 - 11. http://www.jpr2718.org/ax2p.pdf """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == BinaryQuadratic.name: return _find_DN(var, coeff) def _find_DN(var, coeff): x, y = var X, Y = symbols("X, Y", integer=True) A, B = _transformation_to_DN(var, coeff) u = (A*Matrix([X, Y]) + B)[0] v = (A*Matrix([X, Y]) + B)[1] eq = x**2*coeff[x**2] + x*y*coeff[x*y] + y**2*coeff[y**2] + x*coeff[x] + y*coeff[y] + coeff[1] simplified = _mexpand(eq.subs(zip((x, y), (u, v)))) coeff = simplified.as_coefficients_dict() return -coeff[Y**2]/coeff[X**2], -coeff[1]/coeff[X**2] def check_param(x, y, a, t): """ If there is a number modulo ``a`` such that ``x`` and ``y`` are both integers, then return a parametric representation for ``x`` and ``y`` else return (None, None). Here ``x`` and ``y`` are functions of ``t``. """ from sympy.simplify.simplify import clear_coefficients if x.is_number and not x.is_Integer: return (None, None) if y.is_number and not y.is_Integer: return (None, None) m, n = symbols("m, n", integer=True) c, p = (m*x + n*y).as_content_primitive() if a % c.q: return (None, None) # clear_coefficients(mx + b, R)[1] -> (R - b)/m eq = clear_coefficients(x, m)[1] - clear_coefficients(y, n)[1] junk, eq = eq.as_content_primitive() return diop_solve(eq, t) def diop_ternary_quadratic(eq, parameterize=False): """ Solves the general quadratic ternary form, `ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`. Returns a tuple `(x, y, z)` which is a base solution for the above equation. If there are no solutions, `(None, None, None)` is returned. Usage ===== ``diop_ternary_quadratic(eq)``: Return a tuple containing a basic solution to ``eq``. Details ======= ``eq`` should be an homogeneous expression of degree two in three variables and it is assumed to be zero. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.solvers.diophantine.diophantine import diop_ternary_quadratic >>> diop_ternary_quadratic(x**2 + 3*y**2 - z**2) (1, 0, 1) >>> diop_ternary_quadratic(4*x**2 + 5*y**2 - z**2) (1, 0, 2) >>> diop_ternary_quadratic(45*x**2 - 7*y**2 - 8*x*y - z**2) (28, 45, 105) >>> diop_ternary_quadratic(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y) (9, 1, 5) """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type in ( "homogeneous_ternary_quadratic", "homogeneous_ternary_quadratic_normal"): sol = _diop_ternary_quadratic(var, coeff) if len(sol) > 0: x_0, y_0, z_0 = list(sol)[0] else: x_0, y_0, z_0 = None, None, None if parameterize: return _parametrize_ternary_quadratic( (x_0, y_0, z_0), var, coeff) return x_0, y_0, z_0 def _diop_ternary_quadratic(_var, coeff): x, y, z = _var var = [x, y, z] # Equations of the form B*x*y + C*z*x + E*y*z = 0 and At least two of the # coefficients A, B, C are non-zero. # There are infinitely many solutions for the equation. # Ex: (0, 0, t), (0, t, 0), (t, 0, 0) # Equation can be re-written as y*(B*x + E*z) = -C*x*z and we can find rather # unobvious solutions. Set y = -C and B*x + E*z = x*z. The latter can be solved by # using methods for binary quadratic diophantine equations. Let's select the # solution which minimizes |x| + |z| result = DiophantineSolutionSet(var) def unpack_sol(sol): if len(sol) > 0: return list(sol)[0] return None, None, None if not any(coeff[i**2] for i in var): if coeff[x*z]: sols = diophantine(coeff[x*y]*x + coeff[y*z]*z - x*z) s = sols.pop() min_sum = abs(s[0]) + abs(s[1]) for r in sols: m = abs(r[0]) + abs(r[1]) if m < min_sum: s = r min_sum = m result.add(_remove_gcd(s[0], -coeff[x*z], s[1])) return result else: var[0], var[1] = _var[1], _var[0] y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff)) if x_0 is not None: result.add((x_0, y_0, z_0)) return result if coeff[x**2] == 0: # If the coefficient of x is zero change the variables if coeff[y**2] == 0: var[0], var[2] = _var[2], _var[0] z_0, y_0, x_0 = unpack_sol(_diop_ternary_quadratic(var, coeff)) else: var[0], var[1] = _var[1], _var[0] y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff)) else: if coeff[x*y] or coeff[x*z]: # Apply the transformation x --> X - (B*y + C*z)/(2*A) A = coeff[x**2] B = coeff[x*y] C = coeff[x*z] D = coeff[y**2] E = coeff[y*z] F = coeff[z**2] _coeff = dict() _coeff[x**2] = 4*A**2 _coeff[y**2] = 4*A*D - B**2 _coeff[z**2] = 4*A*F - C**2 _coeff[y*z] = 4*A*E - 2*B*C _coeff[x*y] = 0 _coeff[x*z] = 0 x_0, y_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, _coeff)) if x_0 is None: return result p, q = _rational_pq(B*y_0 + C*z_0, 2*A) x_0, y_0, z_0 = x_0*q - p, y_0*q, z_0*q elif coeff[z*y] != 0: if coeff[y**2] == 0: if coeff[z**2] == 0: # Equations of the form A*x**2 + E*yz = 0. A = coeff[x**2] E = coeff[y*z] b, a = _rational_pq(-E, A) x_0, y_0, z_0 = b, a, b else: # Ax**2 + E*y*z + F*z**2 = 0 var[0], var[2] = _var[2], _var[0] z_0, y_0, x_0 = unpack_sol(_diop_ternary_quadratic(var, coeff)) else: # A*x**2 + D*y**2 + E*y*z + F*z**2 = 0, C may be zero var[0], var[1] = _var[1], _var[0] y_0, x_0, z_0 = unpack_sol(_diop_ternary_quadratic(var, coeff)) else: # Ax**2 + D*y**2 + F*z**2 = 0, C may be zero x_0, y_0, z_0 = unpack_sol(_diop_ternary_quadratic_normal(var, coeff)) if x_0 is None: return result result.add(_remove_gcd(x_0, y_0, z_0)) return result def transformation_to_normal(eq): """ Returns the transformation Matrix that converts a general ternary quadratic equation ``eq`` (`ax^2 + by^2 + cz^2 + dxy + eyz + fxz`) to a form without cross terms: `ax^2 + by^2 + cz^2 = 0`. This is not used in solving ternary quadratics; it is only implemented for the sake of completeness. """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type in ( "homogeneous_ternary_quadratic", "homogeneous_ternary_quadratic_normal"): return _transformation_to_normal(var, coeff) def _transformation_to_normal(var, coeff): _var = list(var) # copy x, y, z = var if not any(coeff[i**2] for i in var): # https://math.stackexchange.com/questions/448051/transform-quadratic-ternary-form-to-normal-form/448065#448065 a = coeff[x*y] b = coeff[y*z] c = coeff[x*z] swap = False if not a: # b can't be 0 or else there aren't 3 vars swap = True a, b = b, a T = Matrix(((1, 1, -b/a), (1, -1, -c/a), (0, 0, 1))) if swap: T.row_swap(0, 1) T.col_swap(0, 1) return T if coeff[x**2] == 0: # If the coefficient of x is zero change the variables if coeff[y**2] == 0: _var[0], _var[2] = var[2], var[0] T = _transformation_to_normal(_var, coeff) T.row_swap(0, 2) T.col_swap(0, 2) return T else: _var[0], _var[1] = var[1], var[0] T = _transformation_to_normal(_var, coeff) T.row_swap(0, 1) T.col_swap(0, 1) return T # Apply the transformation x --> X - (B*Y + C*Z)/(2*A) if coeff[x*y] != 0 or coeff[x*z] != 0: A = coeff[x**2] B = coeff[x*y] C = coeff[x*z] D = coeff[y**2] E = coeff[y*z] F = coeff[z**2] _coeff = dict() _coeff[x**2] = 4*A**2 _coeff[y**2] = 4*A*D - B**2 _coeff[z**2] = 4*A*F - C**2 _coeff[y*z] = 4*A*E - 2*B*C _coeff[x*y] = 0 _coeff[x*z] = 0 T_0 = _transformation_to_normal(_var, _coeff) return Matrix(3, 3, [1, S(-B)/(2*A), S(-C)/(2*A), 0, 1, 0, 0, 0, 1])*T_0 elif coeff[y*z] != 0: if coeff[y**2] == 0: if coeff[z**2] == 0: # Equations of the form A*x**2 + E*yz = 0. # Apply transformation y -> Y + Z ans z -> Y - Z return Matrix(3, 3, [1, 0, 0, 0, 1, 1, 0, 1, -1]) else: # Ax**2 + E*y*z + F*z**2 = 0 _var[0], _var[2] = var[2], var[0] T = _transformation_to_normal(_var, coeff) T.row_swap(0, 2) T.col_swap(0, 2) return T else: # A*x**2 + D*y**2 + E*y*z + F*z**2 = 0, F may be zero _var[0], _var[1] = var[1], var[0] T = _transformation_to_normal(_var, coeff) T.row_swap(0, 1) T.col_swap(0, 1) return T else: return Matrix.eye(3) def parametrize_ternary_quadratic(eq): """ Returns the parametrized general solution for the ternary quadratic equation ``eq`` which has the form `ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`. Examples ======== >>> from sympy import Tuple, ordered >>> from sympy.abc import x, y, z >>> from sympy.solvers.diophantine.diophantine import parametrize_ternary_quadratic The parametrized solution may be returned with three parameters: >>> parametrize_ternary_quadratic(2*x**2 + y**2 - 2*z**2) (p**2 - 2*q**2, -2*p**2 + 4*p*q - 4*p*r - 4*q**2, p**2 - 4*p*q + 2*q**2 - 4*q*r) There might also be only two parameters: >>> parametrize_ternary_quadratic(4*x**2 + 2*y**2 - 3*z**2) (2*p**2 - 3*q**2, -4*p**2 + 12*p*q - 6*q**2, 4*p**2 - 8*p*q + 6*q**2) Notes ===== Consider ``p`` and ``q`` in the previous 2-parameter solution and observe that more than one solution can be represented by a given pair of parameters. If `p` and ``q`` are not coprime, this is trivially true since the common factor will also be a common factor of the solution values. But it may also be true even when ``p`` and ``q`` are coprime: >>> sol = Tuple(*_) >>> p, q = ordered(sol.free_symbols) >>> sol.subs([(p, 3), (q, 2)]) (6, 12, 12) >>> sol.subs([(q, 1), (p, 1)]) (-1, 2, 2) >>> sol.subs([(q, 0), (p, 1)]) (2, -4, 4) >>> sol.subs([(q, 1), (p, 0)]) (-3, -6, 6) Except for sign and a common factor, these are equivalent to the solution of (1, 2, 2). References ========== .. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart, London Mathematical Society Student Texts 41, Cambridge University Press, Cambridge, 1998. """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type in ( "homogeneous_ternary_quadratic", "homogeneous_ternary_quadratic_normal"): x_0, y_0, z_0 = list(_diop_ternary_quadratic(var, coeff))[0] return _parametrize_ternary_quadratic( (x_0, y_0, z_0), var, coeff) def _parametrize_ternary_quadratic(solution, _var, coeff): # called for a*x**2 + b*y**2 + c*z**2 + d*x*y + e*y*z + f*x*z = 0 assert 1 not in coeff x_0, y_0, z_0 = solution v = list(_var) # copy if x_0 is None: return (None, None, None) if solution.count(0) >= 2: # if there are 2 zeros the equation reduces # to k*X**2 == 0 where X is x, y, or z so X must # be zero, too. So there is only the trivial # solution. return (None, None, None) if x_0 == 0: v[0], v[1] = v[1], v[0] y_p, x_p, z_p = _parametrize_ternary_quadratic( (y_0, x_0, z_0), v, coeff) return x_p, y_p, z_p x, y, z = v r, p, q = symbols("r, p, q", integer=True) eq = sum(k*v for k, v in coeff.items()) eq_1 = _mexpand(eq.subs(zip( (x, y, z), (r*x_0, r*y_0 + p, r*z_0 + q)))) A, B = eq_1.as_independent(r, as_Add=True) x = A*x_0 y = (A*y_0 - _mexpand(B/r*p)) z = (A*z_0 - _mexpand(B/r*q)) return _remove_gcd(x, y, z) def diop_ternary_quadratic_normal(eq, parameterize=False): """ Solves the quadratic ternary diophantine equation, `ax^2 + by^2 + cz^2 = 0`. Here the coefficients `a`, `b`, and `c` should be non zero. Otherwise the equation will be a quadratic binary or univariate equation. If solvable, returns a tuple `(x, y, z)` that satisfies the given equation. If the equation does not have integer solutions, `(None, None, None)` is returned. Usage ===== ``diop_ternary_quadratic_normal(eq)``: where ``eq`` is an equation of the form `ax^2 + by^2 + cz^2 = 0`. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.solvers.diophantine.diophantine import diop_ternary_quadratic_normal >>> diop_ternary_quadratic_normal(x**2 + 3*y**2 - z**2) (1, 0, 1) >>> diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2) (1, 0, 2) >>> diop_ternary_quadratic_normal(34*x**2 - 3*y**2 - 301*z**2) (4, 9, 1) """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == HomogeneousTernaryQuadraticNormal.name: sol = _diop_ternary_quadratic_normal(var, coeff) if len(sol) > 0: x_0, y_0, z_0 = list(sol)[0] else: x_0, y_0, z_0 = None, None, None if parameterize: return _parametrize_ternary_quadratic( (x_0, y_0, z_0), var, coeff) return x_0, y_0, z_0 def _diop_ternary_quadratic_normal(var, coeff): x, y, z = var a = coeff[x**2] b = coeff[y**2] c = coeff[z**2] try: assert len([k for k in coeff if coeff[k]]) == 3 assert all(coeff[i**2] for i in var) except AssertionError: raise ValueError(filldedent(''' coeff dict is not consistent with assumption of this routine: coefficients should be those of an expression in the form a*x**2 + b*y**2 + c*z**2 where a*b*c != 0.''')) (sqf_of_a, sqf_of_b, sqf_of_c), (a_1, b_1, c_1), (a_2, b_2, c_2) = \ sqf_normal(a, b, c, steps=True) A = -a_2*c_2 B = -b_2*c_2 result = DiophantineSolutionSet(var) # If following two conditions are satisfied then there are no solutions if A < 0 and B < 0: return result if ( sqrt_mod(-b_2*c_2, a_2) is None or sqrt_mod(-c_2*a_2, b_2) is None or sqrt_mod(-a_2*b_2, c_2) is None): return result z_0, x_0, y_0 = descent(A, B) z_0, q = _rational_pq(z_0, abs(c_2)) x_0 *= q y_0 *= q x_0, y_0, z_0 = _remove_gcd(x_0, y_0, z_0) # Holzer reduction if sign(a) == sign(b): x_0, y_0, z_0 = holzer(x_0, y_0, z_0, abs(a_2), abs(b_2), abs(c_2)) elif sign(a) == sign(c): x_0, z_0, y_0 = holzer(x_0, z_0, y_0, abs(a_2), abs(c_2), abs(b_2)) else: y_0, z_0, x_0 = holzer(y_0, z_0, x_0, abs(b_2), abs(c_2), abs(a_2)) x_0 = reconstruct(b_1, c_1, x_0) y_0 = reconstruct(a_1, c_1, y_0) z_0 = reconstruct(a_1, b_1, z_0) sq_lcm = ilcm(sqf_of_a, sqf_of_b, sqf_of_c) x_0 = abs(x_0*sq_lcm//sqf_of_a) y_0 = abs(y_0*sq_lcm//sqf_of_b) z_0 = abs(z_0*sq_lcm//sqf_of_c) result.add(_remove_gcd(x_0, y_0, z_0)) return result def sqf_normal(a, b, c, steps=False): """ Return `a', b', c'`, the coefficients of the square-free normal form of `ax^2 + by^2 + cz^2 = 0`, where `a', b', c'` are pairwise prime. If `steps` is True then also return three tuples: `sq`, `sqf`, and `(a', b', c')` where `sq` contains the square factors of `a`, `b` and `c` after removing the `gcd(a, b, c)`; `sqf` contains the values of `a`, `b` and `c` after removing both the `gcd(a, b, c)` and the square factors. The solutions for `ax^2 + by^2 + cz^2 = 0` can be recovered from the solutions of `a'x^2 + b'y^2 + c'z^2 = 0`. Examples ======== >>> from sympy.solvers.diophantine.diophantine import sqf_normal >>> sqf_normal(2 * 3**2 * 5, 2 * 5 * 11, 2 * 7**2 * 11) (11, 1, 5) >>> sqf_normal(2 * 3**2 * 5, 2 * 5 * 11, 2 * 7**2 * 11, True) ((3, 1, 7), (5, 55, 11), (11, 1, 5)) References ========== .. [1] Legendre's Theorem, Legrange's Descent, http://public.csusm.edu/aitken_html/notes/legendre.pdf See Also ======== reconstruct() """ ABC = _remove_gcd(a, b, c) sq = tuple(square_factor(i) for i in ABC) sqf = A, B, C = tuple([i//j**2 for i,j in zip(ABC, sq)]) pc = igcd(A, B) A /= pc B /= pc pa = igcd(B, C) B /= pa C /= pa pb = igcd(A, C) A /= pb B /= pb A *= pa B *= pb C *= pc if steps: return (sq, sqf, (A, B, C)) else: return A, B, C def square_factor(a): r""" Returns an integer `c` s.t. `a = c^2k, \ c,k \in Z`. Here `k` is square free. `a` can be given as an integer or a dictionary of factors. Examples ======== >>> from sympy.solvers.diophantine.diophantine import square_factor >>> square_factor(24) 2 >>> square_factor(-36*3) 6 >>> square_factor(1) 1 >>> square_factor({3: 2, 2: 1, -1: 1}) # -18 3 See Also ======== sympy.ntheory.factor_.core """ f = a if isinstance(a, dict) else factorint(a) return Mul(*[p**(e//2) for p, e in f.items()]) def reconstruct(A, B, z): """ Reconstruct the `z` value of an equivalent solution of `ax^2 + by^2 + cz^2` from the `z` value of a solution of the square-free normal form of the equation, `a'*x^2 + b'*y^2 + c'*z^2`, where `a'`, `b'` and `c'` are square free and `gcd(a', b', c') == 1`. """ f = factorint(igcd(A, B)) for p, e in f.items(): if e != 1: raise ValueError('a and b should be square-free') z *= p return z def ldescent(A, B): """ Return a non-trivial solution to `w^2 = Ax^2 + By^2` using Lagrange's method; return None if there is no such solution. . Here, `A \\neq 0` and `B \\neq 0` and `A` and `B` are square free. Output a tuple `(w_0, x_0, y_0)` which is a solution to the above equation. Examples ======== >>> from sympy.solvers.diophantine.diophantine import ldescent >>> ldescent(1, 1) # w^2 = x^2 + y^2 (1, 1, 0) >>> ldescent(4, -7) # w^2 = 4x^2 - 7y^2 (2, -1, 0) This means that `x = -1, y = 0` and `w = 2` is a solution to the equation `w^2 = 4x^2 - 7y^2` >>> ldescent(5, -1) # w^2 = 5x^2 - y^2 (2, 1, -1) References ========== .. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart, London Mathematical Society Student Texts 41, Cambridge University Press, Cambridge, 1998. .. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, [online], Available: http://eprints.nottingham.ac.uk/60/1/kvxefz87.pdf """ if abs(A) > abs(B): w, y, x = ldescent(B, A) return w, x, y if A == 1: return (1, 1, 0) if B == 1: return (1, 0, 1) if B == -1: # and A == -1 return r = sqrt_mod(A, B) Q = (r**2 - A) // B if Q == 0: B_0 = 1 d = 0 else: div = divisors(Q) B_0 = None for i in div: sQ, _exact = integer_nthroot(abs(Q) // i, 2) if _exact: B_0, d = sign(Q)*i, sQ break if B_0 is not None: W, X, Y = ldescent(A, B_0) return _remove_gcd((-A*X + r*W), (r*X - W), Y*(B_0*d)) def descent(A, B): """ Returns a non-trivial solution, (x, y, z), to `x^2 = Ay^2 + Bz^2` using Lagrange's descent method with lattice-reduction. `A` and `B` are assumed to be valid for such a solution to exist. This is faster than the normal Lagrange's descent algorithm because the Gaussian reduction is used. Examples ======== >>> from sympy.solvers.diophantine.diophantine import descent >>> descent(3, 1) # x**2 = 3*y**2 + z**2 (1, 0, 1) `(x, y, z) = (1, 0, 1)` is a solution to the above equation. >>> descent(41, -113) (-16, -3, 1) References ========== .. [1] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, Mathematics of Computation, Volume 00, Number 0. """ if abs(A) > abs(B): x, y, z = descent(B, A) return x, z, y if B == 1: return (1, 0, 1) if A == 1: return (1, 1, 0) if B == -A: return (0, 1, 1) if B == A: x, z, y = descent(-1, A) return (A*y, z, x) w = sqrt_mod(A, B) x_0, z_0 = gaussian_reduce(w, A, B) t = (x_0**2 - A*z_0**2) // B t_2 = square_factor(t) t_1 = t // t_2**2 x_1, z_1, y_1 = descent(A, t_1) return _remove_gcd(x_0*x_1 + A*z_0*z_1, z_0*x_1 + x_0*z_1, t_1*t_2*y_1) def gaussian_reduce(w, a, b): r""" Returns a reduced solution `(x, z)` to the congruence `X^2 - aZ^2 \equiv 0 \ (mod \ b)` so that `x^2 + |a|z^2` is minimal. Details ======= Here ``w`` is a solution of the congruence `x^2 \equiv a \ (mod \ b)` References ========== .. [1] Gaussian lattice Reduction [online]. Available: http://home.ie.cuhk.edu.hk/~wkshum/wordpress/?p=404 .. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, Mathematics of Computation, Volume 00, Number 0. """ u = (0, 1) v = (1, 0) if dot(u, v, w, a, b) < 0: v = (-v[0], -v[1]) if norm(u, w, a, b) < norm(v, w, a, b): u, v = v, u while norm(u, w, a, b) > norm(v, w, a, b): k = dot(u, v, w, a, b) // dot(v, v, w, a, b) u, v = v, (u[0]- k*v[0], u[1]- k*v[1]) u, v = v, u if dot(u, v, w, a, b) < dot(v, v, w, a, b)/2 or norm((u[0]-v[0], u[1]-v[1]), w, a, b) > norm(v, w, a, b): c = v else: c = (u[0] - v[0], u[1] - v[1]) return c[0]*w + b*c[1], c[0] def dot(u, v, w, a, b): r""" Returns a special dot product of the vectors `u = (u_{1}, u_{2})` and `v = (v_{1}, v_{2})` which is defined in order to reduce solution of the congruence equation `X^2 - aZ^2 \equiv 0 \ (mod \ b)`. """ u_1, u_2 = u v_1, v_2 = v return (w*u_1 + b*u_2)*(w*v_1 + b*v_2) + abs(a)*u_1*v_1 def norm(u, w, a, b): r""" Returns the norm of the vector `u = (u_{1}, u_{2})` under the dot product defined by `u \cdot v = (wu_{1} + bu_{2})(w*v_{1} + bv_{2}) + |a|*u_{1}*v_{1}` where `u = (u_{1}, u_{2})` and `v = (v_{1}, v_{2})`. """ u_1, u_2 = u return sqrt(dot((u_1, u_2), (u_1, u_2), w, a, b)) def holzer(x, y, z, a, b, c): r""" Simplify the solution `(x, y, z)` of the equation `ax^2 + by^2 = cz^2` with `a, b, c > 0` and `z^2 \geq \mid ab \mid` to a new reduced solution `(x', y', z')` such that `z'^2 \leq \mid ab \mid`. The algorithm is an interpretation of Mordell's reduction as described on page 8 of Cremona and Rusin's paper [1]_ and the work of Mordell in reference [2]_. References ========== .. [1] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, Mathematics of Computation, Volume 00, Number 0. .. [2] Diophantine Equations, L. J. Mordell, page 48. """ if _odd(c): k = 2*c else: k = c//2 small = a*b*c step = 0 while True: t1, t2, t3 = a*x**2, b*y**2, c*z**2 # check that it's a solution if t1 + t2 != t3: if step == 0: raise ValueError('bad starting solution') break x_0, y_0, z_0 = x, y, z if max(t1, t2, t3) <= small: # Holzer condition break uv = u, v = base_solution_linear(k, y_0, -x_0) if None in uv: break p, q = -(a*u*x_0 + b*v*y_0), c*z_0 r = Rational(p, q) if _even(c): w = _nint_or_floor(p, q) assert abs(w - r) <= S.Half else: w = p//q # floor if _odd(a*u + b*v + c*w): w += 1 assert abs(w - r) <= S.One A = (a*u**2 + b*v**2 + c*w**2) B = (a*u*x_0 + b*v*y_0 + c*w*z_0) x = Rational(x_0*A - 2*u*B, k) y = Rational(y_0*A - 2*v*B, k) z = Rational(z_0*A - 2*w*B, k) assert all(i.is_Integer for i in (x, y, z)) step += 1 return tuple([int(i) for i in (x_0, y_0, z_0)]) def diop_general_pythagorean(eq, param=symbols("m", integer=True)): """ Solves the general pythagorean equation, `a_{1}^2x_{1}^2 + a_{2}^2x_{2}^2 + . . . + a_{n}^2x_{n}^2 - a_{n + 1}^2x_{n + 1}^2 = 0`. Returns a tuple which contains a parametrized solution to the equation, sorted in the same order as the input variables. Usage ===== ``diop_general_pythagorean(eq, param)``: where ``eq`` is a general pythagorean equation which is assumed to be zero and ``param`` is the base parameter used to construct other parameters by subscripting. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_general_pythagorean >>> from sympy.abc import a, b, c, d, e >>> diop_general_pythagorean(a**2 + b**2 + c**2 - d**2) (m1**2 + m2**2 - m3**2, 2*m1*m3, 2*m2*m3, m1**2 + m2**2 + m3**2) >>> diop_general_pythagorean(9*a**2 - 4*b**2 + 16*c**2 + 25*d**2 + e**2) (10*m1**2 + 10*m2**2 + 10*m3**2 - 10*m4**2, 15*m1**2 + 15*m2**2 + 15*m3**2 + 15*m4**2, 15*m1*m4, 12*m2*m4, 60*m3*m4) """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == GeneralPythagorean.name: return list(_diop_general_pythagorean(var, coeff, param))[0] def _diop_general_pythagorean(var, coeff, t): if sign(coeff[var[0]**2]) + sign(coeff[var[1]**2]) + sign(coeff[var[2]**2]) < 0: for key in coeff.keys(): coeff[key] = -coeff[key] n = len(var) index = 0 for i, v in enumerate(var): if sign(coeff[v**2]) == -1: index = i m = symbols('%s1:%i' % (t, n), integer=True) ith = sum(m_i**2 for m_i in m) L = [ith - 2*m[n - 2]**2] L.extend([2*m[i]*m[n-2] for i in range(n - 2)]) sol = L[:index] + [ith] + L[index:] lcm = 1 for i, v in enumerate(var): if i == index or (index > 0 and i == 0) or (index == 0 and i == 1): lcm = ilcm(lcm, sqrt(abs(coeff[v**2]))) else: s = sqrt(coeff[v**2]) lcm = ilcm(lcm, s if _odd(s) else s//2) for i, v in enumerate(var): sol[i] = (lcm*sol[i]) / sqrt(abs(coeff[v**2])) result = DiophantineSolutionSet(var) result.add(sol) return result def diop_general_sum_of_squares(eq, limit=1): r""" Solves the equation `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`. Returns at most ``limit`` number of solutions. Usage ===== ``general_sum_of_squares(eq, limit)`` : Here ``eq`` is an expression which is assumed to be zero. Also, ``eq`` should be in the form, `x_{1}^2 + x_{2}^2 + . . . + x_{n}^2 - k = 0`. Details ======= When `n = 3` if `k = 4^a(8m + 7)` for some `a, m \in Z` then there will be no solutions. Refer [1]_ for more details. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_squares >>> from sympy.abc import a, b, c, d, e >>> diop_general_sum_of_squares(a**2 + b**2 + c**2 + d**2 + e**2 - 2345) {(15, 22, 22, 24, 24)} Reference ========= .. [1] Representing an integer as a sum of three squares, [online], Available: http://www.proofwiki.org/wiki/Integer_as_Sum_of_Three_Squares """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == GeneralSumOfSquares.name: return set(_diop_general_sum_of_squares(var, -int(coeff[1]), limit)) def _diop_general_sum_of_squares(var, k, limit=1): # solves Eq(sum(i**2 for i in var), k) n = len(var) if n < 3: raise ValueError('n must be greater than 2') result = DiophantineSolutionSet(var) if k < 0 or limit < 1: return result sign = [-1 if x.is_nonpositive else 1 for x in var] negs = sign.count(-1) != 0 took = 0 for t in sum_of_squares(k, n, zeros=True): if negs: result.add([sign[i]*j for i, j in enumerate(t)]) else: result.add(t) took += 1 if took == limit: break return result def diop_general_sum_of_even_powers(eq, limit=1): """ Solves the equation `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0` where `e` is an even, integer power. Returns at most ``limit`` number of solutions. Usage ===== ``general_sum_of_even_powers(eq, limit)`` : Here ``eq`` is an expression which is assumed to be zero. Also, ``eq`` should be in the form, `x_{1}^e + x_{2}^e + . . . + x_{n}^e - k = 0`. Examples ======== >>> from sympy.solvers.diophantine.diophantine import diop_general_sum_of_even_powers >>> from sympy.abc import a, b >>> diop_general_sum_of_even_powers(a**4 + b**4 - (2**4 + 3**4)) {(2, 3)} See Also ======== power_representation """ var, coeff, diop_type = classify_diop(eq, _dict=False) if diop_type == GeneralSumOfEvenPowers.name: for k in coeff.keys(): if k.is_Pow and coeff[k]: p = k.exp return set(_diop_general_sum_of_even_powers(var, p, -coeff[1], limit)) def _diop_general_sum_of_even_powers(var, p, n, limit=1): # solves Eq(sum(i**2 for i in var), n) k = len(var) result = DiophantineSolutionSet(var) if n < 0 or limit < 1: return result sign = [-1 if x.is_nonpositive else 1 for x in var] negs = sign.count(-1) != 0 took = 0 for t in power_representation(n, p, k): if negs: result.add([sign[i]*j for i, j in enumerate(t)]) else: result.add(t) took += 1 if took == limit: break return result ## Functions below this comment can be more suitably grouped under ## an Additive number theory module rather than the Diophantine ## equation module. def partition(n, k=None, zeros=False): """ Returns a generator that can be used to generate partitions of an integer `n`. A partition of `n` is a set of positive integers which add up to `n`. For example, partitions of 3 are 3, 1 + 2, 1 + 1 + 1. A partition is returned as a tuple. If ``k`` equals None, then all possible partitions are returned irrespective of their size, otherwise only the partitions of size ``k`` are returned. If the ``zero`` parameter is set to True then a suitable number of zeros are added at the end of every partition of size less than ``k``. ``zero`` parameter is considered only if ``k`` is not None. When the partitions are over, the last `next()` call throws the ``StopIteration`` exception, so this function should always be used inside a try - except block. Details ======= ``partition(n, k)``: Here ``n`` is a positive integer and ``k`` is the size of the partition which is also positive integer. Examples ======== >>> from sympy.solvers.diophantine.diophantine import partition >>> f = partition(5) >>> next(f) (1, 1, 1, 1, 1) >>> next(f) (1, 1, 1, 2) >>> g = partition(5, 3) >>> next(g) (1, 1, 3) >>> next(g) (1, 2, 2) >>> g = partition(5, 3, zeros=True) >>> next(g) (0, 0, 5) """ from sympy.utilities.iterables import ordered_partitions if not zeros or k is None: for i in ordered_partitions(n, k): yield tuple(i) else: for m in range(1, k + 1): for i in ordered_partitions(n, m): i = tuple(i) yield (0,)*(k - len(i)) + i def prime_as_sum_of_two_squares(p): """ Represent a prime `p` as a unique sum of two squares; this can only be done if the prime is congruent to 1 mod 4. Examples ======== >>> from sympy.solvers.diophantine.diophantine import prime_as_sum_of_two_squares >>> prime_as_sum_of_two_squares(7) # can't be done >>> prime_as_sum_of_two_squares(5) (1, 2) Reference ========= .. [1] Representing a number as a sum of four squares, [online], Available: http://schorn.ch/lagrange.html See Also ======== sum_of_squares() """ if not p % 4 == 1: return if p % 8 == 5: b = 2 else: b = 3 while pow(b, (p - 1) // 2, p) == 1: b = nextprime(b) b = pow(b, (p - 1) // 4, p) a = p while b**2 > p: a, b = b, a % b return (int(a % b), int(b)) # convert from long def sum_of_three_squares(n): r""" Returns a 3-tuple `(a, b, c)` such that `a^2 + b^2 + c^2 = n` and `a, b, c \geq 0`. Returns None if `n = 4^a(8m + 7)` for some `a, m \in Z`. See [1]_ for more details. Usage ===== ``sum_of_three_squares(n)``: Here ``n`` is a non-negative integer. Examples ======== >>> from sympy.solvers.diophantine.diophantine import sum_of_three_squares >>> sum_of_three_squares(44542) (18, 37, 207) References ========== .. [1] Representing a number as a sum of three squares, [online], Available: http://schorn.ch/lagrange.html See Also ======== sum_of_squares() """ special = {1:(1, 0, 0), 2:(1, 1, 0), 3:(1, 1, 1), 10: (1, 3, 0), 34: (3, 3, 4), 58:(3, 7, 0), 85:(6, 7, 0), 130:(3, 11, 0), 214:(3, 6, 13), 226:(8, 9, 9), 370:(8, 9, 15), 526:(6, 7, 21), 706:(15, 15, 16), 730:(1, 27, 0), 1414:(6, 17, 33), 1906:(13, 21, 36), 2986: (21, 32, 39), 9634: (56, 57, 57)} v = 0 if n == 0: return (0, 0, 0) v = multiplicity(4, n) n //= 4**v if n % 8 == 7: return if n in special.keys(): x, y, z = special[n] return _sorted_tuple(2**v*x, 2**v*y, 2**v*z) s, _exact = integer_nthroot(n, 2) if _exact: return (2**v*s, 0, 0) x = None if n % 8 == 3: s = s if _odd(s) else s - 1 for x in range(s, -1, -2): N = (n - x**2) // 2 if isprime(N): y, z = prime_as_sum_of_two_squares(N) return _sorted_tuple(2**v*x, 2**v*(y + z), 2**v*abs(y - z)) return if n % 8 == 2 or n % 8 == 6: s = s if _odd(s) else s - 1 else: s = s - 1 if _odd(s) else s for x in range(s, -1, -2): N = n - x**2 if isprime(N): y, z = prime_as_sum_of_two_squares(N) return _sorted_tuple(2**v*x, 2**v*y, 2**v*z) def sum_of_four_squares(n): r""" Returns a 4-tuple `(a, b, c, d)` such that `a^2 + b^2 + c^2 + d^2 = n`. Here `a, b, c, d \geq 0`. Usage ===== ``sum_of_four_squares(n)``: Here ``n`` is a non-negative integer. Examples ======== >>> from sympy.solvers.diophantine.diophantine import sum_of_four_squares >>> sum_of_four_squares(3456) (8, 8, 32, 48) >>> sum_of_four_squares(1294585930293) (0, 1234, 2161, 1137796) References ========== .. [1] Representing a number as a sum of four squares, [online], Available: http://schorn.ch/lagrange.html See Also ======== sum_of_squares() """ if n == 0: return (0, 0, 0, 0) v = multiplicity(4, n) n //= 4**v if n % 8 == 7: d = 2 n = n - 4 elif n % 8 == 6 or n % 8 == 2: d = 1 n = n - 1 else: d = 0 x, y, z = sum_of_three_squares(n) return _sorted_tuple(2**v*d, 2**v*x, 2**v*y, 2**v*z) def power_representation(n, p, k, zeros=False): r""" Returns a generator for finding k-tuples of integers, `(n_{1}, n_{2}, . . . n_{k})`, such that `n = n_{1}^p + n_{2}^p + . . . n_{k}^p`. Usage ===== ``power_representation(n, p, k, zeros)``: Represent non-negative number ``n`` as a sum of ``k`` ``p``\ th powers. If ``zeros`` is true, then the solutions is allowed to contain zeros. Examples ======== >>> from sympy.solvers.diophantine.diophantine import power_representation Represent 1729 as a sum of two cubes: >>> f = power_representation(1729, 3, 2) >>> next(f) (9, 10) >>> next(f) (1, 12) If the flag `zeros` is True, the solution may contain tuples with zeros; any such solutions will be generated after the solutions without zeros: >>> list(power_representation(125, 2, 3, zeros=True)) [(5, 6, 8), (3, 4, 10), (0, 5, 10), (0, 2, 11)] For even `p` the `permute_sign` function can be used to get all signed values: >>> from sympy.utilities.iterables import permute_signs >>> list(permute_signs((1, 12))) [(1, 12), (-1, 12), (1, -12), (-1, -12)] All possible signed permutations can also be obtained: >>> from sympy.utilities.iterables import signed_permutations >>> list(signed_permutations((1, 12))) [(1, 12), (-1, 12), (1, -12), (-1, -12), (12, 1), (-12, 1), (12, -1), (-12, -1)] """ n, p, k = [as_int(i) for i in (n, p, k)] if n < 0: if p % 2: for t in power_representation(-n, p, k, zeros): yield tuple(-i for i in t) return if p < 1 or k < 1: raise ValueError(filldedent(''' Expecting positive integers for `(p, k)`, but got `(%s, %s)`''' % (p, k))) if n == 0: if zeros: yield (0,)*k return if k == 1: if p == 1: yield (n,) else: be = perfect_power(n) if be: b, e = be d, r = divmod(e, p) if not r: yield (b**d,) return if p == 1: for t in partition(n, k, zeros=zeros): yield t return if p == 2: feasible = _can_do_sum_of_squares(n, k) if not feasible: return if not zeros and n > 33 and k >= 5 and k <= n and n - k in ( 13, 10, 7, 5, 4, 2, 1): '''Todd G. Will, "When Is n^2 a Sum of k Squares?", [online]. Available: https://www.maa.org/sites/default/files/Will-MMz-201037918.pdf''' return if feasible is not True: # it's prime and k == 2 yield prime_as_sum_of_two_squares(n) return if k == 2 and p > 2: be = perfect_power(n) if be and be[1] % p == 0: return # Fermat: a**n + b**n = c**n has no solution for n > 2 if n >= k: a = integer_nthroot(n - (k - 1), p)[0] for t in pow_rep_recursive(a, k, n, [], p): yield tuple(reversed(t)) if zeros: a = integer_nthroot(n, p)[0] for i in range(1, k): for t in pow_rep_recursive(a, i, n, [], p): yield tuple(reversed(t + (0,) * (k - i))) sum_of_powers = power_representation def pow_rep_recursive(n_i, k, n_remaining, terms, p): if k == 0 and n_remaining == 0: yield tuple(terms) else: if n_i >= 1 and k > 0: for t in pow_rep_recursive(n_i - 1, k, n_remaining, terms, p): yield t residual = n_remaining - pow(n_i, p) if residual >= 0: for t in pow_rep_recursive(n_i, k - 1, residual, terms + [n_i], p): yield t def sum_of_squares(n, k, zeros=False): """Return a generator that yields the k-tuples of nonnegative values, the squares of which sum to n. If zeros is False (default) then the solution will not contain zeros. The nonnegative elements of a tuple are sorted. * If k == 1 and n is square, (n,) is returned. * If k == 2 then n can only be written as a sum of squares if every prime in the factorization of n that has the form 4*k + 3 has an even multiplicity. If n is prime then it can only be written as a sum of two squares if it is in the form 4*k + 1. * if k == 3 then n can be written as a sum of squares if it does not have the form 4**m*(8*k + 7). * all integers can be written as the sum of 4 squares. * if k > 4 then n can be partitioned and each partition can be written as a sum of 4 squares; if n is not evenly divisible by 4 then n can be written as a sum of squares only if the an additional partition can be written as sum of squares. For example, if k = 6 then n is partitioned into two parts, the first being written as a sum of 4 squares and the second being written as a sum of 2 squares -- which can only be done if the condition above for k = 2 can be met, so this will automatically reject certain partitions of n. Examples ======== >>> from sympy.solvers.diophantine.diophantine import sum_of_squares >>> list(sum_of_squares(25, 2)) [(3, 4)] >>> list(sum_of_squares(25, 2, True)) [(3, 4), (0, 5)] >>> list(sum_of_squares(25, 4)) [(1, 2, 2, 4)] See Also ======== sympy.utilities.iterables.signed_permutations """ for t in power_representation(n, 2, k, zeros): yield t def _can_do_sum_of_squares(n, k): """Return True if n can be written as the sum of k squares, False if it can't, or 1 if k == 2 and n is prime (in which case it *can* be written as a sum of two squares). A False is returned only if it can't be written as k-squares, even if 0s are allowed. """ if k < 1: return False if n < 0: return False if n == 0: return True if k == 1: return is_square(n) if k == 2: if n in (1, 2): return True if isprime(n): if n % 4 == 1: return 1 # signal that it was prime return False else: f = factorint(n) for p, m in f.items(): # we can proceed iff no prime factor in the form 4*k + 3 # has an odd multiplicity if (p % 4 == 3) and m % 2: return False return True if k == 3: if (n//4**multiplicity(4, n)) % 8 == 7: return False # every number can be written as a sum of 4 squares; for k > 4 partitions # can be 0 return True
e0056a02e739657a34f1e5437720fa26d7a86b217547f79a6c51f5d77eb6397a
r""" This module contains :py:meth:`~sympy.solvers.ode.dsolve` and different helper functions that it uses. :py:meth:`~sympy.solvers.ode.dsolve` solves ordinary differential equations. See the docstring on the various functions for their uses. Note that partial differential equations support is in ``pde.py``. Note that hint functions have docstrings describing their various methods, but they are intended for internal use. Use ``dsolve(ode, func, hint=hint)`` to solve an ODE using a specific hint. See also the docstring on :py:meth:`~sympy.solvers.ode.dsolve`. **Functions in this module** These are the user functions in this module: - :py:meth:`~sympy.solvers.ode.dsolve` - Solves ODEs. - :py:meth:`~sympy.solvers.ode.classify_ode` - Classifies ODEs into possible hints for :py:meth:`~sympy.solvers.ode.dsolve`. - :py:meth:`~sympy.solvers.ode.checkodesol` - Checks if an equation is the solution to an ODE. - :py:meth:`~sympy.solvers.ode.homogeneous_order` - Returns the homogeneous order of an expression. - :py:meth:`~sympy.solvers.ode.infinitesimals` - Returns the infinitesimals of the Lie group of point transformations of an ODE, such that it is invariant. - :py:meth:`~sympy.solvers.ode.checkinfsol` - Checks if the given infinitesimals are the actual infinitesimals of a first order ODE. These are the non-solver helper functions that are for internal use. The user should use the various options to :py:meth:`~sympy.solvers.ode.dsolve` to obtain the functionality provided by these functions: - :py:meth:`~sympy.solvers.ode.ode.odesimp` - Does all forms of ODE simplification. - :py:meth:`~sympy.solvers.ode.ode.ode_sol_simplicity` - A key function for comparing solutions by simplicity. - :py:meth:`~sympy.solvers.ode.constantsimp` - Simplifies arbitrary constants. - :py:meth:`~sympy.solvers.ode.ode.constant_renumber` - Renumber arbitrary constants. - :py:meth:`~sympy.solvers.ode.ode._handle_Integral` - Evaluate unevaluated Integrals. See also the docstrings of these functions. **Currently implemented solver methods** The following methods are implemented for solving ordinary differential equations. See the docstrings of the various hint functions for more information on each (run ``help(ode)``): - 1st order separable differential equations. - 1st order differential equations whose coefficients or `dx` and `dy` are functions homogeneous of the same order. - 1st order exact differential equations. - 1st order linear differential equations. - 1st order Bernoulli differential equations. - Power series solutions for first order differential equations. - Lie Group method of solving first order differential equations. - 2nd order Liouville differential equations. - Power series solutions for second order differential equations at ordinary and regular singular points. - `n`\th order differential equation that can be solved with algebraic rearrangement and integration. - `n`\th order linear homogeneous differential equation with constant coefficients. - `n`\th order linear inhomogeneous differential equation with constant coefficients using the method of undetermined coefficients. - `n`\th order linear inhomogeneous differential equation with constant coefficients using the method of variation of parameters. **Philosophy behind this module** This module is designed to make it easy to add new ODE solving methods without having to mess with the solving code for other methods. The idea is that there is a :py:meth:`~sympy.solvers.ode.classify_ode` function, which takes in an ODE and tells you what hints, if any, will solve the ODE. It does this without attempting to solve the ODE, so it is fast. Each solving method is a hint, and it has its own function, named ``ode_<hint>``. That function takes in the ODE and any match expression gathered by :py:meth:`~sympy.solvers.ode.classify_ode` and returns a solved result. If this result has any integrals in it, the hint function will return an unevaluated :py:class:`~sympy.integrals.integrals.Integral` class. :py:meth:`~sympy.solvers.ode.dsolve`, which is the user wrapper function around all of this, will then call :py:meth:`~sympy.solvers.ode.ode.odesimp` on the result, which, among other things, will attempt to solve the equation for the dependent variable (the function we are solving for), simplify the arbitrary constants in the expression, and evaluate any integrals, if the hint allows it. **How to add new solution methods** If you have an ODE that you want :py:meth:`~sympy.solvers.ode.dsolve` to be able to solve, try to avoid adding special case code here. Instead, try finding a general method that will solve your ODE, as well as others. This way, the :py:mod:`~sympy.solvers.ode` module will become more robust, and unhindered by special case hacks. WolphramAlpha and Maple's DETools[odeadvisor] function are two resources you can use to classify a specific ODE. It is also better for a method to work with an `n`\th order ODE instead of only with specific orders, if possible. To add a new method, there are a few things that you need to do. First, you need a hint name for your method. Try to name your hint so that it is unambiguous with all other methods, including ones that may not be implemented yet. If your method uses integrals, also include a ``hint_Integral`` hint. If there is more than one way to solve ODEs with your method, include a hint for each one, as well as a ``<hint>_best`` hint. Your ``ode_<hint>_best()`` function should choose the best using min with ``ode_sol_simplicity`` as the key argument. See :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_best`, for example. The function that uses your method will be called ``ode_<hint>()``, so the hint must only use characters that are allowed in a Python function name (alphanumeric characters and the underscore '``_``' character). Include a function for every hint, except for ``_Integral`` hints (:py:meth:`~sympy.solvers.ode.dsolve` takes care of those automatically). Hint names should be all lowercase, unless a word is commonly capitalized (such as Integral or Bernoulli). If you have a hint that you do not want to run with ``all_Integral`` that doesn't have an ``_Integral`` counterpart (such as a best hint that would defeat the purpose of ``all_Integral``), you will need to remove it manually in the :py:meth:`~sympy.solvers.ode.dsolve` code. See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for guidelines on writing a hint name. Determine *in general* how the solutions returned by your method compare with other methods that can potentially solve the same ODEs. Then, put your hints in the :py:data:`~sympy.solvers.ode.allhints` tuple in the order that they should be called. The ordering of this tuple determines which hints are default. Note that exceptions are ok, because it is easy for the user to choose individual hints with :py:meth:`~sympy.solvers.ode.dsolve`. In general, ``_Integral`` variants should go at the end of the list, and ``_best`` variants should go before the various hints they apply to. For example, the ``undetermined_coefficients`` hint comes before the ``variation_of_parameters`` hint because, even though variation of parameters is more general than undetermined coefficients, undetermined coefficients generally returns cleaner results for the ODEs that it can solve than variation of parameters does, and it does not require integration, so it is much faster. Next, you need to have a match expression or a function that matches the type of the ODE, which you should put in :py:meth:`~sympy.solvers.ode.classify_ode` (if the match function is more than just a few lines, like :py:meth:`~sympy.solvers.ode.ode._undetermined_coefficients_match`, it should go outside of :py:meth:`~sympy.solvers.ode.classify_ode`). It should match the ODE without solving for it as much as possible, so that :py:meth:`~sympy.solvers.ode.classify_ode` remains fast and is not hindered by bugs in solving code. Be sure to consider corner cases. For example, if your solution method involves dividing by something, make sure you exclude the case where that division will be 0. In most cases, the matching of the ODE will also give you the various parts that you need to solve it. You should put that in a dictionary (``.match()`` will do this for you), and add that as ``matching_hints['hint'] = matchdict`` in the relevant part of :py:meth:`~sympy.solvers.ode.classify_ode`. :py:meth:`~sympy.solvers.ode.classify_ode` will then send this to :py:meth:`~sympy.solvers.ode.dsolve`, which will send it to your function as the ``match`` argument. Your function should be named ``ode_<hint>(eq, func, order, match)`. If you need to send more information, put it in the ``match`` dictionary. For example, if you had to substitute in a dummy variable in :py:meth:`~sympy.solvers.ode.classify_ode` to match the ODE, you will need to pass it to your function using the `match` dict to access it. You can access the independent variable using ``func.args[0]``, and the dependent variable (the function you are trying to solve for) as ``func.func``. If, while trying to solve the ODE, you find that you cannot, raise ``NotImplementedError``. :py:meth:`~sympy.solvers.ode.dsolve` will catch this error with the ``all`` meta-hint, rather than causing the whole routine to fail. Add a docstring to your function that describes the method employed. Like with anything else in SymPy, you will need to add a doctest to the docstring, in addition to real tests in ``test_ode.py``. Try to maintain consistency with the other hint functions' docstrings. Add your method to the list at the top of this docstring. Also, add your method to ``ode.rst`` in the ``docs/src`` directory, so that the Sphinx docs will pull its docstring into the main SymPy documentation. Be sure to make the Sphinx documentation by running ``make html`` from within the doc directory to verify that the docstring formats correctly. If your solution method involves integrating, use :py:obj:`~.Integral` instead of :py:meth:`~sympy.core.expr.Expr.integrate`. This allows the user to bypass hard/slow integration by using the ``_Integral`` variant of your hint. In most cases, calling :py:meth:`sympy.core.basic.Basic.doit` will integrate your solution. If this is not the case, you will need to write special code in :py:meth:`~sympy.solvers.ode.ode._handle_Integral`. Arbitrary constants should be symbols named ``C1``, ``C2``, and so on. All solution methods should return an equality instance. If you need an arbitrary number of arbitrary constants, you can use ``constants = numbered_symbols(prefix='C', cls=Symbol, start=1)``. If it is possible to solve for the dependent function in a general way, do so. Otherwise, do as best as you can, but do not call solve in your ``ode_<hint>()`` function. :py:meth:`~sympy.solvers.ode.ode.odesimp` will attempt to solve the solution for you, so you do not need to do that. Lastly, if your ODE has a common simplification that can be applied to your solutions, you can add a special case in :py:meth:`~sympy.solvers.ode.ode.odesimp` for it. For example, solutions returned from the ``1st_homogeneous_coeff`` hints often have many :obj:`~sympy.functions.elementary.exponential.log` terms, so :py:meth:`~sympy.solvers.ode.ode.odesimp` calls :py:meth:`~sympy.simplify.simplify.logcombine` on them (it also helps to write the arbitrary constant as ``log(C1)`` instead of ``C1`` in this case). Also consider common ways that you can rearrange your solution to have :py:meth:`~sympy.solvers.ode.constantsimp` take better advantage of it. It is better to put simplification in :py:meth:`~sympy.solvers.ode.ode.odesimp` than in your method, because it can then be turned off with the simplify flag in :py:meth:`~sympy.solvers.ode.dsolve`. If you have any extraneous simplification in your function, be sure to only run it using ``if match.get('simplify', True):``, especially if it can be slow or if it can reduce the domain of the solution. Finally, as with every contribution to SymPy, your method will need to be tested. Add a test for each method in ``test_ode.py``. Follow the conventions there, i.e., test the solver using ``dsolve(eq, f(x), hint=your_hint)``, and also test the solution using :py:meth:`~sympy.solvers.ode.checkodesol` (you can put these in a separate tests and skip/XFAIL if it runs too slow/doesn't work). Be sure to call your hint specifically in :py:meth:`~sympy.solvers.ode.dsolve`, that way the test won't be broken simply by the introduction of another matching hint. If your method works for higher order (>1) ODEs, you will need to run ``sol = constant_renumber(sol, 'C', 1, order)`` for each solution, where ``order`` is the order of the ODE. This is because ``constant_renumber`` renumbers the arbitrary constants by printing order, which is platform dependent. Try to test every corner case of your solver, including a range of orders if it is a `n`\th order solver, but if your solver is slow, such as if it involves hard integration, try to keep the test run time down. Feel free to refactor existing hints to avoid duplicating code or creating inconsistencies. If you can show that your method exactly duplicates an existing method, including in the simplicity and speed of obtaining the solutions, then you can remove the old, less general method. The existing code is tested extensively in ``test_ode.py``, so if anything is broken, one of those tests will surely fail. """ from __future__ import print_function, division from collections import defaultdict from itertools import islice from sympy.functions import hyper from sympy.core import Add, S, Mul, Pow, oo, Rational from sympy.core.compatibility import ordered, iterable from sympy.core.containers import Tuple from sympy.core.exprtools import factor_terms from sympy.core.expr import AtomicExpr, Expr from sympy.core.function import (Function, Derivative, AppliedUndef, diff, expand, expand_mul, Subs, _mexpand) from sympy.core.multidimensional import vectorize from sympy.core.numbers import NaN, zoo, Number from sympy.core.relational import Equality, Eq from sympy.core.symbol import Symbol, Wild, Dummy, symbols from sympy.core.sympify import sympify from sympy.logic.boolalg import (BooleanAtom, BooleanTrue, BooleanFalse) from sympy.functions import cos, cosh, exp, im, log, re, sin, sinh, sqrt, \ atan2, conjugate, cbrt, besselj, bessely, airyai, airybi from sympy.functions.combinatorial.factorials import factorial from sympy.integrals.integrals import Integral, integrate from sympy.matrices import wronskian from sympy.polys import (Poly, RootOf, rootof, terms_gcd, PolynomialError, lcm, roots, gcd) from sympy.polys.polytools import cancel, degree, div from sympy.series import Order from sympy.series.series import series from sympy.simplify import (collect, logcombine, powsimp, # type: ignore separatevars, simplify, trigsimp, posify, cse) from sympy.simplify.powsimp import powdenest from sympy.simplify.radsimp import collect_const from sympy.solvers import checksol, solve from sympy.solvers.pde import pdsolve from sympy.utilities import numbered_symbols, default_sort_key, sift from sympy.utilities.iterables import uniq from sympy.solvers.deutils import _preprocess, ode_order, _desolve from .subscheck import sub_func_doit #: This is a list of hints in the order that they should be preferred by #: :py:meth:`~sympy.solvers.ode.classify_ode`. In general, hints earlier in the #: list should produce simpler solutions than those later in the list (for #: ODEs that fit both). For now, the order of this list is based on empirical #: observations by the developers of SymPy. #: #: The hint used by :py:meth:`~sympy.solvers.ode.dsolve` for a specific ODE #: can be overridden (see the docstring). #: #: In general, ``_Integral`` hints are grouped at the end of the list, unless #: there is a method that returns an unevaluable integral most of the time #: (which go near the end of the list anyway). ``default``, ``all``, #: ``best``, and ``all_Integral`` meta-hints should not be included in this #: list, but ``_best`` and ``_Integral`` hints should be included. allhints = ( "factorable", "nth_algebraic", "separable", "1st_exact", "1st_linear", "Bernoulli", "Riccati_special_minus2", "1st_homogeneous_coeff_best", "1st_homogeneous_coeff_subs_indep_div_dep", "1st_homogeneous_coeff_subs_dep_div_indep", "almost_linear", "linear_coefficients", "separable_reduced", "1st_power_series", "lie_group", "nth_linear_constant_coeff_homogeneous", "nth_linear_euler_eq_homogeneous", "nth_linear_constant_coeff_undetermined_coefficients", "nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients", "nth_linear_constant_coeff_variation_of_parameters", "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters", "Liouville", "2nd_linear_airy", "2nd_linear_bessel", "2nd_hypergeometric", "2nd_hypergeometric_Integral", "nth_order_reducible", "2nd_power_series_ordinary", "2nd_power_series_regular", "nth_algebraic_Integral", "separable_Integral", "1st_exact_Integral", "1st_linear_Integral", "Bernoulli_Integral", "1st_homogeneous_coeff_subs_indep_div_dep_Integral", "1st_homogeneous_coeff_subs_dep_div_indep_Integral", "almost_linear_Integral", "linear_coefficients_Integral", "separable_reduced_Integral", "nth_linear_constant_coeff_variation_of_parameters_Integral", "nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral", "Liouville_Integral", ) lie_heuristics = ( "abaco1_simple", "abaco1_product", "abaco2_similar", "abaco2_unique_unknown", "abaco2_unique_general", "linear", "function_sum", "bivariate", "chi" ) def get_numbered_constants(eq, num=1, start=1, prefix='C'): """ Returns a list of constants that do not occur in eq already. """ ncs = iter_numbered_constants(eq, start, prefix) Cs = [next(ncs) for i in range(num)] return (Cs[0] if num == 1 else tuple(Cs)) def iter_numbered_constants(eq, start=1, prefix='C'): """ Returns an iterator of constants that do not occur in eq already. """ if isinstance(eq, (Expr, Eq)): eq = [eq] elif not iterable(eq): raise ValueError("Expected Expr or iterable but got %s" % eq) atom_set = set().union(*[i.free_symbols for i in eq]) func_set = set().union(*[i.atoms(Function) for i in eq]) if func_set: atom_set |= {Symbol(str(f.func)) for f in func_set} return numbered_symbols(start=start, prefix=prefix, exclude=atom_set) def dsolve(eq, func=None, hint="default", simplify=True, ics= None, xi=None, eta=None, x0=0, n=6, **kwargs): r""" Solves any (supported) kind of ordinary differential equation and system of ordinary differential equations. For single ordinary differential equation ========================================= It is classified under this when number of equation in ``eq`` is one. **Usage** ``dsolve(eq, f(x), hint)`` -> Solve ordinary differential equation ``eq`` for function ``f(x)``, using method ``hint``. **Details** ``eq`` can be any supported ordinary differential equation (see the :py:mod:`~sympy.solvers.ode` docstring for supported methods). This can either be an :py:class:`~sympy.core.relational.Equality`, or an expression, which is assumed to be equal to ``0``. ``f(x)`` is a function of one variable whose derivatives in that variable make up the ordinary differential equation ``eq``. In many cases it is not necessary to provide this; it will be autodetected (and an error raised if it couldn't be detected). ``hint`` is the solving method that you want dsolve to use. Use ``classify_ode(eq, f(x))`` to get all of the possible hints for an ODE. The default hint, ``default``, will use whatever hint is returned first by :py:meth:`~sympy.solvers.ode.classify_ode`. See Hints below for more options that you can use for hint. ``simplify`` enables simplification by :py:meth:`~sympy.solvers.ode.ode.odesimp`. See its docstring for more information. Turn this off, for example, to disable solving of solutions for ``func`` or simplification of arbitrary constants. It will still integrate with this hint. Note that the solution may contain more arbitrary constants than the order of the ODE with this option enabled. ``xi`` and ``eta`` are the infinitesimal functions of an ordinary differential equation. They are the infinitesimals of the Lie group of point transformations for which the differential equation is invariant. The user can specify values for the infinitesimals. If nothing is specified, ``xi`` and ``eta`` are calculated using :py:meth:`~sympy.solvers.ode.infinitesimals` with the help of various heuristics. ``ics`` is the set of initial/boundary conditions for the differential equation. It should be given in the form of ``{f(x0): x1, f(x).diff(x).subs(x, x2): x3}`` and so on. For power series solutions, if no initial conditions are specified ``f(0)`` is assumed to be ``C0`` and the power series solution is calculated about 0. ``x0`` is the point about which the power series solution of a differential equation is to be evaluated. ``n`` gives the exponent of the dependent variable up to which the power series solution of a differential equation is to be evaluated. **Hints** Aside from the various solving methods, there are also some meta-hints that you can pass to :py:meth:`~sympy.solvers.ode.dsolve`: ``default``: This uses whatever hint is returned first by :py:meth:`~sympy.solvers.ode.classify_ode`. This is the default argument to :py:meth:`~sympy.solvers.ode.dsolve`. ``all``: To make :py:meth:`~sympy.solvers.ode.dsolve` apply all relevant classification hints, use ``dsolve(ODE, func, hint="all")``. This will return a dictionary of ``hint:solution`` terms. If a hint causes dsolve to raise the ``NotImplementedError``, value of that hint's key will be the exception object raised. The dictionary will also include some special keys: - ``order``: The order of the ODE. See also :py:meth:`~sympy.solvers.deutils.ode_order` in ``deutils.py``. - ``best``: The simplest hint; what would be returned by ``best`` below. - ``best_hint``: The hint that would produce the solution given by ``best``. If more than one hint produces the best solution, the first one in the tuple returned by :py:meth:`~sympy.solvers.ode.classify_ode` is chosen. - ``default``: The solution that would be returned by default. This is the one produced by the hint that appears first in the tuple returned by :py:meth:`~sympy.solvers.ode.classify_ode`. ``all_Integral``: This is the same as ``all``, except if a hint also has a corresponding ``_Integral`` hint, it only returns the ``_Integral`` hint. This is useful if ``all`` causes :py:meth:`~sympy.solvers.ode.dsolve` to hang because of a difficult or impossible integral. This meta-hint will also be much faster than ``all``, because :py:meth:`~sympy.core.expr.Expr.integrate` is an expensive routine. ``best``: To have :py:meth:`~sympy.solvers.ode.dsolve` try all methods and return the simplest one. This takes into account whether the solution is solvable in the function, whether it contains any Integral classes (i.e. unevaluatable integrals), and which one is the shortest in size. See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for more info on hints, and the :py:mod:`~sympy.solvers.ode` docstring for a list of all supported hints. **Tips** - You can declare the derivative of an unknown function this way: >>> from sympy import Function, Derivative >>> from sympy.abc import x # x is the independent variable >>> f = Function("f")(x) # f is a function of x >>> # f_ will be the derivative of f with respect to x >>> f_ = Derivative(f, x) - See ``test_ode.py`` for many tests, which serves also as a set of examples for how to use :py:meth:`~sympy.solvers.ode.dsolve`. - :py:meth:`~sympy.solvers.ode.dsolve` always returns an :py:class:`~sympy.core.relational.Equality` class (except for the case when the hint is ``all`` or ``all_Integral``). If possible, it solves the solution explicitly for the function being solved for. Otherwise, it returns an implicit solution. - Arbitrary constants are symbols named ``C1``, ``C2``, and so on. - Because all solutions should be mathematically equivalent, some hints may return the exact same result for an ODE. Often, though, two different hints will return the same solution formatted differently. The two should be equivalent. Also note that sometimes the values of the arbitrary constants in two different solutions may not be the same, because one constant may have "absorbed" other constants into it. - Do ``help(ode.ode_<hintname>)`` to get help more information on a specific hint, where ``<hintname>`` is the name of a hint without ``_Integral``. For system of ordinary differential equations ============================================= **Usage** ``dsolve(eq, func)`` -> Solve a system of ordinary differential equations ``eq`` for ``func`` being list of functions including `x(t)`, `y(t)`, `z(t)` where number of functions in the list depends upon the number of equations provided in ``eq``. **Details** ``eq`` can be any supported system of ordinary differential equations This can either be an :py:class:`~sympy.core.relational.Equality`, or an expression, which is assumed to be equal to ``0``. ``func`` holds ``x(t)`` and ``y(t)`` being functions of one variable which together with some of their derivatives make up the system of ordinary differential equation ``eq``. It is not necessary to provide this; it will be autodetected (and an error raised if it couldn't be detected). **Hints** The hints are formed by parameters returned by classify_sysode, combining them give hints name used later for forming method name. Examples ======== >>> from sympy import Function, dsolve, Eq, Derivative, sin, cos, symbols >>> from sympy.abc import x >>> f = Function('f') >>> dsolve(Derivative(f(x), x, x) + 9*f(x), f(x)) Eq(f(x), C1*sin(3*x) + C2*cos(3*x)) >>> eq = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x) >>> dsolve(eq, hint='1st_exact') [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))] >>> dsolve(eq, hint='almost_linear') [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))] >>> t = symbols('t') >>> x, y = symbols('x, y', cls=Function) >>> eq = (Eq(Derivative(x(t),t), 12*t*x(t) + 8*y(t)), Eq(Derivative(y(t),t), 21*x(t) + 7*t*y(t))) >>> dsolve(eq) [Eq(x(t), C1*x0(t) + C2*x0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t)), Eq(y(t), C1*y0(t) + C2*(y0(t)*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)**2, t) + exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0(t)))] >>> eq = (Eq(Derivative(x(t),t),x(t)*y(t)*sin(t)), Eq(Derivative(y(t),t),y(t)**2*sin(t))) >>> dsolve(eq) {Eq(x(t), -exp(C1)/(C2*exp(C1) - cos(t))), Eq(y(t), -1/(C1 - cos(t)))} """ if iterable(eq): from sympy.solvers.ode.systems import dsolve_system # This may have to be changed in future # when we have weakly and strongly # connected components. This have to # changed to show the systems that haven't # been solved. try: sol = dsolve_system(eq, funcs=func, ics=ics, doit=True) return sol[0] if len(sol) == 1 else sol except NotImplementedError: pass match = classify_sysode(eq, func) eq = match['eq'] order = match['order'] func = match['func'] t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] # keep highest order term coefficient positive for i in range(len(eq)): for func_ in func: if isinstance(func_, list): pass else: if eq[i].coeff(diff(func[i],t,ode_order(eq[i], func[i]))).is_negative: eq[i] = -eq[i] match['eq'] = eq if len(set(order.values()))!=1: raise ValueError("It solves only those systems of equations whose orders are equal") match['order'] = list(order.values())[0] def recur_len(l): return sum(recur_len(item) if isinstance(item,list) else 1 for item in l) if recur_len(func) != len(eq): raise ValueError("dsolve() and classify_sysode() work with " "number of functions being equal to number of equations") if match['type_of_equation'] is None: raise NotImplementedError else: if match['is_linear'] == True: solvefunc = globals()['sysode_linear_%(no_of_equation)seq_order%(order)s' % match] else: solvefunc = globals()['sysode_nonlinear_%(no_of_equation)seq_order%(order)s' % match] sols = solvefunc(match) if ics: constants = Tuple(*sols).free_symbols - Tuple(*eq).free_symbols solved_constants = solve_ics(sols, func, constants, ics) return [sol.subs(solved_constants) for sol in sols] return sols else: given_hint = hint # hint given by the user # See the docstring of _desolve for more details. hints = _desolve(eq, func=func, hint=hint, simplify=True, xi=xi, eta=eta, type='ode', ics=ics, x0=x0, n=n, **kwargs) eq = hints.pop('eq', eq) all_ = hints.pop('all', False) if all_: retdict = {} failed_hints = {} gethints = classify_ode(eq, dict=True) orderedhints = gethints['ordered_hints'] for hint in hints: try: rv = _helper_simplify(eq, hint, hints[hint], simplify) except NotImplementedError as detail: failed_hints[hint] = detail else: retdict[hint] = rv func = hints[hint]['func'] retdict['best'] = min(list(retdict.values()), key=lambda x: ode_sol_simplicity(x, func, trysolving=not simplify)) if given_hint == 'best': return retdict['best'] for i in orderedhints: if retdict['best'] == retdict.get(i, None): retdict['best_hint'] = i break retdict['default'] = gethints['default'] retdict['order'] = gethints['order'] retdict.update(failed_hints) return retdict else: # The key 'hint' stores the hint needed to be solved for. hint = hints['hint'] return _helper_simplify(eq, hint, hints, simplify, ics=ics) def _helper_simplify(eq, hint, match, simplify=True, ics=None, **kwargs): r""" Helper function of dsolve that calls the respective :py:mod:`~sympy.solvers.ode` functions to solve for the ordinary differential equations. This minimizes the computation in calling :py:meth:`~sympy.solvers.deutils._desolve` multiple times. """ r = match func = r['func'] order = r['order'] match = r[hint] if isinstance(match, SingleODESolver): solvefunc = match elif hint.endswith('_Integral'): solvefunc = globals()['ode_' + hint[:-len('_Integral')]] else: solvefunc = globals()['ode_' + hint] free = eq.free_symbols cons = lambda s: s.free_symbols.difference(free) if simplify: # odesimp() will attempt to integrate, if necessary, apply constantsimp(), # attempt to solve for func, and apply any other hint specific # simplifications if isinstance(solvefunc, SingleODESolver): sols = solvefunc.get_general_solution() else: sols = solvefunc(eq, func, order, match) if iterable(sols): rv = [odesimp(eq, s, func, hint) for s in sols] else: rv = odesimp(eq, sols, func, hint) else: # We still want to integrate (you can disable it separately with the hint) if isinstance(solvefunc, SingleODESolver): exprs = solvefunc.get_general_solution(simplify=False) else: match['simplify'] = False # Some hints can take advantage of this option exprs = solvefunc(eq, func, order, match) if isinstance(exprs, list): rv = [_handle_Integral(expr, func, hint) for expr in exprs] else: rv = _handle_Integral(exprs, func, hint) if isinstance(rv, list): rv = _remove_redundant_solutions(eq, rv, order, func.args[0]) if len(rv) == 1: rv = rv[0] if ics and not 'power_series' in hint: if isinstance(rv, (Expr, Eq)): solved_constants = solve_ics([rv], [r['func']], cons(rv), ics) rv = rv.subs(solved_constants) else: rv1 = [] for s in rv: try: solved_constants = solve_ics([s], [r['func']], cons(s), ics) except ValueError: continue rv1.append(s.subs(solved_constants)) if len(rv1) == 1: return rv1[0] rv = rv1 return rv def solve_ics(sols, funcs, constants, ics): """ Solve for the constants given initial conditions ``sols`` is a list of solutions. ``funcs`` is a list of functions. ``constants`` is a list of constants. ``ics`` is the set of initial/boundary conditions for the differential equation. It should be given in the form of ``{f(x0): x1, f(x).diff(x).subs(x, x2): x3}`` and so on. Returns a dictionary mapping constants to values. ``solution.subs(constants)`` will replace the constants in ``solution``. Example ======= >>> # From dsolve(f(x).diff(x) - f(x), f(x)) >>> from sympy import symbols, Eq, exp, Function >>> from sympy.solvers.ode.ode import solve_ics >>> f = Function('f') >>> x, C1 = symbols('x C1') >>> sols = [Eq(f(x), C1*exp(x))] >>> funcs = [f(x)] >>> constants = [C1] >>> ics = {f(0): 2} >>> solved_constants = solve_ics(sols, funcs, constants, ics) >>> solved_constants {C1: 2} >>> sols[0].subs(solved_constants) Eq(f(x), 2*exp(x)) """ # Assume ics are of the form f(x0): value or Subs(diff(f(x), x, n), (x, # x0)): value (currently checked by classify_ode). To solve, replace x # with x0, f(x0) with value, then solve for constants. For f^(n)(x0), # differentiate the solution n times, so that f^(n)(x) appears. x = funcs[0].args[0] diff_sols = [] subs_sols = [] diff_variables = set() for funcarg, value in ics.items(): if isinstance(funcarg, AppliedUndef): x0 = funcarg.args[0] matching_func = [f for f in funcs if f.func == funcarg.func][0] S = sols elif isinstance(funcarg, (Subs, Derivative)): if isinstance(funcarg, Subs): # Make sure it stays a subs. Otherwise subs below will produce # a different looking term. funcarg = funcarg.doit() if isinstance(funcarg, Subs): deriv = funcarg.expr x0 = funcarg.point[0] variables = funcarg.expr.variables matching_func = deriv elif isinstance(funcarg, Derivative): deriv = funcarg x0 = funcarg.variables[0] variables = (x,)*len(funcarg.variables) matching_func = deriv.subs(x0, x) if variables not in diff_variables: for sol in sols: if sol.has(deriv.expr.func): diff_sols.append(Eq(sol.lhs.diff(*variables), sol.rhs.diff(*variables))) diff_variables.add(variables) S = diff_sols else: raise NotImplementedError("Unrecognized initial condition") for sol in S: if sol.has(matching_func): sol2 = sol sol2 = sol2.subs(x, x0) sol2 = sol2.subs(funcarg, value) # This check is necessary because of issue #15724 if not isinstance(sol2, BooleanAtom) or not subs_sols: subs_sols = [s for s in subs_sols if not isinstance(s, BooleanAtom)] subs_sols.append(sol2) # TODO: Use solveset here try: solved_constants = solve(subs_sols, constants, dict=True) except NotImplementedError: solved_constants = [] # XXX: We can't differentiate between the solution not existing because of # invalid initial conditions, and not existing because solve is not smart # enough. If we could use solveset, this might be improvable, but for now, # we use NotImplementedError in this case. if not solved_constants: raise ValueError("Couldn't solve for initial conditions") if solved_constants == True: raise ValueError("Initial conditions did not produce any solutions for constants. Perhaps they are degenerate.") if len(solved_constants) > 1: raise NotImplementedError("Initial conditions produced too many solutions for constants") return solved_constants[0] def classify_ode(eq, func=None, dict=False, ics=None, *, prep=True, xi=None, eta=None, n=None, **kwargs): r""" Returns a tuple of possible :py:meth:`~sympy.solvers.ode.dsolve` classifications for an ODE. The tuple is ordered so that first item is the classification that :py:meth:`~sympy.solvers.ode.dsolve` uses to solve the ODE by default. In general, classifications at the near the beginning of the list will produce better solutions faster than those near the end, thought there are always exceptions. To make :py:meth:`~sympy.solvers.ode.dsolve` use a different classification, use ``dsolve(ODE, func, hint=<classification>)``. See also the :py:meth:`~sympy.solvers.ode.dsolve` docstring for different meta-hints you can use. If ``dict`` is true, :py:meth:`~sympy.solvers.ode.classify_ode` will return a dictionary of ``hint:match`` expression terms. This is intended for internal use by :py:meth:`~sympy.solvers.ode.dsolve`. Note that because dictionaries are ordered arbitrarily, this will most likely not be in the same order as the tuple. You can get help on different hints by executing ``help(ode.ode_hintname)``, where ``hintname`` is the name of the hint without ``_Integral``. See :py:data:`~sympy.solvers.ode.allhints` or the :py:mod:`~sympy.solvers.ode` docstring for a list of all supported hints that can be returned from :py:meth:`~sympy.solvers.ode.classify_ode`. Notes ===== These are remarks on hint names. ``_Integral`` If a classification has ``_Integral`` at the end, it will return the expression with an unevaluated :py:class:`~.Integral` class in it. Note that a hint may do this anyway if :py:meth:`~sympy.core.expr.Expr.integrate` cannot do the integral, though just using an ``_Integral`` will do so much faster. Indeed, an ``_Integral`` hint will always be faster than its corresponding hint without ``_Integral`` because :py:meth:`~sympy.core.expr.Expr.integrate` is an expensive routine. If :py:meth:`~sympy.solvers.ode.dsolve` hangs, it is probably because :py:meth:`~sympy.core.expr.Expr.integrate` is hanging on a tough or impossible integral. Try using an ``_Integral`` hint or ``all_Integral`` to get it return something. Note that some hints do not have ``_Integral`` counterparts. This is because :py:func:`~sympy.integrals.integrals.integrate` is not used in solving the ODE for those method. For example, `n`\th order linear homogeneous ODEs with constant coefficients do not require integration to solve, so there is no ``nth_linear_homogeneous_constant_coeff_Integrate`` hint. You can easily evaluate any unevaluated :py:class:`~sympy.integrals.integrals.Integral`\s in an expression by doing ``expr.doit()``. Ordinals Some hints contain an ordinal such as ``1st_linear``. This is to help differentiate them from other hints, as well as from other methods that may not be implemented yet. If a hint has ``nth`` in it, such as the ``nth_linear`` hints, this means that the method used to applies to ODEs of any order. ``indep`` and ``dep`` Some hints contain the words ``indep`` or ``dep``. These reference the independent variable and the dependent function, respectively. For example, if an ODE is in terms of `f(x)`, then ``indep`` will refer to `x` and ``dep`` will refer to `f`. ``subs`` If a hints has the word ``subs`` in it, it means the the ODE is solved by substituting the expression given after the word ``subs`` for a single dummy variable. This is usually in terms of ``indep`` and ``dep`` as above. The substituted expression will be written only in characters allowed for names of Python objects, meaning operators will be spelled out. For example, ``indep``/``dep`` will be written as ``indep_div_dep``. ``coeff`` The word ``coeff`` in a hint refers to the coefficients of something in the ODE, usually of the derivative terms. See the docstring for the individual methods for more info (``help(ode)``). This is contrast to ``coefficients``, as in ``undetermined_coefficients``, which refers to the common name of a method. ``_best`` Methods that have more than one fundamental way to solve will have a hint for each sub-method and a ``_best`` meta-classification. This will evaluate all hints and return the best, using the same considerations as the normal ``best`` meta-hint. Examples ======== >>> from sympy import Function, classify_ode, Eq >>> from sympy.abc import x >>> f = Function('f') >>> classify_ode(Eq(f(x).diff(x), 0), f(x)) ('nth_algebraic', 'separable', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_homogeneous', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_linear_Integral', 'Bernoulli_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') >>> classify_ode(f(x).diff(x, 2) + 3*f(x).diff(x) + 2*f(x) - 4) ('nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', 'nth_linear_constant_coeff_variation_of_parameters_Integral') """ ics = sympify(ics) if func and len(func.args) != 1: raise ValueError("dsolve() and classify_ode() only " "work with functions of one variable, not %s" % func) if isinstance(eq, Equality): eq = eq.lhs - eq.rhs # Some methods want the unprocessed equation eq_orig = eq if prep or func is None: eq, func_ = _preprocess(eq, func) if func is None: func = func_ x = func.args[0] f = func.func y = Dummy('y') terms = n order = ode_order(eq, f(x)) # hint:matchdict or hint:(tuple of matchdicts) # Also will contain "default":<default hint> and "order":order items. matching_hints = {"order": order} df = f(x).diff(x) a = Wild('a', exclude=[f(x)]) d = Wild('d', exclude=[df, f(x).diff(x, 2)]) e = Wild('e', exclude=[df]) k = Wild('k', exclude=[df]) n = Wild('n', exclude=[x, f(x), df]) c1 = Wild('c1', exclude=[x]) a3 = Wild('a3', exclude=[f(x), df, f(x).diff(x, 2)]) b3 = Wild('b3', exclude=[f(x), df, f(x).diff(x, 2)]) c3 = Wild('c3', exclude=[f(x), df, f(x).diff(x, 2)]) r3 = {'xi': xi, 'eta': eta} # Used for the lie_group hint boundary = {} # Used to extract initial conditions C1 = Symbol("C1") # Preprocessing to get the initial conditions out if ics is not None: for funcarg in ics: # Separating derivatives if isinstance(funcarg, (Subs, Derivative)): # f(x).diff(x).subs(x, 0) is a Subs, but f(x).diff(x).subs(x, # y) is a Derivative if isinstance(funcarg, Subs): deriv = funcarg.expr old = funcarg.variables[0] new = funcarg.point[0] elif isinstance(funcarg, Derivative): deriv = funcarg # No information on this. Just assume it was x old = x new = funcarg.variables[0] if (isinstance(deriv, Derivative) and isinstance(deriv.args[0], AppliedUndef) and deriv.args[0].func == f and len(deriv.args[0].args) == 1 and old == x and not new.has(x) and all(i == deriv.variables[0] for i in deriv.variables) and not ics[funcarg].has(f)): dorder = ode_order(deriv, x) temp = 'f' + str(dorder) boundary.update({temp: new, temp + 'val': ics[funcarg]}) else: raise ValueError("Enter valid boundary conditions for Derivatives") # Separating functions elif isinstance(funcarg, AppliedUndef): if (funcarg.func == f and len(funcarg.args) == 1 and not funcarg.args[0].has(x) and not ics[funcarg].has(f)): boundary.update({'f0': funcarg.args[0], 'f0val': ics[funcarg]}) else: raise ValueError("Enter valid boundary conditions for Function") else: raise ValueError("Enter boundary conditions of the form ics={f(point}: value, f(x).diff(x, order).subs(x, point): value}") # Any ODE that can be solved with a combination of algebra and # integrals e.g.: # d^3/dx^3(x y) = F(x) ode = SingleODEProblem(eq_orig, func, x, prep=prep) solvers = { NthAlgebraic: ('nth_algebraic',), FirstLinear: ('1st_linear',), AlmostLinear: ('almost_linear',), Bernoulli: ('Bernoulli',), Factorable: ('factorable',), RiccatiSpecial: ('Riccati_special_minus2',), } for solvercls in solvers: solver = solvercls(ode) if solver.matches(): for hints in solvers[solvercls]: matching_hints[hints] = solver if solvercls.has_integral: matching_hints[hints + "_Integral"] = solver eq = expand(eq) # Precondition to try remove f(x) from highest order derivative reduced_eq = None if eq.is_Add: deriv_coef = eq.coeff(f(x).diff(x, order)) if deriv_coef not in (1, 0): r = deriv_coef.match(a*f(x)**c1) if r and r[c1]: den = f(x)**r[c1] reduced_eq = Add(*[arg/den for arg in eq.args]) if not reduced_eq: reduced_eq = eq if order == 1: # NON-REDUCED FORM OF EQUATION matches r = collect(eq, df, exact=True).match(d + e * df) if r: r['d'] = d r['e'] = e r['y'] = y r[d] = r[d].subs(f(x), y) r[e] = r[e].subs(f(x), y) # FIRST ORDER POWER SERIES WHICH NEEDS INITIAL CONDITIONS # TODO: Hint first order series should match only if d/e is analytic. # For now, only d/e and (d/e).diff(arg) is checked for existence at # at a given point. # This is currently done internally in ode_1st_power_series. point = boundary.get('f0', 0) value = boundary.get('f0val', C1) check = cancel(r[d]/r[e]) check1 = check.subs({x: point, y: value}) if not check1.has(oo) and not check1.has(zoo) and \ not check1.has(NaN) and not check1.has(-oo): check2 = (check1.diff(x)).subs({x: point, y: value}) if not check2.has(oo) and not check2.has(zoo) and \ not check2.has(NaN) and not check2.has(-oo): rseries = r.copy() rseries.update({'terms': terms, 'f0': point, 'f0val': value}) matching_hints["1st_power_series"] = rseries r3.update(r) ## Exact Differential Equation: P(x, y) + Q(x, y)*y' = 0 where # dP/dy == dQ/dx try: if r[d] != 0: numerator = simplify(r[d].diff(y) - r[e].diff(x)) # The following few conditions try to convert a non-exact # differential equation into an exact one. # References : Differential equations with applications # and historical notes - George E. Simmons if numerator: # If (dP/dy - dQ/dx) / Q = f(x) # then exp(integral(f(x))*equation becomes exact factor = simplify(numerator/r[e]) variables = factor.free_symbols if len(variables) == 1 and x == variables.pop(): factor = exp(Integral(factor).doit()) r[d] *= factor r[e] *= factor matching_hints["1st_exact"] = r matching_hints["1st_exact_Integral"] = r else: # If (dP/dy - dQ/dx) / -P = f(y) # then exp(integral(f(y))*equation becomes exact factor = simplify(-numerator/r[d]) variables = factor.free_symbols if len(variables) == 1 and y == variables.pop(): factor = exp(Integral(factor).doit()) r[d] *= factor r[e] *= factor matching_hints["1st_exact"] = r matching_hints["1st_exact_Integral"] = r else: matching_hints["1st_exact"] = r matching_hints["1st_exact_Integral"] = r except NotImplementedError: # Differentiating the coefficients might fail because of things # like f(2*x).diff(x). See issue 4624 and issue 4719. pass # Any first order ODE can be ideally solved by the Lie Group # method matching_hints["lie_group"] = r3 # This match is used for several cases below; we now collect on # f(x) so the matching works. r = collect(reduced_eq, df, exact=True).match(d + e*df) if r: # Using r[d] and r[e] without any modification for hints # linear-coefficients and separable-reduced. num, den = r[d], r[e] # ODE = d/e + df r['d'] = d r['e'] = e r['y'] = y r[d] = num.subs(f(x), y) r[e] = den.subs(f(x), y) ## Separable Case: y' == P(y)*Q(x) r[d] = separatevars(r[d]) r[e] = separatevars(r[e]) # m1[coeff]*m1[x]*m1[y] + m2[coeff]*m2[x]*m2[y]*y' m1 = separatevars(r[d], dict=True, symbols=(x, y)) m2 = separatevars(r[e], dict=True, symbols=(x, y)) if m1 and m2: r1 = {'m1': m1, 'm2': m2, 'y': y} matching_hints["separable"] = r1 matching_hints["separable_Integral"] = r1 ## First order equation with homogeneous coefficients: # dy/dx == F(y/x) or dy/dx == F(x/y) ordera = homogeneous_order(r[d], x, y) if ordera is not None: orderb = homogeneous_order(r[e], x, y) if ordera == orderb: # u1=y/x and u2=x/y u1 = Dummy('u1') u2 = Dummy('u2') s = "1st_homogeneous_coeff_subs" s1 = s + "_dep_div_indep" s2 = s + "_indep_div_dep" if simplify((r[d] + u1*r[e]).subs({x: 1, y: u1})) != 0: matching_hints[s1] = r matching_hints[s1 + "_Integral"] = r if simplify((r[e] + u2*r[d]).subs({x: u2, y: 1})) != 0: matching_hints[s2] = r matching_hints[s2 + "_Integral"] = r if s1 in matching_hints and s2 in matching_hints: matching_hints["1st_homogeneous_coeff_best"] = r ## Linear coefficients of the form # y'+ F((a*x + b*y + c)/(a'*x + b'y + c')) = 0 # that can be reduced to homogeneous form. F = num/den params = _linear_coeff_match(F, func) if params: xarg, yarg = params u = Dummy('u') t = Dummy('t') # Dummy substitution for df and f(x). dummy_eq = reduced_eq.subs(((df, t), (f(x), u))) reps = ((x, x + xarg), (u, u + yarg), (t, df), (u, f(x))) dummy_eq = simplify(dummy_eq.subs(reps)) # get the re-cast values for e and d r2 = collect(expand(dummy_eq), [df, f(x)]).match(e*df + d) if r2: orderd = homogeneous_order(r2[d], x, f(x)) if orderd is not None: ordere = homogeneous_order(r2[e], x, f(x)) if orderd == ordere: # Match arguments are passed in such a way that it # is coherent with the already existing homogeneous # functions. r2[d] = r2[d].subs(f(x), y) r2[e] = r2[e].subs(f(x), y) r2.update({'xarg': xarg, 'yarg': yarg, 'd': d, 'e': e, 'y': y}) matching_hints["linear_coefficients"] = r2 matching_hints["linear_coefficients_Integral"] = r2 ## Equation of the form y' + (y/x)*H(x^n*y) = 0 # that can be reduced to separable form factor = simplify(x/f(x)*num/den) # Try representing factor in terms of x^n*y # where n is lowest power of x in factor; # first remove terms like sqrt(2)*3 from factor.atoms(Mul) num, dem = factor.as_numer_denom() num = expand(num) dem = expand(dem) def _degree(expr, x): # Made this function to calculate the degree of # x in an expression. If expr will be of form # x**p*y, (wheare p can be variables/rationals) then it # will return p. for val in expr: if val.has(x): if isinstance(val, Pow) and val.as_base_exp()[0] == x: return (val.as_base_exp()[1]) elif val == x: return (val.as_base_exp()[1]) else: return _degree(val.args, x) return 0 def _powers(expr): # this function will return all the different relative power of x w.r.t f(x). # expr = x**p * f(x)**q then it will return {p/q}. pows = set() if isinstance(expr, Add): exprs = expr.atoms(Add) elif isinstance(expr, Mul): exprs = expr.atoms(Mul) elif isinstance(expr, Pow): exprs = expr.atoms(Pow) else: exprs = {expr} for arg in exprs: if arg.has(x): _, u = arg.as_independent(x, f(x)) pow = _degree((u.subs(f(x), y), ), x)/_degree((u.subs(f(x), y), ), y) pows.add(pow) return pows pows = _powers(num) pows.update(_powers(dem)) pows = list(pows) if(len(pows)==1) and pows[0]!=zoo: t = Dummy('t') r2 = {'t': t} num = num.subs(x**pows[0]*f(x), t) dem = dem.subs(x**pows[0]*f(x), t) test = num/dem free = test.free_symbols if len(free) == 1 and free.pop() == t: r2.update({'power' : pows[0], 'u' : test}) matching_hints['separable_reduced'] = r2 matching_hints["separable_reduced_Integral"] = r2 elif order == 2: # Liouville ODE in the form # f(x).diff(x, 2) + g(f(x))*(f(x).diff(x))**2 + h(x)*f(x).diff(x) # See Goldstein and Braun, "Advanced Methods for the Solution of # Differential Equations", pg. 98 s = d*f(x).diff(x, 2) + e*df**2 + k*df r = reduced_eq.match(s) if r and r[d] != 0: y = Dummy('y') g = simplify(r[e]/r[d]).subs(f(x), y) h = simplify(r[k]/r[d]).subs(f(x), y) if y in h.free_symbols or x in g.free_symbols: pass else: r = {'g': g, 'h': h, 'y': y} matching_hints["Liouville"] = r matching_hints["Liouville_Integral"] = r # Homogeneous second order differential equation of the form # a3*f(x).diff(x, 2) + b3*f(x).diff(x) + c3 # It has a definite power series solution at point x0 if, b3/a3 and c3/a3 # are analytic at x0. deq = a3*(f(x).diff(x, 2)) + b3*df + c3*f(x) r = collect(reduced_eq, [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq) ordinary = False if r: if not all([r[key].is_polynomial() for key in r]): n, d = reduced_eq.as_numer_denom() reduced_eq = expand(n) r = collect(reduced_eq, [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq) if r and r[a3] != 0: p = cancel(r[b3]/r[a3]) # Used below q = cancel(r[c3]/r[a3]) # Used below point = kwargs.get('x0', 0) check = p.subs(x, point) if not check.has(oo, NaN, zoo, -oo): check = q.subs(x, point) if not check.has(oo, NaN, zoo, -oo): ordinary = True r.update({'a3': a3, 'b3': b3, 'c3': c3, 'x0': point, 'terms': terms}) matching_hints["2nd_power_series_ordinary"] = r # Checking if the differential equation has a regular singular point # at x0. It has a regular singular point at x0, if (b3/a3)*(x - x0) # and (c3/a3)*((x - x0)**2) are analytic at x0. if not ordinary: p = cancel((x - point)*p) check = p.subs(x, point) if not check.has(oo, NaN, zoo, -oo): q = cancel(((x - point)**2)*q) check = q.subs(x, point) if not check.has(oo, NaN, zoo, -oo): coeff_dict = {'p': p, 'q': q, 'x0': point, 'terms': terms} matching_hints["2nd_power_series_regular"] = coeff_dict # For Hypergeometric solutions. _r = {} _r.update(r) rn = match_2nd_hypergeometric(_r, func) if rn: matching_hints["2nd_hypergeometric"] = rn matching_hints["2nd_hypergeometric_Integral"] = rn # If the ODE has regular singular point at x0 and is of the form # Eq((x)**2*Derivative(y(x), x, x) + x*Derivative(y(x), x) + # (a4**2*x**(2*p)-n**2)*y(x) thus Bessel's equation rn = match_2nd_linear_bessel(r, f(x)) if rn: matching_hints["2nd_linear_bessel"] = rn # If the ODE is ordinary and is of the form of Airy's Equation # Eq(x**2*Derivative(y(x),x,x)-(ax+b)*y(x)) if p.is_zero: a4 = Wild('a4', exclude=[x,f(x),df]) b4 = Wild('b4', exclude=[x,f(x),df]) rn = q.match(a4+b4*x) if rn and rn[b4] != 0: rn = {'b':rn[a4],'m':rn[b4]} matching_hints["2nd_linear_airy"] = rn if order > 0: # Any ODE that can be solved with a substitution and # repeated integration e.g.: # `d^2/dx^2(y) + x*d/dx(y) = constant #f'(x) must be finite for this to work r = _nth_order_reducible_match(reduced_eq, func) if r: matching_hints['nth_order_reducible'] = r # nth order linear ODE # a_n(x)y^(n) + ... + a_1(x)y' + a_0(x)y = F(x) = b r = _nth_linear_match(reduced_eq, func, order) # Constant coefficient case (a_i is constant for all i) if r and not any(r[i].has(x) for i in r if i >= 0): # Inhomogeneous case: F(x) is not identically 0 if r[-1]: eq_homogeneous = Add(eq,-r[-1]) undetcoeff = _undetermined_coefficients_match(r[-1], x, func, eq_homogeneous) s = "nth_linear_constant_coeff_variation_of_parameters" matching_hints[s] = r matching_hints[s + "_Integral"] = r if undetcoeff['test']: r['trialset'] = undetcoeff['trialset'] matching_hints[ "nth_linear_constant_coeff_undetermined_coefficients" ] = r # Homogeneous case: F(x) is identically 0 else: matching_hints["nth_linear_constant_coeff_homogeneous"] = r # nth order Euler equation a_n*x**n*y^(n) + ... + a_1*x*y' + a_0*y = F(x) #In case of Homogeneous euler equation F(x) = 0 def _test_term(coeff, order): r""" Linear Euler ODEs have the form K*x**order*diff(y(x),x,order) = F(x), where K is independent of x and y(x), order>= 0. So we need to check that for each term, coeff == K*x**order from some K. We have a few cases, since coeff may have several different types. """ if order < 0: raise ValueError("order should be greater than 0") if coeff == 0: return True if order == 0: if x in coeff.free_symbols: return False return True if coeff.is_Mul: if coeff.has(f(x)): return False return x**order in coeff.args elif coeff.is_Pow: return coeff.as_base_exp() == (x, order) elif order == 1: return x == coeff return False # Find coefficient for highest derivative, multiply coefficients to # bring the equation into Euler form if possible r_rescaled = None if r is not None: coeff = r[order] factor = x**order / coeff r_rescaled = {i: factor*r[i] for i in r if i != 'trialset'} # XXX: Mixing up the trialset with the coefficients is error-prone. # These should be separated as something like r['coeffs'] and # r['trialset'] if r_rescaled and not any(not _test_term(r_rescaled[i], i) for i in r_rescaled if i != 'trialset' and i >= 0): if not r_rescaled[-1]: matching_hints["nth_linear_euler_eq_homogeneous"] = r_rescaled else: matching_hints["nth_linear_euler_eq_nonhomogeneous_variation_of_parameters"] = r_rescaled matching_hints["nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral"] = r_rescaled e, re = posify(r_rescaled[-1].subs(x, exp(x))) undetcoeff = _undetermined_coefficients_match(e.subs(re), x) if undetcoeff['test']: r_rescaled['trialset'] = undetcoeff['trialset'] matching_hints["nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients"] = r_rescaled # Order keys based on allhints. retlist = [i for i in allhints if i in matching_hints] if dict: # Dictionaries are ordered arbitrarily, so make note of which # hint would come first for dsolve(). Use an ordered dict in Py 3. matching_hints["default"] = retlist[0] if retlist else None matching_hints["ordered_hints"] = tuple(retlist) return matching_hints else: return tuple(retlist) def equivalence(max_num_pow, dem_pow): # this function is made for checking the equivalence with 2F1 type of equation. # max_num_pow is the value of maximum power of x in numerator # and dem_pow is list of powers of different factor of form (a*x b). # reference from table 1 in paper - "Non-Liouvillian solutions for second order # linear ODEs" by L. Chan, E.S. Cheb-Terrab. # We can extend it for 1F1 and 0F1 type also. if max_num_pow == 2: if dem_pow in [[2, 2], [2, 2, 2]]: return "2F1" elif max_num_pow == 1: if dem_pow in [[1, 2, 2], [2, 2, 2], [1, 2], [2, 2]]: return "2F1" elif max_num_pow == 0: if dem_pow in [[1, 1, 2], [2, 2], [1 ,2, 2], [1, 1], [2], [1, 2], [2, 2]]: return "2F1" return None def equivalence_hypergeometric(A, B, func): from sympy import factor # This method for finding the equivalence is only for 2F1 type. # We can extend it for 1F1 and 0F1 type also. x = func.args[0] # making given equation in normal form I1 = factor(cancel(A.diff(x)/2 + A**2/4 - B)) # computing shifted invariant(J1) of the equation J1 = factor(cancel(x**2*I1 + S(1)/4)) num, dem = J1.as_numer_denom() num = powdenest(expand(num)) dem = powdenest(expand(dem)) pow_num = set() pow_dem = set() # this function will compute the different powers of variable(x) in J1. # then it will help in finding value of k. k is power of x such that we can express # J1 = x**k * J0(x**k) then all the powers in J0 become integers. def _power_counting(num): _pow = {0} for val in num: if val.has(x): if isinstance(val, Pow) and val.as_base_exp()[0] == x: _pow.add(val.as_base_exp()[1]) elif val == x: _pow.add(val.as_base_exp()[1]) else: _pow.update(_power_counting(val.args)) return _pow pow_num = _power_counting((num, )) pow_dem = _power_counting((dem, )) pow_dem.update(pow_num) _pow = pow_dem k = gcd(_pow) # computing I0 of the given equation I0 = powdenest(simplify(factor(((J1/k**2) - S(1)/4)/((x**k)**2))), force=True) I0 = factor(cancel(powdenest(I0.subs(x, x**(S(1)/k)), force=True))) num, dem = I0.as_numer_denom() max_num_pow = max(_power_counting((num, ))) dem_args = dem.args sing_point = [] dem_pow = [] # calculating singular point of I0. for arg in dem_args: if arg.has(x): if isinstance(arg, Pow): # (x-a)**n dem_pow.append(arg.as_base_exp()[1]) sing_point.append(list(roots(arg.as_base_exp()[0], x).keys())[0]) else: # (x-a) type dem_pow.append(arg.as_base_exp()[1]) sing_point.append(list(roots(arg, x).keys())[0]) dem_pow.sort() # checking if equivalence is exists or not. if equivalence(max_num_pow, dem_pow) == "2F1": return {'I0':I0, 'k':k, 'sing_point':sing_point, 'type':"2F1"} else: return None def ode_2nd_hypergeometric(eq, func, order, match): from sympy.simplify.hyperexpand import hyperexpand from sympy import factor x = func.args[0] C0, C1 = get_numbered_constants(eq, num=2) a = match['a'] b = match['b'] c = match['c'] A = match['A'] # B = match['B'] sol = None if match['type'] == "2F1": if c.is_integer == False: sol = C0*hyper([a, b], [c], x) + C1*hyper([a-c+1, b-c+1], [2-c], x)*x**(1-c) elif c == 1: y2 = Integral(exp(Integral((-(a+b+1)*x + c)/(x**2-x), x))/(hyperexpand(hyper([a, b], [c], x))**2), x)*hyper([a, b], [c], x) sol = C0*hyper([a, b], [c], x) + C1*y2 elif (c-a-b).is_integer == False: sol = C0*hyper([a, b], [1+a+b-c], 1-x) + C1*hyper([c-a, c-b], [1+c-a-b], 1-x)*(1-x)**(c-a-b) if sol is None: raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by" + " the hypergeometric method") # applying transformation in the solution subs = match['mobius'] dtdx = simplify(1/(subs.diff(x))) _B = ((a + b + 1)*x - c).subs(x, subs)*dtdx _B = factor(_B + ((x**2 -x).subs(x, subs))*(dtdx.diff(x)*dtdx)) _A = factor((x**2 - x).subs(x, subs)*(dtdx**2)) e = exp(logcombine(Integral(cancel(_B/(2*_A)), x), force=True)) sol = sol.subs(x, match['mobius']) sol = sol.subs(x, x**match['k']) e = e.subs(x, x**match['k']) if not A.is_zero: e1 = Integral(A/2, x) e1 = exp(logcombine(e1, force=True)) sol = cancel((e/e1)*x**((-match['k']+1)/2))*sol sol = Eq(func, sol) return sol sol = cancel((e)*x**((-match['k']+1)/2))*sol sol = Eq(func, sol) return sol def match_2nd_2F1_hypergeometric(I, k, sing_point, func): from sympy import factor x = func.args[0] a = Wild("a") b = Wild("b") c = Wild("c") t = Wild("t") s = Wild("s") r = Wild("r") alpha = Wild("alpha") beta = Wild("beta") gamma = Wild("gamma") delta = Wild("delta") rn = {'type':None} # I0 of the standerd 2F1 equation. I0 = ((a-b+1)*(a-b-1)*x**2 + 2*((1-a-b)*c + 2*a*b)*x + c*(c-2))/(4*x**2*(x-1)**2) if sing_point != [0, 1]: # If singular point is [0, 1] then we have standerd equation. eqs = [] sing_eqs = [-beta/alpha, -delta/gamma, (delta-beta)/(alpha-gamma)] # making equations for the finding the mobius transformation for i in range(3): if i<len(sing_point): eqs.append(Eq(sing_eqs[i], sing_point[i])) else: eqs.append(Eq(1/sing_eqs[i], 0)) # solving above equations for the mobius transformation _beta = -alpha*sing_point[0] _delta = -gamma*sing_point[1] _gamma = alpha if len(sing_point) == 3: _gamma = (_beta + sing_point[2]*alpha)/(sing_point[2] - sing_point[1]) mob = (alpha*x + beta)/(gamma*x + delta) mob = mob.subs(beta, _beta) mob = mob.subs(delta, _delta) mob = mob.subs(gamma, _gamma) mob = cancel(mob) t = (beta - delta*x)/(gamma*x - alpha) t = cancel(((t.subs(beta, _beta)).subs(delta, _delta)).subs(gamma, _gamma)) else: mob = x t = x # applying mobius transformation in I to make it into I0. I = I.subs(x, t) I = I*(t.diff(x))**2 I = factor(I) dict_I = {x**2:0, x:0, 1:0} I0_num, I0_dem = I0.as_numer_denom() # collecting coeff of (x**2, x), of the standerd equation. # substituting (a-b) = s, (a+b) = r dict_I0 = {x**2:s**2 - 1, x:(2*(1-r)*c + (r+s)*(r-s)), 1:c*(c-2)} # collecting coeff of (x**2, x) from I0 of the given equation. dict_I.update(collect(expand(cancel(I*I0_dem)), [x**2, x], evaluate=False)) eqs = [] # We are comparing the coeff of powers of different x, for finding the values of # parameters of standerd equation. for key in [x**2, x, 1]: eqs.append(Eq(dict_I[key], dict_I0[key])) # We can have many possible roots for the equation. # I am selecting the root on the basis that when we have # standard equation eq = x*(x-1)*f(x).diff(x, 2) + ((a+b+1)*x-c)*f(x).diff(x) + a*b*f(x) # then root should be a, b, c. _c = 1 - factor(sqrt(1+eqs[2].lhs)) if not _c.has(Symbol): _c = min(list(roots(eqs[2], c))) _s = factor(sqrt(eqs[0].lhs + 1)) _r = _c - factor(sqrt(_c**2 + _s**2 + eqs[1].lhs - 2*_c)) _a = (_r + _s)/2 _b = (_r - _s)/2 rn = {'a':simplify(_a), 'b':simplify(_b), 'c':simplify(_c), 'k':k, 'mobius':mob, 'type':"2F1"} return rn def match_2nd_hypergeometric(r, func): x = func.args[0] a3 = Wild('a3', exclude=[func, func.diff(x), func.diff(x, 2)]) b3 = Wild('b3', exclude=[func, func.diff(x), func.diff(x, 2)]) c3 = Wild('c3', exclude=[func, func.diff(x), func.diff(x, 2)]) A = cancel(r[b3]/r[a3]) B = cancel(r[c3]/r[a3]) d = equivalence_hypergeometric(A, B, func) rn = None if d: if d['type'] == "2F1": rn = match_2nd_2F1_hypergeometric(d['I0'], d['k'], d['sing_point'], func) if rn is not None: rn.update({'A':A, 'B':B}) # We can extend it for 1F1 and 0F1 type also. return rn def match_2nd_linear_bessel(r, func): from sympy.polys.polytools import factor # eq = a3*f(x).diff(x, 2) + b3*f(x).diff(x) + c3*f(x) f = func x = func.args[0] df = f.diff(x) a = Wild('a', exclude=[f,df]) b = Wild('b', exclude=[x, f,df]) a4 = Wild('a4', exclude=[x,f,df]) b4 = Wild('b4', exclude=[x,f,df]) c4 = Wild('c4', exclude=[x,f,df]) d4 = Wild('d4', exclude=[x,f,df]) a3 = Wild('a3', exclude=[f, df, f.diff(x, 2)]) b3 = Wild('b3', exclude=[f, df, f.diff(x, 2)]) c3 = Wild('c3', exclude=[f, df, f.diff(x, 2)]) # leading coeff of f(x).diff(x, 2) coeff = factor(r[a3]).match(a4*(x-b)**b4) if coeff: # if coeff[b4] = 0 means constant coefficient if coeff[b4] == 0: return None point = coeff[b] else: return None if point: r[a3] = simplify(r[a3].subs(x, x+point)) r[b3] = simplify(r[b3].subs(x, x+point)) r[c3] = simplify(r[c3].subs(x, x+point)) # making a3 in the form of x**2 r[a3] = cancel(r[a3]/(coeff[a4]*(x)**(-2+coeff[b4]))) r[b3] = cancel(r[b3]/(coeff[a4]*(x)**(-2+coeff[b4]))) r[c3] = cancel(r[c3]/(coeff[a4]*(x)**(-2+coeff[b4]))) # checking if b3 is of form c*(x-b) coeff1 = factor(r[b3]).match(a4*(x)) if coeff1 is None: return None # c3 maybe of very complex form so I am simply checking (a - b) form # if yes later I will match with the standerd form of bessel in a and b # a, b are wild variable defined above. _coeff2 = r[c3].match(a - b) if _coeff2 is None: return None # matching with standerd form for c3 coeff2 = factor(_coeff2[a]).match(c4**2*(x)**(2*a4)) if coeff2 is None: return None if _coeff2[b] == 0: coeff2[d4] = 0 else: coeff2[d4] = factor(_coeff2[b]).match(d4**2)[d4] rn = {'n':coeff2[d4], 'a4':coeff2[c4], 'd4':coeff2[a4]} rn['c4'] = coeff1[a4] rn['b4'] = point return rn def classify_sysode(eq, funcs=None, **kwargs): r""" Returns a dictionary of parameter names and values that define the system of ordinary differential equations in ``eq``. The parameters are further used in :py:meth:`~sympy.solvers.ode.dsolve` for solving that system. Some parameter names and values are: 'is_linear' (boolean), which tells whether the given system is linear. Note that "linear" here refers to the operator: terms such as ``x*diff(x,t)`` are nonlinear, whereas terms like ``sin(t)*diff(x,t)`` are still linear operators. 'func' (list) contains the :py:class:`~sympy.core.function.Function`s that appear with a derivative in the ODE, i.e. those that we are trying to solve the ODE for. 'order' (dict) with the maximum derivative for each element of the 'func' parameter. 'func_coeff' (dict or Matrix) with the coefficient for each triple ``(equation number, function, order)```. The coefficients are those subexpressions that do not appear in 'func', and hence can be considered constant for purposes of ODE solving. The value of this parameter can also be a Matrix if the system of ODEs are linear first order of the form X' = AX where X is the vector of dependent variables. Here, this function returns the coefficient matrix A. 'eq' (list) with the equations from ``eq``, sympified and transformed into expressions (we are solving for these expressions to be zero). 'no_of_equations' (int) is the number of equations (same as ``len(eq)``). 'type_of_equation' (string) is an internal classification of the type of ODE. 'is_constant' (boolean), which tells if the system of ODEs is constant coefficient or not. This key is temporary addition for now and is in the match dict only when the system of ODEs is linear first order constant coefficient homogeneous. So, this key's value is True for now if it is available else it doesn't exist. 'is_homogeneous' (boolean), which tells if the system of ODEs is homogeneous. Like the key 'is_constant', this key is a temporary addition and it is True since this key value is available only when the system is linear first order constant coefficient homogeneous. References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode-toc1.htm -A. D. Polyanin and A. V. Manzhirov, Handbook of Mathematics for Engineers and Scientists Examples ======== >>> from sympy import Function, Eq, symbols, diff >>> from sympy.solvers.ode.ode import classify_sysode >>> from sympy.abc import t >>> f, x, y = symbols('f, x, y', cls=Function) >>> k, l, m, n = symbols('k, l, m, n', Integer=True) >>> x1 = diff(x(t), t) ; y1 = diff(y(t), t) >>> x2 = diff(x(t), t, t) ; y2 = diff(y(t), t, t) >>> eq = (Eq(x1, 12*x(t) - 6*y(t)), Eq(y1, 11*x(t) + 3*y(t))) >>> classify_sysode(eq) {'eq': [-12*x(t) + 6*y(t) + Derivative(x(t), t), -11*x(t) - 3*y(t) + Derivative(y(t), t)], 'func': [x(t), y(t)], 'func_coeff': {(0, x(t), 0): -12, (0, x(t), 1): 1, (0, y(t), 0): 6, (0, y(t), 1): 0, (1, x(t), 0): -11, (1, x(t), 1): 0, (1, y(t), 0): -3, (1, y(t), 1): 1}, 'is_linear': True, 'no_of_equation': 2, 'order': {x(t): 1, y(t): 1}, 'type_of_equation': None} >>> eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t) + 2), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t))) >>> classify_sysode(eq) {'eq': [-t**2*y(t) - 5*t*x(t) + Derivative(x(t), t) - 2, t**2*x(t) - 5*t*y(t) + Derivative(y(t), t)], 'func': [x(t), y(t)], 'func_coeff': {(0, x(t), 0): -5*t, (0, x(t), 1): 1, (0, y(t), 0): -t**2, (0, y(t), 1): 0, (1, x(t), 0): t**2, (1, x(t), 1): 0, (1, y(t), 0): -5*t, (1, y(t), 1): 1}, 'is_linear': True, 'no_of_equation': 2, 'order': {x(t): 1, y(t): 1}, 'type_of_equation': None} """ # Sympify equations and convert iterables of equations into # a list of equations def _sympify(eq): return list(map(sympify, eq if iterable(eq) else [eq])) eq, funcs = (_sympify(w) for w in [eq, funcs]) for i, fi in enumerate(eq): if isinstance(fi, Equality): eq[i] = fi.lhs - fi.rhs t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] matching_hints = {"no_of_equation":i+1} matching_hints['eq'] = eq if i==0: raise ValueError("classify_sysode() works for systems of ODEs. " "For scalar ODEs, classify_ode should be used") # find all the functions if not given order = dict() if funcs==[None]: funcs = _extract_funcs(eq) funcs = list(set(funcs)) if len(funcs) != len(eq): raise ValueError("Number of functions given is not equal to the number of equations %s" % funcs) # This logic of list of lists in funcs to # be replaced later. func_dict = dict() for func in funcs: if not order.get(func, False): max_order = 0 for i, eqs_ in enumerate(eq): order_ = ode_order(eqs_,func) if max_order < order_: max_order = order_ eq_no = i if eq_no in func_dict: func_dict[eq_no] = [func_dict[eq_no], func] else: func_dict[eq_no] = func order[func] = max_order funcs = [func_dict[i] for i in range(len(func_dict))] matching_hints['func'] = funcs for func in funcs: if isinstance(func, list): for func_elem in func: if len(func_elem.args) != 1: raise ValueError("dsolve() and classify_sysode() work with " "functions of one variable only, not %s" % func) else: if func and len(func.args) != 1: raise ValueError("dsolve() and classify_sysode() work with " "functions of one variable only, not %s" % func) # find the order of all equation in system of odes matching_hints["order"] = order # find coefficients of terms f(t), diff(f(t),t) and higher derivatives # and similarly for other functions g(t), diff(g(t),t) in all equations. # Here j denotes the equation number, funcs[l] denotes the function about # which we are talking about and k denotes the order of function funcs[l] # whose coefficient we are calculating. def linearity_check(eqs, j, func, is_linear_): for k in range(order[func] + 1): func_coef[j, func, k] = collect(eqs.expand(), [diff(func, t, k)]).coeff(diff(func, t, k)) if is_linear_ == True: if func_coef[j, func, k] == 0: if k == 0: coef = eqs.as_independent(func, as_Add=True)[1] for xr in range(1, ode_order(eqs,func) + 1): coef -= eqs.as_independent(diff(func, t, xr), as_Add=True)[1] if coef != 0: is_linear_ = False else: if eqs.as_independent(diff(func, t, k), as_Add=True)[1]: is_linear_ = False else: for func_ in funcs: if isinstance(func_, list): for elem_func_ in func_: dep = func_coef[j, func, k].as_independent(elem_func_, as_Add=True)[1] if dep != 0: is_linear_ = False else: dep = func_coef[j, func, k].as_independent(func_, as_Add=True)[1] if dep != 0: is_linear_ = False return is_linear_ func_coef = {} is_linear = True for j, eqs in enumerate(eq): for func in funcs: if isinstance(func, list): for func_elem in func: is_linear = linearity_check(eqs, j, func_elem, is_linear) else: is_linear = linearity_check(eqs, j, func, is_linear) matching_hints['func_coeff'] = func_coef matching_hints['is_linear'] = is_linear if len(set(order.values())) == 1: order_eq = list(matching_hints['order'].values())[0] if matching_hints['is_linear'] == True: if matching_hints['no_of_equation'] == 2: if order_eq == 1: type_of_equation = check_linear_2eq_order1(eq, funcs, func_coef) else: type_of_equation = None # If the equation doesn't match up with any of the # general case solvers in systems.py and the number # of equations is greater than 2, then NotImplementedError # should be raised. else: type_of_equation = None else: if matching_hints['no_of_equation'] == 2: if order_eq == 1: type_of_equation = check_nonlinear_2eq_order1(eq, funcs, func_coef) else: type_of_equation = None elif matching_hints['no_of_equation'] == 3: if order_eq == 1: type_of_equation = check_nonlinear_3eq_order1(eq, funcs, func_coef) else: type_of_equation = None else: type_of_equation = None else: type_of_equation = None matching_hints['type_of_equation'] = type_of_equation return matching_hints def check_linear_2eq_order1(eq, func, func_coef): x = func[0].func y = func[1].func fc = func_coef t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] r = dict() # for equations Eq(a1*diff(x(t),t), b1*x(t) + c1*y(t) + d1) # and Eq(a2*diff(y(t),t), b2*x(t) + c2*y(t) + d2) r['a1'] = fc[0,x(t),1] ; r['a2'] = fc[1,y(t),1] r['b1'] = -fc[0,x(t),0]/fc[0,x(t),1] ; r['b2'] = -fc[1,x(t),0]/fc[1,y(t),1] r['c1'] = -fc[0,y(t),0]/fc[0,x(t),1] ; r['c2'] = -fc[1,y(t),0]/fc[1,y(t),1] forcing = [S.Zero,S.Zero] for i in range(2): for j in Add.make_args(eq[i]): if not j.has(x(t), y(t)): forcing[i] += j if not (forcing[0].has(t) or forcing[1].has(t)): # We can handle homogeneous case and simple constant forcings r['d1'] = forcing[0] r['d2'] = forcing[1] else: # Issue #9244: nonhomogeneous linear systems are not supported return None # Conditions to check for type 6 whose equations are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and # Eq(diff(y(t),t), a*[f(t) + a*h(t)]x(t) + a*[g(t) - h(t)]*y(t)) p = 0 q = 0 p1 = cancel(r['b2']/(cancel(r['b2']/r['c2']).as_numer_denom()[0])) p2 = cancel(r['b1']/(cancel(r['b1']/r['c1']).as_numer_denom()[0])) for n, i in enumerate([p1, p2]): for j in Mul.make_args(collect_const(i)): if not j.has(t): q = j if q and n==0: if ((r['b2']/j - r['b1'])/(r['c1'] - r['c2']/j)) == j: p = 1 elif q and n==1: if ((r['b1']/j - r['b2'])/(r['c2'] - r['c1']/j)) == j: p = 2 # End of condition for type 6 if r['d1']!=0 or r['d2']!=0: return None else: if all(not r[k].has(t) for k in 'a1 a2 b1 b2 c1 c2'.split()): return None else: r['b1'] = r['b1']/r['a1'] ; r['b2'] = r['b2']/r['a2'] r['c1'] = r['c1']/r['a1'] ; r['c2'] = r['c2']/r['a2'] if p: return "type6" else: # Equations for type 7 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), h(t)*x(t) + p(t)*y(t)) return "type7" def check_nonlinear_2eq_order1(eq, func, func_coef): t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] f = Wild('f') g = Wild('g') u, v = symbols('u, v', cls=Dummy) def check_type(x, y): r1 = eq[0].match(t*diff(x(t),t) - x(t) + f) r2 = eq[1].match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t) r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t) if not (r1 and r2): r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f) r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t) r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t) if r1 and r2 and not (r1[f].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t) \ or r2[g].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t)): return 'type5' else: return None for func_ in func: if isinstance(func_, list): x = func[0][0].func y = func[0][1].func eq_type = check_type(x, y) if not eq_type: eq_type = check_type(y, x) return eq_type x = func[0].func y = func[1].func fc = func_coef n = Wild('n', exclude=[x(t),y(t)]) f1 = Wild('f1', exclude=[v,t]) f2 = Wild('f2', exclude=[v,t]) g1 = Wild('g1', exclude=[u,t]) g2 = Wild('g2', exclude=[u,t]) for i in range(2): eqs = 0 for terms in Add.make_args(eq[i]): eqs += terms/fc[i,func[i],1] eq[i] = eqs r = eq[0].match(diff(x(t),t) - x(t)**n*f) if r: g = (diff(y(t),t) - eq[1])/r[f] if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)): return 'type1' r = eq[0].match(diff(x(t),t) - exp(n*x(t))*f) if r: g = (diff(y(t),t) - eq[1])/r[f] if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)): return 'type2' g = Wild('g') r1 = eq[0].match(diff(x(t),t) - f) r2 = eq[1].match(diff(y(t),t) - g) if r1 and r2 and not (r1[f].subs(x(t),u).subs(y(t),v).has(t) or \ r2[g].subs(x(t),u).subs(y(t),v).has(t)): return 'type3' r1 = eq[0].match(diff(x(t),t) - f) r2 = eq[1].match(diff(y(t),t) - g) num, den = ( (r1[f].subs(x(t),u).subs(y(t),v))/ (r2[g].subs(x(t),u).subs(y(t),v))).as_numer_denom() R1 = num.match(f1*g1) R2 = den.match(f2*g2) # phi = (r1[f].subs(x(t),u).subs(y(t),v))/num if R1 and R2: return 'type4' return None def check_nonlinear_2eq_order2(eq, func, func_coef): return None def check_nonlinear_3eq_order1(eq, func, func_coef): x = func[0].func y = func[1].func z = func[2].func fc = func_coef t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] u, v, w = symbols('u, v, w', cls=Dummy) a = Wild('a', exclude=[x(t), y(t), z(t), t]) b = Wild('b', exclude=[x(t), y(t), z(t), t]) c = Wild('c', exclude=[x(t), y(t), z(t), t]) f = Wild('f') F1 = Wild('F1') F2 = Wild('F2') F3 = Wild('F3') for i in range(3): eqs = 0 for terms in Add.make_args(eq[i]): eqs += terms/fc[i,func[i],1] eq[i] = eqs r1 = eq[0].match(diff(x(t),t) - a*y(t)*z(t)) r2 = eq[1].match(diff(y(t),t) - b*z(t)*x(t)) r3 = eq[2].match(diff(z(t),t) - c*x(t)*y(t)) if r1 and r2 and r3: num1, den1 = r1[a].as_numer_denom() num2, den2 = r2[b].as_numer_denom() num3, den3 = r3[c].as_numer_denom() if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]): return 'type1' r = eq[0].match(diff(x(t),t) - y(t)*z(t)*f) if r: r1 = collect_const(r[f]).match(a*f) r2 = ((diff(y(t),t) - eq[1])/r1[f]).match(b*z(t)*x(t)) r3 = ((diff(z(t),t) - eq[2])/r1[f]).match(c*x(t)*y(t)) if r1 and r2 and r3: num1, den1 = r1[a].as_numer_denom() num2, den2 = r2[b].as_numer_denom() num3, den3 = r3[c].as_numer_denom() if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]): return 'type2' r = eq[0].match(diff(x(t),t) - (F2-F3)) if r: r1 = collect_const(r[F2]).match(c*F2) r1.update(collect_const(r[F3]).match(b*F3)) if r1: if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]): r1[F2], r1[F3] = r1[F3], r1[F2] r1[c], r1[b] = -r1[b], -r1[c] r2 = eq[1].match(diff(y(t),t) - a*r1[F3] + r1[c]*F1) if r2: r3 = (eq[2] == diff(z(t),t) - r1[b]*r2[F1] + r2[a]*r1[F2]) if r1 and r2 and r3: return 'type3' r = eq[0].match(diff(x(t),t) - z(t)*F2 + y(t)*F3) if r: r1 = collect_const(r[F2]).match(c*F2) r1.update(collect_const(r[F3]).match(b*F3)) if r1: if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]): r1[F2], r1[F3] = r1[F3], r1[F2] r1[c], r1[b] = -r1[b], -r1[c] r2 = (diff(y(t),t) - eq[1]).match(a*x(t)*r1[F3] - r1[c]*z(t)*F1) if r2: r3 = (diff(z(t),t) - eq[2] == r1[b]*y(t)*r2[F1] - r2[a]*x(t)*r1[F2]) if r1 and r2 and r3: return 'type4' r = (diff(x(t),t) - eq[0]).match(x(t)*(F2 - F3)) if r: r1 = collect_const(r[F2]).match(c*F2) r1.update(collect_const(r[F3]).match(b*F3)) if r1: if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]): r1[F2], r1[F3] = r1[F3], r1[F2] r1[c], r1[b] = -r1[b], -r1[c] r2 = (diff(y(t),t) - eq[1]).match(y(t)*(a*r1[F3] - r1[c]*F1)) if r2: r3 = (diff(z(t),t) - eq[2] == z(t)*(r1[b]*r2[F1] - r2[a]*r1[F2])) if r1 and r2 and r3: return 'type5' return None def check_nonlinear_3eq_order2(eq, func, func_coef): return None @vectorize(0) def odesimp(ode, eq, func, hint): r""" Simplifies solutions of ODEs, including trying to solve for ``func`` and running :py:meth:`~sympy.solvers.ode.constantsimp`. It may use knowledge of the type of solution that the hint returns to apply additional simplifications. It also attempts to integrate any :py:class:`~sympy.integrals.integrals.Integral`\s in the expression, if the hint is not an ``_Integral`` hint. This function should have no effect on expressions returned by :py:meth:`~sympy.solvers.ode.dsolve`, as :py:meth:`~sympy.solvers.ode.dsolve` already calls :py:meth:`~sympy.solvers.ode.ode.odesimp`, but the individual hint functions do not call :py:meth:`~sympy.solvers.ode.ode.odesimp` (because the :py:meth:`~sympy.solvers.ode.dsolve` wrapper does). Therefore, this function is designed for mainly internal use. Examples ======== >>> from sympy import sin, symbols, dsolve, pprint, Function >>> from sympy.solvers.ode.ode import odesimp >>> x , u2, C1= symbols('x,u2,C1') >>> f = Function('f') >>> eq = dsolve(x*f(x).diff(x) - f(x) - x*sin(f(x)/x), f(x), ... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral', ... simplify=False) >>> pprint(eq, wrap_line=False) x ---- f(x) / | | / 1 \ | -|u2 + -------| | | /1 \| | | sin|--|| | \ \u2// log(f(x)) = log(C1) + | ---------------- d(u2) | 2 | u2 | / >>> pprint(odesimp(eq, f(x), 1, {C1}, ... hint='1st_homogeneous_coeff_subs_indep_div_dep' ... )) #doctest: +SKIP x --------- = C1 /f(x)\ tan|----| \2*x / """ x = func.args[0] f = func.func C1 = get_numbered_constants(eq, num=1) constants = eq.free_symbols - ode.free_symbols # First, integrate if the hint allows it. eq = _handle_Integral(eq, func, hint) if hint.startswith("nth_linear_euler_eq_nonhomogeneous"): eq = simplify(eq) if not isinstance(eq, Equality): raise TypeError("eq should be an instance of Equality") # Second, clean up the arbitrary constants. # Right now, nth linear hints can put as many as 2*order constants in an # expression. If that number grows with another hint, the third argument # here should be raised accordingly, or constantsimp() rewritten to handle # an arbitrary number of constants. eq = constantsimp(eq, constants) # Lastly, now that we have cleaned up the expression, try solving for func. # When CRootOf is implemented in solve(), we will want to return a CRootOf # every time instead of an Equality. # Get the f(x) on the left if possible. if eq.rhs == func and not eq.lhs.has(func): eq = [Eq(eq.rhs, eq.lhs)] # make sure we are working with lists of solutions in simplified form. if eq.lhs == func and not eq.rhs.has(func): # The solution is already solved eq = [eq] # special simplification of the rhs if hint.startswith("nth_linear_constant_coeff"): # Collect terms to make the solution look nice. # This is also necessary for constantsimp to remove unnecessary # terms from the particular solution from variation of parameters # # Collect is not behaving reliably here. The results for # some linear constant-coefficient equations with repeated # roots do not properly simplify all constants sometimes. # 'collectterms' gives different orders sometimes, and results # differ in collect based on that order. The # sort-reverse trick fixes things, but may fail in the # future. In addition, collect is splitting exponentials with # rational powers for no reason. We have to do a match # to fix this using Wilds. # # XXX: This global collectterms hack should be removed. global collectterms collectterms.sort(key=default_sort_key) collectterms.reverse() assert len(eq) == 1 and eq[0].lhs == f(x) sol = eq[0].rhs sol = expand_mul(sol) for i, reroot, imroot in collectterms: sol = collect(sol, x**i*exp(reroot*x)*sin(abs(imroot)*x)) sol = collect(sol, x**i*exp(reroot*x)*cos(imroot*x)) for i, reroot, imroot in collectterms: sol = collect(sol, x**i*exp(reroot*x)) del collectterms # Collect is splitting exponentials with rational powers for # no reason. We call powsimp to fix. sol = powsimp(sol) eq[0] = Eq(f(x), sol) else: # The solution is not solved, so try to solve it try: floats = any(i.is_Float for i in eq.atoms(Number)) eqsol = solve(eq, func, force=True, rational=False if floats else None) if not eqsol: raise NotImplementedError except (NotImplementedError, PolynomialError): eq = [eq] else: def _expand(expr): numer, denom = expr.as_numer_denom() if denom.is_Add: return expr else: return powsimp(expr.expand(), combine='exp', deep=True) # XXX: the rest of odesimp() expects each ``t`` to be in a # specific normal form: rational expression with numerator # expanded, but with combined exponential functions (at # least in this setup all tests pass). eq = [Eq(f(x), _expand(t)) for t in eqsol] # special simplification of the lhs. if hint.startswith("1st_homogeneous_coeff"): for j, eqi in enumerate(eq): newi = logcombine(eqi, force=True) if isinstance(newi.lhs, log) and newi.rhs == 0: newi = Eq(newi.lhs.args[0]/C1, C1) eq[j] = newi # We cleaned up the constants before solving to help the solve engine with # a simpler expression, but the solved expression could have introduced # things like -C1, so rerun constantsimp() one last time before returning. for i, eqi in enumerate(eq): eq[i] = constantsimp(eqi, constants) eq[i] = constant_renumber(eq[i], ode.free_symbols) # If there is only 1 solution, return it; # otherwise return the list of solutions. if len(eq) == 1: eq = eq[0] return eq def ode_sol_simplicity(sol, func, trysolving=True): r""" Returns an extended integer representing how simple a solution to an ODE is. The following things are considered, in order from most simple to least: - ``sol`` is solved for ``func``. - ``sol`` is not solved for ``func``, but can be if passed to solve (e.g., a solution returned by ``dsolve(ode, func, simplify=False``). - If ``sol`` is not solved for ``func``, then base the result on the length of ``sol``, as computed by ``len(str(sol))``. - If ``sol`` has any unevaluated :py:class:`~sympy.integrals.integrals.Integral`\s, this will automatically be considered less simple than any of the above. This function returns an integer such that if solution A is simpler than solution B by above metric, then ``ode_sol_simplicity(sola, func) < ode_sol_simplicity(solb, func)``. Currently, the following are the numbers returned, but if the heuristic is ever improved, this may change. Only the ordering is guaranteed. +----------------------------------------------+-------------------+ | Simplicity | Return | +==============================================+===================+ | ``sol`` solved for ``func`` | ``-2`` | +----------------------------------------------+-------------------+ | ``sol`` not solved for ``func`` but can be | ``-1`` | +----------------------------------------------+-------------------+ | ``sol`` is not solved nor solvable for | ``len(str(sol))`` | | ``func`` | | +----------------------------------------------+-------------------+ | ``sol`` contains an | ``oo`` | | :obj:`~sympy.integrals.integrals.Integral` | | +----------------------------------------------+-------------------+ ``oo`` here means the SymPy infinity, which should compare greater than any integer. If you already know :py:meth:`~sympy.solvers.solvers.solve` cannot solve ``sol``, you can use ``trysolving=False`` to skip that step, which is the only potentially slow step. For example, :py:meth:`~sympy.solvers.ode.dsolve` with the ``simplify=False`` flag should do this. If ``sol`` is a list of solutions, if the worst solution in the list returns ``oo`` it returns that, otherwise it returns ``len(str(sol))``, that is, the length of the string representation of the whole list. Examples ======== This function is designed to be passed to ``min`` as the key argument, such as ``min(listofsolutions, key=lambda i: ode_sol_simplicity(i, f(x)))``. >>> from sympy import symbols, Function, Eq, tan, Integral >>> from sympy.solvers.ode.ode import ode_sol_simplicity >>> x, C1, C2 = symbols('x, C1, C2') >>> f = Function('f') >>> ode_sol_simplicity(Eq(f(x), C1*x**2), f(x)) -2 >>> ode_sol_simplicity(Eq(x**2 + f(x), C1), f(x)) -1 >>> ode_sol_simplicity(Eq(f(x), C1*Integral(2*x, x)), f(x)) oo >>> eq1 = Eq(f(x)/tan(f(x)/(2*x)), C1) >>> eq2 = Eq(f(x)/tan(f(x)/(2*x) + f(x)), C2) >>> [ode_sol_simplicity(eq, f(x)) for eq in [eq1, eq2]] [28, 35] >>> min([eq1, eq2], key=lambda i: ode_sol_simplicity(i, f(x))) Eq(f(x)/tan(f(x)/(2*x)), C1) """ # TODO: if two solutions are solved for f(x), we still want to be # able to get the simpler of the two # See the docstring for the coercion rules. We check easier (faster) # things here first, to save time. if iterable(sol): # See if there are Integrals for i in sol: if ode_sol_simplicity(i, func, trysolving=trysolving) == oo: return oo return len(str(sol)) if sol.has(Integral): return oo # Next, try to solve for func. This code will change slightly when CRootOf # is implemented in solve(). Probably a CRootOf solution should fall # somewhere between a normal solution and an unsolvable expression. # First, see if they are already solved if sol.lhs == func and not sol.rhs.has(func) or \ sol.rhs == func and not sol.lhs.has(func): return -2 # We are not so lucky, try solving manually if trysolving: try: sols = solve(sol, func) if not sols: raise NotImplementedError except NotImplementedError: pass else: return -1 # Finally, a naive computation based on the length of the string version # of the expression. This may favor combined fractions because they # will not have duplicate denominators, and may slightly favor expressions # with fewer additions and subtractions, as those are separated by spaces # by the printer. # Additional ideas for simplicity heuristics are welcome, like maybe # checking if a equation has a larger domain, or if constantsimp has # introduced arbitrary constants numbered higher than the order of a # given ODE that sol is a solution of. return len(str(sol)) def _extract_funcs(eqs): from sympy.core.basic import preorder_traversal funcs = [] for eq in eqs: derivs = [node for node in preorder_traversal(eq) if isinstance(node, Derivative)] func = [] for d in derivs: func += list(d.atoms(AppliedUndef)) for func_ in func: funcs.append(func_) funcs = list(uniq(funcs)) return funcs def _get_constant_subexpressions(expr, Cs): Cs = set(Cs) Ces = [] def _recursive_walk(expr): expr_syms = expr.free_symbols if expr_syms and expr_syms.issubset(Cs): Ces.append(expr) else: if expr.func == exp: expr = expr.expand(mul=True) if expr.func in (Add, Mul): d = sift(expr.args, lambda i : i.free_symbols.issubset(Cs)) if len(d[True]) > 1: x = expr.func(*d[True]) if not x.is_number: Ces.append(x) elif isinstance(expr, Integral): if expr.free_symbols.issubset(Cs) and \ all(len(x) == 3 for x in expr.limits): Ces.append(expr) for i in expr.args: _recursive_walk(i) return _recursive_walk(expr) return Ces def __remove_linear_redundancies(expr, Cs): cnts = {i: expr.count(i) for i in Cs} Cs = [i for i in Cs if cnts[i] > 0] def _linear(expr): if isinstance(expr, Add): xs = [i for i in Cs if expr.count(i)==cnts[i] \ and 0 == expr.diff(i, 2)] d = {} for x in xs: y = expr.diff(x) if y not in d: d[y]=[] d[y].append(x) for y in d: if len(d[y]) > 1: d[y].sort(key=str) for x in d[y][1:]: expr = expr.subs(x, 0) return expr def _recursive_walk(expr): if len(expr.args) != 0: expr = expr.func(*[_recursive_walk(i) for i in expr.args]) expr = _linear(expr) return expr if isinstance(expr, Equality): lhs, rhs = [_recursive_walk(i) for i in expr.args] f = lambda i: isinstance(i, Number) or i in Cs if isinstance(lhs, Symbol) and lhs in Cs: rhs, lhs = lhs, rhs if lhs.func in (Add, Symbol) and rhs.func in (Add, Symbol): dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f) drhs = sift([rhs] if isinstance(rhs, AtomicExpr) else rhs.args, f) for i in [True, False]: for hs in [dlhs, drhs]: if i not in hs: hs[i] = [0] # this calculation can be simplified lhs = Add(*dlhs[False]) - Add(*drhs[False]) rhs = Add(*drhs[True]) - Add(*dlhs[True]) elif lhs.func in (Mul, Symbol) and rhs.func in (Mul, Symbol): dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f) if True in dlhs: if False not in dlhs: dlhs[False] = [1] lhs = Mul(*dlhs[False]) rhs = rhs/Mul(*dlhs[True]) return Eq(lhs, rhs) else: return _recursive_walk(expr) @vectorize(0) def constantsimp(expr, constants): r""" Simplifies an expression with arbitrary constants in it. This function is written specifically to work with :py:meth:`~sympy.solvers.ode.dsolve`, and is not intended for general use. Simplification is done by "absorbing" the arbitrary constants into other arbitrary constants, numbers, and symbols that they are not independent of. The symbols must all have the same name with numbers after it, for example, ``C1``, ``C2``, ``C3``. The ``symbolname`` here would be '``C``', the ``startnumber`` would be 1, and the ``endnumber`` would be 3. If the arbitrary constants are independent of the variable ``x``, then the independent symbol would be ``x``. There is no need to specify the dependent function, such as ``f(x)``, because it already has the independent symbol, ``x``, in it. Because terms are "absorbed" into arbitrary constants and because constants are renumbered after simplifying, the arbitrary constants in expr are not necessarily equal to the ones of the same name in the returned result. If two or more arbitrary constants are added, multiplied, or raised to the power of each other, they are first absorbed together into a single arbitrary constant. Then the new constant is combined into other terms if necessary. Absorption of constants is done with limited assistance: 1. terms of :py:class:`~sympy.core.add.Add`\s are collected to try join constants so `e^x (C_1 \cos(x) + C_2 \cos(x))` will simplify to `e^x C_1 \cos(x)`; 2. powers with exponents that are :py:class:`~sympy.core.add.Add`\s are expanded so `e^{C_1 + x}` will be simplified to `C_1 e^x`. Use :py:meth:`~sympy.solvers.ode.ode.constant_renumber` to renumber constants after simplification or else arbitrary numbers on constants may appear, e.g. `C_1 + C_3 x`. In rare cases, a single constant can be "simplified" into two constants. Every differential equation solution should have as many arbitrary constants as the order of the differential equation. The result here will be technically correct, but it may, for example, have `C_1` and `C_2` in an expression, when `C_1` is actually equal to `C_2`. Use your discretion in such situations, and also take advantage of the ability to use hints in :py:meth:`~sympy.solvers.ode.dsolve`. Examples ======== >>> from sympy import symbols >>> from sympy.solvers.ode.ode import constantsimp >>> C1, C2, C3, x, y = symbols('C1, C2, C3, x, y') >>> constantsimp(2*C1*x, {C1, C2, C3}) C1*x >>> constantsimp(C1 + 2 + x, {C1, C2, C3}) C1 + x >>> constantsimp(C1*C2 + 2 + C2 + C3*x, {C1, C2, C3}) C1 + C3*x """ # This function works recursively. The idea is that, for Mul, # Add, Pow, and Function, if the class has a constant in it, then # we can simplify it, which we do by recursing down and # simplifying up. Otherwise, we can skip that part of the # expression. Cs = constants orig_expr = expr constant_subexprs = _get_constant_subexpressions(expr, Cs) for xe in constant_subexprs: xes = list(xe.free_symbols) if not xes: continue if all([expr.count(c) == xe.count(c) for c in xes]): xes.sort(key=str) expr = expr.subs(xe, xes[0]) # try to perform common sub-expression elimination of constant terms try: commons, rexpr = cse(expr) commons.reverse() rexpr = rexpr[0] for s in commons: cs = list(s[1].atoms(Symbol)) if len(cs) == 1 and cs[0] in Cs and \ cs[0] not in rexpr.atoms(Symbol) and \ not any(cs[0] in ex for ex in commons if ex != s): rexpr = rexpr.subs(s[0], cs[0]) else: rexpr = rexpr.subs(*s) expr = rexpr except IndexError: pass expr = __remove_linear_redundancies(expr, Cs) def _conditional_term_factoring(expr): new_expr = terms_gcd(expr, clear=False, deep=True, expand=False) # we do not want to factor exponentials, so handle this separately if new_expr.is_Mul: infac = False asfac = False for m in new_expr.args: if isinstance(m, exp): asfac = True elif m.is_Add: infac = any(isinstance(fi, exp) for t in m.args for fi in Mul.make_args(t)) if asfac and infac: new_expr = expr break return new_expr expr = _conditional_term_factoring(expr) # call recursively if more simplification is possible if orig_expr != expr: return constantsimp(expr, Cs) return expr def constant_renumber(expr, variables=None, newconstants=None): r""" Renumber arbitrary constants in ``expr`` to use the symbol names as given in ``newconstants``. In the process, this reorders expression terms in a standard way. If ``newconstants`` is not provided then the new constant names will be ``C1``, ``C2`` etc. Otherwise ``newconstants`` should be an iterable giving the new symbols to use for the constants in order. The ``variables`` argument is a list of non-constant symbols. All other free symbols found in ``expr`` are assumed to be constants and will be renumbered. If ``variables`` is not given then any numbered symbol beginning with ``C`` (e.g. ``C1``) is assumed to be a constant. Symbols are renumbered based on ``.sort_key()``, so they should be numbered roughly in the order that they appear in the final, printed expression. Note that this ordering is based in part on hashes, so it can produce different results on different machines. The structure of this function is very similar to that of :py:meth:`~sympy.solvers.ode.constantsimp`. Examples ======== >>> from sympy import symbols >>> from sympy.solvers.ode.ode import constant_renumber >>> x, C1, C2, C3 = symbols('x,C1:4') >>> expr = C3 + C2*x + C1*x**2 >>> expr C1*x**2 + C2*x + C3 >>> constant_renumber(expr) C1 + C2*x + C3*x**2 The ``variables`` argument specifies which are constants so that the other symbols will not be renumbered: >>> constant_renumber(expr, [C1, x]) C1*x**2 + C2 + C3*x The ``newconstants`` argument is used to specify what symbols to use when replacing the constants: >>> constant_renumber(expr, [x], newconstants=symbols('E1:4')) E1 + E2*x + E3*x**2 """ # System of expressions if isinstance(expr, (set, list, tuple)): return type(expr)(constant_renumber(Tuple(*expr), variables=variables, newconstants=newconstants)) # Symbols in solution but not ODE are constants if variables is not None: variables = set(variables) free_symbols = expr.free_symbols constantsymbols = list(free_symbols - variables) # Any Cn is a constant... else: variables = set() isconstant = lambda s: s.startswith('C') and s[1:].isdigit() constantsymbols = [sym for sym in expr.free_symbols if isconstant(sym.name)] # Find new constants checking that they aren't already in the ODE if newconstants is None: iter_constants = numbered_symbols(start=1, prefix='C', exclude=variables) else: iter_constants = (sym for sym in newconstants if sym not in variables) constants_found = [] # make a mapping to send all constantsymbols to S.One and use # that to make sure that term ordering is not dependent on # the indexed value of C C_1 = [(ci, S.One) for ci in constantsymbols] sort_key=lambda arg: default_sort_key(arg.subs(C_1)) def _constant_renumber(expr): r""" We need to have an internal recursive function """ # For system of expressions if isinstance(expr, Tuple): renumbered = [_constant_renumber(e) for e in expr] return Tuple(*renumbered) if isinstance(expr, Equality): return Eq( _constant_renumber(expr.lhs), _constant_renumber(expr.rhs)) if type(expr) not in (Mul, Add, Pow) and not expr.is_Function and \ not expr.has(*constantsymbols): # Base case, as above. Hope there aren't constants inside # of some other class, because they won't be renumbered. return expr elif expr.is_Piecewise: return expr elif expr in constantsymbols: if expr not in constants_found: constants_found.append(expr) return expr elif expr.is_Function or expr.is_Pow: return expr.func( *[_constant_renumber(x) for x in expr.args]) else: sortedargs = list(expr.args) sortedargs.sort(key=sort_key) return expr.func(*[_constant_renumber(x) for x in sortedargs]) expr = _constant_renumber(expr) # Don't renumber symbols present in the ODE. constants_found = [c for c in constants_found if c not in variables] # Renumbering happens here subs_dict = {var: cons for var, cons in zip(constants_found, iter_constants)} expr = expr.subs(subs_dict, simultaneous=True) return expr def _handle_Integral(expr, func, hint): r""" Converts a solution with Integrals in it into an actual solution. For most hints, this simply runs ``expr.doit()``. """ # XXX: This global y hack should be removed global y x = func.args[0] f = func.func if hint == "1st_exact": sol = (expr.doit()).subs(y, f(x)) del y elif hint == "1st_exact_Integral": sol = Eq(Subs(expr.lhs, y, f(x)), expr.rhs) del y elif hint == "nth_linear_constant_coeff_homogeneous": sol = expr elif not hint.endswith("_Integral"): sol = expr.doit() else: sol = expr return sol # FIXME: replace the general solution in the docstring with # dsolve(equation, hint='1st_exact_Integral'). You will need to be able # to have assumptions on P and Q that dP/dy = dQ/dx. def ode_1st_exact(eq, func, order, match): r""" Solves 1st order exact ordinary differential equations. A 1st order differential equation is called exact if it is the total differential of a function. That is, the differential equation .. math:: P(x, y) \,\partial{}x + Q(x, y) \,\partial{}y = 0 is exact if there is some function `F(x, y)` such that `P(x, y) = \partial{}F/\partial{}x` and `Q(x, y) = \partial{}F/\partial{}y`. It can be shown that a necessary and sufficient condition for a first order ODE to be exact is that `\partial{}P/\partial{}y = \partial{}Q/\partial{}x`. Then, the solution will be as given below:: >>> from sympy import Function, Eq, Integral, symbols, pprint >>> x, y, t, x0, y0, C1= symbols('x,y,t,x0,y0,C1') >>> P, Q, F= map(Function, ['P', 'Q', 'F']) >>> pprint(Eq(Eq(F(x, y), Integral(P(t, y), (t, x0, x)) + ... Integral(Q(x0, t), (t, y0, y))), C1)) x y / / | | F(x, y) = | P(t, y) dt + | Q(x0, t) dt = C1 | | / / x0 y0 Where the first partials of `P` and `Q` exist and are continuous in a simply connected region. A note: SymPy currently has no way to represent inert substitution on an expression, so the hint ``1st_exact_Integral`` will return an integral with `dy`. This is supposed to represent the function that you are solving for. Examples ======== >>> from sympy import Function, dsolve, cos, sin >>> from sympy.abc import x >>> f = Function('f') >>> dsolve(cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x), ... f(x), hint='1st_exact') Eq(x*cos(f(x)) + f(x)**3/3, C1) References ========== - https://en.wikipedia.org/wiki/Exact_differential_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 73 # indirect doctest """ x = func.args[0] r = match # d+e*diff(f(x),x) e = r[r['e']] d = r[r['d']] # XXX: This global y hack should be removed global y # This is the only way to pass dummy y to _handle_Integral y = r['y'] C1 = get_numbered_constants(eq, num=1) # Refer Joel Moses, "Symbolic Integration - The Stormy Decade", # Communications of the ACM, Volume 14, Number 8, August 1971, pp. 558 # which gives the method to solve an exact differential equation. sol = Integral(d, x) + Integral((e - (Integral(d, x).diff(y))), y) return Eq(sol, C1) def ode_1st_homogeneous_coeff_best(eq, func, order, match): r""" Returns the best solution to an ODE from the two hints ``1st_homogeneous_coeff_subs_dep_div_indep`` and ``1st_homogeneous_coeff_subs_indep_div_dep``. This is as determined by :py:meth:`~sympy.solvers.ode.ode.ode_sol_simplicity`. See the :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep` and :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep` docstrings for more information on these hints. Note that there is no ``ode_1st_homogeneous_coeff_best_Integral`` hint. Examples ======== >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x), ... hint='1st_homogeneous_coeff_best', simplify=False)) / 2 \ | 3*x | log|----- + 1| | 2 | \f (x) / log(f(x)) = log(C1) - -------------- 3 References ========== - https://en.wikipedia.org/wiki/Homogeneous_differential_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 59 # indirect doctest """ # There are two substitutions that solve the equation, u1=y/x and u2=x/y # They produce different integrals, so try them both and see which # one is easier. sol1 = ode_1st_homogeneous_coeff_subs_indep_div_dep(eq, func, order, match) sol2 = ode_1st_homogeneous_coeff_subs_dep_div_indep(eq, func, order, match) simplify = match.get('simplify', True) if simplify: # why is odesimp called here? Should it be at the usual spot? sol1 = odesimp(eq, sol1, func, "1st_homogeneous_coeff_subs_indep_div_dep") sol2 = odesimp(eq, sol2, func, "1st_homogeneous_coeff_subs_dep_div_indep") return min([sol1, sol2], key=lambda x: ode_sol_simplicity(x, func, trysolving=not simplify)) def ode_1st_homogeneous_coeff_subs_dep_div_indep(eq, func, order, match): r""" Solves a 1st order differential equation with homogeneous coefficients using the substitution `u_1 = \frac{\text{<dependent variable>}}{\text{<independent variable>}}`. This is a differential equation .. math:: P(x, y) + Q(x, y) dy/dx = 0 such that `P` and `Q` are homogeneous and of the same order. A function `F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`. Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See also the docstring of :py:meth:`~sympy.solvers.ode.homogeneous_order`. If the coefficients `P` and `Q` in the differential equation above are homogeneous functions of the same order, then it can be shown that the substitution `y = u_1 x` (i.e. `u_1 = y/x`) will turn the differential equation into an equation separable in the variables `x` and `u`. If `h(u_1)` is the function that results from making the substitution `u_1 = f(x)/x` on `P(x, f(x))` and `g(u_2)` is the function that results from the substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) + Q(x, f(x)) f'(x) = 0`, then the general solution is:: >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f, g, h = map(Function, ['f', 'g', 'h']) >>> genform = g(f(x)/x) + h(f(x)/x)*f(x).diff(x) >>> pprint(genform) /f(x)\ /f(x)\ d g|----| + h|----|*--(f(x)) \ x / \ x / dx >>> pprint(dsolve(genform, f(x), ... hint='1st_homogeneous_coeff_subs_dep_div_indep_Integral')) f(x) ---- x / | | -h(u1) log(x) = C1 + | ---------------- d(u1) | u1*h(u1) + g(u1) | / Where `u_1 h(u_1) + g(u_1) \ne 0` and `x \ne 0`. See also the docstrings of :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_best` and :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`. Examples ======== >>> from sympy import Function, dsolve >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x), ... hint='1st_homogeneous_coeff_subs_dep_div_indep', simplify=False)) / 3 \ |3*f(x) f (x)| log|------ + -----| | x 3 | \ x / log(x) = log(C1) - ------------------- 3 References ========== - https://en.wikipedia.org/wiki/Homogeneous_differential_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 59 # indirect doctest """ x = func.args[0] f = func.func u = Dummy('u') u1 = Dummy('u1') # u1 == f(x)/x r = match # d+e*diff(f(x),x) C1 = get_numbered_constants(eq, num=1) xarg = match.get('xarg', 0) yarg = match.get('yarg', 0) int = Integral( (-r[r['e']]/(r[r['d']] + u1*r[r['e']])).subs({x: 1, r['y']: u1}), (u1, None, f(x)/x)) sol = logcombine(Eq(log(x), int + log(C1)), force=True) sol = sol.subs(f(x), u).subs(((u, u - yarg), (x, x - xarg), (u, f(x)))) return sol def ode_1st_homogeneous_coeff_subs_indep_div_dep(eq, func, order, match): r""" Solves a 1st order differential equation with homogeneous coefficients using the substitution `u_2 = \frac{\text{<independent variable>}}{\text{<dependent variable>}}`. This is a differential equation .. math:: P(x, y) + Q(x, y) dy/dx = 0 such that `P` and `Q` are homogeneous and of the same order. A function `F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`. Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See also the docstring of :py:meth:`~sympy.solvers.ode.homogeneous_order`. If the coefficients `P` and `Q` in the differential equation above are homogeneous functions of the same order, then it can be shown that the substitution `x = u_2 y` (i.e. `u_2 = x/y`) will turn the differential equation into an equation separable in the variables `y` and `u_2`. If `h(u_2)` is the function that results from making the substitution `u_2 = x/f(x)` on `P(x, f(x))` and `g(u_2)` is the function that results from the substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) + Q(x, f(x)) f'(x) = 0`, then the general solution is: >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f, g, h = map(Function, ['f', 'g', 'h']) >>> genform = g(x/f(x)) + h(x/f(x))*f(x).diff(x) >>> pprint(genform) / x \ / x \ d g|----| + h|----|*--(f(x)) \f(x)/ \f(x)/ dx >>> pprint(dsolve(genform, f(x), ... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral')) x ---- f(x) / | | -g(u2) | ---------------- d(u2) | u2*g(u2) + h(u2) | / <BLANKLINE> f(x) = C1*e Where `u_2 g(u_2) + h(u_2) \ne 0` and `f(x) \ne 0`. See also the docstrings of :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_best` and :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep`. Examples ======== >>> from sympy import Function, pprint, dsolve >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x), ... hint='1st_homogeneous_coeff_subs_indep_div_dep', ... simplify=False)) / 2 \ | 3*x | log|----- + 1| | 2 | \f (x) / log(f(x)) = log(C1) - -------------- 3 References ========== - https://en.wikipedia.org/wiki/Homogeneous_differential_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 59 # indirect doctest """ x = func.args[0] f = func.func u = Dummy('u') u2 = Dummy('u2') # u2 == x/f(x) r = match # d+e*diff(f(x),x) C1 = get_numbered_constants(eq, num=1) xarg = match.get('xarg', 0) # If xarg present take xarg, else zero yarg = match.get('yarg', 0) # If yarg present take yarg, else zero int = Integral( simplify( (-r[r['d']]/(r[r['e']] + u2*r[r['d']])).subs({x: u2, r['y']: 1})), (u2, None, x/f(x))) sol = logcombine(Eq(log(f(x)), int + log(C1)), force=True) sol = sol.subs(f(x), u).subs(((u, u - yarg), (x, x - xarg), (u, f(x)))) return sol # XXX: Should this function maybe go somewhere else? def homogeneous_order(eq, *symbols): r""" Returns the order `n` if `g` is homogeneous and ``None`` if it is not homogeneous. Determines if a function is homogeneous and if so of what order. A function `f(x, y, \cdots)` is homogeneous of order `n` if `f(t x, t y, \cdots) = t^n f(x, y, \cdots)`. If the function is of two variables, `F(x, y)`, then `f` being homogeneous of any order is equivalent to being able to rewrite `F(x, y)` as `G(x/y)` or `H(y/x)`. This fact is used to solve 1st order ordinary differential equations whose coefficients are homogeneous of the same order (see the docstrings of :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep` and :py:meth:`~sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`). Symbols can be functions, but every argument of the function must be a symbol, and the arguments of the function that appear in the expression must match those given in the list of symbols. If a declared function appears with different arguments than given in the list of symbols, ``None`` is returned. Examples ======== >>> from sympy import Function, homogeneous_order, sqrt >>> from sympy.abc import x, y >>> f = Function('f') >>> homogeneous_order(f(x), f(x)) is None True >>> homogeneous_order(f(x,y), f(y, x), x, y) is None True >>> homogeneous_order(f(x), f(x), x) 1 >>> homogeneous_order(x**2*f(x)/sqrt(x**2+f(x)**2), x, f(x)) 2 >>> homogeneous_order(x**2+f(x), x, f(x)) is None True """ if not symbols: raise ValueError("homogeneous_order: no symbols were given.") symset = set(symbols) eq = sympify(eq) # The following are not supported if eq.has(Order, Derivative): return None # These are all constants if (eq.is_Number or eq.is_NumberSymbol or eq.is_number ): return S.Zero # Replace all functions with dummy variables dum = numbered_symbols(prefix='d', cls=Dummy) newsyms = set() for i in [j for j in symset if getattr(j, 'is_Function')]: iargs = set(i.args) if iargs.difference(symset): return None else: dummyvar = next(dum) eq = eq.subs(i, dummyvar) symset.remove(i) newsyms.add(dummyvar) symset.update(newsyms) if not eq.free_symbols & symset: return None # assuming order of a nested function can only be equal to zero if isinstance(eq, Function): return None if homogeneous_order( eq.args[0], *tuple(symset)) != 0 else S.Zero # make the replacement of x with x*t and see if t can be factored out t = Dummy('t', positive=True) # It is sufficient that t > 0 eqs = separatevars(eq.subs([(i, t*i) for i in symset]), [t], dict=True)[t] if eqs is S.One: return S.Zero # there was no term with only t i, d = eqs.as_independent(t, as_Add=False) b, e = d.as_base_exp() if b == t: return e def ode_Liouville(eq, func, order, match): r""" Solves 2nd order Liouville differential equations. The general form of a Liouville ODE is .. math:: \frac{d^2 y}{dx^2} + g(y) \left(\! \frac{dy}{dx}\!\right)^2 + h(x) \frac{dy}{dx}\text{.} The general solution is: >>> from sympy import Function, dsolve, Eq, pprint, diff >>> from sympy.abc import x >>> f, g, h = map(Function, ['f', 'g', 'h']) >>> genform = Eq(diff(f(x),x,x) + g(f(x))*diff(f(x),x)**2 + ... h(x)*diff(f(x),x), 0) >>> pprint(genform) 2 2 /d \ d d g(f(x))*|--(f(x))| + h(x)*--(f(x)) + ---(f(x)) = 0 \dx / dx 2 dx >>> pprint(dsolve(genform, f(x), hint='Liouville_Integral')) f(x) / / | | | / | / | | | | | - | h(x) dx | | g(y) dy | | | | | / | / C1 + C2* | e dx + | e dy = 0 | | / / Examples ======== >>> from sympy import Function, dsolve, Eq, pprint >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(diff(f(x), x, x) + diff(f(x), x)**2/f(x) + ... diff(f(x), x)/x, f(x), hint='Liouville')) ________________ ________________ [f(x) = -\/ C1 + C2*log(x) , f(x) = \/ C1 + C2*log(x) ] References ========== - Goldstein and Braun, "Advanced Methods for the Solution of Differential Equations", pp. 98 - http://www.maplesoft.com/support/help/Maple/view.aspx?path=odeadvisor/Liouville # indirect doctest """ # Liouville ODE: # f(x).diff(x, 2) + g(f(x))*(f(x).diff(x, 2))**2 + h(x)*f(x).diff(x) # See Goldstein and Braun, "Advanced Methods for the Solution of # Differential Equations", pg. 98, as well as # http://www.maplesoft.com/support/help/view.aspx?path=odeadvisor/Liouville x = func.args[0] f = func.func r = match # f(x).diff(x, 2) + g*f(x).diff(x)**2 + h*f(x).diff(x) y = r['y'] C1, C2 = get_numbered_constants(eq, num=2) int = Integral(exp(Integral(r['g'], y)), (y, None, f(x))) sol = Eq(int + C1*Integral(exp(-Integral(r['h'], x)), x) + C2, 0) return sol def ode_2nd_power_series_ordinary(eq, func, order, match): r""" Gives a power series solution to a second order homogeneous differential equation with polynomial coefficients at an ordinary point. A homogeneous differential equation is of the form .. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) = 0 For simplicity it is assumed that `P(x)`, `Q(x)` and `R(x)` are polynomials, it is sufficient that `\frac{Q(x)}{P(x)}` and `\frac{R(x)}{P(x)}` exists at `x_{0}`. A recurrence relation is obtained by substituting `y` as `\sum_{n=0}^\infty a_{n}x^{n}`, in the differential equation, and equating the nth term. Using this relation various terms can be generated. Examples ======== >>> from sympy import dsolve, Function, pprint >>> from sympy.abc import x >>> f = Function("f") >>> eq = f(x).diff(x, 2) + f(x) >>> pprint(dsolve(eq, hint='2nd_power_series_ordinary')) / 4 2 \ / 2\ |x x | | x | / 6\ f(x) = C2*|-- - -- + 1| + C1*x*|1 - --| + O\x / \24 2 / \ 6 / References ========== - http://tutorial.math.lamar.edu/Classes/DE/SeriesSolutions.aspx - George E. Simmons, "Differential Equations with Applications and Historical Notes", p.p 176 - 184 """ x = func.args[0] f = func.func C0, C1 = get_numbered_constants(eq, num=2) n = Dummy("n", integer=True) s = Wild("s") k = Wild("k", exclude=[x]) x0 = match.get('x0') terms = match.get('terms', 5) p = match[match['a3']] q = match[match['b3']] r = match[match['c3']] seriesdict = {} recurr = Function("r") # Generating the recurrence relation which works this way: # for the second order term the summation begins at n = 2. The coefficients # p is multiplied with an*(n - 1)*(n - 2)*x**n-2 and a substitution is made such that # the exponent of x becomes n. # For example, if p is x, then the second degree recurrence term is # an*(n - 1)*(n - 2)*x**n-1, substituting (n - 1) as n, it transforms to # an+1*n*(n - 1)*x**n. # A similar process is done with the first order and zeroth order term. coefflist = [(recurr(n), r), (n*recurr(n), q), (n*(n - 1)*recurr(n), p)] for index, coeff in enumerate(coefflist): if coeff[1]: f2 = powsimp(expand((coeff[1]*(x - x0)**(n - index)).subs(x, x + x0))) if f2.is_Add: addargs = f2.args else: addargs = [f2] for arg in addargs: powm = arg.match(s*x**k) term = coeff[0]*powm[s] if not powm[k].is_Symbol: term = term.subs(n, n - powm[k].as_independent(n)[0]) startind = powm[k].subs(n, index) # Seeing if the startterm can be reduced further. # If it vanishes for n lesser than startind, it is # equal to summation from n. if startind: for i in reversed(range(startind)): if not term.subs(n, i): seriesdict[term] = i else: seriesdict[term] = i + 1 break else: seriesdict[term] = S.Zero # Stripping of terms so that the sum starts with the same number. teq = S.Zero suminit = seriesdict.values() rkeys = seriesdict.keys() req = Add(*rkeys) if any(suminit): maxval = max(suminit) for term in seriesdict: val = seriesdict[term] if val != maxval: for i in range(val, maxval): teq += term.subs(n, val) finaldict = {} if teq: fargs = teq.atoms(AppliedUndef) if len(fargs) == 1: finaldict[fargs.pop()] = 0 else: maxf = max(fargs, key = lambda x: x.args[0]) sol = solve(teq, maxf) if isinstance(sol, list): sol = sol[0] finaldict[maxf] = sol # Finding the recurrence relation in terms of the largest term. fargs = req.atoms(AppliedUndef) maxf = max(fargs, key = lambda x: x.args[0]) minf = min(fargs, key = lambda x: x.args[0]) if minf.args[0].is_Symbol: startiter = 0 else: startiter = -minf.args[0].as_independent(n)[0] lhs = maxf rhs = solve(req, maxf) if isinstance(rhs, list): rhs = rhs[0] # Checking how many values are already present tcounter = len([t for t in finaldict.values() if t]) for _ in range(tcounter, terms - 3): # Assuming c0 and c1 to be arbitrary check = rhs.subs(n, startiter) nlhs = lhs.subs(n, startiter) nrhs = check.subs(finaldict) finaldict[nlhs] = nrhs startiter += 1 # Post processing series = C0 + C1*(x - x0) for term in finaldict: if finaldict[term]: fact = term.args[0] series += (finaldict[term].subs([(recurr(0), C0), (recurr(1), C1)])*( x - x0)**fact) series = collect(expand_mul(series), [C0, C1]) + Order(x**terms) return Eq(f(x), series) def ode_2nd_linear_airy(eq, func, order, match): r""" Gives solution of the Airy differential equation .. math :: \frac{d^2y}{dx^2} + (a + b x) y(x) = 0 in terms of Airy special functions airyai and airybi. Examples ======== >>> from sympy import dsolve, Function >>> from sympy.abc import x >>> f = Function("f") >>> eq = f(x).diff(x, 2) - x*f(x) >>> dsolve(eq) Eq(f(x), C1*airyai(x) + C2*airybi(x)) """ x = func.args[0] f = func.func C0, C1 = get_numbered_constants(eq, num=2) b = match['b'] m = match['m'] if m.is_positive: arg = - b/cbrt(m)**2 - cbrt(m)*x elif m.is_negative: arg = - b/cbrt(-m)**2 + cbrt(-m)*x else: arg = - b/cbrt(-m)**2 + cbrt(-m)*x return Eq(f(x), C0*airyai(arg) + C1*airybi(arg)) def ode_2nd_power_series_regular(eq, func, order, match): r""" Gives a power series solution to a second order homogeneous differential equation with polynomial coefficients at a regular point. A second order homogeneous differential equation is of the form .. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) = 0 A point is said to regular singular at `x0` if `x - x0\frac{Q(x)}{P(x)}` and `(x - x0)^{2}\frac{R(x)}{P(x)}` are analytic at `x0`. For simplicity `P(x)`, `Q(x)` and `R(x)` are assumed to be polynomials. The algorithm for finding the power series solutions is: 1. Try expressing `(x - x0)P(x)` and `((x - x0)^{2})Q(x)` as power series solutions about x0. Find `p0` and `q0` which are the constants of the power series expansions. 2. Solve the indicial equation `f(m) = m(m - 1) + m*p0 + q0`, to obtain the roots `m1` and `m2` of the indicial equation. 3. If `m1 - m2` is a non integer there exists two series solutions. If `m1 = m2`, there exists only one solution. If `m1 - m2` is an integer, then the existence of one solution is confirmed. The other solution may or may not exist. The power series solution is of the form `x^{m}\sum_{n=0}^\infty a_{n}x^{n}`. The coefficients are determined by the following recurrence relation. `a_{n} = -\frac{\sum_{k=0}^{n-1} q_{n-k} + (m + k)p_{n-k}}{f(m + n)}`. For the case in which `m1 - m2` is an integer, it can be seen from the recurrence relation that for the lower root `m`, when `n` equals the difference of both the roots, the denominator becomes zero. So if the numerator is not equal to zero, a second series solution exists. Examples ======== >>> from sympy import dsolve, Function, pprint >>> from sympy.abc import x >>> f = Function("f") >>> eq = x*(f(x).diff(x, 2)) + 2*(f(x).diff(x)) + x*f(x) >>> pprint(dsolve(eq, hint='2nd_power_series_regular')) / 6 4 2 \ | x x x | / 4 2 \ C1*|- --- + -- - -- + 1| | x x | \ 720 24 2 / / 6\ f(x) = C2*|--- - -- + 1| + ------------------------ + O\x / \120 6 / x References ========== - George E. Simmons, "Differential Equations with Applications and Historical Notes", p.p 176 - 184 """ x = func.args[0] f = func.func C0, C1 = get_numbered_constants(eq, num=2) m = Dummy("m") # for solving the indicial equation x0 = match.get('x0') terms = match.get('terms', 5) p = match['p'] q = match['q'] # Generating the indicial equation indicial = [] for term in [p, q]: if not term.has(x): indicial.append(term) else: term = series(term, n=1, x0=x0) if isinstance(term, Order): indicial.append(S.Zero) else: for arg in term.args: if not arg.has(x): indicial.append(arg) break p0, q0 = indicial sollist = solve(m*(m - 1) + m*p0 + q0, m) if sollist and isinstance(sollist, list) and all( [sol.is_real for sol in sollist]): serdict1 = {} serdict2 = {} if len(sollist) == 1: # Only one series solution exists in this case. m1 = m2 = sollist.pop() if terms-m1-1 <= 0: return Eq(f(x), Order(terms)) serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0) else: m1 = sollist[0] m2 = sollist[1] if m1 < m2: m1, m2 = m2, m1 # Irrespective of whether m1 - m2 is an integer or not, one # Frobenius series solution exists. serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0) if not (m1 - m2).is_integer: # Second frobenius series solution exists. serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1) else: # Check if second frobenius series solution exists. serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1, check=m1) if serdict1: finalseries1 = C0 for key in serdict1: power = int(key.name[1:]) finalseries1 += serdict1[key]*(x - x0)**power finalseries1 = (x - x0)**m1*finalseries1 finalseries2 = S.Zero if serdict2: for key in serdict2: power = int(key.name[1:]) finalseries2 += serdict2[key]*(x - x0)**power finalseries2 += C1 finalseries2 = (x - x0)**m2*finalseries2 return Eq(f(x), collect(finalseries1 + finalseries2, [C0, C1]) + Order(x**terms)) def ode_2nd_linear_bessel(eq, func, order, match): r""" Gives solution of the Bessel differential equation .. math :: x^2 \frac{d^2y}{dx^2} + x \frac{dy}{dx} y(x) + (x^2-n^2) y(x) if n is integer then the solution is of the form Eq(f(x), C0 besselj(n,x) + C1 bessely(n,x)) as both the solutions are linearly independent else if n is a fraction then the solution is of the form Eq(f(x), C0 besselj(n,x) + C1 besselj(-n,x)) which can also transform into Eq(f(x), C0 besselj(n,x) + C1 bessely(n,x)). Examples ======== >>> from sympy.abc import x >>> from sympy import Symbol >>> v = Symbol('v', positive=True) >>> from sympy.solvers.ode import dsolve >>> from sympy import Function >>> f = Function('f') >>> y = f(x) >>> genform = x**2*y.diff(x, 2) + x*y.diff(x) + (x**2 - v**2)*y >>> dsolve(genform) Eq(f(x), C1*besselj(v, x) + C2*bessely(v, x)) References ========== https://www.math24.net/bessel-differential-equation/ """ x = func.args[0] f = func.func C0, C1 = get_numbered_constants(eq, num=2) n = match['n'] a4 = match['a4'] c4 = match['c4'] d4 = match['d4'] b4 = match['b4'] n = sqrt(n**2 + Rational(1, 4)*(c4 - 1)**2) return Eq(f(x), ((x**(Rational(1-c4,2)))*(C0*besselj(n/d4,a4*x**d4/d4) + C1*bessely(n/d4,a4*x**d4/d4))).subs(x, x-b4)) def _frobenius(n, m, p0, q0, p, q, x0, x, c, check=None): r""" Returns a dict with keys as coefficients and values as their values in terms of C0 """ n = int(n) # In cases where m1 - m2 is not an integer m2 = check d = Dummy("d") numsyms = numbered_symbols("C", start=0) numsyms = [next(numsyms) for i in range(n + 1)] serlist = [] for ser in [p, q]: # Order term not present if ser.is_polynomial(x) and Poly(ser, x).degree() <= n: if x0: ser = ser.subs(x, x + x0) dict_ = Poly(ser, x).as_dict() # Order term present else: tseries = series(ser, x=x0, n=n+1) # Removing order dict_ = Poly(list(ordered(tseries.args))[: -1], x).as_dict() # Fill in with zeros, if coefficients are zero. for i in range(n + 1): if (i,) not in dict_: dict_[(i,)] = S.Zero serlist.append(dict_) pseries = serlist[0] qseries = serlist[1] indicial = d*(d - 1) + d*p0 + q0 frobdict = {} for i in range(1, n + 1): num = c*(m*pseries[(i,)] + qseries[(i,)]) for j in range(1, i): sym = Symbol("C" + str(j)) num += frobdict[sym]*((m + j)*pseries[(i - j,)] + qseries[(i - j,)]) # Checking for cases when m1 - m2 is an integer. If num equals zero # then a second Frobenius series solution cannot be found. If num is not zero # then set constant as zero and proceed. if m2 is not None and i == m2 - m: if num: return False else: frobdict[numsyms[i]] = S.Zero else: frobdict[numsyms[i]] = -num/(indicial.subs(d, m+i)) return frobdict def _nth_order_reducible_match(eq, func): r""" Matches any differential equation that can be rewritten with a smaller order. Only derivatives of ``func`` alone, wrt a single variable, are considered, and only in them should ``func`` appear. """ # ODE only handles functions of 1 variable so this affirms that state assert len(func.args) == 1 x = func.args[0] vc = [d.variable_count[0] for d in eq.atoms(Derivative) if d.expr == func and len(d.variable_count) == 1] ords = [c for v, c in vc if v == x] if len(ords) < 2: return smallest = min(ords) # make sure func does not appear outside of derivatives D = Dummy() if eq.subs(func.diff(x, smallest), D).has(func): return return {'n': smallest} def ode_nth_order_reducible(eq, func, order, match): r""" Solves ODEs that only involve derivatives of the dependent variable using a substitution of the form `f^n(x) = g(x)`. For example any second order ODE of the form `f''(x) = h(f'(x), x)` can be transformed into a pair of 1st order ODEs `g'(x) = h(g(x), x)` and `f'(x) = g(x)`. Usually the 1st order ODE for `g` is easier to solve. If that gives an explicit solution for `g` then `f` is found simply by integration. Examples ======== >>> from sympy import Function, dsolve, Eq >>> from sympy.abc import x >>> f = Function('f') >>> eq = Eq(x*f(x).diff(x)**2 + f(x).diff(x, 2), 0) >>> dsolve(eq, f(x), hint='nth_order_reducible') ... # doctest: +NORMALIZE_WHITESPACE Eq(f(x), C1 - sqrt(-1/C2)*log(-C2*sqrt(-1/C2) + x) + sqrt(-1/C2)*log(C2*sqrt(-1/C2) + x)) """ x = func.args[0] f = func.func n = match['n'] # get a unique function name for g names = [a.name for a in eq.atoms(AppliedUndef)] while True: name = Dummy().name if name not in names: g = Function(name) break w = f(x).diff(x, n) geq = eq.subs(w, g(x)) gsol = dsolve(geq, g(x)) if not isinstance(gsol, list): gsol = [gsol] # Might be multiple solutions to the reduced ODE: fsol = [] for gsoli in gsol: fsoli = dsolve(gsoli.subs(g(x), w), f(x)) # or do integration n times fsol.append(fsoli) if len(fsol) == 1: fsol = fsol[0] return fsol def _remove_redundant_solutions(eq, solns, order, var): r""" Remove redundant solutions from the set of solutions. This function is needed because otherwise dsolve can return redundant solutions. As an example consider: eq = Eq((f(x).diff(x, 2))*f(x).diff(x), 0) There are two ways to find solutions to eq. The first is to solve f(x).diff(x, 2) = 0 leading to solution f(x)=C1 + C2*x. The second is to solve the equation f(x).diff(x) = 0 leading to the solution f(x) = C1. In this particular case we then see that the second solution is a special case of the first and we don't want to return it. This does not always happen. If we have eq = Eq((f(x)**2-4)*(f(x).diff(x)-4), 0) then we get the algebraic solution f(x) = [-2, 2] and the integral solution f(x) = x + C1 and in this case the two solutions are not equivalent wrt initial conditions so both should be returned. """ def is_special_case_of(soln1, soln2): return _is_special_case_of(soln1, soln2, eq, order, var) unique_solns = [] for soln1 in solns: for soln2 in unique_solns[:]: if is_special_case_of(soln1, soln2): break elif is_special_case_of(soln2, soln1): unique_solns.remove(soln2) else: unique_solns.append(soln1) return unique_solns def _is_special_case_of(soln1, soln2, eq, order, var): r""" True if soln1 is found to be a special case of soln2 wrt some value of the constants that appear in soln2. False otherwise. """ # The solutions returned by dsolve may be given explicitly or implicitly. # We will equate the sol1=(soln1.rhs - soln1.lhs), sol2=(soln2.rhs - soln2.lhs) # of the two solutions. # # Since this is supposed to hold for all x it also holds for derivatives. # For an order n ode we should be able to differentiate # each solution n times to get n+1 equations. # # We then try to solve those n+1 equations for the integrations constants # in sol2. If we can find a solution that doesn't depend on x then it # means that some value of the constants in sol1 is a special case of # sol2 corresponding to a particular choice of the integration constants. # In case the solution is in implicit form we subtract the sides soln1 = soln1.rhs - soln1.lhs soln2 = soln2.rhs - soln2.lhs # Work for the series solution if soln1.has(Order) and soln2.has(Order): if soln1.getO() == soln2.getO(): soln1 = soln1.removeO() soln2 = soln2.removeO() else: return False elif soln1.has(Order) or soln2.has(Order): return False constants1 = soln1.free_symbols.difference(eq.free_symbols) constants2 = soln2.free_symbols.difference(eq.free_symbols) constants1_new = get_numbered_constants(Tuple(soln1, soln2), len(constants1)) if len(constants1) == 1: constants1_new = {constants1_new} for c_old, c_new in zip(constants1, constants1_new): soln1 = soln1.subs(c_old, c_new) # n equations for sol1 = sol2, sol1'=sol2', ... lhs = soln1 rhs = soln2 eqns = [Eq(lhs, rhs)] for n in range(1, order): lhs = lhs.diff(var) rhs = rhs.diff(var) eq = Eq(lhs, rhs) eqns.append(eq) # BooleanTrue/False awkwardly show up for trivial equations if any(isinstance(eq, BooleanFalse) for eq in eqns): return False eqns = [eq for eq in eqns if not isinstance(eq, BooleanTrue)] try: constant_solns = solve(eqns, constants2) except NotImplementedError: return False # Sometimes returns a dict and sometimes a list of dicts if isinstance(constant_solns, dict): constant_solns = [constant_solns] # after solving the issue 17418, maybe we don't need the following checksol code. for constant_soln in constant_solns: for eq in eqns: eq=eq.rhs-eq.lhs if checksol(eq, constant_soln) is not True: return False # If any solution gives all constants as expressions that don't depend on # x then there exists constants for soln2 that give soln1 for constant_soln in constant_solns: if not any(c.has(var) for c in constant_soln.values()): return True return False def _nth_linear_match(eq, func, order): r""" Matches a differential equation to the linear form: .. math:: a_n(x) y^{(n)} + \cdots + a_1(x)y' + a_0(x) y + B(x) = 0 Returns a dict of order:coeff terms, where order is the order of the derivative on each term, and coeff is the coefficient of that derivative. The key ``-1`` holds the function `B(x)`. Returns ``None`` if the ODE is not linear. This function assumes that ``func`` has already been checked to be good. Examples ======== >>> from sympy import Function, cos, sin >>> from sympy.abc import x >>> from sympy.solvers.ode.ode import _nth_linear_match >>> f = Function('f') >>> _nth_linear_match(f(x).diff(x, 3) + 2*f(x).diff(x) + ... x*f(x).diff(x, 2) + cos(x)*f(x).diff(x) + x - f(x) - ... sin(x), f(x), 3) {-1: x - sin(x), 0: -1, 1: cos(x) + 2, 2: x, 3: 1} >>> _nth_linear_match(f(x).diff(x, 3) + 2*f(x).diff(x) + ... x*f(x).diff(x, 2) + cos(x)*f(x).diff(x) + x - f(x) - ... sin(f(x)), f(x), 3) == None True """ x = func.args[0] one_x = {x} terms = {i: S.Zero for i in range(-1, order + 1)} for i in Add.make_args(eq): if not i.has(func): terms[-1] += i else: c, f = i.as_independent(func) if (isinstance(f, Derivative) and set(f.variables) == one_x and f.args[0] == func): terms[f.derivative_count] += c elif f == func: terms[len(f.args[1:])] += c else: return None return terms def ode_nth_linear_euler_eq_homogeneous(eq, func, order, match, returns='sol'): r""" Solves an `n`\th order linear homogeneous variable-coefficient Cauchy-Euler equidimensional ordinary differential equation. This is an equation with form `0 = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x) \cdots`. These equations can be solved in a general manner, by substituting solutions of the form `f(x) = x^r`, and deriving a characteristic equation for `r`. When there are repeated roots, we include extra terms of the form `C_{r k} \ln^k(x) x^r`, where `C_{r k}` is an arbitrary integration constant, `r` is a root of the characteristic equation, and `k` ranges over the multiplicity of `r`. In the cases where the roots are complex, solutions of the form `C_1 x^a \sin(b \log(x)) + C_2 x^a \cos(b \log(x))` are returned, based on expansions with Euler's formula. The general solution is the sum of the terms found. If SymPy cannot find exact roots to the characteristic equation, a :py:obj:`~.ComplexRootOf` instance will be returned instead. >>> from sympy import Function, dsolve >>> from sympy.abc import x >>> f = Function('f') >>> dsolve(4*x**2*f(x).diff(x, 2) + f(x), f(x), ... hint='nth_linear_euler_eq_homogeneous') ... # doctest: +NORMALIZE_WHITESPACE Eq(f(x), sqrt(x)*(C1 + C2*log(x))) Note that because this method does not involve integration, there is no ``nth_linear_euler_eq_homogeneous_Integral`` hint. The following is for internal use: - ``returns = 'sol'`` returns the solution to the ODE. - ``returns = 'list'`` returns a list of linearly independent solutions, corresponding to the fundamental solution set, for use with non homogeneous solution methods like variation of parameters and undetermined coefficients. Note that, though the solutions should be linearly independent, this function does not explicitly check that. You can do ``assert simplify(wronskian(sollist)) != 0`` to check for linear independence. Also, ``assert len(sollist) == order`` will need to pass. - ``returns = 'both'``, return a dictionary ``{'sol': <solution to ODE>, 'list': <list of linearly independent solutions>}``. Examples ======== >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f = Function('f') >>> eq = f(x).diff(x, 2)*x**2 - 4*f(x).diff(x)*x + 6*f(x) >>> pprint(dsolve(eq, f(x), ... hint='nth_linear_euler_eq_homogeneous')) 2 f(x) = x *(C1 + C2*x) References ========== - https://en.wikipedia.org/wiki/Cauchy%E2%80%93Euler_equation - C. Bender & S. Orszag, "Advanced Mathematical Methods for Scientists and Engineers", Springer 1999, pp. 12 # indirect doctest """ # XXX: This global collectterms hack should be removed. global collectterms collectterms = [] x = func.args[0] f = func.func r = match # First, set up characteristic equation. chareq, symbol = S.Zero, Dummy('x') for i in r.keys(): if not isinstance(i, str) and i >= 0: chareq += (r[i]*diff(x**symbol, x, i)*x**-symbol).expand() chareq = Poly(chareq, symbol) chareqroots = [rootof(chareq, k) for k in range(chareq.degree())] # A generator of constants constants = list(get_numbered_constants(eq, num=chareq.degree()*2)) constants.reverse() # Create a dict root: multiplicity or charroots charroots = defaultdict(int) for root in chareqroots: charroots[root] += 1 gsol = S.Zero # We need keep track of terms so we can run collect() at the end. # This is necessary for constantsimp to work properly. ln = log for root, multiplicity in charroots.items(): for i in range(multiplicity): if isinstance(root, RootOf): gsol += (x**root) * constants.pop() if multiplicity != 1: raise ValueError("Value should be 1") collectterms = [(0, root, 0)] + collectterms elif root.is_real: gsol += ln(x)**i*(x**root) * constants.pop() collectterms = [(i, root, 0)] + collectterms else: reroot = re(root) imroot = im(root) gsol += ln(x)**i * (x**reroot) * ( constants.pop() * sin(abs(imroot)*ln(x)) + constants.pop() * cos(imroot*ln(x))) # Preserve ordering (multiplicity, real part, imaginary part) # It will be assumed implicitly when constructing # fundamental solution sets. collectterms = [(i, reroot, imroot)] + collectterms if returns == 'sol': return Eq(f(x), gsol) elif returns in ('list' 'both'): # HOW TO TEST THIS CODE? (dsolve does not pass 'returns' through) # Create a list of (hopefully) linearly independent solutions gensols = [] # Keep track of when to use sin or cos for nonzero imroot for i, reroot, imroot in collectterms: if imroot == 0: gensols.append(ln(x)**i*x**reroot) else: sin_form = ln(x)**i*x**reroot*sin(abs(imroot)*ln(x)) if sin_form in gensols: cos_form = ln(x)**i*x**reroot*cos(imroot*ln(x)) gensols.append(cos_form) else: gensols.append(sin_form) if returns == 'list': return gensols else: return {'sol': Eq(f(x), gsol), 'list': gensols} else: raise ValueError('Unknown value for key "returns".') def ode_nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients(eq, func, order, match, returns='sol'): r""" Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional ordinary differential equation using undetermined coefficients. This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x) \cdots`. These equations can be solved in a general manner, by substituting solutions of the form `x = exp(t)`, and deriving a characteristic equation of form `g(exp(t)) = b_0 f(t) + b_1 f'(t) + b_2 f''(t) \cdots` which can be then solved by nth_linear_constant_coeff_undetermined_coefficients if g(exp(t)) has finite number of linearly independent derivatives. Functions that fit this requirement are finite sums functions of the form `a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i` is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`, and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have a finite number of derivatives, because they can be expanded into `\sin(a x)` and `\cos(b x)` terms. However, SymPy currently cannot do that expansion, so you will need to manually rewrite the expression in terms of the above to use this method. So, for example, you will need to manually convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method of undetermined coefficients on it. After replacement of x by exp(t), this method works by creating a trial function from the expression and all of its linear independent derivatives and substituting them into the original ODE. The coefficients for each term will be a system of linear equations, which are be solved for and substituted, giving the solution. If any of the trial functions are linearly dependent on the solution to the homogeneous equation, they are multiplied by sufficient `x` to make them linearly independent. Examples ======== >>> from sympy import dsolve, Function, Derivative, log >>> from sympy.abc import x >>> f = Function('f') >>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - log(x) >>> dsolve(eq, f(x), ... hint='nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients').expand() Eq(f(x), C1*x + C2*x**2 + log(x)/2 + 3/4) """ x = func.args[0] f = func.func r = match chareq, eq, symbol = S.Zero, S.Zero, Dummy('x') for i in r.keys(): if not isinstance(i, str) and i >= 0: chareq += (r[i]*diff(x**symbol, x, i)*x**-symbol).expand() for i in range(1,degree(Poly(chareq, symbol))+1): eq += chareq.coeff(symbol**i)*diff(f(x), x, i) if chareq.as_coeff_add(symbol)[0]: eq += chareq.as_coeff_add(symbol)[0]*f(x) e, re = posify(r[-1].subs(x, exp(x))) eq += e.subs(re) match = _nth_linear_match(eq, f(x), ode_order(eq, f(x))) eq_homogeneous = Add(eq,-match[-1]) match['trialset'] = _undetermined_coefficients_match(match[-1], x, func, eq_homogeneous)['trialset'] return ode_nth_linear_constant_coeff_undetermined_coefficients(eq, func, order, match).subs(x, log(x)).subs(f(log(x)), f(x)).expand() def ode_nth_linear_euler_eq_nonhomogeneous_variation_of_parameters(eq, func, order, match, returns='sol'): r""" Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional ordinary differential equation using variation of parameters. This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x) \cdots`. This method works by assuming that the particular solution takes the form .. math:: \sum_{x=1}^{n} c_i(x) y_i(x) {a_n} {x^n} \text{,} where `y_i` is the `i`\th solution to the homogeneous equation. The solution is then solved using Wronskian's and Cramer's Rule. The particular solution is given by multiplying eq given below with `a_n x^{n}` .. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \,dx \right) y_i(x) \text{,} where `W(x)` is the Wronskian of the fundamental system (the system of `n` linearly independent solutions to the homogeneous equation), and `W_i(x)` is the Wronskian of the fundamental system with the `i`\th column replaced with `[0, 0, \cdots, 0, \frac{x^{- n}}{a_n} g{\left(x \right)}]`. This method is general enough to solve any `n`\th order inhomogeneous linear differential equation, but sometimes SymPy cannot simplify the Wronskian well enough to integrate it. If this method hangs, try using the ``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and simplifying the integrals manually. Also, prefer using ``nth_linear_constant_coeff_undetermined_coefficients`` when it applies, because it doesn't use integration, making it faster and more reliable. Warning, using simplify=False with 'nth_linear_constant_coeff_variation_of_parameters' in :py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will not attempt to simplify the Wronskian before integrating. It is recommended that you only use simplify=False with 'nth_linear_constant_coeff_variation_of_parameters_Integral' for this method, especially if the solution to the homogeneous equation has trigonometric functions in it. Examples ======== >>> from sympy import Function, dsolve, Derivative >>> from sympy.abc import x >>> f = Function('f') >>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - x**4 >>> dsolve(eq, f(x), ... hint='nth_linear_euler_eq_nonhomogeneous_variation_of_parameters').expand() Eq(f(x), C1*x + C2*x**2 + x**4/6) """ x = func.args[0] f = func.func r = match gensol = ode_nth_linear_euler_eq_homogeneous(eq, func, order, match, returns='both') match.update(gensol) r[-1] = r[-1]/r[ode_order(eq, f(x))] sol = _solve_variation_of_parameters(eq, func, order, match) return Eq(f(x), r['sol'].rhs + (sol.rhs - r['sol'].rhs)*r[ode_order(eq, f(x))]) def _linear_coeff_match(expr, func): r""" Helper function to match hint ``linear_coefficients``. Matches the expression to the form `(a_1 x + b_1 f(x) + c_1)/(a_2 x + b_2 f(x) + c_2)` where the following conditions hold: 1. `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are Rationals; 2. `c_1` or `c_2` are not equal to zero; 3. `a_2 b_1 - a_1 b_2` is not equal to zero. Return ``xarg``, ``yarg`` where 1. ``xarg`` = `(b_2 c_1 - b_1 c_2)/(a_2 b_1 - a_1 b_2)` 2. ``yarg`` = `(a_1 c_2 - a_2 c_1)/(a_2 b_1 - a_1 b_2)` Examples ======== >>> from sympy import Function >>> from sympy.abc import x >>> from sympy.solvers.ode.ode import _linear_coeff_match >>> from sympy.functions.elementary.trigonometric import sin >>> f = Function('f') >>> _linear_coeff_match(( ... (-25*f(x) - 8*x + 62)/(4*f(x) + 11*x - 11)), f(x)) (1/9, 22/9) >>> _linear_coeff_match( ... sin((-5*f(x) - 8*x + 6)/(4*f(x) + x - 1)), f(x)) (19/27, 2/27) >>> _linear_coeff_match(sin(f(x)/x), f(x)) """ f = func.func x = func.args[0] def abc(eq): r''' Internal function of _linear_coeff_match that returns Rationals a, b, c if eq is a*x + b*f(x) + c, else None. ''' eq = _mexpand(eq) c = eq.as_independent(x, f(x), as_Add=True)[0] if not c.is_Rational: return a = eq.coeff(x) if not a.is_Rational: return b = eq.coeff(f(x)) if not b.is_Rational: return if eq == a*x + b*f(x) + c: return a, b, c def match(arg): r''' Internal function of _linear_coeff_match that returns Rationals a1, b1, c1, a2, b2, c2 and a2*b1 - a1*b2 of the expression (a1*x + b1*f(x) + c1)/(a2*x + b2*f(x) + c2) if one of c1 or c2 and a2*b1 - a1*b2 is non-zero, else None. ''' n, d = arg.together().as_numer_denom() m = abc(n) if m is not None: a1, b1, c1 = m m = abc(d) if m is not None: a2, b2, c2 = m d = a2*b1 - a1*b2 if (c1 or c2) and d: return a1, b1, c1, a2, b2, c2, d m = [fi.args[0] for fi in expr.atoms(Function) if fi.func != f and len(fi.args) == 1 and not fi.args[0].is_Function] or {expr} m1 = match(m.pop()) if m1 and all(match(mi) == m1 for mi in m): a1, b1, c1, a2, b2, c2, denom = m1 return (b2*c1 - b1*c2)/denom, (a1*c2 - a2*c1)/denom def ode_linear_coefficients(eq, func, order, match): r""" Solves a differential equation with linear coefficients. The general form of a differential equation with linear coefficients is .. math:: y' + F\left(\!\frac{a_1 x + b_1 y + c_1}{a_2 x + b_2 y + c_2}\!\right) = 0\text{,} where `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are constants and `a_1 b_2 - a_2 b_1 \ne 0`. This can be solved by substituting: .. math:: x = x' + \frac{b_2 c_1 - b_1 c_2}{a_2 b_1 - a_1 b_2} y = y' + \frac{a_1 c_2 - a_2 c_1}{a_2 b_1 - a_1 b_2}\text{.} This substitution reduces the equation to a homogeneous differential equation. See Also ======== :meth:`sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_best` :meth:`sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep` :meth:`sympy.solvers.ode.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep` Examples ======== >>> from sympy import Function, pprint >>> from sympy.solvers.ode.ode import dsolve >>> from sympy.abc import x >>> f = Function('f') >>> df = f(x).diff(x) >>> eq = (x + f(x) + 1)*df + (f(x) - 6*x + 1) >>> dsolve(eq, hint='linear_coefficients') [Eq(f(x), -x - sqrt(C1 + 7*x**2) - 1), Eq(f(x), -x + sqrt(C1 + 7*x**2) - 1)] >>> pprint(dsolve(eq, hint='linear_coefficients')) ___________ ___________ / 2 / 2 [f(x) = -x - \/ C1 + 7*x - 1, f(x) = -x + \/ C1 + 7*x - 1] References ========== - Joel Moses, "Symbolic Integration - The Stormy Decade", Communications of the ACM, Volume 14, Number 8, August 1971, pp. 558 """ return ode_1st_homogeneous_coeff_best(eq, func, order, match) def ode_separable_reduced(eq, func, order, match): r""" Solves a differential equation that can be reduced to the separable form. The general form of this equation is .. math:: y' + (y/x) H(x^n y) = 0\text{}. This can be solved by substituting `u(y) = x^n y`. The equation then reduces to the separable form `\frac{u'}{u (\mathrm{power} - H(u))} - \frac{1}{x} = 0`. The general solution is: >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x, n >>> f, g = map(Function, ['f', 'g']) >>> genform = f(x).diff(x) + (f(x)/x)*g(x**n*f(x)) >>> pprint(genform) / n \ d f(x)*g\x *f(x)/ --(f(x)) + --------------- dx x >>> pprint(dsolve(genform, hint='separable_reduced')) n x *f(x) / | | 1 | ------------ dy = C1 + log(x) | y*(n - g(y)) | / See Also ======== :meth:`sympy.solvers.ode.ode.ode_separable` Examples ======== >>> from sympy import Function, pprint >>> from sympy.solvers.ode.ode import dsolve >>> from sympy.abc import x >>> f = Function('f') >>> d = f(x).diff(x) >>> eq = (x - x**2*f(x))*d - f(x) >>> dsolve(eq, hint='separable_reduced') [Eq(f(x), (1 - sqrt(C1*x**2 + 1))/x), Eq(f(x), (sqrt(C1*x**2 + 1) + 1)/x)] >>> pprint(dsolve(eq, hint='separable_reduced')) ___________ ___________ / 2 / 2 1 - \/ C1*x + 1 \/ C1*x + 1 + 1 [f(x) = ------------------, f(x) = ------------------] x x References ========== - Joel Moses, "Symbolic Integration - The Stormy Decade", Communications of the ACM, Volume 14, Number 8, August 1971, pp. 558 """ # Arguments are passed in a way so that they are coherent with the # ode_separable function x = func.args[0] f = func.func y = Dummy('y') u = match['u'].subs(match['t'], y) ycoeff = 1/(y*(match['power'] - u)) m1 = {y: 1, x: -1/x, 'coeff': 1} m2 = {y: ycoeff, x: 1, 'coeff': 1} r = {'m1': m1, 'm2': m2, 'y': y, 'hint': x**match['power']*f(x)} return ode_separable(eq, func, order, r) def ode_1st_power_series(eq, func, order, match): r""" The power series solution is a method which gives the Taylor series expansion to the solution of a differential equation. For a first order differential equation `\frac{dy}{dx} = h(x, y)`, a power series solution exists at a point `x = x_{0}` if `h(x, y)` is analytic at `x_{0}`. The solution is given by .. math:: y(x) = y(x_{0}) + \sum_{n = 1}^{\infty} \frac{F_{n}(x_{0},b)(x - x_{0})^n}{n!}, where `y(x_{0}) = b` is the value of y at the initial value of `x_{0}`. To compute the values of the `F_{n}(x_{0},b)` the following algorithm is followed, until the required number of terms are generated. 1. `F_1 = h(x_{0}, b)` 2. `F_{n+1} = \frac{\partial F_{n}}{\partial x} + \frac{\partial F_{n}}{\partial y}F_{1}` Examples ======== >>> from sympy import Function, pprint, exp >>> from sympy.solvers.ode.ode import dsolve >>> from sympy.abc import x >>> f = Function('f') >>> eq = exp(x)*(f(x).diff(x)) - f(x) >>> pprint(dsolve(eq, hint='1st_power_series')) 3 4 5 C1*x C1*x C1*x / 6\ f(x) = C1 + C1*x - ----- + ----- + ----- + O\x / 6 24 60 References ========== - Travis W. Walker, Analytic power series technique for solving first-order differential equations, p.p 17, 18 """ x = func.args[0] y = match['y'] f = func.func h = -match[match['d']]/match[match['e']] point = match.get('f0') value = match.get('f0val') terms = match.get('terms') # First term F = h if not h: return Eq(f(x), value) # Initialization series = value if terms > 1: hc = h.subs({x: point, y: value}) if hc.has(oo) or hc.has(NaN) or hc.has(zoo): # Derivative does not exist, not analytic return Eq(f(x), oo) elif hc: series += hc*(x - point) for factcount in range(2, terms): Fnew = F.diff(x) + F.diff(y)*h Fnewc = Fnew.subs({x: point, y: value}) # Same logic as above if Fnewc.has(oo) or Fnewc.has(NaN) or Fnewc.has(-oo) or Fnewc.has(zoo): return Eq(f(x), oo) series += Fnewc*((x - point)**factcount)/factorial(factcount) F = Fnew series += Order(x**terms) return Eq(f(x), series) def ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match, returns='sol'): r""" Solves an `n`\th order linear homogeneous differential equation with constant coefficients. This is an equation of the form .. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x) + a_0 f(x) = 0\text{.} These equations can be solved in a general manner, by taking the roots of the characteristic equation `a_n m^n + a_{n-1} m^{n-1} + \cdots + a_1 m + a_0 = 0`. The solution will then be the sum of `C_n x^i e^{r x}` terms, for each where `C_n` is an arbitrary constant, `r` is a root of the characteristic equation and `i` is one of each from 0 to the multiplicity of the root - 1 (for example, a root 3 of multiplicity 2 would create the terms `C_1 e^{3 x} + C_2 x e^{3 x}`). The exponential is usually expanded for complex roots using Euler's equation `e^{I x} = \cos(x) + I \sin(x)`. Complex roots always come in conjugate pairs in polynomials with real coefficients, so the two roots will be represented (after simplifying the constants) as `e^{a x} \left(C_1 \cos(b x) + C_2 \sin(b x)\right)`. If SymPy cannot find exact roots to the characteristic equation, a :py:class:`~sympy.polys.rootoftools.ComplexRootOf` instance will be return instead. >>> from sympy import Function, dsolve >>> from sympy.abc import x >>> f = Function('f') >>> dsolve(f(x).diff(x, 5) + 10*f(x).diff(x) - 2*f(x), f(x), ... hint='nth_linear_constant_coeff_homogeneous') ... # doctest: +NORMALIZE_WHITESPACE Eq(f(x), C5*exp(x*CRootOf(_x**5 + 10*_x - 2, 0)) + (C1*sin(x*im(CRootOf(_x**5 + 10*_x - 2, 1))) + C2*cos(x*im(CRootOf(_x**5 + 10*_x - 2, 1))))*exp(x*re(CRootOf(_x**5 + 10*_x - 2, 1))) + (C3*sin(x*im(CRootOf(_x**5 + 10*_x - 2, 3))) + C4*cos(x*im(CRootOf(_x**5 + 10*_x - 2, 3))))*exp(x*re(CRootOf(_x**5 + 10*_x - 2, 3)))) Note that because this method does not involve integration, there is no ``nth_linear_constant_coeff_homogeneous_Integral`` hint. The following is for internal use: - ``returns = 'sol'`` returns the solution to the ODE. - ``returns = 'list'`` returns a list of linearly independent solutions, for use with non homogeneous solution methods like variation of parameters and undetermined coefficients. Note that, though the solutions should be linearly independent, this function does not explicitly check that. You can do ``assert simplify(wronskian(sollist)) != 0`` to check for linear independence. Also, ``assert len(sollist) == order`` will need to pass. - ``returns = 'both'``, return a dictionary ``{'sol': <solution to ODE>, 'list': <list of linearly independent solutions>}``. Examples ======== >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(f(x).diff(x, 4) + 2*f(x).diff(x, 3) - ... 2*f(x).diff(x, 2) - 6*f(x).diff(x) + 5*f(x), f(x), ... hint='nth_linear_constant_coeff_homogeneous')) x -2*x f(x) = (C1 + C2*x)*e + (C3*sin(x) + C4*cos(x))*e References ========== - https://en.wikipedia.org/wiki/Linear_differential_equation section: Nonhomogeneous_equation_with_constant_coefficients - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 211 # indirect doctest """ x = func.args[0] f = func.func r = match # First, set up characteristic equation. chareq, symbol = S.Zero, Dummy('x') for i in r.keys(): if type(i) == str or i < 0: pass else: chareq += r[i]*symbol**i chareq = Poly(chareq, symbol) # Can't just call roots because it doesn't return rootof for unsolveable # polynomials. chareqroots = roots(chareq, multiple=True) if len(chareqroots) != order: chareqroots = [rootof(chareq, k) for k in range(chareq.degree())] chareq_is_complex = not all([i.is_real for i in chareq.all_coeffs()]) # A generator of constants constants = list(get_numbered_constants(eq, num=chareq.degree()*2)) # Create a dict root: multiplicity or charroots charroots = defaultdict(int) for root in chareqroots: charroots[root] += 1 # We need to keep track of terms so we can run collect() at the end. # This is necessary for constantsimp to work properly. # # XXX: This global collectterms hack should be removed. global collectterms collectterms = [] gensols = [] conjugate_roots = [] # used to prevent double-use of conjugate roots # Loop over roots in theorder provided by roots/rootof... for root in chareqroots: # but don't repoeat multiple roots. if root not in charroots: continue multiplicity = charroots.pop(root) for i in range(multiplicity): if chareq_is_complex: gensols.append(x**i*exp(root*x)) collectterms = [(i, root, 0)] + collectterms continue reroot = re(root) imroot = im(root) if imroot.has(atan2) and reroot.has(atan2): # Remove this condition when re and im stop returning # circular atan2 usages. gensols.append(x**i*exp(root*x)) collectterms = [(i, root, 0)] + collectterms else: if root in conjugate_roots: collectterms = [(i, reroot, imroot)] + collectterms continue if imroot == 0: gensols.append(x**i*exp(reroot*x)) collectterms = [(i, reroot, 0)] + collectterms continue conjugate_roots.append(conjugate(root)) gensols.append(x**i*exp(reroot*x) * sin(abs(imroot) * x)) gensols.append(x**i*exp(reroot*x) * cos( imroot * x)) # This ordering is important collectterms = [(i, reroot, imroot)] + collectterms if returns == 'list': return gensols elif returns in ('sol' 'both'): gsol = Add(*[i*j for (i, j) in zip(constants, gensols)]) if returns == 'sol': return Eq(f(x), gsol) else: return {'sol': Eq(f(x), gsol), 'list': gensols} else: raise ValueError('Unknown value for key "returns".') def ode_nth_linear_constant_coeff_undetermined_coefficients(eq, func, order, match): r""" Solves an `n`\th order linear differential equation with constant coefficients using the method of undetermined coefficients. This method works on differential equations of the form .. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x) + a_0 f(x) = P(x)\text{,} where `P(x)` is a function that has a finite number of linearly independent derivatives. Functions that fit this requirement are finite sums functions of the form `a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i` is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`, and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have a finite number of derivatives, because they can be expanded into `\sin(a x)` and `\cos(b x)` terms. However, SymPy currently cannot do that expansion, so you will need to manually rewrite the expression in terms of the above to use this method. So, for example, you will need to manually convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method of undetermined coefficients on it. This method works by creating a trial function from the expression and all of its linear independent derivatives and substituting them into the original ODE. The coefficients for each term will be a system of linear equations, which are be solved for and substituted, giving the solution. If any of the trial functions are linearly dependent on the solution to the homogeneous equation, they are multiplied by sufficient `x` to make them linearly independent. Examples ======== >>> from sympy import Function, dsolve, pprint, exp, cos >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(f(x).diff(x, 2) + 2*f(x).diff(x) + f(x) - ... 4*exp(-x)*x**2 + cos(2*x), f(x), ... hint='nth_linear_constant_coeff_undetermined_coefficients')) / / 3\\ | | x || -x 4*sin(2*x) 3*cos(2*x) f(x) = |C1 + x*|C2 + --||*e - ---------- + ---------- \ \ 3 // 25 25 References ========== - https://en.wikipedia.org/wiki/Method_of_undetermined_coefficients - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 221 # indirect doctest """ gensol = ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match, returns='both') match.update(gensol) return _solve_undetermined_coefficients(eq, func, order, match) def _solve_undetermined_coefficients(eq, func, order, match): r""" Helper function for the method of undetermined coefficients. See the :py:meth:`~sympy.solvers.ode.ode.ode_nth_linear_constant_coeff_undetermined_coefficients` docstring for more information on this method. The parameter ``match`` should be a dictionary that has the following keys: ``list`` A list of solutions to the homogeneous equation, such as the list returned by ``ode_nth_linear_constant_coeff_homogeneous(returns='list')``. ``sol`` The general solution, such as the solution returned by ``ode_nth_linear_constant_coeff_homogeneous(returns='sol')``. ``trialset`` The set of trial functions as returned by ``_undetermined_coefficients_match()['trialset']``. """ x = func.args[0] f = func.func r = match coeffs = numbered_symbols('a', cls=Dummy) coefflist = [] gensols = r['list'] gsol = r['sol'] trialset = r['trialset'] if len(gensols) != order: raise NotImplementedError("Cannot find " + str(order) + " solutions to the homogeneous equation necessary to apply" + " undetermined coefficients to " + str(eq) + " (number of terms != order)") trialfunc = 0 for i in trialset: c = next(coeffs) coefflist.append(c) trialfunc += c*i eqs = sub_func_doit(eq, f(x), trialfunc) coeffsdict = dict(list(zip(trialset, [0]*(len(trialset) + 1)))) eqs = _mexpand(eqs) for i in Add.make_args(eqs): s = separatevars(i, dict=True, symbols=[x]) if coeffsdict.get(s[x]): coeffsdict[s[x]] += s['coeff'] else: coeffsdict[s[x]] = s['coeff'] coeffvals = solve(list(coeffsdict.values()), coefflist) if not coeffvals: raise NotImplementedError( "Could not solve `%s` using the " "method of undetermined coefficients " "(unable to solve for coefficients)." % eq) psol = trialfunc.subs(coeffvals) return Eq(f(x), gsol.rhs + psol) def _undetermined_coefficients_match(expr, x, func=None, eq_homogeneous=S.Zero): r""" Returns a trial function match if undetermined coefficients can be applied to ``expr``, and ``None`` otherwise. A trial expression can be found for an expression for use with the method of undetermined coefficients if the expression is an additive/multiplicative combination of constants, polynomials in `x` (the independent variable of expr), `\sin(a x + b)`, `\cos(a x + b)`, and `e^{a x}` terms (in other words, it has a finite number of linearly independent derivatives). Note that you may still need to multiply each term returned here by sufficient `x` to make it linearly independent with the solutions to the homogeneous equation. This is intended for internal use by ``undetermined_coefficients`` hints. SymPy currently has no way to convert `\sin^n(x) \cos^m(y)` into a sum of only `\sin(a x)` and `\cos(b x)` terms, so these are not implemented. So, for example, you will need to manually convert `\sin^2(x)` into `[1 + \cos(2 x)]/2` to properly apply the method of undetermined coefficients on it. Examples ======== >>> from sympy import log, exp >>> from sympy.solvers.ode.ode import _undetermined_coefficients_match >>> from sympy.abc import x >>> _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x) {'test': True, 'trialset': {x*exp(x), exp(-x), exp(x)}} >>> _undetermined_coefficients_match(log(x), x) {'test': False} """ a = Wild('a', exclude=[x]) b = Wild('b', exclude=[x]) expr = powsimp(expr, combine='exp') # exp(x)*exp(2*x + 1) => exp(3*x + 1) retdict = {} def _test_term(expr, x): r""" Test if ``expr`` fits the proper form for undetermined coefficients. """ if not expr.has(x): return True elif expr.is_Add: return all(_test_term(i, x) for i in expr.args) elif expr.is_Mul: if expr.has(sin, cos): foundtrig = False # Make sure that there is only one trig function in the args. # See the docstring. for i in expr.args: if i.has(sin, cos): if foundtrig: return False else: foundtrig = True return all(_test_term(i, x) for i in expr.args) elif expr.is_Function: if expr.func in (sin, cos, exp, sinh, cosh): if expr.args[0].match(a*x + b): return True else: return False else: return False elif expr.is_Pow and expr.base.is_Symbol and expr.exp.is_Integer and \ expr.exp >= 0: return True elif expr.is_Pow and expr.base.is_number: if expr.exp.match(a*x + b): return True else: return False elif expr.is_Symbol or expr.is_number: return True else: return False def _get_trial_set(expr, x, exprs=set([])): r""" Returns a set of trial terms for undetermined coefficients. The idea behind undetermined coefficients is that the terms expression repeat themselves after a finite number of derivatives, except for the coefficients (they are linearly dependent). So if we collect these, we should have the terms of our trial function. """ def _remove_coefficient(expr, x): r""" Returns the expression without a coefficient. Similar to expr.as_independent(x)[1], except it only works multiplicatively. """ term = S.One if expr.is_Mul: for i in expr.args: if i.has(x): term *= i elif expr.has(x): term = expr return term expr = expand_mul(expr) if expr.is_Add: for term in expr.args: if _remove_coefficient(term, x) in exprs: pass else: exprs.add(_remove_coefficient(term, x)) exprs = exprs.union(_get_trial_set(term, x, exprs)) else: term = _remove_coefficient(expr, x) tmpset = exprs.union({term}) oldset = set([]) while tmpset != oldset: # If you get stuck in this loop, then _test_term is probably # broken oldset = tmpset.copy() expr = expr.diff(x) term = _remove_coefficient(expr, x) if term.is_Add: tmpset = tmpset.union(_get_trial_set(term, x, tmpset)) else: tmpset.add(term) exprs = tmpset return exprs def is_homogeneous_solution(term): r""" This function checks whether the given trialset contains any root of homogenous equation""" return expand(sub_func_doit(eq_homogeneous, func, term)).is_zero retdict['test'] = _test_term(expr, x) if retdict['test']: # Try to generate a list of trial solutions that will have the # undetermined coefficients. Note that if any of these are not linearly # independent with any of the solutions to the homogeneous equation, # then they will need to be multiplied by sufficient x to make them so. # This function DOES NOT do that (it doesn't even look at the # homogeneous equation). temp_set = set([]) for i in Add.make_args(expr): act = _get_trial_set(i,x) if eq_homogeneous is not S.Zero: while any(is_homogeneous_solution(ts) for ts in act): act = {x*ts for ts in act} temp_set = temp_set.union(act) retdict['trialset'] = temp_set return retdict def ode_nth_linear_constant_coeff_variation_of_parameters(eq, func, order, match): r""" Solves an `n`\th order linear differential equation with constant coefficients using the method of variation of parameters. This method works on any differential equations of the form .. math:: f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x) + a_0 f(x) = P(x)\text{.} This method works by assuming that the particular solution takes the form .. math:: \sum_{x=1}^{n} c_i(x) y_i(x)\text{,} where `y_i` is the `i`\th solution to the homogeneous equation. The solution is then solved using Wronskian's and Cramer's Rule. The particular solution is given by .. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \,dx \right) y_i(x) \text{,} where `W(x)` is the Wronskian of the fundamental system (the system of `n` linearly independent solutions to the homogeneous equation), and `W_i(x)` is the Wronskian of the fundamental system with the `i`\th column replaced with `[0, 0, \cdots, 0, P(x)]`. This method is general enough to solve any `n`\th order inhomogeneous linear differential equation with constant coefficients, but sometimes SymPy cannot simplify the Wronskian well enough to integrate it. If this method hangs, try using the ``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and simplifying the integrals manually. Also, prefer using ``nth_linear_constant_coeff_undetermined_coefficients`` when it applies, because it doesn't use integration, making it faster and more reliable. Warning, using simplify=False with 'nth_linear_constant_coeff_variation_of_parameters' in :py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will not attempt to simplify the Wronskian before integrating. It is recommended that you only use simplify=False with 'nth_linear_constant_coeff_variation_of_parameters_Integral' for this method, especially if the solution to the homogeneous equation has trigonometric functions in it. Examples ======== >>> from sympy import Function, dsolve, pprint, exp, log >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(f(x).diff(x, 3) - 3*f(x).diff(x, 2) + ... 3*f(x).diff(x) - f(x) - exp(x)*log(x), f(x), ... hint='nth_linear_constant_coeff_variation_of_parameters')) / / / x*log(x) 11*x\\\ x f(x) = |C1 + x*|C2 + x*|C3 + -------- - ----|||*e \ \ \ 6 36 /// References ========== - https://en.wikipedia.org/wiki/Variation_of_parameters - http://planetmath.org/VariationOfParameters - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 233 # indirect doctest """ gensol = ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match, returns='both') match.update(gensol) return _solve_variation_of_parameters(eq, func, order, match) def _solve_variation_of_parameters(eq, func, order, match): r""" Helper function for the method of variation of parameters and nonhomogeneous euler eq. See the :py:meth:`~sympy.solvers.ode.ode.ode_nth_linear_constant_coeff_variation_of_parameters` docstring for more information on this method. The parameter ``match`` should be a dictionary that has the following keys: ``list`` A list of solutions to the homogeneous equation, such as the list returned by ``ode_nth_linear_constant_coeff_homogeneous(returns='list')``. ``sol`` The general solution, such as the solution returned by ``ode_nth_linear_constant_coeff_homogeneous(returns='sol')``. """ x = func.args[0] f = func.func r = match psol = 0 gensols = r['list'] gsol = r['sol'] wr = wronskian(gensols, x) if r.get('simplify', True): wr = simplify(wr) # We need much better simplification for # some ODEs. See issue 4662, for example. # To reduce commonly occurring sin(x)**2 + cos(x)**2 to 1 wr = trigsimp(wr, deep=True, recursive=True) if not wr: # The wronskian will be 0 iff the solutions are not linearly # independent. raise NotImplementedError("Cannot find " + str(order) + " solutions to the homogeneous equation necessary to apply " + "variation of parameters to " + str(eq) + " (Wronskian == 0)") if len(gensols) != order: raise NotImplementedError("Cannot find " + str(order) + " solutions to the homogeneous equation necessary to apply " + "variation of parameters to " + str(eq) + " (number of terms != order)") negoneterm = (-1)**(order) for i in gensols: psol += negoneterm*Integral(wronskian([sol for sol in gensols if sol != i], x)*r[-1]/wr, x)*i/r[order] negoneterm *= -1 if r.get('simplify', True): psol = simplify(psol) psol = trigsimp(psol, deep=True) return Eq(f(x), gsol.rhs + psol) def ode_separable(eq, func, order, match): r""" Solves separable 1st order differential equations. This is any differential equation that can be written as `P(y) \tfrac{dy}{dx} = Q(x)`. The solution can then just be found by rearranging terms and integrating: `\int P(y) \,dy = \int Q(x) \,dx`. This hint uses :py:meth:`sympy.simplify.simplify.separatevars` as its back end, so if a separable equation is not caught by this solver, it is most likely the fault of that function. :py:meth:`~sympy.simplify.simplify.separatevars` is smart enough to do most expansion and factoring necessary to convert a separable equation `F(x, y)` into the proper form `P(x)\cdot{}Q(y)`. The general solution is:: >>> from sympy import Function, dsolve, Eq, pprint >>> from sympy.abc import x >>> a, b, c, d, f = map(Function, ['a', 'b', 'c', 'd', 'f']) >>> genform = Eq(a(x)*b(f(x))*f(x).diff(x), c(x)*d(f(x))) >>> pprint(genform) d a(x)*b(f(x))*--(f(x)) = c(x)*d(f(x)) dx >>> pprint(dsolve(genform, f(x), hint='separable_Integral')) f(x) / / | | | b(y) | c(x) | ---- dy = C1 + | ---- dx | d(y) | a(x) | | / / Examples ======== >>> from sympy import Function, dsolve, Eq >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(Eq(f(x)*f(x).diff(x) + x, 3*x*f(x)**2), f(x), ... hint='separable', simplify=False)) / 2 \ 2 log\3*f (x) - 1/ x ---------------- = C1 + -- 6 2 References ========== - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 52 # indirect doctest """ x = func.args[0] f = func.func C1 = get_numbered_constants(eq, num=1) r = match # {'m1':m1, 'm2':m2, 'y':y} u = r.get('hint', f(x)) # get u from separable_reduced else get f(x) return Eq(Integral(r['m2']['coeff']*r['m2'][r['y']]/r['m1'][r['y']], (r['y'], None, u)), Integral(-r['m1']['coeff']*r['m1'][x]/ r['m2'][x], x) + C1) def checkinfsol(eq, infinitesimals, func=None, order=None): r""" This function is used to check if the given infinitesimals are the actual infinitesimals of the given first order differential equation. This method is specific to the Lie Group Solver of ODEs. As of now, it simply checks, by substituting the infinitesimals in the partial differential equation. .. math:: \frac{\partial \eta}{\partial x} + \left(\frac{\partial \eta}{\partial y} - \frac{\partial \xi}{\partial x}\right)*h - \frac{\partial \xi}{\partial y}*h^{2} - \xi\frac{\partial h}{\partial x} - \eta\frac{\partial h}{\partial y} = 0 where `\eta`, and `\xi` are the infinitesimals and `h(x,y) = \frac{dy}{dx}` The infinitesimals should be given in the form of a list of dicts ``[{xi(x, y): inf, eta(x, y): inf}]``, corresponding to the output of the function infinitesimals. It returns a list of values of the form ``[(True/False, sol)]`` where ``sol`` is the value obtained after substituting the infinitesimals in the PDE. If it is ``True``, then ``sol`` would be 0. """ if isinstance(eq, Equality): eq = eq.lhs - eq.rhs if not func: eq, func = _preprocess(eq) variables = func.args if len(variables) != 1: raise ValueError("ODE's have only one independent variable") else: x = variables[0] if not order: order = ode_order(eq, func) if order != 1: raise NotImplementedError("Lie groups solver has been implemented " "only for first order differential equations") else: df = func.diff(x) a = Wild('a', exclude = [df]) b = Wild('b', exclude = [df]) match = collect(expand(eq), df).match(a*df + b) if match: h = -simplify(match[b]/match[a]) else: try: sol = solve(eq, df) except NotImplementedError: raise NotImplementedError("Infinitesimals for the " "first order ODE could not be found") else: h = sol[0] # Find infinitesimals for one solution y = Dummy('y') h = h.subs(func, y) xi = Function('xi')(x, y) eta = Function('eta')(x, y) dxi = Function('xi')(x, func) deta = Function('eta')(x, func) pde = (eta.diff(x) + (eta.diff(y) - xi.diff(x))*h - (xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y))) soltup = [] for sol in infinitesimals: tsol = {xi: S(sol[dxi]).subs(func, y), eta: S(sol[deta]).subs(func, y)} sol = simplify(pde.subs(tsol).doit()) if sol: soltup.append((False, sol.subs(y, func))) else: soltup.append((True, 0)) return soltup def _ode_lie_group_try_heuristic(eq, heuristic, func, match, inf): xi = Function("xi") eta = Function("eta") f = func.func x = func.args[0] y = match['y'] h = match['h'] tempsol = [] if not inf: try: inf = infinitesimals(eq, hint=heuristic, func=func, order=1, match=match) except ValueError: return None for infsim in inf: xiinf = (infsim[xi(x, func)]).subs(func, y) etainf = (infsim[eta(x, func)]).subs(func, y) # This condition creates recursion while using pdsolve. # Since the first step while solving a PDE of form # a*(f(x, y).diff(x)) + b*(f(x, y).diff(y)) + c = 0 # is to solve the ODE dy/dx = b/a if simplify(etainf/xiinf) == h: continue rpde = f(x, y).diff(x)*xiinf + f(x, y).diff(y)*etainf r = pdsolve(rpde, func=f(x, y)).rhs s = pdsolve(rpde - 1, func=f(x, y)).rhs newcoord = [_lie_group_remove(coord) for coord in [r, s]] r = Dummy("r") s = Dummy("s") C1 = Symbol("C1") rcoord = newcoord[0] scoord = newcoord[-1] try: sol = solve([r - rcoord, s - scoord], x, y, dict=True) if sol == []: continue except NotImplementedError: continue else: sol = sol[0] xsub = sol[x] ysub = sol[y] num = simplify(scoord.diff(x) + scoord.diff(y)*h) denom = simplify(rcoord.diff(x) + rcoord.diff(y)*h) if num and denom: diffeq = simplify((num/denom).subs([(x, xsub), (y, ysub)])) sep = separatevars(diffeq, symbols=[r, s], dict=True) if sep: # Trying to separate, r and s coordinates deq = integrate((1/sep[s]), s) + C1 - integrate(sep['coeff']*sep[r], r) # Substituting and reverting back to original coordinates deq = deq.subs([(r, rcoord), (s, scoord)]) try: sdeq = solve(deq, y) except NotImplementedError: tempsol.append(deq) else: return [Eq(f(x), sol) for sol in sdeq] elif denom: # (ds/dr) is zero which means s is constant return [Eq(f(x), solve(scoord - C1, y)[0])] elif num: # (dr/ds) is zero which means r is constant return [Eq(f(x), solve(rcoord - C1, y)[0])] # If nothing works, return solution as it is, without solving for y if tempsol: return [Eq(sol.subs(y, f(x)), 0) for sol in tempsol] return None def _ode_lie_group( s, func, order, match): heuristics = lie_heuristics inf = {} f = func.func x = func.args[0] df = func.diff(x) xi = Function("xi") eta = Function("eta") xis = match['xi'] etas = match['eta'] y = match.pop('y', None) if y: h = -simplify(match[match['d']]/match[match['e']]) y = y else: y = Dummy("y") h = s.subs(func, y) if xis is not None and etas is not None: inf = [{xi(x, f(x)): S(xis), eta(x, f(x)): S(etas)}] if checkinfsol(Eq(df, s), inf, func=f(x), order=1)[0][0]: heuristics = ["user_defined"] + list(heuristics) match = {'h': h, 'y': y} # This is done so that if any heuristic raises a ValueError # another heuristic can be used. sol = None for heuristic in heuristics: sol = _ode_lie_group_try_heuristic(Eq(df, s), heuristic, func, match, inf) if sol: return sol return sol def ode_lie_group(eq, func, order, match): r""" This hint implements the Lie group method of solving first order differential equations. The aim is to convert the given differential equation from the given coordinate system into another coordinate system where it becomes invariant under the one-parameter Lie group of translations. The converted ODE can be easily solved by quadrature. It makes use of the :py:meth:`sympy.solvers.ode.infinitesimals` function which returns the infinitesimals of the transformation. The coordinates `r` and `s` can be found by solving the following Partial Differential Equations. .. math :: \xi\frac{\partial r}{\partial x} + \eta\frac{\partial r}{\partial y} = 0 .. math :: \xi\frac{\partial s}{\partial x} + \eta\frac{\partial s}{\partial y} = 1 The differential equation becomes separable in the new coordinate system .. math :: \frac{ds}{dr} = \frac{\frac{\partial s}{\partial x} + h(x, y)\frac{\partial s}{\partial y}}{ \frac{\partial r}{\partial x} + h(x, y)\frac{\partial r}{\partial y}} After finding the solution by integration, it is then converted back to the original coordinate system by substituting `r` and `s` in terms of `x` and `y` again. Examples ======== >>> from sympy import Function, dsolve, exp, pprint >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(f(x).diff(x) + 2*x*f(x) - x*exp(-x**2), f(x), ... hint='lie_group')) / 2\ 2 | x | -x f(x) = |C1 + --|*e \ 2 / References ========== - Solving differential equations by Symmetry Groups, John Starrett, pp. 1 - pp. 14 """ x = func.args[0] df = func.diff(x) try: eqsol = solve(eq, df) except NotImplementedError: eqsol = [] desols = [] for s in eqsol: sol = _ode_lie_group(s, func, order, match=match) if sol: desols.extend(sol) if desols == []: raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by" + " the lie group method") return desols def _lie_group_remove(coords): r""" This function is strictly meant for internal use by the Lie group ODE solving method. It replaces arbitrary functions returned by pdsolve as follows: 1] If coords is an arbitrary function, then its argument is returned. 2] An arbitrary function in an Add object is replaced by zero. 3] An arbitrary function in a Mul object is replaced by one. 4] If there is no arbitrary function coords is returned unchanged. Examples ======== >>> from sympy.solvers.ode.ode import _lie_group_remove >>> from sympy import Function >>> from sympy.abc import x, y >>> F = Function("F") >>> eq = x**2*y >>> _lie_group_remove(eq) x**2*y >>> eq = F(x**2*y) >>> _lie_group_remove(eq) x**2*y >>> eq = x*y**2 + F(x**3) >>> _lie_group_remove(eq) x*y**2 >>> eq = (F(x**3) + y)*x**4 >>> _lie_group_remove(eq) x**4*y """ if isinstance(coords, AppliedUndef): return coords.args[0] elif coords.is_Add: subfunc = coords.atoms(AppliedUndef) if subfunc: for func in subfunc: coords = coords.subs(func, 0) return coords elif coords.is_Pow: base, expr = coords.as_base_exp() base = _lie_group_remove(base) expr = _lie_group_remove(expr) return base**expr elif coords.is_Mul: mulargs = [] coordargs = coords.args for arg in coordargs: if not isinstance(coords, AppliedUndef): mulargs.append(_lie_group_remove(arg)) return Mul(*mulargs) return coords def infinitesimals(eq, func=None, order=None, hint='default', match=None): r""" The infinitesimal functions of an ordinary differential equation, `\xi(x,y)` and `\eta(x,y)`, are the infinitesimals of the Lie group of point transformations for which the differential equation is invariant. So, the ODE `y'=f(x,y)` would admit a Lie group `x^*=X(x,y;\varepsilon)=x+\varepsilon\xi(x,y)`, `y^*=Y(x,y;\varepsilon)=y+\varepsilon\eta(x,y)` such that `(y^*)'=f(x^*, y^*)`. A change of coordinates, to `r(x,y)` and `s(x,y)`, can be performed so this Lie group becomes the translation group, `r^*=r` and `s^*=s+\varepsilon`. They are tangents to the coordinate curves of the new system. Consider the transformation `(x, y) \to (X, Y)` such that the differential equation remains invariant. `\xi` and `\eta` are the tangents to the transformed coordinates `X` and `Y`, at `\varepsilon=0`. .. math:: \left(\frac{\partial X(x,y;\varepsilon)}{\partial\varepsilon }\right)|_{\varepsilon=0} = \xi, \left(\frac{\partial Y(x,y;\varepsilon)}{\partial\varepsilon }\right)|_{\varepsilon=0} = \eta, The infinitesimals can be found by solving the following PDE: >>> from sympy import Function, Eq, pprint >>> from sympy.abc import x, y >>> xi, eta, h = map(Function, ['xi', 'eta', 'h']) >>> h = h(x, y) # dy/dx = h >>> eta = eta(x, y) >>> xi = xi(x, y) >>> genform = Eq(eta.diff(x) + (eta.diff(y) - xi.diff(x))*h ... - (xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)), 0) >>> pprint(genform) /d d \ d 2 d |--(eta(x, y)) - --(xi(x, y))|*h(x, y) - eta(x, y)*--(h(x, y)) - h (x, y)*--(x \dy dx / dy dy <BLANKLINE> d d i(x, y)) - xi(x, y)*--(h(x, y)) + --(eta(x, y)) = 0 dx dx Solving the above mentioned PDE is not trivial, and can be solved only by making intelligent assumptions for `\xi` and `\eta` (heuristics). Once an infinitesimal is found, the attempt to find more heuristics stops. This is done to optimise the speed of solving the differential equation. If a list of all the infinitesimals is needed, ``hint`` should be flagged as ``all``, which gives the complete list of infinitesimals. If the infinitesimals for a particular heuristic needs to be found, it can be passed as a flag to ``hint``. Examples ======== >>> from sympy import Function >>> from sympy.solvers.ode.ode import infinitesimals >>> from sympy.abc import x >>> f = Function('f') >>> eq = f(x).diff(x) - x**2*f(x) >>> infinitesimals(eq) [{eta(x, f(x)): exp(x**3/3), xi(x, f(x)): 0}] References ========== - Solving differential equations by Symmetry Groups, John Starrett, pp. 1 - pp. 14 """ if isinstance(eq, Equality): eq = eq.lhs - eq.rhs if not func: eq, func = _preprocess(eq) variables = func.args if len(variables) != 1: raise ValueError("ODE's have only one independent variable") else: x = variables[0] if not order: order = ode_order(eq, func) if order != 1: raise NotImplementedError("Infinitesimals for only " "first order ODE's have been implemented") else: df = func.diff(x) # Matching differential equation of the form a*df + b a = Wild('a', exclude = [df]) b = Wild('b', exclude = [df]) if match: # Used by lie_group hint h = match['h'] y = match['y'] else: match = collect(expand(eq), df).match(a*df + b) if match: h = -simplify(match[b]/match[a]) else: try: sol = solve(eq, df) except NotImplementedError: raise NotImplementedError("Infinitesimals for the " "first order ODE could not be found") else: h = sol[0] # Find infinitesimals for one solution y = Dummy("y") h = h.subs(func, y) u = Dummy("u") hx = h.diff(x) hy = h.diff(y) hinv = ((1/h).subs([(x, u), (y, x)])).subs(u, y) # Inverse ODE match = {'h': h, 'func': func, 'hx': hx, 'hy': hy, 'y': y, 'hinv': hinv} if hint == 'all': xieta = [] for heuristic in lie_heuristics: function = globals()['lie_heuristic_' + heuristic] inflist = function(match, comp=True) if inflist: xieta.extend([inf for inf in inflist if inf not in xieta]) if xieta: return xieta else: raise NotImplementedError("Infinitesimals could not be found for " "the given ODE") elif hint == 'default': for heuristic in lie_heuristics: function = globals()['lie_heuristic_' + heuristic] xieta = function(match, comp=False) if xieta: return xieta raise NotImplementedError("Infinitesimals could not be found for" " the given ODE") elif hint not in lie_heuristics: raise ValueError("Heuristic not recognized: " + hint) else: function = globals()['lie_heuristic_' + hint] xieta = function(match, comp=True) if xieta: return xieta else: raise ValueError("Infinitesimals could not be found using the" " given heuristic") def lie_heuristic_abaco1_simple(match, comp=False): r""" The first heuristic uses the following four sets of assumptions on `\xi` and `\eta` .. math:: \xi = 0, \eta = f(x) .. math:: \xi = 0, \eta = f(y) .. math:: \xi = f(x), \eta = 0 .. math:: \xi = f(y), \eta = 0 The success of this heuristic is determined by algebraic factorisation. For the first assumption `\xi = 0` and `\eta` to be a function of `x`, the PDE .. math:: \frac{\partial \eta}{\partial x} + (\frac{\partial \eta}{\partial y} - \frac{\partial \xi}{\partial x})*h - \frac{\partial \xi}{\partial y}*h^{2} - \xi*\frac{\partial h}{\partial x} - \eta*\frac{\partial h}{\partial y} = 0 reduces to `f'(x) - f\frac{\partial h}{\partial y} = 0` If `\frac{\partial h}{\partial y}` is a function of `x`, then this can usually be integrated easily. A similar idea is applied to the other 3 assumptions as well. References ========== - E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra Solving of First Order ODEs Using Symmetry Methods, pp. 8 """ xieta = [] y = match['y'] h = match['h'] func = match['func'] x = func.args[0] hx = match['hx'] hy = match['hy'] xi = Function('xi')(x, func) eta = Function('eta')(x, func) hysym = hy.free_symbols if y not in hysym: try: fx = exp(integrate(hy, x)) except NotImplementedError: pass else: inf = {xi: S.Zero, eta: fx} if not comp: return [inf] if comp and inf not in xieta: xieta.append(inf) factor = hy/h facsym = factor.free_symbols if x not in facsym: try: fy = exp(integrate(factor, y)) except NotImplementedError: pass else: inf = {xi: S.Zero, eta: fy.subs(y, func)} if not comp: return [inf] if comp and inf not in xieta: xieta.append(inf) factor = -hx/h facsym = factor.free_symbols if y not in facsym: try: fx = exp(integrate(factor, x)) except NotImplementedError: pass else: inf = {xi: fx, eta: S.Zero} if not comp: return [inf] if comp and inf not in xieta: xieta.append(inf) factor = -hx/(h**2) facsym = factor.free_symbols if x not in facsym: try: fy = exp(integrate(factor, y)) except NotImplementedError: pass else: inf = {xi: fy.subs(y, func), eta: S.Zero} if not comp: return [inf] if comp and inf not in xieta: xieta.append(inf) if xieta: return xieta def lie_heuristic_abaco1_product(match, comp=False): r""" The second heuristic uses the following two assumptions on `\xi` and `\eta` .. math:: \eta = 0, \xi = f(x)*g(y) .. math:: \eta = f(x)*g(y), \xi = 0 The first assumption of this heuristic holds good if `\frac{1}{h^{2}}\frac{\partial^2}{\partial x \partial y}\log(h)` is separable in `x` and `y`, then the separated factors containing `x` is `f(x)`, and `g(y)` is obtained by .. math:: e^{\int f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)\,dy} provided `f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)` is a function of `y` only. The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as `\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption satisfies. After obtaining `f(x)` and `g(y)`, the coordinates are again interchanged, to get `\eta` as `f(x)*g(y)` References ========== - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order ODE Patterns, pp. 7 - pp. 8 """ xieta = [] y = match['y'] h = match['h'] hinv = match['hinv'] func = match['func'] x = func.args[0] xi = Function('xi')(x, func) eta = Function('eta')(x, func) inf = separatevars(((log(h).diff(y)).diff(x))/h**2, dict=True, symbols=[x, y]) if inf and inf['coeff']: fx = inf[x] gy = simplify(fx*((1/(fx*h)).diff(x))) gysyms = gy.free_symbols if x not in gysyms: gy = exp(integrate(gy, y)) inf = {eta: S.Zero, xi: (fx*gy).subs(y, func)} if not comp: return [inf] if comp and inf not in xieta: xieta.append(inf) u1 = Dummy("u1") inf = separatevars(((log(hinv).diff(y)).diff(x))/hinv**2, dict=True, symbols=[x, y]) if inf and inf['coeff']: fx = inf[x] gy = simplify(fx*((1/(fx*hinv)).diff(x))) gysyms = gy.free_symbols if x not in gysyms: gy = exp(integrate(gy, y)) etaval = fx*gy etaval = (etaval.subs([(x, u1), (y, x)])).subs(u1, y) inf = {eta: etaval.subs(y, func), xi: S.Zero} if not comp: return [inf] if comp and inf not in xieta: xieta.append(inf) if xieta: return xieta def lie_heuristic_bivariate(match, comp=False): r""" The third heuristic assumes the infinitesimals `\xi` and `\eta` to be bi-variate polynomials in `x` and `y`. The assumption made here for the logic below is that `h` is a rational function in `x` and `y` though that may not be necessary for the infinitesimals to be bivariate polynomials. The coefficients of the infinitesimals are found out by substituting them in the PDE and grouping similar terms that are polynomials and since they form a linear system, solve and check for non trivial solutions. The degree of the assumed bivariates are increased till a certain maximum value. References ========== - Lie Groups and Differential Equations pp. 327 - pp. 329 """ h = match['h'] hx = match['hx'] hy = match['hy'] func = match['func'] x = func.args[0] y = match['y'] xi = Function('xi')(x, func) eta = Function('eta')(x, func) if h.is_rational_function(): # The maximum degree that the infinitesimals can take is # calculated by this technique. etax, etay, etad, xix, xiy, xid = symbols("etax etay etad xix xiy xid") ipde = etax + (etay - xix)*h - xiy*h**2 - xid*hx - etad*hy num, denom = cancel(ipde).as_numer_denom() deg = Poly(num, x, y).total_degree() deta = Function('deta')(x, y) dxi = Function('dxi')(x, y) ipde = (deta.diff(x) + (deta.diff(y) - dxi.diff(x))*h - (dxi.diff(y))*h**2 - dxi*hx - deta*hy) xieq = Symbol("xi0") etaeq = Symbol("eta0") for i in range(deg + 1): if i: xieq += Add(*[ Symbol("xi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power) for power in range(i + 1)]) etaeq += Add(*[ Symbol("eta_" + str(power) + "_" + str(i - power))*x**power*y**(i - power) for power in range(i + 1)]) pden, denom = (ipde.subs({dxi: xieq, deta: etaeq}).doit()).as_numer_denom() pden = expand(pden) # If the individual terms are monomials, the coefficients # are grouped if pden.is_polynomial(x, y) and pden.is_Add: polyy = Poly(pden, x, y).as_dict() if polyy: symset = xieq.free_symbols.union(etaeq.free_symbols) - {x, y} soldict = solve(polyy.values(), *symset) if isinstance(soldict, list): soldict = soldict[0] if any(soldict.values()): xired = xieq.subs(soldict) etared = etaeq.subs(soldict) # Scaling is done by substituting one for the parameters # This can be any number except zero. dict_ = dict((sym, 1) for sym in symset) inf = {eta: etared.subs(dict_).subs(y, func), xi: xired.subs(dict_).subs(y, func)} return [inf] def lie_heuristic_chi(match, comp=False): r""" The aim of the fourth heuristic is to find the function `\chi(x, y)` that satisfies the PDE `\frac{d\chi}{dx} + h\frac{d\chi}{dx} - \frac{\partial h}{\partial y}\chi = 0`. This assumes `\chi` to be a bivariate polynomial in `x` and `y`. By intuition, `h` should be a rational function in `x` and `y`. The method used here is to substitute a general binomial for `\chi` up to a certain maximum degree is reached. The coefficients of the polynomials, are calculated by by collecting terms of the same order in `x` and `y`. After finding `\chi`, the next step is to use `\eta = \xi*h + \chi`, to determine `\xi` and `\eta`. This can be done by dividing `\chi` by `h` which would give `-\xi` as the quotient and `\eta` as the remainder. References ========== - E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra Solving of First Order ODEs Using Symmetry Methods, pp. 8 """ h = match['h'] hy = match['hy'] func = match['func'] x = func.args[0] y = match['y'] xi = Function('xi')(x, func) eta = Function('eta')(x, func) if h.is_rational_function(): schi, schix, schiy = symbols("schi, schix, schiy") cpde = schix + h*schiy - hy*schi num, denom = cancel(cpde).as_numer_denom() deg = Poly(num, x, y).total_degree() chi = Function('chi')(x, y) chix = chi.diff(x) chiy = chi.diff(y) cpde = chix + h*chiy - hy*chi chieq = Symbol("chi") for i in range(1, deg + 1): chieq += Add(*[ Symbol("chi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power) for power in range(i + 1)]) cnum, cden = cancel(cpde.subs({chi : chieq}).doit()).as_numer_denom() cnum = expand(cnum) if cnum.is_polynomial(x, y) and cnum.is_Add: cpoly = Poly(cnum, x, y).as_dict() if cpoly: solsyms = chieq.free_symbols - {x, y} soldict = solve(cpoly.values(), *solsyms) if isinstance(soldict, list): soldict = soldict[0] if any(soldict.values()): chieq = chieq.subs(soldict) dict_ = dict((sym, 1) for sym in solsyms) chieq = chieq.subs(dict_) # After finding chi, the main aim is to find out # eta, xi by the equation eta = xi*h + chi # One method to set xi, would be rearranging it to # (eta/h) - xi = (chi/h). This would mean dividing # chi by h would give -xi as the quotient and eta # as the remainder. Thanks to Sean Vig for suggesting # this method. xic, etac = div(chieq, h) inf = {eta: etac.subs(y, func), xi: -xic.subs(y, func)} return [inf] def lie_heuristic_function_sum(match, comp=False): r""" This heuristic uses the following two assumptions on `\xi` and `\eta` .. math:: \eta = 0, \xi = f(x) + g(y) .. math:: \eta = f(x) + g(y), \xi = 0 The first assumption of this heuristic holds good if .. math:: \frac{\partial}{\partial y}[(h\frac{\partial^{2}}{ \partial x^{2}}(h^{-1}))^{-1}] is separable in `x` and `y`, 1. The separated factors containing `y` is `\frac{\partial g}{\partial y}`. From this `g(y)` can be determined. 2. The separated factors containing `x` is `f''(x)`. 3. `h\frac{\partial^{2}}{\partial x^{2}}(h^{-1})` equals `\frac{f''(x)}{f(x) + g(y)}`. From this `f(x)` can be determined. The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as `\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption satisfies. After obtaining `f(x)` and `g(y)`, the coordinates are again interchanged, to get `\eta` as `f(x) + g(y)`. For both assumptions, the constant factors are separated among `g(y)` and `f''(x)`, such that `f''(x)` obtained from 3] is the same as that obtained from 2]. If not possible, then this heuristic fails. References ========== - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order ODE Patterns, pp. 7 - pp. 8 """ xieta = [] h = match['h'] func = match['func'] hinv = match['hinv'] x = func.args[0] y = match['y'] xi = Function('xi')(x, func) eta = Function('eta')(x, func) for odefac in [h, hinv]: factor = odefac*((1/odefac).diff(x, 2)) sep = separatevars((1/factor).diff(y), dict=True, symbols=[x, y]) if sep and sep['coeff'] and sep[x].has(x) and sep[y].has(y): k = Dummy("k") try: gy = k*integrate(sep[y], y) except NotImplementedError: pass else: fdd = 1/(k*sep[x]*sep['coeff']) fx = simplify(fdd/factor - gy) check = simplify(fx.diff(x, 2) - fdd) if fx: if not check: fx = fx.subs(k, 1) gy = (gy/k) else: sol = solve(check, k) if sol: sol = sol[0] fx = fx.subs(k, sol) gy = (gy/k)*sol else: continue if odefac == hinv: # Inverse ODE fx = fx.subs(x, y) gy = gy.subs(y, x) etaval = factor_terms(fx + gy) if etaval.is_Mul: etaval = Mul(*[arg for arg in etaval.args if arg.has(x, y)]) if odefac == hinv: # Inverse ODE inf = {eta: etaval.subs(y, func), xi : S.Zero} else: inf = {xi: etaval.subs(y, func), eta : S.Zero} if not comp: return [inf] else: xieta.append(inf) if xieta: return xieta def lie_heuristic_abaco2_similar(match, comp=False): r""" This heuristic uses the following two assumptions on `\xi` and `\eta` .. math:: \eta = g(x), \xi = f(x) .. math:: \eta = f(y), \xi = g(y) For the first assumption, 1. First `\frac{\frac{\partial h}{\partial y}}{\frac{\partial^{2} h}{ \partial yy}}` is calculated. Let us say this value is A 2. If this is constant, then `h` is matched to the form `A(x) + B(x)e^{ \frac{y}{C}}` then, `\frac{e^{\int \frac{A(x)}{C} \,dx}}{B(x)}` gives `f(x)` and `A(x)*f(x)` gives `g(x)` 3. Otherwise `\frac{\frac{\partial A}{\partial X}}{\frac{\partial A}{ \partial Y}} = \gamma` is calculated. If a] `\gamma` is a function of `x` alone b] `\frac{\gamma\frac{\partial h}{\partial y} - \gamma'(x) - \frac{ \partial h}{\partial x}}{h + \gamma} = G` is a function of `x` alone. then, `e^{\int G \,dx}` gives `f(x)` and `-\gamma*f(x)` gives `g(x)` The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as `\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption satisfies. After obtaining `f(x)` and `g(x)`, the coordinates are again interchanged, to get `\xi` as `f(x^*)` and `\eta` as `g(y^*)` References ========== - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order ODE Patterns, pp. 10 - pp. 12 """ h = match['h'] hx = match['hx'] hy = match['hy'] func = match['func'] hinv = match['hinv'] x = func.args[0] y = match['y'] xi = Function('xi')(x, func) eta = Function('eta')(x, func) factor = cancel(h.diff(y)/h.diff(y, 2)) factorx = factor.diff(x) factory = factor.diff(y) if not factor.has(x) and not factor.has(y): A = Wild('A', exclude=[y]) B = Wild('B', exclude=[y]) C = Wild('C', exclude=[x, y]) match = h.match(A + B*exp(y/C)) try: tau = exp(-integrate(match[A]/match[C]), x)/match[B] except NotImplementedError: pass else: gx = match[A]*tau return [{xi: tau, eta: gx}] else: gamma = cancel(factorx/factory) if not gamma.has(y): tauint = cancel((gamma*hy - gamma.diff(x) - hx)/(h + gamma)) if not tauint.has(y): try: tau = exp(integrate(tauint, x)) except NotImplementedError: pass else: gx = -tau*gamma return [{xi: tau, eta: gx}] factor = cancel(hinv.diff(y)/hinv.diff(y, 2)) factorx = factor.diff(x) factory = factor.diff(y) if not factor.has(x) and not factor.has(y): A = Wild('A', exclude=[y]) B = Wild('B', exclude=[y]) C = Wild('C', exclude=[x, y]) match = h.match(A + B*exp(y/C)) try: tau = exp(-integrate(match[A]/match[C]), x)/match[B] except NotImplementedError: pass else: gx = match[A]*tau return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}] else: gamma = cancel(factorx/factory) if not gamma.has(y): tauint = cancel((gamma*hinv.diff(y) - gamma.diff(x) - hinv.diff(x))/( hinv + gamma)) if not tauint.has(y): try: tau = exp(integrate(tauint, x)) except NotImplementedError: pass else: gx = -tau*gamma return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}] def lie_heuristic_abaco2_unique_unknown(match, comp=False): r""" This heuristic assumes the presence of unknown functions or known functions with non-integer powers. 1. A list of all functions and non-integer powers containing x and y 2. Loop over each element `f` in the list, find `\frac{\frac{\partial f}{\partial x}}{ \frac{\partial f}{\partial x}} = R` If it is separable in `x` and `y`, let `X` be the factors containing `x`. Then a] Check if `\xi = X` and `\eta = -\frac{X}{R}` satisfy the PDE. If yes, then return `\xi` and `\eta` b] Check if `\xi = \frac{-R}{X}` and `\eta = -\frac{1}{X}` satisfy the PDE. If yes, then return `\xi` and `\eta` If not, then check if a] :math:`\xi = -R,\eta = 1` b] :math:`\xi = 1, \eta = -\frac{1}{R}` are solutions. References ========== - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order ODE Patterns, pp. 10 - pp. 12 """ h = match['h'] hx = match['hx'] hy = match['hy'] func = match['func'] x = func.args[0] y = match['y'] xi = Function('xi')(x, func) eta = Function('eta')(x, func) funclist = [] for atom in h.atoms(Pow): base, exp = atom.as_base_exp() if base.has(x) and base.has(y): if not exp.is_Integer: funclist.append(atom) for function in h.atoms(AppliedUndef): syms = function.free_symbols if x in syms and y in syms: funclist.append(function) for f in funclist: frac = cancel(f.diff(y)/f.diff(x)) sep = separatevars(frac, dict=True, symbols=[x, y]) if sep and sep['coeff']: xitry1 = sep[x] etatry1 = -1/(sep[y]*sep['coeff']) pde1 = etatry1.diff(y)*h - xitry1.diff(x)*h - xitry1*hx - etatry1*hy if not simplify(pde1): return [{xi: xitry1, eta: etatry1.subs(y, func)}] xitry2 = 1/etatry1 etatry2 = 1/xitry1 pde2 = etatry2.diff(x) - (xitry2.diff(y))*h**2 - xitry2*hx - etatry2*hy if not simplify(expand(pde2)): return [{xi: xitry2.subs(y, func), eta: etatry2}] else: etatry = -1/frac pde = etatry.diff(x) + etatry.diff(y)*h - hx - etatry*hy if not simplify(pde): return [{xi: S.One, eta: etatry.subs(y, func)}] xitry = -frac pde = -xitry.diff(x)*h -xitry.diff(y)*h**2 - xitry*hx -hy if not simplify(expand(pde)): return [{xi: xitry.subs(y, func), eta: S.One}] def lie_heuristic_abaco2_unique_general(match, comp=False): r""" This heuristic finds if infinitesimals of the form `\eta = f(x)`, `\xi = g(y)` without making any assumptions on `h`. The complete sequence of steps is given in the paper mentioned below. References ========== - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order ODE Patterns, pp. 10 - pp. 12 """ hx = match['hx'] hy = match['hy'] func = match['func'] x = func.args[0] y = match['y'] xi = Function('xi')(x, func) eta = Function('eta')(x, func) A = hx.diff(y) B = hy.diff(y) + hy**2 C = hx.diff(x) - hx**2 if not (A and B and C): return Ax = A.diff(x) Ay = A.diff(y) Axy = Ax.diff(y) Axx = Ax.diff(x) Ayy = Ay.diff(y) D = simplify(2*Axy + hx*Ay - Ax*hy + (hx*hy + 2*A)*A)*A - 3*Ax*Ay if not D: E1 = simplify(3*Ax**2 + ((hx**2 + 2*C)*A - 2*Axx)*A) if E1: E2 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2) if not E2: E3 = simplify( E1*((28*Ax + 4*hx*A)*A**3 - E1*(hy*A + Ay)) - E1.diff(x)*8*A**4) if not E3: etaval = cancel((4*A**3*(Ax - hx*A) + E1*(hy*A - Ay))/(S(2)*A*E1)) if x not in etaval: try: etaval = exp(integrate(etaval, y)) except NotImplementedError: pass else: xival = -4*A**3*etaval/E1 if y not in xival: return [{xi: xival, eta: etaval.subs(y, func)}] else: E1 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2) if E1: E2 = simplify( 4*A**3*D - D**2 + E1*((2*Axx - (hx**2 + 2*C)*A)*A - 3*Ax**2)) if not E2: E3 = simplify( -(A*D)*E1.diff(y) + ((E1.diff(x) - hy*D)*A + 3*Ay*D + (A*hx - 3*Ax)*E1)*E1) if not E3: etaval = cancel(((A*hx - Ax)*E1 - (Ay + A*hy)*D)/(S(2)*A*D)) if x not in etaval: try: etaval = exp(integrate(etaval, y)) except NotImplementedError: pass else: xival = -E1*etaval/D if y not in xival: return [{xi: xival, eta: etaval.subs(y, func)}] def lie_heuristic_linear(match, comp=False): r""" This heuristic assumes 1. `\xi = ax + by + c` and 2. `\eta = fx + gy + h` After substituting the following assumptions in the determining PDE, it reduces to .. math:: f + (g - a)h - bh^{2} - (ax + by + c)\frac{\partial h}{\partial x} - (fx + gy + c)\frac{\partial h}{\partial y} Solving the reduced PDE obtained, using the method of characteristics, becomes impractical. The method followed is grouping similar terms and solving the system of linear equations obtained. The difference between the bivariate heuristic is that `h` need not be a rational function in this case. References ========== - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order ODE Patterns, pp. 10 - pp. 12 """ h = match['h'] hx = match['hx'] hy = match['hy'] func = match['func'] x = func.args[0] y = match['y'] xi = Function('xi')(x, func) eta = Function('eta')(x, func) coeffdict = {} symbols = numbered_symbols("c", cls=Dummy) symlist = [next(symbols) for _ in islice(symbols, 6)] C0, C1, C2, C3, C4, C5 = symlist pde = C3 + (C4 - C0)*h - (C0*x + C1*y + C2)*hx - (C3*x + C4*y + C5)*hy - C1*h**2 pde, denom = pde.as_numer_denom() pde = powsimp(expand(pde)) if pde.is_Add: terms = pde.args for term in terms: if term.is_Mul: rem = Mul(*[m for m in term.args if not m.has(x, y)]) xypart = term/rem if xypart not in coeffdict: coeffdict[xypart] = rem else: coeffdict[xypart] += rem else: if term not in coeffdict: coeffdict[term] = S.One else: coeffdict[term] += S.One sollist = coeffdict.values() soldict = solve(sollist, symlist) if soldict: if isinstance(soldict, list): soldict = soldict[0] subval = soldict.values() if any(t for t in subval): onedict = dict(zip(symlist, [1]*6)) xival = C0*x + C1*func + C2 etaval = C3*x + C4*func + C5 xival = xival.subs(soldict) etaval = etaval.subs(soldict) xival = xival.subs(onedict) etaval = etaval.subs(onedict) return [{xi: xival, eta: etaval}] def sysode_linear_2eq_order1(match_): x = match_['func'][0].func y = match_['func'][1].func func = match_['func'] fc = match_['func_coeff'] eq = match_['eq'] r = dict() t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] for i in range(2): eqs = 0 for terms in Add.make_args(eq[i]): eqs += terms/fc[i,func[i],1] eq[i] = eqs # for equations Eq(a1*diff(x(t),t), a*x(t) + b*y(t) + k1) # and Eq(a2*diff(x(t),t), c*x(t) + d*y(t) + k2) r['a'] = -fc[0,x(t),0]/fc[0,x(t),1] r['c'] = -fc[1,x(t),0]/fc[1,y(t),1] r['b'] = -fc[0,y(t),0]/fc[0,x(t),1] r['d'] = -fc[1,y(t),0]/fc[1,y(t),1] forcing = [S.Zero,S.Zero] for i in range(2): for j in Add.make_args(eq[i]): if not j.has(x(t), y(t)): forcing[i] += j if not (forcing[0].has(t) or forcing[1].has(t)): r['k1'] = forcing[0] r['k2'] = forcing[1] else: raise NotImplementedError("Only homogeneous problems are supported" + " (and constant inhomogeneity)") if match_['type_of_equation'] == 'type6': sol = _linear_2eq_order1_type6(x, y, t, r, eq) if match_['type_of_equation'] == 'type7': sol = _linear_2eq_order1_type7(x, y, t, r, eq) return sol def _linear_2eq_order1_type6(x, y, t, r, eq): r""" The equations of this type of ode are . .. math:: x' = f(t) x + g(t) y .. math:: y' = a [f(t) + a h(t)] x + a [g(t) - h(t)] y This is solved by first multiplying the first equation by `-a` and adding it to the second equation to obtain .. math:: y' - a x' = -a h(t) (y - a x) Setting `U = y - ax` and integrating the equation we arrive at .. math:: y - ax = C_1 e^{-a \int h(t) \,dt} and on substituting the value of y in first equation give rise to first order ODEs. After solving for `x`, we can obtain `y` by substituting the value of `x` in second equation. """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) p = 0 q = 0 p1 = cancel(r['c']/cancel(r['c']/r['d']).as_numer_denom()[0]) p2 = cancel(r['a']/cancel(r['a']/r['b']).as_numer_denom()[0]) for n, i in enumerate([p1, p2]): for j in Mul.make_args(collect_const(i)): if not j.has(t): q = j if q!=0 and n==0: if ((r['c']/j - r['a'])/(r['b'] - r['d']/j)) == j: p = 1 s = j break if q!=0 and n==1: if ((r['a']/j - r['c'])/(r['d'] - r['b']/j)) == j: p = 2 s = j break if p == 1: equ = diff(x(t),t) - r['a']*x(t) - r['b']*(s*x(t) + C1*exp(-s*Integral(r['b'] - r['d']/s, t))) hint1 = classify_ode(equ)[1] sol1 = dsolve(equ, hint=hint1+'_Integral').rhs sol2 = s*sol1 + C1*exp(-s*Integral(r['b'] - r['d']/s, t)) elif p ==2: equ = diff(y(t),t) - r['c']*y(t) - r['d']*s*y(t) + C1*exp(-s*Integral(r['d'] - r['b']/s, t)) hint1 = classify_ode(equ)[1] sol2 = dsolve(equ, hint=hint1+'_Integral').rhs sol1 = s*sol2 + C1*exp(-s*Integral(r['d'] - r['b']/s, t)) return [Eq(x(t), sol1), Eq(y(t), sol2)] def _linear_2eq_order1_type7(x, y, t, r, eq): r""" The equations of this type of ode are . .. math:: x' = f(t) x + g(t) y .. math:: y' = h(t) x + p(t) y Differentiating the first equation and substituting the value of `y` from second equation will give a second-order linear equation .. math:: g x'' - (fg + gp + g') x' + (fgp - g^{2} h + f g' - f' g) x = 0 This above equation can be easily integrated if following conditions are satisfied. 1. `fgp - g^{2} h + f g' - f' g = 0` 2. `fgp - g^{2} h + f g' - f' g = ag, fg + gp + g' = bg` If first condition is satisfied then it is solved by current dsolve solver and in second case it becomes a constant coefficient differential equation which is also solved by current solver. Otherwise if the above condition fails then, a particular solution is assumed as `x = x_0(t)` and `y = y_0(t)` Then the general solution is expressed as .. math:: x = C_1 x_0(t) + C_2 x_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt .. math:: y = C_1 y_0(t) + C_2 [\frac{F(t) P(t)}{x_0(t)} + y_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt] where C1 and C2 are arbitrary constants and .. math:: F(t) = e^{\int f(t) \,dt} , P(t) = e^{\int p(t) \,dt} """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) e1 = r['a']*r['b']*r['c'] - r['b']**2*r['c'] + r['a']*diff(r['b'],t) - diff(r['a'],t)*r['b'] e2 = r['a']*r['c']*r['d'] - r['b']*r['c']**2 + diff(r['c'],t)*r['d'] - r['c']*diff(r['d'],t) m1 = r['a']*r['b'] + r['b']*r['d'] + diff(r['b'],t) m2 = r['a']*r['c'] + r['c']*r['d'] + diff(r['c'],t) if e1 == 0: sol1 = dsolve(r['b']*diff(x(t),t,t) - m1*diff(x(t),t)).rhs sol2 = dsolve(diff(y(t),t) - r['c']*sol1 - r['d']*y(t)).rhs elif e2 == 0: sol2 = dsolve(r['c']*diff(y(t),t,t) - m2*diff(y(t),t)).rhs sol1 = dsolve(diff(x(t),t) - r['a']*x(t) - r['b']*sol2).rhs elif not (e1/r['b']).has(t) and not (m1/r['b']).has(t): sol1 = dsolve(diff(x(t),t,t) - (m1/r['b'])*diff(x(t),t) - (e1/r['b'])*x(t)).rhs sol2 = dsolve(diff(y(t),t) - r['c']*sol1 - r['d']*y(t)).rhs elif not (e2/r['c']).has(t) and not (m2/r['c']).has(t): sol2 = dsolve(diff(y(t),t,t) - (m2/r['c'])*diff(y(t),t) - (e2/r['c'])*y(t)).rhs sol1 = dsolve(diff(x(t),t) - r['a']*x(t) - r['b']*sol2).rhs else: x0 = Function('x0')(t) # x0 and y0 being particular solutions y0 = Function('y0')(t) F = exp(Integral(r['a'],t)) P = exp(Integral(r['d'],t)) sol1 = C1*x0 + C2*x0*Integral(r['b']*F*P/x0**2, t) sol2 = C1*y0 + C2*(F*P/x0 + y0*Integral(r['b']*F*P/x0**2, t)) return [Eq(x(t), sol1), Eq(y(t), sol2)] def sysode_nonlinear_2eq_order1(match_): func = match_['func'] eq = match_['eq'] fc = match_['func_coeff'] t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] if match_['type_of_equation'] == 'type5': sol = _nonlinear_2eq_order1_type5(func, t, eq) return sol x = func[0].func y = func[1].func for i in range(2): eqs = 0 for terms in Add.make_args(eq[i]): eqs += terms/fc[i,func[i],1] eq[i] = eqs if match_['type_of_equation'] == 'type1': sol = _nonlinear_2eq_order1_type1(x, y, t, eq) elif match_['type_of_equation'] == 'type2': sol = _nonlinear_2eq_order1_type2(x, y, t, eq) elif match_['type_of_equation'] == 'type3': sol = _nonlinear_2eq_order1_type3(x, y, t, eq) elif match_['type_of_equation'] == 'type4': sol = _nonlinear_2eq_order1_type4(x, y, t, eq) return sol def _nonlinear_2eq_order1_type1(x, y, t, eq): r""" Equations: .. math:: x' = x^n F(x,y) .. math:: y' = g(y) F(x,y) Solution: .. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2 where if `n \neq 1` .. math:: \varphi = [C_1 + (1-n) \int \frac{1}{g(y)} \,dy]^{\frac{1}{1-n}} if `n = 1` .. math:: \varphi = C_1 e^{\int \frac{1}{g(y)} \,dy} where `C_1` and `C_2` are arbitrary constants. """ C1, C2 = get_numbered_constants(eq, num=2) n = Wild('n', exclude=[x(t),y(t)]) f = Wild('f') u, v = symbols('u, v') r = eq[0].match(diff(x(t),t) - x(t)**n*f) g = ((diff(y(t),t) - eq[1])/r[f]).subs(y(t),v) F = r[f].subs(x(t),u).subs(y(t),v) n = r[n] if n!=1: phi = (C1 + (1-n)*Integral(1/g, v))**(1/(1-n)) else: phi = C1*exp(Integral(1/g, v)) phi = phi.doit() sol2 = solve(Integral(1/(g*F.subs(u,phi)), v).doit() - t - C2, v) sol = [] for sols in sol2: sol.append(Eq(x(t),phi.subs(v, sols))) sol.append(Eq(y(t), sols)) return sol def _nonlinear_2eq_order1_type2(x, y, t, eq): r""" Equations: .. math:: x' = e^{\lambda x} F(x,y) .. math:: y' = g(y) F(x,y) Solution: .. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2 where if `\lambda \neq 0` .. math:: \varphi = -\frac{1}{\lambda} log(C_1 - \lambda \int \frac{1}{g(y)} \,dy) if `\lambda = 0` .. math:: \varphi = C_1 + \int \frac{1}{g(y)} \,dy where `C_1` and `C_2` are arbitrary constants. """ C1, C2 = get_numbered_constants(eq, num=2) n = Wild('n', exclude=[x(t),y(t)]) f = Wild('f') u, v = symbols('u, v') r = eq[0].match(diff(x(t),t) - exp(n*x(t))*f) g = ((diff(y(t),t) - eq[1])/r[f]).subs(y(t),v) F = r[f].subs(x(t),u).subs(y(t),v) n = r[n] if n: phi = -1/n*log(C1 - n*Integral(1/g, v)) else: phi = C1 + Integral(1/g, v) phi = phi.doit() sol2 = solve(Integral(1/(g*F.subs(u,phi)), v).doit() - t - C2, v) sol = [] for sols in sol2: sol.append(Eq(x(t),phi.subs(v, sols))) sol.append(Eq(y(t), sols)) return sol def _nonlinear_2eq_order1_type3(x, y, t, eq): r""" Autonomous system of general form .. math:: x' = F(x,y) .. math:: y' = G(x,y) Assuming `y = y(x, C_1)` where `C_1` is an arbitrary constant is the general solution of the first-order equation .. math:: F(x,y) y'_x = G(x,y) Then the general solution of the original system of equations has the form .. math:: \int \frac{1}{F(x,y(x,C_1))} \,dx = t + C_1 """ C1, C2, C3, C4 = get_numbered_constants(eq, num=4) v = Function('v') u = Symbol('u') f = Wild('f') g = Wild('g') r1 = eq[0].match(diff(x(t),t) - f) r2 = eq[1].match(diff(y(t),t) - g) F = r1[f].subs(x(t), u).subs(y(t), v(u)) G = r2[g].subs(x(t), u).subs(y(t), v(u)) sol2r = dsolve(Eq(diff(v(u), u), G/F)) if isinstance(sol2r, Expr): sol2r = [sol2r] for sol2s in sol2r: sol1 = solve(Integral(1/F.subs(v(u), sol2s.rhs), u).doit() - t - C2, u) sol = [] for sols in sol1: sol.append(Eq(x(t), sols)) sol.append(Eq(y(t), (sol2s.rhs).subs(u, sols))) return sol def _nonlinear_2eq_order1_type4(x, y, t, eq): r""" Equation: .. math:: x' = f_1(x) g_1(y) \phi(x,y,t) .. math:: y' = f_2(x) g_2(y) \phi(x,y,t) First integral: .. math:: \int \frac{f_2(x)}{f_1(x)} \,dx - \int \frac{g_1(y)}{g_2(y)} \,dy = C where `C` is an arbitrary constant. On solving the first integral for `x` (resp., `y` ) and on substituting the resulting expression into either equation of the original solution, one arrives at a first-order equation for determining `y` (resp., `x` ). """ C1, C2 = get_numbered_constants(eq, num=2) u, v = symbols('u, v') U, V = symbols('U, V', cls=Function) f = Wild('f') g = Wild('g') f1 = Wild('f1', exclude=[v,t]) f2 = Wild('f2', exclude=[v,t]) g1 = Wild('g1', exclude=[u,t]) g2 = Wild('g2', exclude=[u,t]) r1 = eq[0].match(diff(x(t),t) - f) r2 = eq[1].match(diff(y(t),t) - g) num, den = ( (r1[f].subs(x(t),u).subs(y(t),v))/ (r2[g].subs(x(t),u).subs(y(t),v))).as_numer_denom() R1 = num.match(f1*g1) R2 = den.match(f2*g2) phi = (r1[f].subs(x(t),u).subs(y(t),v))/num F1 = R1[f1]; F2 = R2[f2] G1 = R1[g1]; G2 = R2[g2] sol1r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, u) sol2r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, v) sol = [] for sols in sol1r: sol.append(Eq(y(t), dsolve(diff(V(t),t) - F2.subs(u,sols).subs(v,V(t))*G2.subs(v,V(t))*phi.subs(u,sols).subs(v,V(t))).rhs)) for sols in sol2r: sol.append(Eq(x(t), dsolve(diff(U(t),t) - F1.subs(u,U(t))*G1.subs(v,sols).subs(u,U(t))*phi.subs(v,sols).subs(u,U(t))).rhs)) return set(sol) def _nonlinear_2eq_order1_type5(func, t, eq): r""" Clairaut system of ODEs .. math:: x = t x' + F(x',y') .. math:: y = t y' + G(x',y') The following are solutions of the system `(i)` straight lines: .. math:: x = C_1 t + F(C_1, C_2), y = C_2 t + G(C_1, C_2) where `C_1` and `C_2` are arbitrary constants; `(ii)` envelopes of the above lines; `(iii)` continuously differentiable lines made up from segments of the lines `(i)` and `(ii)`. """ C1, C2 = get_numbered_constants(eq, num=2) f = Wild('f') g = Wild('g') def check_type(x, y): r1 = eq[0].match(t*diff(x(t),t) - x(t) + f) r2 = eq[1].match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t) r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t) if not (r1 and r2): r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f) r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g) if not (r1 and r2): r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t) r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t) return [r1, r2] for func_ in func: if isinstance(func_, list): x = func[0][0].func y = func[0][1].func [r1, r2] = check_type(x, y) if not (r1 and r2): [r1, r2] = check_type(y, x) x, y = y, x x1 = diff(x(t),t); y1 = diff(y(t),t) return {Eq(x(t), C1*t + r1[f].subs(x1,C1).subs(y1,C2)), Eq(y(t), C2*t + r2[g].subs(x1,C1).subs(y1,C2))} def sysode_nonlinear_3eq_order1(match_): x = match_['func'][0].func y = match_['func'][1].func z = match_['func'][2].func eq = match_['eq'] t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0] if match_['type_of_equation'] == 'type1': sol = _nonlinear_3eq_order1_type1(x, y, z, t, eq) if match_['type_of_equation'] == 'type2': sol = _nonlinear_3eq_order1_type2(x, y, z, t, eq) if match_['type_of_equation'] == 'type3': sol = _nonlinear_3eq_order1_type3(x, y, z, t, eq) if match_['type_of_equation'] == 'type4': sol = _nonlinear_3eq_order1_type4(x, y, z, t, eq) if match_['type_of_equation'] == 'type5': sol = _nonlinear_3eq_order1_type5(x, y, z, t, eq) return sol def _nonlinear_3eq_order1_type1(x, y, z, t, eq): r""" Equations: .. math:: a x' = (b - c) y z, \enspace b y' = (c - a) z x, \enspace c z' = (a - b) x y First Integrals: .. math:: a x^{2} + b y^{2} + c z^{2} = C_1 .. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2 where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and `z` and on substituting the resulting expressions into the first equation of the system, we arrives at a separable first-order equation on `x`. Similarly doing that for other two equations, we will arrive at first order equation on `y` and `z` too. References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0401.pdf """ C1, C2 = get_numbered_constants(eq, num=2) u, v, w = symbols('u, v, w') p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) r = (diff(x(t),t) - eq[0]).match(p*y(t)*z(t)) r.update((diff(y(t),t) - eq[1]).match(q*z(t)*x(t))) r.update((diff(z(t),t) - eq[2]).match(s*x(t)*y(t))) n1, d1 = r[p].as_numer_denom() n2, d2 = r[q].as_numer_denom() n3, d3 = r[s].as_numer_denom() val = solve([n1*u-d1*v+d1*w, d2*u+n2*v-d2*w, d3*u-d3*v-n3*w],[u,v]) vals = [val[v], val[u]] c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1]) b = vals[0].subs(w, c) a = vals[1].subs(w, c) y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b))) z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c))) z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c))) x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a))) x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a))) y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b))) sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x) sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y) sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z) return [sol1, sol2, sol3] def _nonlinear_3eq_order1_type2(x, y, z, t, eq): r""" Equations: .. math:: a x' = (b - c) y z f(x, y, z, t) .. math:: b y' = (c - a) z x f(x, y, z, t) .. math:: c z' = (a - b) x y f(x, y, z, t) First Integrals: .. math:: a x^{2} + b y^{2} + c z^{2} = C_1 .. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2 where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and `z` and on substituting the resulting expressions into the first equation of the system, we arrives at a first-order differential equations on `x`. Similarly doing that for other two equations we will arrive at first order equation on `y` and `z`. References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0402.pdf """ C1, C2 = get_numbered_constants(eq, num=2) u, v, w = symbols('u, v, w') p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) f = Wild('f') r1 = (diff(x(t),t) - eq[0]).match(y(t)*z(t)*f) r = collect_const(r1[f]).match(p*f) r.update(((diff(y(t),t) - eq[1])/r[f]).match(q*z(t)*x(t))) r.update(((diff(z(t),t) - eq[2])/r[f]).match(s*x(t)*y(t))) n1, d1 = r[p].as_numer_denom() n2, d2 = r[q].as_numer_denom() n3, d3 = r[s].as_numer_denom() val = solve([n1*u-d1*v+d1*w, d2*u+n2*v-d2*w, -d3*u+d3*v+n3*w],[u,v]) vals = [val[v], val[u]] c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1]) a = vals[0].subs(w, c) b = vals[1].subs(w, c) y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b))) z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c))) z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c))) x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a))) x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a))) y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b))) sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x*r[f]) sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y*r[f]) sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z*r[f]) return [sol1, sol2, sol3] def _nonlinear_3eq_order1_type3(x, y, z, t, eq): r""" Equations: .. math:: x' = c F_2 - b F_3, \enspace y' = a F_3 - c F_1, \enspace z' = b F_1 - a F_2 where `F_n = F_n(x, y, z, t)`. 1. First Integral: .. math:: a x + b y + c z = C_1, where C is an arbitrary constant. 2. If we assume function `F_n` to be independent of `t`,i.e, `F_n` = `F_n (x, y, z)` Then, on eliminating `t` and `z` from the first two equation of the system, one arrives at the first-order equation .. math:: \frac{dy}{dx} = \frac{a F_3 (x, y, z) - c F_1 (x, y, z)}{c F_2 (x, y, z) - b F_3 (x, y, z)} where `z = \frac{1}{c} (C_1 - a x - b y)` References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0404.pdf """ C1 = get_numbered_constants(eq, num=1) u, v, w = symbols('u, v, w') fu, fv, fw = symbols('u, v, w', cls=Function) p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) F1, F2, F3 = symbols('F1, F2, F3', cls=Wild) r1 = (diff(x(t), t) - eq[0]).match(F2-F3) r = collect_const(r1[F2]).match(s*F2) r.update(collect_const(r1[F3]).match(q*F3)) if eq[1].has(r[F2]) and not eq[1].has(r[F3]): r[F2], r[F3] = r[F3], r[F2] r[s], r[q] = -r[q], -r[s] r.update((diff(y(t), t) - eq[1]).match(p*r[F3] - r[s]*F1)) a = r[p]; b = r[q]; c = r[s] F1 = r[F1].subs(x(t), u).subs(y(t),v).subs(z(t), w) F2 = r[F2].subs(x(t), u).subs(y(t),v).subs(z(t), w) F3 = r[F3].subs(x(t), u).subs(y(t),v).subs(z(t), w) z_xy = (C1-a*u-b*v)/c y_zx = (C1-a*u-c*w)/b x_yz = (C1-b*v-c*w)/a y_x = dsolve(diff(fv(u),u) - ((a*F3-c*F1)/(c*F2-b*F3)).subs(w,z_xy).subs(v,fv(u))).rhs z_x = dsolve(diff(fw(u),u) - ((b*F1-a*F2)/(c*F2-b*F3)).subs(v,y_zx).subs(w,fw(u))).rhs z_y = dsolve(diff(fw(v),v) - ((b*F1-a*F2)/(a*F3-c*F1)).subs(u,x_yz).subs(w,fw(v))).rhs x_y = dsolve(diff(fu(v),v) - ((c*F2-b*F3)/(a*F3-c*F1)).subs(w,z_xy).subs(u,fu(v))).rhs y_z = dsolve(diff(fv(w),w) - ((a*F3-c*F1)/(b*F1-a*F2)).subs(u,x_yz).subs(v,fv(w))).rhs x_z = dsolve(diff(fu(w),w) - ((c*F2-b*F3)/(b*F1-a*F2)).subs(v,y_zx).subs(u,fu(w))).rhs sol1 = dsolve(diff(fu(t),t) - (c*F2 - b*F3).subs(v,y_x).subs(w,z_x).subs(u,fu(t))).rhs sol2 = dsolve(diff(fv(t),t) - (a*F3 - c*F1).subs(u,x_y).subs(w,z_y).subs(v,fv(t))).rhs sol3 = dsolve(diff(fw(t),t) - (b*F1 - a*F2).subs(u,x_z).subs(v,y_z).subs(w,fw(t))).rhs return [sol1, sol2, sol3] def _nonlinear_3eq_order1_type4(x, y, z, t, eq): r""" Equations: .. math:: x' = c z F_2 - b y F_3, \enspace y' = a x F_3 - c z F_1, \enspace z' = b y F_1 - a x F_2 where `F_n = F_n (x, y, z, t)` 1. First integral: .. math:: a x^{2} + b y^{2} + c z^{2} = C_1 where `C` is an arbitrary constant. 2. Assuming the function `F_n` is independent of `t`: `F_n = F_n (x, y, z)`. Then on eliminating `t` and `z` from the first two equations of the system, one arrives at the first-order equation .. math:: \frac{dy}{dx} = \frac{a x F_3 (x, y, z) - c z F_1 (x, y, z)} {c z F_2 (x, y, z) - b y F_3 (x, y, z)} where `z = \pm \sqrt{\frac{1}{c} (C_1 - a x^{2} - b y^{2})}` References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0405.pdf """ C1 = get_numbered_constants(eq, num=1) u, v, w = symbols('u, v, w') p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) F1, F2, F3 = symbols('F1, F2, F3', cls=Wild) r1 = eq[0].match(diff(x(t),t) - z(t)*F2 + y(t)*F3) r = collect_const(r1[F2]).match(s*F2) r.update(collect_const(r1[F3]).match(q*F3)) if eq[1].has(r[F2]) and not eq[1].has(r[F3]): r[F2], r[F3] = r[F3], r[F2] r[s], r[q] = -r[q], -r[s] r.update((diff(y(t),t) - eq[1]).match(p*x(t)*r[F3] - r[s]*z(t)*F1)) a = r[p]; b = r[q]; c = r[s] F1 = r[F1].subs(x(t),u).subs(y(t),v).subs(z(t),w) F2 = r[F2].subs(x(t),u).subs(y(t),v).subs(z(t),w) F3 = r[F3].subs(x(t),u).subs(y(t),v).subs(z(t),w) x_yz = sqrt((C1 - b*v**2 - c*w**2)/a) y_zx = sqrt((C1 - c*w**2 - a*u**2)/b) z_xy = sqrt((C1 - a*u**2 - b*v**2)/c) y_x = dsolve(diff(v(u),u) - ((a*u*F3-c*w*F1)/(c*w*F2-b*v*F3)).subs(w,z_xy).subs(v,v(u))).rhs z_x = dsolve(diff(w(u),u) - ((b*v*F1-a*u*F2)/(c*w*F2-b*v*F3)).subs(v,y_zx).subs(w,w(u))).rhs z_y = dsolve(diff(w(v),v) - ((b*v*F1-a*u*F2)/(a*u*F3-c*w*F1)).subs(u,x_yz).subs(w,w(v))).rhs x_y = dsolve(diff(u(v),v) - ((c*w*F2-b*v*F3)/(a*u*F3-c*w*F1)).subs(w,z_xy).subs(u,u(v))).rhs y_z = dsolve(diff(v(w),w) - ((a*u*F3-c*w*F1)/(b*v*F1-a*u*F2)).subs(u,x_yz).subs(v,v(w))).rhs x_z = dsolve(diff(u(w),w) - ((c*w*F2-b*v*F3)/(b*v*F1-a*u*F2)).subs(v,y_zx).subs(u,u(w))).rhs sol1 = dsolve(diff(u(t),t) - (c*w*F2 - b*v*F3).subs(v,y_x).subs(w,z_x).subs(u,u(t))).rhs sol2 = dsolve(diff(v(t),t) - (a*u*F3 - c*w*F1).subs(u,x_y).subs(w,z_y).subs(v,v(t))).rhs sol3 = dsolve(diff(w(t),t) - (b*v*F1 - a*u*F2).subs(u,x_z).subs(v,y_z).subs(w,w(t))).rhs return [sol1, sol2, sol3] def _nonlinear_3eq_order1_type5(x, y, z, t, eq): r""" .. math:: x' = x (c F_2 - b F_3), \enspace y' = y (a F_3 - c F_1), \enspace z' = z (b F_1 - a F_2) where `F_n = F_n (x, y, z, t)` and are arbitrary functions. First Integral: .. math:: \left|x\right|^{a} \left|y\right|^{b} \left|z\right|^{c} = C_1 where `C` is an arbitrary constant. If the function `F_n` is independent of `t`, then, by eliminating `t` and `z` from the first two equations of the system, one arrives at a first-order equation. References ========== -http://eqworld.ipmnet.ru/en/solutions/sysode/sode0406.pdf """ C1 = get_numbered_constants(eq, num=1) u, v, w = symbols('u, v, w') fu, fv, fw = symbols('u, v, w', cls=Function) p = Wild('p', exclude=[x(t), y(t), z(t), t]) q = Wild('q', exclude=[x(t), y(t), z(t), t]) s = Wild('s', exclude=[x(t), y(t), z(t), t]) F1, F2, F3 = symbols('F1, F2, F3', cls=Wild) r1 = eq[0].match(diff(x(t), t) - x(t)*F2 + x(t)*F3) r = collect_const(r1[F2]).match(s*F2) r.update(collect_const(r1[F3]).match(q*F3)) if eq[1].has(r[F2]) and not eq[1].has(r[F3]): r[F2], r[F3] = r[F3], r[F2] r[s], r[q] = -r[q], -r[s] r.update((diff(y(t), t) - eq[1]).match(y(t)*(p*r[F3] - r[s]*F1))) a = r[p]; b = r[q]; c = r[s] F1 = r[F1].subs(x(t), u).subs(y(t), v).subs(z(t), w) F2 = r[F2].subs(x(t), u).subs(y(t), v).subs(z(t), w) F3 = r[F3].subs(x(t), u).subs(y(t), v).subs(z(t), w) x_yz = (C1*v**-b*w**-c)**-a y_zx = (C1*w**-c*u**-a)**-b z_xy = (C1*u**-a*v**-b)**-c y_x = dsolve(diff(fv(u), u) - ((v*(a*F3 - c*F1))/(u*(c*F2 - b*F3))).subs(w, z_xy).subs(v, fv(u))).rhs z_x = dsolve(diff(fw(u), u) - ((w*(b*F1 - a*F2))/(u*(c*F2 - b*F3))).subs(v, y_zx).subs(w, fw(u))).rhs z_y = dsolve(diff(fw(v), v) - ((w*(b*F1 - a*F2))/(v*(a*F3 - c*F1))).subs(u, x_yz).subs(w, fw(v))).rhs x_y = dsolve(diff(fu(v), v) - ((u*(c*F2 - b*F3))/(v*(a*F3 - c*F1))).subs(w, z_xy).subs(u, fu(v))).rhs y_z = dsolve(diff(fv(w), w) - ((v*(a*F3 - c*F1))/(w*(b*F1 - a*F2))).subs(u, x_yz).subs(v, fv(w))).rhs x_z = dsolve(diff(fu(w), w) - ((u*(c*F2 - b*F3))/(w*(b*F1 - a*F2))).subs(v, y_zx).subs(u, fu(w))).rhs sol1 = dsolve(diff(fu(t), t) - (u*(c*F2 - b*F3)).subs(v, y_x).subs(w, z_x).subs(u, fu(t))).rhs sol2 = dsolve(diff(fv(t), t) - (v*(a*F3 - c*F1)).subs(u, x_y).subs(w, z_y).subs(v, fv(t))).rhs sol3 = dsolve(diff(fw(t), t) - (w*(b*F1 - a*F2)).subs(u, x_z).subs(v, y_z).subs(w, fw(t))).rhs return [sol1, sol2, sol3] #This import is written at the bottom to avoid circular imports. from .single import (NthAlgebraic, Factorable, FirstLinear, AlmostLinear, Bernoulli, SingleODEProblem, SingleODESolver, RiccatiSpecial)
a15c48d4a7e2ce64f4be29ad6cf4f9a254299008a731c2e4b6bcb948e1b3566f
# # This is the module for ODE solver classes for single ODEs. # import typing if typing.TYPE_CHECKING: from typing import ClassVar from typing import Dict, Type from typing import Iterator, List, Optional from sympy.core import S from sympy.core.exprtools import factor_terms from sympy.core.expr import Expr from sympy.core.function import AppliedUndef, Derivative, Function, expand from sympy.core.numbers import Float from sympy.core.relational import Equality, Eq from sympy.core.symbol import Symbol, Dummy, Wild from sympy.core.mul import Mul from sympy.functions import exp, sqrt, tan, log from sympy.integrals import Integral from sympy.polys.polytools import cancel, factor from sympy.simplify.simplify import simplify from sympy.simplify.radsimp import fraction from sympy.utilities import numbered_symbols from sympy.solvers.solvers import solve from sympy.solvers.deutils import ode_order, _preprocess class ODEMatchError(NotImplementedError): """Raised if a SingleODESolver is asked to solve an ODE it does not match""" pass def cached_property(func): '''Decorator to cache property method''' attrname = '_' + func.__name__ def propfunc(self): val = getattr(self, attrname, None) if val is None: val = func(self) setattr(self, attrname, val) return val return property(propfunc) class SingleODEProblem: """Represents an ordinary differential equation (ODE) This class is used internally in the by dsolve and related functions/classes so that properties of an ODE can be computed efficiently. Examples ======== This class is used internally by dsolve. To instantiate an instance directly first define an ODE problem: >>> from sympy import Function, Symbol >>> x = Symbol('x') >>> f = Function('f') >>> eq = f(x).diff(x, 2) Now you can create a SingleODEProblem instance and query its properties: >>> from sympy.solvers.ode.single import SingleODEProblem >>> problem = SingleODEProblem(f(x).diff(x), f(x), x) >>> problem.eq Derivative(f(x), x) >>> problem.func f(x) >>> problem.sym x """ # Instance attributes: eq = None # type: Expr func = None # type: AppliedUndef sym = None # type: Symbol _order = None # type: int _eq_expanded = None # type: Expr _eq_preprocessed = None # type: Expr def __init__(self, eq, func, sym, prep=True): assert isinstance(eq, Expr) assert isinstance(func, AppliedUndef) assert isinstance(sym, Symbol) assert isinstance(prep, bool) self.eq = eq self.func = func self.sym = sym self.prep = prep @cached_property def order(self) -> int: return ode_order(self.eq, self.func) @cached_property def eq_preprocessed(self) -> Expr: return self._get_eq_preprocessed() @cached_property def eq_expanded(self) -> Expr: return expand(self.eq_preprocessed) def _get_eq_preprocessed(self) -> Expr: if self.prep: process_eq, process_func = _preprocess(self.eq, self.func) if process_func != self.func: raise ValueError else: process_eq = self.eq return process_eq def get_numbered_constants(self, num=1, start=1, prefix='C') -> List[Symbol]: """ Returns a list of constants that do not occur in eq already. """ ncs = self.iter_numbered_constants(start, prefix) Cs = [next(ncs) for i in range(num)] return Cs def iter_numbered_constants(self, start=1, prefix='C') -> Iterator[Symbol]: """ Returns an iterator of constants that do not occur in eq already. """ atom_set = self.eq.free_symbols func_set = self.eq.atoms(Function) if func_set: atom_set |= {Symbol(str(f.func)) for f in func_set} return numbered_symbols(start=start, prefix=prefix, exclude=atom_set) # TODO: Add methods that can be used by many ODE solvers: # order # is_linear() # get_linear_coefficients() # eq_prepared (the ODE in prepared form) class SingleODESolver: """ Base class for Single ODE solvers. Subclasses should implement the _matches and _get_general_solution methods. This class is not intended to be instantiated directly but its subclasses are as part of dsolve. Examples ======== You can use a subclass of SingleODEProblem to solve a particular type of ODE. We first define a particular ODE problem: >>> from sympy import Function, Symbol >>> x = Symbol('x') >>> f = Function('f') >>> eq = f(x).diff(x, 2) Now we solve this problem using the NthAlgebraic solver which is a subclass of SingleODESolver: >>> from sympy.solvers.ode.single import NthAlgebraic, SingleODEProblem >>> problem = SingleODEProblem(eq, f(x), x) >>> solver = NthAlgebraic(problem) >>> solver.get_general_solution() [Eq(f(x), _C*x + _C)] The normal way to solve an ODE is to use dsolve (which would use NthAlgebraic and other solvers internally). When using dsolve a number of other things are done such as evaluating integrals, simplifying the solution and renumbering the constants: >>> from sympy import dsolve >>> dsolve(eq, hint='nth_algebraic') Eq(f(x), C1 + C2*x) """ # Subclasses should store the hint name (the argument to dsolve) in this # attribute hint = None # type: ClassVar[str] # Subclasses should define this to indicate if they support an _Integral # hint. has_integral = None # type: ClassVar[bool] # The ODE to be solved ode_problem = None # type: SingleODEProblem # Cache whether or not the equation has matched the method _matched = None # type: Optional[bool] # Subclasses should store in this attribute the list of order(s) of ODE # that subclass can solve or leave it to None if not specific to any order order = None # type: Optional[list] def __init__(self, ode_problem): self.ode_problem = ode_problem def matches(self) -> bool: if self.order is not None and self.ode_problem.order not in self.order: self._matched = False return self._matched if self._matched is None: self._matched = self._matches() return self._matched def get_general_solution(self, *, simplify: bool = True) -> List[Equality]: if not self.matches(): msg = "%s solver can not solve:\n%s" raise ODEMatchError(msg % (self.hint, self.ode_problem.eq)) return self._get_general_solution() def _matches(self) -> bool: msg = "Subclasses of SingleODESolver should implement matches." raise NotImplementedError(msg) def _get_general_solution(self, *, simplify: bool = True) -> List[Equality]: msg = "Subclasses of SingleODESolver should implement get_general_solution." raise NotImplementedError(msg) class SinglePatternODESolver(SingleODESolver): '''Superclass for ODE solvers based on pattern matching''' def wilds(self): prob = self.ode_problem f = prob.func.func x = prob.sym order = prob.order return self._wilds(f, x, order) def wilds_match(self): match = self._wilds_match return [match.get(w, S.Zero) for w in self.wilds()] def _matches(self): eq = self.ode_problem.eq_expanded f = self.ode_problem.func.func x = self.ode_problem.sym order = self.ode_problem.order df = f(x).diff(x) if order != 1: return False pattern = self._equation(f(x), x, 1) if not pattern.coeff(df).has(Wild): eq = expand(eq / eq.coeff(df)) eq = eq.collect(f(x), func = cancel) self._wilds_match = match = eq.match(pattern) if match is not None: return self._verify(f(x)) return False def _verify(self, fx) -> bool: return True def _wilds(self, f, x, order): msg = "Subclasses of SingleODESolver should implement _wilds" raise NotImplementedError(msg) def _equation(self, fx, x, order): msg = "Subclasses of SingleODESolver should implement _equation" raise NotImplementedError(msg) class NthAlgebraic(SingleODESolver): r""" Solves an `n`\th order ordinary differential equation using algebra and integrals. There is no general form for the kind of equation that this can solve. The the equation is solved algebraically treating differentiation as an invertible algebraic function. Examples ======== >>> from sympy import Function, dsolve, Eq >>> from sympy.abc import x >>> f = Function('f') >>> eq = Eq(f(x) * (f(x).diff(x)**2 - 1), 0) >>> dsolve(eq, f(x), hint='nth_algebraic') [Eq(f(x), 0), Eq(f(x), C1 - x), Eq(f(x), C1 + x)] Note that this solver can return algebraic solutions that do not have any integration constants (f(x) = 0 in the above example). """ hint = 'nth_algebraic' has_integral = True # nth_algebraic_Integral hint def _matches(self): r""" Matches any differential equation that nth_algebraic can solve. Uses `sympy.solve` but teaches it how to integrate derivatives. This involves calling `sympy.solve` and does most of the work of finding a solution (apart from evaluating the integrals). """ eq = self.ode_problem.eq func = self.ode_problem.func var = self.ode_problem.sym # Derivative that solve can handle: diffx = self._get_diffx(var) # Replace derivatives wrt the independent variable with diffx def replace(eq, var): def expand_diffx(*args): differand, diffs = args[0], args[1:] toreplace = differand for v, n in diffs: for _ in range(n): if v == var: toreplace = diffx(toreplace) else: toreplace = Derivative(toreplace, v) return toreplace return eq.replace(Derivative, expand_diffx) # Restore derivatives in solution afterwards def unreplace(eq, var): return eq.replace(diffx, lambda e: Derivative(e, var)) subs_eqn = replace(eq, var) try: # turn off simplification to protect Integrals that have # _t instead of fx in them and would otherwise factor # as t_*Integral(1, x) solns = solve(subs_eqn, func, simplify=False) except NotImplementedError: solns = [] solns = [simplify(unreplace(soln, var)) for soln in solns] solns = [Equality(func, soln) for soln in solns] self.solutions = solns return len(solns) != 0 def _get_general_solution(self, *, simplify: bool = True): return self.solutions # This needs to produce an invertible function but the inverse depends # which variable we are integrating with respect to. Since the class can # be stored in cached results we need to ensure that we always get the # same class back for each particular integration variable so we store these # classes in a global dict: _diffx_stored = {} # type: Dict[Symbol, Type[Function]] @staticmethod def _get_diffx(var): diffcls = NthAlgebraic._diffx_stored.get(var, None) if diffcls is None: # A class that behaves like Derivative wrt var but is "invertible". class diffx(Function): def inverse(self): # don't use integrate here because fx has been replaced by _t # in the equation; integrals will not be correct while solve # is at work. return lambda expr: Integral(expr, var) + Dummy('C') diffcls = NthAlgebraic._diffx_stored.setdefault(var, diffx) return diffcls class FirstLinear(SinglePatternODESolver): r""" Solves 1st order linear differential equations. These are differential equations of the form .. math:: dy/dx + P(x) y = Q(x)\text{.} These kinds of differential equations can be solved in a general way. The integrating factor `e^{\int P(x) \,dx}` will turn the equation into a separable equation. The general solution is:: >>> from sympy import Function, dsolve, Eq, pprint, diff, sin >>> from sympy.abc import x >>> f, P, Q = map(Function, ['f', 'P', 'Q']) >>> genform = Eq(f(x).diff(x) + P(x)*f(x), Q(x)) >>> pprint(genform) d P(x)*f(x) + --(f(x)) = Q(x) dx >>> pprint(dsolve(genform, f(x), hint='1st_linear_Integral')) / / \ | | | | | / | / | | | | | | | | P(x) dx | - | P(x) dx | | | | | | | / | / f(x) = |C1 + | Q(x)*e dx|*e | | | \ / / Examples ======== >>> f = Function('f') >>> pprint(dsolve(Eq(x*diff(f(x), x) - f(x), x**2*sin(x)), ... f(x), '1st_linear')) f(x) = x*(C1 - cos(x)) References ========== - https://en.wikipedia.org/wiki/Linear_differential_equation#First_order_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 92 # indirect doctest """ hint = '1st_linear' has_integral = True order = [1] def _wilds(self, f, x, order): P = Wild('P', exclude=[f(x)]) Q = Wild('Q', exclude=[f(x), f(x).diff(x)]) return P, Q def _equation(self, fx, x, order): P, Q = self.wilds() return fx.diff(x) + P*fx - Q def _get_general_solution(self, *, simplify: bool = True): P, Q = self.wilds_match() fx = self.ode_problem.func x = self.ode_problem.sym (C1,) = self.ode_problem.get_numbered_constants(num=1) gensol = Eq(fx, (((C1 + Integral(Q*exp(Integral(P, x)),x)) * exp(-Integral(P, x))))) return [gensol] class AlmostLinear(SinglePatternODESolver): r""" Solves an almost-linear differential equation. The general form of an almost linear differential equation is .. math:: a(x) g'(f(x)) f'(x) + b(x) g(f(x)) + c(x) Here `f(x)` is the function to be solved for (the dependent variable). The substitution `g(f(x)) = u(x)` leads to a linear differential equation for `u(x)` of the form `a(x) u' + b(x) u + c(x) = 0`. This can be solved for `u(x)` by the `first_linear` hint and then `f(x)` is found by solving `g(f(x)) = u(x)`. See Also ======== :meth:`sympy.solvers.ode.single.FirstLinear` Examples ======== >>> from sympy import Function, pprint, sin, cos >>> from sympy.solvers.ode import dsolve >>> from sympy.abc import x >>> f = Function('f') >>> d = f(x).diff(x) >>> eq = x*d + x*f(x) + 1 >>> dsolve(eq, f(x), hint='almost_linear') Eq(f(x), (C1 - Ei(x))*exp(-x)) >>> pprint(dsolve(eq, f(x), hint='almost_linear')) -x f(x) = (C1 - Ei(x))*e >>> example = cos(f(x))*f(x).diff(x) + sin(f(x)) + 1 >>> pprint(example) d sin(f(x)) + cos(f(x))*--(f(x)) + 1 dx >>> pprint(dsolve(example, f(x), hint='almost_linear')) / -x \ / -x \ [f(x) = pi - asin\C1*e - 1/, f(x) = asin\C1*e - 1/] References ========== - Joel Moses, "Symbolic Integration - The Stormy Decade", Communications of the ACM, Volume 14, Number 8, August 1971, pp. 558 """ hint = "almost_linear" has_integral = True order = [1] def _wilds(self, f, x, order): P = Wild('P', exclude=[f(x).diff(x)]) Q = Wild('Q', exclude=[f(x).diff(x)]) return P, Q def _equation(self, fx, x, order): P, Q = self.wilds() return P*fx.diff(x) + Q def _verify(self, fx): a, b = self.wilds_match() c, b = b.as_independent(fx) if b.is_Add else (S.Zero, b) # a, b and c are the function a(x), b(x) and c(x) respectively. # c(x) is obtained by separating out b as terms with and without fx i.e, l(y) # The following conditions checks if the given equation is an almost-linear differential equation using the fact that # a(x)*(l(y))' / l(y)' is independent of l(y) if b.diff(fx) != 0 and not simplify(b.diff(fx)/a).has(fx): self.ly = factor_terms(b).as_independent(fx, as_Add=False)[1] # Gives the term containing fx i.e., l(y) self.ax = a / self.ly.diff(fx) self.cx = -c # cx is taken as -c(x) to simplify expression in the solution integral self.bx = factor_terms(b) / self.ly return True return False def _get_general_solution(self, *, simplify: bool = True): x = self.ode_problem.sym (C1,) = self.ode_problem.get_numbered_constants(num=1) gensol = Eq(self.ly, (((C1 + Integral((self.cx/self.ax)*exp(Integral(self.bx/self.ax, x)),x)) * exp(-Integral(self.bx/self.ax, x))))) return [gensol] class Bernoulli(SinglePatternODESolver): r""" Solves Bernoulli differential equations. These are equations of the form .. math:: dy/dx + P(x) y = Q(x) y^n\text{, }n \ne 1`\text{.} The substitution `w = 1/y^{1-n}` will transform an equation of this form into one that is linear (see the docstring of :py:meth:`~sympy.solvers.ode.single.FirstLinear`). The general solution is:: >>> from sympy import Function, dsolve, Eq, pprint >>> from sympy.abc import x, n >>> f, P, Q = map(Function, ['f', 'P', 'Q']) >>> genform = Eq(f(x).diff(x) + P(x)*f(x), Q(x)*f(x)**n) >>> pprint(genform) d n P(x)*f(x) + --(f(x)) = Q(x)*f (x) dx >>> pprint(dsolve(genform, f(x), hint='Bernoulli_Integral'), num_columns=110) -1 ----- n - 1 // / / \ \ || | | | | || | / | / | / | || | | | | | | | || | (1 - n)* | P(x) dx | (1 - n)* | P(x) dx | (n - 1)* | P(x) dx| || | | | | | | | || | / | / | / | f(x) = ||C1 - n* | Q(x)*e dx + | Q(x)*e dx|*e | || | | | | \\ / / / / Note that the equation is separable when `n = 1` (see the docstring of :py:meth:`~sympy.solvers.ode.ode.ode_separable`). >>> pprint(dsolve(Eq(f(x).diff(x) + P(x)*f(x), Q(x)*f(x)), f(x), ... hint='separable_Integral')) f(x) / | / | 1 | | - dy = C1 + | (-P(x) + Q(x)) dx | y | | / / Examples ======== >>> from sympy import Function, dsolve, Eq, pprint, log >>> from sympy.abc import x >>> f = Function('f') >>> pprint(dsolve(Eq(x*f(x).diff(x) + f(x), log(x)*f(x)**2), ... f(x), hint='Bernoulli')) 1 f(x) = ----------------- C1*x + log(x) + 1 References ========== - https://en.wikipedia.org/wiki/Bernoulli_differential_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 95 # indirect doctest """ hint = "Bernoulli" has_integral = True order = [1] def _wilds(self, f, x, order): P = Wild('P', exclude=[f(x)]) Q = Wild('Q', exclude=[f(x)]) n = Wild('n', exclude=[x, f(x), f(x).diff(x)]) return P, Q, n def _equation(self, fx, x, order): P, Q, n = self.wilds() return fx.diff(x) + P*fx - Q*fx**n def _get_general_solution(self, *, simplify: bool = True): P, Q, n = self.wilds_match() fx = self.ode_problem.func x = self.ode_problem.sym (C1,) = self.ode_problem.get_numbered_constants(num=1) if n==1: gensol = Eq(log(fx), ( (C1 + Integral((-P + Q),x) ))) else: gensol = Eq(fx**(1-n), ( (C1 - (n - 1) * Integral(Q*exp(-n*Integral(P, x)) * exp(Integral(P, x)), x) ) * exp(-(1 - n)*Integral(P, x))) ) return [gensol] class Factorable(SingleODESolver): r""" Solves equations having a solvable factor. This function is used to solve the equation having factors. Factors may be of type algebraic or ode. It will try to solve each factor independently. Factors will be solved by calling dsolve. We will return the list of solutions. Examples ======== >>> from sympy import Function, dsolve, pprint >>> from sympy.abc import x >>> f = Function('f') >>> eq = (f(x)**2-4)*(f(x).diff(x)+f(x)) >>> pprint(dsolve(eq, f(x))) -x [f(x) = 2, f(x) = -2, f(x) = C1*e ] """ hint = "factorable" has_integral = False def _matches(self): eq = self.ode_problem.eq f = self.ode_problem.func.func x = self.ode_problem.sym order =self.ode_problem.order df = f(x).diff(x) self.eqs = [] eq = eq.collect(f(x), func = cancel) eq = fraction(factor(eq))[0] factors = Mul.make_args(factor(eq)) roots = [fac.as_base_exp() for fac in factors if len(fac.args)!=0] if len(roots)>1 or roots[0][1]>1: for base,expo in roots: if base.has(f(x)): self.eqs.append(base) if len(self.eqs)>0: return True roots = solve(eq, df) if len(roots)>0: self.eqs = [(df - root) for root in roots] if len(self.eqs)==1: if order>1: return False if self.eqs[0].has(Float): return False return fraction(factor(self.eqs[0]))[0]-eq!=0 return True return False def _get_general_solution(self, *, simplify: bool = True): func = self.ode_problem.func.func x = self.ode_problem.sym eqns = self.eqs sols = [] for eq in eqns: try: sol = dsolve(eq, func(x)) except NotImplementedError: continue else: if isinstance(sol, list): sols.extend(sol) else: sols.append(sol) if sols == []: raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by" + " the factorable group method") return sols class RiccatiSpecial(SinglePatternODESolver): r""" The general Riccati equation has the form .. math:: dy/dx = f(x) y^2 + g(x) y + h(x)\text{.} While it does not have a general solution [1], the "special" form, `dy/dx = a y^2 - b x^c`, does have solutions in many cases [2]. This routine returns a solution for `a(dy/dx) = b y^2 + c y/x + d/x^2` that is obtained by using a suitable change of variables to reduce it to the special form and is valid when neither `a` nor `b` are zero and either `c` or `d` is zero. >>> from sympy.abc import x, a, b, c, d >>> from sympy.solvers.ode import dsolve, checkodesol >>> from sympy import pprint, Function >>> f = Function('f') >>> y = f(x) >>> genform = a*y.diff(x) - (b*y**2 + c*y/x + d/x**2) >>> sol = dsolve(genform, y) >>> pprint(sol, wrap_line=False) / / __________________ \\ | __________________ | / 2 || | / 2 | \/ 4*b*d - (a + c) *log(x)|| -|a + c - \/ 4*b*d - (a + c) *tan|C1 + ----------------------------|| \ \ 2*a // f(x) = ------------------------------------------------------------------------ 2*b*x >>> checkodesol(genform, sol, order=1)[0] True References ========== 1. http://www.maplesoft.com/support/help/Maple/view.aspx?path=odeadvisor/Riccati 2. http://eqworld.ipmnet.ru/en/solutions/ode/ode0106.pdf - http://eqworld.ipmnet.ru/en/solutions/ode/ode0123.pdf """ hint = "Riccati_special_minus2" has_integral = False order = [1] def _wilds(self, f, x, order): a = Wild('a', exclude=[x, f(x), f(x).diff(x), 0]) b = Wild('b', exclude=[x, f(x), f(x).diff(x), 0]) c = Wild('c', exclude=[x, f(x), f(x).diff(x)]) d = Wild('d', exclude=[x, f(x), f(x).diff(x)]) return a, b, c, d def _equation(self, fx, x, order): a, b, c, d = self.wilds() return a*fx.diff(x) + b*fx**2 + c*fx/x + d/x**2 def _get_general_solution(self, *, simplify: bool = True): a, b, c, d = self.wilds_match() fx = self.ode_problem.func x = self.ode_problem.sym (C1,) = self.ode_problem.get_numbered_constants(num=1) mu = sqrt(4*d*b - (a - c)**2) gensol = Eq(fx, (a - c - mu*tan(mu/(2*a)*log(x) + C1))/(2*b*x)) return [gensol] # Avoid circular import: from .ode import dsolve
e8a4293b8da7755fa1bed55ba13a9b094de5d8473c6f8879920fd3307d6546bd
from sympy import (acos, acosh, asinh, atan, cos, Derivative, diff, Dummy, Eq, Ne, exp, Function, I, Integral, LambertW, log, O, pi, Rational, rootof, S, sin, sqrt, Subs, Symbol, tan, asin, sinh, Piecewise, symbols, Poly, sec, re, im, atan2, collect, hyper, integrate) from sympy.solvers.ode import (classify_ode, homogeneous_order, infinitesimals, checkinfsol, dsolve) from sympy.solvers.ode.subscheck import checkodesol, checksysodesol from sympy.solvers.ode.ode import (_linear_coeff_match, _undetermined_coefficients_match, classify_sysode, constant_renumber, constantsimp, get_numbered_constants, solve_ics) from sympy.functions import airyai, airybi, besselj, bessely from sympy.solvers.deutils import ode_order from sympy.testing.pytest import XFAIL, skip, raises, slow, ON_TRAVIS, SKIP C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10 = symbols('C0:11') u, x, y, z = symbols('u,x:z', real=True) f = Function('f') g = Function('g') h = Function('h') # Note: the tests below may fail (but still be correct) if ODE solver, # the integral engine, solve(), or even simplify() changes. Also, in # differently formatted solutions, the arbitrary constants might not be # equal. Using specific hints in tests can help to avoid this. # Tests of order higher than 1 should run the solutions through # constant_renumber because it will normalize it (constant_renumber causes # dsolve() to return different results on different machines) def test_get_numbered_constants(): with raises(ValueError): get_numbered_constants(None) def test_dsolve_all_hint(): eq = f(x).diff(x) output = dsolve(eq, hint='all') # Match the Dummy variables: sol1 = output['separable_Integral'] _y = sol1.lhs.args[1][0] sol1 = output['1st_homogeneous_coeff_subs_dep_div_indep_Integral'] _u1 = sol1.rhs.args[1].args[1][0] expected = {'Bernoulli_Integral': Eq(f(x), C1 + Integral(0, x)), '1st_homogeneous_coeff_best': Eq(f(x), C1), 'Bernoulli': Eq(f(x), C1), 'nth_algebraic': Eq(f(x), C1), 'nth_linear_euler_eq_homogeneous': Eq(f(x), C1), 'nth_linear_constant_coeff_homogeneous': Eq(f(x), C1), 'separable': Eq(f(x), C1), '1st_homogeneous_coeff_subs_indep_div_dep': Eq(f(x), C1), 'nth_algebraic_Integral': Eq(f(x), C1), '1st_linear': Eq(f(x), C1), '1st_linear_Integral': Eq(f(x), C1 + Integral(0, x)), 'lie_group': Eq(f(x), C1), '1st_homogeneous_coeff_subs_dep_div_indep': Eq(f(x), C1), '1st_homogeneous_coeff_subs_dep_div_indep_Integral': Eq(log(x), C1 + Integral(-1/_u1, (_u1, f(x)/x))), '1st_power_series': Eq(f(x), C1), 'separable_Integral': Eq(Integral(1, (_y, f(x))), C1 + Integral(0, x)), '1st_homogeneous_coeff_subs_indep_div_dep_Integral': Eq(f(x), C1), 'best': Eq(f(x), C1), 'best_hint': 'nth_algebraic', 'default': 'nth_algebraic', 'order': 1} assert output == expected assert dsolve(eq, hint='best') == Eq(f(x), C1) def test_dsolve_ics(): # Maybe this should just use one of the solutions instead of raising... with raises(NotImplementedError): dsolve(f(x).diff(x) - sqrt(f(x)), ics={f(1):1}) @slow @XFAIL def test_nonlinear_3eq_order1_type1(): if ON_TRAVIS: skip("Too slow for travis.") a, b, c = symbols('a b c') eqs = [ a * f(x).diff(x) - (b - c) * g(x) * h(x), b * g(x).diff(x) - (c - a) * h(x) * f(x), c * h(x).diff(x) - (a - b) * f(x) * g(x), ] assert dsolve(eqs) # NotImplementedError def test_dsolve_euler_rootof(): eq = x**6 * f(x).diff(x, 6) - x*f(x).diff(x) + f(x) sol = Eq(f(x), C1*x + C2*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 0) + C3*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 1) + C4*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 2) + C5*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 3) + C6*x**rootof(x**5 - 14*x**4 + 71*x**3 - 154*x**2 + 120*x - 1, 4) ) assert dsolve(eq) == sol def test_nth_euler_imroot(): eq = x**2 * f(x).diff(x, 2) + x * f(x).diff(x) + 4 * f(x) - 1/x sol = Eq(f(x), C1*sin(2*log(x)) + C2*cos(2*log(x)) + 1/(5*x)) dsolve_sol = dsolve(eq, hint='nth_linear_euler_eq_nonhomogeneous_variation_of_parameters') assert dsolve_sol == sol assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] def test_constant_coeff_circular_atan2(): eq = f(x).diff(x, x) + y*f(x) sol = Eq(f(x), C1*exp(-x*sqrt(-y)) + C2*exp(x*sqrt(-y))) assert dsolve(eq) == sol assert checkodesol(eq, sol, order=2, solve_for_func=False)[0] @XFAIL def test_nonlinear_3eq_order1_type4(): eqs = [ Eq(f(x).diff(x), (2*h(x)*g(x) - 3*g(x)*h(x))), Eq(g(x).diff(x), (4*f(x)*h(x) - 2*h(x)*f(x))), Eq(h(x).diff(x), (3*g(x)*f(x) - 4*f(x)*g(x))), ] dsolve(eqs) # KeyError when matching # sol = ? # assert dsolve_sol == sol # assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0]) @slow @XFAIL def test_nonlinear_3eq_order1_type3(): if ON_TRAVIS: skip("Too slow for travis.") eqs = [ Eq(f(x).diff(x), (2*f(x)**2 - 3 )), Eq(g(x).diff(x), (4 - 2*h(x) )), Eq(h(x).diff(x), (3*h(x) - 4*f(x)**2)), ] dsolve(eqs) # Not sure if this finishes... # sol = ? # assert dsolve_sol == sol # assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0]) @XFAIL def test_nonlinear_3eq_order1_type5(): eqs = [ Eq(f(x).diff(x), f(x)*(2*f(x) - 3*g(x))), Eq(g(x).diff(x), g(x)*(4*g(x) - 2*h(x))), Eq(h(x).diff(x), h(x)*(3*h(x) - 4*f(x))), ] dsolve(eqs) # KeyError # sol = ? # assert dsolve_sol == sol # assert checksysodesol(eqs, dsolve_sol) == (True, [0, 0, 0]) def test_linear_2eq_order1(): x, y, z = symbols('x, y, z', cls=Function) k, l, m, n = symbols('k, l, m, n', Integer=True) t = Symbol('t') x0, y0 = symbols('x0, y0', cls=Function) eq1 = (Eq(diff(x(t),t), x(t) + y(t) + 9), Eq(diff(y(t),t), 2*x(t) + 5*y(t) + 23)) sol1 = [Eq(x(t), C1*exp(t*(sqrt(6) + 3)) + C2*exp(t*(-sqrt(6) + 3)) - Rational(22, 3)), \ Eq(y(t), C1*(2 + sqrt(6))*exp(t*(sqrt(6) + 3)) + C2*(-sqrt(6) + 2)*exp(t*(-sqrt(6) + 3)) - Rational(5, 3))] assert checksysodesol(eq1, sol1) == (True, [0, 0]) eq2 = (Eq(diff(x(t),t), x(t) + y(t) + 81), Eq(diff(y(t),t), -2*x(t) + y(t) + 23)) sol2 = [Eq(x(t), (C1*cos(sqrt(2)*t) + C2*sin(sqrt(2)*t))*exp(t) - Rational(58, 3)), \ Eq(y(t), (-sqrt(2)*C1*sin(sqrt(2)*t) + sqrt(2)*C2*cos(sqrt(2)*t))*exp(t) - Rational(185, 3))] assert checksysodesol(eq2, sol2) == (True, [0, 0]) eq3 = (Eq(diff(x(t),t), 5*t*x(t) + 2*y(t)), Eq(diff(y(t),t), 2*x(t) + 5*t*y(t))) sol3 = [Eq(x(t), (C1*exp(2*t) + C2*exp(-2*t))*exp(Rational(5, 2)*t**2)), \ Eq(y(t), (C1*exp(2*t) - C2*exp(-2*t))*exp(Rational(5, 2)*t**2))] assert checksysodesol(eq3, sol3) == (True, [0, 0]) eq4 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t))) sol4 = [Eq(x(t), (C1*cos((t**3)/3) + C2*sin((t**3)/3))*exp(Rational(5, 2)*t**2)), \ Eq(y(t), (-C1*sin((t**3)/3) + C2*cos((t**3)/3))*exp(Rational(5, 2)*t**2))] assert checksysodesol(eq4, sol4) == (True, [0, 0]) eq5 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + (5*t+9*t**2)*y(t))) sol5 = [Eq(x(t), (C1*exp((sqrt(77)/2 + Rational(9, 2))*(t**3)/3) + \ C2*exp((-sqrt(77)/2 + Rational(9, 2))*(t**3)/3))*exp(Rational(5, 2)*t**2)), \ Eq(y(t), (C1*(sqrt(77)/2 + Rational(9, 2))*exp((sqrt(77)/2 + Rational(9, 2))*(t**3)/3) + \ C2*(-sqrt(77)/2 + Rational(9, 2))*exp((-sqrt(77)/2 + Rational(9, 2))*(t**3)/3))*exp(Rational(5, 2)*t**2))] assert checksysodesol(eq5, sol5) == (True, [0, 0]) eq6 = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), (1-t**2)*x(t) + (5*t+9*t**2)*y(t))) sol6 = [Eq(x(t), C1*x0(t) + C2*x0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t)), \ Eq(y(t), C1*y0(t) + C2*(y0(t)*Integral(t**2*exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)**2, t) + \ exp(Integral(5*t, t))*exp(Integral(9*t**2 + 5*t, t))/x0(t)))] s = dsolve(eq6) assert s == sol6 # too complicated to test with subs and simplify # assert checksysodesol(eq10, sol10) == (True, [0, 0]) # this one fails def test_nonlinear_2eq_order1(): x, y, z = symbols('x, y, z', cls=Function) t = Symbol('t') eq1 = (Eq(diff(x(t),t),x(t)*y(t)**3), Eq(diff(y(t),t),y(t)**5)) sol1 = [ Eq(x(t), C1*exp((-1/(4*C2 + 4*t))**(Rational(-1, 4)))), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), C1*exp(-1/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), C1*exp(-I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), C1*exp(I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))] assert dsolve(eq1) == sol1 assert checksysodesol(eq1, sol1) == (True, [0, 0]) eq2 = (Eq(diff(x(t),t), exp(3*x(t))*y(t)**3),Eq(diff(y(t),t), y(t)**5)) sol2 = [ Eq(x(t), -log(C1 - 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), -log(C1 + 3/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), -log(C1 + 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), -log(C1 - 3*I/(-1/(4*C2 + 4*t))**Rational(1, 4))/3), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))] assert dsolve(eq2) == sol2 assert checksysodesol(eq2, sol2) == (True, [0, 0]) eq3 = (Eq(diff(x(t),t), y(t)*x(t)), Eq(diff(y(t),t), x(t)**3)) tt = Rational(2, 3) sol3 = [ Eq(x(t), 6**tt/(6*(-sinh(sqrt(C1)*(C2 + t)/2)/sqrt(C1))**tt)), Eq(y(t), sqrt(C1 + C1/sinh(sqrt(C1)*(C2 + t)/2)**2)/3)] assert dsolve(eq3) == sol3 # FIXME: assert checksysodesol(eq3, sol3) == (True, [0, 0]) eq4 = (Eq(diff(x(t),t),x(t)*y(t)*sin(t)**2), Eq(diff(y(t),t),y(t)**2*sin(t)**2)) sol4 = set([Eq(x(t), -2*exp(C1)/(C2*exp(C1) + t - sin(2*t)/2)), Eq(y(t), -2/(C1 + t - sin(2*t)/2))]) assert dsolve(eq4) == sol4 # FIXME: assert checksysodesol(eq4, sol4) == (True, [0, 0]) eq5 = (Eq(x(t),t*diff(x(t),t)+diff(x(t),t)*diff(y(t),t)), Eq(y(t),t*diff(y(t),t)+diff(y(t),t)**2)) sol5 = set([Eq(x(t), C1*C2 + C1*t), Eq(y(t), C2**2 + C2*t)]) assert dsolve(eq5) == sol5 assert checksysodesol(eq5, sol5) == (True, [0, 0]) eq6 = (Eq(diff(x(t),t),x(t)**2*y(t)**3), Eq(diff(y(t),t),y(t)**5)) sol6 = [ Eq(x(t), 1/(C1 - 1/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), -(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), 1/(C1 + (-1/(4*C2 + 4*t))**(Rational(-1, 4)))), Eq(y(t), (-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), 1/(C1 + I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), -I*(-1/(4*C2 + 4*t))**Rational(1, 4)), Eq(x(t), 1/(C1 - I/(-1/(4*C2 + 4*t))**Rational(1, 4))), Eq(y(t), I*(-1/(4*C2 + 4*t))**Rational(1, 4))] assert dsolve(eq6) == sol6 assert checksysodesol(eq6, sol6) == (True, [0, 0]) @slow def test_nonlinear_3eq_order1(): x, y, z = symbols('x, y, z', cls=Function) t, u = symbols('t u') eq1 = (4*diff(x(t),t) + 2*y(t)*z(t), 3*diff(y(t),t) - z(t)*x(t), 5*diff(z(t),t) - x(t)*y(t)) sol1 = [Eq(4*Integral(1/(sqrt(-4*u**2 - 3*C1 + C2)*sqrt(-4*u**2 + 5*C1 - C2)), (u, x(t))), C3 - sqrt(15)*t/15), Eq(3*Integral(1/(sqrt(-6*u**2 - C1 + 5*C2)*sqrt(3*u**2 + C1 - 4*C2)), (u, y(t))), C3 + sqrt(5)*t/10), Eq(5*Integral(1/(sqrt(-10*u**2 - 3*C1 + C2)* sqrt(5*u**2 + 4*C1 - C2)), (u, z(t))), C3 + sqrt(3)*t/6)] assert [i.dummy_eq(j) for i, j in zip(dsolve(eq1), sol1)] # FIXME: assert checksysodesol(eq1, sol1) == (True, [0, 0, 0]) eq2 = (4*diff(x(t),t) + 2*y(t)*z(t)*sin(t), 3*diff(y(t),t) - z(t)*x(t)*sin(t), 5*diff(z(t),t) - x(t)*y(t)*sin(t)) sol2 = [Eq(3*Integral(1/(sqrt(-6*u**2 - C1 + 5*C2)*sqrt(3*u**2 + C1 - 4*C2)), (u, x(t))), C3 + sqrt(5)*cos(t)/10), Eq(4*Integral(1/(sqrt(-4*u**2 - 3*C1 + C2)*sqrt(-4*u**2 + 5*C1 - C2)), (u, y(t))), C3 - sqrt(15)*cos(t)/15), Eq(5*Integral(1/(sqrt(-10*u**2 - 3*C1 + C2)* sqrt(5*u**2 + 4*C1 - C2)), (u, z(t))), C3 + sqrt(3)*cos(t)/6)] assert [i.dummy_eq(j) for i, j in zip(dsolve(eq2), sol2)] # FIXME: assert checksysodesol(eq2, sol2) == (True, [0, 0, 0]) @slow def test_dsolve_options(): eq = x*f(x).diff(x) + f(x) a = dsolve(eq, hint='all') b = dsolve(eq, hint='all', simplify=False) c = dsolve(eq, hint='all_Integral') keys = ['1st_exact', '1st_exact_Integral', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear', '1st_linear_Integral', 'Bernoulli', 'Bernoulli_Integral', 'almost_linear', 'almost_linear_Integral', 'best', 'best_hint', 'default', 'lie_group', 'nth_linear_euler_eq_homogeneous', 'order', 'separable', 'separable_Integral'] Integral_keys = ['1st_exact_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_linear_Integral', 'Bernoulli_Integral', 'almost_linear_Integral', 'best', 'best_hint', 'default', 'nth_linear_euler_eq_homogeneous', 'order', 'separable_Integral'] assert sorted(a.keys()) == keys assert a['order'] == ode_order(eq, f(x)) assert a['best'] == Eq(f(x), C1/x) assert dsolve(eq, hint='best') == Eq(f(x), C1/x) assert a['default'] == 'separable' assert a['best_hint'] == 'separable' assert not a['1st_exact'].has(Integral) assert not a['separable'].has(Integral) assert not a['1st_homogeneous_coeff_best'].has(Integral) assert not a['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral) assert not a['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral) assert not a['1st_linear'].has(Integral) assert a['1st_linear_Integral'].has(Integral) assert a['1st_exact_Integral'].has(Integral) assert a['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral) assert a['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral) assert a['separable_Integral'].has(Integral) assert sorted(b.keys()) == keys assert b['order'] == ode_order(eq, f(x)) assert b['best'] == Eq(f(x), C1/x) assert dsolve(eq, hint='best', simplify=False) == Eq(f(x), C1/x) assert b['default'] == 'separable' assert b['best_hint'] == '1st_linear' assert a['separable'] != b['separable'] assert a['1st_homogeneous_coeff_subs_dep_div_indep'] != \ b['1st_homogeneous_coeff_subs_dep_div_indep'] assert a['1st_homogeneous_coeff_subs_indep_div_dep'] != \ b['1st_homogeneous_coeff_subs_indep_div_dep'] assert not b['1st_exact'].has(Integral) assert not b['separable'].has(Integral) assert not b['1st_homogeneous_coeff_best'].has(Integral) assert not b['1st_homogeneous_coeff_subs_dep_div_indep'].has(Integral) assert not b['1st_homogeneous_coeff_subs_indep_div_dep'].has(Integral) assert not b['1st_linear'].has(Integral) assert b['1st_linear_Integral'].has(Integral) assert b['1st_exact_Integral'].has(Integral) assert b['1st_homogeneous_coeff_subs_dep_div_indep_Integral'].has(Integral) assert b['1st_homogeneous_coeff_subs_indep_div_dep_Integral'].has(Integral) assert b['separable_Integral'].has(Integral) assert sorted(c.keys()) == Integral_keys raises(ValueError, lambda: dsolve(eq, hint='notarealhint')) raises(ValueError, lambda: dsolve(eq, hint='Liouville')) assert dsolve(f(x).diff(x) - 1/f(x)**2, hint='all')['best'] == \ dsolve(f(x).diff(x) - 1/f(x)**2, hint='best') assert dsolve(f(x) + f(x).diff(x) + sin(x).diff(x) + 1, f(x), hint="1st_linear_Integral") == \ Eq(f(x), (C1 + Integral((-sin(x).diff(x) - 1)* exp(Integral(1, x)), x))*exp(-Integral(1, x))) def test_classify_ode(): assert classify_ode(f(x).diff(x, 2), f(x)) == \ ( 'nth_algebraic', 'nth_linear_constant_coeff_homogeneous', 'nth_linear_euler_eq_homogeneous', 'Liouville', '2nd_power_series_ordinary', 'nth_algebraic_Integral', 'Liouville_Integral', ) assert classify_ode(f(x), f(x)) == ('nth_algebraic', 'nth_algebraic_Integral') assert classify_ode(Eq(f(x).diff(x), 0), f(x)) == ( 'nth_algebraic', 'separable', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_homogeneous', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_linear_Integral', 'Bernoulli_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') assert classify_ode(f(x).diff(x)**2, f(x)) == ('factorable', 'nth_algebraic', 'separable', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_homogeneous', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_linear_Integral', 'Bernoulli_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') # issue 4749: f(x) should be cleared from highest derivative before classifying a = classify_ode(Eq(f(x).diff(x) + f(x), x), f(x)) b = classify_ode(f(x).diff(x)*f(x) + f(x)*f(x) - x*f(x), f(x)) c = classify_ode(f(x).diff(x)/f(x) + f(x)/f(x) - x/f(x), f(x)) assert a == ('1st_linear', 'Bernoulli', 'almost_linear', '1st_power_series', "lie_group", 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_linear_Integral', 'Bernoulli_Integral', 'almost_linear_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') assert b == ('factorable', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_linear_Integral', 'Bernoulli_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') assert c == ('1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_linear_Integral', 'Bernoulli_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') assert classify_ode( 2*x*f(x)*f(x).diff(x) + (1 + x)*f(x)**2 - exp(x), f(x) ) == ('Bernoulli', 'almost_linear', 'lie_group', 'Bernoulli_Integral', 'almost_linear_Integral') assert 'Riccati_special_minus2' in \ classify_ode(2*f(x).diff(x) + f(x)**2 - f(x)/x + 3*x**(-2), f(x)) raises(ValueError, lambda: classify_ode(x + f(x, y).diff(x).diff( y), f(x, y))) # issue 5176 k = Symbol('k') assert classify_ode(f(x).diff(x)/(k*f(x) + k*x*f(x)) + 2*f(x)/(k*f(x) + k*x*f(x)) + x*f(x).diff(x)/(k*f(x) + k*x*f(x)) + z, f(x)) == \ ('separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral') # preprocessing ans = ('nth_algebraic', 'separable', '1st_exact', '1st_linear', 'Bernoulli', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', 'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters', 'nth_algebraic_Integral', 'separable_Integral', '1st_exact_Integral', '1st_linear_Integral', 'Bernoulli_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral', 'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral') # w/o f(x) given assert classify_ode(diff(f(x) + x, x) + diff(f(x), x)) == ans # w/ f(x) and prep=True assert classify_ode(diff(f(x) + x, x) + diff(f(x), x), f(x), prep=True) == ans assert classify_ode(Eq(2*x**3*f(x).diff(x), 0), f(x)) == \ ('factorable', 'nth_algebraic', 'separable', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_linear_euler_eq_homogeneous', 'nth_algebraic_Integral', 'separable_Integral', '1st_linear_Integral', 'Bernoulli_Integral') assert classify_ode(Eq(2*f(x)**3*f(x).diff(x), 0), f(x)) == \ ('factorable', 'nth_algebraic', 'separable', '1st_linear', 'Bernoulli', '1st_power_series', 'lie_group', 'nth_algebraic_Integral', 'separable_Integral', '1st_linear_Integral', 'Bernoulli_Integral') # test issue 13864 assert classify_ode(Eq(diff(f(x), x) - f(x)**x, 0), f(x)) == \ ('1st_power_series', 'lie_group') assert isinstance(classify_ode(Eq(f(x), 5), f(x), dict=True), dict) def test_classify_ode_ics(): # Dummy eq = f(x).diff(x, x) - f(x) # Not f(0) or f'(0) ics = {x: 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) ############################ # f(0) type (AppliedUndef) # ############################ # Wrong function ics = {g(0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Contains x ics = {f(x): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Too many args ics = {f(0, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # point contains f # XXX: Should be NotImplementedError ics = {f(0): f(1)} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Does not raise ics = {f(0): 1} classify_ode(eq, f(x), ics=ics) ##################### # f'(0) type (Subs) # ##################### # Wrong function ics = {g(x).diff(x).subs(x, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Contains x ics = {f(y).diff(y).subs(y, x): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Wrong variable ics = {f(y).diff(y).subs(y, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Too many args ics = {f(x, y).diff(x).subs(x, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Derivative wrt wrong vars ics = {Derivative(f(x), x, y).subs(x, 0): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # point contains f # XXX: Should be NotImplementedError ics = {f(x).diff(x).subs(x, 0): f(0)} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Does not raise ics = {f(x).diff(x).subs(x, 0): 1} classify_ode(eq, f(x), ics=ics) ########################### # f'(y) type (Derivative) # ########################### # Wrong function ics = {g(x).diff(x).subs(x, y): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Contains x ics = {f(y).diff(y).subs(y, x): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Too many args ics = {f(x, y).diff(x).subs(x, y): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Derivative wrt wrong vars ics = {Derivative(f(x), x, z).subs(x, y): 1} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # point contains f # XXX: Should be NotImplementedError ics = {f(x).diff(x).subs(x, y): f(0)} raises(ValueError, lambda: classify_ode(eq, f(x), ics=ics)) # Does not raise ics = {f(x).diff(x).subs(x, y): 1} classify_ode(eq, f(x), ics=ics) def test_classify_sysode(): # Here x is assumed to be x(t) and y as y(t) for simplicity. # Similarly diff(x,t) and diff(y,y) is assumed to be x1 and y1 respectively. k, l, m, n = symbols('k, l, m, n', Integer=True) k1, k2, k3, l1, l2, l3, m1, m2, m3 = symbols('k1, k2, k3, l1, l2, l3, m1, m2, m3', Integer=True) P, Q, R, p, q, r = symbols('P, Q, R, p, q, r', cls=Function) P1, P2, P3, Q1, Q2, R1, R2 = symbols('P1, P2, P3, Q1, Q2, R1, R2', cls=Function) x, y, z = symbols('x, y, z', cls=Function) t = symbols('t') x1 = diff(x(t),t) ; y1 = diff(y(t),t) ; eq6 = (Eq(x1, exp(k*x(t))*P(x(t),y(t))), Eq(y1,r(y(t))*P(x(t),y(t)))) sol6 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \ (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': 'type2', 'func': \ [x(t), y(t)], 'is_linear': False, 'eq': [-P(x(t), y(t))*exp(k*x(t)) + Derivative(x(t), t), -P(x(t), \ y(t))*r(y(t)) + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq6) == sol6 eq7 = (Eq(x1, x(t)**2+y(t)/x(t)), Eq(y1, x(t)/y(t))) sol7 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): 0, (1, x(t), 1): 0, (0, x(t), 1): 1, (1, y(t), 0): 0, \ (1, x(t), 0): -1/y(t), (0, y(t), 1): 0, (0, y(t), 0): -1/x(t), (1, y(t), 1): 1}, 'type_of_equation': 'type3', \ 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)**2 + Derivative(x(t), t) - y(t)/x(t), -x(t)/y(t) + \ Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq7) == sol7 eq8 = (Eq(x1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t)), Eq(y1, P1(x(t))*Q1(y(t))*R(x(t),y(t),t))) sol8 = {'func': [x(t), y(t)], 'is_linear': False, 'type_of_equation': 'type4', 'eq': \ [-P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + Derivative(x(t), t), -P1(x(t))*Q1(y(t))*R(x(t), y(t), t) + \ Derivative(y(t), t)], 'func_coeff': {(0, y(t), 1): 0, (1, y(t), 1): 1, (1, x(t), 1): 0, (0, y(t), 0): 0, \ (1, x(t), 0): 0, (0, x(t), 0): 0, (1, y(t), 0): 0, (0, x(t), 1): 1}, 'order': {y(t): 1, x(t): 1}, 'no_of_equation': 2} assert classify_sysode(eq8) == sol8 eq11 = (Eq(x1,x(t)*y(t)**3), Eq(y1,y(t)**5)) sol11 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)**3, (1, x(t), 1): 0, (0, x(t), 1): 1, \ (1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): 0, (1, y(t), 1): 1}, 'type_of_equation': \ 'type1', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)**3 + Derivative(x(t), t), \ -y(t)**5 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq11) == sol11 eq13 = (Eq(x1,x(t)*y(t)*sin(t)**2), Eq(y1,y(t)**2*sin(t)**2)) sol13 = {'no_of_equation': 2, 'func_coeff': {(0, x(t), 0): -y(t)*sin(t)**2, (1, x(t), 1): 0, (0, x(t), 1): 1, \ (1, y(t), 0): 0, (1, x(t), 0): 0, (0, y(t), 1): 0, (0, y(t), 0): -x(t)*sin(t)**2, (1, y(t), 1): 1}, \ 'type_of_equation': 'type4', 'func': [x(t), y(t)], 'is_linear': False, 'eq': [-x(t)*y(t)*sin(t)**2 + \ Derivative(x(t), t), -y(t)**2*sin(t)**2 + Derivative(y(t), t)], 'order': {y(t): 1, x(t): 1}} assert classify_sysode(eq13) == sol13 def test_solve_ics(): # Basic tests that things work from dsolve. assert dsolve(f(x).diff(x) - 1/f(x), f(x), ics={f(1): 2}) == \ Eq(f(x), sqrt(2 * x + 2)) assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(0): 1}) == Eq(f(x), exp(x)) assert dsolve(f(x).diff(x) - f(x), f(x), ics={f(x).diff(x).subs(x, 0): 1}) == Eq(f(x), exp(x)) assert dsolve(f(x).diff(x, x) + f(x), f(x), ics={f(0): 1, f(x).diff(x).subs(x, 0): 1}) == Eq(f(x), sin(x) + cos(x)) assert dsolve([f(x).diff(x) - f(x) + g(x), g(x).diff(x) - g(x) - f(x)], [f(x), g(x)], ics={f(0): 1, g(0): 0}) == [Eq(f(x), exp(x)*cos(x)), Eq(g(x), exp(x)*sin(x))] # Test cases where dsolve returns two solutions. eq = (x**2*f(x)**2 - x).diff(x) assert dsolve(eq, f(x), ics={f(1): 0}) == [Eq(f(x), -sqrt(x - 1)/x), Eq(f(x), sqrt(x - 1)/x)] assert dsolve(eq, f(x), ics={f(x).diff(x).subs(x, 1): 0}) == [Eq(f(x), -sqrt(x - S.Half)/x), Eq(f(x), sqrt(x - S.Half)/x)] eq = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x) assert dsolve(eq, f(x), ics={f(0):1}, hint='1st_exact', simplify=False) == Eq(x*cos(f(x)) + f(x)**3/3, Rational(1, 3)) assert dsolve(eq, f(x), ics={f(0):1}, hint='1st_exact', simplify=True) == Eq(x*cos(f(x)) + f(x)**3/3, Rational(1, 3)) assert solve_ics([Eq(f(x), C1*exp(x))], [f(x)], [C1], {f(0): 1}) == {C1: 1} assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1, f(pi/2): 1}) == {C1: 1, C2: 1} assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1, f(x).diff(x).subs(x, 0): 1}) == {C1: 1, C2: 1} assert solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1}) == \ {C2: 1} # Some more complicated tests Refer to PR #16098 assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x, 1):0})) == \ {Eq(f(x), 0), Eq(f(x), x ** 3 / 6 - x / 2)} assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0})) == \ {Eq(f(x), 0), Eq(f(x), C2*x + x**3/6)} K, r, f0 = symbols('K r f0') sol = Eq(f(x), K*f0*exp(r*x)/((-K + f0)*(f0*exp(r*x)/(-K + f0) - 1))) assert (dsolve(Eq(f(x).diff(x), r * f(x) * (1 - f(x) / K)), f(x), ics={f(0): f0})) == sol #Order dependent issues Refer to PR #16098 assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(x).diff(x).subs(x,0):0, f(0):0})) == \ {Eq(f(x), 0), Eq(f(x), x ** 3 / 6)} assert set(dsolve(f(x).diff(x)*(f(x).diff(x, 2)-x), ics={f(0):0, f(x).diff(x).subs(x,0):0})) == \ {Eq(f(x), 0), Eq(f(x), x ** 3 / 6)} # XXX: Ought to be ValueError raises(ValueError, lambda: solve_ics([Eq(f(x), C1*sin(x) + C2*cos(x))], [f(x)], [C1, C2], {f(0): 1, f(pi): 1})) # Degenerate case. f'(0) is identically 0. raises(ValueError, lambda: solve_ics([Eq(f(x), sqrt(C1 - x**2))], [f(x)], [C1], {f(x).diff(x).subs(x, 0): 0})) EI, q, L = symbols('EI q L') # eq = Eq(EI*diff(f(x), x, 4), q) sols = [Eq(f(x), C1 + C2*x + C3*x**2 + C4*x**3 + q*x**4/(24*EI))] funcs = [f(x)] constants = [C1, C2, C3, C4] # Test both cases, Derivative (the default from f(x).diff(x).subs(x, L)), # and Subs ics1 = {f(0): 0, f(x).diff(x).subs(x, 0): 0, f(L).diff(L, 2): 0, f(L).diff(L, 3): 0} ics2 = {f(0): 0, f(x).diff(x).subs(x, 0): 0, Subs(f(x).diff(x, 2), x, L): 0, Subs(f(x).diff(x, 3), x, L): 0} solved_constants1 = solve_ics(sols, funcs, constants, ics1) solved_constants2 = solve_ics(sols, funcs, constants, ics2) assert solved_constants1 == solved_constants2 == { C1: 0, C2: 0, C3: L**2*q/(4*EI), C4: -L*q/(6*EI)} def test_ode_order(): f = Function('f') g = Function('g') x = Symbol('x') assert ode_order(3*x*exp(f(x)), f(x)) == 0 assert ode_order(x*diff(f(x), x) + 3*x*f(x) - sin(x)/x, f(x)) == 1 assert ode_order(x**2*f(x).diff(x, x) + x*diff(f(x), x) - f(x), f(x)) == 2 assert ode_order(diff(x*exp(f(x)), x, x), f(x)) == 2 assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), f(x)) == 3 assert ode_order(diff(f(x), x, x), g(x)) == 0 assert ode_order(diff(f(x), x, x)*diff(g(x), x), f(x)) == 2 assert ode_order(diff(f(x), x, x)*diff(g(x), x), g(x)) == 1 assert ode_order(diff(x*diff(x*exp(f(x)), x, x), x), g(x)) == 0 # issue 5835: ode_order has to also work for unevaluated derivatives # (ie, without using doit()). assert ode_order(Derivative(x*f(x), x), f(x)) == 1 assert ode_order(x*sin(Derivative(x*f(x)**2, x, x)), f(x)) == 2 assert ode_order(Derivative(x*Derivative(x*exp(f(x)), x, x), x), g(x)) == 0 assert ode_order(Derivative(f(x), x, x), g(x)) == 0 assert ode_order(Derivative(x*exp(f(x)), x, x), f(x)) == 2 assert ode_order(Derivative(f(x), x, x)*Derivative(g(x), x), g(x)) == 1 assert ode_order(Derivative(x*Derivative(f(x), x, x), x), f(x)) == 3 assert ode_order( x*sin(Derivative(x*Derivative(f(x), x)**2, x, x)), f(x)) == 3 # In all tests below, checkodesol has the order option set to prevent # superfluous calls to ode_order(), and the solve_for_func flag set to False # because dsolve() already tries to solve for the function, unless the # simplify=False option is set. def test_old_ode_tests(): # These are simple tests from the old ode module eq1 = Eq(f(x).diff(x), 0) eq2 = Eq(3*f(x).diff(x) - 5, 0) eq3 = Eq(3*f(x).diff(x), 5) eq4 = Eq(9*f(x).diff(x, x) + f(x), 0) eq5 = Eq(9*f(x).diff(x, x), f(x)) # Type: a(x)f'(x)+b(x)*f(x)+c(x)=0 eq6 = Eq(x**2*f(x).diff(x) + 3*x*f(x) - sin(x)/x, 0) eq7 = Eq(f(x).diff(x, x) - 3*diff(f(x), x) + 2*f(x), 0) # Type: 2nd order, constant coefficients (two real different roots) eq8 = Eq(f(x).diff(x, x) - 4*diff(f(x), x) + 4*f(x), 0) # Type: 2nd order, constant coefficients (two real equal roots) eq9 = Eq(f(x).diff(x, x) + 2*diff(f(x), x) + 3*f(x), 0) # Type: 2nd order, constant coefficients (two complex roots) eq10 = Eq(3*f(x).diff(x) - 1, 0) eq11 = Eq(x*f(x).diff(x) - 1, 0) sol1 = Eq(f(x), C1) sol2 = Eq(f(x), C1 + x*Rational(5, 3)) sol3 = Eq(f(x), C1 + x*Rational(5, 3)) sol4 = Eq(f(x), C1*sin(x/3) + C2*cos(x/3)) sol5 = Eq(f(x), C1*exp(-x/3) + C2*exp(x/3)) sol6 = Eq(f(x), (C1 - cos(x))/x**3) sol7 = Eq(f(x), (C1 + C2*exp(x))*exp(x)) sol8 = Eq(f(x), (C1 + C2*x)*exp(2*x)) sol9 = Eq(f(x), (C1*sin(x*sqrt(2)) + C2*cos(x*sqrt(2)))*exp(-x)) sol10 = Eq(f(x), C1 + x/3) sol11 = Eq(f(x), C1 + log(x)) assert dsolve(eq1) == sol1 assert dsolve(eq1.lhs) == sol1 assert dsolve(eq2) == sol2 assert dsolve(eq3) == sol3 assert dsolve(eq4) == sol4 assert dsolve(eq5) == sol5 assert dsolve(eq6) == sol6 assert dsolve(eq7) == sol7 assert dsolve(eq8) == sol8 assert dsolve(eq9) == sol9 assert dsolve(eq10) == sol10 assert dsolve(eq11) == sol11 assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=2, solve_for_func=False)[0] assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0] assert checkodesol(eq6, sol6, order=1, solve_for_func=False)[0] assert checkodesol(eq7, sol7, order=2, solve_for_func=False)[0] assert checkodesol(eq8, sol8, order=2, solve_for_func=False)[0] assert checkodesol(eq9, sol9, order=2, solve_for_func=False)[0] assert checkodesol(eq10, sol10, order=1, solve_for_func=False)[0] assert checkodesol(eq11, sol11, order=1, solve_for_func=False)[0] @slow def test_1st_exact1(): # Type: Exact differential equation, p(x,f) + q(x,f)*f' == 0, # where dp/df == dq/dx eq1 = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x) eq2 = (2*x*f(x) + 1)/f(x) + (f(x) - x)/f(x)**2*f(x).diff(x) eq3 = 2*x + f(x)*cos(x) + (2*f(x) + sin(x) - sin(f(x)))*f(x).diff(x) eq4 = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x) eq5 = 2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x) sol1 = [Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))] sol2 = Eq(f(x), exp(C1 - x**2 + LambertW(-x*exp(-C1 + x**2)))) sol2b = Eq(log(f(x)) + x/f(x) + x**2, C1) sol3 = Eq(f(x)*sin(x) + cos(f(x)) + x**2 + f(x)**2, C1) sol4 = Eq(x*cos(f(x)) + f(x)**3/3, C1) sol5 = Eq(x**2*f(x) + f(x)**3/3, C1) assert dsolve(eq1, f(x), hint='1st_exact') == sol1 assert dsolve(eq2, f(x), hint='1st_exact') == sol2 assert dsolve(eq3, f(x), hint='1st_exact') == sol3 assert dsolve(eq4, hint='1st_exact') == sol4 assert dsolve(eq5, hint='1st_exact', simplify=False) == sol5 assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0] # issue 5080 blocks the testing of this solution # FIXME: assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0] assert checkodesol(eq2, sol2b, order=1, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=1, solve_for_func=False)[0] assert checkodesol(eq5, sol5, order=1, solve_for_func=False)[0] @slow @XFAIL def test_1st_exact2_broken(): """ This is an exact equation that fails under the exact engine. It is caught by first order homogeneous albeit with a much contorted solution. The exact engine fails because of a poorly simplified integral of q(0,y)dy, where q is the function multiplying f'. The solutions should be Eq(sqrt(x**2+f(x)**2)**3+y**3, C1). The equation below is equivalent, but it is so complex that checkodesol fails, and takes a long time to do so. """ if ON_TRAVIS: skip("Too slow for travis.") eq = (x*sqrt(x**2 + f(x)**2) - (x**2*f(x)/(f(x) - sqrt(x**2 + f(x)**2)))*f(x).diff(x)) sol = Eq(log(x), C1 - 9*sqrt(1 + f(x)**2/x**2)*asinh(f(x)/x)/(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)) - 9*sqrt(1 + f(x)**2/x**2)* log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/ (-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)) + 9*asinh(f(x)/x)*f(x)/(x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2))) + 9*f(x)*log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/ (x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)))) assert dsolve(eq) == sol # Slow # FIXME: Checked in test_1st_exact2_broken_check below @slow def test_1st_exact2_broken_check(): # See test_1st_exact2_broken above eq = (x*sqrt(x**2 + f(x)**2) - (x**2*f(x)/(f(x) - sqrt(x**2 + f(x)**2)))*f(x).diff(x)) sol = Eq(log(x), C1 - 9*sqrt(1 + f(x)**2/x**2)*asinh(f(x)/x)/(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)) - 9*sqrt(1 + f(x)**2/x**2)* log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/ (-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)) + 9*asinh(f(x)/x)*f(x)/(x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2))) + 9*f(x)*log(1 - sqrt(1 + f(x)**2/x**2)*f(x)/x + 2*f(x)**2/x**2)/ (x*(-27*f(x)/x + 27*sqrt(1 + f(x)**2/x**2)))) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_homogeneous_order(): assert homogeneous_order(exp(y/x) + tan(y/x), x, y) == 0 assert homogeneous_order(x**2 + sin(x)*cos(y), x, y) is None assert homogeneous_order(x - y - x*sin(y/x), x, y) == 1 assert homogeneous_order((x*y + sqrt(x**4 + y**4) + x**2*(log(x) - log(y)))/ (pi*x**Rational(2, 3)*sqrt(y)**3), x, y) == Rational(-1, 6) assert homogeneous_order(y/x*cos(y/x) - x/y*sin(y/x) + cos(y/x), x, y) == 0 assert homogeneous_order(f(x), x, f(x)) == 1 assert homogeneous_order(f(x)**2, x, f(x)) == 2 assert homogeneous_order(x*y*z, x, y) == 2 assert homogeneous_order(x*y*z, x, y, z) == 3 assert homogeneous_order(x**2*f(x)/sqrt(x**2 + f(x)**2), f(x)) is None assert homogeneous_order(f(x, y)**2, x, f(x, y), y) == 2 assert homogeneous_order(f(x, y)**2, x, f(x), y) is None assert homogeneous_order(f(x, y)**2, x, f(x, y)) is None assert homogeneous_order(f(y, x)**2, x, y, f(x, y)) is None assert homogeneous_order(f(y), f(x), x) is None assert homogeneous_order(-f(x)/x + 1/sin(f(x)/ x), f(x), x) == 0 assert homogeneous_order(log(1/y) + log(x**2), x, y) is None assert homogeneous_order(log(1/y) + log(x), x, y) == 0 assert homogeneous_order(log(x/y), x, y) == 0 assert homogeneous_order(2*log(1/y) + 2*log(x), x, y) == 0 a = Symbol('a') assert homogeneous_order(a*log(1/y) + a*log(x), x, y) == 0 assert homogeneous_order(f(x).diff(x), x, y) is None assert homogeneous_order(-f(x).diff(x) + x, x, y) is None assert homogeneous_order(O(x), x, y) is None assert homogeneous_order(x + O(x**2), x, y) is None assert homogeneous_order(x**pi, x) == pi assert homogeneous_order(x**x, x) is None raises(ValueError, lambda: homogeneous_order(x*y)) @slow def test_1st_homogeneous_coeff_ode(): # Type: First order homogeneous, y'=f(y/x) eq1 = f(x)/x*cos(f(x)/x) - (x/f(x)*sin(f(x)/x) + cos(f(x)/x))*f(x).diff(x) eq2 = x*f(x).diff(x) - f(x) - x*sin(f(x)/x) eq3 = f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x) eq4 = 2*f(x)*exp(x/f(x)) + f(x)*f(x).diff(x) - 2*x*exp(x/f(x))*f(x).diff(x) eq5 = 2*x**2*f(x) + f(x)**3 + (x*f(x)**2 - 2*x**3)*f(x).diff(x) eq6 = x*exp(f(x)/x) - f(x)*sin(f(x)/x) + x*sin(f(x)/x)*f(x).diff(x) eq7 = (x + sqrt(f(x)**2 - x*f(x)))*f(x).diff(x) - f(x) eq8 = x + f(x) - (x - f(x))*f(x).diff(x) sol1 = Eq(log(x), C1 - log(f(x)*sin(f(x)/x)/x)) sol2 = Eq(log(x), log(C1) + log(cos(f(x)/x) - 1)/2 - log(cos(f(x)/x) + 1)/2) sol3 = Eq(f(x), -exp(C1)*LambertW(-x*exp(-C1 + 1))) sol4 = Eq(log(f(x)), C1 - 2*exp(x/f(x))) sol5 = Eq(f(x), exp(2*C1 + LambertW(-2*x**4*exp(-4*C1))/2)/x) sol6 = Eq(log(x), C1 + exp(-f(x)/x)*sin(f(x)/x)/2 + exp(-f(x)/x)*cos(f(x)/x)/2) sol7 = Eq(log(f(x)), C1 - 2*sqrt(-x/f(x) + 1)) sol8 = Eq(log(x), C1 - log(sqrt(1 + f(x)**2/x**2)) + atan(f(x)/x)) # indep_div_dep actually has a simpler solution for eq2, # but it runs too slow assert dsolve(eq1, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol1 assert dsolve(eq2, hint='1st_homogeneous_coeff_subs_dep_div_indep', simplify=False) == sol2 assert dsolve(eq3, hint='1st_homogeneous_coeff_best') == sol3 assert dsolve(eq4, hint='1st_homogeneous_coeff_best') == sol4 assert dsolve(eq5, hint='1st_homogeneous_coeff_best') == sol5 assert dsolve(eq6, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol6 assert dsolve(eq7, hint='1st_homogeneous_coeff_best') == sol7 assert dsolve(eq8, hint='1st_homogeneous_coeff_best') == sol8 # FIXME: sol3 and sol5 don't work with checkodesol (because of LambertW?) # previous code was testing with these other solutions: sol3b = Eq(-f(x)/(1 + log(x/f(x))), C1) sol5b = Eq(log(C1*x*sqrt(1/x)*sqrt(f(x))) + x**2/(2*f(x)**2), 0) assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0] assert checkodesol(eq3, sol3b, order=1, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=1, solve_for_func=False)[0] assert checkodesol(eq5, sol5b, order=1, solve_for_func=False)[0] assert checkodesol(eq6, sol6, order=1, solve_for_func=False)[0] assert checkodesol(eq8, sol8, order=1, solve_for_func=False)[0] def test_1st_homogeneous_coeff_ode_check2(): eq2 = x*f(x).diff(x) - f(x) - x*sin(f(x)/x) sol2 = Eq(x/tan(f(x)/(2*x)), C1) assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0] def test_1st_homogeneous_coeff_ode_check3(): eq3 = f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x) # This solution is correct: sol3 = Eq(f(x), -exp(C1)*LambertW(-x*exp(1 - C1))) assert dsolve(eq3) == sol3 # FIXME: Checked in test_1st_homogeneous_coeff_ode_check3_check below # Alternate form: sol3a = Eq(f(x), x*exp(1 - LambertW(C1*x))) assert checkodesol(eq3, sol3a, solve_for_func=True)[0] @XFAIL def test_1st_homogeneous_coeff_ode_check3_check(): # See test_1st_homogeneous_coeff_ode_check3 above eq3 = f(x) + (x*log(f(x)/x) - 2*x)*diff(f(x), x) sol3 = Eq(f(x), -exp(C1)*LambertW(-x*exp(1 - C1))) assert checkodesol(eq3, sol3) == (True, 0) # XFAIL def test_1st_homogeneous_coeff_ode_check7(): eq7 = (x + sqrt(f(x)**2 - x*f(x)))*f(x).diff(x) - f(x) sol7 = Eq(log(f(x)), C1 - 2*sqrt(-x/f(x) + 1)) assert dsolve(eq7) == sol7 assert checkodesol(eq7, sol7, order=1, solve_for_func=False) == (True, 0) def test_1st_homogeneous_coeff_ode2(): eq1 = f(x).diff(x) - f(x)/x + 1/sin(f(x)/x) eq2 = x**2 + f(x)**2 - 2*x*f(x)*f(x).diff(x) eq3 = x*exp(f(x)/x) + f(x) - x*f(x).diff(x) sol1 = [Eq(f(x), x*(-acos(C1 + log(x)) + 2*pi)), Eq(f(x), x*acos(C1 + log(x)))] sol2 = Eq(log(f(x)), log(C1) + log(x/f(x)) - log(x**2/f(x)**2 - 1)) sol3 = Eq(f(x), log((1/(C1 - log(x)))**x)) # specific hints are applied for speed reasons assert dsolve(eq1, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol1 assert dsolve(eq2, hint='1st_homogeneous_coeff_best', simplify=False) == sol2 assert dsolve(eq3, hint='1st_homogeneous_coeff_subs_dep_div_indep') == sol3 # FIXME: sol3 doesn't work with checkodesol (because of **x?) # previous code was testing with this other solution: sol3b = Eq(f(x), log(log(C1/x)**(-x))) assert checkodesol(eq1, sol1, order=1, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=1, solve_for_func=False)[0] assert checkodesol(eq3, sol3b, order=1, solve_for_func=False)[0] def test_1st_homogeneous_coeff_ode_check9(): _u2 = Dummy('u2') __a = Dummy('a') eq9 = f(x)**2 + (x*sqrt(f(x)**2 - x**2) - x*f(x))*f(x).diff(x) sol9 = Eq(-Integral(-1/(-(1 - sqrt(1 - _u2**2))*_u2 + _u2), (_u2, __a, x/f(x))) + log(C1*f(x)), 0) assert checkodesol(eq9, sol9, order=1, solve_for_func=False)[0] def test_1st_homogeneous_coeff_ode3(): # The standard integration engine cannot handle one of the integrals # involved (see issue 4551). meijerg code comes up with an answer, but in # unconventional form. # checkodesol fails for this equation, so its test is in # test_1st_homogeneous_coeff_ode_check9 above. It has to compare string # expressions because u2 is a dummy variable. eq = f(x)**2 + (x*sqrt(f(x)**2 - x**2) - x*f(x))*f(x).diff(x) sol = Eq(log(f(x)), C1 + Piecewise( (acosh(f(x)/x), abs(f(x)**2)/x**2 > 1), (-I*asin(f(x)/x), True))) assert dsolve(eq, hint='1st_homogeneous_coeff_subs_indep_div_dep') == sol def test_1st_homogeneous_coeff_corner_case(): eq1 = f(x).diff(x) - f(x)/x c1 = classify_ode(eq1, f(x)) eq2 = x*f(x).diff(x) - f(x) c2 = classify_ode(eq2, f(x)) sdi = "1st_homogeneous_coeff_subs_dep_div_indep" sid = "1st_homogeneous_coeff_subs_indep_div_dep" assert sid not in c1 and sdi not in c1 assert sid not in c2 and sdi not in c2 @slow def test_nth_linear_constant_coeff_homogeneous(): # From Exercise 20, in Ordinary Differential Equations, # Tenenbaum and Pollard, pg. 220 a = Symbol('a', positive=True) k = Symbol('k', real=True) eq1 = f(x).diff(x, 2) + 2*f(x).diff(x) eq2 = f(x).diff(x, 2) - 3*f(x).diff(x) + 2*f(x) eq3 = f(x).diff(x, 2) - f(x) eq4 = f(x).diff(x, 3) + f(x).diff(x, 2) - 6*f(x).diff(x) eq5 = 6*f(x).diff(x, 2) - 11*f(x).diff(x) + 4*f(x) eq6 = Eq(f(x).diff(x, 2) + 2*f(x).diff(x) - f(x), 0) eq7 = diff(f(x), x, 3) + diff(f(x), x, 2) - 10*diff(f(x), x) - 6*f(x) eq8 = f(x).diff(x, 4) - f(x).diff(x, 3) - 4*f(x).diff(x, 2) + \ 4*f(x).diff(x) eq9 = f(x).diff(x, 4) + 4*f(x).diff(x, 3) + f(x).diff(x, 2) - \ 4*f(x).diff(x) - 2*f(x) eq10 = f(x).diff(x, 4) - a**2*f(x) eq11 = f(x).diff(x, 2) - 2*k*f(x).diff(x) - 2*f(x) eq12 = f(x).diff(x, 2) + 4*k*f(x).diff(x) - 12*k**2*f(x) eq13 = f(x).diff(x, 4) eq14 = f(x).diff(x, 2) + 4*f(x).diff(x) + 4*f(x) eq15 = 3*f(x).diff(x, 3) + 5*f(x).diff(x, 2) + f(x).diff(x) - f(x) eq16 = f(x).diff(x, 3) - 6*f(x).diff(x, 2) + 12*f(x).diff(x) - 8*f(x) eq17 = f(x).diff(x, 2) - 2*a*f(x).diff(x) + a**2*f(x) eq18 = f(x).diff(x, 4) + 3*f(x).diff(x, 3) eq19 = f(x).diff(x, 4) - 2*f(x).diff(x, 2) eq20 = f(x).diff(x, 4) + 2*f(x).diff(x, 3) - 11*f(x).diff(x, 2) - \ 12*f(x).diff(x) + 36*f(x) eq21 = 36*f(x).diff(x, 4) - 37*f(x).diff(x, 2) + 4*f(x).diff(x) + 5*f(x) eq22 = f(x).diff(x, 4) - 8*f(x).diff(x, 2) + 16*f(x) eq23 = f(x).diff(x, 2) - 2*f(x).diff(x) + 5*f(x) eq24 = f(x).diff(x, 2) - f(x).diff(x) + f(x) eq25 = f(x).diff(x, 4) + 5*f(x).diff(x, 2) + 6*f(x) eq26 = f(x).diff(x, 2) - 4*f(x).diff(x) + 20*f(x) eq27 = f(x).diff(x, 4) + 4*f(x).diff(x, 2) + 4*f(x) eq28 = f(x).diff(x, 3) + 8*f(x) eq29 = f(x).diff(x, 4) + 4*f(x).diff(x, 2) eq30 = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) eq31 = f(x).diff(x, 4) + f(x).diff(x, 2) + f(x) eq32 = f(x).diff(x, 4) + 4*f(x).diff(x, 2) + f(x) sol1 = Eq(f(x), C1 + C2*exp(-2*x)) sol2 = Eq(f(x), (C1 + C2*exp(x))*exp(x)) sol3 = Eq(f(x), C1*exp(x) + C2*exp(-x)) sol4 = Eq(f(x), C1 + C2*exp(-3*x) + C3*exp(2*x)) sol5 = Eq(f(x), C1*exp(x/2) + C2*exp(x*Rational(4, 3))) sol6 = Eq(f(x), C1*exp(x*(-1 + sqrt(2))) + C2*exp(x*(-sqrt(2) - 1))) sol7 = Eq(f(x), C3*exp(3*x) + (C1*exp(-sqrt(2)*x) + C2*exp(sqrt(2)*x))*exp(-2*x)) sol8 = Eq(f(x), C1 + C2*exp(x) + C3*exp(-2*x) + C4*exp(2*x)) sol9 = Eq(f(x), C3*exp(-x) + C4*exp(x) + (C1*exp(-sqrt(2)*x) + C2*exp(sqrt(2)*x))*exp(-2*x)) sol10 = Eq(f(x), C1*sin(x*sqrt(a)) + C2*cos(x*sqrt(a)) + C3*exp(x*sqrt(a)) + C4*exp(-x*sqrt(a))) sol11 = Eq(f(x), C1*exp(x*(k - sqrt(k**2 + 2))) + C2*exp(x*(k + sqrt(k**2 + 2)))) sol12 = Eq(f(x), C1*exp(-6*k*x) + C2*exp(2*k*x)) sol13 = Eq(f(x), C1 + C2*x + C3*x**2 + C4*x**3) sol14 = Eq(f(x), (C1 + C2*x)*exp(-2*x)) sol15 = Eq(f(x), (C1 + C2*x)*exp(-x) + C3*exp(x/3)) sol16 = Eq(f(x), (C1 + x*(C2 + C3*x))*exp(2*x)) sol17 = Eq(f(x), (C1 + C2*x)*exp(a*x)) sol18 = Eq(f(x), C1 + C2*x + C3*x**2 + C4*exp(-3*x)) sol19 = Eq(f(x), C1 + C2*x + C3*exp(x*sqrt(2)) + C4*exp(-x*sqrt(2))) sol20 = Eq(f(x), (C1 + C2*x)*exp(-3*x) + (C3 + C4*x)*exp(2*x)) sol21 = Eq(f(x), C1*exp(x/2) + C2*exp(-x) + C3*exp(-x/3) + C4*exp(x*Rational(5, 6))) sol22 = Eq(f(x), (C1 + C2*x)*exp(-2*x) + (C3 + C4*x)*exp(2*x)) sol23 = Eq(f(x), (C1*sin(2*x) + C2*cos(2*x))*exp(x)) sol24 = Eq(f(x), (C1*sin(x*sqrt(3)/2) + C2*cos(x*sqrt(3)/2))*exp(x/2)) sol25 = Eq(f(x), C1*cos(x*sqrt(3)) + C2*sin(x*sqrt(3)) + C3*sin(x*sqrt(2)) + C4*cos(x*sqrt(2))) sol26 = Eq(f(x), (C1*sin(4*x) + C2*cos(4*x))*exp(2*x)) sol27 = Eq(f(x), (C1 + C2*x)*sin(x*sqrt(2)) + (C3 + C4*x)*cos(x*sqrt(2))) sol28 = Eq(f(x), (C1*sin(x*sqrt(3)) + C2*cos(x*sqrt(3)))*exp(x) + C3*exp(-2*x)) sol29 = Eq(f(x), C1 + C2*sin(2*x) + C3*cos(2*x) + C4*x) sol30 = Eq(f(x), C1 + (C2 + C3*x)*sin(x) + (C4 + C5*x)*cos(x)) sol31 = Eq(f(x), (C1*sin(sqrt(3)*x/2) + C2*cos(sqrt(3)*x/2))/sqrt(exp(x)) + (C3*sin(sqrt(3)*x/2) + C4*cos(sqrt(3)*x/2))*sqrt(exp(x))) sol32 = Eq(f(x), C1*sin(x*sqrt(-sqrt(3) + 2)) + C2*sin(x*sqrt(sqrt(3) + 2)) + C3*cos(x*sqrt(-sqrt(3) + 2)) + C4*cos(x*sqrt(sqrt(3) + 2))) sol1s = constant_renumber(sol1) sol2s = constant_renumber(sol2) sol3s = constant_renumber(sol3) sol4s = constant_renumber(sol4) sol5s = constant_renumber(sol5) sol6s = constant_renumber(sol6) sol7s = constant_renumber(sol7) sol8s = constant_renumber(sol8) sol9s = constant_renumber(sol9) sol10s = constant_renumber(sol10) sol11s = constant_renumber(sol11) sol12s = constant_renumber(sol12) sol13s = constant_renumber(sol13) sol14s = constant_renumber(sol14) sol15s = constant_renumber(sol15) sol16s = constant_renumber(sol16) sol17s = constant_renumber(sol17) sol18s = constant_renumber(sol18) sol19s = constant_renumber(sol19) sol20s = constant_renumber(sol20) sol21s = constant_renumber(sol21) sol22s = constant_renumber(sol22) sol23s = constant_renumber(sol23) sol24s = constant_renumber(sol24) sol25s = constant_renumber(sol25) sol26s = constant_renumber(sol26) sol27s = constant_renumber(sol27) sol28s = constant_renumber(sol28) sol29s = constant_renumber(sol29) sol30s = constant_renumber(sol30) assert dsolve(eq1) in (sol1, sol1s) assert dsolve(eq2) in (sol2, sol2s) assert dsolve(eq3) in (sol3, sol3s) assert dsolve(eq4) in (sol4, sol4s) assert dsolve(eq5) in (sol5, sol5s) assert dsolve(eq6) in (sol6, sol6s) got = dsolve(eq7) assert got in (sol7, sol7s), got assert dsolve(eq8) in (sol8, sol8s) got = dsolve(eq9) assert got in (sol9, sol9s), got assert dsolve(eq10) in (sol10, sol10s) assert dsolve(eq11) in (sol11, sol11s) assert dsolve(eq12) in (sol12, sol12s) assert dsolve(eq13) in (sol13, sol13s) assert dsolve(eq14) in (sol14, sol14s) assert dsolve(eq15) in (sol15, sol15s) got = dsolve(eq16) assert got in (sol16, sol16s), got assert dsolve(eq17) in (sol17, sol17s) assert dsolve(eq18) in (sol18, sol18s) assert dsolve(eq19) in (sol19, sol19s) assert dsolve(eq20) in (sol20, sol20s) assert dsolve(eq21) in (sol21, sol21s) assert dsolve(eq22) in (sol22, sol22s) assert dsolve(eq23) in (sol23, sol23s) assert dsolve(eq24) in (sol24, sol24s) assert dsolve(eq25) in (sol25, sol25s) assert dsolve(eq26) in (sol26, sol26s) assert dsolve(eq27) in (sol27, sol27s) assert dsolve(eq28) in (sol28, sol28s) assert dsolve(eq29) in (sol29, sol29s) assert dsolve(eq30) in (sol30, sol30s) assert dsolve(eq31) in (sol31,) assert dsolve(eq32) in (sol32,) assert checkodesol(eq1, sol1, order=2, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=2, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=2, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=3, solve_for_func=False)[0] assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0] assert checkodesol(eq6, sol6, order=2, solve_for_func=False)[0] assert checkodesol(eq7, sol7, order=3, solve_for_func=False)[0] assert checkodesol(eq8, sol8, order=4, solve_for_func=False)[0] assert checkodesol(eq9, sol9, order=4, solve_for_func=False)[0] assert checkodesol(eq10, sol10, order=4, solve_for_func=False)[0] assert checkodesol(eq11, sol11, order=2, solve_for_func=False)[0] assert checkodesol(eq12, sol12, order=2, solve_for_func=False)[0] assert checkodesol(eq13, sol13, order=4, solve_for_func=False)[0] assert checkodesol(eq14, sol14, order=2, solve_for_func=False)[0] assert checkodesol(eq15, sol15, order=3, solve_for_func=False)[0] assert checkodesol(eq16, sol16, order=3, solve_for_func=False)[0] assert checkodesol(eq17, sol17, order=2, solve_for_func=False)[0] assert checkodesol(eq18, sol18, order=4, solve_for_func=False)[0] assert checkodesol(eq19, sol19, order=4, solve_for_func=False)[0] assert checkodesol(eq20, sol20, order=4, solve_for_func=False)[0] assert checkodesol(eq21, sol21, order=4, solve_for_func=False)[0] assert checkodesol(eq22, sol22, order=4, solve_for_func=False)[0] assert checkodesol(eq23, sol23, order=2, solve_for_func=False)[0] assert checkodesol(eq24, sol24, order=2, solve_for_func=False)[0] assert checkodesol(eq25, sol25, order=4, solve_for_func=False)[0] assert checkodesol(eq26, sol26, order=2, solve_for_func=False)[0] assert checkodesol(eq27, sol27, order=4, solve_for_func=False)[0] assert checkodesol(eq28, sol28, order=3, solve_for_func=False)[0] assert checkodesol(eq29, sol29, order=4, solve_for_func=False)[0] assert checkodesol(eq30, sol30, order=5, solve_for_func=False)[0] assert checkodesol(eq31, sol31, order=4, solve_for_func=False)[0] assert checkodesol(eq32, sol32, order=4, solve_for_func=False)[0] # Issue #15237 eqn = Derivative(x*f(x), x, x, x) hint = 'nth_linear_constant_coeff_homogeneous' raises(ValueError, lambda: dsolve(eqn, f(x), hint, prep=True)) raises(ValueError, lambda: dsolve(eqn, f(x), hint, prep=False)) def test_nth_linear_constant_coeff_homogeneous_rootof(): # One real root, two complex conjugate pairs eq = f(x).diff(x, 5) + 11*f(x).diff(x) - 2*f(x) r1, r2, r3, r4, r5 = [rootof(x**5 + 11*x - 2, n) for n in range(5)] sol = Eq(f(x), C5*exp(r1*x) + exp(re(r2)*x) * (C1*sin(im(r2)*x) + C2*cos(im(r2)*x)) + exp(re(r4)*x) * (C3*sin(im(r4)*x) + C4*cos(im(r4)*x)) ) assert dsolve(eq) == sol # FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs... # Three real roots, one complex conjugate pair eq = f(x).diff(x,5) - 3*f(x).diff(x) + f(x) r1, r2, r3, r4, r5 = [rootof(x**5 - 3*x + 1, n) for n in range(5)] sol = Eq(f(x), C3*exp(r1*x) + C4*exp(r2*x) + C5*exp(r3*x) + exp(re(r4)*x) * (C1*sin(im(r4)*x) + C2*cos(im(r4)*x)) ) assert dsolve(eq) == sol # FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs... # Five distinct real roots eq = f(x).diff(x,5) - 100*f(x).diff(x,3) + 1000*f(x).diff(x) + f(x) r1, r2, r3, r4, r5 = [rootof(x**5 - 100*x**3 + 1000*x + 1, n) for n in range(5)] sol = Eq(f(x), C1*exp(r1*x) + C2*exp(r2*x) + C3*exp(r3*x) + C4*exp(r4*x) + C5*exp(r5*x)) assert dsolve(eq) == sol # FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs... # Rational root and unsolvable quintic eq = f(x).diff(x, 6) - 6*f(x).diff(x, 5) + 5*f(x).diff(x, 4) + 10*f(x).diff(x) - 50 * f(x) r2, r3, r4, r5, r6 = [rootof(x**5 - x**4 + 10, n) for n in range(5)] sol = Eq(f(x), C5*exp(5*x) + C6*exp(x*r2) + exp(re(r3)*x) * (C1*sin(im(r3)*x) + C2*cos(im(r3)*x)) + exp(re(r5)*x) * (C3*sin(im(r5)*x) + C4*cos(im(r5)*x)) ) assert dsolve(eq) == sol # FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs... # Five double roots (this is (x**5 - x + 1)**2) eq = f(x).diff(x, 10) - 2*f(x).diff(x, 6) + 2*f(x).diff(x, 5) + f(x).diff(x, 2) - 2*f(x).diff(x, 1) + f(x) r1, r2, r3, r4, r5 = [rootof(x**5 - x + 1, n) for n in range(5)] sol = Eq(f(x), (C1 + C2*x)*exp(x*r1) + (C10*sin(x*im(r4)) + C7*x*sin(x*im(r4)) + ( C8 + C9*x)*cos(x*im(r4)))*exp(x*re(r4)) + (C3*x*sin(x*im(r2)) + C6*sin(x*im(r2) ) + (C4 + C5*x)*cos(x*im(r2)))*exp(x*re(r2))) got = dsolve(eq) assert sol == got, got # FIXME: assert checkodesol(eq, sol) == (True, [0]) # Hangs... def test_nth_linear_constant_coeff_homogeneous_irrational(): our_hint='nth_linear_constant_coeff_homogeneous' eq = Eq(sqrt(2) * f(x).diff(x,x,x) + f(x).diff(x), 0) sol = Eq(f(x), C1 + C2*sin(2**Rational(3, 4)*x/2) + C3*cos(2**Rational(3, 4)*x/2)) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint) == sol assert dsolve(eq, f(x)) == sol assert checkodesol(eq, sol, order=3, solve_for_func=False)[0] E = exp(1) eq = Eq(E * f(x).diff(x,x,x) + f(x).diff(x), 0) sol = Eq(f(x), C1 + C2*sin(x/sqrt(E)) + C3*cos(x/sqrt(E))) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint) == sol assert dsolve(eq, f(x)) == sol assert checkodesol(eq, sol, order=3, solve_for_func=False)[0] eq = Eq(pi * f(x).diff(x,x,x) + f(x).diff(x), 0) sol = Eq(f(x), C1 + C2*sin(x/sqrt(pi)) + C3*cos(x/sqrt(pi))) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint) == sol assert dsolve(eq, f(x)) == sol assert checkodesol(eq, sol, order=3, solve_for_func=False)[0] eq = Eq(I * f(x).diff(x,x,x) + f(x).diff(x), 0) sol = Eq(f(x), C1 + C2*exp(-sqrt(I)*x) + C3*exp(sqrt(I)*x)) assert our_hint in classify_ode(eq) assert dsolve(eq, f(x), hint=our_hint) == sol assert dsolve(eq, f(x)) == sol assert checkodesol(eq, sol, order=3, solve_for_func=False)[0] @XFAIL @slow def test_nth_linear_constant_coeff_homogeneous_rootof_sol(): # See https://github.com/sympy/sympy/issues/15753 if ON_TRAVIS: skip("Too slow for travis.") eq = f(x).diff(x, 5) + 11*f(x).diff(x) - 2*f(x) sol = Eq(f(x), C1*exp(x*rootof(x**5 + 11*x - 2, 0)) + C2*exp(x*rootof(x**5 + 11*x - 2, 1)) + C3*exp(x*rootof(x**5 + 11*x - 2, 2)) + C4*exp(x*rootof(x**5 + 11*x - 2, 3)) + C5*exp(x*rootof(x**5 + 11*x - 2, 4))) assert checkodesol(eq, sol, order=5, solve_for_func=False)[0] @XFAIL def test_noncircularized_real_imaginary_parts(): # If this passes, lines numbered 3878-3882 (at the time of this commit) # of sympy/solvers/ode.py for nth_linear_constant_coeff_homogeneous # should be removed. y = sqrt(1+x) i, r = im(y), re(y) assert not (i.has(atan2) and r.has(atan2)) def test_collect_respecting_exponentials(): # If this test passes, lines 1306-1311 (at the time of this commit) # of sympy/solvers/ode.py should be removed. sol = 1 + exp(x/2) assert sol == collect( sol, exp(x/3)) def test_undetermined_coefficients_match(): assert _undetermined_coefficients_match(g(x), x) == {'test': False} assert _undetermined_coefficients_match(sin(2*x + sqrt(5)), x) == \ {'test': True, 'trialset': set([cos(2*x + sqrt(5)), sin(2*x + sqrt(5))])} assert _undetermined_coefficients_match(sin(x)*cos(x), x) == \ {'test': False} s = set([cos(x), x*cos(x), x**2*cos(x), x**2*sin(x), x*sin(x), sin(x)]) assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': s} assert _undetermined_coefficients_match( sin(x)*x**2 + sin(x)*x + sin(x), x) == {'test': True, 'trialset': s} assert _undetermined_coefficients_match( exp(2*x)*sin(x)*(x**2 + x + 1), x ) == { 'test': True, 'trialset': set([exp(2*x)*sin(x), x**2*exp(2*x)*sin(x), cos(x)*exp(2*x), x**2*cos(x)*exp(2*x), x*cos(x)*exp(2*x), x*exp(2*x)*sin(x)])} assert _undetermined_coefficients_match(1/sin(x), x) == {'test': False} assert _undetermined_coefficients_match(log(x), x) == {'test': False} assert _undetermined_coefficients_match(2**(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': set([2**x, x*2**x, x**2*2**x])} assert _undetermined_coefficients_match(x**y, x) == {'test': False} assert _undetermined_coefficients_match(exp(x)*exp(2*x + 1), x) == \ {'test': True, 'trialset': set([exp(1 + 3*x)])} assert _undetermined_coefficients_match(sin(x)*(x**2 + x + 1), x) == \ {'test': True, 'trialset': set([x*cos(x), x*sin(x), x**2*cos(x), x**2*sin(x), cos(x), sin(x)])} assert _undetermined_coefficients_match(sin(x)*(x + sin(x)), x) == \ {'test': False} assert _undetermined_coefficients_match(sin(x)*(x + sin(2*x)), x) == \ {'test': False} assert _undetermined_coefficients_match(sin(x)*tan(x), x) == \ {'test': False} assert _undetermined_coefficients_match( x**2*sin(x)*exp(x) + x*sin(x) + x, x ) == { 'test': True, 'trialset': set([x**2*cos(x)*exp(x), x, cos(x), S.One, exp(x)*sin(x), sin(x), x*exp(x)*sin(x), x*cos(x), x*cos(x)*exp(x), x*sin(x), cos(x)*exp(x), x**2*exp(x)*sin(x)])} assert _undetermined_coefficients_match(4*x*sin(x - 2), x) == { 'trialset': set([x*cos(x - 2), x*sin(x - 2), cos(x - 2), sin(x - 2)]), 'test': True, } assert _undetermined_coefficients_match(2**x*x, x) == \ {'test': True, 'trialset': set([2**x, x*2**x])} assert _undetermined_coefficients_match(2**x*exp(2*x), x) == \ {'test': True, 'trialset': set([2**x*exp(2*x)])} assert _undetermined_coefficients_match(exp(-x)/x, x) == \ {'test': False} # Below are from Ordinary Differential Equations, # Tenenbaum and Pollard, pg. 231 assert _undetermined_coefficients_match(S(4), x) == \ {'test': True, 'trialset': set([S.One])} assert _undetermined_coefficients_match(12*exp(x), x) == \ {'test': True, 'trialset': set([exp(x)])} assert _undetermined_coefficients_match(exp(I*x), x) == \ {'test': True, 'trialset': set([exp(I*x)])} assert _undetermined_coefficients_match(sin(x), x) == \ {'test': True, 'trialset': set([cos(x), sin(x)])} assert _undetermined_coefficients_match(cos(x), x) == \ {'test': True, 'trialset': set([cos(x), sin(x)])} assert _undetermined_coefficients_match(8 + 6*exp(x) + 2*sin(x), x) == \ {'test': True, 'trialset': set([S.One, cos(x), sin(x), exp(x)])} assert _undetermined_coefficients_match(x**2, x) == \ {'test': True, 'trialset': set([S.One, x, x**2])} assert _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x) == \ {'test': True, 'trialset': set([x*exp(x), exp(x), exp(-x)])} assert _undetermined_coefficients_match(2*exp(2*x)*sin(x), x) == \ {'test': True, 'trialset': set([exp(2*x)*sin(x), cos(x)*exp(2*x)])} assert _undetermined_coefficients_match(x - sin(x), x) == \ {'test': True, 'trialset': set([S.One, x, cos(x), sin(x)])} assert _undetermined_coefficients_match(x**2 + 2*x, x) == \ {'test': True, 'trialset': set([S.One, x, x**2])} assert _undetermined_coefficients_match(4*x*sin(x), x) == \ {'test': True, 'trialset': set([x*cos(x), x*sin(x), cos(x), sin(x)])} assert _undetermined_coefficients_match(x*sin(2*x), x) == \ {'test': True, 'trialset': set([x*cos(2*x), x*sin(2*x), cos(2*x), sin(2*x)])} assert _undetermined_coefficients_match(x**2*exp(-x), x) == \ {'test': True, 'trialset': set([x*exp(-x), x**2*exp(-x), exp(-x)])} assert _undetermined_coefficients_match(2*exp(-x) - x**2*exp(-x), x) == \ {'test': True, 'trialset': set([x*exp(-x), x**2*exp(-x), exp(-x)])} assert _undetermined_coefficients_match(exp(-2*x) + x**2, x) == \ {'test': True, 'trialset': set([S.One, x, x**2, exp(-2*x)])} assert _undetermined_coefficients_match(x*exp(-x), x) == \ {'test': True, 'trialset': set([x*exp(-x), exp(-x)])} assert _undetermined_coefficients_match(x + exp(2*x), x) == \ {'test': True, 'trialset': set([S.One, x, exp(2*x)])} assert _undetermined_coefficients_match(sin(x) + exp(-x), x) == \ {'test': True, 'trialset': set([cos(x), sin(x), exp(-x)])} assert _undetermined_coefficients_match(exp(x), x) == \ {'test': True, 'trialset': set([exp(x)])} # converted from sin(x)**2 assert _undetermined_coefficients_match(S.Half - cos(2*x)/2, x) == \ {'test': True, 'trialset': set([S.One, cos(2*x), sin(2*x)])} # converted from exp(2*x)*sin(x)**2 assert _undetermined_coefficients_match( exp(2*x)*(S.Half + cos(2*x)/2), x ) == { 'test': True, 'trialset': set([exp(2*x)*sin(2*x), cos(2*x)*exp(2*x), exp(2*x)])} assert _undetermined_coefficients_match(2*x + sin(x) + cos(x), x) == \ {'test': True, 'trialset': set([S.One, x, cos(x), sin(x)])} # converted from sin(2*x)*sin(x) assert _undetermined_coefficients_match(cos(x)/2 - cos(3*x)/2, x) == \ {'test': True, 'trialset': set([cos(x), cos(3*x), sin(x), sin(3*x)])} assert _undetermined_coefficients_match(cos(x**2), x) == {'test': False} assert _undetermined_coefficients_match(2**(x**2), x) == {'test': False} def test_issue_12623(): t = symbols("t") u = symbols("u",cls=Function) R, L, C, E_0, alpha = symbols("R L C E_0 alpha",positive=True) omega = Symbol('omega') eqRLC_1 = Eq( u(t).diff(t,t) + R /L*u(t).diff(t) + 1/(L*C)*u(t), alpha) sol_1 = Eq(u(t), C*L*alpha + C1*exp(t*(-R - sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L)) + C2*exp(t*(-R + sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L))) assert dsolve(eqRLC_1) == sol_1 assert checkodesol(eqRLC_1, sol_1) == (True, 0) eqRLC_2 = Eq( L*C*u(t).diff(t,t) + R*C*u(t).diff(t) + u(t), E_0*exp(I*omega*t) ) sol_2 = Eq(u(t), C1*exp(t*(-R - sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L)) + C2*exp(t*(-R + sqrt(C*R**2 - 4*L)/sqrt(C))/(2*L)) + E_0*exp(I*omega*t)/(-C*L*omega**2 + I*C*R*omega + 1)) assert dsolve(eqRLC_2) == sol_2 assert checkodesol(eqRLC_2, sol_2) == (True, 0) #issue-https://github.com/sympy/sympy/issues/12623 def test_issue_5787(): # This test case is to show the classification of imaginary constants under # nth_linear_constant_coeff_undetermined_coefficients eq = Eq(diff(f(x), x), I*f(x) + S.Half - I) our_hint = 'nth_linear_constant_coeff_undetermined_coefficients' assert our_hint in classify_ode(eq) def test_nth_linear_constant_coeff_undetermined_coefficients_imaginary_exp(): # Equivalent to eq26 in # test_nth_linear_constant_coeff_undetermined_coefficients above. This # previously failed because the algorithm for undetermined coefficients # didn't know to multiply exp(I*x) by sufficient x because it is linearly # dependent on sin(x) and cos(x). hint = 'nth_linear_constant_coeff_undetermined_coefficients' eq26a = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x) sol26 = Eq(f(x), C1 + x**2*(I*exp(I*x)/8 + 1) + (C2 + C3*x)*sin(x) + (C4 + C5*x)*cos(x)) assert dsolve(eq26a, hint=hint) == sol26 assert checkodesol(eq26a, sol26) == (True, 0) @slow def test_nth_linear_constant_coeff_variation_of_parameters(): hint = 'nth_linear_constant_coeff_variation_of_parameters' g = exp(-x) f2 = f(x).diff(x, 2) c = 3*f(x).diff(x, 3) + 5*f2 + f(x).diff(x) - f(x) - x eq1 = c - x*g eq2 = c - g eq3 = f(x).diff(x) - 1 eq4 = f2 + 3*f(x).diff(x) + 2*f(x) - 4 eq5 = f2 + 3*f(x).diff(x) + 2*f(x) - 12*exp(x) eq6 = f2 - 2*f(x).diff(x) - 8*f(x) - 9*x*exp(x) - 10*exp(-x) eq7 = f2 + 2*f(x).diff(x) + f(x) - x**2*exp(-x) eq8 = f2 - 3*f(x).diff(x) + 2*f(x) - x*exp(-x) eq9 = f(x).diff(x, 3) - 3*f2 + 3*f(x).diff(x) - f(x) - exp(x) eq10 = f2 + 2*f(x).diff(x) + f(x) - exp(-x)/x eq11 = f2 + f(x) - 1/sin(x)*1/cos(x) eq12 = f(x).diff(x, 4) - 1/x sol1 = Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x**2/24 - 3*x/32))*exp(-x) - 1) sol2 = Eq(f(x), C3*exp(x/3) - x + (C1 + x*(C2 - x/8))*exp(-x) - 1) sol3 = Eq(f(x), C1 + x) sol4 = Eq(f(x), 2 + C1*exp(-x) + C2*exp(-2*x)) sol5 = Eq(f(x), 2*exp(x) + C1*exp(-x) + C2*exp(-2*x)) sol6 = Eq(f(x), -x*exp(x) - 2*exp(-x) + C1*exp(-2*x) + C2*exp(4*x)) sol7 = Eq(f(x), (C1 + x*(C2 + x**3/12))*exp(-x)) sol8 = Eq(f(x), C1*exp(x) + C2*exp(2*x) + (6*x + 5)*exp(-x)/36) sol9 = Eq(f(x), (C1 + x*(C2 + x*(C3 + x/6)))*exp(x)) sol10 = Eq(f(x), (C1 + x*(C2 + log(x)))*exp(-x)) sol11 = Eq(f(x), (C1 + log(sin(x) - 1)/2 - log(sin(x) + 1)/2 )*cos(x) + (C2 + log(cos(x) - 1)/2 - log(cos(x) + 1)/2)*sin(x)) sol12 = Eq(f(x), C1 + C2*x + x**3*(C3 + log(x)/6) + C4*x**2) sol1s = constant_renumber(sol1) sol2s = constant_renumber(sol2) sol3s = constant_renumber(sol3) sol4s = constant_renumber(sol4) sol5s = constant_renumber(sol5) sol6s = constant_renumber(sol6) sol7s = constant_renumber(sol7) sol8s = constant_renumber(sol8) sol9s = constant_renumber(sol9) sol10s = constant_renumber(sol10) sol11s = constant_renumber(sol11) sol12s = constant_renumber(sol12) got = dsolve(eq1, hint=hint) assert got in (sol1, sol1s), got got = dsolve(eq2, hint=hint) assert got in (sol2, sol2s), got assert dsolve(eq3, hint=hint) in (sol3, sol3s) assert dsolve(eq4, hint=hint) in (sol4, sol4s) assert dsolve(eq5, hint=hint) in (sol5, sol5s) assert dsolve(eq6, hint=hint) in (sol6, sol6s) got = dsolve(eq7, hint=hint) assert got in (sol7, sol7s), got assert dsolve(eq8, hint=hint) in (sol8, sol8s) got = dsolve(eq9, hint=hint) assert got in (sol9, sol9s), got assert dsolve(eq10, hint=hint) in (sol10, sol10s) assert dsolve(eq11, hint=hint + '_Integral').doit() in (sol11, sol11s) assert dsolve(eq12, hint=hint) in (sol12, sol12s) assert checkodesol(eq1, sol1, order=3, solve_for_func=False)[0] assert checkodesol(eq2, sol2, order=3, solve_for_func=False)[0] assert checkodesol(eq3, sol3, order=1, solve_for_func=False)[0] assert checkodesol(eq4, sol4, order=2, solve_for_func=False)[0] assert checkodesol(eq5, sol5, order=2, solve_for_func=False)[0] assert checkodesol(eq6, sol6, order=2, solve_for_func=False)[0] assert checkodesol(eq7, sol7, order=2, solve_for_func=False)[0] assert checkodesol(eq8, sol8, order=2, solve_for_func=False)[0] assert checkodesol(eq9, sol9, order=3, solve_for_func=False)[0] assert checkodesol(eq10, sol10, order=2, solve_for_func=False)[0] assert checkodesol(eq12, sol12, order=4, solve_for_func=False)[0] @slow def test_nth_linear_constant_coeff_variation_of_parameters_simplify_False(): # solve_variation_of_parameters shouldn't attempt to simplify the # Wronskian if simplify=False. If wronskian() ever gets good enough # to simplify the result itself, this test might fail. our_hint = 'nth_linear_constant_coeff_variation_of_parameters_Integral' eq = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x) sol_simp = dsolve(eq, f(x), hint=our_hint, simplify=True) sol_nsimp = dsolve(eq, f(x), hint=our_hint, simplify=False) assert sol_simp != sol_nsimp assert checkodesol(eq, sol_simp, order=5, solve_for_func=False) == (True, 0) assert checkodesol(eq, sol_simp, order=5, solve_for_func=False) == (True, 0) def test_unexpanded_Liouville_ODE(): # This is the same as eq1 from test_Liouville_ODE() above. eq1 = diff(f(x), x)/x + diff(f(x), x, x)/2 - diff(f(x), x)**2/2 eq2 = eq1*exp(-f(x))/exp(f(x)) sol2 = Eq(f(x), C1 + log(x) - log(C2 + x)) sol2s = constant_renumber(sol2) assert dsolve(eq2) in (sol2, sol2s) assert checkodesol(eq2, sol2, order=2, solve_for_func=False)[0] def test_issue_4785(): from sympy.abc import A eq = x + A*(x + diff(f(x), x) + f(x)) + diff(f(x), x) + f(x) + 2 assert classify_ode(eq, f(x)) == ('1st_linear', 'almost_linear', '1st_power_series', 'lie_group', 'nth_linear_constant_coeff_undetermined_coefficients', 'nth_linear_constant_coeff_variation_of_parameters', '1st_linear_Integral', 'almost_linear_Integral', 'nth_linear_constant_coeff_variation_of_parameters_Integral') # issue 4864 eq = (x**2 + f(x)**2)*f(x).diff(x) - 2*x*f(x) assert classify_ode(eq, f(x)) == ('1st_exact', '1st_homogeneous_coeff_best', '1st_homogeneous_coeff_subs_indep_div_dep', '1st_homogeneous_coeff_subs_dep_div_indep', '1st_power_series', 'lie_group', '1st_exact_Integral', '1st_homogeneous_coeff_subs_indep_div_dep_Integral', '1st_homogeneous_coeff_subs_dep_div_indep_Integral') def test_issue_4825(): raises(ValueError, lambda: dsolve(f(x, y).diff(x) - y*f(x, y), f(x))) assert classify_ode(f(x, y).diff(x) - y*f(x, y), f(x), dict=True) == \ {'order': 0, 'default': None, 'ordered_hints': ()} # See also issue 3793, test Z13. raises(ValueError, lambda: dsolve(f(x).diff(x), f(y))) assert classify_ode(f(x).diff(x), f(y), dict=True) == \ {'order': 0, 'default': None, 'ordered_hints': ()} def test_constant_renumber_order_issue_5308(): from sympy.utilities.iterables import variations assert constant_renumber(C1*x + C2*y) == \ constant_renumber(C1*y + C2*x) == \ C1*x + C2*y e = C1*(C2 + x)*(C3 + y) for a, b, c in variations([C1, C2, C3], 3): assert constant_renumber(a*(b + x)*(c + y)) == e def test_constant_renumber(): e1, e2, x, y = symbols("e1:3 x y") exprs = [e2*x, e1*x + e2*y] assert constant_renumber(exprs[0]) == e2*x assert constant_renumber(exprs[0], variables=[x]) == C1*x assert constant_renumber(exprs[0], variables=[x], newconstants=[C2]) == C2*x assert constant_renumber(exprs, variables=[x, y]) == [C1*x, C1*y + C2*x] assert constant_renumber(exprs, variables=[x, y], newconstants=symbols("C3:5")) == [C3*x, C3*y + C4*x] def test_issue_5770(): k = Symbol("k", real=True) t = Symbol('t') w = Function('w') sol = dsolve(w(t).diff(t, 6) - k**6*w(t), w(t)) assert len([s for s in sol.free_symbols if s.name.startswith('C')]) == 6 assert constantsimp((C1*cos(x) + C2*cos(x))*exp(x), set([C1, C2])) == \ C1*cos(x)*exp(x) assert constantsimp(C1*cos(x) + C2*cos(x) + C3*sin(x), set([C1, C2, C3])) == \ C1*cos(x) + C3*sin(x) assert constantsimp(exp(C1 + x), set([C1])) == C1*exp(x) assert constantsimp(x + C1 + y, set([C1, y])) == C1 + x assert constantsimp(x + C1 + Integral(x, (x, 1, 2)), set([C1])) == C1 + x def test_issue_5112_5430(): assert homogeneous_order(-log(x) + acosh(x), x) is None assert homogeneous_order(y - log(x), x, y) is None def test_issue_5095(): f = Function('f') raises(ValueError, lambda: dsolve(f(x).diff(x)**2, f(x), 'fdsjf')) def test_exact_enhancement(): f = Function('f')(x) df = Derivative(f, x) eq = f/x**2 + ((f*x - 1)/x)*df sol = [Eq(f, (i*sqrt(C1*x**2 + 1) + 1)/x) for i in (-1, 1)] assert set(dsolve(eq, f)) == set(sol) assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0), (True, 0)] eq = (x*f - 1) + df*(x**2 - x*f) sol = [Eq(f, x - sqrt(C1 + x**2 - 2*log(x))), Eq(f, x + sqrt(C1 + x**2 - 2*log(x)))] assert set(dsolve(eq, f)) == set(sol) assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0), (True, 0)] eq = (x + 2)*sin(f) + df*x*cos(f) sol = [Eq(f, -asin(C1*exp(-x)/x**2) + pi), Eq(f, asin(C1*exp(-x)/x**2))] assert set(dsolve(eq, f)) == set(sol) assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0), (True, 0)] @slow def test_separable_reduced(): f = Function('f') x = Symbol('x') df = f(x).diff(x) eq = (x / f(x))*df + tan(x**2*f(x) / (x**2*f(x) - 1)) assert classify_ode(eq) == ('separable_reduced', 'lie_group', 'separable_reduced_Integral') eq = x* df + f(x)* (1 / (x**2*f(x) - 1)) assert classify_ode(eq) == ('separable_reduced', 'lie_group', 'separable_reduced_Integral') sol = dsolve(eq, hint = 'separable_reduced', simplify=False) assert sol.lhs == log(x**2*f(x))/3 + log(x**2*f(x) - Rational(3, 2))/6 assert sol.rhs == C1 + log(x) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] eq = f(x).diff(x) + (f(x) / (x**4*f(x) - x)) assert classify_ode(eq) == ('separable_reduced', 'lie_group', 'separable_reduced_Integral') sol = dsolve(eq, hint = 'separable_reduced') # FIXME: This one hangs #assert checkodesol(eq, sol, order=1, solve_for_func=False) == [(True, 0)] * 4 assert len(sol) == 4 eq = x*df + f(x)*(x**2*f(x)) sol = dsolve(eq, hint = 'separable_reduced', simplify=False) assert sol == Eq(log(x**2*f(x))/2 - log(x**2*f(x) - 2)/2, C1 + log(x)) assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] eq = Eq(f(x).diff(x) + f(x)/x * (1 + (x**(S(2)/3)*f(x))**2), 0) sol = dsolve(eq, hint = 'separable_reduced', simplify=False) assert sol == Eq(-3*log(x**(S(2)/3)*f(x)) + 3*log(3*x**(S(4)/3)*f(x)**2 + 1)/2, C1 + log(x)) assert checkodesol(eq, sol, solve_for_func=False) == (True, 0) eq = Eq(f(x).diff(x) + f(x)/x * (1 + (x*f(x))**2), 0) sol = dsolve(eq, hint = 'separable_reduced') assert sol == [Eq(f(x), -sqrt(2)*sqrt(1/(C1 + log(x)))/(2*x)),\ Eq(f(x), sqrt(2)*sqrt(1/(C1 + log(x)))/(2*x))] assert checkodesol(eq, sol) == [(True, 0)]*2 eq = Eq(f(x).diff(x) + (x**4*f(x)**2 + x**2*f(x))*f(x)/(x*(x**6*f(x)**3 + x**4*f(x)**2)), 0) sol = dsolve(eq, hint = 'separable_reduced') assert sol == Eq(f(x), C1 + 1/(2*x**2)) assert checkodesol(eq, sol) == (True, 0) eq = Eq(f(x).diff(x) + (f(x)**2)*f(x)/(x), 0) sol = dsolve(eq, hint = 'separable_reduced') assert sol == [Eq(f(x), -sqrt(2)*sqrt(1/(C1 + log(x)))/2),\ Eq(f(x), sqrt(2)*sqrt(1/(C1 + log(x)))/2)] assert checkodesol(eq, sol) == [(True, 0), (True, 0)] eq = Eq(f(x).diff(x) + (f(x)+3)*f(x)/(x*(f(x)+2)), 0) sol = dsolve(eq, hint = 'separable_reduced', simplify=False) assert sol == Eq(-log(f(x) + 3)/3 - 2*log(f(x))/3, C1 + log(x)) assert checkodesol(eq, sol, solve_for_func=False) == (True, 0) eq = Eq(f(x).diff(x) + (f(x)+3)*f(x)/x, 0) sol = dsolve(eq, hint = 'separable_reduced') assert sol == Eq(f(x), 3/(C1*x**3 - 1)) assert checkodesol(eq, sol) == (True, 0) eq = Eq(f(x).diff(x) + (f(x)**2+f(x))*f(x)/(x), 0) sol = dsolve(eq, hint='separable_reduced', simplify=False) assert sol == Eq(-log(f(x) + 1) + log(f(x)) + 1/f(x), C1 + log(x)) assert checkodesol(eq, sol, solve_for_func=False) == (True, 0) def test_homogeneous_function(): f = Function('f') eq1 = tan(x + f(x)) eq2 = sin((3*x)/(4*f(x))) eq3 = cos(x*f(x)*Rational(3, 4)) eq4 = log((3*x + 4*f(x))/(5*f(x) + 7*x)) eq5 = exp((2*x**2)/(3*f(x)**2)) eq6 = log((3*x + 4*f(x))/(5*f(x) + 7*x) + exp((2*x**2)/(3*f(x)**2))) eq7 = sin((3*x)/(5*f(x) + x**2)) assert homogeneous_order(eq1, x, f(x)) == None assert homogeneous_order(eq2, x, f(x)) == 0 assert homogeneous_order(eq3, x, f(x)) == None assert homogeneous_order(eq4, x, f(x)) == 0 assert homogeneous_order(eq5, x, f(x)) == 0 assert homogeneous_order(eq6, x, f(x)) == 0 assert homogeneous_order(eq7, x, f(x)) == None def test_linear_coeff_match(): n, d = z*(2*x + 3*f(x) + 5), z*(7*x + 9*f(x) + 11) rat = n/d eq1 = sin(rat) + cos(rat.expand()) eq2 = rat eq3 = log(sin(rat)) ans = (4, Rational(-13, 3)) assert _linear_coeff_match(eq1, f(x)) == ans assert _linear_coeff_match(eq2, f(x)) == ans assert _linear_coeff_match(eq3, f(x)) == ans # no c eq4 = (3*x)/f(x) # not x and f(x) eq5 = (3*x + 2)/x # denom will be zero eq6 = (3*x + 2*f(x) + 1)/(3*x + 2*f(x) + 5) # not rational coefficient eq7 = (3*x + 2*f(x) + sqrt(2))/(3*x + 2*f(x) + 5) assert _linear_coeff_match(eq4, f(x)) is None assert _linear_coeff_match(eq5, f(x)) is None assert _linear_coeff_match(eq6, f(x)) is None assert _linear_coeff_match(eq7, f(x)) is None def test_linear_coefficients(): f = Function('f') sol = Eq(f(x), C1/(x**2 + 6*x + 9) - Rational(3, 2)) eq = f(x).diff(x) + (3 + 2*f(x))/(x + 3) assert dsolve(eq, hint='linear_coefficients') == sol assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_constantsimp_take_problem(): c = exp(C1) + 2 assert len(Poly(constantsimp(exp(C1) + c + c*x, [C1])).gens) == 2 def test_issue_6879(): f = Function('f') eq = Eq(Derivative(f(x), x, 2) - 2*Derivative(f(x), x) + f(x), sin(x)) sol = (C1 + C2*x)*exp(x) + cos(x)/2 assert dsolve(eq).rhs == sol assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_issue_6989(): f = Function('f') k = Symbol('k') eq = f(x).diff(x) - x*exp(-k*x) csol = Eq(f(x), C1 + Piecewise( ((-k*x - 1)*exp(-k*x)/k**2, Ne(k**2, 0)), (x**2/2, True) )) sol = dsolve(eq, f(x)) assert sol == csol assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] eq = -f(x).diff(x) + x*exp(-k*x) csol = Eq(f(x), C1 + Piecewise( ((-k*x - 1)*exp(-k*x)/k**2, Ne(k**2, 0)), (x**2/2, True) )) sol = dsolve(eq, f(x)) assert sol == csol assert checkodesol(eq, sol, order=1, solve_for_func=False)[0] def test_heuristic1(): y, a, b, c, a4, a3, a2, a1, a0 = symbols("y a b c a4 a3 a2 a1 a0") f = Function('f') xi = Function('xi') eta = Function('eta') df = f(x).diff(x) eq = Eq(df, x**2*f(x)) eq1 = f(x).diff(x) + a*f(x) - c*exp(b*x) eq2 = f(x).diff(x) + 2*x*f(x) - x*exp(-x**2) eq3 = (1 + 2*x)*df + 2 - 4*exp(-f(x)) eq4 = f(x).diff(x) - (a4*x**4 + a3*x**3 + a2*x**2 + a1*x + a0)**Rational(-1, 2) eq5 = x**2*df - f(x) + x**2*exp(x - (1/x)) eqlist = [eq, eq1, eq2, eq3, eq4, eq5] i = infinitesimals(eq, hint='abaco1_simple') assert i == [{eta(x, f(x)): exp(x**3/3), xi(x, f(x)): 0}, {eta(x, f(x)): f(x), xi(x, f(x)): 0}, {eta(x, f(x)): 0, xi(x, f(x)): x**(-2)}] i1 = infinitesimals(eq1, hint='abaco1_simple') assert i1 == [{eta(x, f(x)): exp(-a*x), xi(x, f(x)): 0}] i2 = infinitesimals(eq2, hint='abaco1_simple') assert i2 == [{eta(x, f(x)): exp(-x**2), xi(x, f(x)): 0}] i3 = infinitesimals(eq3, hint='abaco1_simple') assert i3 == [{eta(x, f(x)): 0, xi(x, f(x)): 2*x + 1}, {eta(x, f(x)): 0, xi(x, f(x)): 1/(exp(f(x)) - 2)}] i4 = infinitesimals(eq4, hint='abaco1_simple') assert i4 == [{eta(x, f(x)): 1, xi(x, f(x)): 0}, {eta(x, f(x)): 0, xi(x, f(x)): sqrt(a0 + a1*x + a2*x**2 + a3*x**3 + a4*x**4)}] i5 = infinitesimals(eq5, hint='abaco1_simple') assert i5 == [{xi(x, f(x)): 0, eta(x, f(x)): exp(-1/x)}] ilist = [i, i1, i2, i3, i4, i5] for eq, i in (zip(eqlist, ilist)): check = checkinfsol(eq, i) assert check[0] def test_issue_6247(): eq = x**2*f(x)**2 + x*Derivative(f(x), x) sol = Eq(f(x), 2*C1/(C1*x**2 - 1)) assert dsolve(eq, hint = 'separable_reduced') == sol assert checkodesol(eq, sol, order=1)[0] eq = f(x).diff(x, x) + 4*f(x) sol = Eq(f(x), C1*sin(2*x) + C2*cos(2*x)) assert dsolve(eq) == sol assert checkodesol(eq, sol, order=1)[0] def test_heuristic2(): xi = Function('xi') eta = Function('eta') df = f(x).diff(x) # This ODE can be solved by the Lie Group method, when there are # better assumptions eq = df - (f(x)/x)*(x*log(x**2/f(x)) + 2) i = infinitesimals(eq, hint='abaco1_product') assert i == [{eta(x, f(x)): f(x)*exp(-x), xi(x, f(x)): 0}] assert checkinfsol(eq, i)[0] @slow def test_heuristic3(): xi = Function('xi') eta = Function('eta') a, b = symbols("a b") df = f(x).diff(x) eq = x**2*df + x*f(x) + f(x)**2 + x**2 i = infinitesimals(eq, hint='bivariate') assert i == [{eta(x, f(x)): f(x), xi(x, f(x)): x}] assert checkinfsol(eq, i)[0] eq = x**2*(-f(x)**2 + df)- a*x**2*f(x) + 2 - a*x i = infinitesimals(eq, hint='bivariate') assert checkinfsol(eq, i)[0] def test_heuristic_4(): y, a = symbols("y a") eq = x*(f(x).diff(x)) + 1 - f(x)**2 i = infinitesimals(eq, hint='chi') assert checkinfsol(eq, i)[0] def test_heuristic_function_sum(): xi = Function('xi') eta = Function('eta') eq = f(x).diff(x) - (3*(1 + x**2/f(x)**2)*atan(f(x)/x) + (1 - 2*f(x))/x + (1 - 3*f(x))*(x/f(x)**2)) i = infinitesimals(eq, hint='function_sum') assert i == [{eta(x, f(x)): f(x)**(-2) + x**(-2), xi(x, f(x)): 0}] assert checkinfsol(eq, i)[0] def test_heuristic_abaco2_similar(): xi = Function('xi') eta = Function('eta') F = Function('F') a, b = symbols("a b") eq = f(x).diff(x) - F(a*x + b*f(x)) i = infinitesimals(eq, hint='abaco2_similar') assert i == [{eta(x, f(x)): -a/b, xi(x, f(x)): 1}] assert checkinfsol(eq, i)[0] eq = f(x).diff(x) - (f(x)**2 / (sin(f(x) - x) - x**2 + 2*x*f(x))) i = infinitesimals(eq, hint='abaco2_similar') assert i == [{eta(x, f(x)): f(x)**2, xi(x, f(x)): f(x)**2}] assert checkinfsol(eq, i)[0] def test_heuristic_abaco2_unique_unknown(): xi = Function('xi') eta = Function('eta') F = Function('F') a, b = symbols("a b") x = Symbol("x", positive=True) eq = f(x).diff(x) - x**(a - 1)*(f(x)**(1 - b))*F(x**a/a + f(x)**b/b) i = infinitesimals(eq, hint='abaco2_unique_unknown') assert i == [{eta(x, f(x)): -f(x)*f(x)**(-b), xi(x, f(x)): x*x**(-a)}] assert checkinfsol(eq, i)[0] eq = f(x).diff(x) + tan(F(x**2 + f(x)**2) + atan(x/f(x))) i = infinitesimals(eq, hint='abaco2_unique_unknown') assert i == [{eta(x, f(x)): x, xi(x, f(x)): -f(x)}] assert checkinfsol(eq, i)[0] eq = (x*f(x).diff(x) + f(x) + 2*x)**2 -4*x*f(x) -4*x**2 -4*a i = infinitesimals(eq, hint='abaco2_unique_unknown') assert checkinfsol(eq, i)[0] def test_heuristic_linear(): a, b, m, n = symbols("a b m n") eq = x**(n*(m + 1) - m)*(f(x).diff(x)) - a*f(x)**n -b*x**(n*(m + 1)) i = infinitesimals(eq, hint='linear') assert checkinfsol(eq, i)[0] @XFAIL def test_kamke(): a, b, alpha, c = symbols("a b alpha c") eq = x**2*(a*f(x)**2+(f(x).diff(x))) + b*x**alpha + c i = infinitesimals(eq, hint='sum_function') # XFAIL assert checkinfsol(eq, i)[0] def test_series(): C1 = Symbol("C1") eq = f(x).diff(x) - f(x) sol = Eq(f(x), C1 + C1*x + C1*x**2/2 + C1*x**3/6 + C1*x**4/24 + C1*x**5/120 + O(x**6)) assert dsolve(eq, hint='1st_power_series') == sol assert checkodesol(eq, sol, order=1)[0] eq = f(x).diff(x) - x*f(x) sol = Eq(f(x), C1*x**4/8 + C1*x**2/2 + C1 + O(x**6)) assert dsolve(eq, hint='1st_power_series') == sol assert checkodesol(eq, sol, order=1)[0] eq = f(x).diff(x) - sin(x*f(x)) sol = Eq(f(x), (x - 2)**2*(1+ sin(4))*cos(4) + (x - 2)*sin(4) + 2 + O(x**3)) assert dsolve(eq, hint='1st_power_series', ics={f(2): 2}, n=3) == sol # FIXME: The solution here should be O((x-2)**3) so is incorrect #assert checkodesol(eq, sol, order=1)[0] @XFAIL @SKIP def test_lie_group_issue17322_1(): eq=x*f(x).diff(x)*(f(x)+4) + (f(x)**2) -2*f(x)-2*x sol = dsolve(eq, f(x)) # Hangs assert checkodesol(eq, sol) == (True, 0) @XFAIL @SKIP def test_lie_group_issue17322_2(): eq=x*f(x).diff(x)*(f(x)+4) + (f(x)**2) -2*f(x)-2*x sol = dsolve(eq) # Hangs assert checkodesol(eq, sol) == (True, 0) @XFAIL @SKIP def test_lie_group_issue17322_3(): eq=Eq(x**7*Derivative(f(x), x) + 5*x**3*f(x)**2 - (2*x**2 + 2)*f(x)**3, 0) sol = dsolve(eq) # Hangs assert checkodesol(eq, sol) == (True, 0) @XFAIL def test_lie_group_issue17322_4(): eq=f(x).diff(x) - (f(x) - x*log(x))**2/x**2 + log(x) sol = dsolve(eq) # NotImplementedError assert checkodesol(eq, sol) == (True, 0) @slow def test_lie_group(): C1 = Symbol("C1") x = Symbol("x") # assuming x is real generates an error! a, b, c = symbols("a b c") eq = f(x).diff(x)**2 sol = dsolve(eq, f(x), hint='lie_group') assert checkodesol(eq, sol) == (True, 0) eq = Eq(f(x).diff(x), x**2*f(x)) sol = dsolve(eq, f(x), hint='lie_group') assert sol == Eq(f(x), C1*exp(x**3)**Rational(1, 3)) assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x) + a*f(x) - c*exp(b*x) sol = dsolve(eq, f(x), hint='lie_group') assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x) + 2*x*f(x) - x*exp(-x**2) sol = dsolve(eq, f(x), hint='lie_group') actual_sol = Eq(f(x), (C1 + x**2/2)*exp(-x**2)) errstr = str(eq)+' : '+str(sol)+' == '+str(actual_sol) assert sol == actual_sol, errstr assert checkodesol(eq, sol) == (True, 0) eq = (1 + 2*x)*(f(x).diff(x)) + 2 - 4*exp(-f(x)) sol = dsolve(eq, f(x), hint='lie_group') assert sol == Eq(f(x), log(C1/(2*x + 1) + 2)) assert checkodesol(eq, sol) == (True, 0) eq = x**2*(f(x).diff(x)) - f(x) + x**2*exp(x - (1/x)) sol = dsolve(eq, f(x), hint='lie_group') assert checkodesol(eq, sol)[0] eq = x**2*f(x)**2 + x*Derivative(f(x), x) sol = dsolve(eq, f(x), hint='lie_group') assert sol == Eq(f(x), 2/(C1 + x**2)) assert checkodesol(eq, sol) == (True, 0) eq=diff(f(x),x) + 2*x*f(x) - x*exp(-x**2) sol = Eq(f(x), exp(-x**2)*(C1 + x**2/2)) assert sol == dsolve(eq, hint='lie_group') assert checkodesol(eq, sol) == (True, 0) eq = diff(f(x),x) + f(x)*cos(x) - exp(2*x) sol = Eq(f(x), exp(-sin(x))*(C1 + Integral(exp(2*x)*exp(sin(x)), x))) assert sol == dsolve(eq, hint='lie_group') assert checkodesol(eq, sol) == (True, 0) eq = diff(f(x),x) + f(x)*cos(x) - sin(2*x)/2 sol = Eq(f(x), C1*exp(-sin(x)) + sin(x) - 1) assert sol == dsolve(eq, hint='lie_group') assert checkodesol(eq, sol) == (True, 0) eq = x*diff(f(x),x) + f(x) - x*sin(x) sol = Eq(f(x), (C1 - x*cos(x) + sin(x))/x) assert sol == dsolve(eq, hint='lie_group') assert checkodesol(eq, sol) == (True, 0) eq = x*diff(f(x),x) - f(x) - x/log(x) sol = Eq(f(x), x*(C1 + log(log(x)))) assert sol == dsolve(eq, hint='lie_group') assert checkodesol(eq, sol) == (True, 0) eq = (f(x).diff(x)-f(x)) * (f(x).diff(x)+f(x)) sol = [Eq(f(x), C1*exp(x)), Eq(f(x), C1*exp(-x))] assert set(sol) == set(dsolve(eq, hint='lie_group')) assert checkodesol(eq, sol[0]) == (True, 0) assert checkodesol(eq, sol[1]) == (True, 0) eq = f(x).diff(x) * (f(x).diff(x) - f(x)) sol = [Eq(f(x), C1*exp(x)), Eq(f(x), C1)] assert set(sol) == set(dsolve(eq, hint='lie_group')) assert checkodesol(eq, sol[0]) == (True, 0) assert checkodesol(eq, sol[1]) == (True, 0) @XFAIL def test_lie_group_issue15219(): eqn = exp(f(x).diff(x)-f(x)) assert 'lie_group' not in classify_ode(eqn, f(x)) def test_user_infinitesimals(): x = Symbol("x") # assuming x is real generates an error eq = x*(f(x).diff(x)) + 1 - f(x)**2 sol = Eq(f(x), (C1 + x**2)/(C1 - x**2)) infinitesimals = {'xi':sqrt(f(x) - 1)/sqrt(f(x) + 1), 'eta':0} assert dsolve(eq, hint='lie_group', **infinitesimals) == sol assert checkodesol(eq, sol) == (True, 0) def test_issue_7081(): eq = x*(f(x).diff(x)) + 1 - f(x)**2 s = Eq(f(x), -1/(-C1 + x**2)*(C1 + x**2)) assert dsolve(eq) == s assert checkodesol(eq, s) == (True, 0) @slow def test_2nd_power_series_ordinary(): C1, C2 = symbols("C1 C2") eq = f(x).diff(x, 2) - x*f(x) assert classify_ode(eq) == ('2nd_linear_airy', '2nd_power_series_ordinary') sol = Eq(f(x), C2*(x**3/6 + 1) + C1*x*(x**3/12 + 1) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_ordinary') == sol assert checkodesol(eq, sol) == (True, 0) sol = Eq(f(x), C2*((x + 2)**4/6 + (x + 2)**3/6 - (x + 2)**2 + 1) + C1*(x + (x + 2)**4/12 - (x + 2)**3/3 + S(2)) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_ordinary', x0=-2) == sol # FIXME: Solution should be O((x+2)**6) # assert checkodesol(eq, sol) == (True, 0) sol = Eq(f(x), C2*x + C1 + O(x**2)) assert dsolve(eq, hint='2nd_power_series_ordinary', n=2) == sol assert checkodesol(eq, sol) == (True, 0) eq = (1 + x**2)*(f(x).diff(x, 2)) + 2*x*(f(x).diff(x)) -2*f(x) assert classify_ode(eq) == ('2nd_power_series_ordinary',) sol = Eq(f(x), C2*(-x**4/3 + x**2 + 1) + C1*x + O(x**6)) assert dsolve(eq) == sol assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) + x*(f(x).diff(x)) + f(x) assert classify_ode(eq) == ('2nd_power_series_ordinary',) sol = Eq(f(x), C2*(x**4/8 - x**2/2 + 1) + C1*x*(-x**2/3 + 1) + O(x**6)) assert dsolve(eq) == sol # FIXME: checkodesol fails for this solution... # assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) + f(x).diff(x) - x*f(x) assert classify_ode(eq) == ('2nd_power_series_ordinary',) sol = Eq(f(x), C2*(-x**4/24 + x**3/6 + 1) + C1*x*(x**3/24 + x**2/6 - x/2 + 1) + O(x**6)) assert dsolve(eq) == sol # FIXME: checkodesol fails for this solution... # assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) + x*f(x) assert classify_ode(eq) == ('2nd_linear_airy', '2nd_power_series_ordinary') sol = Eq(f(x), C2*(x**6/180 - x**3/6 + 1) + C1*x*(-x**3/12 + 1) + O(x**7)) assert dsolve(eq, hint='2nd_power_series_ordinary', n=7) == sol assert checkodesol(eq, sol) == (True, 0) def test_Airy_equation(): eq = f(x).diff(x, 2) - x*f(x) sol = Eq(f(x), C1*airyai(x) + C2*airybi(x)) sols = constant_renumber(sol) assert classify_ode(eq) == ("2nd_linear_airy",'2nd_power_series_ordinary') assert checkodesol(eq, sol) == (True, 0) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_airy') in (sol, sols) eq = f(x).diff(x, 2) + 2*x*f(x) sol = Eq(f(x), C1*airyai(-2**(S(1)/3)*x) + C2*airybi(-2**(S(1)/3)*x)) sols = constant_renumber(sol) assert classify_ode(eq) == ("2nd_linear_airy",'2nd_power_series_ordinary') assert checkodesol(eq, sol) == (True, 0) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_airy') in (sol, sols) def test_2nd_power_series_regular(): C1, C2 = symbols("C1 C2") eq = x**2*(f(x).diff(x, 2)) - 3*x*(f(x).diff(x)) + (4*x + 4)*f(x) sol = Eq(f(x), C1*x**2*(-16*x**3/9 + 4*x**2 - 4*x + 1) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_regular') == sol assert checkodesol(eq, sol) == (True, 0) eq = 4*x**2*(f(x).diff(x, 2)) -8*x**2*(f(x).diff(x)) + (4*x**2 + 1)*f(x) sol = Eq(f(x), C1*sqrt(x)*(x**4/24 + x**3/6 + x**2/2 + x + 1) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_regular') == sol assert checkodesol(eq, sol) == (True, 0) eq = x**2*(f(x).diff(x, 2)) - x**2*(f(x).diff(x)) + ( x**2 - 2)*f(x) sol = Eq(f(x), C1*(-x**6/720 - 3*x**5/80 - x**4/8 + x**2/2 + x/2 + 1)/x + C2*x**2*(-x**3/60 + x**2/20 + x/2 + 1) + O(x**6)) assert dsolve(eq) == sol assert checkodesol(eq, sol) == (True, 0) eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - Rational(1, 4))*f(x) sol = Eq(f(x), C1*(x**4/24 - x**2/2 + 1)/sqrt(x) + C2*sqrt(x)*(x**4/120 - x**2/6 + 1) + O(x**6)) assert dsolve(eq, hint='2nd_power_series_regular') == sol assert checkodesol(eq, sol) == (True, 0) def test_2nd_linear_bessel_equation(): eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - 4)*f(x) sol = Eq(f(x), C1*besselj(2, x) + C2*bessely(2, x)) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 +25)*f(x) sol = Eq(f(x), C1*besselj(5*I, x) + C2*bessely(5*I, x)) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2)*f(x) sol = Eq(f(x), C1*besselj(0, x) + C2*bessely(0, x)) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (81*x**2 -S(1)/9)*f(x) sol = Eq(f(x), C1*besselj(S(1)/3, 9*x) + C2*bessely(S(1)/3, 9*x)) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**4 - 4)*f(x) sol = Eq(f(x), C1*besselj(1, x**2/2) + C2*bessely(1, x**2/2)) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = x**2*(f(x).diff(x, 2)) + 2*x*(f(x).diff(x)) + (x**4 - 4)*f(x) sol = Eq(f(x), (C1*besselj(sqrt(17)/4, x**2/2) + C2*bessely(sqrt(17)/4, x**2/2))/sqrt(x)) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = x**2*(f(x).diff(x, 2)) + x*(f(x).diff(x)) + (x**2 - S(1)/4)*f(x) sol = Eq(f(x), C1*besselj(S(1)/2, x) + C2*bessely(S(1)/2, x)) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = x**2*(f(x).diff(x, 2)) - 3*x*(f(x).diff(x)) + (4*x + 4)*f(x) sol = Eq(f(x), x**2*(C1*besselj(0, 4*sqrt(x)) + C2*bessely(0, 4*sqrt(x)))) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = x*(f(x).diff(x, 2)) - f(x).diff(x) + 4*x**3*f(x) sol = Eq(f(x), x*(C1*besselj(S(1)/2, x**2) + C2*bessely(S(1)/2, x**2))) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) eq = (x-2)**2*(f(x).diff(x, 2)) - (x-2)*f(x).diff(x) + 4*(x-2)**2*f(x) sol = Eq(f(x), (x - 2)*(C1*besselj(1, 2*x - 4) + C2*bessely(1, 2*x - 4))) sols = constant_renumber(sol) assert dsolve(eq, f(x)) in (sol, sols) assert dsolve(eq, f(x), hint='2nd_linear_bessel') in (sol, sols) assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) def test_issue_7093(): x = Symbol("x") # assuming x is real leads to an error sol = [Eq(f(x), C1 - 2*x*sqrt(x**3)/5), Eq(f(x), C1 + 2*x*sqrt(x**3)/5)] eq = Derivative(f(x), x)**2 - x**3 assert set(dsolve(eq)) == set(sol) assert checkodesol(eq, sol) == [(True, 0)] * 2 def test_dsolve_linsystem_symbol(): eps = Symbol('epsilon', positive=True) eq1 = (Eq(diff(f(x), x), -eps*g(x)), Eq(diff(g(x), x), eps*f(x))) sol1 = [Eq(f(x), -C1*eps*cos(eps*x) - C2*eps*sin(eps*x)), Eq(g(x), -C1*eps*sin(eps*x) + C2*eps*cos(eps*x))] assert checksysodesol(eq1, sol1) == (True, [0, 0]) def test_C1_function_9239(): t = Symbol('t') C1 = Function('C1') C2 = Function('C2') C3 = Symbol('C3') C4 = Symbol('C4') eq = (Eq(diff(C1(t), t), 9*C2(t)), Eq(diff(C2(t), t), 12*C1(t))) sol = [Eq(C1(t), 9*C3*exp(6*sqrt(3)*t) + 9*C4*exp(-6*sqrt(3)*t)), Eq(C2(t), 6*sqrt(3)*C3*exp(6*sqrt(3)*t) - 6*sqrt(3)*C4*exp(-6*sqrt(3)*t))] assert checksysodesol(eq, sol) == (True, [0, 0]) def test_issue_15056(): t = Symbol('t') C3 = Symbol('C3') assert get_numbered_constants(Symbol('C1') * Function('C2')(t)) == C3 def test_issue_10379(): t,y = symbols('t,y') eq = f(t).diff(t)-(1-51.05*y*f(t)) sol = Eq(f(t), (0.019588638589618*exp(y*(C1 - 51.05*t)) + 0.019588638589618)/y) dsolve_sol = dsolve(eq, rational=False) assert str(dsolve_sol) == str(sol) assert checkodesol(eq, dsolve_sol)[0] def test_issue_10867(): x = Symbol('x') eq = Eq(g(x).diff(x).diff(x), (x-2)**2 + (x-3)**3) sol = Eq(g(x), C1 + C2*x + x**5/20 - 2*x**4/3 + 23*x**3/6 - 23*x**2/2) assert dsolve(eq, g(x)) == sol assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) def test_issue_11290(): eq = cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x) sol_1 = dsolve(eq, f(x), simplify=False, hint='1st_exact_Integral') sol_0 = dsolve(eq, f(x), simplify=False, hint='1st_exact') assert sol_1.dummy_eq(Eq(Subs( Integral(u**2 - x*sin(u) - Integral(-sin(u), x), u) + Integral(cos(u), x), u, f(x)), C1)) assert sol_1.doit() == sol_0 assert checkodesol(eq, sol_0, order=1, solve_for_func=False) assert checkodesol(eq, sol_1, order=1, solve_for_func=False) def test_issue_4838(): # Issue #15999 eq = f(x).diff(x) - C1*f(x) sol = Eq(f(x), C2*exp(C1*x)) assert dsolve(eq, f(x)) == sol assert checkodesol(eq, sol, order=1, solve_for_func=False) == (True, 0) # Issue #13691 eq = f(x).diff(x) - C1*g(x).diff(x) sol = Eq(f(x), C2 + C1*g(x)) assert dsolve(eq, f(x)) == sol assert checkodesol(eq, sol, f(x), order=1, solve_for_func=False) == (True, 0) # Issue #4838 eq = f(x).diff(x) - 3*C1 - 3*x**2 sol = Eq(f(x), C2 + 3*C1*x + x**3) assert dsolve(eq, f(x)) == sol assert checkodesol(eq, sol, order=1, solve_for_func=False) == (True, 0) @slow def test_issue_14395(): eq = Derivative(f(x), x, x) + 9*f(x) - sec(x) sol = Eq(f(x), (C1 - x/3 + sin(2*x)/3)*sin(3*x) + (C2 + log(cos(x)) - 2*log(cos(x)**2)/3 + 2*cos(x)**2/3)*cos(3*x)) assert dsolve(eq, f(x)) == sol # FIXME: assert checkodesol(eq, sol, order=2, solve_for_func=False) == (True, 0) # Needs to be a way to know how to combine derivatives in the expression def test_factoring_ode(): from sympy import Mul eqn = Derivative(x*f(x), x, x, x) + Derivative(f(x), x, x, x) # 2-arg Mul! soln = Eq(f(x), C1 + C2*x + C3/Mul(2, (x + 1), evaluate=False)) assert checkodesol(eqn, soln, order=2, solve_for_func=False)[0] assert soln == dsolve(eqn, f(x)) def test_issue_11542(): m = 96 g = 9.8 k = .2 f1 = g * m t = Symbol('t') v = Function('v') v_equation = dsolve(f1 - k * (v(t) ** 2) - m * Derivative(v(t)), 0) assert str(v_equation) == \ 'Eq(v(t), -68.585712797929/tanh(C1 - 0.142886901662352*t))' def test_issue_15913(): eq = -C1/x - 2*x*f(x) - f(x) + Derivative(f(x), x) sol = C2*exp(x**2 + x) + exp(x**2 + x)*Integral(C1*exp(-x**2 - x)/x, x) assert checkodesol(eq, sol) == (True, 0) sol = C1 + C2*exp(-x*y) eq = Derivative(y*f(x), x) + f(x).diff(x, 2) assert checkodesol(eq, sol, f(x)) == (True, 0) def test_issue_16146(): raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x), g(x), h(x)])) raises(ValueError, lambda: dsolve([f(x).diff(x), g(x).diff(x)], [f(x)])) def test_dsolve_remove_redundant_solutions(): eq = (f(x)-2)*f(x).diff(x) sol = Eq(f(x), C1) assert dsolve(eq) == sol eq = (f(x)-sin(x))*(f(x).diff(x, 2)) sol = {Eq(f(x), C1 + C2*x), Eq(f(x), sin(x))} assert set(dsolve(eq)) == sol eq = (f(x)**2-2*f(x)+1)*f(x).diff(x, 3) sol = Eq(f(x), C1 + C2*x + C3*x**2) assert dsolve(eq) == sol def test_issue_17322(): eq = (f(x).diff(x)-f(x)) * (f(x).diff(x)+f(x)) sol = [Eq(f(x), C1*exp(-x)), Eq(f(x), C1*exp(x))] assert set(sol) == set(dsolve(eq, hint='lie_group')) assert checkodesol(eq, sol) == 2*[(True, 0)] eq = f(x).diff(x)*(f(x).diff(x)+f(x)) sol = [Eq(f(x), C1), Eq(f(x), C1*exp(-x))] assert set(sol) == set(dsolve(eq, hint='lie_group')) assert checkodesol(eq, sol) == 2*[(True, 0)] def test_2nd_2F1_hypergeometric(): eq = x*(x-1)*f(x).diff(x, 2) + (S(3)/2 -2*x)*f(x).diff(x) + 2*f(x) sol = Eq(f(x), C1*x**(S(5)/2)*hyper((S(3)/2, S(1)/2), (S(7)/2,), x) + C2*hyper((-1, -2), (-S(3)/2,), x)) assert sol == dsolve(eq, hint='2nd_hypergeometric') assert checkodesol(eq, sol) == (True, 0) eq = x*(x-1)*f(x).diff(x, 2) + (S(7)/2*x)*f(x).diff(x) + f(x) sol = Eq(f(x), (C1*(1 - x)**(S(5)/2)*hyper((S(1)/2, 2), (S(7)/2,), 1 - x) + C2*hyper((-S(1)/2, -2), (-S(3)/2,), 1 - x))/(x - 1)**(S(5)/2)) assert sol == dsolve(eq, hint='2nd_hypergeometric') assert checkodesol(eq, sol) == (True, 0) eq = x*(x-1)*f(x).diff(x, 2) + (S(3)+ S(7)/2*x)*f(x).diff(x) + f(x) sol = Eq(f(x), (C1*(1 - x)**(S(11)/2)*hyper((S(1)/2, 2), (S(13)/2,), 1 - x) + C2*hyper((-S(7)/2, -5), (-S(9)/2,), 1 - x))/(x - 1)**(S(11)/2)) assert sol == dsolve(eq, hint='2nd_hypergeometric') assert checkodesol(eq, sol) == (True, 0) eq = x*(x-1)*f(x).diff(x, 2) + (-1+ S(7)/2*x)*f(x).diff(x) + f(x) sol = Eq(f(x), (C1 + C2*Integral(exp(Integral((1 - x/2)/(x*(x - 1)), x))/(1 - x/2)**2, x))*exp(Integral(1/(x - 1), x)/4)*exp(-Integral(7/(x - 1), x)/4)*hyper((S(1)/2, -1), (1,), x)) assert sol == dsolve(eq, hint='2nd_hypergeometric_Integral') assert checkodesol(eq, sol) == (True, 0) eq = -x**(S(5)/7)*(-416*x**(S(9)/7)/9 - 2385*x**(S(5)/7)/49 + S(298)*x/3)*f(x)/(196*(-x**(S(6)/7) + x)**2*(x**(S(6)/7) + x)**2) + Derivative(f(x), (x, 2)) sol = Eq(f(x), x**(S(45)/98)*(C1*x**(S(4)/49)*hyper((S(1)/3, -S(1)/2), (S(9)/7,), x**(S(2)/7)) + C2*hyper((S(1)/21, -S(11)/14), (S(5)/7,), x**(S(2)/7)))/(x**(S(2)/7) - 1)**(S(19)/84)) assert sol == dsolve(eq, hint='2nd_hypergeometric') # assert checkodesol(eq, sol) == (True, 0) #issue-https://github.com/sympy/sympy/issues/17702 def test_issue_5096(): eq = f(x).diff(x, x) + f(x) - x*sin(x - 2) sol = Eq(f(x), C1*sin(x) + C2*cos(x) - x**2*cos(x - 2)/4 + x*sin(x - 2)/4) assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients') assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) + f(x) - x**4*sin(x-1) sol = Eq(f(x), C1*sin(x) + C2*cos(x) - x**5*cos(x - 1)/10 + x**4*sin(x - 1)/4 + x**3*cos(x - 1)/2 - 3*x**2*sin(x - 1)/4 - 3*x*cos(x - 1)/4) assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients') assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) - f(x) - exp(x - 1) sol = Eq(f(x), C2*exp(-x) + (C1 + x*exp(-1)/2)*exp(x)) got = dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients') assert sol == got, got assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2)+f(x)-(sin(x-2)+1) sol = Eq(f(x), C1*sin(x) + C2*cos(x) - x*cos(x - 2)/2 + 1) assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients') assert checkodesol(eq, sol) == (True, 0) eq = 2*x**2*f(x).diff(x, 2) + f(x) + sqrt(2*x)*sin(log(2*x)/2) sol = Eq(f(x), sqrt(x)*(C1*sin(log(x)/2) + C2*cos(log(x)/2) + sqrt(2)*log(x)*cos(log(2*x)/2)/2)) assert sol == dsolve(eq, hint='nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients') assert checkodesol(eq, sol) == (True, 0) eq = 2*x**2*f(x).diff(x, 2) + f(x) + sin(log(2*x)/2) sol = Eq(f(x), C1*sqrt(x)*sin(log(x)/2) + C2*sqrt(x)*cos(log(x)/2) - 2*sin(log(2*x)/2)/5 - 4*cos(log(2*x)/2)/5) assert sol == dsolve(eq, hint='nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients') assert checkodesol(eq, sol) == (True, 0) def test_issue_15996(): eq = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - 2*x - exp(I*x) sol = Eq(f(x), C1 + x**2 + (C2 + x*(C3 - x/8 + 3*exp(I*x)/2 + 3*exp(-I*x)/2) + 5*exp(2*I*x)/16 + 2*I*exp(I*x) - 2*I*exp(-I*x))*sin(x) + (C4 + x*(C5 + I*x/8 + 3*I*exp(I*x)/2 - 3*I*exp(-I*x)/2) + 5*I*exp(2*I*x)/16 - 2*exp(I*x) - 2*exp(-I*x))*cos(x) - I*exp(I*x)) got = dsolve(eq, hint='nth_linear_constant_coeff_variation_of_parameters') assert sol == got, got assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 5) + 2*f(x).diff(x, 3) + f(x).diff(x) - exp(I*x) sol = Eq(f(x), C1 + (C2 + x*(C3 - x/8) + 5*exp(2*I*x)/16)*sin(x) + (C4 + x*(C5 + I*x/8) + 5*I*exp(2*I*x)/16)*cos(x) - I*exp(I*x)) got = dsolve(eq, hint='nth_linear_constant_coeff_variation_of_parameters') assert sol == got, got assert checkodesol(eq, sol) == (True, 0) def test_issue_18408(): eq = f(x).diff(x, 3) - f(x).diff(x) - sinh(x) sol = Eq(f(x), C1 + C2*exp(-x) + C3*exp(x) + x*sinh(x)/2) assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients') assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 2) - 49*f(x) - sinh(3*x) sol = Eq(f(x), C1*exp(-7*x) + C2*exp(7*x) - sinh(3*x)/40) assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients') assert checkodesol(eq, sol) == (True, 0) eq = f(x).diff(x, 3) - f(x).diff(x) - sinh(x) - exp(x) sol = Eq(f(x), C1 + C3*exp(-x) + x*sinh(x)/2 + (C2 + x/2)*exp(x)) assert sol == dsolve(eq, hint='nth_linear_constant_coeff_undetermined_coefficients') assert checkodesol(eq, sol) == (True, 0) def test_issue_9446(): f = Function('f') assert dsolve(Eq(f(2 * x), sin(Derivative(f(x)))), f(x)) == \ [Eq(f(x), C1 + pi*x - Integral(asin(f(2*x)), x)), Eq(f(x), C1 + Integral(asin(f(2*x)), x))] assert integrate(-asin(f(2*x)+pi), x) == -Integral(asin(pi + f(2*x)), x) def test_issue_20192(): # kamke ode 1.1 a0,a1,a2,a3,a4 = symbols('a0, a1, a2, a3, a4') eq = f(x).diff(x)-(a4*x**4 + a3*x**3 + a2*x**2 + a1*x + a0)**(-1/2) sol = Eq(f(x), C1 + Integral(1/sqrt(a0 + a1*x + a2*x**2 + a3*x**3 + a4*x**4), x)) assert sol == dsolve(eq,hint='factorable') assert checkodesol(eq, sol) == (True, 0)
9c5ca22126a2cfcbdfb4c576ba1dfbd2615c480a6ea0a690a68cdbdce12b9cc0
from __future__ import absolute_import from sympy.codegen import Assignment from sympy.codegen.ast import none from sympy.codegen.cfunctions import expm1, log1p from sympy.codegen.scipy_nodes import cosm1 from sympy.codegen.matrix_nodes import MatrixSolve from sympy.core import Expr, Mod, symbols, Eq, Le, Gt, zoo, oo, Rational, Pow from sympy.core.numbers import pi from sympy.core.singleton import S from sympy.functions import acos, KroneckerDelta, Piecewise, sign, sqrt from sympy.logic import And, Or from sympy.matrices import SparseMatrix, MatrixSymbol, Identity from sympy.printing.pycode import ( MpmathPrinter, NumPyPrinter, PythonCodePrinter, pycode, SciPyPrinter, SymPyPrinter ) from sympy.testing.pytest import raises from sympy.tensor import IndexedBase from sympy.testing.pytest import skip from sympy.external import import_module from sympy.functions.special.gamma_functions import loggamma x, y, z = symbols('x y z') p = IndexedBase("p") def test_PythonCodePrinter(): prntr = PythonCodePrinter() assert not prntr.module_imports assert prntr.doprint(x**y) == 'x**y' assert prntr.doprint(Mod(x, 2)) == 'x % 2' assert prntr.doprint(And(x, y)) == 'x and y' assert prntr.doprint(Or(x, y)) == 'x or y' assert not prntr.module_imports assert prntr.doprint(pi) == 'math.pi' assert prntr.module_imports == {'math': {'pi'}} assert prntr.doprint(x**Rational(1, 2)) == 'math.sqrt(x)' assert prntr.doprint(sqrt(x)) == 'math.sqrt(x)' assert prntr.module_imports == {'math': {'pi', 'sqrt'}} assert prntr.doprint(acos(x)) == 'math.acos(x)' assert prntr.doprint(Assignment(x, 2)) == 'x = 2' assert prntr.doprint(Piecewise((1, Eq(x, 0)), (2, x>6))) == '((1) if (x == 0) else (2) if (x > 6) else None)' assert prntr.doprint(Piecewise((2, Le(x, 0)), (3, Gt(x, 0)), evaluate=False)) == '((2) if (x <= 0) else'\ ' (3) if (x > 0) else None)' assert prntr.doprint(sign(x)) == '(0.0 if x == 0 else math.copysign(1, x))' assert prntr.doprint(p[0, 1]) == 'p[0, 1]' assert prntr.doprint(KroneckerDelta(x,y)) == '(1 if x == y else 0)' def test_PythonCodePrinter_standard(): import sys prntr = PythonCodePrinter({'standard':None}) python_version = sys.version_info.major if python_version == 2: assert prntr.standard == 'python2' if python_version == 3: assert prntr.standard == 'python3' raises(ValueError, lambda: PythonCodePrinter({'standard':'python4'})) def test_MpmathPrinter(): p = MpmathPrinter() assert p.doprint(sign(x)) == 'mpmath.sign(x)' assert p.doprint(Rational(1, 2)) == 'mpmath.mpf(1)/mpmath.mpf(2)' assert p.doprint(S.Exp1) == 'mpmath.e' assert p.doprint(S.Pi) == 'mpmath.pi' assert p.doprint(S.GoldenRatio) == 'mpmath.phi' assert p.doprint(S.EulerGamma) == 'mpmath.euler' assert p.doprint(S.NaN) == 'mpmath.nan' assert p.doprint(S.Infinity) == 'mpmath.inf' assert p.doprint(S.NegativeInfinity) == 'mpmath.ninf' assert p.doprint(loggamma(x)) == 'mpmath.loggamma(x)' def test_NumPyPrinter(): from sympy import (Lambda, ZeroMatrix, OneMatrix, FunctionMatrix, HadamardProduct, KroneckerProduct, Adjoint, DiagonalOf, DiagMatrix, DiagonalMatrix) from sympy.abc import a, b p = NumPyPrinter() assert p.doprint(sign(x)) == 'numpy.sign(x)' A = MatrixSymbol("A", 2, 2) B = MatrixSymbol("B", 2, 2) C = MatrixSymbol("C", 1, 5) D = MatrixSymbol("D", 3, 4) assert p.doprint(A**(-1)) == "numpy.linalg.inv(A)" assert p.doprint(A**5) == "numpy.linalg.matrix_power(A, 5)" assert p.doprint(Identity(3)) == "numpy.eye(3)" u = MatrixSymbol('x', 2, 1) v = MatrixSymbol('y', 2, 1) assert p.doprint(MatrixSolve(A, u)) == 'numpy.linalg.solve(A, x)' assert p.doprint(MatrixSolve(A, u) + v) == 'numpy.linalg.solve(A, x) + y' assert p.doprint(ZeroMatrix(2, 3)) == "numpy.zeros((2, 3))" assert p.doprint(OneMatrix(2, 3)) == "numpy.ones((2, 3))" assert p.doprint(FunctionMatrix(4, 5, Lambda((a, b), a + b))) == \ "numpy.fromfunction(lambda a, b: a + b, (4, 5))" assert p.doprint(HadamardProduct(A, B)) == "numpy.multiply(A, B)" assert p.doprint(KroneckerProduct(A, B)) == "numpy.kron(A, B)" assert p.doprint(Adjoint(A)) == "numpy.conjugate(numpy.transpose(A))" assert p.doprint(DiagonalOf(A)) == "numpy.reshape(numpy.diag(A), (-1, 1))" assert p.doprint(DiagMatrix(C)) == "numpy.diagflat(C)" assert p.doprint(DiagonalMatrix(D)) == "numpy.multiply(D, numpy.eye(3, 4))" # Workaround for numpy negative integer power errors assert p.doprint(x**-1) == 'x**(-1.0)' assert p.doprint(x**-2) == 'x**(-2.0)' expr = Pow(2, -1, evaluate=False) assert p.doprint(expr) == "2**(-1.0)" assert p.doprint(S.Exp1) == 'numpy.e' assert p.doprint(S.Pi) == 'numpy.pi' assert p.doprint(S.EulerGamma) == 'numpy.euler_gamma' assert p.doprint(S.NaN) == 'numpy.nan' assert p.doprint(S.Infinity) == 'numpy.PINF' assert p.doprint(S.NegativeInfinity) == 'numpy.NINF' def test_issue_18770(): numpy = import_module('numpy') if not numpy: skip("numpy not installed.") from sympy import lambdify, Min, Max expr1 = Min(0.1*x + 3, x + 1, 0.5*x + 1) func = lambdify(x, expr1, "numpy") assert (func(numpy.linspace(0, 3, 3)) == [1.0 , 1.75, 2.5 ]).all() assert func(4) == 3 expr1 = Max(x**2 , x**3) func = lambdify(x,expr1, "numpy") assert (func(numpy.linspace(-1 , 2, 4)) == [1, 0, 1, 8] ).all() assert func(4) == 64 def test_SciPyPrinter(): p = SciPyPrinter() expr = acos(x) assert 'numpy' not in p.module_imports assert p.doprint(expr) == 'numpy.arccos(x)' assert 'numpy' in p.module_imports assert not any(m.startswith('scipy') for m in p.module_imports) smat = SparseMatrix(2, 5, {(0, 1): 3}) assert p.doprint(smat) == \ 'scipy.sparse.coo_matrix(([3], ([0], [1])), shape=(2, 5))' assert 'scipy.sparse' in p.module_imports assert p.doprint(S.GoldenRatio) == 'scipy.constants.golden_ratio' assert p.doprint(S.Pi) == 'scipy.constants.pi' assert p.doprint(S.Exp1) == 'numpy.e' def test_pycode_reserved_words(): s1, s2 = symbols('if else') raises(ValueError, lambda: pycode(s1 + s2, error_on_reserved=True)) py_str = pycode(s1 + s2) assert py_str in ('else_ + if_', 'if_ + else_') def test_sqrt(): prntr = PythonCodePrinter() assert prntr._print_Pow(sqrt(x), rational=False) == 'math.sqrt(x)' assert prntr._print_Pow(1/sqrt(x), rational=False) == '1/math.sqrt(x)' prntr = PythonCodePrinter({'standard' : 'python2'}) assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1./2.)' assert prntr._print_Pow(1/sqrt(x), rational=True) == 'x**(-1./2.)' prntr = PythonCodePrinter({'standard' : 'python3'}) assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' assert prntr._print_Pow(1/sqrt(x), rational=True) == 'x**(-1/2)' prntr = MpmathPrinter() assert prntr._print_Pow(sqrt(x), rational=False) == 'mpmath.sqrt(x)' assert prntr._print_Pow(sqrt(x), rational=True) == \ "x**(mpmath.mpf(1)/mpmath.mpf(2))" prntr = NumPyPrinter() assert prntr._print_Pow(sqrt(x), rational=False) == 'numpy.sqrt(x)' assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' prntr = SciPyPrinter() assert prntr._print_Pow(sqrt(x), rational=False) == 'numpy.sqrt(x)' assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' prntr = SymPyPrinter() assert prntr._print_Pow(sqrt(x), rational=False) == 'sympy.sqrt(x)' assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' def test_frac(): from sympy import frac expr = frac(x) prntr = NumPyPrinter() assert prntr.doprint(expr) == 'numpy.mod(x, 1)' prntr = SciPyPrinter() assert prntr.doprint(expr) == 'numpy.mod(x, 1)' prntr = PythonCodePrinter() assert prntr.doprint(expr) == 'x % 1' prntr = MpmathPrinter() assert prntr.doprint(expr) == 'mpmath.frac(x)' prntr = SymPyPrinter() assert prntr.doprint(expr) == 'sympy.functions.elementary.integers.frac(x)' class CustomPrintedObject(Expr): def _numpycode(self, printer): return 'numpy' def _mpmathcode(self, printer): return 'mpmath' def test_printmethod(): obj = CustomPrintedObject() assert NumPyPrinter().doprint(obj) == 'numpy' assert MpmathPrinter().doprint(obj) == 'mpmath' def test_codegen_ast_nodes(): assert pycode(none) == 'None' def test_issue_14283(): prntr = PythonCodePrinter() assert prntr.doprint(zoo) == "float('nan')" assert prntr.doprint(-oo) == "float('-inf')" def test_NumPyPrinter_print_seq(): n = NumPyPrinter() assert n._print_seq(range(2)) == '(0, 1,)' def test_issue_16535_16536(): from sympy import lowergamma, uppergamma a = symbols('a') expr1 = lowergamma(a, x) expr2 = uppergamma(a, x) prntr = SciPyPrinter() assert prntr.doprint(expr1) == 'scipy.special.gamma(a)*scipy.special.gammainc(a, x)' assert prntr.doprint(expr2) == 'scipy.special.gamma(a)*scipy.special.gammaincc(a, x)' prntr = NumPyPrinter() assert prntr.doprint(expr1) == ' # Not supported in Python with NumPy:\n # lowergamma\nlowergamma(a, x)' assert prntr.doprint(expr2) == ' # Not supported in Python with NumPy:\n # uppergamma\nuppergamma(a, x)' prntr = PythonCodePrinter() assert prntr.doprint(expr1) == ' # Not supported in Python:\n # lowergamma\nlowergamma(a, x)' assert prntr.doprint(expr2) == ' # Not supported in Python:\n # uppergamma\nuppergamma(a, x)' def test_Integral(): from sympy import Integral, exp single = Integral(exp(-x), (x, 0, oo)) double = Integral(x**2*exp(x*y), (x, -z, z), (y, 0, z)) indefinite = Integral(x**2, x) evaluateat = Integral(x**2, (x, 1)) prntr = SciPyPrinter() assert prntr.doprint(single) == 'scipy.integrate.quad(lambda x: numpy.exp(-x), 0, numpy.PINF)[0]' assert prntr.doprint(double) == 'scipy.integrate.nquad(lambda x, y: x**2*numpy.exp(x*y), ((-z, z), (0, z)))[0]' raises(NotImplementedError, lambda: prntr.doprint(indefinite)) raises(NotImplementedError, lambda: prntr.doprint(evaluateat)) prntr = MpmathPrinter() assert prntr.doprint(single) == 'mpmath.quad(lambda x: mpmath.exp(-x), (0, mpmath.inf))' assert prntr.doprint(double) == 'mpmath.quad(lambda x, y: x**2*mpmath.exp(x*y), (-z, z), (0, z))' raises(NotImplementedError, lambda: prntr.doprint(indefinite)) raises(NotImplementedError, lambda: prntr.doprint(evaluateat)) def test_fresnel_integrals(): from sympy import fresnelc, fresnels expr1 = fresnelc(x) expr2 = fresnels(x) prntr = SciPyPrinter() assert prntr.doprint(expr1) == 'scipy.special.fresnel(x)[1]' assert prntr.doprint(expr2) == 'scipy.special.fresnel(x)[0]' prntr = NumPyPrinter() assert prntr.doprint(expr1) == ' # Not supported in Python with NumPy:\n # fresnelc\nfresnelc(x)' assert prntr.doprint(expr2) == ' # Not supported in Python with NumPy:\n # fresnels\nfresnels(x)' prntr = PythonCodePrinter() assert prntr.doprint(expr1) == ' # Not supported in Python:\n # fresnelc\nfresnelc(x)' assert prntr.doprint(expr2) == ' # Not supported in Python:\n # fresnels\nfresnels(x)' prntr = MpmathPrinter() assert prntr.doprint(expr1) == 'mpmath.fresnelc(x)' assert prntr.doprint(expr2) == 'mpmath.fresnels(x)' def test_beta(): from sympy import beta expr = beta(x, y) prntr = SciPyPrinter() assert prntr.doprint(expr) == 'scipy.special.beta(x, y)' prntr = NumPyPrinter() assert prntr.doprint(expr) == 'math.gamma(x)*math.gamma(y)/math.gamma(x + y)' prntr = PythonCodePrinter() assert prntr.doprint(expr) == 'math.gamma(x)*math.gamma(y)/math.gamma(x + y)' prntr = PythonCodePrinter({'allow_unknown_functions': True}) assert prntr.doprint(expr) == 'math.gamma(x)*math.gamma(y)/math.gamma(x + y)' prntr = MpmathPrinter() assert prntr.doprint(expr) == 'mpmath.beta(x, y)' def test_airy(): from sympy import airyai, airybi expr1 = airyai(x) expr2 = airybi(x) prntr = SciPyPrinter() assert prntr.doprint(expr1) == 'scipy.special.airy(x)[0]' assert prntr.doprint(expr2) == 'scipy.special.airy(x)[2]' prntr = NumPyPrinter() assert prntr.doprint(expr1) == ' # Not supported in Python with NumPy:\n # airyai\nairyai(x)' assert prntr.doprint(expr2) == ' # Not supported in Python with NumPy:\n # airybi\nairybi(x)' prntr = PythonCodePrinter() assert prntr.doprint(expr1) == ' # Not supported in Python:\n # airyai\nairyai(x)' assert prntr.doprint(expr2) == ' # Not supported in Python:\n # airybi\nairybi(x)' def test_airy_prime(): from sympy import airyaiprime, airybiprime expr1 = airyaiprime(x) expr2 = airybiprime(x) prntr = SciPyPrinter() assert prntr.doprint(expr1) == 'scipy.special.airy(x)[1]' assert prntr.doprint(expr2) == 'scipy.special.airy(x)[3]' prntr = NumPyPrinter() assert prntr.doprint(expr1) == ' # Not supported in Python with NumPy:\n # airyaiprime\nairyaiprime(x)' assert prntr.doprint(expr2) == ' # Not supported in Python with NumPy:\n # airybiprime\nairybiprime(x)' prntr = PythonCodePrinter() assert prntr.doprint(expr1) == ' # Not supported in Python:\n # airyaiprime\nairyaiprime(x)' assert prntr.doprint(expr2) == ' # Not supported in Python:\n # airybiprime\nairybiprime(x)' def test_numerical_accuracy_functions(): prntr = SciPyPrinter() assert prntr.doprint(expm1(x)) == 'numpy.expm1(x)' assert prntr.doprint(log1p(x)) == 'numpy.log1p(x)' assert prntr.doprint(cosm1(x)) == 'scipy.special.cosm1(x)'
9240a1e4485688bcf4e8621c7ce48500db89a4ef3bac47b7fd52e4972f4cf63a
from sympy import (sin, cos, atan2, log, exp, gamma, conjugate, sqrt, factorial, Integral, Piecewise, Add, diff, symbols, S, Float, Dummy, Eq, Range, Catalan, EulerGamma, E, GoldenRatio, I, pi, Function, Rational, Integer, Lambda, sign, Mod) from sympy.codegen import For, Assignment, aug_assign from sympy.codegen.ast import Declaration, Variable, float32, float64, \ value_const, real, bool_, While, FunctionPrototype, FunctionDefinition, \ integer, Return from sympy.core.relational import Relational from sympy.logic.boolalg import And, Or, Not, Equivalent, Xor from sympy.matrices import Matrix, MatrixSymbol from sympy.printing.fortran import fcode, FCodePrinter from sympy.tensor import IndexedBase, Idx from sympy.utilities.lambdify import implemented_function from sympy.testing.pytest import raises, warns_deprecated_sympy def test_printmethod(): x = symbols('x') class nint(Function): def _fcode(self, printer): return "nint(%s)" % printer._print(self.args[0]) assert fcode(nint(x)) == " nint(x)" def test_fcode_sign(): #issue 12267 x=symbols('x') y=symbols('y', integer=True) z=symbols('z', complex=True) assert fcode(sign(x), standard=95, source_format='free') == "merge(0d0, dsign(1d0, x), x == 0d0)" assert fcode(sign(y), standard=95, source_format='free') == "merge(0, isign(1, y), y == 0)" assert fcode(sign(z), standard=95, source_format='free') == "merge(cmplx(0d0, 0d0), z/abs(z), abs(z) == 0d0)" raises(NotImplementedError, lambda: fcode(sign(x))) def test_fcode_Pow(): x, y = symbols('x,y') n = symbols('n', integer=True) assert fcode(x**3) == " x**3" assert fcode(x**(y**3)) == " x**(y**3)" assert fcode(1/(sin(x)*3.5)**(x - y**x)/(x**2 + y)) == \ " (3.5d0*sin(x))**(-x + y**x)/(x**2 + y)" assert fcode(sqrt(x)) == ' sqrt(x)' assert fcode(sqrt(n)) == ' sqrt(dble(n))' assert fcode(x**0.5) == ' sqrt(x)' assert fcode(sqrt(x)) == ' sqrt(x)' assert fcode(sqrt(10)) == ' sqrt(10.0d0)' assert fcode(x**-1.0) == ' 1d0/x' assert fcode(x**-2.0, 'y', source_format='free') == 'y = x**(-2.0d0)' # 2823 assert fcode(x**Rational(3, 7)) == ' x**(3.0d0/7.0d0)' def test_fcode_Rational(): x = symbols('x') assert fcode(Rational(3, 7)) == " 3.0d0/7.0d0" assert fcode(Rational(18, 9)) == " 2" assert fcode(Rational(3, -7)) == " -3.0d0/7.0d0" assert fcode(Rational(-3, -7)) == " 3.0d0/7.0d0" assert fcode(x + Rational(3, 7)) == " x + 3.0d0/7.0d0" assert fcode(Rational(3, 7)*x) == " (3.0d0/7.0d0)*x" def test_fcode_Integer(): assert fcode(Integer(67)) == " 67" assert fcode(Integer(-1)) == " -1" def test_fcode_Float(): assert fcode(Float(42.0)) == " 42.0000000000000d0" assert fcode(Float(-1e20)) == " -1.00000000000000d+20" def test_fcode_functions(): x, y = symbols('x,y') assert fcode(sin(x) ** cos(y)) == " sin(x)**cos(y)" raises(NotImplementedError, lambda: fcode(Mod(x, y), standard=66)) raises(NotImplementedError, lambda: fcode(x % y, standard=66)) raises(NotImplementedError, lambda: fcode(Mod(x, y), standard=77)) raises(NotImplementedError, lambda: fcode(x % y, standard=77)) for standard in [90, 95, 2003, 2008]: assert fcode(Mod(x, y), standard=standard) == " modulo(x, y)" assert fcode(x % y, standard=standard) == " modulo(x, y)" def test_case(): ob = FCodePrinter() x,x_,x__,y,X,X_,Y = symbols('x,x_,x__,y,X,X_,Y') assert fcode(exp(x_) + sin(x*y) + cos(X*Y)) == \ ' exp(x_) + sin(x*y) + cos(X__*Y_)' assert fcode(exp(x__) + 2*x*Y*X_**Rational(7, 2)) == \ ' 2*X_**(7.0d0/2.0d0)*Y*x + exp(x__)' assert fcode(exp(x_) + sin(x*y) + cos(X*Y), name_mangling=False) == \ ' exp(x_) + sin(x*y) + cos(X*Y)' assert fcode(x - cos(X), name_mangling=False) == ' x - cos(X)' assert ob.doprint(X*sin(x) + x_, assign_to='me') == ' me = X*sin(x_) + x__' assert ob.doprint(X*sin(x), assign_to='mu') == ' mu = X*sin(x_)' assert ob.doprint(x_, assign_to='ad') == ' ad = x__' n, m = symbols('n,m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') i = Idx('i', m) I = Idx('I', n) assert fcode(A[i, I]*x[I], assign_to=y[i], source_format='free') == ( "do i = 1, m\n" " y(i) = 0\n" "end do\n" "do i = 1, m\n" " do I_ = 1, n\n" " y(i) = A(i, I_)*x(I_) + y(i)\n" " end do\n" "end do" ) #issue 6814 def test_fcode_functions_with_integers(): x= symbols('x') log10_17 = log(10).evalf(17) loglog10_17 = '0.8340324452479558d0' assert fcode(x * log(10)) == " x*%sd0" % log10_17 assert fcode(x * log(10)) == " x*%sd0" % log10_17 assert fcode(x * log(S(10))) == " x*%sd0" % log10_17 assert fcode(log(S(10))) == " %sd0" % log10_17 assert fcode(exp(10)) == " %sd0" % exp(10).evalf(17) assert fcode(x * log(log(10))) == " x*%s" % loglog10_17 assert fcode(x * log(log(S(10)))) == " x*%s" % loglog10_17 def test_fcode_NumberSymbol(): prec = 17 p = FCodePrinter() assert fcode(Catalan) == ' parameter (Catalan = %sd0)\n Catalan' % Catalan.evalf(prec) assert fcode(EulerGamma) == ' parameter (EulerGamma = %sd0)\n EulerGamma' % EulerGamma.evalf(prec) assert fcode(E) == ' parameter (E = %sd0)\n E' % E.evalf(prec) assert fcode(GoldenRatio) == ' parameter (GoldenRatio = %sd0)\n GoldenRatio' % GoldenRatio.evalf(prec) assert fcode(pi) == ' parameter (pi = %sd0)\n pi' % pi.evalf(prec) assert fcode( pi, precision=5) == ' parameter (pi = %sd0)\n pi' % pi.evalf(5) assert fcode(Catalan, human=False) == (set( [(Catalan, p._print(Catalan.evalf(prec)))]), set([]), ' Catalan') assert fcode(EulerGamma, human=False) == (set([(EulerGamma, p._print( EulerGamma.evalf(prec)))]), set([]), ' EulerGamma') assert fcode(E, human=False) == ( set([(E, p._print(E.evalf(prec)))]), set([]), ' E') assert fcode(GoldenRatio, human=False) == (set([(GoldenRatio, p._print( GoldenRatio.evalf(prec)))]), set([]), ' GoldenRatio') assert fcode(pi, human=False) == ( set([(pi, p._print(pi.evalf(prec)))]), set([]), ' pi') assert fcode(pi, precision=5, human=False) == ( set([(pi, p._print(pi.evalf(5)))]), set([]), ' pi') def test_fcode_complex(): assert fcode(I) == " cmplx(0,1)" x = symbols('x') assert fcode(4*I) == " cmplx(0,4)" assert fcode(3 + 4*I) == " cmplx(3,4)" assert fcode(3 + 4*I + x) == " cmplx(3,4) + x" assert fcode(I*x) == " cmplx(0,1)*x" assert fcode(3 + 4*I - x) == " cmplx(3,4) - x" x = symbols('x', imaginary=True) assert fcode(5*x) == " 5*x" assert fcode(I*x) == " cmplx(0,1)*x" assert fcode(3 + x) == " x + 3" def test_implicit(): x, y = symbols('x,y') assert fcode(sin(x)) == " sin(x)" assert fcode(atan2(x, y)) == " atan2(x, y)" assert fcode(conjugate(x)) == " conjg(x)" def test_not_fortran(): x = symbols('x') g = Function('g') gamma_f = fcode(gamma(x)) assert gamma_f == "C Not supported in Fortran:\nC gamma\n gamma(x)" assert fcode(Integral(sin(x))) == "C Not supported in Fortran:\nC Integral\n Integral(sin(x), x)" assert fcode(g(x)) == "C Not supported in Fortran:\nC g\n g(x)" def test_user_functions(): x = symbols('x') assert fcode(sin(x), user_functions={"sin": "zsin"}) == " zsin(x)" x = symbols('x') assert fcode( gamma(x), user_functions={"gamma": "mygamma"}) == " mygamma(x)" g = Function('g') assert fcode(g(x), user_functions={"g": "great"}) == " great(x)" n = symbols('n', integer=True) assert fcode( factorial(n), user_functions={"factorial": "fct"}) == " fct(n)" def test_inline_function(): x = symbols('x') g = implemented_function('g', Lambda(x, 2*x)) assert fcode(g(x)) == " 2*x" g = implemented_function('g', Lambda(x, 2*pi/x)) assert fcode(g(x)) == ( " parameter (pi = %sd0)\n" " 2*pi/x" ) % pi.evalf(17) A = IndexedBase('A') i = Idx('i', symbols('n', integer=True)) g = implemented_function('g', Lambda(x, x*(1 + x)*(2 + x))) assert fcode(g(A[i]), assign_to=A[i]) == ( " do i = 1, n\n" " A(i) = (A(i) + 1)*(A(i) + 2)*A(i)\n" " end do" ) def test_assign_to(): x = symbols('x') assert fcode(sin(x), assign_to="s") == " s = sin(x)" def test_line_wrapping(): x, y = symbols('x,y') assert fcode(((x + y)**10).expand(), assign_to="var") == ( " var = x**10 + 10*x**9*y + 45*x**8*y**2 + 120*x**7*y**3 + 210*x**6*\n" " @ y**4 + 252*x**5*y**5 + 210*x**4*y**6 + 120*x**3*y**7 + 45*x**2*y\n" " @ **8 + 10*x*y**9 + y**10" ) e = [x**i for i in range(11)] assert fcode(Add(*e)) == ( " x**10 + x**9 + x**8 + x**7 + x**6 + x**5 + x**4 + x**3 + x**2 + x\n" " @ + 1" ) def test_fcode_precedence(): x, y = symbols("x y") assert fcode(And(x < y, y < x + 1), source_format="free") == \ "x < y .and. y < x + 1" assert fcode(Or(x < y, y < x + 1), source_format="free") == \ "x < y .or. y < x + 1" assert fcode(Xor(x < y, y < x + 1, evaluate=False), source_format="free") == "x < y .neqv. y < x + 1" assert fcode(Equivalent(x < y, y < x + 1), source_format="free") == \ "x < y .eqv. y < x + 1" def test_fcode_Logical(): x, y, z = symbols("x y z") # unary Not assert fcode(Not(x), source_format="free") == ".not. x" # binary And assert fcode(And(x, y), source_format="free") == "x .and. y" assert fcode(And(x, Not(y)), source_format="free") == "x .and. .not. y" assert fcode(And(Not(x), y), source_format="free") == "y .and. .not. x" assert fcode(And(Not(x), Not(y)), source_format="free") == \ ".not. x .and. .not. y" assert fcode(Not(And(x, y), evaluate=False), source_format="free") == \ ".not. (x .and. y)" # binary Or assert fcode(Or(x, y), source_format="free") == "x .or. y" assert fcode(Or(x, Not(y)), source_format="free") == "x .or. .not. y" assert fcode(Or(Not(x), y), source_format="free") == "y .or. .not. x" assert fcode(Or(Not(x), Not(y)), source_format="free") == \ ".not. x .or. .not. y" assert fcode(Not(Or(x, y), evaluate=False), source_format="free") == \ ".not. (x .or. y)" # mixed And/Or assert fcode(And(Or(y, z), x), source_format="free") == "x .and. (y .or. z)" assert fcode(And(Or(z, x), y), source_format="free") == "y .and. (x .or. z)" assert fcode(And(Or(x, y), z), source_format="free") == "z .and. (x .or. y)" assert fcode(Or(And(y, z), x), source_format="free") == "x .or. y .and. z" assert fcode(Or(And(z, x), y), source_format="free") == "y .or. x .and. z" assert fcode(Or(And(x, y), z), source_format="free") == "z .or. x .and. y" # trinary And assert fcode(And(x, y, z), source_format="free") == "x .and. y .and. z" assert fcode(And(x, y, Not(z)), source_format="free") == \ "x .and. y .and. .not. z" assert fcode(And(x, Not(y), z), source_format="free") == \ "x .and. z .and. .not. y" assert fcode(And(Not(x), y, z), source_format="free") == \ "y .and. z .and. .not. x" assert fcode(Not(And(x, y, z), evaluate=False), source_format="free") == \ ".not. (x .and. y .and. z)" # trinary Or assert fcode(Or(x, y, z), source_format="free") == "x .or. y .or. z" assert fcode(Or(x, y, Not(z)), source_format="free") == \ "x .or. y .or. .not. z" assert fcode(Or(x, Not(y), z), source_format="free") == \ "x .or. z .or. .not. y" assert fcode(Or(Not(x), y, z), source_format="free") == \ "y .or. z .or. .not. x" assert fcode(Not(Or(x, y, z), evaluate=False), source_format="free") == \ ".not. (x .or. y .or. z)" def test_fcode_Xlogical(): x, y, z = symbols("x y z") # binary Xor assert fcode(Xor(x, y, evaluate=False), source_format="free") == \ "x .neqv. y" assert fcode(Xor(x, Not(y), evaluate=False), source_format="free") == \ "x .neqv. .not. y" assert fcode(Xor(Not(x), y, evaluate=False), source_format="free") == \ "y .neqv. .not. x" assert fcode(Xor(Not(x), Not(y), evaluate=False), source_format="free") == ".not. x .neqv. .not. y" assert fcode(Not(Xor(x, y, evaluate=False), evaluate=False), source_format="free") == ".not. (x .neqv. y)" # binary Equivalent assert fcode(Equivalent(x, y), source_format="free") == "x .eqv. y" assert fcode(Equivalent(x, Not(y)), source_format="free") == \ "x .eqv. .not. y" assert fcode(Equivalent(Not(x), y), source_format="free") == \ "y .eqv. .not. x" assert fcode(Equivalent(Not(x), Not(y)), source_format="free") == \ ".not. x .eqv. .not. y" assert fcode(Not(Equivalent(x, y), evaluate=False), source_format="free") == ".not. (x .eqv. y)" # mixed And/Equivalent assert fcode(Equivalent(And(y, z), x), source_format="free") == \ "x .eqv. y .and. z" assert fcode(Equivalent(And(z, x), y), source_format="free") == \ "y .eqv. x .and. z" assert fcode(Equivalent(And(x, y), z), source_format="free") == \ "z .eqv. x .and. y" assert fcode(And(Equivalent(y, z), x), source_format="free") == \ "x .and. (y .eqv. z)" assert fcode(And(Equivalent(z, x), y), source_format="free") == \ "y .and. (x .eqv. z)" assert fcode(And(Equivalent(x, y), z), source_format="free") == \ "z .and. (x .eqv. y)" # mixed Or/Equivalent assert fcode(Equivalent(Or(y, z), x), source_format="free") == \ "x .eqv. y .or. z" assert fcode(Equivalent(Or(z, x), y), source_format="free") == \ "y .eqv. x .or. z" assert fcode(Equivalent(Or(x, y), z), source_format="free") == \ "z .eqv. x .or. y" assert fcode(Or(Equivalent(y, z), x), source_format="free") == \ "x .or. (y .eqv. z)" assert fcode(Or(Equivalent(z, x), y), source_format="free") == \ "y .or. (x .eqv. z)" assert fcode(Or(Equivalent(x, y), z), source_format="free") == \ "z .or. (x .eqv. y)" # mixed Xor/Equivalent assert fcode(Equivalent(Xor(y, z, evaluate=False), x), source_format="free") == "x .eqv. (y .neqv. z)" assert fcode(Equivalent(Xor(z, x, evaluate=False), y), source_format="free") == "y .eqv. (x .neqv. z)" assert fcode(Equivalent(Xor(x, y, evaluate=False), z), source_format="free") == "z .eqv. (x .neqv. y)" assert fcode(Xor(Equivalent(y, z), x, evaluate=False), source_format="free") == "x .neqv. (y .eqv. z)" assert fcode(Xor(Equivalent(z, x), y, evaluate=False), source_format="free") == "y .neqv. (x .eqv. z)" assert fcode(Xor(Equivalent(x, y), z, evaluate=False), source_format="free") == "z .neqv. (x .eqv. y)" # mixed And/Xor assert fcode(Xor(And(y, z), x, evaluate=False), source_format="free") == \ "x .neqv. y .and. z" assert fcode(Xor(And(z, x), y, evaluate=False), source_format="free") == \ "y .neqv. x .and. z" assert fcode(Xor(And(x, y), z, evaluate=False), source_format="free") == \ "z .neqv. x .and. y" assert fcode(And(Xor(y, z, evaluate=False), x), source_format="free") == \ "x .and. (y .neqv. z)" assert fcode(And(Xor(z, x, evaluate=False), y), source_format="free") == \ "y .and. (x .neqv. z)" assert fcode(And(Xor(x, y, evaluate=False), z), source_format="free") == \ "z .and. (x .neqv. y)" # mixed Or/Xor assert fcode(Xor(Or(y, z), x, evaluate=False), source_format="free") == \ "x .neqv. y .or. z" assert fcode(Xor(Or(z, x), y, evaluate=False), source_format="free") == \ "y .neqv. x .or. z" assert fcode(Xor(Or(x, y), z, evaluate=False), source_format="free") == \ "z .neqv. x .or. y" assert fcode(Or(Xor(y, z, evaluate=False), x), source_format="free") == \ "x .or. (y .neqv. z)" assert fcode(Or(Xor(z, x, evaluate=False), y), source_format="free") == \ "y .or. (x .neqv. z)" assert fcode(Or(Xor(x, y, evaluate=False), z), source_format="free") == \ "z .or. (x .neqv. y)" # trinary Xor assert fcode(Xor(x, y, z, evaluate=False), source_format="free") == \ "x .neqv. y .neqv. z" assert fcode(Xor(x, y, Not(z), evaluate=False), source_format="free") == \ "x .neqv. y .neqv. .not. z" assert fcode(Xor(x, Not(y), z, evaluate=False), source_format="free") == \ "x .neqv. z .neqv. .not. y" assert fcode(Xor(Not(x), y, z, evaluate=False), source_format="free") == \ "y .neqv. z .neqv. .not. x" def test_fcode_Relational(): x, y = symbols("x y") assert fcode(Relational(x, y, "=="), source_format="free") == "x == y" assert fcode(Relational(x, y, "!="), source_format="free") == "x /= y" assert fcode(Relational(x, y, ">="), source_format="free") == "x >= y" assert fcode(Relational(x, y, "<="), source_format="free") == "x <= y" assert fcode(Relational(x, y, ">"), source_format="free") == "x > y" assert fcode(Relational(x, y, "<"), source_format="free") == "x < y" def test_fcode_Piecewise(): x = symbols('x') expr = Piecewise((x, x < 1), (x**2, True)) # Check that inline conditional (merge) fails if standard isn't 95+ raises(NotImplementedError, lambda: fcode(expr)) code = fcode(expr, standard=95) expected = " merge(x, x**2, x < 1)" assert code == expected assert fcode(Piecewise((x, x < 1), (x**2, True)), assign_to="var") == ( " if (x < 1) then\n" " var = x\n" " else\n" " var = x**2\n" " end if" ) a = cos(x)/x b = sin(x)/x for i in range(10): a = diff(a, x) b = diff(b, x) expected = ( " if (x < 0) then\n" " weird_name = -cos(x)/x + 10*sin(x)/x**2 + 90*cos(x)/x**3 - 720*\n" " @ sin(x)/x**4 - 5040*cos(x)/x**5 + 30240*sin(x)/x**6 + 151200*cos(x\n" " @ )/x**7 - 604800*sin(x)/x**8 - 1814400*cos(x)/x**9 + 3628800*sin(x\n" " @ )/x**10 + 3628800*cos(x)/x**11\n" " else\n" " weird_name = -sin(x)/x - 10*cos(x)/x**2 + 90*sin(x)/x**3 + 720*\n" " @ cos(x)/x**4 - 5040*sin(x)/x**5 - 30240*cos(x)/x**6 + 151200*sin(x\n" " @ )/x**7 + 604800*cos(x)/x**8 - 1814400*sin(x)/x**9 - 3628800*cos(x\n" " @ )/x**10 + 3628800*sin(x)/x**11\n" " end if" ) code = fcode(Piecewise((a, x < 0), (b, True)), assign_to="weird_name") assert code == expected code = fcode(Piecewise((x, x < 1), (x**2, x > 1), (sin(x), True)), standard=95) expected = " merge(x, merge(x**2, sin(x), x > 1), x < 1)" assert code == expected # Check that Piecewise without a True (default) condition error expr = Piecewise((x, x < 1), (x**2, x > 1), (sin(x), x > 0)) raises(ValueError, lambda: fcode(expr)) def test_wrap_fortran(): # "########################################################################" printer = FCodePrinter() lines = [ "C This is a long comment on a single line that must be wrapped properly to produce nice output", " this = is + a + long + and + nasty + fortran + statement + that * must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that * must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that * must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement(that)/must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement(that)/must + be + wrapped + properly", ] wrapped_lines = printer._wrap_fortran(lines) expected_lines = [ "C This is a long comment on a single line that must be wrapped", "C properly to produce nice output", " this = is + a + long + and + nasty + fortran + statement + that *", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that *", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that", " @ * must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that*", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that", " @ *must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement +", " @ that*must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that**", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that", " @ **must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement + that", " @ **must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement +", " @ that**must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement(that)/", " @ must + be + wrapped + properly", " this = is + a + long + and + nasty + fortran + statement(that)", " @ /must + be + wrapped + properly", ] for line in wrapped_lines: assert len(line) <= 72 for w, e in zip(wrapped_lines, expected_lines): assert w == e assert len(wrapped_lines) == len(expected_lines) def test_wrap_fortran_keep_d0(): printer = FCodePrinter() lines = [ ' this_variable_is_very_long_because_we_try_to_test_line_break=1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break = 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break = 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break = 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break = 10.0d0' ] expected = [ ' this_variable_is_very_long_because_we_try_to_test_line_break=1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =', ' @ 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =', ' @ 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =', ' @ 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =', ' @ 1.0d0', ' this_variable_is_very_long_because_we_try_to_test_line_break =', ' @ 10.0d0' ] assert printer._wrap_fortran(lines) == expected def test_settings(): raises(TypeError, lambda: fcode(S(4), method="garbage")) def test_free_form_code_line(): x, y = symbols('x,y') assert fcode(cos(x) + sin(y), source_format='free') == "sin(y) + cos(x)" def test_free_form_continuation_line(): x, y = symbols('x,y') result = fcode(((cos(x) + sin(y))**(7)).expand(), source_format='free') expected = ( 'sin(y)**7 + 7*sin(y)**6*cos(x) + 21*sin(y)**5*cos(x)**2 + 35*sin(y)**4* &\n' ' cos(x)**3 + 35*sin(y)**3*cos(x)**4 + 21*sin(y)**2*cos(x)**5 + 7* &\n' ' sin(y)*cos(x)**6 + cos(x)**7' ) assert result == expected def test_free_form_comment_line(): printer = FCodePrinter({'source_format': 'free'}) lines = [ "! This is a long comment on a single line that must be wrapped properly to produce nice output"] expected = [ '! This is a long comment on a single line that must be wrapped properly', '! to produce nice output'] assert printer._wrap_fortran(lines) == expected def test_loops(): n, m = symbols('n,m', integer=True) A = IndexedBase('A') x = IndexedBase('x') y = IndexedBase('y') i = Idx('i', m) j = Idx('j', n) expected = ( 'do i = 1, m\n' ' y(i) = 0\n' 'end do\n' 'do i = 1, m\n' ' do j = 1, n\n' ' y(i) = %(rhs)s\n' ' end do\n' 'end do' ) code = fcode(A[i, j]*x[j], assign_to=y[i], source_format='free') assert (code == expected % {'rhs': 'y(i) + A(i, j)*x(j)'} or code == expected % {'rhs': 'y(i) + x(j)*A(i, j)'} or code == expected % {'rhs': 'x(j)*A(i, j) + y(i)'} or code == expected % {'rhs': 'A(i, j)*x(j) + y(i)'}) def test_dummy_loops(): i, m = symbols('i m', integer=True, cls=Dummy) x = IndexedBase('x') y = IndexedBase('y') i = Idx(i, m) expected = ( 'do i_%(icount)i = 1, m_%(mcount)i\n' ' y(i_%(icount)i) = x(i_%(icount)i)\n' 'end do' ) % {'icount': i.label.dummy_index, 'mcount': m.dummy_index} code = fcode(x[i], assign_to=y[i], source_format='free') assert code == expected def test_fcode_Indexed_without_looking_for_contraction(): len_y = 5 y = IndexedBase('y', shape=(len_y,)) x = IndexedBase('x', shape=(len_y,)) Dy = IndexedBase('Dy', shape=(len_y-1,)) i = Idx('i', len_y-1) e=Eq(Dy[i], (y[i+1]-y[i])/(x[i+1]-x[i])) code0 = fcode(e.rhs, assign_to=e.lhs, contract=False) assert code0.endswith('Dy(i) = (y(i + 1) - y(i))/(x(i + 1) - x(i))') def test_derived_classes(): class MyFancyFCodePrinter(FCodePrinter): _default_settings = FCodePrinter._default_settings.copy() printer = MyFancyFCodePrinter() x = symbols('x') assert printer.doprint(sin(x), "bork") == " bork = sin(x)" def test_indent(): codelines = ( 'subroutine test(a)\n' 'integer :: a, i, j\n' '\n' 'do\n' 'do \n' 'do j = 1, 5\n' 'if (a>b) then\n' 'if(b>0) then\n' 'a = 3\n' 'donot_indent_me = 2\n' 'do_not_indent_me_either = 2\n' 'ifIam_indented_something_went_wrong = 2\n' 'if_I_am_indented_something_went_wrong = 2\n' 'end should not be unindented here\n' 'end if\n' 'endif\n' 'end do\n' 'end do\n' 'enddo\n' 'end subroutine\n' '\n' 'subroutine test2(a)\n' 'integer :: a\n' 'do\n' 'a = a + 1\n' 'end do \n' 'end subroutine\n' ) expected = ( 'subroutine test(a)\n' 'integer :: a, i, j\n' '\n' 'do\n' ' do \n' ' do j = 1, 5\n' ' if (a>b) then\n' ' if(b>0) then\n' ' a = 3\n' ' donot_indent_me = 2\n' ' do_not_indent_me_either = 2\n' ' ifIam_indented_something_went_wrong = 2\n' ' if_I_am_indented_something_went_wrong = 2\n' ' end should not be unindented here\n' ' end if\n' ' endif\n' ' end do\n' ' end do\n' 'enddo\n' 'end subroutine\n' '\n' 'subroutine test2(a)\n' 'integer :: a\n' 'do\n' ' a = a + 1\n' 'end do \n' 'end subroutine\n' ) p = FCodePrinter({'source_format': 'free'}) result = p.indent_code(codelines) assert result == expected def test_Matrix_printing(): x, y, z = symbols('x,y,z') # Test returning a Matrix mat = Matrix([x*y, Piecewise((2 + x, y>0), (y, True)), sin(z)]) A = MatrixSymbol('A', 3, 1) assert fcode(mat, A) == ( " A(1, 1) = x*y\n" " if (y > 0) then\n" " A(2, 1) = x + 2\n" " else\n" " A(2, 1) = y\n" " end if\n" " A(3, 1) = sin(z)") # Test using MatrixElements in expressions expr = Piecewise((2*A[2, 0], x > 0), (A[2, 0], True)) + sin(A[1, 0]) + A[0, 0] assert fcode(expr, standard=95) == ( " merge(2*A(3, 1), A(3, 1), x > 0) + sin(A(2, 1)) + A(1, 1)") # Test using MatrixElements in a Matrix q = MatrixSymbol('q', 5, 1) M = MatrixSymbol('M', 3, 3) m = Matrix([[sin(q[1,0]), 0, cos(q[2,0])], [q[1,0] + q[2,0], q[3, 0], 5], [2*q[4, 0]/q[1,0], sqrt(q[0,0]) + 4, 0]]) assert fcode(m, M) == ( " M(1, 1) = sin(q(2, 1))\n" " M(2, 1) = q(2, 1) + q(3, 1)\n" " M(3, 1) = 2*q(5, 1)/q(2, 1)\n" " M(1, 2) = 0\n" " M(2, 2) = q(4, 1)\n" " M(3, 2) = sqrt(q(1, 1)) + 4\n" " M(1, 3) = cos(q(3, 1))\n" " M(2, 3) = 5\n" " M(3, 3) = 0") def test_fcode_For(): x, y = symbols('x y') f = For(x, Range(0, 10, 2), [Assignment(y, x * y)]) sol = fcode(f) assert sol == (" do x = 0, 10, 2\n" " y = x*y\n" " end do") def test_fcode_Declaration(): def check(expr, ref, **kwargs): assert fcode(expr, standard=95, source_format='free', **kwargs) == ref i = symbols('i', integer=True) var1 = Variable.deduced(i) dcl1 = Declaration(var1) check(dcl1, "integer*4 :: i") x, y = symbols('x y') var2 = Variable(x, float32, value=42, attrs={value_const}) dcl2b = Declaration(var2) check(dcl2b, 'real*4, parameter :: x = 42') var3 = Variable(y, type=bool_) dcl3 = Declaration(var3) check(dcl3, 'logical :: y') check(float32, "real*4") check(float64, "real*8") check(real, "real*4", type_aliases={real: float32}) check(real, "real*8", type_aliases={real: float64}) 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(fcode(A[0, 0]) == " A(1, 1)") assert(fcode(3 * A[0, 0]) == " 3*A(1, 1)") F = C[0, 0].subs(C, A - B) assert(fcode(F) == " (A - B)(1, 1)") def test_aug_assign(): x = symbols('x') assert fcode(aug_assign(x, '+', 1), source_format='free') == 'x = x + 1' def test_While(): x = symbols('x') assert fcode(While(abs(x) > 1, [aug_assign(x, '-', 1)]), source_format='free') == ( 'do while (abs(x) > 1)\n' ' x = x - 1\n' 'end do' ) def test_FunctionPrototype_print(): x = symbols('x') n = symbols('n', integer=True) vx = Variable(x, type=real) vn = Variable(n, type=integer) fp1 = FunctionPrototype(real, 'power', [vx, vn]) # Should be changed to proper test once multi-line generation is working # see https://github.com/sympy/sympy/issues/15824 raises(NotImplementedError, lambda: fcode(fp1)) def test_FunctionDefinition_print(): x = symbols('x') n = symbols('n', integer=True) vx = Variable(x, type=real) vn = Variable(n, type=integer) body = [Assignment(x, x**n), Return(x)] fd1 = FunctionDefinition(real, 'power', [vx, vn], body) # Should be changed to proper test once multi-line generation is working # see https://github.com/sympy/sympy/issues/15824 raises(NotImplementedError, lambda: fcode(fd1)) def test_fcode_submodule(): # Test the compatibility sympy.printing.fcode module imports with warns_deprecated_sympy(): import sympy.printing.fcode # noqa:F401
9ad03b7ede189661eeeed1e08b69abfc2ce5c9d6780f2e510f8b4962787d906f
from sympy.tensor.toperators import PartialDerivative from sympy import ( Abs, Chi, Ci, CosineTransform, Dict, Ei, Eq, FallingFactorial, FiniteSet, Float, FourierTransform, Function, Indexed, IndexedBase, Integral, Interval, InverseCosineTransform, InverseFourierTransform, Derivative, InverseLaplaceTransform, InverseMellinTransform, InverseSineTransform, Lambda, LaplaceTransform, Limit, Matrix, Max, MellinTransform, Min, Mul, Order, Piecewise, Poly, ring, field, ZZ, Pow, Product, Range, Rational, RisingFactorial, rootof, RootSum, S, Shi, Si, SineTransform, Subs, Sum, Symbol, ImageSet, Tuple, Ynm, Znm, arg, asin, acsc, asinh, Mod, assoc_laguerre, assoc_legendre, beta, binomial, catalan, ceiling, chebyshevt, chebyshevu, conjugate, cot, coth, diff, dirichlet_eta, euler, exp, expint, factorial, factorial2, floor, gamma, gegenbauer, hermite, hyper, im, jacobi, laguerre, legendre, lerchphi, log, frac, meijerg, oo, polar_lift, polylog, re, root, sin, sqrt, symbols, uppergamma, zeta, subfactorial, totient, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, cos, tan, Wild, true, false, Equivalent, Not, Contains, divisor_sigma, SeqPer, SeqFormula, MatrixSlice, SeqAdd, SeqMul, fourier_series, pi, ConditionSet, ComplexRegion, fps, AccumBounds, reduced_totient, primenu, primeomega, SingularityFunction, stieltjes, mathieuc, mathieus, mathieucprime, mathieusprime, UnevaluatedExpr, Quaternion, I, KroneckerProduct, LambertW) from sympy.ntheory.factor_ import udivisor_sigma from sympy.abc import mu, tau from sympy.printing.latex import (latex, translate, greek_letters_set, tex_greek_dictionary, multiline_latex, latex_escape, LatexPrinter) from sympy.tensor.array import (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableSparseNDimArray, MutableDenseNDimArray, tensorproduct) from sympy.testing.pytest import XFAIL, raises from sympy.functions import DiracDelta, Heaviside, KroneckerDelta, LeviCivita from sympy.functions.combinatorial.numbers import bernoulli, bell, lucas, \ fibonacci, tribonacci from sympy.logic import Implies from sympy.logic.boolalg import And, Or, Xor from sympy.physics.control.lti import TransferFunction, Series, Parallel, Feedback from sympy.physics.quantum import Commutator, Operator from sympy.physics.units import meter, gibibyte, microgram, second from sympy.core.trace import Tr from sympy.combinatorics.permutations import \ Cycle, Permutation, AppliedPermutation from sympy.matrices.expressions.permutation import PermutationMatrix from sympy import MatrixSymbol, ln from sympy.vector import CoordSys3D, Cross, Curl, Dot, Divergence, Gradient, Laplacian from sympy.sets.setexpr import SetExpr from sympy.sets.sets import \ Union, Intersection, Complement, SymmetricDifference, ProductSet import sympy as sym class lowergamma(sym.lowergamma): pass # testing notation inheritance by a subclass with same name x, y, z, t, w, a, b, c, s, p = symbols('x y z t w a b c s p') k, m, n = symbols('k m n', integer=True) def test_printmethod(): class R(Abs): def _latex(self, printer): return "foo(%s)" % printer._print(self.args[0]) assert latex(R(x)) == "foo(x)" class R(Abs): def _latex(self, printer): return "foo" assert latex(R(x)) == "foo" def test_latex_basic(): assert latex(1 + x) == "x + 1" assert latex(x**2) == "x^{2}" assert latex(x**(1 + x)) == "x^{x + 1}" assert latex(x**3 + x + 1 + x**2) == "x^{3} + x^{2} + x + 1" assert latex(2*x*y) == "2 x y" assert latex(2*x*y, mul_symbol='dot') == r"2 \cdot x \cdot y" assert latex(3*x**2*y, mul_symbol='\\,') == r"3\,x^{2}\,y" assert latex(1.5*3**x, mul_symbol='\\,') == r"1.5 \cdot 3^{x}" assert latex(Mul(0, 1, evaluate=False)) == r'0 \cdot 1' assert latex(Mul(1, 0, evaluate=False)) == r'1 \cdot 0' assert latex(Mul(1, 1, evaluate=False)) == r'1 \cdot 1' assert latex(Mul(-1, 1, evaluate=False)) == r'\left(-1\right) 1' assert latex(Mul(1, 1, 1, evaluate=False)) == r'1 \cdot 1 \cdot 1' assert latex(Mul(1, 2, evaluate=False)) == r'1 \cdot 2' assert latex(Mul(1, S.Half, evaluate=False)) == r'1 \frac{1}{2}' assert latex(Mul(1, 1, S.Half, evaluate=False)) == \ r'1 \cdot 1 \frac{1}{2}' assert latex(Mul(1, 1, 2, 3, x, evaluate=False)) == \ r'1 \cdot 1 \cdot 2 \cdot 3 x' assert latex(Mul(1, -1, evaluate=False)) == r'1 \left(-1\right)' assert latex(Mul(4, 3, 2, 1, 0, y, x, evaluate=False)) == \ r'4 \cdot 3 \cdot 2 \cdot 1 \cdot 0 y x' assert latex(Mul(4, 3, 2, 1+z, 0, y, x, evaluate=False)) == \ r'4 \cdot 3 \cdot 2 \left(z + 1\right) 0 y x' assert latex(Mul(Rational(2, 3), Rational(5, 7), evaluate=False)) == \ r'\frac{2}{3} \frac{5}{7}' assert latex(1/x) == r"\frac{1}{x}" assert latex(1/x, fold_short_frac=True) == "1 / x" assert latex(-S(3)/2) == r"- \frac{3}{2}" assert latex(-S(3)/2, fold_short_frac=True) == r"- 3 / 2" assert latex(1/x**2) == r"\frac{1}{x^{2}}" assert latex(1/(x + y)/2) == r"\frac{1}{2 \left(x + y\right)}" assert latex(x/2) == r"\frac{x}{2}" assert latex(x/2, fold_short_frac=True) == "x / 2" assert latex((x + y)/(2*x)) == r"\frac{x + y}{2 x}" assert latex((x + y)/(2*x), fold_short_frac=True) == \ r"\left(x + y\right) / 2 x" assert latex((x + y)/(2*x), long_frac_ratio=0) == \ r"\frac{1}{2 x} \left(x + y\right)" assert latex((x + y)/x) == r"\frac{x + y}{x}" assert latex((x + y)/x, long_frac_ratio=3) == r"\frac{x + y}{x}" assert latex((2*sqrt(2)*x)/3) == r"\frac{2 \sqrt{2} x}{3}" assert latex((2*sqrt(2)*x)/3, long_frac_ratio=2) == \ r"\frac{2 x}{3} \sqrt{2}" assert latex(binomial(x, y)) == r"{\binom{x}{y}}" x_star = Symbol('x^*') f = Function('f') assert latex(x_star**2) == r"\left(x^{*}\right)^{2}" assert latex(x_star**2, parenthesize_super=False) == r"{x^{*}}^{2}" assert latex(Derivative(f(x_star), x_star,2)) == r"\frac{d^{2}}{d \left(x^{*}\right)^{2}} f{\left(x^{*} \right)}" assert latex(Derivative(f(x_star), x_star,2), parenthesize_super=False) == r"\frac{d^{2}}{d {x^{*}}^{2}} f{\left(x^{*} \right)}" assert latex(2*Integral(x, x)/3) == r"\frac{2 \int x\, dx}{3}" assert latex(2*Integral(x, x)/3, fold_short_frac=True) == \ r"\left(2 \int x\, dx\right) / 3" assert latex(sqrt(x)) == r"\sqrt{x}" assert latex(x**Rational(1, 3)) == r"\sqrt[3]{x}" assert latex(x**Rational(1, 3), root_notation=False) == r"x^{\frac{1}{3}}" assert latex(sqrt(x)**3) == r"x^{\frac{3}{2}}" assert latex(sqrt(x), itex=True) == r"\sqrt{x}" assert latex(x**Rational(1, 3), itex=True) == r"\root{3}{x}" assert latex(sqrt(x)**3, itex=True) == r"x^{\frac{3}{2}}" assert latex(x**Rational(3, 4)) == r"x^{\frac{3}{4}}" assert latex(x**Rational(3, 4), fold_frac_powers=True) == "x^{3/4}" assert latex((x + 1)**Rational(3, 4)) == \ r"\left(x + 1\right)^{\frac{3}{4}}" assert latex((x + 1)**Rational(3, 4), fold_frac_powers=True) == \ r"\left(x + 1\right)^{3/4}" assert latex(1.5e20*x) == r"1.5 \cdot 10^{20} x" assert latex(1.5e20*x, mul_symbol='dot') == r"1.5 \cdot 10^{20} \cdot x" assert latex(1.5e20*x, mul_symbol='times') == \ r"1.5 \times 10^{20} \times x" assert latex(1/sin(x)) == r"\frac{1}{\sin{\left(x \right)}}" assert latex(sin(x)**-1) == r"\frac{1}{\sin{\left(x \right)}}" assert latex(sin(x)**Rational(3, 2)) == \ r"\sin^{\frac{3}{2}}{\left(x \right)}" assert latex(sin(x)**Rational(3, 2), fold_frac_powers=True) == \ r"\sin^{3/2}{\left(x \right)}" assert latex(~x) == r"\neg x" assert latex(x & y) == r"x \wedge y" assert latex(x & y & z) == r"x \wedge y \wedge z" assert latex(x | y) == r"x \vee y" assert latex(x | y | z) == r"x \vee y \vee z" assert latex((x & y) | z) == r"z \vee \left(x \wedge y\right)" assert latex(Implies(x, y)) == r"x \Rightarrow y" assert latex(~(x >> ~y)) == r"x \not\Rightarrow \neg y" assert latex(Implies(Or(x,y), z)) == r"\left(x \vee y\right) \Rightarrow z" assert latex(Implies(z, Or(x,y))) == r"z \Rightarrow \left(x \vee y\right)" assert latex(~(x & y)) == r"\neg \left(x \wedge y\right)" assert latex(~x, symbol_names={x: "x_i"}) == r"\neg x_i" assert latex(x & y, symbol_names={x: "x_i", y: "y_i"}) == \ r"x_i \wedge y_i" assert latex(x & y & z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \ r"x_i \wedge y_i \wedge z_i" assert latex(x | y, symbol_names={x: "x_i", y: "y_i"}) == r"x_i \vee y_i" assert latex(x | y | z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \ r"x_i \vee y_i \vee z_i" assert latex((x & y) | z, symbol_names={x: "x_i", y: "y_i", z: "z_i"}) == \ r"z_i \vee \left(x_i \wedge y_i\right)" assert latex(Implies(x, y), symbol_names={x: "x_i", y: "y_i"}) == \ r"x_i \Rightarrow y_i" p = Symbol('p', positive=True) assert latex(exp(-p)*log(p)) == r"e^{- p} \log{\left(p \right)}" def test_latex_builtins(): assert latex(True) == r"\text{True}" assert latex(False) == r"\text{False}" assert latex(None) == r"\text{None}" assert latex(true) == r"\text{True}" assert latex(false) == r'\text{False}' def test_latex_SingularityFunction(): assert latex(SingularityFunction(x, 4, 5)) == \ r"{\left\langle x - 4 \right\rangle}^{5}" assert latex(SingularityFunction(x, -3, 4)) == \ r"{\left\langle x + 3 \right\rangle}^{4}" assert latex(SingularityFunction(x, 0, 4)) == \ r"{\left\langle x \right\rangle}^{4}" assert latex(SingularityFunction(x, a, n)) == \ r"{\left\langle - a + x \right\rangle}^{n}" assert latex(SingularityFunction(x, 4, -2)) == \ r"{\left\langle x - 4 \right\rangle}^{-2}" assert latex(SingularityFunction(x, 4, -1)) == \ r"{\left\langle x - 4 \right\rangle}^{-1}" def test_latex_cycle(): assert latex(Cycle(1, 2, 4)) == r"\left( 1\; 2\; 4\right)" assert latex(Cycle(1, 2)(4, 5, 6)) == \ r"\left( 1\; 2\right)\left( 4\; 5\; 6\right)" assert latex(Cycle()) == r"\left( \right)" def test_latex_permutation(): assert latex(Permutation(1, 2, 4)) == r"\left( 1\; 2\; 4\right)" assert latex(Permutation(1, 2)(4, 5, 6)) == \ r"\left( 1\; 2\right)\left( 4\; 5\; 6\right)" assert latex(Permutation()) == r"\left( \right)" assert latex(Permutation(2, 4)*Permutation(5)) == \ r"\left( 2\; 4\right)\left( 5\right)" assert latex(Permutation(5)) == r"\left( 5\right)" assert latex(Permutation(0, 1), perm_cyclic=False) == \ r"\begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}" assert latex(Permutation(0, 1)(2, 3), perm_cyclic=False) == \ r"\begin{pmatrix} 0 & 1 & 2 & 3 \\ 1 & 0 & 3 & 2 \end{pmatrix}" assert latex(Permutation(), perm_cyclic=False) == \ r"\left( \right)" def test_latex_Float(): assert latex(Float(1.0e100)) == r"1.0 \cdot 10^{100}" assert latex(Float(1.0e-100)) == r"1.0 \cdot 10^{-100}" assert latex(Float(1.0e-100), mul_symbol="times") == \ r"1.0 \times 10^{-100}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=2) == \ r"1.0 \cdot 10^{4}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=4) == \ r"1.0 \cdot 10^{4}" assert latex(Float('10000.0'), full_prec=False, min=-2, max=5) == \ r"10000.0" assert latex(Float('0.099999'), full_prec=True, min=-2, max=5) == \ r"9.99990000000000 \cdot 10^{-2}" def test_latex_vector_expressions(): A = CoordSys3D('A') assert latex(Cross(A.i, A.j*A.x*3+A.k)) == \ r"\mathbf{\hat{i}_{A}} \times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)" assert latex(Cross(A.i, A.j)) == \ r"\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}" assert latex(x*Cross(A.i, A.j)) == \ r"x \left(\mathbf{\hat{i}_{A}} \times \mathbf{\hat{j}_{A}}\right)" assert latex(Cross(x*A.i, A.j)) == \ r'- \mathbf{\hat{j}_{A}} \times \left((x)\mathbf{\hat{i}_{A}}\right)' assert latex(Curl(3*A.x*A.j)) == \ r"\nabla\times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(Curl(3*A.x*A.j+A.i)) == \ r"\nabla\times \left(\mathbf{\hat{i}_{A}} + (3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(Curl(3*x*A.x*A.j)) == \ r"\nabla\times \left((3 \mathbf{{x}_{A}} x)\mathbf{\hat{j}_{A}}\right)" assert latex(x*Curl(3*A.x*A.j)) == \ r"x \left(\nabla\times \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)\right)" assert latex(Divergence(3*A.x*A.j+A.i)) == \ r"\nabla\cdot \left(\mathbf{\hat{i}_{A}} + (3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(Divergence(3*A.x*A.j)) == \ r"\nabla\cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)" assert latex(x*Divergence(3*A.x*A.j)) == \ r"x \left(\nabla\cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}}\right)\right)" assert latex(Dot(A.i, A.j*A.x*3+A.k)) == \ r"\mathbf{\hat{i}_{A}} \cdot \left((3 \mathbf{{x}_{A}})\mathbf{\hat{j}_{A}} + \mathbf{\hat{k}_{A}}\right)" assert latex(Dot(A.i, A.j)) == \ r"\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}" assert latex(Dot(x*A.i, A.j)) == \ r"\mathbf{\hat{j}_{A}} \cdot \left((x)\mathbf{\hat{i}_{A}}\right)" assert latex(x*Dot(A.i, A.j)) == \ r"x \left(\mathbf{\hat{i}_{A}} \cdot \mathbf{\hat{j}_{A}}\right)" assert latex(Gradient(A.x)) == r"\nabla \mathbf{{x}_{A}}" assert latex(Gradient(A.x + 3*A.y)) == \ r"\nabla \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)" assert latex(x*Gradient(A.x)) == r"x \left(\nabla \mathbf{{x}_{A}}\right)" assert latex(Gradient(x*A.x)) == r"\nabla \left(\mathbf{{x}_{A}} x\right)" assert latex(Laplacian(A.x)) == r"\triangle \mathbf{{x}_{A}}" assert latex(Laplacian(A.x + 3*A.y)) == \ r"\triangle \left(\mathbf{{x}_{A}} + 3 \mathbf{{y}_{A}}\right)" assert latex(x*Laplacian(A.x)) == r"x \left(\triangle \mathbf{{x}_{A}}\right)" assert latex(Laplacian(x*A.x)) == r"\triangle \left(\mathbf{{x}_{A}} x\right)" def test_latex_symbols(): Gamma, lmbda, rho = symbols('Gamma, lambda, rho') tau, Tau, TAU, taU = symbols('tau, Tau, TAU, taU') assert latex(tau) == r"\tau" assert latex(Tau) == "T" assert latex(TAU) == r"\tau" assert latex(taU) == r"\tau" # Check that all capitalized greek letters are handled explicitly capitalized_letters = set(l.capitalize() for l in greek_letters_set) assert len(capitalized_letters - set(tex_greek_dictionary.keys())) == 0 assert latex(Gamma + lmbda) == r"\Gamma + \lambda" assert latex(Gamma * lmbda) == r"\Gamma \lambda" assert latex(Symbol('q1')) == r"q_{1}" assert latex(Symbol('q21')) == r"q_{21}" assert latex(Symbol('epsilon0')) == r"\epsilon_{0}" assert latex(Symbol('omega1')) == r"\omega_{1}" assert latex(Symbol('91')) == r"91" assert latex(Symbol('alpha_new')) == r"\alpha_{new}" assert latex(Symbol('C^orig')) == r"C^{orig}" assert latex(Symbol('x^alpha')) == r"x^{\alpha}" assert latex(Symbol('beta^alpha')) == r"\beta^{\alpha}" assert latex(Symbol('e^Alpha')) == r"e^{A}" assert latex(Symbol('omega_alpha^beta')) == r"\omega^{\beta}_{\alpha}" assert latex(Symbol('omega') ** Symbol('beta')) == r"\omega^{\beta}" @XFAIL def test_latex_symbols_failing(): rho, mass, volume = symbols('rho, mass, volume') assert latex( volume * rho == mass) == r"\rho \mathrm{volume} = \mathrm{mass}" assert latex(volume / mass * rho == 1) == \ r"\rho \mathrm{volume} {\mathrm{mass}}^{(-1)} = 1" assert latex(mass**3 * volume**3) == \ r"{\mathrm{mass}}^{3} \cdot {\mathrm{volume}}^{3}" def test_latex_functions(): assert latex(exp(x)) == "e^{x}" assert latex(exp(1) + exp(2)) == "e + e^{2}" f = Function('f') assert latex(f(x)) == r'f{\left(x \right)}' assert latex(f) == r'f' g = Function('g') assert latex(g(x, y)) == r'g{\left(x,y \right)}' assert latex(g) == r'g' h = Function('h') assert latex(h(x, y, z)) == r'h{\left(x,y,z \right)}' assert latex(h) == r'h' Li = Function('Li') assert latex(Li) == r'\operatorname{Li}' assert latex(Li(x)) == r'\operatorname{Li}{\left(x \right)}' mybeta = Function('beta') # not to be confused with the beta function assert latex(mybeta(x, y, z)) == r"\beta{\left(x,y,z \right)}" assert latex(beta(x, y)) == r'\operatorname{B}\left(x, y\right)' assert latex(beta(x, y)**2) == r'\operatorname{B}^{2}\left(x, y\right)' assert latex(mybeta(x)) == r"\beta{\left(x \right)}" assert latex(mybeta) == r"\beta" g = Function('gamma') # not to be confused with the gamma function assert latex(g(x, y, z)) == r"\gamma{\left(x,y,z \right)}" assert latex(g(x)) == r"\gamma{\left(x \right)}" assert latex(g) == r"\gamma" a1 = Function('a_1') assert latex(a1) == r"\operatorname{a_{1}}" assert latex(a1(x)) == r"\operatorname{a_{1}}{\left(x \right)}" # issue 5868 omega1 = Function('omega1') assert latex(omega1) == r"\omega_{1}" assert latex(omega1(x)) == r"\omega_{1}{\left(x \right)}" assert latex(sin(x)) == r"\sin{\left(x \right)}" assert latex(sin(x), fold_func_brackets=True) == r"\sin {x}" assert latex(sin(2*x**2), fold_func_brackets=True) == \ r"\sin {2 x^{2}}" assert latex(sin(x**2), fold_func_brackets=True) == \ r"\sin {x^{2}}" assert latex(asin(x)**2) == r"\operatorname{asin}^{2}{\left(x \right)}" assert latex(asin(x)**2, inv_trig_style="full") == \ r"\arcsin^{2}{\left(x \right)}" assert latex(asin(x)**2, inv_trig_style="power") == \ r"\sin^{-1}{\left(x \right)}^{2}" assert latex(asin(x**2), inv_trig_style="power", fold_func_brackets=True) == \ r"\sin^{-1} {x^{2}}" assert latex(acsc(x), inv_trig_style="full") == \ r"\operatorname{arccsc}{\left(x \right)}" assert latex(asinh(x), inv_trig_style="full") == \ r"\operatorname{arcsinh}{\left(x \right)}" assert latex(factorial(k)) == r"k!" assert latex(factorial(-k)) == r"\left(- k\right)!" assert latex(factorial(k)**2) == r"k!^{2}" assert latex(subfactorial(k)) == r"!k" assert latex(subfactorial(-k)) == r"!\left(- k\right)" assert latex(subfactorial(k)**2) == r"\left(!k\right)^{2}" assert latex(factorial2(k)) == r"k!!" assert latex(factorial2(-k)) == r"\left(- k\right)!!" assert latex(factorial2(k)**2) == r"k!!^{2}" assert latex(binomial(2, k)) == r"{\binom{2}{k}}" assert latex(binomial(2, k)**2) == r"{\binom{2}{k}}^{2}" assert latex(FallingFactorial(3, k)) == r"{\left(3\right)}_{k}" assert latex(RisingFactorial(3, k)) == r"{3}^{\left(k\right)}" assert latex(floor(x)) == r"\left\lfloor{x}\right\rfloor" assert latex(ceiling(x)) == r"\left\lceil{x}\right\rceil" assert latex(frac(x)) == r"\operatorname{frac}{\left(x\right)}" assert latex(floor(x)**2) == r"\left\lfloor{x}\right\rfloor^{2}" assert latex(ceiling(x)**2) == r"\left\lceil{x}\right\rceil^{2}" assert latex(frac(x)**2) == r"\operatorname{frac}{\left(x\right)}^{2}" assert latex(Min(x, 2, x**3)) == r"\min\left(2, x, x^{3}\right)" assert latex(Min(x, y)**2) == r"\min\left(x, y\right)^{2}" assert latex(Max(x, 2, x**3)) == r"\max\left(2, x, x^{3}\right)" assert latex(Max(x, y)**2) == r"\max\left(x, y\right)^{2}" assert latex(Abs(x)) == r"\left|{x}\right|" assert latex(Abs(x)**2) == r"\left|{x}\right|^{2}" assert latex(re(x)) == r"\operatorname{re}{\left(x\right)}" assert latex(re(x + y)) == \ r"\operatorname{re}{\left(x\right)} + \operatorname{re}{\left(y\right)}" assert latex(im(x)) == r"\operatorname{im}{\left(x\right)}" assert latex(conjugate(x)) == r"\overline{x}" assert latex(conjugate(x)**2) == r"\overline{x}^{2}" assert latex(conjugate(x**2)) == r"\overline{x}^{2}" assert latex(gamma(x)) == r"\Gamma\left(x\right)" w = Wild('w') assert latex(gamma(w)) == r"\Gamma\left(w\right)" assert latex(Order(x)) == r"O\left(x\right)" assert latex(Order(x, x)) == r"O\left(x\right)" assert latex(Order(x, (x, 0))) == r"O\left(x\right)" assert latex(Order(x, (x, oo))) == r"O\left(x; x\rightarrow \infty\right)" assert latex(Order(x - y, (x, y))) == \ r"O\left(x - y; x\rightarrow y\right)" assert latex(Order(x, x, y)) == \ r"O\left(x; \left( x, \ y\right)\rightarrow \left( 0, \ 0\right)\right)" assert latex(Order(x, x, y)) == \ r"O\left(x; \left( x, \ y\right)\rightarrow \left( 0, \ 0\right)\right)" assert latex(Order(x, (x, oo), (y, oo))) == \ r"O\left(x; \left( x, \ y\right)\rightarrow \left( \infty, \ \infty\right)\right)" assert latex(lowergamma(x, y)) == r'\gamma\left(x, y\right)' assert latex(lowergamma(x, y)**2) == r'\gamma^{2}\left(x, y\right)' assert latex(uppergamma(x, y)) == r'\Gamma\left(x, y\right)' assert latex(uppergamma(x, y)**2) == r'\Gamma^{2}\left(x, y\right)' assert latex(cot(x)) == r'\cot{\left(x \right)}' assert latex(coth(x)) == r'\coth{\left(x \right)}' assert latex(re(x)) == r'\operatorname{re}{\left(x\right)}' assert latex(im(x)) == r'\operatorname{im}{\left(x\right)}' assert latex(root(x, y)) == r'x^{\frac{1}{y}}' assert latex(arg(x)) == r'\arg{\left(x \right)}' assert latex(zeta(x)) == r"\zeta\left(x\right)" assert latex(zeta(x)**2) == r"\zeta^{2}\left(x\right)" assert latex(zeta(x, y)) == r"\zeta\left(x, y\right)" assert latex(zeta(x, y)**2) == r"\zeta^{2}\left(x, y\right)" assert latex(dirichlet_eta(x)) == r"\eta\left(x\right)" assert latex(dirichlet_eta(x)**2) == r"\eta^{2}\left(x\right)" assert latex(polylog(x, y)) == r"\operatorname{Li}_{x}\left(y\right)" assert latex( polylog(x, y)**2) == r"\operatorname{Li}_{x}^{2}\left(y\right)" assert latex(lerchphi(x, y, n)) == r"\Phi\left(x, y, n\right)" assert latex(lerchphi(x, y, n)**2) == r"\Phi^{2}\left(x, y, n\right)" assert latex(stieltjes(x)) == r"\gamma_{x}" assert latex(stieltjes(x)**2) == r"\gamma_{x}^{2}" assert latex(stieltjes(x, y)) == r"\gamma_{x}\left(y\right)" assert latex(stieltjes(x, y)**2) == r"\gamma_{x}\left(y\right)^{2}" assert latex(elliptic_k(z)) == r"K\left(z\right)" assert latex(elliptic_k(z)**2) == r"K^{2}\left(z\right)" assert latex(elliptic_f(x, y)) == r"F\left(x\middle| y\right)" assert latex(elliptic_f(x, y)**2) == r"F^{2}\left(x\middle| y\right)" assert latex(elliptic_e(x, y)) == r"E\left(x\middle| y\right)" assert latex(elliptic_e(x, y)**2) == r"E^{2}\left(x\middle| y\right)" assert latex(elliptic_e(z)) == r"E\left(z\right)" assert latex(elliptic_e(z)**2) == r"E^{2}\left(z\right)" assert latex(elliptic_pi(x, y, z)) == r"\Pi\left(x; y\middle| z\right)" assert latex(elliptic_pi(x, y, z)**2) == \ r"\Pi^{2}\left(x; y\middle| z\right)" assert latex(elliptic_pi(x, y)) == r"\Pi\left(x\middle| y\right)" assert latex(elliptic_pi(x, y)**2) == r"\Pi^{2}\left(x\middle| y\right)" assert latex(Ei(x)) == r'\operatorname{Ei}{\left(x \right)}' assert latex(Ei(x)**2) == r'\operatorname{Ei}^{2}{\left(x \right)}' assert latex(expint(x, y)) == r'\operatorname{E}_{x}\left(y\right)' assert latex(expint(x, y)**2) == r'\operatorname{E}_{x}^{2}\left(y\right)' assert latex(Shi(x)**2) == r'\operatorname{Shi}^{2}{\left(x \right)}' assert latex(Si(x)**2) == r'\operatorname{Si}^{2}{\left(x \right)}' assert latex(Ci(x)**2) == r'\operatorname{Ci}^{2}{\left(x \right)}' assert latex(Chi(x)**2) == r'\operatorname{Chi}^{2}\left(x\right)' assert latex(Chi(x)) == r'\operatorname{Chi}\left(x\right)' assert latex(jacobi(n, a, b, x)) == \ r'P_{n}^{\left(a,b\right)}\left(x\right)' assert latex(jacobi(n, a, b, x)**2) == \ r'\left(P_{n}^{\left(a,b\right)}\left(x\right)\right)^{2}' assert latex(gegenbauer(n, a, x)) == \ r'C_{n}^{\left(a\right)}\left(x\right)' assert latex(gegenbauer(n, a, x)**2) == \ r'\left(C_{n}^{\left(a\right)}\left(x\right)\right)^{2}' assert latex(chebyshevt(n, x)) == r'T_{n}\left(x\right)' assert latex(chebyshevt(n, x)**2) == \ r'\left(T_{n}\left(x\right)\right)^{2}' assert latex(chebyshevu(n, x)) == r'U_{n}\left(x\right)' assert latex(chebyshevu(n, x)**2) == \ r'\left(U_{n}\left(x\right)\right)^{2}' assert latex(legendre(n, x)) == r'P_{n}\left(x\right)' assert latex(legendre(n, x)**2) == r'\left(P_{n}\left(x\right)\right)^{2}' assert latex(assoc_legendre(n, a, x)) == \ r'P_{n}^{\left(a\right)}\left(x\right)' assert latex(assoc_legendre(n, a, x)**2) == \ r'\left(P_{n}^{\left(a\right)}\left(x\right)\right)^{2}' assert latex(laguerre(n, x)) == r'L_{n}\left(x\right)' assert latex(laguerre(n, x)**2) == r'\left(L_{n}\left(x\right)\right)^{2}' assert latex(assoc_laguerre(n, a, x)) == \ r'L_{n}^{\left(a\right)}\left(x\right)' assert latex(assoc_laguerre(n, a, x)**2) == \ r'\left(L_{n}^{\left(a\right)}\left(x\right)\right)^{2}' assert latex(hermite(n, x)) == r'H_{n}\left(x\right)' assert latex(hermite(n, x)**2) == r'\left(H_{n}\left(x\right)\right)^{2}' theta = Symbol("theta", real=True) phi = Symbol("phi", real=True) assert latex(Ynm(n, m, theta, phi)) == r'Y_{n}^{m}\left(\theta,\phi\right)' assert latex(Ynm(n, m, theta, phi)**3) == \ r'\left(Y_{n}^{m}\left(\theta,\phi\right)\right)^{3}' assert latex(Znm(n, m, theta, phi)) == r'Z_{n}^{m}\left(\theta,\phi\right)' assert latex(Znm(n, m, theta, phi)**3) == \ r'\left(Z_{n}^{m}\left(\theta,\phi\right)\right)^{3}' # Test latex printing of function names with "_" assert latex(polar_lift(0)) == \ r"\operatorname{polar\_lift}{\left(0 \right)}" assert latex(polar_lift(0)**3) == \ r"\operatorname{polar\_lift}^{3}{\left(0 \right)}" assert latex(totient(n)) == r'\phi\left(n\right)' assert latex(totient(n) ** 2) == r'\left(\phi\left(n\right)\right)^{2}' assert latex(reduced_totient(n)) == r'\lambda\left(n\right)' assert latex(reduced_totient(n) ** 2) == \ r'\left(\lambda\left(n\right)\right)^{2}' assert latex(divisor_sigma(x)) == r"\sigma\left(x\right)" assert latex(divisor_sigma(x)**2) == r"\sigma^{2}\left(x\right)" assert latex(divisor_sigma(x, y)) == r"\sigma_y\left(x\right)" assert latex(divisor_sigma(x, y)**2) == r"\sigma^{2}_y\left(x\right)" assert latex(udivisor_sigma(x)) == r"\sigma^*\left(x\right)" assert latex(udivisor_sigma(x)**2) == r"\sigma^*^{2}\left(x\right)" assert latex(udivisor_sigma(x, y)) == r"\sigma^*_y\left(x\right)" assert latex(udivisor_sigma(x, y)**2) == r"\sigma^*^{2}_y\left(x\right)" assert latex(primenu(n)) == r'\nu\left(n\right)' assert latex(primenu(n) ** 2) == r'\left(\nu\left(n\right)\right)^{2}' assert latex(primeomega(n)) == r'\Omega\left(n\right)' assert latex(primeomega(n) ** 2) == \ r'\left(\Omega\left(n\right)\right)^{2}' assert latex(LambertW(n)) == r'W\left(n\right)' assert latex(LambertW(n, -1)) == r'W_{-1}\left(n\right)' assert latex(LambertW(n, k)) == r'W_{k}\left(n\right)' assert latex(Mod(x, 7)) == r'x\bmod{7}' assert latex(Mod(x + 1, 7)) == r'\left(x + 1\right)\bmod{7}' assert latex(Mod(2 * x, 7)) == r'2 x\bmod{7}' assert latex(Mod(x, 7) + 1) == r'\left(x\bmod{7}\right) + 1' assert latex(2 * Mod(x, 7)) == r'2 \left(x\bmod{7}\right)' # some unknown function name should get rendered with \operatorname fjlkd = Function('fjlkd') assert latex(fjlkd(x)) == r'\operatorname{fjlkd}{\left(x \right)}' # even when it is referred to without an argument assert latex(fjlkd) == r'\operatorname{fjlkd}' # test that notation passes to subclasses of the same name only def test_function_subclass_different_name(): class mygamma(gamma): pass assert latex(mygamma) == r"\operatorname{mygamma}" assert latex(mygamma(x)) == r"\operatorname{mygamma}{\left(x \right)}" def test_hyper_printing(): from sympy import pi from sympy.abc import x, z assert latex(meijerg(Tuple(pi, pi, x), Tuple(1), (0, 1), Tuple(1, 2, 3/pi), z)) == \ r'{G_{4, 5}^{2, 3}\left(\begin{matrix} \pi, \pi, x & 1 \\0, 1 & 1, 2, '\ r'\frac{3}{\pi} \end{matrix} \middle| {z} \right)}' assert latex(meijerg(Tuple(), Tuple(1), (0,), Tuple(), z)) == \ r'{G_{1, 1}^{1, 0}\left(\begin{matrix} & 1 \\0 & \end{matrix} \middle| {z} \right)}' assert latex(hyper((x, 2), (3,), z)) == \ r'{{}_{2}F_{1}\left(\begin{matrix} x, 2 ' \ r'\\ 3 \end{matrix}\middle| {z} \right)}' assert latex(hyper(Tuple(), Tuple(1), z)) == \ r'{{}_{0}F_{1}\left(\begin{matrix} ' \ r'\\ 1 \end{matrix}\middle| {z} \right)}' def test_latex_bessel(): from sympy.functions.special.bessel import (besselj, bessely, besseli, besselk, hankel1, hankel2, jn, yn, hn1, hn2) from sympy.abc import z assert latex(besselj(n, z**2)**k) == r'J^{k}_{n}\left(z^{2}\right)' assert latex(bessely(n, z)) == r'Y_{n}\left(z\right)' assert latex(besseli(n, z)) == r'I_{n}\left(z\right)' assert latex(besselk(n, z)) == r'K_{n}\left(z\right)' assert latex(hankel1(n, z**2)**2) == \ r'\left(H^{(1)}_{n}\left(z^{2}\right)\right)^{2}' assert latex(hankel2(n, z)) == r'H^{(2)}_{n}\left(z\right)' assert latex(jn(n, z)) == r'j_{n}\left(z\right)' assert latex(yn(n, z)) == r'y_{n}\left(z\right)' assert latex(hn1(n, z)) == r'h^{(1)}_{n}\left(z\right)' assert latex(hn2(n, z)) == r'h^{(2)}_{n}\left(z\right)' def test_latex_fresnel(): from sympy.functions.special.error_functions import (fresnels, fresnelc) from sympy.abc import z assert latex(fresnels(z)) == r'S\left(z\right)' assert latex(fresnelc(z)) == r'C\left(z\right)' assert latex(fresnels(z)**2) == r'S^{2}\left(z\right)' assert latex(fresnelc(z)**2) == r'C^{2}\left(z\right)' def test_latex_brackets(): assert latex((-1)**x) == r"\left(-1\right)^{x}" def test_latex_indexed(): Psi_symbol = Symbol('Psi_0', complex=True, real=False) Psi_indexed = IndexedBase(Symbol('Psi', complex=True, real=False)) symbol_latex = latex(Psi_symbol * conjugate(Psi_symbol)) indexed_latex = latex(Psi_indexed[0] * conjugate(Psi_indexed[0])) # \\overline{{\\Psi}_{0}} {\\Psi}_{0} vs. \\Psi_{0} \\overline{\\Psi_{0}} assert symbol_latex == '\\Psi_{0} \\overline{\\Psi_{0}}' assert indexed_latex == '\\overline{{\\Psi}_{0}} {\\Psi}_{0}' # Symbol('gamma') gives r'\gamma' assert latex(Indexed('x1', Symbol('i'))) == '{x_{1}}_{i}' assert latex(IndexedBase('gamma')) == r'\gamma' assert latex(IndexedBase('a b')) == 'a b' assert latex(IndexedBase('a_b')) == 'a_{b}' def test_latex_derivatives(): # regular "d" for ordinary derivatives assert latex(diff(x**3, x, evaluate=False)) == \ r"\frac{d}{d x} x^{3}" assert latex(diff(sin(x) + x**2, x, evaluate=False)) == \ r"\frac{d}{d x} \left(x^{2} + \sin{\left(x \right)}\right)" assert latex(diff(diff(sin(x) + x**2, x, evaluate=False), evaluate=False))\ == \ r"\frac{d^{2}}{d x^{2}} \left(x^{2} + \sin{\left(x \right)}\right)" assert latex(diff(diff(diff(sin(x) + x**2, x, evaluate=False), evaluate=False), evaluate=False)) == \ r"\frac{d^{3}}{d x^{3}} \left(x^{2} + \sin{\left(x \right)}\right)" # \partial for partial derivatives assert latex(diff(sin(x * y), x, evaluate=False)) == \ r"\frac{\partial}{\partial x} \sin{\left(x y \right)}" assert latex(diff(sin(x * y) + x**2, x, evaluate=False)) == \ r"\frac{\partial}{\partial x} \left(x^{2} + \sin{\left(x y \right)}\right)" assert latex(diff(diff(sin(x*y) + x**2, x, evaluate=False), x, evaluate=False)) == \ r"\frac{\partial^{2}}{\partial x^{2}} \left(x^{2} + \sin{\left(x y \right)}\right)" assert latex(diff(diff(diff(sin(x*y) + x**2, x, evaluate=False), x, evaluate=False), x, evaluate=False)) == \ r"\frac{\partial^{3}}{\partial x^{3}} \left(x^{2} + \sin{\left(x y \right)}\right)" # mixed partial derivatives f = Function("f") assert latex(diff(diff(f(x, y), x, evaluate=False), y, evaluate=False)) == \ r"\frac{\partial^{2}}{\partial y\partial x} " + latex(f(x, y)) assert latex(diff(diff(diff(f(x, y), x, evaluate=False), x, evaluate=False), y, evaluate=False)) == \ r"\frac{\partial^{3}}{\partial y\partial x^{2}} " + latex(f(x, y)) # for negative nested Derivative assert latex(diff(-diff(y**2,x,evaluate=False),x,evaluate=False)) == r'\frac{d}{d x} \left(- \frac{d}{d x} y^{2}\right)' assert latex(diff(diff(-diff(diff(y,x,evaluate=False),x,evaluate=False),x,evaluate=False),x,evaluate=False)) == \ r'\frac{d^{2}}{d x^{2}} \left(- \frac{d^{2}}{d x^{2}} y\right)' # use ordinary d when one of the variables has been integrated out assert latex(diff(Integral(exp(-x*y), (x, 0, oo)), y, evaluate=False)) == \ r"\frac{d}{d y} \int\limits_{0}^{\infty} e^{- x y}\, dx" # Derivative wrapped in power: assert latex(diff(x, x, evaluate=False)**2) == \ r"\left(\frac{d}{d x} x\right)^{2}" assert latex(diff(f(x), x)**2) == \ r"\left(\frac{d}{d x} f{\left(x \right)}\right)^{2}" assert latex(diff(f(x), (x, n))) == \ r"\frac{d^{n}}{d x^{n}} f{\left(x \right)}" x1 = Symbol('x1') x2 = Symbol('x2') assert latex(diff(f(x1, x2), x1)) == r'\frac{\partial}{\partial x_{1}} f{\left(x_{1},x_{2} \right)}' n1 = Symbol('n1') assert latex(diff(f(x), (x, n1))) == r'\frac{d^{n_{1}}}{d x^{n_{1}}} f{\left(x \right)}' n2 = Symbol('n2') assert latex(diff(f(x), (x, Max(n1, n2)))) == \ r'\frac{d^{\max\left(n_{1}, n_{2}\right)}}{d x^{\max\left(n_{1}, n_{2}\right)}} f{\left(x \right)}' def test_latex_subs(): assert latex(Subs(x*y, ( x, y), (1, 2))) == r'\left. x y \right|_{\substack{ x=1\\ y=2 }}' def test_latex_integrals(): assert latex(Integral(log(x), x)) == r"\int \log{\left(x \right)}\, dx" assert latex(Integral(x**2, (x, 0, 1))) == \ r"\int\limits_{0}^{1} x^{2}\, dx" assert latex(Integral(x**2, (x, 10, 20))) == \ r"\int\limits_{10}^{20} x^{2}\, dx" assert latex(Integral(y*x**2, (x, 0, 1), y)) == \ r"\int\int\limits_{0}^{1} x^{2} y\, dx\, dy" assert latex(Integral(y*x**2, (x, 0, 1), y), mode='equation*') == \ r"\begin{equation*}\int\int\limits_{0}^{1} x^{2} y\, dx\, dy\end{equation*}" assert latex(Integral(y*x**2, (x, 0, 1), y), mode='equation*', itex=True) \ == r"$$\int\int_{0}^{1} x^{2} y\, dx\, dy$$" assert latex(Integral(x, (x, 0))) == r"\int\limits^{0} x\, dx" assert latex(Integral(x*y, x, y)) == r"\iint x y\, dx\, dy" assert latex(Integral(x*y*z, x, y, z)) == r"\iiint x y z\, dx\, dy\, dz" assert latex(Integral(x*y*z*t, x, y, z, t)) == \ r"\iiiint t x y z\, dx\, dy\, dz\, dt" assert latex(Integral(x, x, x, x, x, x, x)) == \ r"\int\int\int\int\int\int x\, dx\, dx\, dx\, dx\, dx\, dx" assert latex(Integral(x, x, y, (z, 0, 1))) == \ r"\int\limits_{0}^{1}\int\int x\, dx\, dy\, dz" # for negative nested Integral assert latex(Integral(-Integral(y**2,x),x)) == \ r'\int \left(- \int y^{2}\, dx\right)\, dx' assert latex(Integral(-Integral(-Integral(y,x),x),x)) == \ r'\int \left(- \int \left(- \int y\, dx\right)\, dx\right)\, dx' # fix issue #10806 assert latex(Integral(z, z)**2) == r"\left(\int z\, dz\right)^{2}" assert latex(Integral(x + z, z)) == r"\int \left(x + z\right)\, dz" assert latex(Integral(x+z/2, z)) == \ r"\int \left(x + \frac{z}{2}\right)\, dz" assert latex(Integral(x**y, z)) == r"\int x^{y}\, dz" def test_latex_sets(): for s in (frozenset, set): assert latex(s([x*y, x**2])) == r"\left\{x^{2}, x y\right\}" assert latex(s(range(1, 6))) == r"\left\{1, 2, 3, 4, 5\right\}" assert latex(s(range(1, 13))) == \ r"\left\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\right\}" s = FiniteSet assert latex(s(*[x*y, x**2])) == r"\left\{x^{2}, x y\right\}" assert latex(s(*range(1, 6))) == r"\left\{1, 2, 3, 4, 5\right\}" assert latex(s(*range(1, 13))) == \ r"\left\{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12\right\}" def test_latex_SetExpr(): iv = Interval(1, 3) se = SetExpr(iv) assert latex(se) == r"SetExpr\left(\left[1, 3\right]\right)" def test_latex_Range(): assert latex(Range(1, 51)) == r'\left\{1, 2, \ldots, 50\right\}' assert latex(Range(1, 4)) == r'\left\{1, 2, 3\right\}' assert latex(Range(0, 3, 1)) == r'\left\{0, 1, 2\right\}' assert latex(Range(0, 30, 1)) == r'\left\{0, 1, \ldots, 29\right\}' assert latex(Range(30, 1, -1)) == r'\left\{30, 29, \ldots, 2\right\}' assert latex(Range(0, oo, 2)) == r'\left\{0, 2, \ldots\right\}' assert latex(Range(oo, -2, -2)) == r'\left\{\ldots, 2, 0\right\}' assert latex(Range(-2, -oo, -1)) == r'\left\{-2, -3, \ldots\right\}' assert latex(Range(-oo, oo)) == r'\left\{\ldots, -1, 0, 1, \ldots\right\}' assert latex(Range(oo, -oo, -1)) == \ r'\left\{\ldots, 1, 0, -1, \ldots\right\}' a, b, c = symbols('a:c') assert latex(Range(a, b, c)) == r'Range\left(a, b, c\right)' assert latex(Range(a, 10, 1)) == r'Range\left(a, 10, 1\right)' assert latex(Range(0, b, 1)) == r'Range\left(0, b, 1\right)' assert latex(Range(0, 10, c)) == r'Range\left(0, 10, c\right)' def test_latex_sequences(): s1 = SeqFormula(a**2, (0, oo)) s2 = SeqPer((1, 2)) latex_str = r'\left[0, 1, 4, 9, \ldots\right]' assert latex(s1) == latex_str latex_str = r'\left[1, 2, 1, 2, \ldots\right]' assert latex(s2) == latex_str s3 = SeqFormula(a**2, (0, 2)) s4 = SeqPer((1, 2), (0, 2)) latex_str = r'\left[0, 1, 4\right]' assert latex(s3) == latex_str latex_str = r'\left[1, 2, 1\right]' assert latex(s4) == latex_str s5 = SeqFormula(a**2, (-oo, 0)) s6 = SeqPer((1, 2), (-oo, 0)) latex_str = r'\left[\ldots, 9, 4, 1, 0\right]' assert latex(s5) == latex_str latex_str = r'\left[\ldots, 2, 1, 2, 1\right]' assert latex(s6) == latex_str latex_str = r'\left[1, 3, 5, 11, \ldots\right]' assert latex(SeqAdd(s1, s2)) == latex_str latex_str = r'\left[1, 3, 5\right]' assert latex(SeqAdd(s3, s4)) == latex_str latex_str = r'\left[\ldots, 11, 5, 3, 1\right]' assert latex(SeqAdd(s5, s6)) == latex_str latex_str = r'\left[0, 2, 4, 18, \ldots\right]' assert latex(SeqMul(s1, s2)) == latex_str latex_str = r'\left[0, 2, 4\right]' assert latex(SeqMul(s3, s4)) == latex_str latex_str = r'\left[\ldots, 18, 4, 2, 0\right]' assert latex(SeqMul(s5, s6)) == latex_str # Sequences with symbolic limits, issue 12629 s7 = SeqFormula(a**2, (a, 0, x)) latex_str = r'\left\{a^{2}\right\}_{a=0}^{x}' assert latex(s7) == latex_str b = Symbol('b') s8 = SeqFormula(b*a**2, (a, 0, 2)) latex_str = r'\left[0, b, 4 b\right]' assert latex(s8) == latex_str def test_latex_FourierSeries(): latex_str = \ r'2 \sin{\left(x \right)} - \sin{\left(2 x \right)} + \frac{2 \sin{\left(3 x \right)}}{3} + \ldots' assert latex(fourier_series(x, (x, -pi, pi))) == latex_str def test_latex_FormalPowerSeries(): latex_str = r'\sum_{k=1}^{\infty} - \frac{\left(-1\right)^{- k} x^{k}}{k}' assert latex(fps(log(1 + x))) == latex_str def test_latex_intervals(): a = Symbol('a', real=True) assert latex(Interval(0, 0)) == r"\left\{0\right\}" assert latex(Interval(0, a)) == r"\left[0, a\right]" assert latex(Interval(0, a, False, False)) == r"\left[0, a\right]" assert latex(Interval(0, a, True, False)) == r"\left(0, a\right]" assert latex(Interval(0, a, False, True)) == r"\left[0, a\right)" assert latex(Interval(0, a, True, True)) == r"\left(0, a\right)" def test_latex_AccumuBounds(): a = Symbol('a', real=True) assert latex(AccumBounds(0, 1)) == r"\left\langle 0, 1\right\rangle" assert latex(AccumBounds(0, a)) == r"\left\langle 0, a\right\rangle" assert latex(AccumBounds(a + 1, a + 2)) == \ r"\left\langle a + 1, a + 2\right\rangle" def test_latex_emptyset(): assert latex(S.EmptySet) == r"\emptyset" def test_latex_universalset(): assert latex(S.UniversalSet) == r"\mathbb{U}" def test_latex_commutator(): A = Operator('A') B = Operator('B') comm = Commutator(B, A) assert latex(comm.doit()) == r"- (A B - B A)" def test_latex_union(): assert latex(Union(Interval(0, 1), Interval(2, 3))) == \ r"\left[0, 1\right] \cup \left[2, 3\right]" assert latex(Union(Interval(1, 1), Interval(2, 2), Interval(3, 4))) == \ r"\left\{1, 2\right\} \cup \left[3, 4\right]" def test_latex_intersection(): assert latex(Intersection(Interval(0, 1), Interval(x, y))) == \ r"\left[0, 1\right] \cap \left[x, y\right]" def test_latex_symmetric_difference(): assert latex(SymmetricDifference(Interval(2, 5), Interval(4, 7), evaluate=False)) == \ r'\left[2, 5\right] \triangle \left[4, 7\right]' def test_latex_Complement(): assert latex(Complement(S.Reals, S.Naturals)) == \ r"\mathbb{R} \setminus \mathbb{N}" def test_latex_productset(): line = Interval(0, 1) bigline = Interval(0, 10) fset = FiniteSet(1, 2, 3) assert latex(line**2) == r"%s^{2}" % latex(line) assert latex(line**10) == r"%s^{10}" % latex(line) assert latex((line * bigline * fset).flatten()) == r"%s \times %s \times %s" % ( latex(line), latex(bigline), latex(fset)) def test_set_operators_parenthesis(): a, b, c, d = symbols('a:d') A = FiniteSet(a) B = FiniteSet(b) C = FiniteSet(c) D = FiniteSet(d) U1 = Union(A, B, evaluate=False) U2 = Union(C, D, evaluate=False) I1 = Intersection(A, B, evaluate=False) I2 = Intersection(C, D, evaluate=False) C1 = Complement(A, B, evaluate=False) C2 = Complement(C, D, evaluate=False) D1 = SymmetricDifference(A, B, evaluate=False) D2 = SymmetricDifference(C, D, evaluate=False) # XXX ProductSet does not support evaluate keyword P1 = ProductSet(A, B) P2 = ProductSet(C, D) assert latex(Intersection(A, U2, evaluate=False)) == \ '\\left\\{a\\right\\} \\cap ' \ '\\left(\\left\\{c\\right\\} \\cup \\left\\{d\\right\\}\\right)' assert latex(Intersection(U1, U2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\cup \\left\\{b\\right\\}\\right) ' \ '\\cap \\left(\\left\\{c\\right\\} \\cup \\left\\{d\\right\\}\\right)' assert latex(Intersection(C1, C2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\setminus ' \ '\\left\\{b\\right\\}\\right) \\cap \\left(\\left\\{c\\right\\} ' \ '\\setminus \\left\\{d\\right\\}\\right)' assert latex(Intersection(D1, D2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\triangle ' \ '\\left\\{b\\right\\}\\right) \\cap \\left(\\left\\{c\\right\\} ' \ '\\triangle \\left\\{d\\right\\}\\right)' assert latex(Intersection(P1, P2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\times \\left\\{b\\right\\}\\right) ' \ '\\cap \\left(\\left\\{c\\right\\} \\times ' \ '\\left\\{d\\right\\}\\right)' assert latex(Union(A, I2, evaluate=False)) == \ '\\left\\{a\\right\\} \\cup ' \ '\\left(\\left\\{c\\right\\} \\cap \\left\\{d\\right\\}\\right)' assert latex(Union(I1, I2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\cap ''\\left\\{b\\right\\}\\right) ' \ '\\cup \\left(\\left\\{c\\right\\} \\cap \\left\\{d\\right\\}\\right)' assert latex(Union(C1, C2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\setminus ' \ '\\left\\{b\\right\\}\\right) \\cup \\left(\\left\\{c\\right\\} ' \ '\\setminus \\left\\{d\\right\\}\\right)' assert latex(Union(D1, D2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\triangle ' \ '\\left\\{b\\right\\}\\right) \\cup \\left(\\left\\{c\\right\\} ' \ '\\triangle \\left\\{d\\right\\}\\right)' assert latex(Union(P1, P2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\times \\left\\{b\\right\\}\\right) ' \ '\\cup \\left(\\left\\{c\\right\\} \\times ' \ '\\left\\{d\\right\\}\\right)' assert latex(Complement(A, C2, evaluate=False)) == \ '\\left\\{a\\right\\} \\setminus \\left(\\left\\{c\\right\\} ' \ '\\setminus \\left\\{d\\right\\}\\right)' assert latex(Complement(U1, U2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\cup \\left\\{b\\right\\}\\right) ' \ '\\setminus \\left(\\left\\{c\\right\\} \\cup ' \ '\\left\\{d\\right\\}\\right)' assert latex(Complement(I1, I2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\cap \\left\\{b\\right\\}\\right) ' \ '\\setminus \\left(\\left\\{c\\right\\} \\cap ' \ '\\left\\{d\\right\\}\\right)' assert latex(Complement(D1, D2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\triangle ' \ '\\left\\{b\\right\\}\\right) \\setminus ' \ '\\left(\\left\\{c\\right\\} \\triangle \\left\\{d\\right\\}\\right)' assert latex(Complement(P1, P2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\times \\left\\{b\\right\\}\\right) '\ '\\setminus \\left(\\left\\{c\\right\\} \\times '\ '\\left\\{d\\right\\}\\right)' assert latex(SymmetricDifference(A, D2, evaluate=False)) == \ '\\left\\{a\\right\\} \\triangle \\left(\\left\\{c\\right\\} ' \ '\\triangle \\left\\{d\\right\\}\\right)' assert latex(SymmetricDifference(U1, U2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\cup \\left\\{b\\right\\}\\right) ' \ '\\triangle \\left(\\left\\{c\\right\\} \\cup ' \ '\\left\\{d\\right\\}\\right)' assert latex(SymmetricDifference(I1, I2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\cap \\left\\{b\\right\\}\\right) ' \ '\\triangle \\left(\\left\\{c\\right\\} \\cap ' \ '\\left\\{d\\right\\}\\right)' assert latex(SymmetricDifference(C1, C2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\setminus ' \ '\\left\\{b\\right\\}\\right) \\triangle ' \ '\\left(\\left\\{c\\right\\} \\setminus \\left\\{d\\right\\}\\right)' assert latex(SymmetricDifference(P1, P2, evaluate=False)) == \ '\\left(\\left\\{a\\right\\} \\times \\left\\{b\\right\\}\\right) ' \ '\\triangle \\left(\\left\\{c\\right\\} \\times ' \ '\\left\\{d\\right\\}\\right)' # XXX This can be incorrect since cartesian product is not associative assert latex(ProductSet(A, P2).flatten()) == \ '\\left\\{a\\right\\} \\times \\left\\{c\\right\\} \\times ' \ '\\left\\{d\\right\\}' assert latex(ProductSet(U1, U2)) == \ '\\left(\\left\\{a\\right\\} \\cup \\left\\{b\\right\\}\\right) ' \ '\\times \\left(\\left\\{c\\right\\} \\cup ' \ '\\left\\{d\\right\\}\\right)' assert latex(ProductSet(I1, I2)) == \ '\\left(\\left\\{a\\right\\} \\cap \\left\\{b\\right\\}\\right) ' \ '\\times \\left(\\left\\{c\\right\\} \\cap ' \ '\\left\\{d\\right\\}\\right)' assert latex(ProductSet(C1, C2)) == \ '\\left(\\left\\{a\\right\\} \\setminus ' \ '\\left\\{b\\right\\}\\right) \\times \\left(\\left\\{c\\right\\} ' \ '\\setminus \\left\\{d\\right\\}\\right)' assert latex(ProductSet(D1, D2)) == \ '\\left(\\left\\{a\\right\\} \\triangle ' \ '\\left\\{b\\right\\}\\right) \\times \\left(\\left\\{c\\right\\} ' \ '\\triangle \\left\\{d\\right\\}\\right)' def test_latex_Complexes(): assert latex(S.Complexes) == r"\mathbb{C}" def test_latex_Naturals(): assert latex(S.Naturals) == r"\mathbb{N}" def test_latex_Naturals0(): assert latex(S.Naturals0) == r"\mathbb{N}_0" def test_latex_Integers(): assert latex(S.Integers) == r"\mathbb{Z}" def test_latex_ImageSet(): x = Symbol('x') assert latex(ImageSet(Lambda(x, x**2), S.Naturals)) == \ r"\left\{x^{2}\; |\; x \in \mathbb{N}\right\}" y = Symbol('y') imgset = ImageSet(Lambda((x, y), x + y), {1, 2, 3}, {3, 4}) assert latex(imgset) == \ r"\left\{x + y\; |\; x \in \left\{1, 2, 3\right\} , y \in \left\{3, 4\right\}\right\}" imgset = ImageSet(Lambda(((x, y),), x + y), ProductSet({1, 2, 3}, {3, 4})) assert latex(imgset) == \ r"\left\{x + y\; |\; \left( x, \ y\right) \in \left\{1, 2, 3\right\} \times \left\{3, 4\right\}\right\}" def test_latex_ConditionSet(): x = Symbol('x') assert latex(ConditionSet(x, Eq(x**2, 1), S.Reals)) == \ r"\left\{x \mid x \in \mathbb{R} \wedge x^{2} = 1 \right\}" assert latex(ConditionSet(x, Eq(x**2, 1), S.UniversalSet)) == \ r"\left\{x \mid x^{2} = 1 \right\}" def test_latex_ComplexRegion(): assert latex(ComplexRegion(Interval(3, 5)*Interval(4, 6))) == \ r"\left\{x + y i\; |\; x, y \in \left[3, 5\right] \times \left[4, 6\right] \right\}" assert latex(ComplexRegion(Interval(0, 1)*Interval(0, 2*pi), polar=True)) == \ r"\left\{r \left(i \sin{\left(\theta \right)} + \cos{\left(\theta "\ r"\right)}\right)\; |\; r, \theta \in \left[0, 1\right] \times \left[0, 2 \pi\right) \right\}" def test_latex_Contains(): x = Symbol('x') assert latex(Contains(x, S.Naturals)) == r"x \in \mathbb{N}" def test_latex_sum(): assert latex(Sum(x*y**2, (x, -2, 2), (y, -5, 5))) == \ r"\sum_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}" assert latex(Sum(x**2, (x, -2, 2))) == \ r"\sum_{x=-2}^{2} x^{2}" assert latex(Sum(x**2 + y, (x, -2, 2))) == \ r"\sum_{x=-2}^{2} \left(x^{2} + y\right)" assert latex(Sum(x**2 + y, (x, -2, 2))**2) == \ r"\left(\sum_{x=-2}^{2} \left(x^{2} + y\right)\right)^{2}" def test_latex_product(): assert latex(Product(x*y**2, (x, -2, 2), (y, -5, 5))) == \ r"\prod_{\substack{-2 \leq x \leq 2\\-5 \leq y \leq 5}} x y^{2}" assert latex(Product(x**2, (x, -2, 2))) == \ r"\prod_{x=-2}^{2} x^{2}" assert latex(Product(x**2 + y, (x, -2, 2))) == \ r"\prod_{x=-2}^{2} \left(x^{2} + y\right)" assert latex(Product(x, (x, -2, 2))**2) == \ r"\left(\prod_{x=-2}^{2} x\right)^{2}" def test_latex_limits(): assert latex(Limit(x, x, oo)) == r"\lim_{x \to \infty} x" # issue 8175 f = Function('f') assert latex(Limit(f(x), x, 0)) == r"\lim_{x \to 0^+} f{\left(x \right)}" assert latex(Limit(f(x), x, 0, "-")) == \ r"\lim_{x \to 0^-} f{\left(x \right)}" # issue #10806 assert latex(Limit(f(x), x, 0)**2) == \ r"\left(\lim_{x \to 0^+} f{\left(x \right)}\right)^{2}" # bi-directional limit assert latex(Limit(f(x), x, 0, dir='+-')) == \ r"\lim_{x \to 0} f{\left(x \right)}" def test_latex_log(): assert latex(log(x)) == r"\log{\left(x \right)}" assert latex(ln(x)) == r"\log{\left(x \right)}" assert latex(log(x), ln_notation=True) == r"\ln{\left(x \right)}" assert latex(log(x)+log(y)) == \ r"\log{\left(x \right)} + \log{\left(y \right)}" assert latex(log(x)+log(y), ln_notation=True) == \ r"\ln{\left(x \right)} + \ln{\left(y \right)}" assert latex(pow(log(x), x)) == r"\log{\left(x \right)}^{x}" assert latex(pow(log(x), x), ln_notation=True) == \ r"\ln{\left(x \right)}^{x}" def test_issue_3568(): beta = Symbol(r'\beta') y = beta + x assert latex(y) in [r'\beta + x', r'x + \beta'] beta = Symbol(r'beta') y = beta + x assert latex(y) in [r'\beta + x', r'x + \beta'] def test_latex(): assert latex((2*tau)**Rational(7, 2)) == "8 \\sqrt{2} \\tau^{\\frac{7}{2}}" assert latex((2*mu)**Rational(7, 2), mode='equation*') == \ "\\begin{equation*}8 \\sqrt{2} \\mu^{\\frac{7}{2}}\\end{equation*}" assert latex((2*mu)**Rational(7, 2), mode='equation', itex=True) == \ "$$8 \\sqrt{2} \\mu^{\\frac{7}{2}}$$" assert latex([2/x, y]) == r"\left[ \frac{2}{x}, \ y\right]" def test_latex_dict(): d = {Rational(1): 1, x**2: 2, x: 3, x**3: 4} assert latex(d) == \ r'\left\{ 1 : 1, \ x : 3, \ x^{2} : 2, \ x^{3} : 4\right\}' D = Dict(d) assert latex(D) == \ r'\left\{ 1 : 1, \ x : 3, \ x^{2} : 2, \ x^{3} : 4\right\}' def test_latex_list(): ll = [Symbol('omega1'), Symbol('a'), Symbol('alpha')] assert latex(ll) == r'\left[ \omega_{1}, \ a, \ \alpha\right]' def test_latex_rational(): # tests issue 3973 assert latex(-Rational(1, 2)) == "- \\frac{1}{2}" assert latex(Rational(-1, 2)) == "- \\frac{1}{2}" assert latex(Rational(1, -2)) == "- \\frac{1}{2}" assert latex(-Rational(-1, 2)) == "\\frac{1}{2}" assert latex(-Rational(1, 2)*x) == "- \\frac{x}{2}" assert latex(-Rational(1, 2)*x + Rational(-2, 3)*y) == \ "- \\frac{x}{2} - \\frac{2 y}{3}" def test_latex_inverse(): # tests issue 4129 assert latex(1/x) == "\\frac{1}{x}" assert latex(1/(x + y)) == "\\frac{1}{x + y}" def test_latex_DiracDelta(): assert latex(DiracDelta(x)) == r"\delta\left(x\right)" assert latex(DiracDelta(x)**2) == r"\left(\delta\left(x\right)\right)^{2}" assert latex(DiracDelta(x, 0)) == r"\delta\left(x\right)" assert latex(DiracDelta(x, 5)) == \ r"\delta^{\left( 5 \right)}\left( x \right)" assert latex(DiracDelta(x, 5)**2) == \ r"\left(\delta^{\left( 5 \right)}\left( x \right)\right)^{2}" def test_latex_Heaviside(): assert latex(Heaviside(x)) == r"\theta\left(x\right)" assert latex(Heaviside(x)**2) == r"\left(\theta\left(x\right)\right)^{2}" def test_latex_KroneckerDelta(): assert latex(KroneckerDelta(x, y)) == r"\delta_{x y}" assert latex(KroneckerDelta(x, y + 1)) == r"\delta_{x, y + 1}" # issue 6578 assert latex(KroneckerDelta(x + 1, y)) == r"\delta_{y, x + 1}" assert latex(Pow(KroneckerDelta(x, y), 2, evaluate=False)) == \ r"\left(\delta_{x y}\right)^{2}" def test_latex_LeviCivita(): assert latex(LeviCivita(x, y, z)) == r"\varepsilon_{x y z}" assert latex(LeviCivita(x, y, z)**2) == \ r"\left(\varepsilon_{x y z}\right)^{2}" assert latex(LeviCivita(x, y, z + 1)) == r"\varepsilon_{x, y, z + 1}" assert latex(LeviCivita(x, y + 1, z)) == r"\varepsilon_{x, y + 1, z}" assert latex(LeviCivita(x + 1, y, z)) == r"\varepsilon_{x + 1, y, z}" def test_mode(): expr = x + y assert latex(expr) == 'x + y' assert latex(expr, mode='plain') == 'x + y' assert latex(expr, mode='inline') == '$x + y$' assert latex( expr, mode='equation*') == '\\begin{equation*}x + y\\end{equation*}' assert latex( expr, mode='equation') == '\\begin{equation}x + y\\end{equation}' raises(ValueError, lambda: latex(expr, mode='foo')) def test_latex_mathieu(): assert latex(mathieuc(x, y, z)) == r"C\left(x, y, z\right)" assert latex(mathieus(x, y, z)) == r"S\left(x, y, z\right)" assert latex(mathieuc(x, y, z)**2) == r"C\left(x, y, z\right)^{2}" assert latex(mathieus(x, y, z)**2) == r"S\left(x, y, z\right)^{2}" assert latex(mathieucprime(x, y, z)) == r"C^{\prime}\left(x, y, z\right)" assert latex(mathieusprime(x, y, z)) == r"S^{\prime}\left(x, y, z\right)" assert latex(mathieucprime(x, y, z)**2) == r"C^{\prime}\left(x, y, z\right)^{2}" assert latex(mathieusprime(x, y, z)**2) == r"S^{\prime}\left(x, y, z\right)^{2}" def test_latex_Piecewise(): p = Piecewise((x, x < 1), (x**2, True)) assert latex(p) == "\\begin{cases} x & \\text{for}\\: x < 1 \\\\x^{2} &" \ " \\text{otherwise} \\end{cases}" assert latex(p, itex=True) == \ "\\begin{cases} x & \\text{for}\\: x \\lt 1 \\\\x^{2} &" \ " \\text{otherwise} \\end{cases}" p = Piecewise((x, x < 0), (0, x >= 0)) assert latex(p) == '\\begin{cases} x & \\text{for}\\: x < 0 \\\\0 &' \ ' \\text{otherwise} \\end{cases}' A, B = symbols("A B", commutative=False) p = Piecewise((A**2, Eq(A, B)), (A*B, True)) s = r"\begin{cases} A^{2} & \text{for}\: A = B \\A B & \text{otherwise} \end{cases}" assert latex(p) == s assert latex(A*p) == r"A \left(%s\right)" % s assert latex(p*A) == r"\left(%s\right) A" % s assert latex(Piecewise((x, x < 1), (x**2, x < 2))) == \ '\\begin{cases} x & ' \ '\\text{for}\\: x < 1 \\\\x^{2} & \\text{for}\\: x < 2 \\end{cases}' def test_latex_Matrix(): M = Matrix([[1 + x, y], [y, x - 1]]) assert latex(M) == \ r'\left[\begin{matrix}x + 1 & y\\y & x - 1\end{matrix}\right]' assert latex(M, mode='inline') == \ r'$\left[\begin{smallmatrix}x + 1 & y\\' \ r'y & x - 1\end{smallmatrix}\right]$' assert latex(M, mat_str='array') == \ r'\left[\begin{array}{cc}x + 1 & y\\y & x - 1\end{array}\right]' assert latex(M, mat_str='bmatrix') == \ r'\left[\begin{bmatrix}x + 1 & y\\y & x - 1\end{bmatrix}\right]' assert latex(M, mat_delim=None, mat_str='bmatrix') == \ r'\begin{bmatrix}x + 1 & y\\y & x - 1\end{bmatrix}' M2 = Matrix(1, 11, range(11)) assert latex(M2) == \ r'\left[\begin{array}{ccccccccccc}' \ r'0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10\end{array}\right]' def test_latex_matrix_with_functions(): t = symbols('t') theta1 = symbols('theta1', cls=Function) M = Matrix([[sin(theta1(t)), cos(theta1(t))], [cos(theta1(t).diff(t)), sin(theta1(t).diff(t))]]) expected = (r'\left[\begin{matrix}\sin{\left(' r'\theta_{1}{\left(t \right)} \right)} & ' r'\cos{\left(\theta_{1}{\left(t \right)} \right)' r'}\\\cos{\left(\frac{d}{d t} \theta_{1}{\left(t ' r'\right)} \right)} & \sin{\left(\frac{d}{d t} ' r'\theta_{1}{\left(t \right)} \right' r')}\end{matrix}\right]') assert latex(M) == expected def test_latex_NDimArray(): x, y, z, w = symbols("x y z w") for ArrayType in (ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray): # Basic: scalar array M = ArrayType(x) assert latex(M) == "x" M = ArrayType([[1 / x, y], [z, w]]) M1 = ArrayType([1 / x, y, z]) M2 = tensorproduct(M1, M) M3 = tensorproduct(M, M) assert latex(M) == \ '\\left[\\begin{matrix}\\frac{1}{x} & y\\\\z & w\\end{matrix}\\right]' assert latex(M1) == \ "\\left[\\begin{matrix}\\frac{1}{x} & y & z\\end{matrix}\\right]" assert latex(M2) == \ r"\left[\begin{matrix}" \ r"\left[\begin{matrix}\frac{1}{x^{2}} & \frac{y}{x}\\\frac{z}{x} & \frac{w}{x}\end{matrix}\right] & " \ r"\left[\begin{matrix}\frac{y}{x} & y^{2}\\y z & w y\end{matrix}\right] & " \ r"\left[\begin{matrix}\frac{z}{x} & y z\\z^{2} & w z\end{matrix}\right]" \ r"\end{matrix}\right]" assert latex(M3) == \ r"""\left[\begin{matrix}"""\ r"""\left[\begin{matrix}\frac{1}{x^{2}} & \frac{y}{x}\\\frac{z}{x} & \frac{w}{x}\end{matrix}\right] & """\ r"""\left[\begin{matrix}\frac{y}{x} & y^{2}\\y z & w y\end{matrix}\right]\\"""\ r"""\left[\begin{matrix}\frac{z}{x} & y z\\z^{2} & w z\end{matrix}\right] & """\ r"""\left[\begin{matrix}\frac{w}{x} & w y\\w z & w^{2}\end{matrix}\right]"""\ r"""\end{matrix}\right]""" Mrow = ArrayType([[x, y, 1/z]]) Mcolumn = ArrayType([[x], [y], [1/z]]) Mcol2 = ArrayType([Mcolumn.tolist()]) assert latex(Mrow) == \ r"\left[\left[\begin{matrix}x & y & \frac{1}{z}\end{matrix}\right]\right]" assert latex(Mcolumn) == \ r"\left[\begin{matrix}x\\y\\\frac{1}{z}\end{matrix}\right]" assert latex(Mcol2) == \ r'\left[\begin{matrix}\left[\begin{matrix}x\\y\\\frac{1}{z}\end{matrix}\right]\end{matrix}\right]' def test_latex_mul_symbol(): assert latex(4*4**x, mul_symbol='times') == "4 \\times 4^{x}" assert latex(4*4**x, mul_symbol='dot') == "4 \\cdot 4^{x}" assert latex(4*4**x, mul_symbol='ldot') == r"4 \,.\, 4^{x}" assert latex(4*x, mul_symbol='times') == "4 \\times x" assert latex(4*x, mul_symbol='dot') == "4 \\cdot x" assert latex(4*x, mul_symbol='ldot') == r"4 \,.\, x" def test_latex_issue_4381(): y = 4*4**log(2) assert latex(y) == r'4 \cdot 4^{\log{\left(2 \right)}}' assert latex(1/y) == r'\frac{1}{4 \cdot 4^{\log{\left(2 \right)}}}' def test_latex_issue_4576(): assert latex(Symbol("beta_13_2")) == r"\beta_{13 2}" assert latex(Symbol("beta_132_20")) == r"\beta_{132 20}" assert latex(Symbol("beta_13")) == r"\beta_{13}" assert latex(Symbol("x_a_b")) == r"x_{a b}" assert latex(Symbol("x_1_2_3")) == r"x_{1 2 3}" assert latex(Symbol("x_a_b1")) == r"x_{a b1}" assert latex(Symbol("x_a_1")) == r"x_{a 1}" assert latex(Symbol("x_1_a")) == r"x_{1 a}" assert latex(Symbol("x_1^aa")) == r"x^{aa}_{1}" assert latex(Symbol("x_1__aa")) == r"x^{aa}_{1}" assert latex(Symbol("x_11^a")) == r"x^{a}_{11}" assert latex(Symbol("x_11__a")) == r"x^{a}_{11}" assert latex(Symbol("x_a_a_a_a")) == r"x_{a a a a}" assert latex(Symbol("x_a_a^a^a")) == r"x^{a a}_{a a}" assert latex(Symbol("x_a_a__a__a")) == r"x^{a a}_{a a}" assert latex(Symbol("alpha_11")) == r"\alpha_{11}" assert latex(Symbol("alpha_11_11")) == r"\alpha_{11 11}" assert latex(Symbol("alpha_alpha")) == r"\alpha_{\alpha}" assert latex(Symbol("alpha^aleph")) == r"\alpha^{\aleph}" assert latex(Symbol("alpha__aleph")) == r"\alpha^{\aleph}" def test_latex_pow_fraction(): x = Symbol('x') # Testing exp assert 'e^{-x}' in latex(exp(-x)/2).replace(' ', '') # Remove Whitespace # Testing e^{-x} in case future changes alter behavior of muls or fracs # In particular current output is \frac{1}{2}e^{- x} but perhaps this will # change to \frac{e^{-x}}{2} # Testing general, non-exp, power assert '3^{-x}' in latex(3**-x/2).replace(' ', '') def test_noncommutative(): A, B, C = symbols('A,B,C', commutative=False) assert latex(A*B*C**-1) == "A B C^{-1}" assert latex(C**-1*A*B) == "C^{-1} A B" assert latex(A*C**-1*B) == "A C^{-1} B" def test_latex_order(): expr = x**3 + x**2*y + y**4 + 3*x*y**3 assert latex(expr, order='lex') == "x^{3} + x^{2} y + 3 x y^{3} + y^{4}" assert latex( expr, order='rev-lex') == "y^{4} + 3 x y^{3} + x^{2} y + x^{3}" assert latex(expr, order='none') == "x^{3} + y^{4} + y x^{2} + 3 x y^{3}" def test_latex_Lambda(): assert latex(Lambda(x, x + 1)) == \ r"\left( x \mapsto x + 1 \right)" assert latex(Lambda((x, y), x + 1)) == \ r"\left( \left( x, \ y\right) \mapsto x + 1 \right)" assert latex(Lambda(x, x)) == \ r"\left( x \mapsto x \right)" def test_latex_PolyElement(): Ruv, u, v = ring("u,v", ZZ) Rxyz, x, y, z = ring("x,y,z", Ruv) assert latex(x - x) == r"0" assert latex(x - 1) == r"x - 1" assert latex(x + 1) == r"x + 1" assert latex((u**2 + 3*u*v + 1)*x**2*y + u + 1) == \ r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + u + 1" assert latex((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x) == \ r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + \left(u + 1\right) x" assert latex((u**2 + 3*u*v + 1)*x**2*y + (u + 1)*x + 1) == \ r"\left({u}^{2} + 3 u v + 1\right) {x}^{2} y + \left(u + 1\right) x + 1" assert latex((-u**2 + 3*u*v - 1)*x**2*y - (u + 1)*x - 1) == \ r"-\left({u}^{2} - 3 u v + 1\right) {x}^{2} y - \left(u + 1\right) x - 1" assert latex(-(v**2 + v + 1)*x + 3*u*v + 1) == \ r"-\left({v}^{2} + v + 1\right) x + 3 u v + 1" assert latex(-(v**2 + v + 1)*x - 3*u*v + 1) == \ r"-\left({v}^{2} + v + 1\right) x - 3 u v + 1" def test_latex_FracElement(): Fuv, u, v = field("u,v", ZZ) Fxyzt, x, y, z, t = field("x,y,z,t", Fuv) assert latex(x - x) == r"0" assert latex(x - 1) == r"x - 1" assert latex(x + 1) == r"x + 1" assert latex(x/3) == r"\frac{x}{3}" assert latex(x/z) == r"\frac{x}{z}" assert latex(x*y/z) == r"\frac{x y}{z}" assert latex(x/(z*t)) == r"\frac{x}{z t}" assert latex(x*y/(z*t)) == r"\frac{x y}{z t}" assert latex((x - 1)/y) == r"\frac{x - 1}{y}" assert latex((x + 1)/y) == r"\frac{x + 1}{y}" assert latex((-x - 1)/y) == r"\frac{-x - 1}{y}" assert latex((x + 1)/(y*z)) == r"\frac{x + 1}{y z}" assert latex(-y/(x + 1)) == r"\frac{-y}{x + 1}" assert latex(y*z/(x + 1)) == r"\frac{y z}{x + 1}" assert latex(((u + 1)*x*y + 1)/((v - 1)*z - 1)) == \ r"\frac{\left(u + 1\right) x y + 1}{\left(v - 1\right) z - 1}" assert latex(((u + 1)*x*y + 1)/((v - 1)*z - t*u*v - 1)) == \ r"\frac{\left(u + 1\right) x y + 1}{\left(v - 1\right) z - u v t - 1}" def test_latex_Poly(): assert latex(Poly(x**2 + 2 * x, x)) == \ r"\operatorname{Poly}{\left( x^{2} + 2 x, x, domain=\mathbb{Z} \right)}" assert latex(Poly(x/y, x)) == \ r"\operatorname{Poly}{\left( \frac{1}{y} x, x, domain=\mathbb{Z}\left(y\right) \right)}" assert latex(Poly(2.0*x + y)) == \ r"\operatorname{Poly}{\left( 2.0 x + 1.0 y, x, y, domain=\mathbb{R} \right)}" def test_latex_Poly_order(): assert latex(Poly([a, 1, b, 2, c, 3], x)) == \ '\\operatorname{Poly}{\\left( a x^{5} + x^{4} + b x^{3} + 2 x^{2} + c'\ ' x + 3, x, domain=\\mathbb{Z}\\left[a, b, c\\right] \\right)}' assert latex(Poly([a, 1, b+c, 2, 3], x)) == \ '\\operatorname{Poly}{\\left( a x^{4} + x^{3} + \\left(b + c\\right) '\ 'x^{2} + 2 x + 3, x, domain=\\mathbb{Z}\\left[a, b, c\\right] \\right)}' assert latex(Poly(a*x**3 + x**2*y - x*y - c*y**3 - b*x*y**2 + y - a*x + b, (x, y))) == \ '\\operatorname{Poly}{\\left( a x^{3} + x^{2}y - b xy^{2} - xy - '\ 'a x - c y^{3} + y + b, x, y, domain=\\mathbb{Z}\\left[a, b, c\\right] \\right)}' def test_latex_ComplexRootOf(): assert latex(rootof(x**5 + x + 3, 0)) == \ r"\operatorname{CRootOf} {\left(x^{5} + x + 3, 0\right)}" def test_latex_RootSum(): assert latex(RootSum(x**5 + x + 3, sin)) == \ r"\operatorname{RootSum} {\left(x^{5} + x + 3, \left( x \mapsto \sin{\left(x \right)} \right)\right)}" def test_settings(): raises(TypeError, lambda: latex(x*y, method="garbage")) def test_latex_numbers(): assert latex(catalan(n)) == r"C_{n}" assert latex(catalan(n)**2) == r"C_{n}^{2}" assert latex(bernoulli(n)) == r"B_{n}" assert latex(bernoulli(n, x)) == r"B_{n}\left(x\right)" assert latex(bernoulli(n)**2) == r"B_{n}^{2}" assert latex(bernoulli(n, x)**2) == r"B_{n}^{2}\left(x\right)" assert latex(bell(n)) == r"B_{n}" assert latex(bell(n, x)) == r"B_{n}\left(x\right)" assert latex(bell(n, m, (x, y))) == r"B_{n, m}\left(x, y\right)" assert latex(bell(n)**2) == r"B_{n}^{2}" assert latex(bell(n, x)**2) == r"B_{n}^{2}\left(x\right)" assert latex(bell(n, m, (x, y))**2) == r"B_{n, m}^{2}\left(x, y\right)" assert latex(fibonacci(n)) == r"F_{n}" assert latex(fibonacci(n, x)) == r"F_{n}\left(x\right)" assert latex(fibonacci(n)**2) == r"F_{n}^{2}" assert latex(fibonacci(n, x)**2) == r"F_{n}^{2}\left(x\right)" assert latex(lucas(n)) == r"L_{n}" assert latex(lucas(n)**2) == r"L_{n}^{2}" assert latex(tribonacci(n)) == r"T_{n}" assert latex(tribonacci(n, x)) == r"T_{n}\left(x\right)" assert latex(tribonacci(n)**2) == r"T_{n}^{2}" assert latex(tribonacci(n, x)**2) == r"T_{n}^{2}\left(x\right)" def test_latex_euler(): assert latex(euler(n)) == r"E_{n}" assert latex(euler(n, x)) == r"E_{n}\left(x\right)" assert latex(euler(n, x)**2) == r"E_{n}^{2}\left(x\right)" def test_lamda(): assert latex(Symbol('lamda')) == r"\lambda" assert latex(Symbol('Lamda')) == r"\Lambda" def test_custom_symbol_names(): x = Symbol('x') y = Symbol('y') assert latex(x) == "x" assert latex(x, symbol_names={x: "x_i"}) == "x_i" assert latex(x + y, symbol_names={x: "x_i"}) == "x_i + y" assert latex(x**2, symbol_names={x: "x_i"}) == "x_i^{2}" assert latex(x + y, symbol_names={x: "x_i", y: "y_j"}) == "x_i + y_j" def test_matAdd(): from sympy import MatrixSymbol from sympy.printing.latex import LatexPrinter C = MatrixSymbol('C', 5, 5) B = MatrixSymbol('B', 5, 5) l = LatexPrinter() assert l._print(C - 2*B) in ['- 2 B + C', 'C -2 B'] assert l._print(C + 2*B) in ['2 B + C', 'C + 2 B'] assert l._print(B - 2*C) in ['B - 2 C', '- 2 C + B'] assert l._print(B + 2*C) in ['B + 2 C', '2 C + B'] def test_matMul(): from sympy import MatrixSymbol from sympy.printing.latex import LatexPrinter A = MatrixSymbol('A', 5, 5) B = MatrixSymbol('B', 5, 5) x = Symbol('x') lp = LatexPrinter() assert lp._print_MatMul(2*A) == '2 A' assert lp._print_MatMul(2*x*A) == '2 x A' assert lp._print_MatMul(-2*A) == '- 2 A' assert lp._print_MatMul(1.5*A) == '1.5 A' assert lp._print_MatMul(sqrt(2)*A) == r'\sqrt{2} A' assert lp._print_MatMul(-sqrt(2)*A) == r'- \sqrt{2} A' assert lp._print_MatMul(2*sqrt(2)*x*A) == r'2 \sqrt{2} x A' assert lp._print_MatMul(-2*A*(A + 2*B)) in [r'- 2 A \left(A + 2 B\right)', r'- 2 A \left(2 B + A\right)'] def test_latex_MatrixSlice(): n = Symbol('n', integer=True) x, y, z, w, t, = symbols('x y z w t') X = MatrixSymbol('X', n, n) Y = MatrixSymbol('Y', 10, 10) Z = MatrixSymbol('Z', 10, 10) assert latex(MatrixSlice(X, (None, None, None), (None, None, None))) == r'X\left[:, :\right]' assert latex(X[x:x + 1, y:y + 1]) == r'X\left[x:x + 1, y:y + 1\right]' assert latex(X[x:x + 1:2, y:y + 1:2]) == r'X\left[x:x + 1:2, y:y + 1:2\right]' assert latex(X[:x, y:]) == r'X\left[:x, y:\right]' assert latex(X[:x, y:]) == r'X\left[:x, y:\right]' assert latex(X[x:, :y]) == r'X\left[x:, :y\right]' assert latex(X[x:y, z:w]) == r'X\left[x:y, z:w\right]' assert latex(X[x:y:t, w:t:x]) == r'X\left[x:y:t, w:t:x\right]' assert latex(X[x::y, t::w]) == r'X\left[x::y, t::w\right]' assert latex(X[:x:y, :t:w]) == r'X\left[:x:y, :t:w\right]' assert latex(X[::x, ::y]) == r'X\left[::x, ::y\right]' assert latex(MatrixSlice(X, (0, None, None), (0, None, None))) == r'X\left[:, :\right]' assert latex(MatrixSlice(X, (None, n, None), (None, n, None))) == r'X\left[:, :\right]' assert latex(MatrixSlice(X, (0, n, None), (0, n, None))) == r'X\left[:, :\right]' assert latex(MatrixSlice(X, (0, n, 2), (0, n, 2))) == r'X\left[::2, ::2\right]' assert latex(X[1:2:3, 4:5:6]) == r'X\left[1:2:3, 4:5:6\right]' assert latex(X[1:3:5, 4:6:8]) == r'X\left[1:3:5, 4:6:8\right]' assert latex(X[1:10:2]) == r'X\left[1:10:2, :\right]' assert latex(Y[:5, 1:9:2]) == r'Y\left[:5, 1:9:2\right]' assert latex(Y[:5, 1:10:2]) == r'Y\left[:5, 1::2\right]' assert latex(Y[5, :5:2]) == r'Y\left[5:6, :5:2\right]' assert latex(X[0:1, 0:1]) == r'X\left[:1, :1\right]' assert latex(X[0:1:2, 0:1:2]) == r'X\left[:1:2, :1:2\right]' assert latex((Y + Z)[2:, 2:]) == r'\left(Y + Z\right)\left[2:, 2:\right]' def test_latex_RandomDomain(): from sympy.stats import Normal, Die, Exponential, pspace, where from sympy.stats.rv import RandomDomain X = Normal('x1', 0, 1) assert latex(where(X > 0)) == r"\text{Domain: }0 < x_{1} \wedge x_{1} < \infty" D = Die('d1', 6) assert latex(where(D > 4)) == r"\text{Domain: }d_{1} = 5 \vee d_{1} = 6" A = Exponential('a', 1) B = Exponential('b', 1) assert latex( pspace(Tuple(A, B)).domain) == \ r"\text{Domain: }0 \leq a \wedge 0 \leq b \wedge a < \infty \wedge b < \infty" assert latex(RandomDomain(FiniteSet(x), FiniteSet(1, 2))) == \ r'\text{Domain: }\left\{x\right\}\text{ in }\left\{1, 2\right\}' def test_PrettyPoly(): from sympy.polys.domains import QQ F = QQ.frac_field(x, y) R = QQ[x, y] assert latex(F.convert(x/(x + y))) == latex(x/(x + y)) assert latex(R.convert(x + y)) == latex(x + y) def test_integral_transforms(): x = Symbol("x") k = Symbol("k") f = Function("f") a = Symbol("a") b = Symbol("b") assert latex(MellinTransform(f(x), x, k)) == \ r"\mathcal{M}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseMellinTransform(f(k), k, x, a, b)) == \ r"\mathcal{M}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(LaplaceTransform(f(x), x, k)) == \ r"\mathcal{L}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseLaplaceTransform(f(k), k, x, (a, b))) == \ r"\mathcal{L}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(FourierTransform(f(x), x, k)) == \ r"\mathcal{F}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseFourierTransform(f(k), k, x)) == \ r"\mathcal{F}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(CosineTransform(f(x), x, k)) == \ r"\mathcal{COS}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseCosineTransform(f(k), k, x)) == \ r"\mathcal{COS}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" assert latex(SineTransform(f(x), x, k)) == \ r"\mathcal{SIN}_{x}\left[f{\left(x \right)}\right]\left(k\right)" assert latex(InverseSineTransform(f(k), k, x)) == \ r"\mathcal{SIN}^{-1}_{k}\left[f{\left(k \right)}\right]\left(x\right)" def test_PolynomialRingBase(): from sympy.polys.domains import QQ assert latex(QQ.old_poly_ring(x, y)) == r"\mathbb{Q}\left[x, y\right]" assert latex(QQ.old_poly_ring(x, y, order="ilex")) == \ r"S_<^{-1}\mathbb{Q}\left[x, y\right]" def test_categories(): from sympy.categories import (Object, IdentityMorphism, NamedMorphism, Category, Diagram, DiagramGrid) A1 = Object("A1") A2 = Object("A2") A3 = Object("A3") f1 = NamedMorphism(A1, A2, "f1") f2 = NamedMorphism(A2, A3, "f2") id_A1 = IdentityMorphism(A1) K1 = Category("K1") assert latex(A1) == "A_{1}" assert latex(f1) == "f_{1}:A_{1}\\rightarrow A_{2}" assert latex(id_A1) == "id:A_{1}\\rightarrow A_{1}" assert latex(f2*f1) == "f_{2}\\circ f_{1}:A_{1}\\rightarrow A_{3}" assert latex(K1) == r"\mathbf{K_{1}}" d = Diagram() assert latex(d) == r"\emptyset" d = Diagram({f1: "unique", f2: S.EmptySet}) assert latex(d) == r"\left\{ f_{2}\circ f_{1}:A_{1}" \ r"\rightarrow A_{3} : \emptyset, \ id:A_{1}\rightarrow " \ r"A_{1} : \emptyset, \ id:A_{2}\rightarrow A_{2} : " \ r"\emptyset, \ id:A_{3}\rightarrow A_{3} : \emptyset, " \ r"\ f_{1}:A_{1}\rightarrow A_{2} : \left\{unique\right\}, " \ r"\ f_{2}:A_{2}\rightarrow A_{3} : \emptyset\right\}" d = Diagram({f1: "unique", f2: S.EmptySet}, {f2 * f1: "unique"}) assert latex(d) == r"\left\{ f_{2}\circ f_{1}:A_{1}" \ r"\rightarrow A_{3} : \emptyset, \ id:A_{1}\rightarrow " \ r"A_{1} : \emptyset, \ id:A_{2}\rightarrow A_{2} : " \ r"\emptyset, \ id:A_{3}\rightarrow A_{3} : \emptyset, " \ r"\ f_{1}:A_{1}\rightarrow A_{2} : \left\{unique\right\}," \ r" \ f_{2}:A_{2}\rightarrow A_{3} : \emptyset\right\}" \ r"\Longrightarrow \left\{ f_{2}\circ f_{1}:A_{1}" \ r"\rightarrow A_{3} : \left\{unique\right\}\right\}" # A linear diagram. A = Object("A") B = Object("B") C = Object("C") f = NamedMorphism(A, B, "f") g = NamedMorphism(B, C, "g") d = Diagram([f, g]) grid = DiagramGrid(d) assert latex(grid) == "\\begin{array}{cc}\n" \ "A & B \\\\\n" \ " & C \n" \ "\\end{array}\n" def test_Modules(): from sympy.polys.domains import QQ from sympy.polys.agca import homomorphism R = QQ.old_poly_ring(x, y) F = R.free_module(2) M = F.submodule([x, y], [1, x**2]) assert latex(F) == r"{\mathbb{Q}\left[x, y\right]}^{2}" assert latex(M) == \ r"\left\langle {\left[ {x},{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle" I = R.ideal(x**2, y) assert latex(I) == r"\left\langle {x^{2}},{y} \right\rangle" Q = F / M assert latex(Q) == \ r"\frac{{\mathbb{Q}\left[x, y\right]}^{2}}{\left\langle {\left[ {x},"\ r"{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle}" assert latex(Q.submodule([1, x**3/2], [2, y])) == \ r"\left\langle {{\left[ {1},{\frac{x^{3}}{2}} \right]} + {\left"\ r"\langle {\left[ {x},{y} \right]},{\left[ {1},{x^{2}} \right]} "\ r"\right\rangle}},{{\left[ {2},{y} \right]} + {\left\langle {\left[ "\ r"{x},{y} \right]},{\left[ {1},{x^{2}} \right]} \right\rangle}} \right\rangle" h = homomorphism(QQ.old_poly_ring(x).free_module(2), QQ.old_poly_ring(x).free_module(2), [0, 0]) assert latex(h) == \ r"{\left[\begin{matrix}0 & 0\\0 & 0\end{matrix}\right]} : "\ r"{{\mathbb{Q}\left[x\right]}^{2}} \to {{\mathbb{Q}\left[x\right]}^{2}}" def test_QuotientRing(): from sympy.polys.domains import QQ R = QQ.old_poly_ring(x)/[x**2 + 1] assert latex(R) == \ r"\frac{\mathbb{Q}\left[x\right]}{\left\langle {x^{2} + 1} \right\rangle}" assert latex(R.one) == r"{1} + {\left\langle {x^{2} + 1} \right\rangle}" def test_Tr(): #TODO: Handle indices A, B = symbols('A B', commutative=False) t = Tr(A*B) assert latex(t) == r'\operatorname{tr}\left(A B\right)' def test_Adjoint(): from sympy.matrices import MatrixSymbol, Adjoint, Inverse, Transpose X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(Adjoint(X)) == r'X^{\dagger}' assert latex(Adjoint(X + Y)) == r'\left(X + Y\right)^{\dagger}' assert latex(Adjoint(X) + Adjoint(Y)) == r'X^{\dagger} + Y^{\dagger}' assert latex(Adjoint(X*Y)) == r'\left(X Y\right)^{\dagger}' assert latex(Adjoint(Y)*Adjoint(X)) == r'Y^{\dagger} X^{\dagger}' assert latex(Adjoint(X**2)) == r'\left(X^{2}\right)^{\dagger}' assert latex(Adjoint(X)**2) == r'\left(X^{\dagger}\right)^{2}' assert latex(Adjoint(Inverse(X))) == r'\left(X^{-1}\right)^{\dagger}' assert latex(Inverse(Adjoint(X))) == r'\left(X^{\dagger}\right)^{-1}' assert latex(Adjoint(Transpose(X))) == r'\left(X^{T}\right)^{\dagger}' assert latex(Transpose(Adjoint(X))) == r'\left(X^{\dagger}\right)^{T}' assert latex(Transpose(Adjoint(X) + Y)) == r'\left(X^{\dagger} + Y\right)^{T}' def test_Transpose(): from sympy.matrices import Transpose, MatPow, HadamardPower X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(Transpose(X)) == r'X^{T}' assert latex(Transpose(X + Y)) == r'\left(X + Y\right)^{T}' assert latex(Transpose(HadamardPower(X, 2))) == \ r'\left(X^{\circ {2}}\right)^{T}' assert latex(HadamardPower(Transpose(X), 2)) == \ r'\left(X^{T}\right)^{\circ {2}}' assert latex(Transpose(MatPow(X, 2))) == \ r'\left(X^{2}\right)^{T}' assert latex(MatPow(Transpose(X), 2)) == \ r'\left(X^{T}\right)^{2}' def test_Hadamard(): from sympy.matrices import MatrixSymbol, HadamardProduct, HadamardPower from sympy.matrices.expressions import MatAdd, MatMul, MatPow X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) assert latex(HadamardProduct(X, Y*Y)) == r'X \circ Y^{2}' assert latex(HadamardProduct(X, Y)*Y) == r'\left(X \circ Y\right) Y' assert latex(HadamardPower(X, 2)) == r'X^{\circ {2}}' assert latex(HadamardPower(X, -1)) == r'X^{\circ \left({-1}\right)}' assert latex(HadamardPower(MatAdd(X, Y), 2)) == \ r'\left(X + Y\right)^{\circ {2}}' assert latex(HadamardPower(MatMul(X, Y), 2)) == \ r'\left(X Y\right)^{\circ {2}}' assert latex(HadamardPower(MatPow(X, -1), -1)) == \ r'\left(X^{-1}\right)^{\circ \left({-1}\right)}' assert latex(MatPow(HadamardPower(X, -1), -1)) == \ r'\left(X^{\circ \left({-1}\right)}\right)^{-1}' assert latex(HadamardPower(X, n+1)) == \ r'X^{\circ \left({n + 1}\right)}' def test_ElementwiseApplyFunction(): from sympy.matrices import MatrixSymbol X = MatrixSymbol('X', 2, 2) expr = (X.T*X).applyfunc(sin) assert latex(expr) == r"{\left( d \mapsto \sin{\left(d \right)} \right)}_{\circ}\left({X^{T} X}\right)" expr = X.applyfunc(Lambda(x, 1/x)) assert latex(expr) == r'{\left( x \mapsto \frac{1}{x} \right)}_{\circ}\left({X}\right)' def test_ZeroMatrix(): from sympy import ZeroMatrix assert latex(ZeroMatrix(1, 1), mat_symbol_style='plain') == r"\mathbb{0}" assert latex(ZeroMatrix(1, 1), mat_symbol_style='bold') == r"\mathbf{0}" def test_OneMatrix(): from sympy import OneMatrix assert latex(OneMatrix(3, 4), mat_symbol_style='plain') == r"\mathbb{1}" assert latex(OneMatrix(3, 4), mat_symbol_style='bold') == r"\mathbf{1}" def test_Identity(): from sympy import Identity assert latex(Identity(1), mat_symbol_style='plain') == r"\mathbb{I}" assert latex(Identity(1), mat_symbol_style='bold') == r"\mathbf{I}" def test_boolean_args_order(): syms = symbols('a:f') expr = And(*syms) assert latex(expr) == 'a \\wedge b \\wedge c \\wedge d \\wedge e \\wedge f' expr = Or(*syms) assert latex(expr) == 'a \\vee b \\vee c \\vee d \\vee e \\vee f' expr = Equivalent(*syms) assert latex(expr) == \ 'a \\Leftrightarrow b \\Leftrightarrow c \\Leftrightarrow d \\Leftrightarrow e \\Leftrightarrow f' expr = Xor(*syms) assert latex(expr) == \ 'a \\veebar b \\veebar c \\veebar d \\veebar e \\veebar f' def test_imaginary(): i = sqrt(-1) assert latex(i) == r'i' def test_builtins_without_args(): assert latex(sin) == r'\sin' assert latex(cos) == r'\cos' assert latex(tan) == r'\tan' assert latex(log) == r'\log' assert latex(Ei) == r'\operatorname{Ei}' assert latex(zeta) == r'\zeta' def test_latex_greek_functions(): # bug because capital greeks that have roman equivalents should not use # \Alpha, \Beta, \Eta, etc. s = Function('Alpha') assert latex(s) == r'A' assert latex(s(x)) == r'A{\left(x \right)}' s = Function('Beta') assert latex(s) == r'B' s = Function('Eta') assert latex(s) == r'H' assert latex(s(x)) == r'H{\left(x \right)}' # bug because sympy.core.numbers.Pi is special p = Function('Pi') # assert latex(p(x)) == r'\Pi{\left(x \right)}' assert latex(p) == r'\Pi' # bug because not all greeks are included c = Function('chi') assert latex(c(x)) == r'\chi{\left(x \right)}' assert latex(c) == r'\chi' def test_translate(): s = 'Alpha' assert translate(s) == 'A' s = 'Beta' assert translate(s) == 'B' s = 'Eta' assert translate(s) == 'H' s = 'omicron' assert translate(s) == 'o' s = 'Pi' assert translate(s) == r'\Pi' s = 'pi' assert translate(s) == r'\pi' s = 'LamdaHatDOT' assert translate(s) == r'\dot{\hat{\Lambda}}' def test_other_symbols(): from sympy.printing.latex import other_symbols for s in other_symbols: assert latex(symbols(s)) == "\\"+s def test_modifiers(): # Test each modifier individually in the simplest case # (with funny capitalizations) assert latex(symbols("xMathring")) == r"\mathring{x}" assert latex(symbols("xCheck")) == r"\check{x}" assert latex(symbols("xBreve")) == r"\breve{x}" assert latex(symbols("xAcute")) == r"\acute{x}" assert latex(symbols("xGrave")) == r"\grave{x}" assert latex(symbols("xTilde")) == r"\tilde{x}" assert latex(symbols("xPrime")) == r"{x}'" assert latex(symbols("xddDDot")) == r"\ddddot{x}" assert latex(symbols("xDdDot")) == r"\dddot{x}" assert latex(symbols("xDDot")) == r"\ddot{x}" assert latex(symbols("xBold")) == r"\boldsymbol{x}" assert latex(symbols("xnOrM")) == r"\left\|{x}\right\|" assert latex(symbols("xAVG")) == r"\left\langle{x}\right\rangle" assert latex(symbols("xHat")) == r"\hat{x}" assert latex(symbols("xDot")) == r"\dot{x}" assert latex(symbols("xBar")) == r"\bar{x}" assert latex(symbols("xVec")) == r"\vec{x}" assert latex(symbols("xAbs")) == r"\left|{x}\right|" assert latex(symbols("xMag")) == r"\left|{x}\right|" assert latex(symbols("xPrM")) == r"{x}'" assert latex(symbols("xBM")) == r"\boldsymbol{x}" # Test strings that are *only* the names of modifiers assert latex(symbols("Mathring")) == r"Mathring" assert latex(symbols("Check")) == r"Check" assert latex(symbols("Breve")) == r"Breve" assert latex(symbols("Acute")) == r"Acute" assert latex(symbols("Grave")) == r"Grave" assert latex(symbols("Tilde")) == r"Tilde" assert latex(symbols("Prime")) == r"Prime" assert latex(symbols("DDot")) == r"\dot{D}" assert latex(symbols("Bold")) == r"Bold" assert latex(symbols("NORm")) == r"NORm" assert latex(symbols("AVG")) == r"AVG" assert latex(symbols("Hat")) == r"Hat" assert latex(symbols("Dot")) == r"Dot" assert latex(symbols("Bar")) == r"Bar" assert latex(symbols("Vec")) == r"Vec" assert latex(symbols("Abs")) == r"Abs" assert latex(symbols("Mag")) == r"Mag" assert latex(symbols("PrM")) == r"PrM" assert latex(symbols("BM")) == r"BM" assert latex(symbols("hbar")) == r"\hbar" # Check a few combinations assert latex(symbols("xvecdot")) == r"\dot{\vec{x}}" assert latex(symbols("xDotVec")) == r"\vec{\dot{x}}" assert latex(symbols("xHATNorm")) == r"\left\|{\hat{x}}\right\|" # Check a couple big, ugly combinations assert latex(symbols('xMathringBm_yCheckPRM__zbreveAbs')) == \ r"\boldsymbol{\mathring{x}}^{\left|{\breve{z}}\right|}_{{\check{y}}'}" assert latex(symbols('alphadothat_nVECDOT__tTildePrime')) == \ r"\hat{\dot{\alpha}}^{{\tilde{t}}'}_{\dot{\vec{n}}}" def test_greek_symbols(): assert latex(Symbol('alpha')) == r'\alpha' assert latex(Symbol('beta')) == r'\beta' assert latex(Symbol('gamma')) == r'\gamma' assert latex(Symbol('delta')) == r'\delta' assert latex(Symbol('epsilon')) == r'\epsilon' assert latex(Symbol('zeta')) == r'\zeta' assert latex(Symbol('eta')) == r'\eta' assert latex(Symbol('theta')) == r'\theta' assert latex(Symbol('iota')) == r'\iota' assert latex(Symbol('kappa')) == r'\kappa' assert latex(Symbol('lambda')) == r'\lambda' assert latex(Symbol('mu')) == r'\mu' assert latex(Symbol('nu')) == r'\nu' assert latex(Symbol('xi')) == r'\xi' assert latex(Symbol('omicron')) == r'o' assert latex(Symbol('pi')) == r'\pi' assert latex(Symbol('rho')) == r'\rho' assert latex(Symbol('sigma')) == r'\sigma' assert latex(Symbol('tau')) == r'\tau' assert latex(Symbol('upsilon')) == r'\upsilon' assert latex(Symbol('phi')) == r'\phi' assert latex(Symbol('chi')) == r'\chi' assert latex(Symbol('psi')) == r'\psi' assert latex(Symbol('omega')) == r'\omega' assert latex(Symbol('Alpha')) == r'A' assert latex(Symbol('Beta')) == r'B' assert latex(Symbol('Gamma')) == r'\Gamma' assert latex(Symbol('Delta')) == r'\Delta' assert latex(Symbol('Epsilon')) == r'E' assert latex(Symbol('Zeta')) == r'Z' assert latex(Symbol('Eta')) == r'H' assert latex(Symbol('Theta')) == r'\Theta' assert latex(Symbol('Iota')) == r'I' assert latex(Symbol('Kappa')) == r'K' assert latex(Symbol('Lambda')) == r'\Lambda' assert latex(Symbol('Mu')) == r'M' assert latex(Symbol('Nu')) == r'N' assert latex(Symbol('Xi')) == r'\Xi' assert latex(Symbol('Omicron')) == r'O' assert latex(Symbol('Pi')) == r'\Pi' assert latex(Symbol('Rho')) == r'P' assert latex(Symbol('Sigma')) == r'\Sigma' assert latex(Symbol('Tau')) == r'T' assert latex(Symbol('Upsilon')) == r'\Upsilon' assert latex(Symbol('Phi')) == r'\Phi' assert latex(Symbol('Chi')) == r'X' assert latex(Symbol('Psi')) == r'\Psi' assert latex(Symbol('Omega')) == r'\Omega' assert latex(Symbol('varepsilon')) == r'\varepsilon' assert latex(Symbol('varkappa')) == r'\varkappa' assert latex(Symbol('varphi')) == r'\varphi' assert latex(Symbol('varpi')) == r'\varpi' assert latex(Symbol('varrho')) == r'\varrho' assert latex(Symbol('varsigma')) == r'\varsigma' assert latex(Symbol('vartheta')) == r'\vartheta' def test_fancyset_symbols(): assert latex(S.Rationals) == '\\mathbb{Q}' assert latex(S.Naturals) == '\\mathbb{N}' assert latex(S.Naturals0) == '\\mathbb{N}_0' assert latex(S.Integers) == '\\mathbb{Z}' assert latex(S.Reals) == '\\mathbb{R}' assert latex(S.Complexes) == '\\mathbb{C}' @XFAIL def test_builtin_without_args_mismatched_names(): assert latex(CosineTransform) == r'\mathcal{COS}' def test_builtin_no_args(): assert latex(Chi) == r'\operatorname{Chi}' assert latex(beta) == r'\operatorname{B}' assert latex(gamma) == r'\Gamma' assert latex(KroneckerDelta) == r'\delta' assert latex(DiracDelta) == r'\delta' assert latex(lowergamma) == r'\gamma' def test_issue_6853(): p = Function('Pi') assert latex(p(x)) == r"\Pi{\left(x \right)}" def test_Mul(): e = Mul(-2, x + 1, evaluate=False) assert latex(e) == r'- 2 \left(x + 1\right)' e = Mul(2, x + 1, evaluate=False) assert latex(e) == r'2 \left(x + 1\right)' e = Mul(S.Half, x + 1, evaluate=False) assert latex(e) == r'\frac{x + 1}{2}' e = Mul(y, x + 1, evaluate=False) assert latex(e) == r'y \left(x + 1\right)' e = Mul(-y, x + 1, evaluate=False) assert latex(e) == r'- y \left(x + 1\right)' e = Mul(-2, x + 1) assert latex(e) == r'- 2 x - 2' e = Mul(2, x + 1) assert latex(e) == r'2 x + 2' def test_Pow(): e = Pow(2, 2, evaluate=False) assert latex(e) == r'2^{2}' assert latex(x**(Rational(-1, 3))) == r'\frac{1}{\sqrt[3]{x}}' x2 = Symbol(r'x^2') assert latex(x2**2) == r'\left(x^{2}\right)^{2}' def test_issue_7180(): assert latex(Equivalent(x, y)) == r"x \Leftrightarrow y" assert latex(Not(Equivalent(x, y))) == r"x \not\Leftrightarrow y" def test_issue_8409(): assert latex(S.Half**n) == r"\left(\frac{1}{2}\right)^{n}" def test_issue_8470(): from sympy.parsing.sympy_parser import parse_expr e = parse_expr("-B*A", evaluate=False) assert latex(e) == r"A \left(- B\right)" def test_issue_15439(): x = MatrixSymbol('x', 2, 2) y = MatrixSymbol('y', 2, 2) assert latex((x * y).subs(y, -y)) == r"x \left(- y\right)" assert latex((x * y).subs(y, -2*y)) == r"x \left(- 2 y\right)" assert latex((x * y).subs(x, -x)) == r"- x y" def test_issue_2934(): assert latex(Symbol(r'\frac{a_1}{b_1}')) == '\\frac{a_1}{b_1}' def test_issue_10489(): latexSymbolWithBrace = 'C_{x_{0}}' s = Symbol(latexSymbolWithBrace) assert latex(s) == latexSymbolWithBrace assert latex(cos(s)) == r'\cos{\left(C_{x_{0}} \right)}' def test_issue_12886(): m__1, l__1 = symbols('m__1, l__1') assert latex(m__1**2 + l__1**2) == \ r'\left(l^{1}\right)^{2} + \left(m^{1}\right)^{2}' def test_issue_13559(): from sympy.parsing.sympy_parser import parse_expr expr = parse_expr('5/1', evaluate=False) assert latex(expr) == r"\frac{5}{1}" def test_issue_13651(): expr = c + Mul(-1, a + b, evaluate=False) assert latex(expr) == r"c - \left(a + b\right)" def test_latex_UnevaluatedExpr(): x = symbols("x") he = UnevaluatedExpr(1/x) assert latex(he) == latex(1/x) == r"\frac{1}{x}" assert latex(he**2) == r"\left(\frac{1}{x}\right)^{2}" assert latex(he + 1) == r"1 + \frac{1}{x}" assert latex(x*he) == r"x \frac{1}{x}" def test_MatrixElement_printing(): # test cases for issue #11821 A = MatrixSymbol("A", 1, 3) B = MatrixSymbol("B", 1, 3) C = MatrixSymbol("C", 1, 3) assert latex(A[0, 0]) == r"A_{0, 0}" assert latex(3 * A[0, 0]) == r"3 A_{0, 0}" F = C[0, 0].subs(C, A - B) assert latex(F) == r"\left(A - B\right)_{0, 0}" i, j, k = symbols("i j k") M = MatrixSymbol("M", k, k) N = MatrixSymbol("N", k, k) assert latex((M*N)[i, j]) == \ r'\sum_{i_{1}=0}^{k - 1} M_{i, i_{1}} N_{i_{1}, j}' def test_MatrixSymbol_printing(): # test cases for issue #14237 A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert latex(-A) == r"- A" assert latex(A - A*B - B) == r"A - A B - B" assert latex(-A*B - A*B*C - B) == r"- A B - A B C - B" def test_KroneckerProduct_printing(): A = MatrixSymbol('A', 3, 3) B = MatrixSymbol('B', 2, 2) assert latex(KroneckerProduct(A, B)) == r'A \otimes B' def test_Series_printing(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) tf3 = TransferFunction(t*x**2 - t**w*x + w, t - y, y) assert latex(Series(tf1, tf2)) == \ '\\left(\\frac{x y^{2} - z}{- t^{3} + y^{3}}\\right) \\left(\\frac{x - y}{x + y}\\right)' assert latex(Series(tf1, tf2, tf3)) == \ '\\left(\\frac{x y^{2} - z}{- t^{3} + y^{3}}\\right) \\left(\\frac{x - y}{x + y}\\right) \\left(\\frac{t x^{2} - t^{w} x + w}{t - y}\\right)' assert latex(Series(-tf2, tf1)) == \ '\\left(\\frac{- x + y}{x + y}\\right) \\left(\\frac{x y^{2} - z}{- t^{3} + y^{3}}\\right)' def test_TransferFunction_printing(): tf1 = TransferFunction(x - 1, x + 1, x) assert latex(tf1) == r"\frac{x - 1}{x + 1}" tf2 = TransferFunction(x + 1, 2 - y, x) assert latex(tf2) == r"\frac{x + 1}{2 - y}" tf3 = TransferFunction(y, y**2 + 2*y + 3, y) assert latex(tf3) == r"\frac{y}{y^{2} + 2 y + 3}" def test_Parallel_printing(): tf1 = TransferFunction(x*y**2 - z, y**3 - t**3, y) tf2 = TransferFunction(x - y, x + y, y) assert latex(Parallel(tf1, tf2)) == \ '\\left(\\frac{x y^{2} - z}{- t^{3} + y^{3}}\\right) \\left(\\frac{x - y}{x + y}\\right)' assert latex(Parallel(-tf2, tf1)) == \ '\\left(\\frac{- x + y}{x + y}\\right) \\left(\\frac{x y^{2} - z}{- t^{3} + y^{3}}\\right)' def test_Feedback_printing(): tf1 = TransferFunction(p, p + x, p) tf2 = TransferFunction(-s + p, p + s, p) assert latex(Feedback(tf1, tf2)) == \ '\\frac{\\frac{p}{p + x}}{\\left(1 \\cdot 1^{-1}\\right) \\left(\\left(\\frac{p}{p + x}\\right) \\left(\\frac{p - s}{p + s}\\right)\\right)}' assert latex(Feedback(tf1*tf2, TransferFunction(1, 1, p))) == \ '\\frac{\\left(\\frac{p}{p + x}\\right) \\left(\\frac{p - s}{p + s}\\right)}{\\left(1 \\cdot 1^{-1}\\right) \\left(\\left(\\frac{p}{p + x}\\right) \\left(\\frac{p - s}{p + s}\\right)\\right)}' def test_Quaternion_latex_printing(): q = Quaternion(x, y, z, t) assert latex(q) == "x + y i + z j + t k" q = Quaternion(x, y, z, x*t) assert latex(q) == "x + y i + z j + t x k" q = Quaternion(x, y, z, x + t) assert latex(q) == r"x + y i + z j + \left(t + x\right) k" def test_TensorProduct_printing(): from sympy.tensor.functions import TensorProduct A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) assert latex(TensorProduct(A, B)) == r"A \otimes B" def test_WedgeProduct_printing(): from sympy.diffgeom.rn import R2 from sympy.diffgeom import WedgeProduct wp = WedgeProduct(R2.dx, R2.dy) assert latex(wp) == r"\operatorname{d}x \wedge \operatorname{d}y" def test_issue_9216(): expr_1 = Pow(1, -1, evaluate=False) assert latex(expr_1) == r"1^{-1}" expr_2 = Pow(1, Pow(1, -1, evaluate=False), evaluate=False) assert latex(expr_2) == r"1^{1^{-1}}" expr_3 = Pow(3, -2, evaluate=False) assert latex(expr_3) == r"\frac{1}{9}" expr_4 = Pow(1, -2, evaluate=False) assert latex(expr_4) == r"1^{-2}" def test_latex_printer_tensor(): from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, tensor_heads L = TensorIndexType("L") i, j, k, l = tensor_indices("i j k l", L) i0 = tensor_indices("i_0", L) A, B, C, D = tensor_heads("A B C D", [L]) H = TensorHead("H", [L, L]) K = TensorHead("K", [L, L, L, L]) assert latex(i) == "{}^{i}" assert latex(-i) == "{}_{i}" expr = A(i) assert latex(expr) == "A{}^{i}" expr = A(i0) assert latex(expr) == "A{}^{i_{0}}" expr = A(-i) assert latex(expr) == "A{}_{i}" expr = -3*A(i) assert latex(expr) == r"-3A{}^{i}" expr = K(i, j, -k, -i0) assert latex(expr) == "K{}^{ij}{}_{ki_{0}}" expr = K(i, -j, -k, i0) assert latex(expr) == "K{}^{i}{}_{jk}{}^{i_{0}}" expr = K(i, -j, k, -i0) assert latex(expr) == "K{}^{i}{}_{j}{}^{k}{}_{i_{0}}" expr = H(i, -j) assert latex(expr) == "H{}^{i}{}_{j}" expr = H(i, j) assert latex(expr) == "H{}^{ij}" expr = H(-i, -j) assert latex(expr) == "H{}_{ij}" expr = (1+x)*A(i) assert latex(expr) == r"\left(x + 1\right)A{}^{i}" expr = H(i, -i) assert latex(expr) == "H{}^{L_{0}}{}_{L_{0}}" expr = H(i, -j)*A(j)*B(k) assert latex(expr) == "H{}^{i}{}_{L_{0}}A{}^{L_{0}}B{}^{k}" expr = A(i) + 3*B(i) assert latex(expr) == "3B{}^{i} + A{}^{i}" # Test ``TensorElement``: from sympy.tensor.tensor import TensorElement expr = TensorElement(K(i, j, k, l), {i: 3, k: 2}) assert latex(expr) == 'K{}^{i=3,j,k=2,l}' expr = TensorElement(K(i, j, k, l), {i: 3}) assert latex(expr) == 'K{}^{i=3,jkl}' expr = TensorElement(K(i, -j, k, l), {i: 3, k: 2}) assert latex(expr) == 'K{}^{i=3}{}_{j}{}^{k=2,l}' expr = TensorElement(K(i, -j, k, -l), {i: 3, k: 2}) assert latex(expr) == 'K{}^{i=3}{}_{j}{}^{k=2}{}_{l}' expr = TensorElement(K(i, j, -k, -l), {i: 3, -k: 2}) assert latex(expr) == 'K{}^{i=3,j}{}_{k=2,l}' expr = TensorElement(K(i, j, -k, -l), {i: 3}) assert latex(expr) == 'K{}^{i=3,j}{}_{kl}' expr = PartialDerivative(A(i), A(i)) assert latex(expr) == r"\frac{\partial}{\partial {A{}^{L_{0}}}}{A{}^{L_{0}}}" expr = PartialDerivative(A(-i), A(-j)) assert latex(expr) == r"\frac{\partial}{\partial {A{}_{j}}}{A{}_{i}}" expr = PartialDerivative(K(i, j, -k, -l), A(m), A(-n)) assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}^{m}} \partial {A{}_{n}}}{K{}^{ij}{}_{kl}}" expr = PartialDerivative(B(-i) + A(-i), A(-j), A(-n)) assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}_{j}} \partial {A{}_{n}}}{\left(A{}_{i} + B{}_{i}\right)}" expr = PartialDerivative(3*A(-i), A(-j), A(-n)) assert latex(expr) == r"\frac{\partial^{2}}{\partial {A{}_{j}} \partial {A{}_{n}}}{\left(3A{}_{i}\right)}" def test_multiline_latex(): a, b, c, d, e, f = symbols('a b c d e f') expr = -a + 2*b -3*c +4*d -5*e expected = r"\begin{eqnarray}" + "\n"\ r"f & = &- a \nonumber\\" + "\n"\ r"& & + 2 b \nonumber\\" + "\n"\ r"& & - 3 c \nonumber\\" + "\n"\ r"& & + 4 d \nonumber\\" + "\n"\ r"& & - 5 e " + "\n"\ r"\end{eqnarray}" assert multiline_latex(f, expr, environment="eqnarray") == expected expected2 = r'\begin{eqnarray}' + '\n'\ r'f & = &- a + 2 b \nonumber\\' + '\n'\ r'& & - 3 c + 4 d \nonumber\\' + '\n'\ r'& & - 5 e ' + '\n'\ r'\end{eqnarray}' assert multiline_latex(f, expr, 2, environment="eqnarray") == expected2 expected3 = r'\begin{eqnarray}' + '\n'\ r'f & = &- a + 2 b - 3 c \nonumber\\'+ '\n'\ r'& & + 4 d - 5 e ' + '\n'\ r'\end{eqnarray}' assert multiline_latex(f, expr, 3, environment="eqnarray") == expected3 expected3dots = r'\begin{eqnarray}' + '\n'\ r'f & = &- a + 2 b - 3 c \dots\nonumber\\'+ '\n'\ r'& & + 4 d - 5 e ' + '\n'\ r'\end{eqnarray}' assert multiline_latex(f, expr, 3, environment="eqnarray", use_dots=True) == expected3dots expected3align = r'\begin{align*}' + '\n'\ r'f = &- a + 2 b - 3 c \\'+ '\n'\ r'& + 4 d - 5 e ' + '\n'\ r'\end{align*}' assert multiline_latex(f, expr, 3) == expected3align assert multiline_latex(f, expr, 3, environment='align*') == expected3align expected2ieee = r'\begin{IEEEeqnarray}{rCl}' + '\n'\ r'f & = &- a + 2 b \nonumber\\' + '\n'\ r'& & - 3 c + 4 d \nonumber\\' + '\n'\ r'& & - 5 e ' + '\n'\ r'\end{IEEEeqnarray}' assert multiline_latex(f, expr, 2, environment="IEEEeqnarray") == expected2ieee raises(ValueError, lambda: multiline_latex(f, expr, environment="foo")) def test_issue_15353(): from sympy import ConditionSet, Tuple, S, sin, cos a, x = symbols('a x') # Obtained from nonlinsolve([(sin(a*x)),cos(a*x)],[x,a]) sol = ConditionSet( Tuple(x, a), Eq(sin(a*x), 0) & Eq(cos(a*x), 0), S.Complexes**2) assert latex(sol) == \ r'\left\{\left( x, \ a\right) \mid \left( x, \ a\right) \in ' \ r'\mathbb{C}^{2} \wedge \sin{\left(a x \right)} = 0 \wedge ' \ r'\cos{\left(a x \right)} = 0 \right\}' def test_trace(): # Issue 15303 from sympy import trace A = MatrixSymbol("A", 2, 2) assert latex(trace(A)) == r"\operatorname{tr}\left(A \right)" assert latex(trace(A**2)) == r"\operatorname{tr}\left(A^{2} \right)" def test_print_basic(): # Issue 15303 from sympy import Basic, Expr # dummy class for testing printing where the function is not # implemented in latex.py class UnimplementedExpr(Expr): def __new__(cls, e): return Basic.__new__(cls, e) # dummy function for testing def unimplemented_expr(expr): return UnimplementedExpr(expr).doit() # override class name to use superscript / subscript def unimplemented_expr_sup_sub(expr): result = UnimplementedExpr(expr) result.__class__.__name__ = 'UnimplementedExpr_x^1' return result assert latex(unimplemented_expr(x)) == r'UnimplementedExpr\left(x\right)' assert latex(unimplemented_expr(x**2)) == \ r'UnimplementedExpr\left(x^{2}\right)' assert latex(unimplemented_expr_sup_sub(x)) == \ r'UnimplementedExpr^{1}_{x}\left(x\right)' def test_MatrixSymbol_bold(): # Issue #15871 from sympy import trace A = MatrixSymbol("A", 2, 2) assert latex(trace(A), mat_symbol_style='bold') == \ r"\operatorname{tr}\left(\mathbf{A} \right)" assert latex(trace(A), mat_symbol_style='plain') == \ r"\operatorname{tr}\left(A \right)" A = MatrixSymbol("A", 3, 3) B = MatrixSymbol("B", 3, 3) C = MatrixSymbol("C", 3, 3) assert latex(-A, mat_symbol_style='bold') == r"- \mathbf{A}" assert latex(A - A*B - B, mat_symbol_style='bold') == \ r"\mathbf{A} - \mathbf{A} \mathbf{B} - \mathbf{B}" assert latex(-A*B - A*B*C - B, mat_symbol_style='bold') == \ r"- \mathbf{A} \mathbf{B} - \mathbf{A} \mathbf{B} \mathbf{C} - \mathbf{B}" A_k = MatrixSymbol("A_k", 3, 3) assert latex(A_k, mat_symbol_style='bold') == r"\mathbf{A}_{k}" A = MatrixSymbol(r"\nabla_k", 3, 3) assert latex(A, mat_symbol_style='bold') == r"\mathbf{\nabla}_{k}" def test_AppliedPermutation(): p = Permutation(0, 1, 2) x = Symbol('x') assert latex(AppliedPermutation(p, x)) == \ r'\sigma_{\left( 0\; 1\; 2\right)}(x)' def test_PermutationMatrix(): p = Permutation(0, 1, 2) assert latex(PermutationMatrix(p)) == r'P_{\left( 0\; 1\; 2\right)}' p = Permutation(0, 3)(1, 2) assert latex(PermutationMatrix(p)) == \ r'P_{\left( 0\; 3\right)\left( 1\; 2\right)}' def test_imaginary_unit(): assert latex(1 + I) == '1 + i' assert latex(1 + I, imaginary_unit='i') == '1 + i' assert latex(1 + I, imaginary_unit='j') == '1 + j' assert latex(1 + I, imaginary_unit='foo') == '1 + foo' assert latex(I, imaginary_unit="ti") == '\\text{i}' assert latex(I, imaginary_unit="tj") == '\\text{j}' def test_text_re_im(): assert latex(im(x), gothic_re_im=True) == r'\Im{\left(x\right)}' assert latex(im(x), gothic_re_im=False) == r'\operatorname{im}{\left(x\right)}' assert latex(re(x), gothic_re_im=True) == r'\Re{\left(x\right)}' assert latex(re(x), gothic_re_im=False) == r'\operatorname{re}{\left(x\right)}' def test_latex_diffgeom(): from sympy.diffgeom import Manifold, Patch, CoordSystem, BaseScalarField, Differential from sympy.diffgeom.rn import R2 x,y = symbols('x y', real=True) m = Manifold('M', 2) assert latex(m) == r'\text{M}' p = Patch('P', m) assert latex(p) == r'\text{P}_{\text{M}}' rect = CoordSystem('rect', p, [x, y]) assert latex(rect) == r'\text{rect}^{\text{P}}_{\text{M}}' b = BaseScalarField(rect, 0) assert latex(b) == r'\mathbf{x}' g = Function('g') s_field = g(R2.x, R2.y) assert latex(Differential(s_field)) == \ r'\operatorname{d}\left(g{\left(\mathbf{x},\mathbf{y} \right)}\right)' def test_unit_printing(): assert latex(5*meter) == r'5 \text{m}' assert latex(3*gibibyte) == r'3 \text{gibibyte}' assert latex(4*microgram/second) == r'\frac{4 \mu\text{g}}{\text{s}}' def test_issue_17092(): x_star = Symbol('x^*') assert latex(Derivative(x_star, x_star,2)) == r'\frac{d^{2}}{d \left(x^{*}\right)^{2}} x^{*}' def test_latex_decimal_separator(): x, y, z, t = symbols('x y z t') k, m, n = symbols('k m n', integer=True) f, g, h = symbols('f g h', cls=Function) # comma decimal_separator assert(latex([1, 2.3, 4.5], decimal_separator='comma') == r'\left[ 1; \ 2{,}3; \ 4{,}5\right]') assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='comma') == r'\left\{1; 2{,}3; 4{,}5\right\}') assert(latex((1, 2.3, 4.6), decimal_separator = 'comma') == r'\left( 1; \ 2{,}3; \ 4{,}6\right)') assert(latex((1,), decimal_separator='comma') == r'\left( 1;\right)') # period decimal_separator assert(latex([1, 2.3, 4.5], decimal_separator='period') == r'\left[ 1, \ 2.3, \ 4.5\right]' ) assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='period') == r'\left\{1, 2.3, 4.5\right\}') assert(latex((1, 2.3, 4.6), decimal_separator = 'period') == r'\left( 1, \ 2.3, \ 4.6\right)') assert(latex((1,), decimal_separator='period') == r'\left( 1,\right)') # default decimal_separator assert(latex([1, 2.3, 4.5]) == r'\left[ 1, \ 2.3, \ 4.5\right]') assert(latex(FiniteSet(1, 2.3, 4.5)) == r'\left\{1, 2.3, 4.5\right\}') assert(latex((1, 2.3, 4.6)) == r'\left( 1, \ 2.3, \ 4.6\right)') assert(latex((1,)) == r'\left( 1,\right)') assert(latex(Mul(3.4,5.3), decimal_separator = 'comma') ==r'18{,}02') assert(latex(3.4*5.3, decimal_separator = 'comma')==r'18{,}02') x = symbols('x') y = symbols('y') z = symbols('z') assert(latex(x*5.3 + 2**y**3.4 + 4.5 + z, decimal_separator = 'comma')== r'2^{y^{3{,}4}} + 5{,}3 x + z + 4{,}5') assert(latex(0.987, decimal_separator='comma') == r'0{,}987') assert(latex(S(0.987), decimal_separator='comma')== r'0{,}987') assert(latex(.3, decimal_separator='comma')== r'0{,}3') assert(latex(S(.3), decimal_separator='comma')== r'0{,}3') assert(latex(5.8*10**(-7), decimal_separator='comma') ==r'5{,}8 \cdot 10^{-7}') assert(latex(S(5.7)*10**(-7), decimal_separator='comma')==r'5{,}7 \cdot 10^{-7}') assert(latex(S(5.7*10**(-7)), decimal_separator='comma')==r'5{,}7 \cdot 10^{-7}') x = symbols('x') assert(latex(1.2*x+3.4, decimal_separator='comma')==r'1{,}2 x + 3{,}4') assert(latex(FiniteSet(1, 2.3, 4.5), decimal_separator='period')==r'\left\{1, 2.3, 4.5\right\}') # Error Handling tests raises(ValueError, lambda: latex([1,2.3,4.5], decimal_separator='non_existing_decimal_separator_in_list')) raises(ValueError, lambda: latex(FiniteSet(1,2.3,4.5), decimal_separator='non_existing_decimal_separator_in_set')) raises(ValueError, lambda: latex((1,2.3,4.5), decimal_separator='non_existing_decimal_separator_in_tuple')) def test_Str(): from sympy.core.symbol import Str assert str(Str('x')) == 'x' def test_latex_escape(): assert latex_escape(r"~^\&%$#_{}") == "".join([ r'\textasciitilde', r'\textasciicircum', r'\textbackslash', r'\&', r'\%', r'\$', r'\#', r'\_', r'\{', r'\}', ]) def test_emptyPrinter(): class MyObject: def __repr__(self): return "<MyObject with {...}>" # unknown objects are monospaced assert latex(MyObject()) == r"\mathtt{\text{<MyObject with \{...\}>}}" # even if they are nested within other objects assert latex((MyObject(),)) == r"\left( \mathtt{\text{<MyObject with \{...\}>}},\right)" def test_global_settings(): import inspect # settings should be visible in the signature of `latex` assert inspect.signature(latex).parameters['imaginary_unit'].default == 'i' assert latex(I) == 'i' try: # but changing the defaults... LatexPrinter.set_global_settings(imaginary_unit='j') # ... should change the signature assert inspect.signature(latex).parameters['imaginary_unit'].default == 'j' assert latex(I) == 'j' finally: # there's no public API to undo this, but we need to make sure we do # so as not to impact other tests del LatexPrinter._global_settings['imaginary_unit'] # check we really did undo it assert inspect.signature(latex).parameters['imaginary_unit'].default == 'i' assert latex(I) == 'i' def test_pickleable(): # this tests that the _PrintFunction instance is pickleable import pickle assert pickle.loads(pickle.dumps(latex)) is latex
fc89eb28a94e0dcfe17487ad453c7fe7b543610f9b1fc299a4d99cd0fcaab850
from __future__ import unicode_literals, print_function from sympy.external import import_module import os cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']}) """ This module contains all the necessary Classes and Function used to Parse C and C++ code into SymPy expression The module serves as a backend for SymPyExpression to parse C code It is also dependent on Clang's AST and Sympy's Codegen AST. The module only supports the features currently supported by the Clang and codegen AST which will be updated as the development of codegen AST and this module progresses. You might find unexpected bugs and exceptions while using the module, feel free to report them to the SymPy Issue Tracker Features Supported ================== - Variable Declarations (integers and reals) - Assignment (using integer & floating literal and function calls) - Function Definitions nad Declaration - Function Calls - Compound statements, Return statements Notes ===== The module is dependent on an external dependency which needs to be installed to use the features of this module. Clang: The C and C++ compiler which is used to extract an AST from the provided C source code. Refrences ========= .. [1] https://github.com/sympy/sympy/issues .. [2] https://clang.llvm.org/docs/ .. [3] https://clang.llvm.org/docs/IntroductionToTheClangAST.html """ if cin: from sympy.codegen.ast import (Variable, Integer, Float, FunctionPrototype, FunctionDefinition, FunctionCall, none, Return, Assignment, intc, int8, int16, int64, uint8, uint16, uint32, uint64, float32, float64, float80, aug_assign, bool_, While, CodeBlock) from sympy.codegen.cnodes import (PreDecrement, PostDecrement, PreIncrement, PostIncrement) from sympy.core import Add, Mod, Mul, Pow, Rel from sympy.logic.boolalg import And, as_Boolean, Not, Or from sympy import Symbol, sympify, true, false import sys import tempfile class BaseParser(object): """Base Class for the C parser""" def __init__(self): """Initializes the Base parser creating a Clang AST index""" self.index = cin.Index.create() def diagnostics(self, out): """Diagostics function for the Clang AST""" for diag in self.tu.diagnostics: print('%s %s (line %s, col %s) %s' % ( { 4: 'FATAL', 3: 'ERROR', 2: 'WARNING', 1: 'NOTE', 0: 'IGNORED', }[diag.severity], diag.location.file, diag.location.line, diag.location.column, diag.spelling ), file=out) class CCodeConverter(BaseParser): """The Code Convereter for Clang AST The converter object takes the C source code or file as input and converts them to SymPy Expressions. """ def __init__(self): """Initializes the code converter""" super(CCodeConverter, self).__init__() self._py_nodes = [] self._data_types = { "void": { cin.TypeKind.VOID: none }, "bool": { cin.TypeKind.BOOL: bool_ }, "int": { cin.TypeKind.SCHAR: int8, cin.TypeKind.SHORT: int16, cin.TypeKind.INT: intc, cin.TypeKind.LONG: int64, cin.TypeKind.UCHAR: uint8, cin.TypeKind.USHORT: uint16, cin.TypeKind.UINT: uint32, cin.TypeKind.ULONG: uint64 }, "float": { cin.TypeKind.FLOAT: float32, cin.TypeKind.DOUBLE: float64, cin.TypeKind.LONGDOUBLE: float80 } } def parse(self, filenames, flags): """Function to parse a file with C source code It takes the filename as an attribute and creates a Clang AST Translation Unit parsing the file. Then the transformation function is called on the transaltion unit, whose reults are collected into a list which is returned by the function. Parameters ========== filenames : string Path to the C file to be parsed flags: list Arguments to be passed to Clang while parsing the C code Returns ======= py_nodes: list A list of sympy AST nodes """ filename = os.path.abspath(filenames) self.tu = self.index.parse( filename, args=flags, options=cin.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD ) for child in self.tu.cursor.get_children(): if child.kind == cin.CursorKind.VAR_DECL: self._py_nodes.append(self.transform(child)) elif (child.kind == cin.CursorKind.FUNCTION_DECL): self._py_nodes.append(self.transform(child)) else: pass return self._py_nodes def parse_str(self, source, flags): """Function to parse a string with C source code It takes the source code as an attribute, stores it in a temporary file and creates a Clang AST Translation Unit parsing the file. Then the transformation function is called on the transaltion unit, whose reults are collected into a list which is returned by the function. Parameters ========== source : string Path to the C file to be parsed flags: list Arguments to be passed to Clang while parsing the C code Returns ======= py_nodes: list A list of sympy AST nodes """ file = tempfile.NamedTemporaryFile(mode = 'w+', suffix = '.cpp') file.write(source) file.seek(0) self.tu = self.index.parse( file.name, args=flags, options=cin.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD ) file.close() for child in self.tu.cursor.get_children(): if child.kind == cin.CursorKind.VAR_DECL: self._py_nodes.append(self.transform(child)) elif (child.kind == cin.CursorKind.FUNCTION_DECL): self._py_nodes.append(self.transform(child)) else: pass return self._py_nodes def transform(self, node): """Transformation Function for Clang AST nodes It determines the kind of node and calls the respective transformation function for that node. Raises ====== NotImplementedError : if the transformation for the provided node is not implemented """ try: handler = getattr(self, 'transform_%s' % node.kind.name.lower()) except AttributeError: print( "Ignoring node of type %s (%s)" % ( node.kind, ' '.join( t.spelling for t in node.get_tokens()) ), file=sys.stderr ) handler = None if handler: result = handler(node) return result def transform_var_decl(self, node): """Transformation Function for Variable Declaration Used to create nodes for variable declarations and assignments with values or function call for the respective nodes in the clang AST Returns ======= A variable node as Declaration, with the initial value if given Raises ====== NotImplementedError : if called for data types not currently implemented Notes ===== The function currently supports following data types: Boolean: bool, _Bool Integer: 8-bit: signed char and unsigned char 16-bit: short, short int, signed short, signed short int, unsigned short, unsigned short int 32-bit: int, signed int, unsigned int 64-bit: long, long int, signed long, signed long int, unsigned long, unsigned long int Floating point: Single Precision: float Double Precision: double Extended Precision: long double """ if node.type.kind in self._data_types["int"]: type = self._data_types["int"][node.type.kind] elif node.type.kind in self._data_types["float"]: type = self._data_types["float"][node.type.kind] elif node.type.kind in self._data_types["bool"]: type = self._data_types["bool"][node.type.kind] else: raise NotImplementedError("Only bool, int " "and float are supported") try: children = node.get_children() child = next(children) #ignoring namespace and type details for the variable while child.kind == cin.CursorKind.NAMESPACE_REF: child = next(children) while child.kind == cin.CursorKind.TYPE_REF: child = next(children) val = self.transform(child) supported_rhs = [ cin.CursorKind.INTEGER_LITERAL, cin.CursorKind.FLOATING_LITERAL, cin.CursorKind.UNEXPOSED_EXPR, cin.CursorKind.BINARY_OPERATOR, cin.CursorKind.PAREN_EXPR, cin.CursorKind.UNARY_OPERATOR, cin.CursorKind.CXX_BOOL_LITERAL_EXPR ] if child.kind in supported_rhs: if isinstance(val, str): value = Symbol(val) elif isinstance(val, bool): if node.type.kind in self._data_types["int"]: value = Integer(0) if val == False else Integer(1) elif node.type.kind in self._data_types["float"]: value = Float(0.0) if val == False else Float(1.0) elif node.type.kind in self._data_types["bool"]: value = sympify(val) elif isinstance(val, (Integer, int, Float, float)): if node.type.kind in self._data_types["int"]: value = Integer(val) elif node.type.kind in self._data_types["float"]: value = Float(val) elif node.type.kind in self._data_types["bool"]: value = sympify(bool(val)) else: value = val return Variable( node.spelling ).as_Declaration( type = type, value = value ) elif child.kind == cin.CursorKind.CALL_EXPR: return Variable( node.spelling ).as_Declaration( value = val ) else: raise NotImplementedError("Given " "variable declaration \"{}\" " "is not possible to parse yet!" .format(" ".join( t.spelling for t in node.get_tokens() ) )) except StopIteration: return Variable( node.spelling ).as_Declaration( type = type ) def transform_function_decl(self, node): """Transformation Function For Function Declaration Used to create nodes for function declarations and definitions for the respective nodes in the clang AST Returns ======= function : Codegen AST node - FunctionPrototype node if function body is not present - FunctionDefinition node if the function body is present """ if node.result_type.kind in self._data_types["int"]: ret_type = self._data_types["int"][node.result_type.kind] elif node.result_type.kind in self._data_types["float"]: ret_type = self._data_types["float"][node.result_type.kind] elif node.result_type.kind in self._data_types["bool"]: ret_type = self._data_types["bool"][node.result_type.kind] elif node.result_type.kind in self._data_types["void"]: ret_type = self._data_types["void"][node.result_type.kind] else: raise NotImplementedError("Only void, bool, int " "and float are supported") body = [] param = [] try: children = node.get_children() child = next(children) # If the node has any children, the first children will be the # return type and namespace for the function declaration. These # nodes can be ignored. while child.kind == cin.CursorKind.NAMESPACE_REF: child = next(children) while child.kind == cin.CursorKind.TYPE_REF: child = next(children) # Subsequent nodes will be the parameters for the function. try: while True: decl = self.transform(child) if (child.kind == cin.CursorKind.PARM_DECL): param.append(decl) elif (child.kind == cin.CursorKind.COMPOUND_STMT): for val in decl: body.append(val) else: body.append(decl) child = next(children) except StopIteration: pass except StopIteration: pass if body == []: function = FunctionPrototype( return_type = ret_type, name = node.spelling, parameters = param ) else: function = FunctionDefinition( return_type = ret_type, name = node.spelling, parameters = param, body = body ) return function def transform_parm_decl(self, node): """Transformation function for Parameter Declaration Used to create parameter nodes for the required functions for the respective nodes in the clang AST Returns ======= param : Codegen AST Node Variable node with the value nad type of the variable Raises ====== ValueError if multiple children encountered in the parameter node """ if node.type.kind in self._data_types["int"]: type = self._data_types["int"][node.type.kind] elif node.type.kind in self._data_types["float"]: type = self._data_types["float"][node.type.kind] elif node.type.kind in self._data_types["bool"]: type = self._data_types["bool"][node.type.kind] else: raise NotImplementedError("Only bool, int " "and float are supported") try: children = node.get_children() child = next(children) # Any namespace nodes can be ignored while child.kind in [cin.CursorKind.NAMESPACE_REF, cin.CursorKind.TYPE_REF, cin.CursorKind.TEMPLATE_REF]: child = next(children) # If there is a child, it is the default value of the parameter. lit = self.transform(child) if node.type.kind in self._data_types["int"]: val = Integer(lit) elif node.type.kind in self._data_types["float"]: val = Float(lit) elif node.type.kind in self._data_types["bool"]: val = sympify(bool(lit)) else: raise NotImplementedError("Only bool, int " "and float are supported") param = Variable( node.spelling ).as_Declaration( type = type, value = val ) except StopIteration: param = Variable( node.spelling ).as_Declaration( type = type ) try: self.transform(next(children)) raise ValueError("Can't handle multiple children on parameter") except StopIteration: pass return param def transform_integer_literal(self, node): """Transformation function for integer literal Used to get the value and type of the given integer literal. Returns ======= val : list List with two arguments type and Value type contains the type of the integer value contains the value stored in the variable Notes ===== Only Base Integer type supported for now """ try: value = next(node.get_tokens()).spelling except StopIteration: # No tokens value = node.literal return int(value) def transform_floating_literal(self, node): """Transformation function for floating literal Used to get the value and type of the given floating literal. Returns ======= val : list List with two arguments type and Value type contains the type of float value contains the value stored in the variable Notes ===== Only Base Float type supported for now """ try: value = next(node.get_tokens()).spelling except (StopIteration, ValueError): # No tokens value = node.literal return float(value) def transform_string_literal(self, node): #TODO: No string type in AST #type = #try: # value = next(node.get_tokens()).spelling #except (StopIteration, ValueError): # No tokens # value = node.literal #val = [type, value] #return val pass def transform_character_literal(self, node): """Transformation function for character literal Used to get the value of the given character literal. Returns ======= val : int val contains the ascii value of the character literal Notes ===== Only for cases where character is assigned to a integer value, since character literal is not in sympy AST """ try: value = next(node.get_tokens()).spelling except (StopIteration, ValueError): # No tokens value = node.literal return ord(str(value[1])) def transform_cxx_bool_literal_expr(self, node): """Transformation function for boolean literal Used to get the value of the given boolean literal. Returns ======= value : bool value contains the boolean value of the variable """ try: value = next(node.get_tokens()).spelling except (StopIteration, ValueError): value = node.literal return True if value == 'true' else False def transform_unexposed_decl(self,node): """Transformation function for unexposed declarations""" pass def transform_unexposed_expr(self, node): """Transformation function for unexposed expression Unexposed expressions are used to wrap float, double literals and expressions Returns ======= expr : Codegen AST Node the result from the wrapped expression None : NoneType No childs are found for the node Raises ====== ValueError if the expression contains multiple children """ # Ignore unexposed nodes; pass whatever is the first # (and should be only) child unaltered. try: children = node.get_children() expr = self.transform(next(children)) except StopIteration: return None try: next(children) raise ValueError("Unexposed expression has > 1 children.") except StopIteration: pass return expr def transform_decl_ref_expr(self, node): """Returns the name of the declaration reference""" return node.spelling def transform_call_expr(self, node): """Transformation function for a call expression Used to create function call nodes for the function calls present in the C code Returns ======= FunctionCall : Codegen AST Node FunctionCall node with parameters if any parameters are present """ param = [] children = node.get_children() child = next(children) while child.kind == cin.CursorKind.NAMESPACE_REF: child = next(children) while child.kind == cin.CursorKind.TYPE_REF: child = next(children) first_child = self.transform(child) try: for child in children: arg = self.transform(child) if (child.kind == cin.CursorKind.INTEGER_LITERAL): param.append(Integer(arg)) elif (child.kind == cin.CursorKind.FLOATING_LITERAL): param.append(Float(arg)) else: param.append(arg) return FunctionCall(first_child, param) except StopIteration: return FunctionCall(first_child) def transform_return_stmt(self, node): """Returns the Return Node for a return statement""" return Return(next(node.get_children()).spelling) def transform_compound_stmt(self, node): """Transformation function for compond statemets Returns ======= expr : list list of Nodes for the expressions present in the statement None : NoneType if the compound statement is empty """ try: expr = [] children = node.get_children() for child in children: expr.append(self.transform(child)) except StopIteration: return None return expr def transform_decl_stmt(self, node): """Transformation function for declaration statements These statements are used to wrap different kinds of declararions like variable or function declaration The function calls the transformer function for the child of the given node Returns ======= statement : Codegen AST Node contains the node returned by the children node for the type of declaration Raises ====== ValueError if multiple children present """ try: children = node.get_children() statement = self.transform(next(children)) except StopIteration: pass try: self.transform(next(children)) raise ValueError("Don't know how to handle multiple statements") except StopIteration: pass return statement def transform_paren_expr(self, node): """Transformation function for Parenthesized expressions Returns the result from its children nodes """ return self.transform(next(node.get_children())) def transform_compound_assignment_operator(self, node): """Transformation function for handling shorthand operators Returns ======= augmented_assignment_expression: Codegen AST node shorthand assignment expression represented as Codegen AST Raises ====== NotImplementedError If the shorthand operator for bitwise operators (~=, ^=, &=, |=, <<=, >>=) is encountered """ return self.transform_binary_operator(node) def transform_unary_operator(self, node): """Transformation function for handling unary operators Returns ======= unary_expression: Codegen AST node simplified unary expression represented as Codegen AST Raises ====== NotImplementedError If dereferencing operator(*), address operator(&) or bitwise NOT operator(~) is encountered """ # supported operators list operators_list = ['+', '-', '++', '--', '!'] tokens = [token for token in node.get_tokens()] # it can be either pre increment/decrement or any other operator from the list if tokens[0].spelling in operators_list: child = self.transform(next(node.get_children())) # (decl_ref) e.g.; int a = ++b; or simply ++b; if isinstance(child, str): if tokens[0].spelling == '+': return Symbol(child) if tokens[0].spelling == '-': return Mul(Symbol(child), -1) if tokens[0].spelling == '++': return PreIncrement(Symbol(child)) if tokens[0].spelling == '--': return PreDecrement(Symbol(child)) if tokens[0].spelling == '!': return Not(Symbol(child)) # e.g.; int a = -1; or int b = -(1 + 2); else: if tokens[0].spelling == '+': return child if tokens[0].spelling == '-': return Mul(child, -1) if tokens[0].spelling == '!': return Not(sympify(bool(child))) # it can be either post increment/decrement # since variable name is obtained in token[0].spelling elif tokens[1].spelling in ['++', '--']: child = self.transform(next(node.get_children())) if tokens[1].spelling == '++': return PostIncrement(Symbol(child)) if tokens[1].spelling == '--': return PostDecrement(Symbol(child)) else: raise NotImplementedError("Dereferencing operator, " "Address operator and bitwise NOT operator " "have not been implemented yet!") def transform_binary_operator(self, node): """Transformation function for handling binary operators Returns ======= binary_expression: Codegen AST node simplified binary expression represented as Codegen AST Raises ====== NotImplementedError If a bitwise operator or unary operator(which is a child of any binary operator in Clang AST) is encountered """ # get all the tokens of assignment # and store it in the tokens list tokens = [token for token in node.get_tokens()] # supported operators list operators_list = ['+', '-', '*', '/', '%','=', '>', '>=', '<', '<=', '==', '!=', '&&', '||', '+=', '-=', '*=', '/=', '%='] # this stack will contain variable content # and type of variable in the rhs combined_variables_stack = [] # this stack will contain operators # to be processed in the rhs operators_stack = [] # iterate through every token for token in tokens: # token is either '(', ')' or # any of the supported operators from the operator list if token.kind == cin.TokenKind.PUNCTUATION: # push '(' to the operators stack if token.spelling == '(': operators_stack.append('(') elif token.spelling == ')': # keep adding the expression to the # combined variables stack unless # '(' is found while (operators_stack and operators_stack[-1] != '('): if len(combined_variables_stack) < 2: raise NotImplementedError( "Unary operators as a part of " "binary operators is not " "supported yet!") rhs = combined_variables_stack.pop() lhs = combined_variables_stack.pop() operator = operators_stack.pop() combined_variables_stack.append( self.perform_operation( lhs, rhs, operator)) # pop '(' operators_stack.pop() # token is an operator (supported) elif token.spelling in operators_list: while (operators_stack and self.priority_of(token.spelling) <= self.priority_of( operators_stack[-1])): if len(combined_variables_stack) < 2: raise NotImplementedError( "Unary operators as a part of " "binary operators is not " "supported yet!") rhs = combined_variables_stack.pop() lhs = combined_variables_stack.pop() operator = operators_stack.pop() combined_variables_stack.append( self.perform_operation( lhs, rhs, operator)) # push current operator operators_stack.append(token.spelling) # token is a bitwise operator elif token.spelling in ['&', '|', '^', '<<', '>>']: raise NotImplementedError( "Bitwise operator has not been " "implemented yet!") # token is a shorthand bitwise operator elif token.spelling in ['&=', '|=', '^=', '<<=', '>>=']: raise NotImplementedError( "Shorthand bitwise operator has not been " "implemented yet!") else: raise NotImplementedError( "Given token {} is not implemented yet!" .format(token.spelling)) # token is an identifier(variable) elif token.kind == cin.TokenKind.IDENTIFIER: combined_variables_stack.append( [token.spelling, 'identifier']) # token is a literal elif token.kind == cin.TokenKind.LITERAL: combined_variables_stack.append( [token.spelling, 'literal']) # token is a keyword, either true or false elif (token.kind == cin.TokenKind.KEYWORD and token.spelling in ['true', 'false']): combined_variables_stack.append( [token.spelling, 'boolean']) else: raise NotImplementedError( "Given token {} is not implemented yet!" .format(token.spelling)) # process remaining operators while operators_stack: if len(combined_variables_stack) < 2: raise NotImplementedError( "Unary operators as a part of " "binary operators is not " "supported yet!") rhs = combined_variables_stack.pop() lhs = combined_variables_stack.pop() operator = operators_stack.pop() combined_variables_stack.append( self.perform_operation(lhs, rhs, operator)) return combined_variables_stack[-1][0] def priority_of(self, op): """To get the priority of given operator""" if op in ['=', '+=', '-=', '*=', '/=', '%=']: return 1 if op in ['&&', '||']: return 2 if op in ['<', '<=', '>', '>=', '==', '!=']: return 3 if op in ['+', '-']: return 4 if op in ['*', '/', '%']: return 5 return 0 def perform_operation(self, lhs, rhs, op): """Performs operation supported by the sympy core Returns ======= combined_variable: list contains variable content and type of variable """ lhs_value = self.get_expr_for_operand(lhs) rhs_value = self.get_expr_for_operand(rhs) if op == '+': return [Add(lhs_value, rhs_value), 'expr'] if op == '-': return [Add(lhs_value, -rhs_value), 'expr'] if op == '*': return [Mul(lhs_value, rhs_value), 'expr'] if op == '/': return [Mul(lhs_value, Pow(rhs_value, Integer(-1))), 'expr'] if op == '%': return [Mod(lhs_value, rhs_value), 'expr'] if op in ['<', '<=', '>', '>=', '==', '!=']: return [Rel(lhs_value, rhs_value, op), 'expr'] if op == '&&': return [And(as_Boolean(lhs_value), as_Boolean(rhs_value)), 'expr'] if op == '||': return [Or(as_Boolean(lhs_value), as_Boolean(rhs_value)), 'expr'] if op == '=': return [Assignment(Variable(lhs_value), rhs_value), 'expr'] if op in ['+=', '-=', '*=', '/=', '%=']: return [aug_assign(Variable(lhs_value), op[0], rhs_value), 'expr'] def get_expr_for_operand(self, combined_variable): """Gives out SymPy Codegen AST node AST node returned is corresponding to combined variable passed.Combined variable contains variable content and type of variable """ if combined_variable[1] == 'identifier': return Symbol(combined_variable[0]) if combined_variable[1] == 'literal': if '.' in combined_variable[0]: return Float(float(combined_variable[0])) else: return Integer(int(combined_variable[0])) if combined_variable[1] == 'expr': return combined_variable[0] if combined_variable[1] == 'boolean': return true if combined_variable[0] == 'true' else false def transform_null_stmt(self, node): """Handles Null Statement and returns None""" return none def transform_while_stmt(self, node): """Transformation function for handling while statement Returns ======= while statement : Codegen AST Node contains the while statement node having condition and statement block """ children = node.get_children() condition = self.transform(next(children)) statements = self.transform(next(children)) if isinstance(statements, list): statement_block = CodeBlock(*statements) else: statement_block = CodeBlock(statements) return While(condition, statement_block) else: class CCodeConverter(): # type: ignore def __init__(self, *args, **kwargs): raise ImportError("Module not Installed") def parse_c(source): """Function for converting a C source code The function reads the source code present in the given file and parses it to give out SymPy Expressions Returns ======= src : list List of Python expression strings """ converter = CCodeConverter() if os.path.exists(source): src = converter.parse(source, flags = []) else: src = converter.parse_str(source, flags = []) return src
c2f0b8531741b12da432e2b8ebfbcf8115940f80a0bbf54eb69daa194f62761b
from sympy.core.backend import zeros, Matrix, diff, eye from sympy import solve_linear_system_LU from sympy.utilities import default_sort_key from sympy.physics.vector import (ReferenceFrame, dynamicsymbols, partial_velocity) from sympy.physics.mechanics.particle import Particle from sympy.physics.mechanics.rigidbody import RigidBody from sympy.physics.mechanics.functions import (msubs, find_dynamicsymbols, _f_list_parser) from sympy.physics.mechanics.linearize import Linearizer from sympy.utilities.exceptions import SymPyDeprecationWarning from sympy.utilities.iterables import iterable __all__ = ['KanesMethod'] class KanesMethod: """Kane's method object. This object is used to do the "book-keeping" as you go through and form equations of motion in the way Kane presents in: Kane, T., Levinson, D. Dynamics Theory and Applications. 1985 McGraw-Hill The attributes are for equations in the form [M] udot = forcing. Attributes ========== q, u : Matrix Matrices of the generalized coordinates and speeds bodylist : iterable Iterable of Point and RigidBody objects in the system. forcelist : iterable Iterable of (Point, vector) or (ReferenceFrame, vector) tuples describing the forces on the system. auxiliary : Matrix If applicable, the set of auxiliary Kane's equations used to solve for non-contributing forces. mass_matrix : Matrix The system's mass matrix forcing : Matrix The system's forcing vector mass_matrix_full : Matrix The "mass matrix" for the u's and q's forcing_full : Matrix The "forcing vector" for the u's and q's Examples ======== This is a simple example for a one degree of freedom translational spring-mass-damper. In this example, we first need to do the kinematics. This involves creating generalized speeds and coordinates and their derivatives. Then we create a point and set its velocity in a frame. >>> from sympy import symbols >>> from sympy.physics.mechanics import dynamicsymbols, ReferenceFrame >>> from sympy.physics.mechanics import Point, Particle, KanesMethod >>> q, u = dynamicsymbols('q u') >>> qd, ud = dynamicsymbols('q u', 1) >>> m, c, k = symbols('m c k') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, u * N.x) Next we need to arrange/store information in the way that KanesMethod requires. The kinematic differential equations need to be stored in a dict. A list of forces/torques must be constructed, where each entry in the list is a (Point, Vector) or (ReferenceFrame, Vector) tuple, where the Vectors represent the Force or Torque. Next a particle needs to be created, and it needs to have a point and mass assigned to it. Finally, a list of all bodies and particles needs to be created. >>> kd = [qd - u] >>> FL = [(P, (-k * q - c * u) * N.x)] >>> pa = Particle('pa', P, m) >>> BL = [pa] Finally we can generate the equations of motion. First we create the KanesMethod object and supply an inertial frame, coordinates, generalized speeds, and the kinematic differential equations. Additional quantities such as configuration and motion constraints, dependent coordinates and speeds, and auxiliary speeds are also supplied here (see the online documentation). Next we form FR* and FR to complete: Fr + Fr* = 0. We have the equations of motion at this point. It makes sense to rearrange them though, so we calculate the mass matrix and the forcing terms, for E.o.M. in the form: [MM] udot = forcing, where MM is the mass matrix, udot is a vector of the time derivatives of the generalized speeds, and forcing is a vector representing "forcing" terms. >>> KM = KanesMethod(N, q_ind=[q], u_ind=[u], kd_eqs=kd) >>> (fr, frstar) = KM.kanes_equations(BL, FL) >>> MM = KM.mass_matrix >>> forcing = KM.forcing >>> rhs = MM.inv() * forcing >>> rhs Matrix([[(-c*u(t) - k*q(t))/m]]) >>> KM.linearize(A_and_B=True)[0] Matrix([ [ 0, 1], [-k/m, -c/m]]) Please look at the documentation pages for more information on how to perform linearization and how to deal with dependent coordinates & speeds, and how do deal with bringing non-contributing forces into evidence. """ def __init__(self, frame, q_ind, u_ind, kd_eqs=None, q_dependent=None, configuration_constraints=None, u_dependent=None, velocity_constraints=None, acceleration_constraints=None, u_auxiliary=None): """Please read the online documentation. """ if not q_ind: q_ind = [dynamicsymbols('dummy_q')] kd_eqs = [dynamicsymbols('dummy_kd')] if not isinstance(frame, ReferenceFrame): raise TypeError('An inertial ReferenceFrame must be supplied') self._inertial = frame self._fr = None self._frstar = None self._forcelist = None self._bodylist = None self._initialize_vectors(q_ind, q_dependent, u_ind, u_dependent, u_auxiliary) self._initialize_kindiffeq_matrices(kd_eqs) self._initialize_constraint_matrices(configuration_constraints, velocity_constraints, acceleration_constraints) def _initialize_vectors(self, q_ind, q_dep, u_ind, u_dep, u_aux): """Initialize the coordinate and speed vectors.""" none_handler = lambda x: Matrix(x) if x else Matrix() # Initialize generalized coordinates q_dep = none_handler(q_dep) if not iterable(q_ind): raise TypeError('Generalized coordinates must be an iterable.') if not iterable(q_dep): raise TypeError('Dependent coordinates must be an iterable.') q_ind = Matrix(q_ind) self._qdep = q_dep self._q = Matrix([q_ind, q_dep]) self._qdot = self.q.diff(dynamicsymbols._t) # Initialize generalized speeds u_dep = none_handler(u_dep) if not iterable(u_ind): raise TypeError('Generalized speeds must be an iterable.') if not iterable(u_dep): raise TypeError('Dependent speeds must be an iterable.') u_ind = Matrix(u_ind) self._udep = u_dep self._u = Matrix([u_ind, u_dep]) self._udot = self.u.diff(dynamicsymbols._t) self._uaux = none_handler(u_aux) def _initialize_constraint_matrices(self, config, vel, acc): """Initializes constraint matrices.""" # Define vector dimensions o = len(self.u) m = len(self._udep) p = o - m none_handler = lambda x: Matrix(x) if x else Matrix() # Initialize configuration constraints config = none_handler(config) if len(self._qdep) != len(config): raise ValueError('There must be an equal number of dependent ' 'coordinates and configuration constraints.') self._f_h = none_handler(config) # Initialize velocity and acceleration constraints vel = none_handler(vel) acc = none_handler(acc) if len(vel) != m: raise ValueError('There must be an equal number of dependent ' 'speeds and velocity constraints.') if acc and (len(acc) != m): raise ValueError('There must be an equal number of dependent ' 'speeds and acceleration constraints.') if vel: u_zero = {i: 0 for i in self.u} udot_zero = {i: 0 for i in self._udot} # When calling kanes_equations, another class instance will be # created if auxiliary u's are present. In this case, the # computation of kinetic differential equation matrices will be # skipped as this was computed during the original KanesMethod # object, and the qd_u_map will not be available. if self._qdot_u_map is not None: vel = msubs(vel, self._qdot_u_map) self._f_nh = msubs(vel, u_zero) self._k_nh = (vel - self._f_nh).jacobian(self.u) # If no acceleration constraints given, calculate them. if not acc: _f_dnh = (self._k_nh.diff(dynamicsymbols._t) * self.u + self._f_nh.diff(dynamicsymbols._t)) if self._qdot_u_map is not None: _f_dnh = msubs(_f_dnh, self._qdot_u_map) self._f_dnh = _f_dnh self._k_dnh = self._k_nh else: if self._qdot_u_map is not None: acc = msubs(acc, self._qdot_u_map) self._f_dnh = msubs(acc, udot_zero) self._k_dnh = (acc - self._f_dnh).jacobian(self._udot) # Form of non-holonomic constraints is B*u + C = 0. # We partition B into independent and dependent columns: # Ars is then -B_dep.inv() * B_ind, and it relates dependent speeds # to independent speeds as: udep = Ars*uind, neglecting the C term. B_ind = self._k_nh[:, :p] B_dep = self._k_nh[:, p:o] self._Ars = -B_dep.LUsolve(B_ind) else: self._f_nh = Matrix() self._k_nh = Matrix() self._f_dnh = Matrix() self._k_dnh = Matrix() self._Ars = Matrix() def _initialize_kindiffeq_matrices(self, kdeqs): """Initialize the kinematic differential equation matrices.""" if kdeqs: if len(self.q) != len(kdeqs): raise ValueError('There must be an equal number of kinematic ' 'differential equations and coordinates.') kdeqs = Matrix(kdeqs) u = self.u qdot = self._qdot # Dictionaries setting things to zero u_zero = {i: 0 for i in u} uaux_zero = {i: 0 for i in self._uaux} qdot_zero = {i: 0 for i in qdot} f_k = msubs(kdeqs, u_zero, qdot_zero) k_ku = (msubs(kdeqs, qdot_zero) - f_k).jacobian(u) k_kqdot = (msubs(kdeqs, u_zero) - f_k).jacobian(qdot) f_k = k_kqdot.LUsolve(f_k) k_ku = k_kqdot.LUsolve(k_ku) k_kqdot = eye(len(qdot)) self._qdot_u_map = solve_linear_system_LU( Matrix([k_kqdot.T, -(k_ku * u + f_k).T]).T, qdot) self._f_k = msubs(f_k, uaux_zero) self._k_ku = msubs(k_ku, uaux_zero) self._k_kqdot = k_kqdot else: self._qdot_u_map = None self._f_k = Matrix() self._k_ku = Matrix() self._k_kqdot = Matrix() def _form_fr(self, fl): """Form the generalized active force.""" if fl is not None and (len(fl) == 0 or not iterable(fl)): raise ValueError('Force pairs must be supplied in an ' 'non-empty iterable or None.') N = self._inertial # pull out relevant velocities for constructing partial velocities vel_list, f_list = _f_list_parser(fl, N) vel_list = [msubs(i, self._qdot_u_map) for i in vel_list] f_list = [msubs(i, self._qdot_u_map) for i in f_list] # Fill Fr with dot product of partial velocities and forces o = len(self.u) b = len(f_list) FR = zeros(o, 1) partials = partial_velocity(vel_list, self.u, N) for i in range(o): FR[i] = sum(partials[j][i] & f_list[j] for j in range(b)) # In case there are dependent speeds if self._udep: p = o - len(self._udep) FRtilde = FR[:p, 0] FRold = FR[p:o, 0] FRtilde += self._Ars.T * FRold FR = FRtilde self._forcelist = fl self._fr = FR return FR def _form_frstar(self, bl): """Form the generalized inertia force.""" if not iterable(bl): raise TypeError('Bodies must be supplied in an iterable.') t = dynamicsymbols._t N = self._inertial # Dicts setting things to zero udot_zero = {i: 0 for i in self._udot} uaux_zero = {i: 0 for i in self._uaux} uauxdot = [diff(i, t) for i in self._uaux] uauxdot_zero = {i: 0 for i in uauxdot} # Dictionary of q' and q'' to u and u' q_ddot_u_map = {k.diff(t): v.diff(t) for (k, v) in self._qdot_u_map.items()} q_ddot_u_map.update(self._qdot_u_map) # Fill up the list of partials: format is a list with num elements # equal to number of entries in body list. Each of these elements is a # list - either of length 1 for the translational components of # particles or of length 2 for the translational and rotational # components of rigid bodies. The inner most list is the list of # partial velocities. def get_partial_velocity(body): if isinstance(body, RigidBody): vlist = [body.masscenter.vel(N), body.frame.ang_vel_in(N)] elif isinstance(body, Particle): vlist = [body.point.vel(N),] else: raise TypeError('The body list may only contain either ' 'RigidBody or Particle as list elements.') v = [msubs(vel, self._qdot_u_map) for vel in vlist] return partial_velocity(v, self.u, N) partials = [get_partial_velocity(body) for body in bl] # Compute fr_star in two components: # fr_star = -(MM*u' + nonMM) o = len(self.u) MM = zeros(o, o) nonMM = zeros(o, 1) zero_uaux = lambda expr: msubs(expr, uaux_zero) zero_udot_uaux = lambda expr: msubs(msubs(expr, udot_zero), uaux_zero) for i, body in enumerate(bl): if isinstance(body, RigidBody): M = zero_uaux(body.mass) I = zero_uaux(body.central_inertia) vel = zero_uaux(body.masscenter.vel(N)) omega = zero_uaux(body.frame.ang_vel_in(N)) acc = zero_udot_uaux(body.masscenter.acc(N)) inertial_force = (M.diff(t) * vel + M * acc) inertial_torque = zero_uaux((I.dt(body.frame) & omega) + msubs(I & body.frame.ang_acc_in(N), udot_zero) + (omega ^ (I & omega))) for j in range(o): tmp_vel = zero_uaux(partials[i][0][j]) tmp_ang = zero_uaux(I & partials[i][1][j]) for k in range(o): # translational MM[j, k] += M * (tmp_vel & partials[i][0][k]) # rotational MM[j, k] += (tmp_ang & partials[i][1][k]) nonMM[j] += inertial_force & partials[i][0][j] nonMM[j] += inertial_torque & partials[i][1][j] else: M = zero_uaux(body.mass) vel = zero_uaux(body.point.vel(N)) acc = zero_udot_uaux(body.point.acc(N)) inertial_force = (M.diff(t) * vel + M * acc) for j in range(o): temp = zero_uaux(partials[i][0][j]) for k in range(o): MM[j, k] += M * (temp & partials[i][0][k]) nonMM[j] += inertial_force & partials[i][0][j] # Compose fr_star out of MM and nonMM MM = zero_uaux(msubs(MM, q_ddot_u_map)) nonMM = msubs(msubs(nonMM, q_ddot_u_map), udot_zero, uauxdot_zero, uaux_zero) fr_star = -(MM * msubs(Matrix(self._udot), uauxdot_zero) + nonMM) # If there are dependent speeds, we need to find fr_star_tilde if self._udep: p = o - len(self._udep) fr_star_ind = fr_star[:p, 0] fr_star_dep = fr_star[p:o, 0] fr_star = fr_star_ind + (self._Ars.T * fr_star_dep) # Apply the same to MM MMi = MM[:p, :] MMd = MM[p:o, :] MM = MMi + (self._Ars.T * MMd) self._bodylist = bl self._frstar = fr_star self._k_d = MM self._f_d = -msubs(self._fr + self._frstar, udot_zero) return fr_star def to_linearizer(self): """Returns an instance of the Linearizer class, initiated from the data in the KanesMethod class. This may be more desirable than using the linearize class method, as the Linearizer object will allow more efficient recalculation (i.e. about varying operating points).""" if (self._fr is None) or (self._frstar is None): raise ValueError('Need to compute Fr, Fr* first.') # Get required equation components. The Kane's method class breaks # these into pieces. Need to reassemble f_c = self._f_h if self._f_nh and self._k_nh: f_v = self._f_nh + self._k_nh*Matrix(self.u) else: f_v = Matrix() if self._f_dnh and self._k_dnh: f_a = self._f_dnh + self._k_dnh*Matrix(self._udot) else: f_a = Matrix() # Dicts to sub to zero, for splitting up expressions u_zero = {i: 0 for i in self.u} ud_zero = {i: 0 for i in self._udot} qd_zero = {i: 0 for i in self._qdot} qd_u_zero = {i: 0 for i in Matrix([self._qdot, self.u])} # Break the kinematic differential eqs apart into f_0 and f_1 f_0 = msubs(self._f_k, u_zero) + self._k_kqdot*Matrix(self._qdot) f_1 = msubs(self._f_k, qd_zero) + self._k_ku*Matrix(self.u) # Break the dynamic differential eqs into f_2 and f_3 f_2 = msubs(self._frstar, qd_u_zero) f_3 = msubs(self._frstar, ud_zero) + self._fr f_4 = zeros(len(f_2), 1) # Get the required vector components q = self.q u = self.u if self._qdep: q_i = q[:-len(self._qdep)] else: q_i = q q_d = self._qdep if self._udep: u_i = u[:-len(self._udep)] else: u_i = u u_d = self._udep # Form dictionary to set auxiliary speeds & their derivatives to 0. uaux = self._uaux uauxdot = uaux.diff(dynamicsymbols._t) uaux_zero = {i: 0 for i in Matrix([uaux, uauxdot])} # Checking for dynamic symbols outside the dynamic differential # equations; throws error if there is. sym_list = set(Matrix([q, self._qdot, u, self._udot, uaux, uauxdot])) if any(find_dynamicsymbols(i, sym_list) for i in [self._k_kqdot, self._k_ku, self._f_k, self._k_dnh, self._f_dnh, self._k_d]): raise ValueError('Cannot have dynamicsymbols outside dynamic \ forcing vector.') # Find all other dynamic symbols, forming the forcing vector r. # Sort r to make it canonical. r = list(find_dynamicsymbols(msubs(self._f_d, uaux_zero), sym_list)) r.sort(key=default_sort_key) # Check for any derivatives of variables in r that are also found in r. for i in r: if diff(i, dynamicsymbols._t) in r: raise ValueError('Cannot have derivatives of specified \ quantities when linearizing forcing terms.') return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i, q_d, u_i, u_d, r) # TODO : Remove `new_method` after 1.1 has been released. def linearize(self, *, new_method=None, **kwargs): """ Linearize the equations of motion about a symbolic operating point. If kwarg A_and_B is False (default), returns M, A, B, r for the linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r. If kwarg A_and_B is True, returns A, B, r for the linearized form dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is computationally intensive if there are many symbolic parameters. For this reason, it may be more desirable to use the default A_and_B=False, returning M, A, and B. Values may then be substituted in to these matrices, and the state space form found as A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat. In both cases, r is found as all dynamicsymbols in the equations of motion that are not part of q, u, q', or u'. They are sorted in canonical form. The operating points may be also entered using the ``op_point`` kwarg. This takes a dictionary of {symbol: value}, or a an iterable of such dictionaries. The values may be numeric or symbolic. The more values you can specify beforehand, the faster this computation will run. For more documentation, please see the ``Linearizer`` class.""" linearizer = self.to_linearizer() result = linearizer.linearize(**kwargs) return result + (linearizer.r,) def kanes_equations(self, bodies, loads=None): """ Method to form Kane's equations, Fr + Fr* = 0. Returns (Fr, Fr*). In the case where auxiliary generalized speeds are present (say, s auxiliary speeds, o generalized speeds, and m motion constraints) the length of the returned vectors will be o - m + s in length. The first o - m equations will be the constrained Kane's equations, then the s auxiliary Kane's equations. These auxiliary equations can be accessed with the auxiliary_eqs(). Parameters ========== bodies : iterable An iterable of all RigidBody's and Particle's in the system. A system must have at least one body. loads : iterable Takes in an iterable of (Particle, Vector) or (ReferenceFrame, Vector) tuples which represent the force at a point or torque on a frame. Must be either a non-empty iterable of tuples or None which corresponds to a system with no constraints. """ if (bodies is None and loads is not None) or isinstance(bodies[0], tuple): # This switches the order if they use the old way. bodies, loads = loads, bodies SymPyDeprecationWarning(value='The API for kanes_equations() has changed such ' 'that the loads (forces and torques) are now the second argument ' 'and is optional with None being the default.', feature='The kanes_equation() argument order', useinstead='switched argument order to update your code, For example: ' 'kanes_equations(loads, bodies) > kanes_equations(bodies, loads).', issue=10945, deprecated_since_version="1.1").warn() if not self._k_kqdot: raise AttributeError('Create an instance of KanesMethod with ' 'kinematic differential equations to use this method.') fr = self._form_fr(loads) frstar = self._form_frstar(bodies) if self._uaux: if not self._udep: km = KanesMethod(self._inertial, self.q, self._uaux, u_auxiliary=self._uaux) else: km = KanesMethod(self._inertial, self.q, self._uaux, u_auxiliary=self._uaux, u_dependent=self._udep, velocity_constraints=(self._k_nh * self.u + self._f_nh)) km._qdot_u_map = self._qdot_u_map self._km = km fraux = km._form_fr(loads) frstaraux = km._form_frstar(bodies) self._aux_eq = fraux + frstaraux self._fr = fr.col_join(fraux) self._frstar = frstar.col_join(frstaraux) return (self._fr, self._frstar) def rhs(self, inv_method=None): """Returns the system's equations of motion in first order form. The output is the right hand side of:: x' = |q'| =: f(q, u, r, p, t) |u'| The right hand side is what is needed by most numerical ODE integrators. Parameters ========== inv_method : str The specific sympy inverse matrix calculation method to use. For a list of valid methods, see :meth:`~sympy.matrices.matrices.MatrixBase.inv` """ rhs = zeros(len(self.q) + len(self.u), 1) kdes = self.kindiffdict() for i, q_i in enumerate(self.q): rhs[i] = kdes[q_i.diff()] if inv_method is None: rhs[len(self.q):, 0] = self.mass_matrix.LUsolve(self.forcing) else: rhs[len(self.q):, 0] = (self.mass_matrix.inv(inv_method, try_block_diag=True) * self.forcing) return rhs def kindiffdict(self): """Returns a dictionary mapping q' to u.""" if not self._qdot_u_map: raise AttributeError('Create an instance of KanesMethod with ' 'kinematic differential equations to use this method.') return self._qdot_u_map @property def auxiliary_eqs(self): """A matrix containing the auxiliary equations.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') if not self._uaux: raise ValueError('No auxiliary speeds have been declared.') return self._aux_eq @property def mass_matrix(self): """The mass matrix of the system.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') return Matrix([self._k_d, self._k_dnh]) @property def mass_matrix_full(self): """The mass matrix of the system, augmented by the kinematic differential equations.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') o = len(self.u) n = len(self.q) return ((self._k_kqdot).row_join(zeros(n, o))).col_join((zeros(o, n)).row_join(self.mass_matrix)) @property def forcing(self): """The forcing vector of the system.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') return -Matrix([self._f_d, self._f_dnh]) @property def forcing_full(self): """The forcing vector of the system, augmented by the kinematic differential equations.""" if not self._fr or not self._frstar: raise ValueError('Need to compute Fr, Fr* first.') f1 = self._k_ku * Matrix(self.u) + self._f_k return -Matrix([f1, self._f_d, self._f_dnh]) @property def q(self): return self._q @property def u(self): return self._u @property def bodylist(self): return self._bodylist @property def forcelist(self): return self._forcelist
0097967bf342faa275fad78233802b9566545d670e9597f4e4dd3b5aa76587cd
from sympy.core.backend import sympify from sympy.physics.vector import Point, ReferenceFrame, Dyadic from sympy.utilities.exceptions import SymPyDeprecationWarning __all__ = ['RigidBody'] class RigidBody: """An idealized rigid body. This is essentially a container which holds the various components which describe a rigid body: a name, mass, center of mass, reference frame, and inertia. All of these need to be supplied on creation, but can be changed afterwards. Attributes ========== name : string The body's name. masscenter : Point The point which represents the center of mass of the rigid body. frame : ReferenceFrame The ReferenceFrame which the rigid body is fixed in. mass : Sympifyable The body's mass. inertia : (Dyadic, Point) The body's inertia about a point; stored in a tuple as shown above. Examples ======== >>> from sympy import Symbol >>> from sympy.physics.mechanics import ReferenceFrame, Point, RigidBody >>> from sympy.physics.mechanics import outer >>> m = Symbol('m') >>> A = ReferenceFrame('A') >>> P = Point('P') >>> I = outer (A.x, A.x) >>> inertia_tuple = (I, P) >>> B = RigidBody('B', P, A, m, inertia_tuple) >>> # Or you could change them afterwards >>> m2 = Symbol('m2') >>> B.mass = m2 """ def __init__(self, name, masscenter, frame, mass, inertia): if not isinstance(name, str): raise TypeError('Supply a valid name.') self._name = name self.masscenter = masscenter self.mass = mass self.frame = frame self.inertia = inertia self.potential_energy = 0 def __str__(self): return self._name def __repr__(self): return self.__str__() @property def frame(self): return self._frame @frame.setter def frame(self, F): if not isinstance(F, ReferenceFrame): raise TypeError("RigdBody frame must be a ReferenceFrame object.") self._frame = F @property def masscenter(self): return self._masscenter @masscenter.setter def masscenter(self, p): if not isinstance(p, Point): raise TypeError("RigidBody center of mass must be a Point object.") self._masscenter = p @property def mass(self): return self._mass @mass.setter def mass(self, m): self._mass = sympify(m) @property def inertia(self): return (self._inertia, self._inertia_point) @inertia.setter def inertia(self, I): if not isinstance(I[0], Dyadic): raise TypeError("RigidBody inertia must be a Dyadic object.") if not isinstance(I[1], Point): raise TypeError("RigidBody inertia must be about a Point.") self._inertia = I[0] self._inertia_point = I[1] # have I S/O, want I S/S* # I S/O = I S/S* + I S*/O; I S/S* = I S/O - I S*/O # I_S/S* = I_S/O - I_S*/O from sympy.physics.mechanics.functions import inertia_of_point_mass I_Ss_O = inertia_of_point_mass(self.mass, self.masscenter.pos_from(I[1]), self.frame) self._central_inertia = I[0] - I_Ss_O @property def central_inertia(self): """The body's central inertia dyadic.""" return self._central_inertia def linear_momentum(self, frame): """ Linear momentum of the rigid body. The linear momentum L, of a rigid body B, with respect to frame N is given by L = M * v* where M is the mass of the rigid body and v* is the velocity of the mass center of B in the frame, N. Parameters ========== frame : ReferenceFrame The frame in which linear momentum is desired. Examples ======== >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer >>> from sympy.physics.mechanics import RigidBody, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> M, v = dynamicsymbols('M v') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, v * N.x) >>> I = outer (N.x, N.x) >>> Inertia_tuple = (I, P) >>> B = RigidBody('B', P, N, M, Inertia_tuple) >>> B.linear_momentum(N) M*v*N.x """ return self.mass * self.masscenter.vel(frame) def angular_momentum(self, point, frame): """Returns the angular momentum of the rigid body about a point in the given frame. The angular momentum H of a rigid body B about some point O in a frame N is given by: H = I . w + r x Mv where I is the central inertia dyadic of B, w is the angular velocity of body B in the frame, N, r is the position vector from point O to the mass center of B, and v is the velocity of the mass center in the frame, N. Parameters ========== point : Point The point about which angular momentum is desired. frame : ReferenceFrame The frame in which angular momentum is desired. Examples ======== >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer >>> from sympy.physics.mechanics import RigidBody, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> M, v, r, omega = dynamicsymbols('M v r omega') >>> N = ReferenceFrame('N') >>> b = ReferenceFrame('b') >>> b.set_ang_vel(N, omega * b.x) >>> P = Point('P') >>> P.set_vel(N, 1 * N.x) >>> I = outer(b.x, b.x) >>> B = RigidBody('B', P, b, M, (I, P)) >>> B.angular_momentum(P, N) omega*b.x """ I = self.central_inertia w = self.frame.ang_vel_in(frame) m = self.mass r = self.masscenter.pos_from(point) v = self.masscenter.vel(frame) return I.dot(w) + r.cross(m * v) def kinetic_energy(self, frame): """Kinetic energy of the rigid body The kinetic energy, T, of a rigid body, B, is given by 'T = 1/2 (I omega^2 + m v^2)' where I and m are the central inertia dyadic and mass of rigid body B, respectively, omega is the body's angular velocity and v is the velocity of the body's mass center in the supplied ReferenceFrame. Parameters ========== frame : ReferenceFrame The RigidBody's angular velocity and the velocity of it's mass center are typically defined with respect to an inertial frame but any relevant frame in which the velocities are known can be supplied. Examples ======== >>> from sympy.physics.mechanics import Point, ReferenceFrame, outer >>> from sympy.physics.mechanics import RigidBody >>> from sympy import symbols >>> M, v, r, omega = symbols('M v r omega') >>> N = ReferenceFrame('N') >>> b = ReferenceFrame('b') >>> b.set_ang_vel(N, omega * b.x) >>> P = Point('P') >>> P.set_vel(N, v * N.x) >>> I = outer (b.x, b.x) >>> inertia_tuple = (I, P) >>> B = RigidBody('B', P, b, M, inertia_tuple) >>> B.kinetic_energy(N) M*v**2/2 + omega**2/2 """ rotational_KE = (self.frame.ang_vel_in(frame) & (self.central_inertia & self.frame.ang_vel_in(frame)) / sympify(2)) translational_KE = (self.mass * (self.masscenter.vel(frame) & self.masscenter.vel(frame)) / sympify(2)) return rotational_KE + translational_KE @property def potential_energy(self): """The potential energy of the RigidBody. Examples ======== >>> from sympy.physics.mechanics import RigidBody, Point, outer, ReferenceFrame >>> from sympy import symbols >>> M, g, h = symbols('M g h') >>> b = ReferenceFrame('b') >>> P = Point('P') >>> I = outer (b.x, b.x) >>> Inertia_tuple = (I, P) >>> B = RigidBody('B', P, b, M, Inertia_tuple) >>> B.potential_energy = M * g * h >>> B.potential_energy M*g*h """ return self._pe @potential_energy.setter def potential_energy(self, scalar): """Used to set the potential energy of this RigidBody. Parameters ========== scalar: Sympifyable The potential energy (a scalar) of the RigidBody. Examples ======== >>> from sympy.physics.mechanics import Point, outer >>> from sympy.physics.mechanics import RigidBody, ReferenceFrame >>> from sympy import symbols >>> b = ReferenceFrame('b') >>> M, g, h = symbols('M g h') >>> P = Point('P') >>> I = outer (b.x, b.x) >>> Inertia_tuple = (I, P) >>> B = RigidBody('B', P, b, M, Inertia_tuple) >>> B.potential_energy = M * g * h """ self._pe = sympify(scalar) def set_potential_energy(self, scalar): SymPyDeprecationWarning( feature="Method sympy.physics.mechanics." + "RigidBody.set_potential_energy(self, scalar)", useinstead="property sympy.physics.mechanics." + "RigidBody.potential_energy", deprecated_since_version="1.5", issue=9800).warn() self.potential_energy = scalar # XXX: To be consistent with the parallel_axis method in Particle this # should have a frame argument... def parallel_axis(self, point): """Returns the inertia dyadic of the body with respect to another point. Parameters ========== point : sympy.physics.vector.Point The point to express the inertia dyadic about. Returns ======= inertia : sympy.physics.vector.Dyadic The inertia dyadic of the rigid body expressed about the provided point. """ # circular import issue from sympy.physics.mechanics.functions import inertia a, b, c = self.masscenter.pos_from(point).to_matrix(self.frame) I = self.mass * inertia(self.frame, b**2 + c**2, c**2 + a**2, a**2 + b**2, -a * b, -b * c, -a * c) return self.central_inertia + I
142ee288c4685cc462d1ed35c2dcce561a7a51aeb609722b71b74204411980c4
from sympy.utilities import dict_merge from sympy.utilities.iterables import iterable from sympy.physics.vector import (Dyadic, Vector, ReferenceFrame, Point, dynamicsymbols) from sympy.physics.vector.printing import (vprint, vsprint, vpprint, vlatex, init_vprinting) from sympy.physics.mechanics.particle import Particle from sympy.physics.mechanics.rigidbody import RigidBody from sympy import simplify from sympy.core.backend import (Matrix, sympify, Mul, Derivative, sin, cos, tan, AppliedUndef, S) __all__ = ['inertia', 'inertia_of_point_mass', 'linear_momentum', 'angular_momentum', 'kinetic_energy', 'potential_energy', 'Lagrangian', 'mechanics_printing', 'mprint', 'msprint', 'mpprint', 'mlatex', 'msubs', 'find_dynamicsymbols'] # These are functions that we've moved and renamed during extracting the # basic vector calculus code from the mechanics packages. mprint = vprint msprint = vsprint mpprint = vpprint mlatex = vlatex def mechanics_printing(**kwargs): """ Initializes time derivative printing for all SymPy objects in mechanics module. """ init_vprinting(**kwargs) mechanics_printing.__doc__ = init_vprinting.__doc__ def inertia(frame, ixx, iyy, izz, ixy=0, iyz=0, izx=0): """Simple way to create inertia Dyadic object. If you don't know what a Dyadic is, just treat this like the inertia tensor. Then, do the easy thing and define it in a body-fixed frame. Parameters ========== frame : ReferenceFrame The frame the inertia is defined in ixx : Sympifyable the xx element in the inertia dyadic iyy : Sympifyable the yy element in the inertia dyadic izz : Sympifyable the zz element in the inertia dyadic ixy : Sympifyable the xy element in the inertia dyadic iyz : Sympifyable the yz element in the inertia dyadic izx : Sympifyable the zx element in the inertia dyadic Examples ======== >>> from sympy.physics.mechanics import ReferenceFrame, inertia >>> N = ReferenceFrame('N') >>> inertia(N, 1, 2, 3) (N.x|N.x) + 2*(N.y|N.y) + 3*(N.z|N.z) """ if not isinstance(frame, ReferenceFrame): raise TypeError('Need to define the inertia in a frame') ol = sympify(ixx) * (frame.x | frame.x) ol += sympify(ixy) * (frame.x | frame.y) ol += sympify(izx) * (frame.x | frame.z) ol += sympify(ixy) * (frame.y | frame.x) ol += sympify(iyy) * (frame.y | frame.y) ol += sympify(iyz) * (frame.y | frame.z) ol += sympify(izx) * (frame.z | frame.x) ol += sympify(iyz) * (frame.z | frame.y) ol += sympify(izz) * (frame.z | frame.z) return ol def inertia_of_point_mass(mass, pos_vec, frame): """Inertia dyadic of a point mass relative to point O. Parameters ========== mass : Sympifyable Mass of the point mass pos_vec : Vector Position from point O to point mass frame : ReferenceFrame Reference frame to express the dyadic in Examples ======== >>> from sympy import symbols >>> from sympy.physics.mechanics import ReferenceFrame, inertia_of_point_mass >>> N = ReferenceFrame('N') >>> r, m = symbols('r m') >>> px = r * N.x >>> inertia_of_point_mass(m, px, N) m*r**2*(N.y|N.y) + m*r**2*(N.z|N.z) """ return mass * (((frame.x | frame.x) + (frame.y | frame.y) + (frame.z | frame.z)) * (pos_vec & pos_vec) - (pos_vec | pos_vec)) def linear_momentum(frame, *body): """Linear momentum of the system. This function returns the linear momentum of a system of Particle's and/or RigidBody's. The linear momentum of a system is equal to the vector sum of the linear momentum of its constituents. Consider a system, S, comprised of a rigid body, A, and a particle, P. The linear momentum of the system, L, is equal to the vector sum of the linear momentum of the particle, L1, and the linear momentum of the rigid body, L2, i.e. L = L1 + L2 Parameters ========== frame : ReferenceFrame The frame in which linear momentum is desired. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose linear momentum is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, linear_momentum >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = Point('Ac') >>> Ac.set_vel(N, 25 * N.y) >>> I = outer(N.x, N.x) >>> A = RigidBody('A', Ac, N, 20, (I, Ac)) >>> linear_momentum(N, A, Pa) 10*N.x + 500*N.y """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please specify a valid ReferenceFrame') else: linear_momentum_sys = Vector(0) for e in body: if isinstance(e, (RigidBody, Particle)): linear_momentum_sys += e.linear_momentum(frame) else: raise TypeError('*body must have only Particle or RigidBody') return linear_momentum_sys def angular_momentum(point, frame, *body): """Angular momentum of a system This function returns the angular momentum of a system of Particle's and/or RigidBody's. The angular momentum of such a system is equal to the vector sum of the angular momentum of its constituents. Consider a system, S, comprised of a rigid body, A, and a particle, P. The angular momentum of the system, H, is equal to the vector sum of the angular momentum of the particle, H1, and the angular momentum of the rigid body, H2, i.e. H = H1 + H2 Parameters ========== point : Point The point about which angular momentum of the system is desired. frame : ReferenceFrame The frame in which angular momentum is desired. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose angular momentum is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, angular_momentum >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> Ac.set_vel(N, 5 * N.y) >>> a = ReferenceFrame('a') >>> a.set_ang_vel(N, 10 * N.z) >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) >>> angular_momentum(O, N, Pa, A) 10*N.z """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please enter a valid ReferenceFrame') if not isinstance(point, Point): raise TypeError('Please specify a valid Point') else: angular_momentum_sys = Vector(0) for e in body: if isinstance(e, (RigidBody, Particle)): angular_momentum_sys += e.angular_momentum(point, frame) else: raise TypeError('*body must have only Particle or RigidBody') return angular_momentum_sys def kinetic_energy(frame, *body): """Kinetic energy of a multibody system. This function returns the kinetic energy of a system of Particle's and/or RigidBody's. The kinetic energy of such a system is equal to the sum of the kinetic energies of its constituents. Consider a system, S, comprising a rigid body, A, and a particle, P. The kinetic energy of the system, T, is equal to the vector sum of the kinetic energy of the particle, T1, and the kinetic energy of the rigid body, T2, i.e. T = T1 + T2 Kinetic energy is a scalar. Parameters ========== frame : ReferenceFrame The frame in which the velocity or angular velocity of the body is defined. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose kinetic energy is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, kinetic_energy >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> Ac.set_vel(N, 5 * N.y) >>> a = ReferenceFrame('a') >>> a.set_ang_vel(N, 10 * N.z) >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) >>> kinetic_energy(N, Pa, A) 350 """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please enter a valid ReferenceFrame') ke_sys = S.Zero for e in body: if isinstance(e, (RigidBody, Particle)): ke_sys += e.kinetic_energy(frame) else: raise TypeError('*body must have only Particle or RigidBody') return ke_sys def potential_energy(*body): """Potential energy of a multibody system. This function returns the potential energy of a system of Particle's and/or RigidBody's. The potential energy of such a system is equal to the sum of the potential energy of its constituents. Consider a system, S, comprising a rigid body, A, and a particle, P. The potential energy of the system, V, is equal to the vector sum of the potential energy of the particle, V1, and the potential energy of the rigid body, V2, i.e. V = V1 + V2 Potential energy is a scalar. Parameters ========== body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose potential energy is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, potential_energy >>> from sympy import symbols >>> M, m, g, h = symbols('M m g h') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> Pa = Particle('Pa', P, m) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> a = ReferenceFrame('a') >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, M, (I, Ac)) >>> Pa.potential_energy = m * g * h >>> A.potential_energy = M * g * h >>> potential_energy(Pa, A) M*g*h + g*h*m """ pe_sys = S.Zero for e in body: if isinstance(e, (RigidBody, Particle)): pe_sys += e.potential_energy else: raise TypeError('*body must have only Particle or RigidBody') return pe_sys def gravity(acceleration, *bodies): """ Returns a list of gravity forces given the acceleration due to gravity and any number of particles or rigidbodies. Example ======= >>> from sympy.physics.mechanics import ReferenceFrame, Point, Particle, outer, RigidBody >>> from sympy.physics.mechanics.functions import gravity >>> from sympy import symbols >>> N = ReferenceFrame('N') >>> m, M, g = symbols('m M g') >>> F1, F2 = symbols('F1 F2') >>> po = Point('po') >>> pa = Particle('pa', po, m) >>> A = ReferenceFrame('A') >>> P = Point('P') >>> I = outer(A.x, A.x) >>> B = RigidBody('B', P, A, M, (I, P)) >>> forceList = [(po, F1), (P, F2)] >>> forceList.extend(gravity(g*N.y, pa, B)) >>> forceList [(po, F1), (P, F2), (po, g*m*N.y), (P, M*g*N.y)] """ gravity_force = [] if not bodies: raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.") for e in bodies: point = getattr(e, 'masscenter', None) if point is None: point = e.point gravity_force.append((point, e.mass*acceleration)) return gravity_force def center_of_mass(point, *bodies): """ Returns the position vector from the given point to the center of mass of the given bodies(particles or rigidbodies). Example ======= >>> from sympy import symbols, S >>> from sympy.physics.vector import Point >>> from sympy.physics.mechanics import Particle, ReferenceFrame, RigidBody, outer >>> from sympy.physics.mechanics.functions import center_of_mass >>> a = ReferenceFrame('a') >>> m = symbols('m', real=True) >>> p1 = Particle('p1', Point('p1_pt'), S(1)) >>> p2 = Particle('p2', Point('p2_pt'), S(2)) >>> p3 = Particle('p3', Point('p3_pt'), S(3)) >>> p4 = Particle('p4', Point('p4_pt'), m) >>> b_f = ReferenceFrame('b_f') >>> b_cm = Point('b_cm') >>> mb = symbols('mb') >>> b = RigidBody('b', b_cm, b_f, mb, (outer(b_f.x, b_f.x), b_cm)) >>> p2.point.set_pos(p1.point, a.x) >>> p3.point.set_pos(p1.point, a.x + a.y) >>> p4.point.set_pos(p1.point, a.y) >>> b.masscenter.set_pos(p1.point, a.y + a.z) >>> point_o=Point('o') >>> point_o.set_pos(p1.point, center_of_mass(p1.point, p1, p2, p3, p4, b)) >>> expr = 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z >>> point_o.pos_from(p1.point) 5/(m + mb + 6)*a.x + (m + mb + 3)/(m + mb + 6)*a.y + mb/(m + mb + 6)*a.z """ if not bodies: raise TypeError("No bodies(instances of Particle or Rigidbody) were passed.") total_mass = 0 vec = Vector(0) for i in bodies: total_mass += i.mass masscenter = getattr(i, 'masscenter', None) if masscenter is None: masscenter = i.point vec += i.mass*masscenter.pos_from(point) return vec/total_mass def Lagrangian(frame, *body): """Lagrangian of a multibody system. This function returns the Lagrangian of a system of Particle's and/or RigidBody's. The Lagrangian of such a system is equal to the difference between the kinetic energies and potential energies of its constituents. If T and V are the kinetic and potential energies of a system then it's Lagrangian, L, is defined as L = T - V The Lagrangian is a scalar. Parameters ========== frame : ReferenceFrame The frame in which the velocity or angular velocity of the body is defined to determine the kinetic energy. body1, body2, body3... : Particle and/or RigidBody The body (or bodies) whose Lagrangian is required. Examples ======== >>> from sympy.physics.mechanics import Point, Particle, ReferenceFrame >>> from sympy.physics.mechanics import RigidBody, outer, Lagrangian >>> from sympy import symbols >>> M, m, g, h = symbols('M m g h') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> O.set_vel(N, 0 * N.x) >>> P = O.locatenew('P', 1 * N.x) >>> P.set_vel(N, 10 * N.x) >>> Pa = Particle('Pa', P, 1) >>> Ac = O.locatenew('Ac', 2 * N.y) >>> Ac.set_vel(N, 5 * N.y) >>> a = ReferenceFrame('a') >>> a.set_ang_vel(N, 10 * N.z) >>> I = outer(N.z, N.z) >>> A = RigidBody('A', Ac, a, 20, (I, Ac)) >>> Pa.potential_energy = m * g * h >>> A.potential_energy = M * g * h >>> Lagrangian(N, Pa, A) -M*g*h - g*h*m + 350 """ if not isinstance(frame, ReferenceFrame): raise TypeError('Please supply a valid ReferenceFrame') for e in body: if not isinstance(e, (RigidBody, Particle)): raise TypeError('*body must have only Particle or RigidBody') return kinetic_energy(frame, *body) - potential_energy(*body) def find_dynamicsymbols(expression, exclude=None, reference_frame=None): """Find all dynamicsymbols in expression. If the optional ``exclude`` kwarg is used, only dynamicsymbols not in the iterable ``exclude`` are returned. If we intend to apply this function on a vector, the optional ''reference_frame'' is also used to inform about the corresponding frame with respect to which the dynamic symbols of the given vector is to be determined. Parameters ========== expression : sympy expression exclude : iterable of dynamicsymbols, optional reference_frame : ReferenceFrame, optional The frame with respect to which the dynamic symbols of the given vector is to be determined. Examples ======== >>> from sympy.physics.mechanics import dynamicsymbols, find_dynamicsymbols >>> from sympy.physics.mechanics import ReferenceFrame >>> x, y = dynamicsymbols('x, y') >>> expr = x + x.diff()*y >>> find_dynamicsymbols(expr) {x(t), y(t), Derivative(x(t), t)} >>> find_dynamicsymbols(expr, exclude=[x, y]) {Derivative(x(t), t)} >>> a, b, c = dynamicsymbols('a, b, c') >>> A = ReferenceFrame('A') >>> v = a * A.x + b * A.y + c * A.z >>> find_dynamicsymbols(v, reference_frame=A) {a(t), b(t), c(t)} """ t_set = {dynamicsymbols._t} if exclude: if iterable(exclude): exclude_set = set(exclude) else: raise TypeError("exclude kwarg must be iterable") else: exclude_set = set() if isinstance(expression, Vector): if reference_frame is None: raise ValueError("You must provide reference_frame when passing a " "vector expression, got %s." % reference_frame) else: expression = expression.to_matrix(reference_frame) return {i for i in expression.atoms(AppliedUndef, Derivative) if i.free_symbols == t_set} - exclude_set def msubs(expr, *sub_dicts, smart=False, **kwargs): """A custom subs for use on expressions derived in physics.mechanics. Traverses the expression tree once, performing the subs found in sub_dicts. Terms inside ``Derivative`` expressions are ignored: >>> from sympy.physics.mechanics import dynamicsymbols, msubs >>> x = dynamicsymbols('x') >>> msubs(x.diff() + x, {x: 1}) Derivative(x(t), t) + 1 Note that sub_dicts can be a single dictionary, or several dictionaries: >>> x, y, z = dynamicsymbols('x, y, z') >>> sub1 = {x: 1, y: 2} >>> sub2 = {z: 3, x.diff(): 4} >>> msubs(x.diff() + x + y + z, sub1, sub2) 10 If smart=True (default False), also checks for conditions that may result in ``nan``, but if simplified would yield a valid expression. For example: >>> from sympy import sin, tan >>> (sin(x)/tan(x)).subs(x, 0) nan >>> msubs(sin(x)/tan(x), {x: 0}, smart=True) 1 It does this by first replacing all ``tan`` with ``sin/cos``. Then each node is traversed. If the node is a fraction, subs is first evaluated on the denominator. If this results in 0, simplification of the entire fraction is attempted. Using this selective simplification, only subexpressions that result in 1/0 are targeted, resulting in faster performance. """ sub_dict = dict_merge(*sub_dicts) if smart: func = _smart_subs elif hasattr(expr, 'msubs'): return expr.msubs(sub_dict) else: func = lambda expr, sub_dict: _crawl(expr, _sub_func, sub_dict) if isinstance(expr, (Matrix, Vector, Dyadic)): return expr.applyfunc(lambda x: func(x, sub_dict)) else: return func(expr, sub_dict) def _crawl(expr, func, *args, **kwargs): """Crawl the expression tree, and apply func to every node.""" val = func(expr, *args, **kwargs) if val is not None: return val new_args = (_crawl(arg, func, *args, **kwargs) for arg in expr.args) return expr.func(*new_args) def _sub_func(expr, sub_dict): """Perform direct matching substitution, ignoring derivatives.""" if expr in sub_dict: return sub_dict[expr] elif not expr.args or expr.is_Derivative: return expr def _tan_repl_func(expr): """Replace tan with sin/cos.""" if isinstance(expr, tan): return sin(*expr.args) / cos(*expr.args) elif not expr.args or expr.is_Derivative: return expr def _smart_subs(expr, sub_dict): """Performs subs, checking for conditions that may result in `nan` or `oo`, and attempts to simplify them out. The expression tree is traversed twice, and the following steps are performed on each expression node: - First traverse: Replace all `tan` with `sin/cos`. - Second traverse: If node is a fraction, check if the denominator evaluates to 0. If so, attempt to simplify it out. Then if node is in sub_dict, sub in the corresponding value.""" expr = _crawl(expr, _tan_repl_func) def _recurser(expr, sub_dict): # Decompose the expression into num, den num, den = _fraction_decomp(expr) if den != 1: # If there is a non trivial denominator, we need to handle it denom_subbed = _recurser(den, sub_dict) if denom_subbed.evalf() == 0: # If denom is 0 after this, attempt to simplify the bad expr expr = simplify(expr) else: # Expression won't result in nan, find numerator num_subbed = _recurser(num, sub_dict) return num_subbed / denom_subbed # We have to crawl the tree manually, because `expr` may have been # modified in the simplify step. First, perform subs as normal: val = _sub_func(expr, sub_dict) if val is not None: return val new_args = (_recurser(arg, sub_dict) for arg in expr.args) return expr.func(*new_args) return _recurser(expr, sub_dict) def _fraction_decomp(expr): """Return num, den such that expr = num/den""" if not isinstance(expr, Mul): return expr, 1 num = [] den = [] for a in expr.args: if a.is_Pow and a.args[1] < 0: den.append(1 / a) else: num.append(a) if not den: return expr, 1 num = Mul(*num) den = Mul(*den) return num, den def _f_list_parser(fl, ref_frame): """Parses the provided forcelist composed of items of the form (obj, force). Returns a tuple containing: vel_list: The velocity (ang_vel for Frames, vel for Points) in the provided reference frame. f_list: The forces. Used internally in the KanesMethod and LagrangesMethod classes. """ def flist_iter(): for pair in fl: obj, force = pair if isinstance(obj, ReferenceFrame): yield obj.ang_vel_in(ref_frame), force elif isinstance(obj, Point): yield obj.vel(ref_frame), force else: raise TypeError('First entry in each forcelist pair must ' 'be a point or frame.') if not fl: vel_list, f_list = (), () else: unzip = lambda l: list(zip(*l)) if l[0] else [(), ()] vel_list, f_list = unzip(list(flist_iter())) return vel_list, f_list
f73768535681bc0850287dc37ab03407429a0db7b9638fd534316bdec7eaae20
__all__ = ['Linearizer'] from sympy.core.backend import Matrix, eye, zeros from sympy.core.compatibility import Iterable from sympy import Dummy from sympy.utilities.iterables import flatten from sympy.physics.vector import dynamicsymbols from sympy.physics.mechanics.functions import msubs from collections import namedtuple class Linearizer: """This object holds the general model form for a dynamic system. This model is used for computing the linearized form of the system, while properly dealing with constraints leading to dependent coordinates and speeds. Attributes ---------- f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : Matrix Matrices holding the general system form. q, u, r : Matrix Matrices holding the generalized coordinates, speeds, and input vectors. q_i, u_i : Matrix Matrices of the independent generalized coordinates and speeds. q_d, u_d : Matrix Matrices of the dependent generalized coordinates and speeds. perm_mat : Matrix Permutation matrix such that [q_ind, u_ind]^T = perm_mat*[q, u]^T """ def __init__(self, f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i=None, q_d=None, u_i=None, u_d=None, r=None, lams=None): """ Parameters ---------- f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a : array_like System of equations holding the general system form. Supply empty array or Matrix if the parameter doesn't exist. q : array_like The generalized coordinates. u : array_like The generalized speeds q_i, u_i : array_like, optional The independent generalized coordinates and speeds. q_d, u_d : array_like, optional The dependent generalized coordinates and speeds. r : array_like, optional The input variables. lams : array_like, optional The lagrange multipliers """ # Generalized equation form self.f_0 = Matrix(f_0) self.f_1 = Matrix(f_1) self.f_2 = Matrix(f_2) self.f_3 = Matrix(f_3) self.f_4 = Matrix(f_4) self.f_c = Matrix(f_c) self.f_v = Matrix(f_v) self.f_a = Matrix(f_a) # Generalized equation variables self.q = Matrix(q) self.u = Matrix(u) none_handler = lambda x: Matrix(x) if x else Matrix() self.q_i = none_handler(q_i) self.q_d = none_handler(q_d) self.u_i = none_handler(u_i) self.u_d = none_handler(u_d) self.r = none_handler(r) self.lams = none_handler(lams) # Derivatives of generalized equation variables self._qd = self.q.diff(dynamicsymbols._t) self._ud = self.u.diff(dynamicsymbols._t) # If the user doesn't actually use generalized variables, and the # qd and u vectors have any intersecting variables, this can cause # problems. We'll fix this with some hackery, and Dummy variables dup_vars = set(self._qd).intersection(self.u) self._qd_dup = Matrix([var if var not in dup_vars else Dummy() for var in self._qd]) # Derive dimesion terms l = len(self.f_c) m = len(self.f_v) n = len(self.q) o = len(self.u) s = len(self.r) k = len(self.lams) dims = namedtuple('dims', ['l', 'm', 'n', 'o', 's', 'k']) self._dims = dims(l, m, n, o, s, k) self._setup_done = False def _setup(self): # Calculations here only need to be run once. They are moved out of # the __init__ method to increase the speed of Linearizer creation. self._form_permutation_matrices() self._form_block_matrices() self._form_coefficient_matrices() self._setup_done = True def _form_permutation_matrices(self): """Form the permutation matrices Pq and Pu.""" # Extract dimension variables l, m, n, o, s, k = self._dims # Compute permutation matrices if n != 0: self._Pq = permutation_matrix(self.q, Matrix([self.q_i, self.q_d])) if l > 0: self._Pqi = self._Pq[:, :-l] self._Pqd = self._Pq[:, -l:] else: self._Pqi = self._Pq self._Pqd = Matrix() if o != 0: self._Pu = permutation_matrix(self.u, Matrix([self.u_i, self.u_d])) if m > 0: self._Pui = self._Pu[:, :-m] self._Pud = self._Pu[:, -m:] else: self._Pui = self._Pu self._Pud = Matrix() # Compute combination permutation matrix for computing A and B P_col1 = Matrix([self._Pqi, zeros(o + k, n - l)]) P_col2 = Matrix([zeros(n, o - m), self._Pui, zeros(k, o - m)]) if P_col1: if P_col2: self.perm_mat = P_col1.row_join(P_col2) else: self.perm_mat = P_col1 else: self.perm_mat = P_col2 def _form_coefficient_matrices(self): """Form the coefficient matrices C_0, C_1, and C_2.""" # Extract dimension variables l, m, n, o, s, k = self._dims # Build up the coefficient matrices C_0, C_1, and C_2 # If there are configuration constraints (l > 0), form C_0 as normal. # If not, C_0 is I_(nxn). Note that this works even if n=0 if l > 0: f_c_jac_q = self.f_c.jacobian(self.q) self._C_0 = (eye(n) - self._Pqd * (f_c_jac_q * self._Pqd).LUsolve(f_c_jac_q)) * self._Pqi else: self._C_0 = eye(n) # If there are motion constraints (m > 0), form C_1 and C_2 as normal. # If not, C_1 is 0, and C_2 is I_(oxo). Note that this works even if # o = 0. if m > 0: f_v_jac_u = self.f_v.jacobian(self.u) temp = f_v_jac_u * self._Pud if n != 0: f_v_jac_q = self.f_v.jacobian(self.q) self._C_1 = -self._Pud * temp.LUsolve(f_v_jac_q) else: self._C_1 = zeros(o, n) self._C_2 = (eye(o) - self._Pud * temp.LUsolve(f_v_jac_u)) * self._Pui else: self._C_1 = zeros(o, n) self._C_2 = eye(o) def _form_block_matrices(self): """Form the block matrices for composing M, A, and B.""" # Extract dimension variables l, m, n, o, s, k = self._dims # Block Matrix Definitions. These are only defined if under certain # conditions. If undefined, an empty matrix is used instead if n != 0: self._M_qq = self.f_0.jacobian(self._qd) self._A_qq = -(self.f_0 + self.f_1).jacobian(self.q) else: self._M_qq = Matrix() self._A_qq = Matrix() if n != 0 and m != 0: self._M_uqc = self.f_a.jacobian(self._qd_dup) self._A_uqc = -self.f_a.jacobian(self.q) else: self._M_uqc = Matrix() self._A_uqc = Matrix() if n != 0 and o - m + k != 0: self._M_uqd = self.f_3.jacobian(self._qd_dup) self._A_uqd = -(self.f_2 + self.f_3 + self.f_4).jacobian(self.q) else: self._M_uqd = Matrix() self._A_uqd = Matrix() if o != 0 and m != 0: self._M_uuc = self.f_a.jacobian(self._ud) self._A_uuc = -self.f_a.jacobian(self.u) else: self._M_uuc = Matrix() self._A_uuc = Matrix() if o != 0 and o - m + k != 0: self._M_uud = self.f_2.jacobian(self._ud) self._A_uud = -(self.f_2 + self.f_3).jacobian(self.u) else: self._M_uud = Matrix() self._A_uud = Matrix() if o != 0 and n != 0: self._A_qu = -self.f_1.jacobian(self.u) else: self._A_qu = Matrix() if k != 0 and o - m + k != 0: self._M_uld = self.f_4.jacobian(self.lams) else: self._M_uld = Matrix() if s != 0 and o - m + k != 0: self._B_u = -self.f_3.jacobian(self.r) else: self._B_u = Matrix() def linearize(self, op_point=None, A_and_B=False, simplify=False): """Linearize the system about the operating point. Note that q_op, u_op, qd_op, ud_op must satisfy the equations of motion. These may be either symbolic or numeric. Parameters ---------- op_point : dict or iterable of dicts, optional Dictionary or iterable of dictionaries containing the operating point conditions. These will be substituted in to the linearized system before the linearization is complete. Leave blank if you want a completely symbolic form. Note that any reduction in symbols (whether substituted for numbers or expressions with a common parameter) will result in faster runtime. A_and_B : bool, optional If A_and_B=False (default), (M, A, B) is returned for forming [M]*[q, u]^T = [A]*[q_ind, u_ind]^T + [B]r. If A_and_B=True, (A, B) is returned for forming dx = [A]x + [B]r, where x = [q_ind, u_ind]^T. simplify : bool, optional Determines if returned values are simplified before return. For large expressions this may be time consuming. Default is False. Potential Issues ---------------- Note that the process of solving with A_and_B=True is computationally intensive if there are many symbolic parameters. For this reason, it may be more desirable to use the default A_and_B=False, returning M, A, and B. More values may then be substituted in to these matrices later on. The state space form can then be found as A = P.T*M.LUsolve(A), B = P.T*M.LUsolve(B), where P = Linearizer.perm_mat. """ # Run the setup if needed: if not self._setup_done: self._setup() # Compose dict of operating conditions if isinstance(op_point, dict): op_point_dict = op_point elif isinstance(op_point, Iterable): op_point_dict = {} for op in op_point: op_point_dict.update(op) else: op_point_dict = {} # Extract dimension variables l, m, n, o, s, k = self._dims # Rename terms to shorten expressions M_qq = self._M_qq M_uqc = self._M_uqc M_uqd = self._M_uqd M_uuc = self._M_uuc M_uud = self._M_uud M_uld = self._M_uld A_qq = self._A_qq A_uqc = self._A_uqc A_uqd = self._A_uqd A_qu = self._A_qu A_uuc = self._A_uuc A_uud = self._A_uud B_u = self._B_u C_0 = self._C_0 C_1 = self._C_1 C_2 = self._C_2 # Build up Mass Matrix # |M_qq 0_nxo 0_nxk| # M = |M_uqc M_uuc 0_mxk| # |M_uqd M_uud M_uld| if o != 0: col2 = Matrix([zeros(n, o), M_uuc, M_uud]) if k != 0: col3 = Matrix([zeros(n + m, k), M_uld]) if n != 0: col1 = Matrix([M_qq, M_uqc, M_uqd]) if o != 0 and k != 0: M = col1.row_join(col2).row_join(col3) elif o != 0: M = col1.row_join(col2) else: M = col1 elif k != 0: M = col2.row_join(col3) else: M = col2 M_eq = msubs(M, op_point_dict) # Build up state coefficient matrix A # |(A_qq + A_qu*C_1)*C_0 A_qu*C_2| # A = |(A_uqc + A_uuc*C_1)*C_0 A_uuc*C_2| # |(A_uqd + A_uud*C_1)*C_0 A_uud*C_2| # Col 1 is only defined if n != 0 if n != 0: r1c1 = A_qq if o != 0: r1c1 += (A_qu * C_1) r1c1 = r1c1 * C_0 if m != 0: r2c1 = A_uqc if o != 0: r2c1 += (A_uuc * C_1) r2c1 = r2c1 * C_0 else: r2c1 = Matrix() if o - m + k != 0: r3c1 = A_uqd if o != 0: r3c1 += (A_uud * C_1) r3c1 = r3c1 * C_0 else: r3c1 = Matrix() col1 = Matrix([r1c1, r2c1, r3c1]) else: col1 = Matrix() # Col 2 is only defined if o != 0 if o != 0: if n != 0: r1c2 = A_qu * C_2 else: r1c2 = Matrix() if m != 0: r2c2 = A_uuc * C_2 else: r2c2 = Matrix() if o - m + k != 0: r3c2 = A_uud * C_2 else: r3c2 = Matrix() col2 = Matrix([r1c2, r2c2, r3c2]) else: col2 = Matrix() if col1: if col2: Amat = col1.row_join(col2) else: Amat = col1 else: Amat = col2 Amat_eq = msubs(Amat, op_point_dict) # Build up the B matrix if there are forcing variables # |0_(n + m)xs| # B = |B_u | if s != 0 and o - m + k != 0: Bmat = zeros(n + m, s).col_join(B_u) Bmat_eq = msubs(Bmat, op_point_dict) else: Bmat_eq = Matrix() # kwarg A_and_B indicates to return A, B for forming the equation # dx = [A]x + [B]r, where x = [q_indnd, u_indnd]^T, if A_and_B: A_cont = self.perm_mat.T * M_eq.LUsolve(Amat_eq) if Bmat_eq: B_cont = self.perm_mat.T * M_eq.LUsolve(Bmat_eq) else: # Bmat = Matrix([]), so no need to sub B_cont = Bmat_eq if simplify: A_cont.simplify() B_cont.simplify() return A_cont, B_cont # Otherwise return M, A, B for forming the equation # [M]dx = [A]x + [B]r, where x = [q, u]^T else: if simplify: M_eq.simplify() Amat_eq.simplify() Bmat_eq.simplify() return M_eq, Amat_eq, Bmat_eq def permutation_matrix(orig_vec, per_vec): """Compute the permutation matrix to change order of orig_vec into order of per_vec. Parameters ---------- orig_vec : array_like Symbols in original ordering. per_vec : array_like Symbols in new ordering. Returns ------- p_matrix : Matrix Permutation matrix such that orig_vec == (p_matrix * per_vec). """ if not isinstance(orig_vec, (list, tuple)): orig_vec = flatten(orig_vec) if not isinstance(per_vec, (list, tuple)): per_vec = flatten(per_vec) if set(orig_vec) != set(per_vec): raise ValueError("orig_vec and per_vec must be the same length, " + "and contain the same symbols.") ind_list = [orig_vec.index(i) for i in per_vec] p_matrix = zeros(len(orig_vec)) for i, j in enumerate(ind_list): p_matrix[i, j] = 1 return p_matrix
4f6826a585780b7d50e2617b089631e1b5379a0dee34da73a46c1b6c6c5fecc5
from sympy.core.backend import diff, zeros, Matrix, eye, sympify from sympy.physics.vector import dynamicsymbols, ReferenceFrame from sympy.physics.mechanics.functions import (find_dynamicsymbols, msubs, _f_list_parser) from sympy.physics.mechanics.linearize import Linearizer from sympy.utilities import default_sort_key from sympy.utilities.iterables import iterable __all__ = ['LagrangesMethod'] class LagrangesMethod: """Lagrange's method object. This object generates the equations of motion in a two step procedure. The first step involves the initialization of LagrangesMethod by supplying the Lagrangian and the generalized coordinates, at the bare minimum. If there are any constraint equations, they can be supplied as keyword arguments. The Lagrange multipliers are automatically generated and are equal in number to the constraint equations. Similarly any non-conservative forces can be supplied in an iterable (as described below and also shown in the example) along with a ReferenceFrame. This is also discussed further in the __init__ method. Attributes ========== q, u : Matrix Matrices of the generalized coordinates and speeds forcelist : iterable Iterable of (Point, vector) or (ReferenceFrame, vector) tuples describing the forces on the system. bodies : iterable Iterable containing the rigid bodies and particles of the system. mass_matrix : Matrix The system's mass matrix forcing : Matrix The system's forcing vector mass_matrix_full : Matrix The "mass matrix" for the qdot's, qdoubledot's, and the lagrange multipliers (lam) forcing_full : Matrix The forcing vector for the qdot's, qdoubledot's and lagrange multipliers (lam) Examples ======== This is a simple example for a one degree of freedom translational spring-mass-damper. In this example, we first need to do the kinematics. This involves creating generalized coordinates and their derivatives. Then we create a point and set its velocity in a frame. >>> from sympy.physics.mechanics import LagrangesMethod, Lagrangian >>> from sympy.physics.mechanics import ReferenceFrame, Particle, Point >>> from sympy.physics.mechanics import dynamicsymbols >>> from sympy import symbols >>> q = dynamicsymbols('q') >>> qd = dynamicsymbols('q', 1) >>> m, k, b = symbols('m k b') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> P.set_vel(N, qd * N.x) We need to then prepare the information as required by LagrangesMethod to generate equations of motion. First we create the Particle, which has a point attached to it. Following this the lagrangian is created from the kinetic and potential energies. Then, an iterable of nonconservative forces/torques must be constructed, where each item is a (Point, Vector) or (ReferenceFrame, Vector) tuple, with the Vectors representing the nonconservative forces or torques. >>> Pa = Particle('Pa', P, m) >>> Pa.potential_energy = k * q**2 / 2.0 >>> L = Lagrangian(N, Pa) >>> fl = [(P, -b * qd * N.x)] Finally we can generate the equations of motion. First we create the LagrangesMethod object. To do this one must supply the Lagrangian, and the generalized coordinates. The constraint equations, the forcelist, and the inertial frame may also be provided, if relevant. Next we generate Lagrange's equations of motion, such that: Lagrange's equations of motion = 0. We have the equations of motion at this point. >>> l = LagrangesMethod(L, [q], forcelist = fl, frame = N) >>> print(l.form_lagranges_equations()) Matrix([[b*Derivative(q(t), t) + 1.0*k*q(t) + m*Derivative(q(t), (t, 2))]]) We can also solve for the states using the 'rhs' method. >>> print(l.rhs()) Matrix([[Derivative(q(t), t)], [(-b*Derivative(q(t), t) - 1.0*k*q(t))/m]]) Please refer to the docstrings on each method for more details. """ def __init__(self, Lagrangian, qs, forcelist=None, bodies=None, frame=None, hol_coneqs=None, nonhol_coneqs=None): """Supply the following for the initialization of LagrangesMethod Lagrangian : Sympifyable qs : array_like The generalized coordinates hol_coneqs : array_like, optional The holonomic constraint equations nonhol_coneqs : array_like, optional The nonholonomic constraint equations forcelist : iterable, optional Takes an iterable of (Point, Vector) or (ReferenceFrame, Vector) tuples which represent the force at a point or torque on a frame. This feature is primarily to account for the nonconservative forces and/or moments. bodies : iterable, optional Takes an iterable containing the rigid bodies and particles of the system. frame : ReferenceFrame, optional Supply the inertial frame. This is used to determine the generalized forces due to non-conservative forces. """ self._L = Matrix([sympify(Lagrangian)]) self.eom = None self._m_cd = Matrix() # Mass Matrix of differentiated coneqs self._m_d = Matrix() # Mass Matrix of dynamic equations self._f_cd = Matrix() # Forcing part of the diff coneqs self._f_d = Matrix() # Forcing part of the dynamic equations self.lam_coeffs = Matrix() # The coeffecients of the multipliers forcelist = forcelist if forcelist else [] if not iterable(forcelist): raise TypeError('Force pairs must be supplied in an iterable.') self._forcelist = forcelist if frame and not isinstance(frame, ReferenceFrame): raise TypeError('frame must be a valid ReferenceFrame') self._bodies = bodies self.inertial = frame self.lam_vec = Matrix() self._term1 = Matrix() self._term2 = Matrix() self._term3 = Matrix() self._term4 = Matrix() # Creating the qs, qdots and qdoubledots if not iterable(qs): raise TypeError('Generalized coordinates must be an iterable') self._q = Matrix(qs) self._qdots = self.q.diff(dynamicsymbols._t) self._qdoubledots = self._qdots.diff(dynamicsymbols._t) mat_build = lambda x: Matrix(x) if x else Matrix() hol_coneqs = mat_build(hol_coneqs) nonhol_coneqs = mat_build(nonhol_coneqs) self.coneqs = Matrix([hol_coneqs.diff(dynamicsymbols._t), nonhol_coneqs]) self._hol_coneqs = hol_coneqs def form_lagranges_equations(self): """Method to form Lagrange's equations of motion. Returns a vector of equations of motion using Lagrange's equations of the second kind. """ qds = self._qdots qdd_zero = {i: 0 for i in self._qdoubledots} n = len(self.q) # Internally we represent the EOM as four terms: # EOM = term1 - term2 - term3 - term4 = 0 # First term self._term1 = self._L.jacobian(qds) self._term1 = self._term1.diff(dynamicsymbols._t).T # Second term self._term2 = self._L.jacobian(self.q).T # Third term if self.coneqs: coneqs = self.coneqs m = len(coneqs) # Creating the multipliers self.lam_vec = Matrix(dynamicsymbols('lam1:' + str(m + 1))) self.lam_coeffs = -coneqs.jacobian(qds) self._term3 = self.lam_coeffs.T * self.lam_vec # Extracting the coeffecients of the qdds from the diff coneqs diffconeqs = coneqs.diff(dynamicsymbols._t) self._m_cd = diffconeqs.jacobian(self._qdoubledots) # The remaining terms i.e. the 'forcing' terms in diff coneqs self._f_cd = -diffconeqs.subs(qdd_zero) else: self._term3 = zeros(n, 1) # Fourth term if self.forcelist: N = self.inertial self._term4 = zeros(n, 1) for i, qd in enumerate(qds): flist = zip(*_f_list_parser(self.forcelist, N)) self._term4[i] = sum(v.diff(qd, N) & f for (v, f) in flist) else: self._term4 = zeros(n, 1) # Form the dynamic mass and forcing matrices without_lam = self._term1 - self._term2 - self._term4 self._m_d = without_lam.jacobian(self._qdoubledots) self._f_d = -without_lam.subs(qdd_zero) # Form the EOM self.eom = without_lam - self._term3 return self.eom @property def mass_matrix(self): """Returns the mass matrix, which is augmented by the Lagrange multipliers, if necessary. If the system is described by 'n' generalized coordinates and there are no constraint equations then an n X n matrix is returned. If there are 'n' generalized coordinates and 'm' constraint equations have been supplied during initialization then an n X (n+m) matrix is returned. The (n + m - 1)th and (n + m)th columns contain the coefficients of the Lagrange multipliers. """ if self.eom is None: raise ValueError('Need to compute the equations of motion first') if self.coneqs: return (self._m_d).row_join(self.lam_coeffs.T) else: return self._m_d @property def mass_matrix_full(self): """Augments the coefficients of qdots to the mass_matrix.""" if self.eom is None: raise ValueError('Need to compute the equations of motion first') n = len(self.q) m = len(self.coneqs) row1 = eye(n).row_join(zeros(n, n + m)) row2 = zeros(n, n).row_join(self.mass_matrix) if self.coneqs: row3 = zeros(m, n).row_join(self._m_cd).row_join(zeros(m, m)) return row1.col_join(row2).col_join(row3) else: return row1.col_join(row2) @property def forcing(self): """Returns the forcing vector from 'lagranges_equations' method.""" if self.eom is None: raise ValueError('Need to compute the equations of motion first') return self._f_d @property def forcing_full(self): """Augments qdots to the forcing vector above.""" if self.eom is None: raise ValueError('Need to compute the equations of motion first') if self.coneqs: return self._qdots.col_join(self.forcing).col_join(self._f_cd) else: return self._qdots.col_join(self.forcing) def to_linearizer(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None): """Returns an instance of the Linearizer class, initiated from the data in the LagrangesMethod class. This may be more desirable than using the linearize class method, as the Linearizer object will allow more efficient recalculation (i.e. about varying operating points). Parameters ========== q_ind, qd_ind : array_like, optional The independent generalized coordinates and speeds. q_dep, qd_dep : array_like, optional The dependent generalized coordinates and speeds. """ # Compose vectors t = dynamicsymbols._t q = self.q u = self._qdots ud = u.diff(t) # Get vector of lagrange multipliers lams = self.lam_vec mat_build = lambda x: Matrix(x) if x else Matrix() q_i = mat_build(q_ind) q_d = mat_build(q_dep) u_i = mat_build(qd_ind) u_d = mat_build(qd_dep) # Compose general form equations f_c = self._hol_coneqs f_v = self.coneqs f_a = f_v.diff(t) f_0 = u f_1 = -u f_2 = self._term1 f_3 = -(self._term2 + self._term4) f_4 = -self._term3 # Check that there are an appropriate number of independent and # dependent coordinates if len(q_d) != len(f_c) or len(u_d) != len(f_v): raise ValueError(("Must supply {:} dependent coordinates, and " + "{:} dependent speeds").format(len(f_c), len(f_v))) if set(Matrix([q_i, q_d])) != set(q): raise ValueError("Must partition q into q_ind and q_dep, with " + "no extra or missing symbols.") if set(Matrix([u_i, u_d])) != set(u): raise ValueError("Must partition qd into qd_ind and qd_dep, " + "with no extra or missing symbols.") # Find all other dynamic symbols, forming the forcing vector r. # Sort r to make it canonical. insyms = set(Matrix([q, u, ud, lams])) r = list(find_dynamicsymbols(f_3, insyms)) r.sort(key=default_sort_key) # Check for any derivatives of variables in r that are also found in r. for i in r: if diff(i, dynamicsymbols._t) in r: raise ValueError('Cannot have derivatives of specified \ quantities when linearizing forcing terms.') return Linearizer(f_0, f_1, f_2, f_3, f_4, f_c, f_v, f_a, q, u, q_i, q_d, u_i, u_d, r, lams) def linearize(self, q_ind=None, qd_ind=None, q_dep=None, qd_dep=None, **kwargs): """Linearize the equations of motion about a symbolic operating point. If kwarg A_and_B is False (default), returns M, A, B, r for the linearized form, M*[q', u']^T = A*[q_ind, u_ind]^T + B*r. If kwarg A_and_B is True, returns A, B, r for the linearized form dx = A*x + B*r, where x = [q_ind, u_ind]^T. Note that this is computationally intensive if there are many symbolic parameters. For this reason, it may be more desirable to use the default A_and_B=False, returning M, A, and B. Values may then be substituted in to these matrices, and the state space form found as A = P.T*M.inv()*A, B = P.T*M.inv()*B, where P = Linearizer.perm_mat. In both cases, r is found as all dynamicsymbols in the equations of motion that are not part of q, u, q', or u'. They are sorted in canonical form. The operating points may be also entered using the ``op_point`` kwarg. This takes a dictionary of {symbol: value}, or a an iterable of such dictionaries. The values may be numeric or symbolic. The more values you can specify beforehand, the faster this computation will run. For more documentation, please see the ``Linearizer`` class.""" linearizer = self.to_linearizer(q_ind, qd_ind, q_dep, qd_dep) result = linearizer.linearize(**kwargs) return result + (linearizer.r,) def solve_multipliers(self, op_point=None, sol_type='dict'): """Solves for the values of the lagrange multipliers symbolically at the specified operating point Parameters ========== op_point : dict or iterable of dicts, optional Point at which to solve at. The operating point is specified as a dictionary or iterable of dictionaries of {symbol: value}. The value may be numeric or symbolic itself. sol_type : str, optional Solution return type. Valid options are: - 'dict': A dict of {symbol : value} (default) - 'Matrix': An ordered column matrix of the solution """ # Determine number of multipliers k = len(self.lam_vec) if k == 0: raise ValueError("System has no lagrange multipliers to solve for.") # Compose dict of operating conditions if isinstance(op_point, dict): op_point_dict = op_point elif iterable(op_point): op_point_dict = {} for op in op_point: op_point_dict.update(op) elif op_point is None: op_point_dict = {} else: raise TypeError("op_point must be either a dictionary or an " "iterable of dictionaries.") # Compose the system to be solved mass_matrix = self.mass_matrix.col_join(-self.lam_coeffs.row_join( zeros(k, k))) force_matrix = self.forcing.col_join(self._f_cd) # Sub in the operating point mass_matrix = msubs(mass_matrix, op_point_dict) force_matrix = msubs(force_matrix, op_point_dict) # Solve for the multipliers sol_list = mass_matrix.LUsolve(-force_matrix)[-k:] if sol_type == 'dict': return dict(zip(self.lam_vec, sol_list)) elif sol_type == 'Matrix': return Matrix(sol_list) else: raise ValueError("Unknown sol_type {:}.".format(sol_type)) def rhs(self, inv_method=None, **kwargs): """Returns equations that can be solved numerically Parameters ========== inv_method : str The specific sympy inverse matrix calculation method to use. For a list of valid methods, see :meth:`~sympy.matrices.matrices.MatrixBase.inv` """ if inv_method is None: self._rhs = self.mass_matrix_full.LUsolve(self.forcing_full) else: self._rhs = (self.mass_matrix_full.inv(inv_method, try_block_diag=True) * self.forcing_full) return self._rhs @property def q(self): return self._q @property def u(self): return self._qdots @property def bodies(self): return self._bodies @property def forcelist(self): return self._forcelist
2931857c81bb500bb83962df30a4bd9be266017ade53d33131207b9e3114bb7e
from sympy.core.backend import sympify from sympy.physics.vector import Point from sympy.utilities.exceptions import SymPyDeprecationWarning __all__ = ['Particle'] class Particle: """A particle. Particles have a non-zero mass and lack spatial extension; they take up no space. Values need to be supplied on initialization, but can be changed later. Parameters ========== name : str Name of particle point : Point A physics/mechanics Point which represents the position, velocity, and acceleration of this Particle mass : sympifyable A SymPy expression representing the Particle's mass Examples ======== >>> from sympy.physics.mechanics import Particle, Point >>> from sympy import Symbol >>> po = Point('po') >>> m = Symbol('m') >>> pa = Particle('pa', po, m) >>> # Or you could change these later >>> pa.mass = m >>> pa.point = po """ def __init__(self, name, point, mass): if not isinstance(name, str): raise TypeError('Supply a valid name.') self._name = name self.mass = mass self.point = point self.potential_energy = 0 def __str__(self): return self._name def __repr__(self): return self.__str__() @property def mass(self): """Mass of the particle.""" return self._mass @mass.setter def mass(self, value): self._mass = sympify(value) @property def point(self): """Point of the particle.""" return self._point @point.setter def point(self, p): if not isinstance(p, Point): raise TypeError("Particle point attribute must be a Point object.") self._point = p def linear_momentum(self, frame): """Linear momentum of the particle. The linear momentum L, of a particle P, with respect to frame N is given by L = m * v where m is the mass of the particle, and v is the velocity of the particle in the frame N. Parameters ========== frame : ReferenceFrame The frame in which linear momentum is desired. Examples ======== >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame >>> from sympy.physics.mechanics import dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> m, v = dynamicsymbols('m v') >>> N = ReferenceFrame('N') >>> P = Point('P') >>> A = Particle('A', P, m) >>> P.set_vel(N, v * N.x) >>> A.linear_momentum(N) m*v*N.x """ return self.mass * self.point.vel(frame) def angular_momentum(self, point, frame): """Angular momentum of the particle about the point. The angular momentum H, about some point O of a particle, P, is given by: H = r x m * v where r is the position vector from point O to the particle P, m is the mass of the particle, and v is the velocity of the particle in the inertial frame, N. Parameters ========== point : Point The point about which angular momentum of the particle is desired. frame : ReferenceFrame The frame in which angular momentum is desired. Examples ======== >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame >>> from sympy.physics.mechanics import dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> m, v, r = dynamicsymbols('m v r') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> A = O.locatenew('A', r * N.x) >>> P = Particle('P', A, m) >>> P.point.set_vel(N, v * N.y) >>> P.angular_momentum(O, N) m*r*v*N.z """ return self.point.pos_from(point) ^ (self.mass * self.point.vel(frame)) def kinetic_energy(self, frame): """Kinetic energy of the particle The kinetic energy, T, of a particle, P, is given by 'T = 1/2 m v^2' where m is the mass of particle P, and v is the velocity of the particle in the supplied ReferenceFrame. Parameters ========== frame : ReferenceFrame The Particle's velocity is typically defined with respect to an inertial frame but any relevant frame in which the velocity is known can be supplied. Examples ======== >>> from sympy.physics.mechanics import Particle, Point, ReferenceFrame >>> from sympy import symbols >>> m, v, r = symbols('m v r') >>> N = ReferenceFrame('N') >>> O = Point('O') >>> P = Particle('P', O, m) >>> P.point.set_vel(N, v * N.y) >>> P.kinetic_energy(N) m*v**2/2 """ return (self.mass / sympify(2) * self.point.vel(frame) & self.point.vel(frame)) @property def potential_energy(self): """The potential energy of the Particle. Examples ======== >>> from sympy.physics.mechanics import Particle, Point >>> from sympy import symbols >>> m, g, h = symbols('m g h') >>> O = Point('O') >>> P = Particle('P', O, m) >>> P.potential_energy = m * g * h >>> P.potential_energy g*h*m """ return self._pe @potential_energy.setter def potential_energy(self, scalar): """Used to set the potential energy of the Particle. Parameters ========== scalar : Sympifyable The potential energy (a scalar) of the Particle. Examples ======== >>> from sympy.physics.mechanics import Particle, Point >>> from sympy import symbols >>> m, g, h = symbols('m g h') >>> O = Point('O') >>> P = Particle('P', O, m) >>> P.potential_energy = m * g * h """ self._pe = sympify(scalar) def set_potential_energy(self, scalar): SymPyDeprecationWarning( feature="Method sympy.physics.mechanics." + "Particle.set_potential_energy(self, scalar)", useinstead="property sympy.physics.mechanics." + "Particle.potential_energy", deprecated_since_version="1.5", issue=9800).warn() self.potential_energy = scalar def parallel_axis(self, point, frame): """Returns an inertia dyadic of the particle with respect to another point and frame. Parameters ========== point : sympy.physics.vector.Point The point to express the inertia dyadic about. frame : sympy.physics.vector.ReferenceFrame The reference frame used to construct the dyadic. Returns ======= inertia : sympy.physics.vector.Dyadic The inertia dyadic of the particle expressed about the provided point and frame. """ # circular import issue from sympy.physics.mechanics import inertia_of_point_mass return inertia_of_point_mass(self.mass, self.point.pos_from(point), frame)
e56d2e4d7a4d9158cc24c4804feb8c11a596fa531049f288c7376f061046b0b7
from __future__ import print_function, division from .vector import Vector, _check_vector from .frame import _check_frame from warnings import warn __all__ = ['Point'] class Point(object): """This object represents a point in a dynamic system. It stores the: position, velocity, and acceleration of a point. The position is a vector defined as the vector distance from a parent point to this point. Parameters ========== name : string The display name of the Point Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> N = ReferenceFrame('N') >>> O = Point('O') >>> P = Point('P') >>> u1, u2, u3 = dynamicsymbols('u1 u2 u3') >>> O.set_vel(N, u1 * N.x + u2 * N.y + u3 * N.z) >>> O.acc(N) u1'*N.x + u2'*N.y + u3'*N.z symbols() can be used to create multiple Points in a single step, for example: >>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> from sympy import symbols >>> N = ReferenceFrame('N') >>> u1, u2 = dynamicsymbols('u1 u2') >>> A, B = symbols('A B', cls=Point) >>> type(A) <class 'sympy.physics.vector.point.Point'> >>> A.set_vel(N, u1 * N.x + u2 * N.y) >>> B.set_vel(N, u2 * N.x + u1 * N.y) >>> A.acc(N) - B.acc(N) (u1' - u2')*N.x + (-u1' + u2')*N.y """ def __init__(self, name): """Initialization of a Point object. """ self.name = name self._pos_dict = {} self._vel_dict = {} self._acc_dict = {} self._pdlist = [self._pos_dict, self._vel_dict, self._acc_dict] def __str__(self): return self.name __repr__ = __str__ def _check_point(self, other): if not isinstance(other, Point): raise TypeError('A Point must be supplied') def _pdict_list(self, other, num): """Returns a list of points that gives the shortest path with respect to position, velocity, or acceleration from this point to the provided point. Parameters ========== other : Point A point that may be related to this point by position, velocity, or acceleration. num : integer 0 for searching the position tree, 1 for searching the velocity tree, and 2 for searching the acceleration tree. Returns ======= list of Points A sequence of points from self to other. Notes ===== It isn't clear if num = 1 or num = 2 actually works because the keys to ``_vel_dict`` and ``_acc_dict`` are :class:`ReferenceFrame` objects which do not have the ``_pdlist`` attribute. """ outlist = [[self]] oldlist = [[]] while outlist != oldlist: oldlist = outlist[:] for i, v in enumerate(outlist): templist = v[-1]._pdlist[num].keys() for i2, v2 in enumerate(templist): if not v.__contains__(v2): littletemplist = v + [v2] if not outlist.__contains__(littletemplist): outlist.append(littletemplist) for i, v in enumerate(oldlist): if v[-1] != other: outlist.remove(v) outlist.sort(key=len) if len(outlist) != 0: return outlist[0] raise ValueError('No Connecting Path found between ' + other.name + ' and ' + self.name) def a1pt_theory(self, otherpoint, outframe, interframe): """Sets the acceleration of this point with the 1-point theory. The 1-point theory for point acceleration looks like this: ^N a^P = ^B a^P + ^N a^O + ^N alpha^B x r^OP + ^N omega^B x (^N omega^B x r^OP) + 2 ^N omega^B x ^B v^P where O is a point fixed in B, P is a point moving in B, and B is rotating in frame N. Parameters ========== otherpoint : Point The first point of the 1-point theory (O) outframe : ReferenceFrame The frame we want this point's acceleration defined in (N) fixedframe : ReferenceFrame The intermediate frame in this calculation (B) Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> from sympy.physics.vector import dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> q = dynamicsymbols('q') >>> q2 = dynamicsymbols('q2') >>> qd = dynamicsymbols('q', 1) >>> q2d = dynamicsymbols('q2', 1) >>> N = ReferenceFrame('N') >>> B = ReferenceFrame('B') >>> B.set_ang_vel(N, 5 * B.y) >>> O = Point('O') >>> P = O.locatenew('P', q * B.x) >>> P.set_vel(B, qd * B.x + q2d * B.y) >>> O.set_vel(N, 0) >>> P.a1pt_theory(O, N, B) (-25*q + q'')*B.x + q2''*B.y - 10*q'*B.z """ _check_frame(outframe) _check_frame(interframe) self._check_point(otherpoint) dist = self.pos_from(otherpoint) v = self.vel(interframe) a1 = otherpoint.acc(outframe) a2 = self.acc(interframe) omega = interframe.ang_vel_in(outframe) alpha = interframe.ang_acc_in(outframe) self.set_acc(outframe, a2 + 2 * (omega ^ v) + a1 + (alpha ^ dist) + (omega ^ (omega ^ dist))) return self.acc(outframe) def a2pt_theory(self, otherpoint, outframe, fixedframe): """Sets the acceleration of this point with the 2-point theory. The 2-point theory for point acceleration looks like this: ^N a^P = ^N a^O + ^N alpha^B x r^OP + ^N omega^B x (^N omega^B x r^OP) where O and P are both points fixed in frame B, which is rotating in frame N. Parameters ========== otherpoint : Point The first point of the 2-point theory (O) outframe : ReferenceFrame The frame we want this point's acceleration defined in (N) fixedframe : ReferenceFrame The frame in which both points are fixed (B) Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> q = dynamicsymbols('q') >>> qd = dynamicsymbols('q', 1) >>> N = ReferenceFrame('N') >>> B = N.orientnew('B', 'Axis', [q, N.z]) >>> O = Point('O') >>> P = O.locatenew('P', 10 * B.x) >>> O.set_vel(N, 5 * N.x) >>> P.a2pt_theory(O, N, B) - 10*q'**2*B.x + 10*q''*B.y """ _check_frame(outframe) _check_frame(fixedframe) self._check_point(otherpoint) dist = self.pos_from(otherpoint) a = otherpoint.acc(outframe) omega = fixedframe.ang_vel_in(outframe) alpha = fixedframe.ang_acc_in(outframe) self.set_acc(outframe, a + (alpha ^ dist) + (omega ^ (omega ^ dist))) return self.acc(outframe) def acc(self, frame): """The acceleration Vector of this Point in a ReferenceFrame. Parameters ========== frame : ReferenceFrame The frame in which the returned acceleration vector will be defined in Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p1.set_acc(N, 10 * N.x) >>> p1.acc(N) 10*N.x """ _check_frame(frame) if not (frame in self._acc_dict): if self._vel_dict[frame] != 0: return (self._vel_dict[frame]).dt(frame) else: return Vector(0) return self._acc_dict[frame] def locatenew(self, name, value): """Creates a new point with a position defined from this point. Parameters ========== name : str The name for the new point value : Vector The position of the new point relative to this point Examples ======== >>> from sympy.physics.vector import ReferenceFrame, Point >>> N = ReferenceFrame('N') >>> P1 = Point('P1') >>> P2 = P1.locatenew('P2', 10 * N.x) """ if not isinstance(name, str): raise TypeError('Must supply a valid name') if value == 0: value = Vector(0) value = _check_vector(value) p = Point(name) p.set_pos(self, value) self.set_pos(p, -value) return p def pos_from(self, otherpoint): """Returns a Vector distance between this Point and the other Point. Parameters ========== otherpoint : Point The otherpoint we are locating this one relative to Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p2 = Point('p2') >>> p1.set_pos(p2, 10 * N.x) >>> p1.pos_from(p2) 10*N.x """ outvec = Vector(0) plist = self._pdict_list(otherpoint, 0) for i in range(len(plist) - 1): outvec += plist[i]._pos_dict[plist[i + 1]] return outvec def set_acc(self, frame, value): """Used to set the acceleration of this Point in a ReferenceFrame. Parameters ========== frame : ReferenceFrame The frame in which this point's acceleration is defined value : Vector The vector value of this point's acceleration in the frame Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p1.set_acc(N, 10 * N.x) >>> p1.acc(N) 10*N.x """ if value == 0: value = Vector(0) value = _check_vector(value) _check_frame(frame) self._acc_dict.update({frame: value}) def set_pos(self, otherpoint, value): """Used to set the position of this point w.r.t. another point. Parameters ========== otherpoint : Point The other point which this point's location is defined relative to value : Vector The vector which defines the location of this point Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p2 = Point('p2') >>> p1.set_pos(p2, 10 * N.x) >>> p1.pos_from(p2) 10*N.x """ if value == 0: value = Vector(0) value = _check_vector(value) self._check_point(otherpoint) self._pos_dict.update({otherpoint: value}) otherpoint._pos_dict.update({self: -value}) def set_vel(self, frame, value): """Sets the velocity Vector of this Point in a ReferenceFrame. Parameters ========== frame : ReferenceFrame The frame in which this point's velocity is defined value : Vector The vector value of this point's velocity in the frame Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p1.set_vel(N, 10 * N.x) >>> p1.vel(N) 10*N.x """ if value == 0: value = Vector(0) value = _check_vector(value) _check_frame(frame) self._vel_dict.update({frame: value}) def v1pt_theory(self, otherpoint, outframe, interframe): """Sets the velocity of this point with the 1-point theory. The 1-point theory for point velocity looks like this: ^N v^P = ^B v^P + ^N v^O + ^N omega^B x r^OP where O is a point fixed in B, P is a point moving in B, and B is rotating in frame N. Parameters ========== otherpoint : Point The first point of the 2-point theory (O) outframe : ReferenceFrame The frame we want this point's velocity defined in (N) interframe : ReferenceFrame The intermediate frame in this calculation (B) Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame >>> from sympy.physics.vector import dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> q = dynamicsymbols('q') >>> q2 = dynamicsymbols('q2') >>> qd = dynamicsymbols('q', 1) >>> q2d = dynamicsymbols('q2', 1) >>> N = ReferenceFrame('N') >>> B = ReferenceFrame('B') >>> B.set_ang_vel(N, 5 * B.y) >>> O = Point('O') >>> P = O.locatenew('P', q * B.x) >>> P.set_vel(B, qd * B.x + q2d * B.y) >>> O.set_vel(N, 0) >>> P.v1pt_theory(O, N, B) q'*B.x + q2'*B.y - 5*q*B.z """ _check_frame(outframe) _check_frame(interframe) self._check_point(otherpoint) dist = self.pos_from(otherpoint) v1 = self.vel(interframe) v2 = otherpoint.vel(outframe) omega = interframe.ang_vel_in(outframe) self.set_vel(outframe, v1 + v2 + (omega ^ dist)) return self.vel(outframe) def v2pt_theory(self, otherpoint, outframe, fixedframe): """Sets the velocity of this point with the 2-point theory. The 2-point theory for point velocity looks like this: ^N v^P = ^N v^O + ^N omega^B x r^OP where O and P are both points fixed in frame B, which is rotating in frame N. Parameters ========== otherpoint : Point The first point of the 2-point theory (O) outframe : ReferenceFrame The frame we want this point's velocity defined in (N) fixedframe : ReferenceFrame The frame in which both points are fixed (B) Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols >>> from sympy.physics.vector import init_vprinting >>> init_vprinting(pretty_print=False) >>> q = dynamicsymbols('q') >>> qd = dynamicsymbols('q', 1) >>> N = ReferenceFrame('N') >>> B = N.orientnew('B', 'Axis', [q, N.z]) >>> O = Point('O') >>> P = O.locatenew('P', 10 * B.x) >>> O.set_vel(N, 5 * N.x) >>> P.v2pt_theory(O, N, B) 5*N.x + 10*q'*B.y """ _check_frame(outframe) _check_frame(fixedframe) self._check_point(otherpoint) dist = self.pos_from(otherpoint) v = otherpoint.vel(outframe) omega = fixedframe.ang_vel_in(outframe) self.set_vel(outframe, v + (omega ^ dist)) return self.vel(outframe) def vel(self, frame): """The velocity Vector of this Point in the ReferenceFrame. Parameters ========== frame : ReferenceFrame The frame in which the returned velocity vector will be defined in Examples ======== >>> from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols >>> N = ReferenceFrame('N') >>> p1 = Point('p1') >>> p1.set_vel(N, 10 * N.x) >>> p1.vel(N) 10*N.x Velocities will be automatically calculated if possible, otherwise a ``ValueError`` will be returned. If it is possible to calculate multiple different velocities from the relative points, the points defined most directly relative to this point will be used. In the case of inconsistent relative positions of points, incorrect velocities may be returned. It is up to the user to define prior relative positions and velocities of points in a self-consistent way. >>> p = Point('p') >>> q = dynamicsymbols('q') >>> p.set_vel(N, 10 * N.x) >>> p2 = Point('p2') >>> p2.set_pos(p, q*N.x) >>> p2.vel(N) (Derivative(q(t), t) + 10)*N.x """ _check_frame(frame) if not (frame in self._vel_dict): valid_neighbor_found = False is_cyclic = False visited = [] queue = [self] candidate_neighbor = [] while queue: #BFS to find nearest point node = queue.pop(0) if node not in visited: visited.append(node) for neighbor, neighbor_pos in node._pos_dict.items(): if neighbor in visited: continue try: neighbor_pos.express(frame) #Checks if pos vector is valid except ValueError: continue if neighbor in queue: is_cyclic = True try : neighbor_velocity = neighbor._vel_dict[frame] #Checks if point has its vel defined in req frame except KeyError: queue.append(neighbor) continue candidate_neighbor.append(neighbor) if not valid_neighbor_found: self.set_vel(frame, self.pos_from(neighbor).dt(frame) + neighbor_velocity) valid_neighbor_found = True if is_cyclic: warn('Kinematic loops are defined among the positions of points. This is likely not desired and may cause errors in your calculations.') if len(candidate_neighbor) > 1: warn('Velocity automatically calculated based on point ' + candidate_neighbor[0].name + ' but it is also possible from points(s):' + str(candidate_neighbor[1:]) + '. Velocities from these points are not necessarily the same. This may cause errors in your calculations.') if valid_neighbor_found: return self._vel_dict[frame] else: raise ValueError('Velocity of point ' + self.name + ' has not been' ' defined in ReferenceFrame ' + frame.name) return self._vel_dict[frame] def partial_velocity(self, frame, *gen_speeds): """Returns the partial velocities of the linear velocity vector of this point in the given frame with respect to one or more provided generalized speeds. Parameters ========== frame : ReferenceFrame The frame with which the velocity is defined in. gen_speeds : functions of time The generalized speeds. Returns ======= partial_velocities : tuple of Vector The partial velocity vectors corresponding to the provided generalized speeds. Examples ======== >>> from sympy.physics.vector import ReferenceFrame, Point >>> from sympy.physics.vector import dynamicsymbols >>> N = ReferenceFrame('N') >>> A = ReferenceFrame('A') >>> p = Point('p') >>> u1, u2 = dynamicsymbols('u1, u2') >>> p.set_vel(N, u1 * N.x + u2 * A.y) >>> p.partial_velocity(N, u1) N.x >>> p.partial_velocity(N, u1, u2) (N.x, A.y) """ partials = [self.vel(frame).diff(speed, frame, var_in_dcm=False) for speed in gen_speeds] if len(partials) == 1: return partials[0] else: return tuple(partials)
12b1bff112d95023e2a7b2279e07262320ec172426ed14dd1b4c827574e21d10
from sympy import evalf, symbols, pi, sin, cos, sqrt, acos, Matrix from sympy.physics.mechanics import (ReferenceFrame, dynamicsymbols, inertia, KanesMethod, RigidBody, Point, dot, msubs) from sympy.testing.pytest import slow, ON_TRAVIS, skip, warns_deprecated_sympy @slow def test_bicycle(): if ON_TRAVIS: skip("Too slow for travis.") # Code to get equations of motion for a bicycle modeled as in: # J.P Meijaard, Jim M Papadopoulos, Andy Ruina and A.L Schwab. Linearized # dynamics equations for the balance and steer of a bicycle: a benchmark # and review. Proceedings of The Royal Society (2007) 463, 1955-1982 # doi: 10.1098/rspa.2007.1857 # Note that this code has been crudely ported from Autolev, which is the # reason for some of the unusual naming conventions. It was purposefully as # similar as possible in order to aide debugging. # Declare Coordinates & Speeds # Simple definitions for qdots - qd = u # Speeds are: yaw frame ang. rate, roll frame ang. rate, rear wheel frame # ang. rate (spinning motion), frame ang. rate (pitching motion), steering # frame ang. rate, and front wheel ang. rate (spinning motion). # Wheel positions are ignorable coordinates, so they are not introduced. q1, q2, q4, q5 = dynamicsymbols('q1 q2 q4 q5') q1d, q2d, q4d, q5d = dynamicsymbols('q1 q2 q4 q5', 1) u1, u2, u3, u4, u5, u6 = dynamicsymbols('u1 u2 u3 u4 u5 u6') u1d, u2d, u3d, u4d, u5d, u6d = dynamicsymbols('u1 u2 u3 u4 u5 u6', 1) # Declare System's Parameters WFrad, WRrad, htangle, forkoffset = symbols('WFrad WRrad htangle forkoffset') forklength, framelength, forkcg1 = symbols('forklength framelength forkcg1') forkcg3, framecg1, framecg3, Iwr11 = symbols('forkcg3 framecg1 framecg3 Iwr11') Iwr22, Iwf11, Iwf22, Iframe11 = symbols('Iwr22 Iwf11 Iwf22 Iframe11') Iframe22, Iframe33, Iframe31, Ifork11 = symbols('Iframe22 Iframe33 Iframe31 Ifork11') Ifork22, Ifork33, Ifork31, g = symbols('Ifork22 Ifork33 Ifork31 g') mframe, mfork, mwf, mwr = symbols('mframe mfork mwf mwr') # Set up reference frames for the system # N - inertial # Y - yaw # R - roll # WR - rear wheel, rotation angle is ignorable coordinate so not oriented # Frame - bicycle frame # TempFrame - statically rotated frame for easier reference inertia definition # Fork - bicycle fork # TempFork - statically rotated frame for easier reference inertia definition # WF - front wheel, again posses a ignorable coordinate N = ReferenceFrame('N') Y = N.orientnew('Y', 'Axis', [q1, N.z]) R = Y.orientnew('R', 'Axis', [q2, Y.x]) Frame = R.orientnew('Frame', 'Axis', [q4 + htangle, R.y]) WR = ReferenceFrame('WR') TempFrame = Frame.orientnew('TempFrame', 'Axis', [-htangle, Frame.y]) Fork = Frame.orientnew('Fork', 'Axis', [q5, Frame.x]) TempFork = Fork.orientnew('TempFork', 'Axis', [-htangle, Fork.y]) WF = ReferenceFrame('WF') # Kinematics of the Bicycle First block of code is forming the positions of # the relevant points # rear wheel contact -> rear wheel mass center -> frame mass center + # frame/fork connection -> fork mass center + front wheel mass center -> # front wheel contact point WR_cont = Point('WR_cont') WR_mc = WR_cont.locatenew('WR_mc', WRrad * R.z) Steer = WR_mc.locatenew('Steer', framelength * Frame.z) Frame_mc = WR_mc.locatenew('Frame_mc', - framecg1 * Frame.x + framecg3 * Frame.z) Fork_mc = Steer.locatenew('Fork_mc', - forkcg1 * Fork.x + forkcg3 * Fork.z) WF_mc = Steer.locatenew('WF_mc', forklength * Fork.x + forkoffset * Fork.z) WF_cont = WF_mc.locatenew('WF_cont', WFrad * (dot(Fork.y, Y.z) * Fork.y - Y.z).normalize()) # Set the angular velocity of each frame. # Angular accelerations end up being calculated automatically by # differentiating the angular velocities when first needed. # u1 is yaw rate # u2 is roll rate # u3 is rear wheel rate # u4 is frame pitch rate # u5 is fork steer rate # u6 is front wheel rate Y.set_ang_vel(N, u1 * Y.z) R.set_ang_vel(Y, u2 * R.x) WR.set_ang_vel(Frame, u3 * Frame.y) Frame.set_ang_vel(R, u4 * Frame.y) Fork.set_ang_vel(Frame, u5 * Fork.x) WF.set_ang_vel(Fork, u6 * Fork.y) # Form the velocities of the previously defined points, using the 2 - point # theorem (written out by hand here). Accelerations again are calculated # automatically when first needed. WR_cont.set_vel(N, 0) WR_mc.v2pt_theory(WR_cont, N, WR) Steer.v2pt_theory(WR_mc, N, Frame) Frame_mc.v2pt_theory(WR_mc, N, Frame) Fork_mc.v2pt_theory(Steer, N, Fork) WF_mc.v2pt_theory(Steer, N, Fork) WF_cont.v2pt_theory(WF_mc, N, WF) # Sets the inertias of each body. Uses the inertia frame to construct the # inertia dyadics. Wheel inertias are only defined by principle moments of # inertia, and are in fact constant in the frame and fork reference frames; # it is for this reason that the orientations of the wheels does not need # to be defined. The frame and fork inertias are defined in the 'Temp' # frames which are fixed to the appropriate body frames; this is to allow # easier input of the reference values of the benchmark paper. Note that # due to slightly different orientations, the products of inertia need to # have their signs flipped; this is done later when entering the numerical # value. Frame_I = (inertia(TempFrame, Iframe11, Iframe22, Iframe33, 0, 0, Iframe31), Frame_mc) Fork_I = (inertia(TempFork, Ifork11, Ifork22, Ifork33, 0, 0, Ifork31), Fork_mc) WR_I = (inertia(Frame, Iwr11, Iwr22, Iwr11), WR_mc) WF_I = (inertia(Fork, Iwf11, Iwf22, Iwf11), WF_mc) # Declaration of the RigidBody containers. :: BodyFrame = RigidBody('BodyFrame', Frame_mc, Frame, mframe, Frame_I) BodyFork = RigidBody('BodyFork', Fork_mc, Fork, mfork, Fork_I) BodyWR = RigidBody('BodyWR', WR_mc, WR, mwr, WR_I) BodyWF = RigidBody('BodyWF', WF_mc, WF, mwf, WF_I) # The kinematic differential equations; they are defined quite simply. Each # entry in this list is equal to zero. kd = [q1d - u1, q2d - u2, q4d - u4, q5d - u5] # The nonholonomic constraints are the velocity of the front wheel contact # point dotted into the X, Y, and Z directions; the yaw frame is used as it # is "closer" to the front wheel (1 less DCM connecting them). These # constraints force the velocity of the front wheel contact point to be 0 # in the inertial frame; the X and Y direction constraints enforce a # "no-slip" condition, and the Z direction constraint forces the front # wheel contact point to not move away from the ground frame, essentially # replicating the holonomic constraint which does not allow the frame pitch # to change in an invalid fashion. conlist_speed = [WF_cont.vel(N) & Y.x, WF_cont.vel(N) & Y.y, WF_cont.vel(N) & Y.z] # The holonomic constraint is that the position from the rear wheel contact # point to the front wheel contact point when dotted into the # normal-to-ground plane direction must be zero; effectively that the front # and rear wheel contact points are always touching the ground plane. This # is actually not part of the dynamic equations, but instead is necessary # for the lineraization process. conlist_coord = [WF_cont.pos_from(WR_cont) & Y.z] # The force list; each body has the appropriate gravitational force applied # at its mass center. FL = [(Frame_mc, -mframe * g * Y.z), (Fork_mc, -mfork * g * Y.z), (WF_mc, -mwf * g * Y.z), (WR_mc, -mwr * g * Y.z)] BL = [BodyFrame, BodyFork, BodyWR, BodyWF] # The N frame is the inertial frame, coordinates are supplied in the order # of independent, dependent coordinates, as are the speeds. The kinematic # differential equation are also entered here. Here the dependent speeds # are specified, in the same order they were provided in earlier, along # with the non-holonomic constraints. The dependent coordinate is also # provided, with the holonomic constraint. Again, this is only provided # for the linearization process. KM = KanesMethod(N, q_ind=[q1, q2, q5], q_dependent=[q4], configuration_constraints=conlist_coord, u_ind=[u2, u3, u5], u_dependent=[u1, u4, u6], velocity_constraints=conlist_speed, kd_eqs=kd) with warns_deprecated_sympy(): (fr, frstar) = KM.kanes_equations(FL, BL) # This is the start of entering in the numerical values from the benchmark # paper to validate the eigen values of the linearized equations from this # model to the reference eigen values. Look at the aforementioned paper for # more information. Some of these are intermediate values, used to # transform values from the paper into the coordinate systems used in this # model. PaperRadRear = 0.3 PaperRadFront = 0.35 HTA = evalf.N(pi / 2 - pi / 10) TrailPaper = 0.08 rake = evalf.N(-(TrailPaper*sin(HTA)-(PaperRadFront*cos(HTA)))) PaperWb = 1.02 PaperFrameCgX = 0.3 PaperFrameCgZ = 0.9 PaperForkCgX = 0.9 PaperForkCgZ = 0.7 FrameLength = evalf.N(PaperWb*sin(HTA)-(rake-(PaperRadFront-PaperRadRear)*cos(HTA))) FrameCGNorm = evalf.N((PaperFrameCgZ - PaperRadRear-(PaperFrameCgX/sin(HTA))*cos(HTA))*sin(HTA)) FrameCGPar = evalf.N(PaperFrameCgX / sin(HTA) + (PaperFrameCgZ - PaperRadRear - PaperFrameCgX / sin(HTA) * cos(HTA)) * cos(HTA)) tempa = evalf.N(PaperForkCgZ - PaperRadFront) tempb = evalf.N(PaperWb-PaperForkCgX) tempc = evalf.N(sqrt(tempa**2+tempb**2)) PaperForkL = evalf.N(PaperWb*cos(HTA)-(PaperRadFront-PaperRadRear)*sin(HTA)) ForkCGNorm = evalf.N(rake+(tempc * sin(pi/2-HTA-acos(tempa/tempc)))) ForkCGPar = evalf.N(tempc * cos((pi/2-HTA)-acos(tempa/tempc))-PaperForkL) # Here is the final assembly of the numerical values. The symbol 'v' is the # forward speed of the bicycle (a concept which only makes sense in the # upright, static equilibrium case?). These are in a dictionary which will # later be substituted in. Again the sign on the *product* of inertia # values is flipped here, due to different orientations of coordinate # systems. v = symbols('v') val_dict = {WFrad: PaperRadFront, WRrad: PaperRadRear, htangle: HTA, forkoffset: rake, forklength: PaperForkL, framelength: FrameLength, forkcg1: ForkCGPar, forkcg3: ForkCGNorm, framecg1: FrameCGNorm, framecg3: FrameCGPar, Iwr11: 0.0603, Iwr22: 0.12, Iwf11: 0.1405, Iwf22: 0.28, Ifork11: 0.05892, Ifork22: 0.06, Ifork33: 0.00708, Ifork31: 0.00756, Iframe11: 9.2, Iframe22: 11, Iframe33: 2.8, Iframe31: -2.4, mfork: 4, mframe: 85, mwf: 3, mwr: 2, g: 9.81, q1: 0, q2: 0, q4: 0, q5: 0, u1: 0, u2: 0, u3: v / PaperRadRear, u4: 0, u5: 0, u6: v / PaperRadFront} # Linearizes the forcing vector; the equations are set up as MM udot = # forcing, where MM is the mass matrix, udot is the vector representing the # time derivatives of the generalized speeds, and forcing is a vector which # contains both external forcing terms and internal forcing terms, such as # centripital or coriolis forces. This actually returns a matrix with as # many rows as *total* coordinates and speeds, but only as many columns as # independent coordinates and speeds. forcing_lin = KM.linearize()[0] # As mentioned above, the size of the linearized forcing terms is expanded # to include both q's and u's, so the mass matrix must have this done as # well. This will likely be changed to be part of the linearized process, # for future reference. MM_full = KM.mass_matrix_full MM_full_s = msubs(MM_full, val_dict) forcing_lin_s = msubs(forcing_lin, KM.kindiffdict(), val_dict) MM_full_s = MM_full_s.evalf() forcing_lin_s = forcing_lin_s.evalf() # Finally, we construct an "A" matrix for the form xdot = A x (x being the # state vector, although in this case, the sizes are a little off). The # following line extracts only the minimum entries required for eigenvalue # analysis, which correspond to rows and columns for lean, steer, lean # rate, and steer rate. Amat = MM_full_s.inv() * forcing_lin_s A = Amat.extract([1, 2, 4, 6], [1, 2, 3, 5]) # Precomputed for comparison Res = Matrix([[ 0, 0, 1.0, 0], [ 0, 0, 0, 1.0], [9.48977444677355, -0.891197738059089*v**2 - 0.571523173729245, -0.105522449805691*v, -0.330515398992311*v], [11.7194768719633, -1.97171508499972*v**2 + 30.9087533932407, 3.67680523332152*v, -3.08486552743311*v]]) # Actual eigenvalue comparison eps = 1.e-12 for i in range(6): error = Res.subs(v, i) - A.subs(v, i) assert all(abs(x) < eps for x in error)
65ddcbc0bb8e74a2c4ee231d98bdea0664df59c9e1e7331727774911fb807efd
from typing import Optional from sympy import Derivative, Integer, Expr from sympy.matrices.common import MatrixCommon from .ndim_array import NDimArray from .arrayop import derive_by_array from sympy import MatrixExpr from sympy import ZeroMatrix from sympy.matrices.expressions.matexpr import _matrix_derivative class ArrayDerivative(Derivative): is_scalar = False def __new__(cls, expr, *variables, **kwargs): obj = super(ArrayDerivative, cls).__new__(cls, expr, *variables, **kwargs) if isinstance(obj, ArrayDerivative): obj._shape = obj._get_shape() return obj def _get_shape(self): shape = () for v, count in self.variable_count: if hasattr(v, "shape"): for i in range(count): shape += v.shape if hasattr(self.expr, "shape"): shape += self.expr.shape return shape @property def shape(self): return self._shape @classmethod def _get_zero_with_shape_like(cls, expr): if isinstance(expr, (MatrixCommon, NDimArray)): return expr.zeros(*expr.shape) elif isinstance(expr, MatrixExpr): return ZeroMatrix(*expr.shape) else: raise RuntimeError("Unable to determine shape of array-derivative.") @staticmethod def _call_derive_scalar_by_matrix(expr, v): # type: (Expr, MatrixCommon) -> Expr return v.applyfunc(lambda x: expr.diff(x)) @staticmethod def _call_derive_scalar_by_matexpr(expr, v): # type: (Expr, MatrixExpr) -> Expr if expr.has(v): return _matrix_derivative(expr, v) else: return ZeroMatrix(*v.shape) @staticmethod def _call_derive_scalar_by_array(expr, v): # type: (Expr, NDimArray) -> Expr return v.applyfunc(lambda x: expr.diff(x)) @staticmethod def _call_derive_matrix_by_scalar(expr, v): # type: (MatrixCommon, Expr) -> Expr return _matrix_derivative(expr, v) @staticmethod def _call_derive_matexpr_by_scalar(expr, v): # type: (MatrixExpr, Expr) -> Expr return expr._eval_derivative(v) @staticmethod def _call_derive_array_by_scalar(expr, v): # type: (NDimArray, Expr) -> Expr return expr.applyfunc(lambda x: x.diff(v)) @staticmethod def _call_derive_default(expr, v): # type: (Expr, Expr) -> Optional[Expr] if expr.has(v): return _matrix_derivative(expr, v) else: return None @classmethod def _dispatch_eval_derivative_n_times(cls, expr, v, count): # Evaluate the derivative `n` times. If # `_eval_derivative_n_times` is not overridden by the current # object, the default in `Basic` will call a loop over # `_eval_derivative`: if not isinstance(count, (int, Integer)) or ((count <= 0) == True): return None # TODO: this could be done with multiple-dispatching: if expr.is_scalar: if isinstance(v, MatrixCommon): result = cls._call_derive_scalar_by_matrix(expr, v) elif isinstance(v, MatrixExpr): result = cls._call_derive_scalar_by_matexpr(expr, v) elif isinstance(v, NDimArray): result = cls._call_derive_scalar_by_array(expr, v) elif v.is_scalar: # scalar by scalar has a special return super(ArrayDerivative, cls)._dispatch_eval_derivative_n_times(expr, v, count) else: return None elif v.is_scalar: if isinstance(expr, MatrixCommon): result = cls._call_derive_matrix_by_scalar(expr, v) elif isinstance(expr, MatrixExpr): result = cls._call_derive_matexpr_by_scalar(expr, v) elif isinstance(expr, NDimArray): result = cls._call_derive_array_by_scalar(expr, v) else: return None else: # Both `expr` and `v` are some array/matrix type: if isinstance(expr, MatrixCommon) or isinstance(expr, MatrixCommon): result = derive_by_array(expr, v) elif isinstance(expr, MatrixExpr) and isinstance(v, MatrixExpr): result = cls._call_derive_default(expr, v) elif isinstance(expr, MatrixExpr) or isinstance(v, MatrixExpr): # if one expression is a symbolic matrix expression while the other isn't, don't evaluate: return None else: result = derive_by_array(expr, v) if result is None: return None if count == 1: return result else: return cls._dispatch_eval_derivative_n_times(result, v, count - 1)
1af055add5bf7194c43fabb0b8c42115b929e5b6e3b65cc3c05cdf08bb0dd468
from __future__ import print_function, division 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.compatibility import SYMPY_INTS, Iterable from sympy.printing.defaults import Printable import itertools 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) 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): raise TypeError(str(other)) 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")
1c7ca883b4d9b42290e647176ac68e7add7d25b4810c1a216274c5ecfb2b28f1
from __future__ import print_function, division import functools from sympy import Basic, Tuple, S from sympy.core.sympify import _sympify from sympy.tensor.array.mutable_ndim_array import MutableNDimArray from sympy.tensor.array.ndim_array import NDimArray, ImmutableNDimArray from sympy.simplify.simplify import simplify class DenseNDimArray(NDimArray): def __new__(self, *args, **kwargs): return ImmutableDenseNDimArray(*args, **kwargs) def __getitem__(self, index): """ Allows to get items from N-dim array. Examples ======== >>> from sympy import MutableDenseNDimArray >>> a = MutableDenseNDimArray([0, 1, 2, 3], (2, 2)) >>> a [[0, 1], [2, 3]] >>> a[0, 0] 0 >>> a[1, 1] 3 >>> a[0] [0, 1] >>> a[1] [2, 3] Symbolic index: >>> from sympy.abc import i, j >>> a[i, j] [[0, 1], [2, 3]][i, j] Replace `i` and `j` to get element `(1, 1)`: >>> a[i, j].subs({i: 1, j: 1}) 3 """ syindex = self._check_symbolic_index(index) if syindex is not None: return syindex index = self._check_index_for_getitem(index) if isinstance(index, tuple) and any([isinstance(i, slice) for i in index]): sl_factors, eindices = self._get_slice_data_for_array_access(index) array = [self._array[self._parse_index(i)] for i in eindices] nshape = [len(el) for i, el in enumerate(sl_factors) if isinstance(index[i], slice)] return type(self)(array, nshape) else: index = self._parse_index(index) return self._array[index] @classmethod def zeros(cls, *shape): list_length = functools.reduce(lambda x, y: x*y, shape, S.One) return cls._new(([0]*list_length,), shape) def tomatrix(self): """ Converts MutableDenseNDimArray to Matrix. Can convert only 2-dim array, else will raise error. Examples ======== >>> from sympy import MutableDenseNDimArray >>> a = MutableDenseNDimArray([1 for i in range(9)], (3, 3)) >>> b = a.tomatrix() >>> b Matrix([ [1, 1, 1], [1, 1, 1], [1, 1, 1]]) """ from sympy.matrices import Matrix if self.rank() != 2: raise ValueError('Dimensions must be of size of 2') return Matrix(self.shape[0], self.shape[1], self._array) def reshape(self, *newshape): """ Returns MutableDenseNDimArray instance with new shape. Elements number must be suitable to new shape. The only argument of method sets new shape. Examples ======== >>> from sympy import MutableDenseNDimArray >>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3)) >>> a.shape (2, 3) >>> a [[1, 2, 3], [4, 5, 6]] >>> b = a.reshape(3, 2) >>> b.shape (3, 2) >>> b [[1, 2], [3, 4], [5, 6]] """ new_total_size = functools.reduce(lambda x,y: x*y, newshape) if new_total_size != self._loop_size: raise ValueError("Invalid reshape parameters " + newshape) # there is no `.func` as this class does not subtype `Basic`: return type(self)(self._array, newshape) class ImmutableDenseNDimArray(DenseNDimArray, ImmutableNDimArray): """ """ def __new__(cls, iterable, shape=None, **kwargs): return cls._new(iterable, shape, **kwargs) @classmethod def _new(cls, iterable, shape, **kwargs): from sympy.utilities.iterables import flatten shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs) shape = Tuple(*map(_sympify, shape)) cls._check_special_bounds(flat_list, shape) flat_list = flatten(flat_list) flat_list = Tuple(*flat_list) self = Basic.__new__(cls, flat_list, shape, **kwargs) self._shape = shape self._array = list(flat_list) self._rank = len(shape) self._loop_size = functools.reduce(lambda x,y: x*y, shape, 1) return self def __setitem__(self, index, value): raise TypeError('immutable N-dim array') def as_mutable(self): return MutableDenseNDimArray(self) def _eval_simplify(self, **kwargs): return self.applyfunc(simplify) class MutableDenseNDimArray(DenseNDimArray, MutableNDimArray): def __new__(cls, iterable=None, shape=None, **kwargs): return cls._new(iterable, shape, **kwargs) @classmethod def _new(cls, iterable, shape, **kwargs): from sympy.utilities.iterables import flatten shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs) flat_list = flatten(flat_list) self = object.__new__(cls) self._shape = shape self._array = list(flat_list) self._rank = len(shape) self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list) return self def __setitem__(self, index, value): """Allows to set items to MutableDenseNDimArray. Examples ======== >>> from sympy import MutableDenseNDimArray >>> a = MutableDenseNDimArray.zeros(2, 2) >>> a[0,0] = 1 >>> a[1,1] = 1 >>> a [[1, 0], [0, 1]] """ if isinstance(index, tuple) and any([isinstance(i, slice) for i in index]): value, eindices, slice_offsets = self._get_slice_data_for_array_assignment(index, value) for i in eindices: other_i = [ind - j for ind, j in zip(i, slice_offsets) if j is not None] self._array[self._parse_index(i)] = value[other_i] else: index = self._parse_index(index) self._setter_iterable_check(value) value = _sympify(value) self._array[index] = value def as_immutable(self): return ImmutableDenseNDimArray(self) @property def free_symbols(self): return {i for j in self._array for i in j.free_symbols}
4188820a6b4f3930b5aca67d8c8dfe6328094c9f677f1e644596ea549eb53c83
from sympy.testing.pytest import raises from sympy import ( Array, ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray, sin, cos, simplify ) from sympy.abc import x, y array_types = [ ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray ] def test_array_negative_indices(): for ArrayType in array_types: test_array = ArrayType([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) assert test_array[:, -1] == Array([5, 10]) assert test_array[:, -2] == Array([4, 9]) assert test_array[:, -3] == Array([3, 8]) assert test_array[:, -4] == Array([2, 7]) assert test_array[:, -5] == Array([1, 6]) assert test_array[:, 0] == Array([1, 6]) assert test_array[:, 1] == Array([2, 7]) assert test_array[:, 2] == Array([3, 8]) assert test_array[:, 3] == Array([4, 9]) assert test_array[:, 4] == Array([5, 10]) raises(ValueError, lambda: test_array[:, -6]) raises(ValueError, lambda: test_array[-3, :]) assert test_array[-1, -1] == 10 def test_issue_18361(): A = Array([sin(2 * x) - 2 * sin(x) * cos(x)]) B = Array([sin(x)**2 + cos(x)**2, 0]) C = Array([(x + x**2)/(x*sin(y)**2 + x*cos(y)**2), 2*sin(x)*cos(x)]) assert simplify(A) == Array([0]) assert simplify(B) == Array([1, 0]) assert simplify(C) == Array([x + 1, sin(2*x)])
8a81af00795abb0be083be3edc3b9e1b41e9a2758d52f60befb331cdaad4a4f5
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.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 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(MatrixExpr, self)._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
f9a4d02c535edd0bae45b5b834ee0aee5b376ca75456b0ca1389faae0207dfb5
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) == set(((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)) not in (S.true, 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)
8de7048ca4ef3bbad98d9ab17a0da2434930629650fa3985ab6343befb813574
#!/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.strategies', 'sympy.strategies.branch', 'sympy.tensor', 'sympy.tensor.array', '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.tests', 'sympy.strategies.branch.tests', 'sympy.strategies.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 )
73f5aa987962ddad0b96e74423aa01f9fbbf7fed72260067c2595e0fb576dcef
#!/usr/bin/env python """ Test that the installed modules in setup.py are up-to-date. If this test fails, run python bin/generate_test_list.py and python bin/generate_module_list.py to generate the up-to-date test and modules list to put in setup.py. """ import generate_test_list import generate_module_list from get_sympy import path_hack path_hack() import setup module_list = generate_module_list.generate_module_list() test_list = generate_test_list.generate_test_list() assert setup.modules == module_list, set(setup.modules).symmetric_difference(set(module_list)) assert setup.tests == test_list, set(setup.tests).symmetric_difference(set(test_list)) print("setup.py modules and tests are OK")
eadfd5db4930f735e42b48050846e699b2161d9a740135b013a919ddf7cd7e82
""" 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,))
b221e7de82351b9dd00f3a8af9d3aee67cb5efe7b798e90b290bd96a684f7d08
from __future__ import print_function, division import random import itertools from typing import Sequence as tSequence, Union as tUnion, List as tList, Tuple as tTuple from sympy import (Matrix, MatrixSymbol, S, Indexed, Basic, Tuple, Range, Set, And, Eq, FiniteSet, ImmutableMatrix, Integer, igcd, Lambda, Mul, Dummy, IndexedBase, Add, Interval, oo, linsolve, eye, Or, Not, Intersection, factorial, Contains, Union, Expr, Function, exp, cacheit, sqrt, pi, gamma, Ge, Piecewise, Symbol, NonSquareMatrixError, EmptySet, ceiling, MatrixBase, ConditionSet, ones, zeros, Identity, Rational, Lt, Gt, Le, Ne, BlockMatrix, Sum) from sympy.core.relational import Relational from sympy.logic.boolalg import Boolean from sympy.utilities.exceptions import SymPyDeprecationWarning from sympy.utilities.iterables import strongly_connected_components from sympy.stats.joint_rv import JointDistribution from sympy.stats.joint_rv_types import JointDistributionHandmade from sympy.stats.rv import (RandomIndexedSymbol, random_symbols, RandomSymbol, _symbol_converter, _value_check, pspace, given, dependent, is_random, sample_iter, Distribution, Density) from sympy.stats.stochastic_process import StochasticPSpace from sympy.stats.symbolic_probability import Probability, Expectation from sympy.stats.frv_types import Bernoulli, BernoulliDistribution, FiniteRV from sympy.stats.drv_types import Poisson, PoissonDistribution from sympy.stats.crv_types import Normal, NormalDistribution, Gamma, GammaDistribution from sympy.core.sympify import _sympify, sympify __all__ = [ 'StochasticProcess', 'DiscreteTimeStochasticProcess', 'DiscreteMarkovChain', 'TransitionMatrixOf', 'StochasticStateSpaceOf', 'GeneratorMatrixOf', 'ContinuousMarkovChain', 'BernoulliProcess', 'PoissonProcess', 'WienerProcess', 'GammaProcess' ] @is_random.register(Indexed) def _(x): return is_random(x.base) @is_random.register(RandomIndexedSymbol) # type: ignore def _(x): return True def _set_converter(itr): """ Helper function for converting list/tuple/set to Set. If parameter is not an instance of list/tuple/set then no operation is performed. Returns ======= Set The argument converted to Set. Raises ====== TypeError If the argument is not an instance of list/tuple/set. """ if isinstance(itr, (list, tuple, set)): itr = FiniteSet(*itr) if not isinstance(itr, Set): raise TypeError("%s is not an instance of list/tuple/set."%(itr)) return itr def _state_converter(itr: tSequence) -> tUnion[Tuple, Range]: """ Helper function for converting list/tuple/set/Range/Tuple/FiniteSet to tuple/Range. """ if isinstance(itr, (Tuple, set, FiniteSet)): itr = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr)) elif isinstance(itr, (list, tuple)): # check if states are unique if len(set(itr)) != len(itr): raise ValueError('The state space must have unique elements.') itr = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr)) elif isinstance(itr, Range): # the only ordered set in sympy I know of # try to convert to tuple try: itr = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr)) except ValueError: pass else: raise TypeError("%s is not an instance of list/tuple/set/Range/Tuple/FiniteSet." % (itr)) return itr def _sym_sympify(arg): """ Converts an arbitrary expression to a type that can be used inside SymPy. As generally strings are unwise to use in the expressions, it returns the Symbol of argument if the string type argument is passed. Parameters ========= arg: The parameter to be converted to be used in Sympy. Returns ======= The converted parameter. """ if isinstance(arg, str): return Symbol(arg) else: return _sympify(arg) def _matrix_checks(matrix): if not isinstance(matrix, (Matrix, MatrixSymbol, ImmutableMatrix)): raise TypeError("Transition probabilities either should " "be a Matrix or a MatrixSymbol.") if matrix.shape[0] != matrix.shape[1]: raise NonSquareMatrixError("%s is not a square matrix"%(matrix)) if isinstance(matrix, Matrix): matrix = ImmutableMatrix(matrix.tolist()) return matrix class StochasticProcess(Basic): """ Base class for all the stochastic processes whether discrete or continuous. Parameters ========== sym: Symbol or str state_space: Set The state space of the stochastic process, by default S.Reals. For discrete sets it is zero indexed. See Also ======== DiscreteTimeStochasticProcess """ index_set = S.Reals def __new__(cls, sym, state_space=S.Reals, **kwargs): sym = _symbol_converter(sym) state_space = _set_converter(state_space) return Basic.__new__(cls, sym, state_space) @property def symbol(self): return self.args[0] @property def state_space(self) -> tUnion[FiniteSet, Range]: if not isinstance(self.args[1], (FiniteSet, Range)): return FiniteSet(*self.args[1]) return self.args[1] def _deprecation_warn_distribution(self): SymPyDeprecationWarning( feature="Calling distribution with RandomIndexedSymbol", useinstead="distribution with just timestamp as argument", issue=20078, deprecated_since_version="1.7.1" ).warn() def distribution(self, key=None): if key is None: self._deprecation_warn_distribution() return Distribution() def density(self, x): return Density() def __call__(self, time): """ Overridden in ContinuousTimeStochasticProcess. """ raise NotImplementedError("Use [] for indexing discrete time stochastic process.") def __getitem__(self, time): """ Overridden in DiscreteTimeStochasticProcess. """ raise NotImplementedError("Use () for indexing continuous time stochastic process.") def probability(self, condition): raise NotImplementedError() def joint_distribution(self, *args): """ Computes the joint distribution of the random indexed variables. Parameters ========== args: iterable The finite list of random indexed variables/the key of a stochastic process whose joint distribution has to be computed. Returns ======= JointDistribution The joint distribution of the list of random indexed variables. An unevaluated object is returned if it is not possible to compute the joint distribution. Raises ====== ValueError: When the arguments passed are not of type RandomIndexSymbol or Number. """ args = list(args) for i, arg in enumerate(args): if S(arg).is_Number: if self.index_set.is_subset(S.Integers): args[i] = self.__getitem__(arg) else: args[i] = self.__call__(arg) elif not isinstance(arg, RandomIndexedSymbol): raise ValueError("Expected a RandomIndexedSymbol or " "key not %s"%(type(arg))) if args[0].pspace.distribution == Distribution(): return JointDistribution(*args) density = Lambda(tuple(args), expr=Mul.fromiter(arg.pspace.process.density(arg) for arg in args)) return JointDistributionHandmade(density) def expectation(self, condition, given_condition): raise NotImplementedError("Abstract method for expectation queries.") def sample(self): raise NotImplementedError("Abstract method for sampling queries.") class DiscreteTimeStochasticProcess(StochasticProcess): """ Base class for all discrete stochastic processes. """ def __getitem__(self, time): """ For indexing discrete time stochastic processes. Returns ======= RandomIndexedSymbol """ time = sympify(time) if not time.is_symbol and time not in self.index_set: raise IndexError("%s is not in the index set of %s"%(time, self.symbol)) idx_obj = Indexed(self.symbol, time) pspace_obj = StochasticPSpace(self.symbol, self, self.distribution(time)) return RandomIndexedSymbol(idx_obj, pspace_obj) class ContinuousTimeStochasticProcess(StochasticProcess): """ Base class for all continuous time stochastic process. """ def __call__(self, time): """ For indexing continuous time stochastic processes. Returns ======= RandomIndexedSymbol """ time = sympify(time) if not time.is_symbol and time not in self.index_set: raise IndexError("%s is not in the index set of %s"%(time, self.symbol)) func_obj = Function(self.symbol)(time) pspace_obj = StochasticPSpace(self.symbol, self, self.distribution(time)) return RandomIndexedSymbol(func_obj, pspace_obj) class TransitionMatrixOf(Boolean): """ Assumes that the matrix is the transition matrix of the process. """ def __new__(cls, process, matrix): if not isinstance(process, DiscreteMarkovChain): raise ValueError("Currently only DiscreteMarkovChain " "support TransitionMatrixOf.") matrix = _matrix_checks(matrix) return Basic.__new__(cls, process, matrix) process = property(lambda self: self.args[0]) matrix = property(lambda self: self.args[1]) class GeneratorMatrixOf(TransitionMatrixOf): """ Assumes that the matrix is the generator matrix of the process. """ def __new__(cls, process, matrix): if not isinstance(process, ContinuousMarkovChain): raise ValueError("Currently only ContinuousMarkovChain " "support GeneratorMatrixOf.") matrix = _matrix_checks(matrix) return Basic.__new__(cls, process, matrix) class StochasticStateSpaceOf(Boolean): def __new__(cls, process, state_space): if not isinstance(process, (DiscreteMarkovChain, ContinuousMarkovChain)): raise ValueError("Currently only DiscreteMarkovChain and ContinuousMarkovChain " "support StochasticStateSpaceOf.") state_space = _state_converter(state_space) if isinstance(state_space, Range): ss_size = ceiling((state_space.stop - state_space.start) / state_space.step) else: ss_size = len(state_space) state_index = Range(ss_size) return Basic.__new__(cls, process, state_index) process = property(lambda self: self.args[0]) state_index = property(lambda self: self.args[1]) class MarkovProcess(StochasticProcess): """ Contains methods that handle queries common to Markov processes. """ @property def number_of_states(self) -> tUnion[Integer, Symbol]: """ The number of states in the Markov Chain. """ return _sympify(self.args[2].shape[0]) @property def _state_index(self) -> Range: """ Returns state index as Range. """ return self.args[1] @classmethod def _sanity_checks(cls, state_space, trans_probs): # Try to never have None as state_space or trans_probs. # This helps a lot if we get it done at the start. if (state_space is None) and (trans_probs is None): _n = Dummy('n', integer=True, nonnegative=True) state_space = _state_converter(Range(_n)) trans_probs = _matrix_checks(MatrixSymbol('_T', _n, _n)) elif state_space is None: trans_probs = _matrix_checks(trans_probs) state_space = _state_converter(Range(trans_probs.shape[0])) elif trans_probs is None: state_space = _state_converter(state_space) if isinstance(state_space, Range): _n = ceiling((state_space.stop - state_space.start) / state_space.step) else: _n = len(state_space) trans_probs = MatrixSymbol('_T', _n, _n) else: state_space = _state_converter(state_space) trans_probs = _matrix_checks(trans_probs) # Range object doesn't want to give a symbolic size # so we do it ourselves. if isinstance(state_space, Range): ss_size = ceiling((state_space.stop - state_space.start) / state_space.step) else: ss_size = len(state_space) if ss_size != trans_probs.shape[0]: raise ValueError('The size of the state space and the number of ' 'rows of the transition matrix must be the same.') return state_space, trans_probs def _extract_information(self, given_condition): """ Helper function to extract information, like, transition matrix/generator matrix, state space, etc. """ if isinstance(self, DiscreteMarkovChain): trans_probs = self.transition_probabilities state_index = self._state_index elif isinstance(self, ContinuousMarkovChain): trans_probs = self.generator_matrix state_index = self._state_index if isinstance(given_condition, And): gcs = given_condition.args given_condition = S.true for gc in gcs: if isinstance(gc, TransitionMatrixOf): trans_probs = gc.matrix if isinstance(gc, StochasticStateSpaceOf): state_index = gc.state_index if isinstance(gc, Relational): given_condition = given_condition & gc if isinstance(given_condition, TransitionMatrixOf): trans_probs = given_condition.matrix given_condition = S.true if isinstance(given_condition, StochasticStateSpaceOf): state_index = given_condition.state_index given_condition = S.true return trans_probs, state_index, given_condition def _check_trans_probs(self, trans_probs, row_sum=1): """ Helper function for checking the validity of transition probabilities. """ if not isinstance(trans_probs, MatrixSymbol): rows = trans_probs.tolist() for row in rows: if (sum(row) - row_sum) != 0: raise ValueError("Values in a row must sum to %s. " "If you are using Float or floats then please use Rational."%(row_sum)) def _work_out_state_index(self, state_index, given_condition, trans_probs): """ Helper function to extract state space if there is a random symbol in the given condition. """ # if given condition is None, then there is no need to work out # state_space from random variables if given_condition != None: rand_var = list(given_condition.atoms(RandomSymbol) - given_condition.atoms(RandomIndexedSymbol)) if len(rand_var) == 1: state_index = rand_var[0].pspace.set # `not None` is `True`. So the old test fails for symbolic sizes. # Need to build the statement differently. sym_cond = not isinstance(self.number_of_states, (int, Integer)) cond1 = not sym_cond and len(state_index) != trans_probs.shape[0] if cond1: raise ValueError("state space is not compatible with the transition probabilities.") if not isinstance(trans_probs.shape[0], Symbol): state_index = FiniteSet(*[i for i in range(trans_probs.shape[0])]) return state_index @cacheit def _preprocess(self, given_condition, evaluate): """ Helper function for pre-processing the information. """ is_insufficient = False if not evaluate: # avoid pre-processing if the result is not to be evaluated return (True, None, None, None) # extracting transition matrix and state space trans_probs, state_index, given_condition = self._extract_information(given_condition) # given_condition does not have sufficient information # for computations if trans_probs == None or \ given_condition == None: is_insufficient = True else: # checking transition probabilities if isinstance(self, DiscreteMarkovChain): self._check_trans_probs(trans_probs, row_sum=1) elif isinstance(self, ContinuousMarkovChain): self._check_trans_probs(trans_probs, row_sum=0) # working out state space state_index = self._work_out_state_index(state_index, given_condition, trans_probs) return is_insufficient, trans_probs, state_index, given_condition def replace_with_index(self, condition): if isinstance(condition, Relational): lhs, rhs = condition.lhs, condition.rhs if not isinstance(lhs, RandomIndexedSymbol): lhs, rhs = rhs, lhs condition = type(condition)(self.index_of.get(lhs, lhs), self.index_of.get(rhs, rhs)) return condition def probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Handles probability queries for Markov process. Parameters ========== condition: Relational given_condition: Relational/And Returns ======= Probability If the information is not sufficient. Expr In all other cases. Note ==== Any information passed at the time of query overrides any information passed at the time of object creation like transition probabilities, state space. Pass the transition matrix using TransitionMatrixOf, generator matrix using GeneratorMatrixOf and state space using StochasticStateSpaceOf in given_condition using & or And. """ check, mat, state_index, new_given_condition = \ self._preprocess(given_condition, evaluate) rv = list(condition.atoms(RandomIndexedSymbol)) symbolic = False for sym in rv: if sym.key.is_symbol: symbolic = True break if check: return Probability(condition, new_given_condition) if isinstance(self, ContinuousMarkovChain): trans_probs = self.transition_probabilities(mat) elif isinstance(self, DiscreteMarkovChain): trans_probs = mat condition = self.replace_with_index(condition) given_condition = self.replace_with_index(given_condition) new_given_condition = self.replace_with_index(new_given_condition) if isinstance(condition, Relational): if isinstance(new_given_condition, And): gcs = new_given_condition.args else: gcs = (new_given_condition, ) min_key_rv = list(new_given_condition.atoms(RandomIndexedSymbol)) if len(min_key_rv): min_key_rv = min_key_rv[0] for r in rv: if min_key_rv.key.is_symbol or r.key.is_symbol: continue if min_key_rv.key > r.key: return Probability(condition) else: min_key_rv = None return Probability(condition) if symbolic: return self._symbolic_probability(condition, new_given_condition, rv, min_key_rv) if len(rv) > 1: rv[0] = condition.lhs rv[1] = condition.rhs if rv[0].key < rv[1].key: rv[0], rv[1] = rv[1], rv[0] if isinstance(condition, Gt): condition = Lt(condition.lhs, condition.rhs) elif isinstance(condition, Lt): condition = Gt(condition.lhs, condition.rhs) elif isinstance(condition, Ge): condition = Le(condition.lhs, condition.rhs) elif isinstance(condition, Le): condition = Ge(condition.lhs, condition.rhs) s = Rational(0, 1) n = len(self.state_space) if isinstance(condition, Eq) or isinstance(condition, Ne): for i in range(0, n): s += self.probability(Eq(rv[0], i), Eq(rv[1], i)) * self.probability(Eq(rv[1], i), new_given_condition) return s if isinstance(condition, Eq) else 1 - s else: upper = 0 greater = False if isinstance(condition, Ge) or isinstance(condition, Lt): upper = 1 if isinstance(condition, Gt) or isinstance(condition, Ge): greater = True for i in range(0, n): if i <= n//2: for j in range(0, i + upper): s += self.probability(Eq(rv[0], i), Eq(rv[1], j)) * self.probability(Eq(rv[1], j), new_given_condition) else: s += self.probability(Eq(rv[0], i), new_given_condition) for j in range(i + upper, n): s -= self.probability(Eq(rv[0], i), Eq(rv[1], j)) * self.probability(Eq(rv[1], j), new_given_condition) return s if greater else 1 - s rv = rv[0] states = condition.as_set() prob, gstate = dict(), None for gc in gcs: if gc.has(min_key_rv): if gc.has(Probability): p, gp = (gc.rhs, gc.lhs) if isinstance(gc.lhs, Probability) \ else (gc.lhs, gc.rhs) gr = gp.args[0] gset = Intersection(gr.as_set(), state_index) gstate = list(gset)[0] prob[gset] = p else: _, gstate = (gc.lhs.key, gc.rhs) if isinstance(gc.lhs, RandomIndexedSymbol) \ else (gc.rhs.key, gc.lhs) if any((k not in self.index_set) for k in (rv.key, min_key_rv.key)): raise IndexError("The timestamps of the process are not in it's index set.") states = Intersection(states, state_index) if not isinstance(self.number_of_states, Symbol) else states for state in Union(states, FiniteSet(gstate)): if not isinstance(state, (int, Integer)) or Ge(state, mat.shape[0]) is True: raise IndexError("No information is available for (%s, %s) in " "transition probabilities of shape, (%s, %s). " "State space is zero indexed." %(gstate, state, mat.shape[0], mat.shape[1])) if prob: gstates = Union(*prob.keys()) if len(gstates) == 1: gstate = list(gstates)[0] gprob = list(prob.values())[0] prob[gstates] = gprob elif len(gstates) == len(state_index) - 1: gstate = list(state_index - gstates)[0] gprob = S.One - sum(prob.values()) prob[state_index - gstates] = gprob else: raise ValueError("Conflicting information.") else: gprob = S.One if min_key_rv == rv: return sum([prob[FiniteSet(state)] for state in states]) if isinstance(self, ContinuousMarkovChain): return gprob * sum([trans_probs(rv.key - min_key_rv.key).__getitem__((gstate, state)) for state in states]) if isinstance(self, DiscreteMarkovChain): return gprob * sum([(trans_probs**(rv.key - min_key_rv.key)).__getitem__((gstate, state)) for state in states]) if isinstance(condition, Not): expr = condition.args[0] return S.One - self.probability(expr, given_condition, evaluate, **kwargs) if isinstance(condition, And): compute_later, state2cond, conds = [], dict(), condition.args for expr in conds: if isinstance(expr, Relational): ris = list(expr.atoms(RandomIndexedSymbol))[0] if state2cond.get(ris, None) is None: state2cond[ris] = S.true state2cond[ris] &= expr else: compute_later.append(expr) ris = [] for ri in state2cond: ris.append(ri) cset = Intersection(state2cond[ri].as_set(), state_index) if len(cset) == 0: return S.Zero state2cond[ri] = cset.as_relational(ri) sorted_ris = sorted(ris, key=lambda ri: ri.key) prod = self.probability(state2cond[sorted_ris[0]], given_condition, evaluate, **kwargs) for i in range(1, len(sorted_ris)): ri, prev_ri = sorted_ris[i], sorted_ris[i-1] if not isinstance(state2cond[ri], Eq): raise ValueError("The process is in multiple states at %s, unable to determine the probability."%(ri)) mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat) prod *= self.probability(state2cond[ri], state2cond[prev_ri] & mat_of & StochasticStateSpaceOf(self, state_index), evaluate, **kwargs) for expr in compute_later: prod *= self.probability(expr, given_condition, evaluate, **kwargs) return prod if isinstance(condition, Or): return sum([self.probability(expr, given_condition, evaluate, **kwargs) for expr in condition.args]) raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been " "implemented yet."%(condition, given_condition)) def _symbolic_probability(self, condition, new_given_condition, rv, min_key_rv): #Function to calculate probability for queries with symbols if isinstance(condition, Relational): curr_state = new_given_condition.rhs if isinstance(new_given_condition.lhs, RandomIndexedSymbol) \ else new_given_condition.lhs next_state = condition.rhs if isinstance(condition.lhs, RandomIndexedSymbol) \ else condition.lhs if isinstance(condition, Eq) or isinstance(condition, Ne): if isinstance(self, DiscreteMarkovChain): P = self.transition_probabilities**(rv[0].key - min_key_rv.key) else: P = exp(self.generator_matrix*(rv[0].key - min_key_rv.key)) prob = P[curr_state, next_state] if isinstance(condition, Eq) else 1 - P[curr_state, next_state] return Piecewise((prob, rv[0].key > min_key_rv.key), (Probability(condition), True)) else: upper = 1 greater = False if isinstance(condition, Ge) or isinstance(condition, Lt): upper = 0 if isinstance(condition, Gt) or isinstance(condition, Ge): greater = True k = Dummy('k') condition = Eq(condition.lhs, k) if isinstance(condition.lhs, RandomIndexedSymbol)\ else Eq(condition.rhs, k) total = Sum(self.probability(condition, new_given_condition), (k, next_state + upper, self.state_space._sup)) return Piecewise((total, rv[0].key > min_key_rv.key), (Probability(condition), True)) if greater\ else Piecewise((1 - total, rv[0].key > min_key_rv.key), (Probability(condition), True)) else: return Probability(condition, new_given_condition) def expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Handles expectation queries for markov process. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. Returns ======= Expectation Unevaluated object if computations cannot be done due to insufficient information. Expr In all other cases when the computations are successful. Note ==== Any information passed at the time of query overrides any information passed at the time of object creation like transition probabilities, state space. Pass the transition matrix using TransitionMatrixOf, generator matrix using GeneratorMatrixOf and state space using StochasticStateSpaceOf in given_condition using & or And. """ check, mat, state_index, condition = \ self._preprocess(condition, evaluate) if check: return Expectation(expr, condition) rvs = random_symbols(expr) if isinstance(expr, Expr) and isinstance(condition, Eq) \ and len(rvs) == 1: # handle queries similar to E(f(X[i]), Eq(X[i-m], <some-state>)) condition=self.replace_with_index(condition) state_index=self.replace_with_index(state_index) rv = list(rvs)[0] lhsg, rhsg = condition.lhs, condition.rhs if not isinstance(lhsg, RandomIndexedSymbol): lhsg, rhsg = (rhsg, lhsg) if rhsg not in state_index: raise ValueError("%s state is not in the state space."%(rhsg)) if rv.key < lhsg.key: raise ValueError("Incorrect given condition is given, expectation " "time %s < time %s"%(rv.key, rv.key)) mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat) cond = condition & mat_of & \ StochasticStateSpaceOf(self, state_index) func = lambda s: self.probability(Eq(rv, s), cond) * expr.subs(rv, self._state_index[s]) return sum([func(s) for s in state_index]) raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been " "implemented yet."%(expr, condition)) class DiscreteMarkovChain(DiscreteTimeStochasticProcess, MarkovProcess): """ Represents a finite discrete time-homogeneous Markov chain. This type of Markov Chain can be uniquely characterised by its (ordered) state space and its one-step transition probability matrix. Parameters ========== sym: The name given to the Markov Chain state_space: Optional, by default, Range(n) trans_probs: Optional, by default, MatrixSymbol('_T', n, n) Examples ======== >>> from sympy.stats import DiscreteMarkovChain, TransitionMatrixOf, P, E >>> from sympy import Matrix, MatrixSymbol, Eq, symbols >>> 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) >>> YS = DiscreteMarkovChain("Y") >>> Y.state_space FiniteSet(0, 1, 2) >>> Y.transition_probabilities Matrix([ [0.5, 0.2, 0.3], [0.2, 0.5, 0.3], [0.2, 0.3, 0.5]]) >>> TS = MatrixSymbol('T', 3, 3) >>> P(Eq(YS[3], 2), Eq(YS[1], 1) & TransitionMatrixOf(YS, TS)) T[0, 2]*T[1, 0] + T[1, 1]*T[1, 2] + T[1, 2]*T[2, 2] >>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2) 0.36 Probabilities will be calculated based on indexes rather than state names. For example, with the Sunny-Cloudy-Rainy model with string state names: >>> from sympy.core.symbol import Str >>> Y = DiscreteMarkovChain("Y", [Str('Sunny'), Str('Cloudy'), Str('Rainy')], T) >>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2) 0.36 This gives the same answer as the ``[0, 1, 2]`` state space. Currently, there is no support for state names within probability and expectation statements. Here is a work-around using ``Str``: >>> P(Eq(Str('Rainy'), Y[3]), Eq(Y[1], Str('Cloudy'))).round(2) 0.36 Symbol state names can also be used: >>> sunny, cloudy, rainy = symbols('Sunny, Cloudy, Rainy') >>> Y = DiscreteMarkovChain("Y", [sunny, cloudy, rainy], T) >>> P(Eq(Y[3], rainy), Eq(Y[1], cloudy)).round(2) 0.36 Expectations will be calculated as follows: >>> E(Y[3], Eq(Y[1], cloudy)) 0.38*Cloudy + 0.36*Rainy + 0.26*Sunny Probability of expressions with multiple RandomIndexedSymbols can also be calculated provided there is only 1 RandomIndexedSymbol in the given condition. It is always better to use Rational instead of floating point numbers for the probabilities in the transition matrix to avoid errors. >>> from sympy import Gt, Le, Rational >>> T = Matrix([[Rational(5, 10), Rational(3, 10), Rational(2, 10)], [Rational(2, 10), Rational(7, 10), Rational(1, 10)], [Rational(3, 10), Rational(3, 10), Rational(4, 10)]]) >>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T) >>> P(Eq(Y[3], Y[1]), Eq(Y[0], 0)).round(3) 0.409 >>> P(Gt(Y[3], Y[1]), Eq(Y[0], 0)).round(2) 0.36 >>> P(Le(Y[15], Y[10]), Eq(Y[8], 2)).round(7) 0.6963328 Symbolic probability queries are also supported >>> from sympy import symbols, Matrix, Rational, Eq, Gt >>> from sympy.stats import P, DiscreteMarkovChain >>> a, b, c, d = symbols('a b c d') >>> T = Matrix([[Rational(1, 10), Rational(4, 10), Rational(5, 10)], [Rational(3, 10), Rational(4, 10), Rational(3, 10)], [Rational(7, 10), Rational(2, 10), Rational(1, 10)]]) >>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T) >>> query = P(Eq(Y[a], b), Eq(Y[c], d)) >>> query.subs({a:10 ,b:2, c:5, d:1}).round(4) 0.3096 >>> P(Eq(Y[10], 2), Eq(Y[5], 1)).evalf().round(4) 0.3096 >>> query_gt = P(Gt(Y[a], b), Eq(Y[c], d)) >>> query_gt.subs({a:21, b:0, c:5, d:0}).evalf().round(5) 0.64705 >>> P(Gt(Y[21], 0), Eq(Y[5], 0)).round(5) 0.64705 There is limited support for arbitrarily sized states: >>> n = symbols('n', nonnegative=True, integer=True) >>> T = MatrixSymbol('T', n, n) >>> Y = DiscreteMarkovChain("Y", trans_probs=T) >>> Y.state_space Range(0, n, 1) >>> query = P(Eq(Y[a], b), Eq(Y[c], d)) >>> query.subs({a:10, b:2, c:5, d:1}) (T**5)[1, 2] References ========== .. [1] https://en.wikipedia.org/wiki/Markov_chain#Discrete-time_Markov_chain .. [2] https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf """ index_set = S.Naturals0 def __new__(cls, sym, state_space=None, trans_probs=None): # type: (Basic, tUnion[str, Symbol], tSequence, tUnion[MatrixBase, MatrixSymbol]) -> DiscreteMarkovChain sym = _symbol_converter(sym) state_space, trans_probs = MarkovProcess._sanity_checks(state_space, trans_probs) obj = Basic.__new__(cls, sym, state_space, trans_probs) indices = dict() if isinstance(obj.number_of_states, Integer): for index, state in enumerate(obj._state_index): indices[state] = index obj.index_of = indices return obj @property def transition_probabilities(self) -> tUnion[MatrixBase, MatrixSymbol]: """ Transition probabilities of discrete Markov chain, either an instance of Matrix or MatrixSymbol. """ return self.args[2] def communication_classes(self) -> tList[tTuple[tList[Basic], Boolean, Integer]]: """ Returns the list of communication classes that partition the states of the markov chain. A communication class is defined to be a set of states such that every state in that set is reachable from every other state in that set. Due to its properties this forms a class in the mathematical sense. Communication classes are also known as recurrence classes. Returns ======= classes The ``classes`` are a list of tuples. Each tuple represents a single communication class with its properties. The first element in the tuple is the list of states in the class, the second element is whether the class is recurrent and the third element is the period of the communication class. Examples ======== >>> from sympy.stats import DiscreteMarkovChain >>> from sympy import Matrix >>> T = Matrix([[0, 1, 0], ... [1, 0, 0], ... [1, 0, 0]]) >>> X = DiscreteMarkovChain('X', [1, 2, 3], T) >>> classes = X.communication_classes() >>> for states, is_recurrent, period in classes: ... states, is_recurrent, period ([1, 2], True, 2) ([3], False, 1) From this we can see that states ``1`` and ``2`` communicate, are recurrent and have a period of 2. We can also see state ``3`` is transient with a period of 1. Notes ===== The algorithm used is of order ``O(n**2)`` where ``n`` is the number of states in the markov chain. It uses Tarjan's algorithm to find the classes themselves and then it uses a breadth-first search algorithm to find each class's periodicity. Most of the algorithm's components approach ``O(n)`` as the matrix becomes more and more sparse. References ========== .. [1] http://www.columbia.edu/~ww2040/4701Sum07/4701-06-Notes-MCII.pdf .. [2] http://cecas.clemson.edu/~shierd/Shier/markov.pdf .. [3] https://ujcontent.uj.ac.za/vital/access/services/Download/uj:7506/CONTENT1 .. [4] https://www.mathworks.com/help/econ/dtmc.classify.html """ n = self.number_of_states T = self.transition_probabilities if isinstance(T, MatrixSymbol): raise NotImplementedError("Cannot perform the operation with a symbolic matrix.") # begin Tarjan's algorithm V = Range(n) # don't use state names. Rather use state # indexes since we use them for matrix # indexing here and later onward E = [(i, j) for i in V for j in V if T[i, j] != 0] classes = strongly_connected_components((V, E)) # end Tarjan's algorithm recurrence = [] periods = [] for class_ in classes: # begin recurrent check (similar to self._check_trans_probs()) submatrix = T[class_, class_] # get the submatrix with those states is_recurrent = S.true rows = submatrix.tolist() for row in rows: if (sum(row) - 1) != 0: is_recurrent = S.false break recurrence.append(is_recurrent) # end recurrent check # begin breadth-first search non_tree_edge_values = set() visited = {class_[0]} newly_visited = {class_[0]} level = {class_[0]: 0} current_level = 0 done = False # imitate a do-while loop while not done: # runs at most len(class_) times done = len(visited) == len(class_) current_level += 1 # this loop and the while loop above run a combined len(class_) number of times. # so this triple nested loop runs through each of the n states once. for i in newly_visited: # the loop below runs len(class_) number of times # complexity is around about O(n * avg(len(class_))) newly_visited = {j for j in class_ if T[i, j] != 0} new_tree_edges = newly_visited.difference(visited) for j in new_tree_edges: level[j] = current_level new_non_tree_edges = newly_visited.intersection(visited) new_non_tree_edge_values = {level[i]-level[j]+1 for j in new_non_tree_edges} non_tree_edge_values = non_tree_edge_values.union(new_non_tree_edge_values) visited = visited.union(new_tree_edges) # igcd needs at least 2 arguments positive_ntev = {val_e for val_e in non_tree_edge_values if val_e > 0} if len(positive_ntev) == 0: periods.append(len(class_)) elif len(positive_ntev) == 1: periods.append(positive_ntev.pop()) else: periods.append(igcd(*positive_ntev)) # end breadth-first search # convert back to the user's state names classes = [[self._state_index[i] for i in class_] for class_ in classes] return sympify(list(zip(classes, recurrence, periods))) def fundamental_matrix(self): """ Each entry fundamental matrix can be interpreted as the expected number of times the chains is in state j if it started in state i. References ========== .. [1] https://lips.cs.princeton.edu/the-fundamental-matrix-of-a-finite-markov-chain/ """ _, _, _, Q = self.decompose() if Q.shape[0] > 0: # if non-ergodic I = eye(Q.shape[0]) if (I - Q).det() == 0: raise ValueError("The fundamental matrix doesn't exist.") return (I - Q).inv().as_immutable() else: # if ergodic P = self.transition_probabilities I = eye(P.shape[0]) w = self.fixed_row_vector() W = Matrix([list(w) for i in range(0, P.shape[0])]) if (I - P + W).det() == 0: raise ValueError("The fundamental matrix doesn't exist.") return (I - P + W).inv().as_immutable() def absorbing_probabilities(self): """ Computes the absorbing probabilities, i.e., the ij-th entry of the matrix denotes the probability of Markov chain being absorbed in state j starting from state i. """ _, _, R, _ = self.decompose() N = self.fundamental_matrix() if R is None or N is None: return None return N*R def absorbing_probabilites(self): SymPyDeprecationWarning( feature="absorbing_probabilites", useinstead="absorbing_probabilities", issue=20042, deprecated_since_version="1.7" ).warn() return self.absorbing_probabilities() def is_regular(self): tuples = self.communication_classes() if len(tuples) == 0: return S.false # not defined for a 0x0 matrix classes, _, periods = list(zip(*tuples)) return And(len(classes) == 1, periods[0] == 1) def is_ergodic(self): tuples = self.communication_classes() if len(tuples) == 0: return S.false # not defined for a 0x0 matrix classes, _, _ = list(zip(*tuples)) return S(len(classes) == 1) def is_absorbing_state(self, state): trans_probs = self.transition_probabilities if isinstance(trans_probs, ImmutableMatrix) and \ state < trans_probs.shape[0]: return S(trans_probs[state, state]) is S.One def is_absorbing_chain(self): states, A, B, C = self.decompose() r = A.shape[0] return And(r > 0, A == Identity(r).as_explicit()) def stationary_distribution(self, condition_set=False) -> tUnion[ImmutableMatrix, ConditionSet, Lambda]: """ The stationary distribution is any row vector, p, that solves p = pP, is row stochastic and each element in p must be nonnegative. That means in matrix form: :math:`(P-I)^T p^T = 0` and :math:`(1, ..., 1) p = 1` where ``P`` is the one-step transition matrix. All time-homogeneous Markov Chains with a finite state space have at least one stationary distribution. In addition, if a finite time-homogeneous Markov Chain is irreducible, the stationary distribution is unique. Parameters ========== condition_set : bool If the chain has a symbolic size or transition matrix, it will return a ``Lambda`` if ``False`` and return a ``ConditionSet`` if ``True``. Examples ======== >>> from sympy.stats import DiscreteMarkovChain >>> from sympy import Matrix, S An irreducible Markov Chain >>> T = Matrix([[S(1)/2, S(1)/2, 0], ... [S(4)/5, S(1)/5, 0], ... [1, 0, 0]]) >>> X = DiscreteMarkovChain('X', trans_probs=T) >>> X.stationary_distribution() Matrix([[8/13, 5/13, 0]]) A reducible Markov Chain >>> T = Matrix([[S(1)/2, S(1)/2, 0], ... [S(4)/5, S(1)/5, 0], ... [0, 0, 1]]) >>> X = DiscreteMarkovChain('X', trans_probs=T) >>> X.stationary_distribution() Matrix([[8/13 - 8*tau0/13, 5/13 - 5*tau0/13, tau0]]) >>> Y = DiscreteMarkovChain('Y') >>> Y.stationary_distribution() Lambda((wm, _T), Eq(wm*_T, wm)) >>> Y.stationary_distribution(condition_set=True) ConditionSet(wm, Eq(wm*_T, wm)) References ========== .. [1] https://www.probabilitycourse.com/chapter11/11_2_6_stationary_and_limiting_distributions.php .. [2] https://galton.uchicago.edu/~yibi/teaching/stat317/2014/Lectures/Lecture4_6up.pdf See Also ======== sympy.stats.stochastic_process_types.DiscreteMarkovChain.limiting_distribution """ trans_probs = self.transition_probabilities n = self.number_of_states if n == 0: return ImmutableMatrix(Matrix([[]])) # symbolic matrix version if isinstance(trans_probs, MatrixSymbol): wm = MatrixSymbol('wm', 1, n) if condition_set: return ConditionSet(wm, Eq(wm * trans_probs, wm)) else: return Lambda((wm, trans_probs), Eq(wm * trans_probs, wm)) # numeric matrix version a = Matrix(trans_probs - Identity(n)).T a[0, 0:n] = ones(1, n) b = zeros(n, 1) b[0, 0] = 1 soln = list(linsolve((a, b)))[0] return ImmutableMatrix([[sol for sol in soln]]) def fixed_row_vector(self): """ A wrapper for ``stationary_distribution()``. """ return self.stationary_distribution() @property def limiting_distribution(self): """ The fixed row vector is the limiting distribution of a discrete Markov chain. """ return self.fixed_row_vector() def decompose(self) -> tTuple[tList[Basic], ImmutableMatrix, ImmutableMatrix, ImmutableMatrix]: """ Decomposes the transition matrix into submatrices with special properties. The transition matrix can be decomposed into 4 submatrices: - A - the submatrix from recurrent states to recurrent states. - B - the submatrix from transient to recurrent states. - C - the submatrix from transient to transient states. - O - the submatrix of zeros for recurrent to transient states. Returns ======= states, A, B, C ``states`` - a list of state names with the first being the recurrent states and the last being the transient states in the order of the row names of A and then the row names of C. ``A`` - the submatrix from recurrent states to recurrent states. ``B`` - the submatrix from transient to recurrent states. ``C`` - the submatrix from transient to transient states. Examples ======== >>> from sympy.stats import DiscreteMarkovChain >>> from sympy import Matrix, S One can decompose this chain for example: >>> T = Matrix([[S(1)/2, S(1)/2, 0, 0, 0], ... [S(2)/5, S(1)/5, S(2)/5, 0, 0], ... [0, 0, 1, 0, 0], ... [0, 0, S(1)/2, S(1)/2, 0], ... [S(1)/2, 0, 0, 0, S(1)/2]]) >>> X = DiscreteMarkovChain('X', trans_probs=T) >>> states, A, B, C = X.decompose() >>> states [2, 0, 1, 3, 4] >>> A # recurrent to recurrent Matrix([[1]]) >>> B # transient to recurrent Matrix([ [ 0], [2/5], [1/2], [ 0]]) >>> C # transient to transient Matrix([ [1/2, 1/2, 0, 0], [2/5, 1/5, 0, 0], [ 0, 0, 1/2, 0], [1/2, 0, 0, 1/2]]) This means that state 2 is the only absorbing state (since A is a 1x1 matrix). B is a 4x1 matrix since the 4 remaining transient states all merge into reccurent state 2. And C is the 4x4 matrix that shows how the transient states 0, 1, 3, 4 all interact. See Also ======== sympy.stats.stochastic_process_types.DiscreteMarkovChain.communication_classes sympy.stats.stochastic_process_types.DiscreteMarkovChain.canonical_form References ========== .. [1] https://en.wikipedia.org/wiki/Absorbing_Markov_chain .. [2] http://people.brandeis.edu/~igusa/Math56aS08/Math56a_S08_notes015.pdf """ trans_probs = self.transition_probabilities classes = self.communication_classes() r_states = [] t_states = [] for states, recurrent, period in classes: if recurrent: r_states += states else: t_states += states states = r_states + t_states indexes = [self.index_of[state] for state in states] A = Matrix(len(r_states), len(r_states), lambda i, j: trans_probs[indexes[i], indexes[j]]) B = Matrix(len(t_states), len(r_states), lambda i, j: trans_probs[indexes[len(r_states) + i], indexes[j]]) C = Matrix(len(t_states), len(t_states), lambda i, j: trans_probs[indexes[len(r_states) + i], indexes[len(r_states) + j]]) return states, A.as_immutable(), B.as_immutable(), C.as_immutable() def canonical_form(self) -> tTuple[tList[Basic], ImmutableMatrix]: """ Reorders the one-step transition matrix so that recurrent states appear first and transient states appear last. Other representations include inserting transient states first and recurrent states last. Returns ======= states, P_new ``states`` is the list that describes the order of the new states in the matrix so that the ith element in ``states`` is the state of the ith row of A. ``P_new`` is the new transition matrix in canonical form. Examples ======== >>> from sympy.stats import DiscreteMarkovChain >>> from sympy import Matrix, S You can convert your chain into canonical form: >>> T = Matrix([[S(1)/2, S(1)/2, 0, 0, 0], ... [S(2)/5, S(1)/5, S(2)/5, 0, 0], ... [0, 0, 1, 0, 0], ... [0, 0, S(1)/2, S(1)/2, 0], ... [S(1)/2, 0, 0, 0, S(1)/2]]) >>> X = DiscreteMarkovChain('X', list(range(1, 6)), trans_probs=T) >>> states, new_matrix = X.canonical_form() >>> states [3, 1, 2, 4, 5] >>> new_matrix Matrix([ [ 1, 0, 0, 0, 0], [ 0, 1/2, 1/2, 0, 0], [2/5, 2/5, 1/5, 0, 0], [1/2, 0, 0, 1/2, 0], [ 0, 1/2, 0, 0, 1/2]]) The new states are [3, 1, 2, 4, 5] and you can create a new chain with this and its canonical form will remain the same (since it is already in canonical form). >>> X = DiscreteMarkovChain('X', states, new_matrix) >>> states, new_matrix = X.canonical_form() >>> states [3, 1, 2, 4, 5] >>> new_matrix Matrix([ [ 1, 0, 0, 0, 0], [ 0, 1/2, 1/2, 0, 0], [2/5, 2/5, 1/5, 0, 0], [1/2, 0, 0, 1/2, 0], [ 0, 1/2, 0, 0, 1/2]]) This is not limited to absorbing chains: >>> T = Matrix([[0, 5, 5, 0, 0], ... [0, 0, 0, 10, 0], ... [5, 0, 5, 0, 0], ... [0, 10, 0, 0, 0], ... [0, 3, 0, 3, 4]])/10 >>> X = DiscreteMarkovChain('X', trans_probs=T) >>> states, new_matrix = X.canonical_form() >>> states [1, 3, 0, 2, 4] >>> new_matrix Matrix([ [ 0, 1, 0, 0, 0], [ 1, 0, 0, 0, 0], [ 1/2, 0, 0, 1/2, 0], [ 0, 0, 1/2, 1/2, 0], [3/10, 3/10, 0, 0, 2/5]]) See Also ======== sympy.stats.stochastic_process_types.DiscreteMarkovChain.communication_classes sympy.stats.stochastic_process_types.DiscreteMarkovChain.decompose References ========== .. [1] https://onlinelibrary.wiley.com/doi/pdf/10.1002/9780470316887.app1 .. [2] http://www.columbia.edu/~ww2040/6711F12/lect1023big.pdf """ states, A, B, C = self.decompose() O = zeros(A.shape[0], C.shape[1]) return states, BlockMatrix([[A, O], [B, C]]).as_explicit() def sample(self): """ Returns ======= sample: iterator object iterator object containing the sample """ if not isinstance(self.transition_probabilities, (Matrix, ImmutableMatrix)): raise ValueError("Transition Matrix must be provided for sampling") Tlist = self.transition_probabilities.tolist() samps = [random.choice(list(self.state_space))] yield samps[0] time = 1 densities = {} for state in self.state_space: states = list(self.state_space) densities[state] = {states[i]: Tlist[state][i] for i in range(len(states))} while time < S.Infinity: samps.append((next(sample_iter(FiniteRV("_", densities[samps[time - 1]]))))) yield samps[time] time += 1 class ContinuousMarkovChain(ContinuousTimeStochasticProcess, MarkovProcess): """ Represents continuous time Markov chain. Parameters ========== sym: Symbol/str state_space: Set Optional, by default, S.Reals gen_mat: Matrix/ImmutableMatrix/MatrixSymbol Optional, by default, None Examples ======== >>> from sympy.stats import ContinuousMarkovChain, P >>> from sympy import Matrix, S, Eq, Gt >>> G = Matrix([[-S(1), S(1)], [S(1), -S(1)]]) >>> C = ContinuousMarkovChain('C', state_space=[0, 1], gen_mat=G) >>> C.limiting_distribution() Matrix([[1/2, 1/2]]) >>> C.state_space FiniteSet(0, 1) >>> C.generator_matrix Matrix([ [-1, 1], [ 1, -1]]) Probability queries are supported >>> P(Eq(C(1.96), 0), Eq(C(0.78), 1)).round(5) 0.45279 >>> P(Gt(C(1.7), 0), Eq(C(0.82), 1)).round(5) 0.58602 Probability of expressions with multiple RandomIndexedSymbols can also be calculated provided there is only 1 RandomIndexedSymbol in the given condition. It is always better to use Rational instead of floating point numbers for the probabilities in the generator matrix to avoid errors. >>> from sympy import Gt, Le, Rational >>> G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]]) >>> C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G) >>> P(Eq(C(3.92), C(1.75)), Eq(C(0.46), 0)).round(5) 0.37933 >>> P(Gt(C(3.92), C(1.75)), Eq(C(0.46), 0)).round(5) 0.34211 >>> P(Le(C(1.57), C(3.14)), Eq(C(1.22), 1)).round(4) 0.7143 Symbolic probability queries are also supported >>> from sympy import S, symbols, Matrix, Rational, Eq, Gt >>> from sympy.stats import P, ContinuousMarkovChain >>> a,b,c,d = symbols('a b c d') >>> G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]]) >>> C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G) >>> query = P(Eq(C(a), b), Eq(C(c), d)) >>> query.subs({a:3.65 ,b:2, c:1.78, d:1}).evalf().round(10) 0.4002723175 >>> P(Eq(C(3.65), 2), Eq(C(1.78), 1)).round(10) 0.4002723175 >>> query_gt = P(Gt(C(a), b), Eq(C(c), d)) >>> query_gt.subs({a:43.2 ,b:0, c:3.29, d:2}).evalf().round(10) 0.6832579186 >>> P(Gt(C(43.2), 0), Eq(C(3.29), 2)).round(10) 0.6832579186 References ========== .. [1] https://en.wikipedia.org/wiki/Markov_chain#Continuous-time_Markov_chain .. [2] http://u.math.biu.ac.il/~amirgi/CTMCnotes.pdf """ index_set = S.Reals def __new__(cls, sym, state_space=None, gen_mat=None): sym = _symbol_converter(sym) state_space, gen_mat = MarkovProcess._sanity_checks(state_space, gen_mat) obj = Basic.__new__(cls, sym, state_space, gen_mat) indices = dict() if isinstance(obj.number_of_states, Integer): for index, state in enumerate(obj.state_space): indices[state] = index obj.index_of = indices return obj @property def generator_matrix(self): return self.args[2] @cacheit def transition_probabilities(self, gen_mat=None): t = Dummy('t') if isinstance(gen_mat, (Matrix, ImmutableMatrix)) and \ gen_mat.is_diagonalizable(): # for faster computation use diagonalized generator matrix Q, D = gen_mat.diagonalize() return Lambda(t, Q*exp(t*D)*Q.inv()) if gen_mat != None: return Lambda(t, exp(t*gen_mat)) def limiting_distribution(self): gen_mat = self.generator_matrix if gen_mat == None: return None if isinstance(gen_mat, MatrixSymbol): wm = MatrixSymbol('wm', 1, gen_mat.shape[0]) return Lambda((wm, gen_mat), Eq(wm*gen_mat, wm)) w = IndexedBase('w') wi = [w[i] for i in range(gen_mat.shape[0])] wm = Matrix([wi]) eqs = (wm*gen_mat).tolist()[0] eqs.append(sum(wi) - 1) soln = list(linsolve(eqs, wi))[0] return ImmutableMatrix([[sol for sol in soln]]) class BernoulliProcess(DiscreteTimeStochasticProcess): """ The Bernoulli process consists of repeated independent Bernoulli process trials with the same parameter `p`. It's assumed that the probability `p` applies to every trial and that the outcomes of each trial are independent of all the rest. Therefore Bernoulli Processs is Discrete State and Discrete Time Stochastic Process. Parameters ========== sym: Symbol/str success: Integer/str The event which is considered to be success, by default is 1. failure: Integer/str The event which is considered to be failure, by default is 0. p: Real Number between 0 and 1 Represents the probability of getting success. Examples ======== >>> from sympy.stats import BernoulliProcess, P, E >>> from sympy import Eq, Gt >>> B = BernoulliProcess("B", p=0.7, success=1, failure=0) >>> B.state_space FiniteSet(0, 1) >>> (B.p).round(2) 0.70 >>> B.success 1 >>> B.failure 0 >>> X = B[1] + B[2] + B[3] >>> P(Eq(X, 0)).round(2) 0.03 >>> P(Eq(X, 2)).round(2) 0.44 >>> P(Eq(X, 4)).round(2) 0 >>> P(Gt(X, 1)).round(2) 0.78 >>> P(Eq(B[1], 0) & Eq(B[2], 1) & Eq(B[3], 0) & Eq(B[4], 1)).round(2) 0.04 >>> B.joint_distribution(B[1], B[2]) JointDistributionHandmade(Lambda((B[1], B[2]), Piecewise((0.7, Eq(B[1], 1)), (0.3, Eq(B[1], 0)), (0, True))*Piecewise((0.7, Eq(B[2], 1)), (0.3, Eq(B[2], 0)), (0, True)))) >>> E(2*B[1] + B[2]).round(2) 2.10 >>> P(B[1] < 1).round(2) 0.30 References ========== .. [1] https://en.wikipedia.org/wiki/Bernoulli_process .. [2] https://mathcs.clarku.edu/~djoyce/ma217/bernoulli.pdf """ index_set = S.Naturals0 def __new__(cls, sym, p, success=1, failure=0): _value_check(p >= 0 and p <= 1, 'Value of p must be between 0 and 1.') sym = _symbol_converter(sym) p = _sympify(p) success = _sym_sympify(success) failure = _sym_sympify(failure) return Basic.__new__(cls, sym, p, success, failure) @property def symbol(self): return self.args[0] @property def p(self): return self.args[1] @property def success(self): return self.args[2] @property def failure(self): return self.args[3] @property def state_space(self): return _set_converter([self.success, self.failure]) def distribution(self, key=None): if key is None: self._deprecation_warn_distribution() return BernoulliDistribution(self.p) return BernoulliDistribution(self.p, self.success, self.failure) def simple_rv(self, rv): return Bernoulli(rv.name, p=self.p, succ=self.success, fail=self.failure) def expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Computes expectation. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. Returns ======= Expectation of the RandomIndexedSymbol. """ return _SubstituteRV._expectation(expr, condition, evaluate, **kwargs) def probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Computes probability. Parameters ========== condition: Relational Condition for which probability has to be computed. Must contain a RandomIndexedSymbol of the process. given_condition: Relational/And The given conditions under which computations should be done. Returns ======= Probability of the condition. """ return _SubstituteRV._probability(condition, given_condition, evaluate, **kwargs) def density(self, x): return Piecewise((self.p, Eq(x, self.success)), (1 - self.p, Eq(x, self.failure)), (S.Zero, True)) class _SubstituteRV: """ Internal class to handle the queries of expectation and probability by substitution. """ @staticmethod def _rvindexed_subs(expr, condition=None): """ Substitutes the RandomIndexedSymbol with the RandomSymbol with same name, distribution and probability as RandomIndexedSymbol. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. """ rvs_expr = random_symbols(expr) if len(rvs_expr) != 0: swapdict_expr = {} for rv in rvs_expr: if isinstance(rv, RandomIndexedSymbol): newrv = rv.pspace.process.simple_rv(rv) # substitute with equivalent simple rv swapdict_expr[rv] = newrv expr = expr.subs(swapdict_expr) rvs_cond = random_symbols(condition) if len(rvs_cond)!=0: swapdict_cond = {} for rv in rvs_cond: if isinstance(rv, RandomIndexedSymbol): newrv = rv.pspace.process.simple_rv(rv) swapdict_cond[rv] = newrv condition = condition.subs(swapdict_cond) return expr, condition @classmethod def _expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Internal method for computing expectation of indexed RV. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. Returns ======= Expectation of the RandomIndexedSymbol. """ new_expr, new_condition = self._rvindexed_subs(expr, condition) if not is_random(new_expr): return new_expr new_pspace = pspace(new_expr) if new_condition is not None: new_expr = given(new_expr, new_condition) if new_expr.is_Add: # As E is Linear return Add(*[new_pspace.compute_expectation( expr=arg, evaluate=evaluate, **kwargs) for arg in new_expr.args]) return new_pspace.compute_expectation( new_expr, evaluate=evaluate, **kwargs) @classmethod def _probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Internal method for computing probability of indexed RV Parameters ========== condition: Relational Condition for which probability has to be computed. Must contain a RandomIndexedSymbol of the process. given_condition: Relational/And The given conditions under which computations should be done. Returns ======= Probability of the condition. """ new_condition, new_givencondition = self._rvindexed_subs(condition, given_condition) if isinstance(new_givencondition, RandomSymbol): condrv = random_symbols(new_condition) if len(condrv) == 1 and condrv[0] == new_givencondition: return BernoulliDistribution(self._probability(new_condition), 0, 1) if any([dependent(rv, new_givencondition) for rv in condrv]): return Probability(new_condition, new_givencondition) else: return self._probability(new_condition) if new_givencondition is not None and \ not isinstance(new_givencondition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (new_givencondition)) if new_givencondition == False or new_condition == False: return S.Zero if new_condition == True: return S.One if not isinstance(new_condition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (new_condition)) if new_givencondition is not None: # If there is a condition # Recompute on new conditional expr return self._probability(given(new_condition, new_givencondition, **kwargs), **kwargs) result = pspace(new_condition).probability(new_condition, **kwargs) if evaluate and hasattr(result, 'doit'): return result.doit() else: return result def get_timerv_swaps(expr, condition): """ Finds the appropriate interval for each time stamp in expr by parsing the given condition and returns intervals for each timestamp and dictionary that maps variable time-stamped Random Indexed Symbol to its corresponding Random Indexed variable with fixed time stamp. Parameters ========== expr: Sympy Expression Expression containing Random Indexed Symbols with variable time stamps condition: Relational/Boolean Expression Expression containing time bounds of variable time stamps in expr Examples ======== >>> from sympy.stats.stochastic_process_types import get_timerv_swaps, PoissonProcess >>> from sympy import symbols, Contains, Interval >>> x, t, d = symbols('x t d', positive=True) >>> X = PoissonProcess("X", 3) >>> get_timerv_swaps(x*X(t), Contains(t, Interval.Lopen(0, 1))) ([Interval.Lopen(0, 1)], {X(t): X(1)}) >>> get_timerv_swaps((X(t)**2 + X(d)**2), Contains(t, Interval.Lopen(0, 1)) ... & Contains(d, Interval.Ropen(1, 4))) # doctest: +SKIP ([Interval.Ropen(1, 4), Interval.Lopen(0, 1)], {X(d): X(3), X(t): X(1)}) Returns ======= intervals: list List of Intervals/FiniteSet on which each time stamp is defined rv_swap: dict Dictionary mapping variable time Random Indexed Symbol to constant time Random Indexed Variable """ if not isinstance(condition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (condition)) expr_syms = list(expr.atoms(RandomIndexedSymbol)) if isinstance(condition, (And, Or)): given_cond_args = condition.args else: # single condition given_cond_args = (condition, ) rv_swap = {} intervals = [] for expr_sym in expr_syms: for arg in given_cond_args: if arg.has(expr_sym.key) and isinstance(expr_sym.key, Symbol): intv = _set_converter(arg.args[1]) diff_key = intv._sup - intv._inf if diff_key == oo: raise ValueError("%s should have finite bounds" % str(expr_sym.name)) elif diff_key == S.Zero: # has singleton set diff_key = intv._sup rv_swap[expr_sym] = expr_sym.subs({expr_sym.key: diff_key}) intervals.append(intv) return intervals, rv_swap class CountingProcess(ContinuousTimeStochasticProcess): """ This class handles the common methods of the Counting Processes such as Poisson, Wiener and Gamma Processes """ index_set = _set_converter(Interval(0, oo)) @property def symbol(self): return self.args[0] def expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Computes expectation Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Boolean The given conditions under which computations should be done, i.e, the intervals on which each variable time stamp in expr is defined Returns ======= Expectation of the given expr """ if condition is not None: intervals, rv_swap = get_timerv_swaps(expr, condition) # they are independent when they have non-overlapping intervals if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet for intv_comb in itertools.combinations(intervals, 2)): if expr.is_Add: return Add.fromiter(self.expectation(arg, condition) for arg in expr.args) expr = expr.subs(rv_swap) else: return Expectation(expr, condition) return _SubstituteRV._expectation(expr, evaluate=evaluate, **kwargs) def _solve_argwith_tworvs(self, arg): if arg.args[0].key >= arg.args[1].key or isinstance(arg, Eq): diff_key = abs(arg.args[0].key - arg.args[1].key) rv = arg.args[0] arg = arg.__class__(rv.pspace.process(diff_key), 0) else: diff_key = arg.args[1].key - arg.args[0].key rv = arg.args[1] arg = arg.__class__(rv.pspace.process(diff_key), 0) return arg def _solve_numerical(self, condition, given_condition=None): if isinstance(condition, And): args_list = list(condition.args) else: args_list = [condition] if given_condition is not None: if isinstance(given_condition, And): args_list.extend(list(given_condition.args)) else: args_list.extend([given_condition]) # sort the args based on timestamp to get the independent increments in # each segment using all the condition args as well as given_condition args args_list = sorted(args_list, key=lambda x: x.args[0].key) result = [] cond_args = list(condition.args) if isinstance(condition, And) else [condition] if args_list[0] in cond_args and not (is_random(args_list[0].args[0]) and is_random(args_list[0].args[1])): result.append(_SubstituteRV._probability(args_list[0])) if is_random(args_list[0].args[0]) and is_random(args_list[0].args[1]): arg = self._solve_argwith_tworvs(args_list[0]) result.append(_SubstituteRV._probability(arg)) for i in range(len(args_list) - 1): curr, nex = args_list[i], args_list[i + 1] diff_key = nex.args[0].key - curr.args[0].key working_set = curr.args[0].pspace.process.state_space if curr.args[1] > nex.args[1]: #impossible condition so return 0 result.append(0) break if isinstance(curr, Eq): working_set = Intersection(working_set, Interval.Lopen(curr.args[1], oo)) else: working_set = Intersection(working_set, curr.as_set()) if isinstance(nex, Eq): working_set = Intersection(working_set, Interval(-oo, nex.args[1])) else: working_set = Intersection(working_set, nex.as_set()) if working_set == EmptySet: rv = Eq(curr.args[0].pspace.process(diff_key), 0) result.append(_SubstituteRV._probability(rv)) else: if working_set.is_finite_set: if isinstance(curr, Eq) and isinstance(nex, Eq): rv = Eq(curr.args[0].pspace.process(diff_key), len(working_set)) result.append(_SubstituteRV._probability(rv)) elif isinstance(curr, Eq) ^ isinstance(nex, Eq): result.append(Add.fromiter(_SubstituteRV._probability(Eq( curr.args[0].pspace.process(diff_key), x)) for x in range(len(working_set)))) else: n = len(working_set) result.append(Add.fromiter((n - x)*_SubstituteRV._probability(Eq( curr.args[0].pspace.process(diff_key), x)) for x in range(n))) else: result.append(_SubstituteRV._probability( curr.args[0].pspace.process(diff_key) <= working_set._sup - working_set._inf)) return Mul.fromiter(result) def probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Computes probability Parameters ========== condition: Relational Condition for which probability has to be computed. Must contain a RandomIndexedSymbol of the process. given_condition: Relational, Boolean The given conditions under which computations should be done, i.e, the intervals on which each variable time stamp in expr is defined Returns ======= Probability of the condition """ check_numeric = True if isinstance(condition, (And, Or)): cond_args = condition.args else: cond_args = (condition, ) # check that condition args are numeric or not if not all(arg.args[0].key.is_number for arg in cond_args): check_numeric = False if given_condition is not None: check_given_numeric = True if isinstance(given_condition, (And, Or)): given_cond_args = given_condition.args else: given_cond_args = (given_condition, ) # check that given condition args are numeric or not if given_condition.has(Contains): check_given_numeric = False # Handle numerical queries if check_numeric and check_given_numeric: res = [] if isinstance(condition, Or): res.append(Add.fromiter(self._solve_numerical(arg, given_condition) for arg in condition.args)) if isinstance(given_condition, Or): res.append(Add.fromiter(self._solve_numerical(condition, arg) for arg in given_condition.args)) if res: return Add.fromiter(res) return self._solve_numerical(condition, given_condition) # No numeric queries, go by Contains?... then check that all the # given condition are in form of `Contains` if not all(arg.has(Contains) for arg in given_cond_args): raise ValueError("If given condition is passed with `Contains`, then " "please pass the evaluated condition with its corresponding information " "in terms of intervals of each time stamp to be passed in given condition.") intervals, rv_swap = get_timerv_swaps(condition, given_condition) # they are independent when they have non-overlapping intervals if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet for intv_comb in itertools.combinations(intervals, 2)): if isinstance(condition, And): return Mul.fromiter(self.probability(arg, given_condition) for arg in condition.args) elif isinstance(condition, Or): return Add.fromiter(self.probability(arg, given_condition) for arg in condition.args) condition = condition.subs(rv_swap) else: return Probability(condition, given_condition) if check_numeric: return self._solve_numerical(condition) return _SubstituteRV._probability(condition, evaluate=evaluate, **kwargs) class PoissonProcess(CountingProcess): """ The Poisson process is a counting process. It is usually used in scenarios where we are counting the occurrences of certain events that appear to happen at a certain rate, but completely at random. Parameters ========== sym: Symbol/str lamda: Positive number Rate of the process, ``lamda > 0`` Examples ======== >>> from sympy.stats import PoissonProcess, P, E >>> from sympy import symbols, Eq, Ne, Contains, Interval >>> X = PoissonProcess("X", lamda=3) >>> X.state_space Naturals0 >>> X.lamda 3 >>> t1, t2 = symbols('t1 t2', positive=True) >>> P(X(t1) < 4) (9*t1**3/2 + 9*t1**2/2 + 3*t1 + 1)*exp(-3*t1) >>> P(Eq(X(t1), 2) | Ne(X(t1), 4), Contains(t1, Interval.Ropen(2, 4))) 1 - 36*exp(-6) >>> P(Eq(X(t1), 2) & Eq(X(t2), 3), Contains(t1, Interval.Lopen(0, 2)) ... & Contains(t2, Interval.Lopen(2, 4))) 648*exp(-12) >>> E(X(t1)) 3*t1 >>> E(X(t1)**2 + 2*X(t2), Contains(t1, Interval.Lopen(0, 1)) ... & Contains(t2, Interval.Lopen(1, 2))) 18 >>> P(X(3) < 1, Eq(X(1), 0)) exp(-6) >>> P(Eq(X(4), 3), Eq(X(2), 3)) exp(-6) >>> P(X(2) <= 3, X(1) > 1) 5*exp(-3) Merging two Poisson Processes >>> Y = PoissonProcess("Y", lamda=4) >>> Z = X + Y >>> Z.lamda 7 Splitting a Poisson Process into two independent Poisson Processes >>> N, M = Z.split(l1=2, l2=5) >>> N.lamda, M.lamda (2, 5) References ========== .. [1] https://www.probabilitycourse.com/chapter11/11_0_0_intro.php .. [2] https://en.wikipedia.org/wiki/Poisson_point_process """ def __new__(cls, sym, lamda): _value_check(lamda > 0, 'lamda should be a positive number.') sym = _symbol_converter(sym) lamda = _sympify(lamda) return Basic.__new__(cls, sym, lamda) @property def lamda(self): return self.args[1] @property def state_space(self): return S.Naturals0 def distribution(self, key): if isinstance(key, RandomIndexedSymbol): self._deprecation_warn_distribution() return PoissonDistribution(self.lamda*key.key) return PoissonDistribution(self.lamda*key) def density(self, x): return (self.lamda*x.key)**x / factorial(x) * exp(-(self.lamda*x.key)) def simple_rv(self, rv): return Poisson(rv.name, lamda=self.lamda*rv.key) def __add__(self, other): if not isinstance(other, PoissonProcess): raise ValueError("Only instances of Poisson Process can be merged") return PoissonProcess(Dummy(self.symbol.name + other.symbol.name), self.lamda + other.lamda) def split(self, l1, l2): if _sympify(l1 + l2) != self.lamda: raise ValueError("Sum of l1 and l2 should be %s" % str(self.lamda)) return PoissonProcess(Dummy("l1"), l1), PoissonProcess(Dummy("l2"), l2) class WienerProcess(CountingProcess): """ The Wiener process is a real valued continuous-time stochastic process. In physics it is used to study Brownian motion and therefore also known as Brownian Motion. Parameters ========== sym: Symbol/str Examples ======== >>> from sympy.stats import WienerProcess, P, E >>> from sympy import symbols, Contains, Interval >>> X = WienerProcess("X") >>> X.state_space Reals >>> t1, t2 = symbols('t1 t2', positive=True) >>> P(X(t1) < 7).simplify() erf(7*sqrt(2)/(2*sqrt(t1)))/2 + 1/2 >>> P((X(t1) > 2) | (X(t1) < 4), Contains(t1, Interval.Ropen(2, 4))).simplify() -erf(1)/2 + erf(2)/2 + 1 >>> E(X(t1)) 0 >>> E(X(t1) + 2*X(t2), Contains(t1, Interval.Lopen(0, 1)) ... & Contains(t2, Interval.Lopen(1, 2))) 0 References ========== .. [1] https://www.probabilitycourse.com/chapter11/11_4_0_brownian_motion_wiener_process.php .. [2] https://en.wikipedia.org/wiki/Wiener_process """ def __new__(cls, sym): sym = _symbol_converter(sym) return Basic.__new__(cls, sym) @property def state_space(self): return S.Reals def distribution(self, key): if isinstance(key, RandomIndexedSymbol): self._deprecation_warn_distribution() return NormalDistribution(0, sqrt(key.key)) return NormalDistribution(0, sqrt(key)) def density(self, x): return exp(-x**2/(2*x.key)) / (sqrt(2*pi)*sqrt(x.key)) def simple_rv(self, rv): return Normal(rv.name, 0, sqrt(rv.key)) class GammaProcess(CountingProcess): """ A Gamma process is a random process with independent gamma distributed increments. It is a pure-jump increasing Levy process. Parameters ========== sym: Symbol/str lamda: Positive number Jump size of the process, ``lamda > 0`` gamma: Positive number Rate of jump arrivals, ``gamma > 0`` Examples ======== >>> from sympy.stats import GammaProcess, E, P, variance >>> from sympy import symbols, Contains, Interval, Not >>> t, d, x, l, g = symbols('t d x l g', positive=True) >>> X = GammaProcess("X", l, g) >>> E(X(t)) g*t/l >>> variance(X(t)).simplify() g*t/l**2 >>> X = GammaProcess('X', 1, 2) >>> P(X(t) < 1).simplify() lowergamma(2*t, 1)/gamma(2*t) >>> P(Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) & ... Contains(d, Interval.Lopen(7, 8))).simplify() -4*exp(-3) + 472*exp(-8)/3 + 1 >>> E(X(2) + x*E(X(5))) 10*x + 4 References ========== .. [1] https://en.wikipedia.org/wiki/Gamma_process """ def __new__(cls, sym, lamda, gamma): _value_check(lamda > 0, 'lamda should be a positive number') _value_check(gamma > 0, 'gamma should be a positive number') sym = _symbol_converter(sym) gamma = _sympify(gamma) lamda = _sympify(lamda) return Basic.__new__(cls, sym, lamda, gamma) @property def lamda(self): return self.args[1] @property def gamma(self): return self.args[2] @property def state_space(self): return _set_converter(Interval(0, oo)) def distribution(self, key): if isinstance(key, RandomIndexedSymbol): self._deprecation_warn_distribution() return GammaDistribution(self.gamma*key.key, 1/self.lamda) return GammaDistribution(self.gamma*key, 1/self.lamda) def density(self, x): k = self.gamma*x.key theta = 1/self.lamda return x**(k - 1) * exp(-x/theta) / (gamma(k)*theta**k) def simple_rv(self, rv): return Gamma(rv.name, self.gamma*rv.key, 1/self.lamda)
f543682b784782dd3a6ef09d6490331467000e077b58b332fcec9ee54ba5994b
from sympy import S, Basic, exp, multigamma, pi from sympy.core.sympify import sympify, _sympify from sympy.matrices import (ImmutableMatrix, Inverse, Trace, Determinant, MatrixSymbol, MatrixBase, Transpose, MatrixSet, matrix2numpy) from sympy.stats.rv import (_value_check, RandomMatrixSymbol, NamedArgsMixin, PSpace, _symbol_converter, MatrixDomain, Distribution) from sympy.external import import_module ################################################################################ #------------------------Matrix Probability Space------------------------------# ################################################################################ class MatrixPSpace(PSpace): """ Represents probability space for Matrix Distributions """ def __new__(cls, sym, distribution, dim_n, dim_m): sym = _symbol_converter(sym) dim_n, dim_m = _sympify(dim_n), _sympify(dim_m) if not (dim_n.is_integer and dim_m.is_integer): raise ValueError("Dimensions should be integers") return Basic.__new__(cls, sym, distribution, dim_n, dim_m) distribution = property(lambda self: self.args[1]) symbol = property(lambda self: self.args[0]) @property def domain(self): return MatrixDomain(self.symbol, self.distribution.set) @property def value(self): return RandomMatrixSymbol(self.symbol, self.args[2], self.args[3], self) @property def values(self): return {self.value} def compute_density(self, expr, *args): rms = expr.atoms(RandomMatrixSymbol) if len(rms) > 1 or (not isinstance(expr, RandomMatrixSymbol)): raise NotImplementedError("Currently, no algorithm has been " "implemented to handle general expressions containing " "multiple matrix distributions.") return self.distribution.pdf(expr) def sample(self, size=(), library='scipy', seed=None): """ Internal sample method Returns dictionary mapping RandomMatrixSymbol to realization value. """ return {self.value: self.distribution.sample(size, library=library, seed=seed)} def rv(symbol, cls, args): args = list(map(sympify, args)) dist = cls(*args) dist.check(*args) dim = dist.dimension pspace = MatrixPSpace(symbol, dist, dim[0], dim[1]) return pspace.value class SampleMatrixScipy: """Returns the sample from scipy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_scipy(dist, size, seed) @classmethod def _sample_scipy(cls, dist, size, seed): """Sample from SciPy.""" from scipy import stats as scipy_stats import numpy scipy_rv_map = { 'WishartDistribution': lambda dist, size, rand_state: scipy_stats.wishart.rvs( df=int(dist.n), scale=matrix2numpy(dist.scale_matrix, float), size=size), 'MatrixNormalDistribution': lambda dist, size, rand_state: scipy_stats.matrix_normal.rvs( mean=matrix2numpy(dist.location_matrix, float), rowcov=matrix2numpy(dist.scale_matrix_1, float), colcov=matrix2numpy(dist.scale_matrix_2, float), size=size, random_state=rand_state) } dist_list = scipy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None samples = [] if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed for _ in range(size[0]): samp = scipy_rv_map[dist.__class__.__name__](dist, size[1] if len(size) > 1 else 1, rand_state) samples.append(samp) return samples class SampleMatrixNumpy: """Returns the sample from numpy of the given distribution""" ### TODO: Add tests after adding matrix distributions in numpy_rv_map def __new__(cls, dist, size, seed=None): return cls._sample_numpy(dist, size, seed) @classmethod def _sample_numpy(cls, dist, size, seed): """Sample from NumPy.""" numpy_rv_map = { } dist_list = numpy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None samples = [] import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed for _ in range(size[0]): samp = numpy_rv_map[dist.__class__.__name__](dist, size[1], rand_state) samples.append(samp) return samples class SampleMatrixPymc: """Returns the sample from pymc3 of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_pymc3(dist, size, seed) @classmethod def _sample_pymc3(cls, dist, size, seed): """Sample from PyMC3.""" import pymc3 pymc3_rv_map = { 'MatrixNormalDistribution': lambda dist: pymc3.MatrixNormal('X', mu=matrix2numpy(dist.location_matrix, float), rowcov=matrix2numpy(dist.scale_matrix_1, float), colcov=matrix2numpy(dist.scale_matrix_2, float), shape=dist.location_matrix.shape), 'WishartDistribution': lambda dist: pymc3.WishartBartlett('X', nu=int(dist.n), S=matrix2numpy(dist.scale_matrix, float)) } dist_list = pymc3_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None with pymc3.Model(): pymc3_rv_map[dist.__class__.__name__](dist) return pymc3.sample(size, chains=1, progressbar=False)[:]['X'] _get_sample_class_matrixrv = { 'scipy': SampleMatrixScipy, 'pymc3': SampleMatrixPymc, 'numpy': SampleMatrixNumpy } ################################################################################ #-------------------------Matrix Distribution----------------------------------# ################################################################################ class MatrixDistribution(Distribution, NamedArgsMixin): """ Abstract class for Matrix Distribution """ def __new__(cls, *args): args = list(map(sympify, args)) return Basic.__new__(cls, *args) @staticmethod def check(*args): pass def __call__(self, expr): if isinstance(expr, list): expr = ImmutableMatrix(expr) return self.pdf(expr) def sample(self, size=(), library='scipy', seed=None): """ Internal sample method Returns dictionary mapping RandomSymbol to realization value. """ libraries = ['scipy', 'numpy', 'pymc3'] if library not in libraries: raise NotImplementedError("Sampling from %s is not supported yet." % str(library)) if not import_module(library): raise ValueError("Failed to import %s" % library) samps = _get_sample_class_matrixrv[library](self, size, seed) if samps is not None: return samps raise NotImplementedError( "Sampling for %s is not currently implemented from %s" % (self.__class__.__name__, library) ) ################################################################################ #------------------------Matrix Distribution Types-----------------------------# ################################################################################ #------------------------------------------------------------------------------- # Matrix Gamma distribution ---------------------------------------------------- class MatrixGammaDistribution(MatrixDistribution): _argnames = ('alpha', 'beta', 'scale_matrix') @staticmethod def check(alpha, beta, scale_matrix): if not isinstance(scale_matrix , MatrixSymbol): _value_check(scale_matrix.is_positive_definite, "The shape " "matrix must be positive definite.") _value_check(scale_matrix.is_square, "Should " "be square matrix") _value_check(alpha.is_positive, "Shape parameter should be positive.") _value_check(beta.is_positive, "Scale parameter should be positive.") @property def set(self): k = self.scale_matrix.shape[0] return MatrixSet(k, k, S.Reals) @property def dimension(self): return self.scale_matrix.shape def pdf(self, x): alpha , beta , scale_matrix = self.alpha, self.beta, self.scale_matrix p = scale_matrix.shape[0] if isinstance(x, list): x = ImmutableMatrix(x) if not isinstance(x, (MatrixBase, MatrixSymbol)): raise ValueError("%s should be an isinstance of Matrix " "or MatrixSymbol" % str(x)) sigma_inv_x = - Inverse(scale_matrix)*x / beta term1 = exp(Trace(sigma_inv_x))/((beta**(p*alpha)) * multigamma(alpha, p)) term2 = (Determinant(scale_matrix))**(-alpha) term3 = (Determinant(x))**(alpha - S(p + 1)/2) return term1 * term2 * term3 def MatrixGamma(symbol, alpha, beta, scale_matrix): """ Creates a random variable with Matrix Gamma Distribution. The density of the said distribution can be found at [1]. Parameters ========== alpha: Positive Real number Shape Parameter beta: Positive Real number Scale Parameter scale_matrix: Positive definite real square matrix Scale Matrix Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import density, MatrixGamma >>> from sympy import MatrixSymbol, symbols >>> a, b = symbols('a b', positive=True) >>> M = MatrixGamma('M', a, b, [[2, 1], [1, 2]]) >>> X = MatrixSymbol('X', 2, 2) >>> density(M)(X).doit() 3**(-a)*b**(-2*a)*exp(Trace(Matrix([ [-2/3, 1/3], [ 1/3, -2/3]])*X)/b)*Determinant(X)**(a - 3/2)/(sqrt(pi)*gamma(a)*gamma(a - 1/2)) >>> density(M)([[1, 0], [0, 1]]).doit() 3**(-a)*b**(-2*a)*exp(-4/(3*b))/(sqrt(pi)*gamma(a)*gamma(a - 1/2)) References ========== .. [1] https://en.wikipedia.org/wiki/Matrix_gamma_distribution """ if isinstance(scale_matrix, list): scale_matrix = ImmutableMatrix(scale_matrix) return rv(symbol, MatrixGammaDistribution, (alpha, beta, scale_matrix)) #------------------------------------------------------------------------------- # Wishart Distribution --------------------------------------------------------- class WishartDistribution(MatrixDistribution): _argnames = ('n', 'scale_matrix') @staticmethod def check(n, scale_matrix): if not isinstance(scale_matrix , MatrixSymbol): _value_check(scale_matrix.is_positive_definite, "The shape " "matrix must be positive definite.") _value_check(scale_matrix.is_square, "Should " "be square matrix") _value_check(n.is_positive, "Shape parameter should be positive.") @property def set(self): k = self.scale_matrix.shape[0] return MatrixSet(k, k, S.Reals) @property def dimension(self): return self.scale_matrix.shape def pdf(self, x): n, scale_matrix = self.n, self.scale_matrix p = scale_matrix.shape[0] if isinstance(x, list): x = ImmutableMatrix(x) if not isinstance(x, (MatrixBase, MatrixSymbol)): raise ValueError("%s should be an isinstance of Matrix " "or MatrixSymbol" % str(x)) sigma_inv_x = - Inverse(scale_matrix)*x / S(2) term1 = exp(Trace(sigma_inv_x))/((2**(p*n/S(2))) * multigamma(n/S(2), p)) term2 = (Determinant(scale_matrix))**(-n/S(2)) term3 = (Determinant(x))**(S(n - p - 1)/2) return term1 * term2 * term3 def Wishart(symbol, n, scale_matrix): """ Creates a random variable with Wishart Distribution. The density of the said distribution can be found at [1]. Parameters ========== n: Positive Real number Represents degrees of freedom scale_matrix: Positive definite real square matrix Scale Matrix Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import density, Wishart >>> from sympy import MatrixSymbol, symbols >>> n = symbols('n', positive=True) >>> W = Wishart('W', n, [[2, 1], [1, 2]]) >>> X = MatrixSymbol('X', 2, 2) >>> density(W)(X).doit() 2**(-n)*3**(-n/2)*exp(Trace(Matrix([ [-1/3, 1/6], [ 1/6, -1/3]])*X))*Determinant(X)**(n/2 - 3/2)/(sqrt(pi)*gamma(n/2)*gamma(n/2 - 1/2)) >>> density(W)([[1, 0], [0, 1]]).doit() 2**(-n)*3**(-n/2)*exp(-2/3)/(sqrt(pi)*gamma(n/2)*gamma(n/2 - 1/2)) References ========== .. [1] https://en.wikipedia.org/wiki/Wishart_distribution """ if isinstance(scale_matrix, list): scale_matrix = ImmutableMatrix(scale_matrix) return rv(symbol, WishartDistribution, (n, scale_matrix)) #------------------------------------------------------------------------------- # Matrix Normal distribution --------------------------------------------------- class MatrixNormalDistribution(MatrixDistribution): _argnames = ('location_matrix', 'scale_matrix_1', 'scale_matrix_2') @staticmethod def check(location_matrix, scale_matrix_1, scale_matrix_2): if not isinstance(scale_matrix_1 , MatrixSymbol): _value_check(scale_matrix_1.is_positive_definite, "The shape " "matrix must be positive definite.") if not isinstance(scale_matrix_2 , MatrixSymbol): _value_check(scale_matrix_2.is_positive_definite, "The shape " "matrix must be positive definite.") _value_check(scale_matrix_1.is_square, "Scale matrix 1 should be " "be square matrix") _value_check(scale_matrix_2.is_square, "Scale matrix 2 should be " "be square matrix") n = location_matrix.shape[0] p = location_matrix.shape[1] _value_check(scale_matrix_1.shape[0] == n, "Scale matrix 1 should be" " of shape %s x %s"% (str(n), str(n))) _value_check(scale_matrix_2.shape[0] == p, "Scale matrix 2 should be" " of shape %s x %s"% (str(p), str(p))) @property def set(self): n, p = self.location_matrix.shape return MatrixSet(n, p, S.Reals) @property def dimension(self): return self.location_matrix.shape def pdf(self, x): M , U , V = self.location_matrix, self.scale_matrix_1, self.scale_matrix_2 n, p = M.shape if isinstance(x, list): x = ImmutableMatrix(x) if not isinstance(x, (MatrixBase, MatrixSymbol)): raise ValueError("%s should be an isinstance of Matrix " "or MatrixSymbol" % str(x)) term1 = Inverse(V)*Transpose(x - M)*Inverse(U)*(x - M) num = exp(-Trace(term1)/S(2)) den = (2*pi)**(S(n*p)/2) * Determinant(U)**S(p)/2 * Determinant(V)**S(n)/2 return num/den def MatrixNormal(symbol, location_matrix, scale_matrix_1, scale_matrix_2): """ Creates a random variable with Matrix Normal Distribution. The density of the said distribution can be found at [1]. Parameters ========== location_matrix: Real ``n x p`` matrix Represents degrees of freedom scale_matrix_1: Positive definite matrix Scale Matrix of shape ``n x n`` scale_matrix_2: Positive definite matrix Scale Matrix of shape ``p x p`` Returns ======= RandomSymbol Examples ======== >>> from sympy import MatrixSymbol >>> from sympy.stats import density, MatrixNormal >>> M = MatrixNormal('M', [[1, 2]], [1], [[1, 0], [0, 1]]) >>> X = MatrixSymbol('X', 1, 2) >>> density(M)(X).doit() 2*exp(-Trace((Matrix([ [-1], [-2]]) + X.T)*(Matrix([[-1, -2]]) + X))/2)/pi >>> density(M)([[3, 4]]).doit() 2*exp(-4)/pi References ========== .. [1] https://en.wikipedia.org/wiki/Matrix_normal_distribution """ if isinstance(location_matrix, list): location_matrix = ImmutableMatrix(location_matrix) if isinstance(scale_matrix_1, list): scale_matrix_1 = ImmutableMatrix(scale_matrix_1) if isinstance(scale_matrix_2, list): scale_matrix_2 = ImmutableMatrix(scale_matrix_2) args = (location_matrix, scale_matrix_1, scale_matrix_2) return rv(symbol, MatrixNormalDistribution, args) #------------------------------------------------------------------------------- # Matrix Student's T distribution --------------------------------------------------- class MatrixStudentTDistribution(MatrixDistribution): _argnames = ('nu', 'location_matrix', 'scale_matrix_1', 'scale_matrix_2') @staticmethod def check(nu, location_matrix, scale_matrix_1, scale_matrix_2): if not isinstance(scale_matrix_1, MatrixSymbol): _value_check(scale_matrix_1.is_positive_definite != False, "The shape " "matrix must be positive definite.") if not isinstance(scale_matrix_2, MatrixSymbol): _value_check(scale_matrix_2.is_positive_definite != False, "The shape " "matrix must be positive definite.") _value_check(scale_matrix_1.is_square != False, "Scale matrix 1 should be " "be square matrix") _value_check(scale_matrix_2.is_square != False, "Scale matrix 2 should be " "be square matrix") n = location_matrix.shape[0] p = location_matrix.shape[1] _value_check(scale_matrix_1.shape[0] == p, "Scale matrix 1 should be" " of shape %s x %s" % (str(p), str(p))) _value_check(scale_matrix_2.shape[0] == n, "Scale matrix 2 should be" " of shape %s x %s" % (str(n), str(n))) _value_check(nu.is_positive != False, "Degrees of freedom must be positive") @property def set(self): n, p = self.location_matrix.shape return MatrixSet(n, p, S.Reals) @property def dimension(self): return self.location_matrix.shape def pdf(self, x): from sympy import eye if isinstance(x, list): x = ImmutableMatrix(x) if not isinstance(x, (MatrixBase, MatrixSymbol)): raise ValueError("%s should be an isinstance of Matrix " "or MatrixSymbol" % str(x)) nu, M, Omega, Sigma = self.nu, self.location_matrix, self.scale_matrix_1, self.scale_matrix_2 n, p = M.shape K = multigamma((nu + n + p - 1)/2, p) * Determinant(Omega)**(-n/2) * Determinant(Sigma)**(-p/2) \ / ((pi)**(n*p/2) * multigamma((nu + p - 1)/2, p)) return K * (Determinant(eye(n) + Inverse(Sigma)*(x - M)*Inverse(Omega)*Transpose(x - M))) \ **(-(nu + n + p -1)/2) def MatrixStudentT(symbol, nu, location_matrix, scale_matrix_1, scale_matrix_2): """ Creates a random variable with Matrix Gamma Distribution. The density of the said distribution can be found at [1]. Parameters ========== nu: Positive Real number degrees of freedom location_matrix: Positive definite real square matrix Location Matrix of shape ``n x p`` scale_matrix_1: Positive definite real square matrix Scale Matrix of shape ``p x p`` scale_matrix_2: Positive definite real square matrix Scale Matrix of shape ``n x n`` Returns ======= RandomSymbol Examples ======== >>> from sympy import MatrixSymbol,symbols >>> from sympy.stats import density, MatrixStudentT >>> v = symbols('v',positive=True) >>> M = MatrixStudentT('M', v, [[1, 2]], [[1, 0], [0, 1]], [1]) >>> X = MatrixSymbol('X', 1, 2) >>> density(M)(X) pi**(-1.0)*gamma(v/2 + 1)*Determinant((Matrix([[-1, -2]]) + X)*(Matrix([ [-1], [-2]]) + X.T) + Matrix([[1]]))**(-v/2 - 1)*Determinant(Matrix([[1]]))**(-1.0)*Determinant(Matrix([ [1, 0], [0, 1]]))**(-0.5)/gamma(v/2) References ========== .. [1] https://en.wikipedia.org/wiki/Matrix_t-distribution """ if isinstance(location_matrix, list): location_matrix = ImmutableMatrix(location_matrix) if isinstance(scale_matrix_1, list): scale_matrix_1 = ImmutableMatrix(scale_matrix_1) if isinstance(scale_matrix_2, list): scale_matrix_2 = ImmutableMatrix(scale_matrix_2) args = (nu, location_matrix, scale_matrix_1, scale_matrix_2) return rv(symbol, MatrixStudentTDistribution, args)
c711a3c625cbea4d5150c76e43bdf2bfdd598511715768a977ee20136cfbce82
""" SymPy statistics module Introduces a random variable type into the SymPy language. Random variables may be declared using prebuilt functions such as Normal, Exponential, Coin, Die, etc... or built with functions like FiniteRV. Queries on random expressions can be made using the functions ========================= ============================= Expression Meaning ------------------------- ----------------------------- ``P(condition)`` Probability ``E(expression)`` Expected value ``H(expression)`` Entropy ``variance(expression)`` Variance ``density(expression)`` Probability Density Function ``sample(expression)`` Produce a realization ``where(condition)`` Where the condition is true ========================= ============================= Examples ======== >>> from sympy.stats import P, E, variance, Die, Normal >>> from sympy import Eq, simplify >>> X, Y = Die('X', 6), Die('Y', 6) # Define two six sided dice >>> Z = Normal('Z', 0, 1) # Declare a Normal random variable with mean 0, std 1 >>> P(X>3) # Probability X is greater than 3 1/2 >>> E(X+Y) # Expectation of the sum of two dice 7 >>> variance(X+Y) # Variance of the sum of two dice 35/6 >>> simplify(P(Z>1)) # Probability of Z being greater than 1 1/2 - erf(sqrt(2)/2)/2 One could also create custom distribution and define custom random variables as follows: 1. If you want to create a Continuous Random Variable: >>> from sympy.stats import ContinuousRV, P, E >>> from sympy import exp, Symbol, Interval, oo >>> x = Symbol('x') >>> pdf = exp(-x) # pdf of the Continuous Distribution >>> Z = ContinuousRV(x, pdf, set=Interval(0, oo)) >>> E(Z) 1 >>> P(Z > 5) exp(-5) 1.1 To create an instance of Continuous Distribution: >>> from sympy.stats import ContinuousDistributionHandmade >>> from sympy import Lambda >>> dist = ContinuousDistributionHandmade(Lambda(x, pdf), set=Interval(0, oo)) >>> dist.pdf(x) exp(-x) 2. If you want to create a Discrete Random Variable: >>> from sympy.stats import DiscreteRV, P, E >>> from sympy import Symbol, S >>> p = S(1)/2 >>> x = Symbol('x', integer=True, positive=True) >>> pdf = p*(1 - p)**(x - 1) >>> D = DiscreteRV(x, pdf, set=S.Naturals) >>> E(D) 2 >>> P(D > 3) 1/8 2.1 To create an instance of Discrete Distribution: >>> from sympy.stats import DiscreteDistributionHandmade >>> from sympy import Lambda >>> dist = DiscreteDistributionHandmade(Lambda(x, pdf), set=S.Naturals) >>> dist.pdf(x) 2**(1 - x)/2 3. If you want to create a Finite Random Variable: >>> from sympy.stats import FiniteRV, P, E >>> from sympy import Rational >>> pmf = {1: Rational(1, 3), 2: Rational(1, 6), 3: Rational(1, 4), 4: Rational(1, 4)} >>> X = FiniteRV('X', pmf) >>> E(X) 29/12 >>> P(X > 3) 1/4 3.1 To create an instance of Finite Distribution: >>> from sympy.stats import FiniteDistributionHandmade >>> dist = FiniteDistributionHandmade(pmf) >>> dist.pmf(x) Lambda(x, Piecewise((1/3, Eq(x, 1)), (1/6, Eq(x, 2)), (1/4, Eq(x, 3) | Eq(x, 4)), (0, True))) """ __all__ = [ 'P', 'E', 'H', 'density', 'where', 'given', 'sample', 'cdf','median', 'characteristic_function', 'pspace', 'sample_iter', 'variance', 'std', 'skewness', 'kurtosis', 'covariance', 'dependent', 'entropy', 'independent', 'random_symbols', 'correlation', 'factorial_moment', 'moment', 'cmoment', 'sampling_density', 'moment_generating_function', 'smoment', 'quantile', 'coskewness', 'sample_stochastic_process', 'FiniteRV', 'DiscreteUniform', 'Die', 'Bernoulli', 'Coin', 'Binomial', 'BetaBinomial', 'Hypergeometric', 'Rademacher', 'IdealSoliton', 'RobustSoliton', 'FiniteDistributionHandmade', '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', 'Logistic','LogCauchy', 'LogLogistic', 'LogitNormal', 'LogNormal', 'Lomax', 'Moyal', 'Maxwell', 'Nakagami', 'Normal', 'GaussianInverse', 'Pareto', 'PowerFunction', 'QuadraticU', 'RaisedCosine', 'Rayleigh','Reciprocal', 'StudentT', 'ShiftedGompertz', 'Trapezoidal', 'Triangular', 'Uniform', 'UniformSum', 'VonMises', 'Wald', 'Weibull', 'WignerSemicircle', 'ContinuousDistributionHandmade', 'FlorySchulz', 'Geometric','Hermite', 'Logarithmic', 'NegativeBinomial', 'Poisson', 'Skellam', 'YuleSimon', 'Zeta', 'DiscreteRV', 'DiscreteDistributionHandmade', 'JointRV', 'Dirichlet', 'GeneralizedMultivariateLogGamma', 'GeneralizedMultivariateLogGammaOmega', 'Multinomial', 'MultivariateBeta', 'MultivariateEwens', 'MultivariateT', 'NegativeMultinomial', 'NormalGamma', 'MultivariateNormal', 'MultivariateLaplace', 'marginal_distribution', 'StochasticProcess', 'DiscreteTimeStochasticProcess', 'DiscreteMarkovChain', 'TransitionMatrixOf', 'StochasticStateSpaceOf', 'GeneratorMatrixOf', 'ContinuousMarkovChain', 'BernoulliProcess', 'PoissonProcess', 'WienerProcess', 'GammaProcess', 'CircularEnsemble', 'CircularUnitaryEnsemble', 'CircularOrthogonalEnsemble', 'CircularSymplecticEnsemble', 'GaussianEnsemble', 'GaussianUnitaryEnsemble', 'GaussianOrthogonalEnsemble', 'GaussianSymplecticEnsemble', 'joint_eigen_distribution', 'JointEigenDistribution', 'level_spacing_distribution', 'MatrixGamma', 'Wishart', 'MatrixNormal', 'MatrixStudentT', 'Probability', 'Expectation', 'Variance', 'Covariance', 'Moment', 'CentralMoment', 'ExpectationMatrix', 'VarianceMatrix', 'CrossCovarianceMatrix' ] from .rv_interface import (P, E, H, density, where, given, sample, cdf, median, characteristic_function, pspace, sample_iter, variance, std, skewness, kurtosis, covariance, dependent, entropy, independent, random_symbols, correlation, factorial_moment, moment, cmoment, sampling_density, moment_generating_function, smoment, quantile, coskewness, sample_stochastic_process) from .frv_types import (FiniteRV, DiscreteUniform, Die, Bernoulli, Coin, Binomial, BetaBinomial, Hypergeometric, Rademacher, FiniteDistributionHandmade, IdealSoliton, RobustSoliton) from .crv_types import (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, Logistic,LogCauchy ,LogLogistic, LogitNormal, LogNormal, Lomax, Maxwell, Moyal, Nakagami, Normal, GaussianInverse, Pareto, QuadraticU, RaisedCosine, Rayleigh, Reciprocal, StudentT, PowerFunction, ShiftedGompertz, Trapezoidal, Triangular, Uniform, UniformSum, VonMises, Wald, Weibull, WignerSemicircle, ContinuousDistributionHandmade) from .drv_types import (FlorySchulz, Geometric, Hermite, Logarithmic, NegativeBinomial, Poisson, Skellam, YuleSimon, Zeta, DiscreteRV, DiscreteDistributionHandmade) from .joint_rv_types import (JointRV, Dirichlet, GeneralizedMultivariateLogGamma, GeneralizedMultivariateLogGammaOmega, Multinomial, MultivariateBeta, MultivariateEwens, MultivariateT, NegativeMultinomial, NormalGamma, MultivariateNormal, MultivariateLaplace, marginal_distribution) from .stochastic_process_types import (StochasticProcess, DiscreteTimeStochasticProcess, DiscreteMarkovChain, TransitionMatrixOf, StochasticStateSpaceOf, GeneratorMatrixOf, ContinuousMarkovChain, BernoulliProcess, PoissonProcess, WienerProcess, GammaProcess) from .random_matrix_models import (CircularEnsemble, CircularUnitaryEnsemble, CircularOrthogonalEnsemble, CircularSymplecticEnsemble, GaussianEnsemble, GaussianUnitaryEnsemble, GaussianOrthogonalEnsemble, GaussianSymplecticEnsemble, joint_eigen_distribution, JointEigenDistribution, level_spacing_distribution) from .matrix_distributions import MatrixGamma, Wishart, MatrixNormal, MatrixStudentT from .symbolic_probability import (Probability, Expectation, Variance, Covariance, Moment, CentralMoment) from .symbolic_multivariate_probability import (ExpectationMatrix, VarianceMatrix, CrossCovarianceMatrix)
0e571f163092278b50e916a4b71ff8f84db80c994d91c496a76cd2dfec8783bc
""" 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)
5f35082da34cfc2a1804fbac93ccab121715e95ac76269412dfd6bad4a6979a2
""" 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 Distribution(Basic): pass 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)) 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()
f88c3856230275a999cfec88e68f86df9ba086e1c855f00f3ed51073866f9c5a
""" Joint Random Variables Module See Also ======== sympy.stats.rv sympy.stats.frv sympy.stats.crv sympy.stats.drv """ from sympy import (Basic, Lambda, sympify, Indexed, Symbol, ProductSet, S, Dummy) from sympy.concrete.products import Product from sympy.concrete.summations import Sum, summation from sympy.core.compatibility import iterable from sympy.core.containers import Tuple from sympy.integrals.integrals import Integral, integrate from sympy.matrices import ImmutableMatrix, matrix2numpy, list2numpy from sympy.stats.crv import SingleContinuousDistribution, SingleContinuousPSpace from sympy.stats.drv import SingleDiscreteDistribution, SingleDiscretePSpace from sympy.stats.rv import (ProductPSpace, NamedArgsMixin, Distribution, ProductDomain, RandomSymbol, random_symbols, SingleDomain, _symbol_converter) from sympy.utilities.misc import filldedent from sympy.external import import_module # __all__ = ['marginal_distribution'] class JointPSpace(ProductPSpace): """ Represents a joint probability space. Represented using symbols for each component and a distribution. """ def __new__(cls, sym, dist): if isinstance(dist, SingleContinuousDistribution): return SingleContinuousPSpace(sym, dist) if isinstance(dist, SingleDiscreteDistribution): return SingleDiscretePSpace(sym, dist) sym = _symbol_converter(sym) return Basic.__new__(cls, sym, dist) @property def set(self): return self.domain.set @property def symbol(self): return self.args[0] @property def distribution(self): return self.args[1] @property def value(self): return JointRandomSymbol(self.symbol, self) @property def component_count(self): _set = self.distribution.set if isinstance(_set, ProductSet): return S(len(_set.args)) elif isinstance(_set, Product): return _set.limits[0][-1] return S.One @property def pdf(self): sym = [Indexed(self.symbol, i) for i in range(self.component_count)] return self.distribution(*sym) @property def domain(self): rvs = random_symbols(self.distribution) if not rvs: return SingleDomain(self.symbol, self.distribution.set) return ProductDomain(*[rv.pspace.domain for rv in rvs]) def component_domain(self, index): return self.set.args[index] def marginal_distribution(self, *indices): count = self.component_count if count.atoms(Symbol): raise ValueError("Marginal distributions cannot be computed " "for symbolic dimensions. It is a work under progress.") orig = [Indexed(self.symbol, i) for i in range(count)] all_syms = [Symbol(str(i)) for i in orig] replace_dict = dict(zip(all_syms, orig)) sym = tuple(Symbol(str(Indexed(self.symbol, i))) for i in indices) limits = list([i,] for i in all_syms if i not in sym) index = 0 for i in range(count): if i not in indices: limits[index].append(self.distribution.set.args[i]) limits[index] = tuple(limits[index]) index += 1 if self.distribution.is_Continuous: f = Lambda(sym, integrate(self.distribution(*all_syms), *limits)) elif self.distribution.is_Discrete: f = Lambda(sym, summation(self.distribution(*all_syms), *limits)) return f.xreplace(replace_dict) def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs): syms = tuple(self.value[i] for i in range(self.component_count)) rvs = rvs or syms if not any([i in rvs for i in syms]): return expr expr = expr*self.pdf for rv in rvs: if isinstance(rv, Indexed): expr = expr.xreplace({rv: Indexed(str(rv.base), rv.args[1])}) elif isinstance(rv, RandomSymbol): expr = expr.xreplace({rv: rv.symbol}) if self.value in random_symbols(expr): raise NotImplementedError(filldedent(''' Expectations of expression with unindexed joint random symbols cannot be calculated yet.''')) limits = tuple((Indexed(str(rv.base),rv.args[1]), self.distribution.set.args[rv.args[1]]) for rv in syms) return Integral(expr, *limits) def where(self, condition): raise NotImplementedError() def compute_density(self, expr): raise NotImplementedError() def sample(self, size=(), library='scipy', seed=None): """ Internal sample method Returns dictionary mapping RandomSymbol to realization value. """ return {RandomSymbol(self.symbol, self): self.distribution.sample(size, library=library, seed=seed)} def probability(self, condition): raise NotImplementedError() class SampleJointScipy: """Returns the sample from scipy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_scipy(dist, size, seed) @classmethod def _sample_scipy(cls, dist, size, seed): """Sample from SciPy.""" from scipy import stats as scipy_stats scipy_rv_map = { 'MultivariateNormalDistribution': lambda dist, size: scipy_stats.multivariate_normal.rvs( mean=matrix2numpy(dist.mu).flatten(), cov=matrix2numpy(dist.sigma), size=size, random_state=seed), 'MultivariateBetaDistribution': lambda dist, size: scipy_stats.dirichlet.rvs( alpha=list2numpy(dist.alpha, float).flatten(), size=size, random_state=seed), 'MultinomialDistribution': lambda dist, size: scipy_stats.multinomial.rvs( n=int(dist.n), p=list2numpy(dist.p, float).flatten(), size=size, random_state=seed) } dist_list = scipy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None samples = scipy_rv_map[dist.__class__.__name__](dist, size) if samples.shape[0:len(size)] != size: samples = samples.reshape((size[0],) + samples.shape) return samples class SampleJointNumpy: """Returns the sample from numpy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_numpy(dist, size, seed) @classmethod def _sample_numpy(cls, dist, size, seed): """Sample from NumPy.""" import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed numpy_rv_map = { 'MultivariateNormalDistribution': lambda dist, size: rand_state.multivariate_normal( mean=matrix2numpy(dist.mu, float).flatten(), cov=matrix2numpy(dist.sigma, float), size=size), 'MultivariateBetaDistribution': lambda dist, size: rand_state.dirichlet( alpha=list2numpy(dist.alpha, float).flatten(), size=size), 'MultinomialDistribution': lambda dist, size: rand_state.multinomial( n=int(dist.n), pvals=list2numpy(dist.p, float).flatten(), size=size) } dist_list = numpy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None samples = numpy_rv_map[dist.__class__.__name__](dist, size) if samples.shape[0:len(size)] != size: samples = samples.reshape((size[0],) + samples.shape) return samples class SampleJointPymc: """Returns the sample from pymc3 of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_pymc3(dist, size, seed) @classmethod def _sample_pymc3(cls, dist, size, seed): """Sample from PyMC3.""" import pymc3 pymc3_rv_map = { 'MultivariateNormalDistribution': lambda dist: pymc3.MvNormal('X', mu=matrix2numpy(dist.mu, float).flatten(), cov=matrix2numpy(dist.sigma, float), shape=(1, dist.mu.shape[0])), 'MultivariateBetaDistribution': lambda dist: pymc3.Dirichlet('X', a=list2numpy(dist.alpha, float).flatten()), 'MultinomialDistribution': lambda dist: pymc3.Multinomial('X', n=int(dist.n), p=list2numpy(dist.p, float).flatten(), shape=(1, len(dist.p))) } dist_list = pymc3_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None with pymc3.Model(): pymc3_rv_map[dist.__class__.__name__](dist) samples = pymc3.sample(size, chains=1, progressbar=False, random_seed=seed)[:]['X'] if samples.shape[0:len(size)] != size: samples = samples.reshape((size[0],) + samples.shape) return samples _get_sample_class_jrv = { 'scipy': SampleJointScipy, 'pymc3': SampleJointPymc, 'numpy': SampleJointNumpy } class JointDistribution(Distribution, NamedArgsMixin): """ Represented by the random variables part of the joint distribution. Contains methods for PDF, CDF, sampling, marginal densities, etc. """ _argnames = ('pdf', ) def __new__(cls, *args): args = list(map(sympify, args)) for i in range(len(args)): if isinstance(args[i], list): args[i] = ImmutableMatrix(args[i]) return Basic.__new__(cls, *args) @property def domain(self): return ProductDomain(self.symbols) @property def pdf(self): return self.density.args[1] def cdf(self, other): if not isinstance(other, dict): raise ValueError("%s should be of type dict, got %s"%(other, type(other))) rvs = other.keys() _set = self.domain.set.sets expr = self.pdf(tuple(i.args[0] for i in self.symbols)) for i in range(len(other)): if rvs[i].is_Continuous: density = Integral(expr, (rvs[i], _set[i].inf, other[rvs[i]])) elif rvs[i].is_Discrete: density = Sum(expr, (rvs[i], _set[i].inf, other[rvs[i]])) return density def sample(self, size=(), library='scipy', seed=None): """ A random realization from the distribution """ libraries = ['scipy', 'numpy', 'pymc3'] if library not in libraries: raise NotImplementedError("Sampling from %s is not supported yet." % str(library)) if not import_module(library): raise ValueError("Failed to import %s" % library) samps = _get_sample_class_jrv[library](self, size, seed=seed) if samps is not None: return samps raise NotImplementedError( "Sampling for %s is not currently implemented from %s" % (self.__class__.__name__, library) ) def __call__(self, *args): return self.pdf(*args) class JointRandomSymbol(RandomSymbol): """ Representation of random symbols with joint probability distributions to allow indexing." """ def __getitem__(self, key): if isinstance(self.pspace, JointPSpace): if (self.pspace.component_count <= key) == True: raise ValueError("Index keys for %s can only up to %s." % (self.name, self.pspace.component_count - 1)) return Indexed(self, key) class MarginalDistribution(Distribution): """ Represents the marginal distribution of a joint probability space. Initialised using a probability distribution and random variables(or their indexed components) which should be a part of the resultant distribution. """ def __new__(cls, dist, *rvs): if len(rvs) == 1 and iterable(rvs[0]): rvs = tuple(rvs[0]) if not all([isinstance(rv, (Indexed, RandomSymbol))] for rv in rvs): raise ValueError(filldedent('''Marginal distribution can be intitialised only in terms of random variables or indexed random variables''')) rvs = Tuple.fromiter(rv for rv in rvs) if not isinstance(dist, JointDistribution) and len(random_symbols(dist)) == 0: return dist return Basic.__new__(cls, dist, rvs) def check(self): pass @property def set(self): rvs = [i for i in self.args[1] if isinstance(i, RandomSymbol)] return ProductSet(*[rv.pspace.set for rv in rvs]) @property def symbols(self): rvs = self.args[1] return {rv.pspace.symbol for rv in rvs} def pdf(self, *x): expr, rvs = self.args[0], self.args[1] marginalise_out = [i for i in random_symbols(expr) if i not in rvs] if isinstance(expr, JointDistribution): count = len(expr.domain.args) x = Dummy('x', real=True, finite=True) syms = tuple(Indexed(x, i) for i in count) expr = expr.pdf(syms) else: syms = tuple(rv.pspace.symbol if isinstance(rv, RandomSymbol) else rv.args[0] for rv in rvs) return Lambda(syms, self.compute_pdf(expr, marginalise_out))(*x) def compute_pdf(self, expr, rvs): for rv in rvs: lpdf = 1 if isinstance(rv, RandomSymbol): lpdf = rv.pspace.pdf expr = self.marginalise_out(expr*lpdf, rv) return expr def marginalise_out(self, expr, rv): from sympy.concrete.summations import Sum if isinstance(rv, RandomSymbol): dom = rv.pspace.set elif isinstance(rv, Indexed): dom = rv.base.component_domain( rv.pspace.component_domain(rv.args[1])) expr = expr.xreplace({rv: rv.pspace.symbol}) if rv.pspace.is_Continuous: #TODO: Modify to support integration #for all kinds of sets. expr = Integral(expr, (rv.pspace.symbol, dom)) elif rv.pspace.is_Discrete: #incorporate this into `Sum`/`summation` if dom in (S.Integers, S.Naturals, S.Naturals0): dom = (dom.inf, dom.sup) expr = Sum(expr, (rv.pspace.symbol, dom)) return expr def __call__(self, *args): return self.pdf(*args)
dfdcf0a53e21268f73eac76230e3a29a8cc233e786f286ed9175c9287bf06b69
from sympy import (Basic, sympify, symbols, Dummy, Lambda, summation, Piecewise, S, cacheit, Sum, exp, I, Ne, Eq, poly, series, factorial, And, lambdify, 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 from sympy.external import import_module class DiscreteDistribution(Distribution): def __call__(self, *args): return self.pdf(*args) class SampleDiscreteScipy: """Returns the sample from scipy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_scipy(dist, size, seed) @classmethod def _sample_scipy(cls, dist, size, seed): """Sample from SciPy.""" from scipy import stats as scipy_stats scipy_rv_map = { 'GeometricDistribution': lambda dist, size: scipy_stats.geom.rvs(p=float(dist.p), size=size, random_state=seed), 'LogarithmicDistribution': lambda dist, size: scipy_stats.logser.rvs(p=float(dist.p), size=size, random_state=seed), 'NegativeBinomialDistribution': lambda dist, size: scipy_stats.nbinom.rvs(n=float(dist.r), p=float(dist.p), size=size, random_state=seed), 'PoissonDistribution': lambda dist, size: scipy_stats.poisson.rvs(mu=float(dist.lamda), size=size, random_state=seed), 'SkellamDistribution': lambda dist, size: scipy_stats.skellam.rvs(mu1=float(dist.mu1), mu2=float(dist.mu2), size=size, random_state=seed), 'YuleSimonDistribution': lambda dist, size: scipy_stats.yulesimon.rvs(alpha=float(dist.rho), size=size, random_state=seed), 'ZetaDistribution': lambda dist, size: scipy_stats.zipf.rvs(a=float(dist.s), size=size, random_state=seed) } dist_list = scipy_rv_map.keys() if dist.__class__.__name__ == 'DiscreteDistributionHandmade': from scipy.stats import rv_discrete z = Dummy('z') handmade_pmf = lambdify(z, dist.pdf(z), ['numpy', 'scipy']) class scipy_pmf(rv_discrete): def _pmf(self, 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) if dist.__class__.__name__ not in dist_list: return None return scipy_rv_map[dist.__class__.__name__](dist, size) class SampleDiscreteNumpy: """Returns the sample from numpy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_numpy(dist, size, seed) @classmethod def _sample_numpy(cls, dist, size, seed): """Sample from NumPy.""" import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed numpy_rv_map = { 'GeometricDistribution': lambda dist, size: rand_state.geometric(p=float(dist.p), size=size), 'PoissonDistribution': lambda dist, size: rand_state.poisson(lam=float(dist.lamda), size=size), 'ZetaDistribution': lambda dist, size: rand_state.zipf(a=float(dist.s), size=size) } dist_list = numpy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None return numpy_rv_map[dist.__class__.__name__](dist, size) class SampleDiscretePymc: """Returns the sample from pymc3 of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_pymc3(dist, size, seed) @classmethod def _sample_pymc3(cls, dist, size, seed): """Sample from PyMC3.""" import pymc3 pymc3_rv_map = { 'GeometricDistribution': lambda dist: pymc3.Geometric('X', p=float(dist.p)), 'PoissonDistribution': lambda dist: pymc3.Poisson('X', mu=float(dist.lamda)), 'NegativeBinomialDistribution': lambda dist: pymc3.NegativeBinomial('X', mu=float((dist.p*dist.r)/(1-dist.p)), alpha=float(dist.r)) } dist_list = pymc3_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None with pymc3.Model(): pymc3_rv_map[dist.__class__.__name__](dist) return pymc3.sample(size, chains=1, progressbar=False, random_seed=seed)[:]['X'] _get_sample_class_drv = { 'scipy': SampleDiscreteScipy, 'pymc3': SampleDiscretePymc, 'numpy': SampleDiscreteNumpy } 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 def sample(self, size=(), library='scipy', seed=None): """ A random realization from the distribution""" libraries = ['scipy', 'numpy', 'pymc3'] if library not in libraries: raise NotImplementedError("Sampling from %s is not supported yet." % str(library)) if not import_module(library): raise ValueError("Failed to import %s" % library) samps = _get_sample_class_drv[library](self, size, seed) if samps is not None: return samps raise NotImplementedError( "Sampling for %s is not currently implemented from %s" % (self.__class__.__name__, library) ) @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()
6d5c2d9983786b51bedbe23261791f88cb5faa76bc30e31eddc6e3b28d75f79b
""" 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, lambdify) 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.external import import_module 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 SampleContinuousScipy: """Returns the sample from scipy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_scipy(dist, size, seed=seed) @classmethod def _sample_scipy(cls, dist, size, seed): """Sample from SciPy.""" import scipy.stats # 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. scipy_rv_map = { 'BetaDistribution': lambda dist, size: scipy.stats.beta.rvs( a=float(dist.alpha), b=float(dist.beta), size=size, random_state=seed), # same parametrisation 'CauchyDistribution': lambda dist, size: scipy.stats.cauchy.rvs( loc=float(dist.x0), scale=float(dist.gamma), size=size, random_state=seed), # same parametrisation 'ChiSquaredDistribution': lambda dist, size: scipy.stats.chi2.rvs( df=float(dist.k), size=size, random_state=seed), # same parametrisation 'ExponentialDistribution': lambda dist, size: scipy.stats.expon.rvs( scale=1 / float(dist.rate), size=size, random_state=seed), # https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.expon.html#scipy.stats.expon 'GammaDistribution': lambda dist, size: scipy.stats.gamma.rvs( a=float(dist.k), scale=float(dist.theta), size=size, random_state=seed), # https://stackoverflow.com/questions/42150965/how-to-plot-gamma-distribution-with-alpha-and-beta-parameters-in-python 'LogNormalDistribution': lambda dist, size: scipy.stats.lognorm.rvs( scale=float(exp(dist.mean)), s=float(dist.std), size=size, random_state=seed), # https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lognorm.html 'NormalDistribution': lambda dist, size: scipy.stats.norm.rvs( loc=float(dist.mean), scale=float(dist.std), size=size, random_state=seed), # same parametrisation 'ParetoDistribution': lambda dist, size: scipy.stats.pareto.rvs( b=float(dist.alpha), scale=float(dist.xm), size=size, random_state=seed), # https://stackoverflow.com/questions/42260519/defining-pareto-distribution-in-python-scipy 'StudentTDistribution': lambda dist, size: scipy.stats.t.rvs( df=float(dist.nu), size=size, random_state=seed), # same parametrisation 'UniformDistribution': lambda dist, size: scipy.stats.uniform.rvs( loc=float(dist.left), scale=float(dist.right - dist.left), size=size, random_state=seed) # https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.uniform.html } # if we don't need to make a handmade pdf, we won't if dist.__class__.__name__ in scipy_rv_map: return scipy_rv_map[dist.__class__.__name__](dist, size) z = Dummy('z') handmade_pdf = lambdify(z, dist.pdf(z), ['numpy', 'scipy']) class scipy_pdf(scipy.stats.rv_continuous): def _pdf(self, 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) class SampleContinuousNumpy: """Returns the sample from numpy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_numpy(dist, size, seed) @classmethod def _sample_numpy(cls, dist, size, seed): """Sample from NumPy.""" import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed numpy_rv_map = { 'BetaDistribution': lambda dist, size: rand_state.beta(a=float(dist.alpha), b=float(dist.beta), size=size), 'ChiSquaredDistribution': lambda dist, size: rand_state.chisquare( df=float(dist.k), size=size), 'ExponentialDistribution': lambda dist, size: rand_state.exponential( 1/float(dist.rate), size=size), 'GammaDistribution': lambda dist, size: rand_state.gamma(float(dist.k), float(dist.theta), size=size), 'LogNormalDistribution': lambda dist, size: rand_state.lognormal( float(dist.mean), float(dist.std), size=size), 'NormalDistribution': lambda dist, size: rand_state.normal( float(dist.mean), float(dist.std), size=size), 'ParetoDistribution': lambda dist, size: (rand_state.pareto( a=float(dist.alpha), size=size) + 1) * float(dist.xm), 'UniformDistribution': lambda dist, size: rand_state.uniform( low=float(dist.left), high=float(dist.right), size=size) } dist_list = numpy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None return numpy_rv_map[dist.__class__.__name__](dist, size) class SampleContinuousPymc: """Returns the sample from pymc3 of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_pymc3(dist, size, seed) @classmethod def _sample_pymc3(cls, dist, size, seed): """Sample from PyMC3.""" import pymc3 pymc3_rv_map = { 'BetaDistribution': lambda dist: pymc3.Beta('X', alpha=float(dist.alpha), beta=float(dist.beta)), 'CauchyDistribution': lambda dist: pymc3.Cauchy('X', alpha=float(dist.x0), beta=float(dist.gamma)), 'ChiSquaredDistribution': lambda dist: pymc3.ChiSquared('X', nu=float(dist.k)), 'ExponentialDistribution': lambda dist: pymc3.Exponential('X', lam=float(dist.rate)), 'GammaDistribution': lambda dist: pymc3.Gamma('X', alpha=float(dist.k), beta=1/float(dist.theta)), 'LogNormalDistribution': lambda dist: pymc3.Lognormal('X', mu=float(dist.mean), sigma=float(dist.std)), 'NormalDistribution': lambda dist: pymc3.Normal('X', float(dist.mean), float(dist.std)), 'GaussianInverseDistribution': lambda dist: pymc3.Wald('X', mu=float(dist.mean), lam=float(dist.shape)), 'ParetoDistribution': lambda dist: pymc3.Pareto('X', alpha=float(dist.alpha), m=float(dist.xm)), 'UniformDistribution': lambda dist: pymc3.Uniform('X', lower=float(dist.left), upper=float(dist.right)) } dist_list = pymc3_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None with pymc3.Model(): pymc3_rv_map[dist.__class__.__name__](dist) return pymc3.sample(size, chains=1, progressbar=False, random_seed=seed)[:]['X'] _get_sample_class_crv = { 'scipy': SampleContinuousScipy, 'pymc3': SampleContinuousPymc, 'numpy': SampleContinuousNumpy } 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 def sample(self, size=(), library='scipy', seed=None): """ A random realization from the distribution """ libraries = ['scipy', 'numpy', 'pymc3'] if library not in libraries: raise NotImplementedError("Sampling from %s is not supported yet." % str(library)) if not import_module(library): raise ValueError("Failed to import %s" % library) samps = _get_sample_class_crv[library](self, size, seed) if samps is not None: return samps raise NotImplementedError( "Sampling for %s is not currently implemented from %s" % (self.__class__.__name__, library) ) @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
4566f8e813b27ab3316e2f423c8781ae305464c04bedcca0e368781217e9c06f
from sympy import Basic, Sum, Dummy, Lambda, Integral from sympy.stats.rv import (NamedArgsMixin, random_symbols, _symbol_converter, PSpace, RandomSymbol, is_random, Distribution) from sympy.stats.crv import ContinuousDistribution, SingleContinuousPSpace from sympy.stats.drv import DiscreteDistribution, SingleDiscretePSpace from sympy.stats.frv import SingleFiniteDistribution, SingleFinitePSpace from sympy.stats.crv_types import ContinuousDistributionHandmade from sympy.stats.drv_types import DiscreteDistributionHandmade from sympy.stats.frv_types import FiniteDistributionHandmade class CompoundPSpace(PSpace): """ A temporary Probability Space for the Compound Distribution. After Marginalization, this returns the corresponding Probability Space of the parent distribution. """ def __new__(cls, s, distribution): s = _symbol_converter(s) if isinstance(distribution, ContinuousDistribution): return SingleContinuousPSpace(s, distribution) if isinstance(distribution, DiscreteDistribution): return SingleDiscretePSpace(s, distribution) if isinstance(distribution, SingleFiniteDistribution): return SingleFinitePSpace(s, distribution) if not isinstance(distribution, CompoundDistribution): raise ValueError("%s should be an isinstance of " "CompoundDistribution"%(distribution)) 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 is_Continuous(self): return self.distribution.is_Continuous @property def is_Finite(self): return self.distribution.is_Finite @property def is_Discrete(self): return self.distribution.is_Discrete @property def distribution(self): return self.args[1] @property def pdf(self): return self.distribution.pdf(self.symbol) @property def set(self): return self.distribution.set @property def domain(self): return self._get_newpspace().domain def _get_newpspace(self, evaluate=False): x = Dummy('x') parent_dist = self.distribution.args[0] func = Lambda(x, self.distribution.pdf(x, evaluate)) new_pspace = self._transform_pspace(self.symbol, parent_dist, func) if new_pspace is not None: return new_pspace message = ("Compound Distribution for %s is not implemeted yet" % str(parent_dist)) raise NotImplementedError(message) def _transform_pspace(self, sym, dist, pdf): """ This function returns the new pspace of the distribution using handmade Distributions and their corresponding pspace. """ pdf = Lambda(sym, pdf(sym)) _set = dist.set if isinstance(dist, ContinuousDistribution): return SingleContinuousPSpace(sym, ContinuousDistributionHandmade(pdf, _set)) elif isinstance(dist, DiscreteDistribution): return SingleDiscretePSpace(sym, DiscreteDistributionHandmade(pdf, _set)) elif isinstance(dist, SingleFiniteDistribution): dens = {k: pdf(k) for k in _set} return SingleFinitePSpace(sym, FiniteDistributionHandmade(dens)) def compute_density(self, expr, *, compound_evaluate=True, **kwargs): new_pspace = self._get_newpspace(compound_evaluate) expr = expr.subs({self.value: new_pspace.value}) return new_pspace.compute_density(expr, **kwargs) def compute_cdf(self, expr, *, compound_evaluate=True, **kwargs): new_pspace = self._get_newpspace(compound_evaluate) expr = expr.subs({self.value: new_pspace.value}) return new_pspace.compute_cdf(expr, **kwargs) def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs): new_pspace = self._get_newpspace(evaluate) expr = expr.subs({self.value: new_pspace.value}) if rvs: rvs = rvs.subs({self.value: new_pspace.value}) if isinstance(new_pspace, SingleFinitePSpace): return new_pspace.compute_expectation(expr, rvs, **kwargs) return new_pspace.compute_expectation(expr, rvs, evaluate, **kwargs) def probability(self, condition, *, compound_evaluate=True, **kwargs): new_pspace = self._get_newpspace(compound_evaluate) condition = condition.subs({self.value: new_pspace.value}) return new_pspace.probability(condition) def conditional_space(self, condition, *, compound_evaluate=True, **kwargs): new_pspace = self._get_newpspace(compound_evaluate) condition = condition.subs({self.value: new_pspace.value}) return new_pspace.conditional_space(condition) class CompoundDistribution(Distribution, NamedArgsMixin): """ Class for Compound Distributions. Parameters ========== dist : Distribution Distribution must contain a random parameter Examples ======== >>> from sympy.stats.compound_rv import CompoundDistribution >>> from sympy.stats.crv_types import NormalDistribution >>> from sympy.stats import Normal >>> from sympy.abc import x >>> X = Normal('X', 2, 4) >>> N = NormalDistribution(X, 4) >>> C = CompoundDistribution(N) >>> C.set Interval(-oo, oo) >>> C.pdf(x, evaluate=True).simplify() exp(-x**2/64 + x/16 - 1/16)/(8*sqrt(pi)) References ========== .. [1] https://en.wikipedia.org/wiki/Compound_probability_distribution """ def __new__(cls, dist): if not isinstance(dist, (ContinuousDistribution, SingleFiniteDistribution, DiscreteDistribution)): message = "Compound Distribution for %s is not implemeted yet" % str(dist) raise NotImplementedError(message) if not cls._compound_check(dist): return dist return Basic.__new__(cls, dist) @property def set(self): return self.args[0].set @property def is_Continuous(self): return isinstance(self.args[0], ContinuousDistribution) @property def is_Finite(self): return isinstance(self.args[0], SingleFiniteDistribution) @property def is_Discrete(self): return isinstance(self.args[0], DiscreteDistribution) def pdf(self, x, evaluate=False): dist = self.args[0] randoms = [rv for rv in dist.args if is_random(rv)] if isinstance(dist, SingleFiniteDistribution): y = Dummy('y', integer=True, negative=False) expr = dist.pmf(y) else: y = Dummy('y') expr = dist.pdf(y) for rv in randoms: expr = self._marginalise(expr, rv, evaluate) return Lambda(y, expr)(x) def _marginalise(self, expr, rv, evaluate): if isinstance(rv.pspace.distribution, SingleFiniteDistribution): rv_dens = rv.pspace.distribution.pmf(rv) else: rv_dens = rv.pspace.distribution.pdf(rv) rv_dom = rv.pspace.domain.set if rv.pspace.is_Discrete or rv.pspace.is_Finite: expr = Sum(expr*rv_dens, (rv, rv_dom._inf, rv_dom._sup)) else: expr = Integral(expr*rv_dens, (rv, rv_dom._inf, rv_dom._sup)) if evaluate: return expr.doit() return expr @classmethod def _compound_check(self, dist): """ Checks if the given distribution contains random parameters. """ randoms = [] for arg in dist.args: randoms.extend(random_symbols(arg)) if len(randoms) == 0: return False return True
db32b81b558d243d967f7b4fac9fc2bda5e90dcd747b4167ef8a3b80c281f629
import itertools from sympy import (Expr, Add, Mul, S, Integral, Eq, Sum, Symbol, expand as _expand, Not) from sympy.core.compatibility import default_sort_key from sympy.core.parameters import global_parameters from sympy.core.sympify import _sympify from sympy.core.relational import Relational from sympy.logic.boolalg import Boolean from sympy.stats import variance, covariance from sympy.stats.rv import (RandomSymbol, pspace, dependent, given, sampling_E, RandomIndexedSymbol, is_random, PSpace, sampling_P, random_symbols) __all__ = ['Probability', 'Expectation', 'Variance', 'Covariance'] @is_random.register(Expr) def _(x): atoms = x.free_symbols if len(atoms) == 1 and next(iter(atoms)) == x: return False return any([is_random(i) for i in atoms]) @is_random.register(RandomSymbol) # type: ignore def _(x): return True class Probability(Expr): """ Symbolic expression for the probability. Examples ======== >>> from sympy.stats import Probability, Normal >>> from sympy import Integral >>> X = Normal("X", 0, 1) >>> prob = Probability(X > 1) >>> prob Probability(X > 1) Integral representation: >>> prob.rewrite(Integral) Integral(sqrt(2)*exp(-_z**2/2)/(2*sqrt(pi)), (_z, 1, oo)) Evaluation of the integral: >>> prob.evaluate_integral() sqrt(2)*(-sqrt(2)*sqrt(pi)*erf(sqrt(2)/2) + sqrt(2)*sqrt(pi))/(4*sqrt(pi)) """ def __new__(cls, prob, condition=None, **kwargs): prob = _sympify(prob) if condition is None: obj = Expr.__new__(cls, prob) else: condition = _sympify(condition) obj = Expr.__new__(cls, prob, condition) obj._condition = condition return obj def doit(self, **hints): condition = self.args[0] given_condition = self._condition numsamples = hints.get('numsamples', False) for_rewrite = not hints.get('for_rewrite', False) if isinstance(condition, Not): return S.One - self.func(condition.args[0], given_condition, evaluate=for_rewrite).doit(**hints) if condition.has(RandomIndexedSymbol): return pspace(condition).probability(condition, given_condition, evaluate=for_rewrite) if isinstance(given_condition, RandomSymbol): condrv = random_symbols(condition) if len(condrv) == 1 and condrv[0] == given_condition: from sympy.stats.frv_types import BernoulliDistribution return BernoulliDistribution(self.func(condition).doit(**hints), 0, 1) if any([dependent(rv, given_condition) for rv in condrv]): return Probability(condition, given_condition) else: return Probability(condition).doit() if given_condition is not None and \ not isinstance(given_condition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (given_condition)) if given_condition == False or condition is S.false: return S.Zero if not isinstance(condition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (condition)) if condition is S.true: return S.One if numsamples: return sampling_P(condition, given_condition, numsamples=numsamples) if given_condition is not None: # If there is a condition # Recompute on new conditional expr return Probability(given(condition, given_condition)).doit() # Otherwise pass work off to the ProbabilitySpace if pspace(condition) == PSpace(): return Probability(condition, given_condition) result = pspace(condition).probability(condition) if hasattr(result, 'doit') and for_rewrite: return result.doit() else: return result def _eval_rewrite_as_Integral(self, arg, condition=None, **kwargs): return self.func(arg, condition=condition).doit(for_rewrite=True) _eval_rewrite_as_Sum = _eval_rewrite_as_Integral def evaluate_integral(self): return self.rewrite(Integral).doit() class Expectation(Expr): """ Symbolic expression for the expectation. Examples ======== >>> from sympy.stats import Expectation, Normal, Probability, Poisson >>> from sympy import symbols, Integral, Sum >>> mu = symbols("mu") >>> sigma = symbols("sigma", positive=True) >>> X = Normal("X", mu, sigma) >>> Expectation(X) Expectation(X) >>> Expectation(X).evaluate_integral().simplify() mu To get the integral expression of the expectation: >>> Expectation(X).rewrite(Integral) Integral(sqrt(2)*X*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)) The same integral expression, in more abstract terms: >>> Expectation(X).rewrite(Probability) Integral(x*Probability(Eq(X, x)), (x, -oo, oo)) To get the Summation expression of the expectation for discrete random variables: >>> lamda = symbols('lamda', positive=True) >>> Z = Poisson('Z', lamda) >>> Expectation(Z).rewrite(Sum) Sum(Z*lamda**Z*exp(-lamda)/factorial(Z), (Z, 0, oo)) This class is aware of some properties of the expectation: >>> from sympy.abc import a >>> Expectation(a*X) Expectation(a*X) >>> Y = Normal("Y", 1, 2) >>> Expectation(X + Y) Expectation(X + Y) To expand the ``Expectation`` into its expression, use ``expand()``: >>> Expectation(X + Y).expand() Expectation(X) + Expectation(Y) >>> Expectation(a*X + Y).expand() a*Expectation(X) + Expectation(Y) >>> Expectation(a*X + Y) Expectation(a*X + Y) >>> Expectation((X + Y)*(X - Y)).expand() Expectation(X**2) - Expectation(Y**2) To evaluate the ``Expectation``, use ``doit()``: >>> Expectation(X + Y).doit() mu + 1 >>> Expectation(X + Expectation(Y + Expectation(2*X))).doit() 3*mu + 1 To prevent evaluating nested ``Expectation``, use ``doit(deep=False)`` >>> Expectation(X + Expectation(Y)).doit(deep=False) mu + Expectation(Expectation(Y)) >>> Expectation(X + Expectation(Y + Expectation(2*X))).doit(deep=False) mu + Expectation(Expectation(Y + Expectation(2*X))) """ def __new__(cls, expr, condition=None, **kwargs): expr = _sympify(expr) if expr.is_Matrix: from sympy.stats.symbolic_multivariate_probability import ExpectationMatrix return ExpectationMatrix(expr, condition) if condition is None: if not is_random(expr): return expr obj = Expr.__new__(cls, expr) else: condition = _sympify(condition) obj = Expr.__new__(cls, expr, condition) obj._condition = condition return obj def expand(self, **hints): expr = self.args[0] condition = self._condition if not is_random(expr): return expr if isinstance(expr, Add): return Add.fromiter(Expectation(a, condition=condition).expand() for a in expr.args) expand_expr = _expand(expr) if isinstance(expand_expr, Add): return Add.fromiter(Expectation(a, condition=condition).expand() for a in expand_expr.args) elif isinstance(expr, Mul): rv = [] nonrv = [] for a in expr.args: if is_random(a): rv.append(a) else: nonrv.append(a) return Mul.fromiter(nonrv)*Expectation(Mul.fromiter(rv), condition=condition) return self def doit(self, **hints): deep = hints.get('deep', True) condition = self._condition expr = self.args[0] numsamples = hints.get('numsamples', False) for_rewrite = not hints.get('for_rewrite', False) if deep: expr = expr.doit(**hints) if not is_random(expr) or isinstance(expr, Expectation): # expr isn't random? return expr if numsamples: # Computing by monte carlo sampling? evalf = hints.get('evalf', True) return sampling_E(expr, condition, numsamples=numsamples, evalf=evalf) if expr.has(RandomIndexedSymbol): return pspace(expr).compute_expectation(expr, condition) # Create new expr and recompute E if condition is not None: # If there is a condition return self.func(given(expr, condition)).doit(**hints) # A few known statements for efficiency if expr.is_Add: # We know that E is Linear return Add(*[self.func(arg, condition).doit(**hints) if not isinstance(arg, Expectation) else self.func(arg, condition) for arg in expr.args]) if expr.is_Mul: if expr.atoms(Expectation): return expr if pspace(expr) == PSpace(): return self.func(expr) # Otherwise case is simple, pass work off to the ProbabilitySpace result = pspace(expr).compute_expectation(expr, evaluate=for_rewrite) if hasattr(result, 'doit') and for_rewrite: return result.doit(**hints) else: return result def _eval_rewrite_as_Probability(self, arg, condition=None, **kwargs): rvs = arg.atoms(RandomSymbol) if len(rvs) > 1: raise NotImplementedError() if len(rvs) == 0: return arg rv = rvs.pop() if rv.pspace is None: raise ValueError("Probability space not known") symbol = rv.symbol if symbol.name[0].isupper(): symbol = Symbol(symbol.name.lower()) else : symbol = Symbol(symbol.name + "_1") if rv.pspace.is_Continuous: return Integral(arg.replace(rv, symbol)*Probability(Eq(rv, symbol), condition), (symbol, rv.pspace.domain.set.inf, rv.pspace.domain.set.sup)) else: if rv.pspace.is_Finite: raise NotImplementedError else: return Sum(arg.replace(rv, symbol)*Probability(Eq(rv, symbol), condition), (symbol, rv.pspace.domain.set.inf, rv.pspace.set.sup)) def _eval_rewrite_as_Integral(self, arg, condition=None, **kwargs): return self.func(arg, condition=condition).doit(deep=False, for_rewrite=True) _eval_rewrite_as_Sum = _eval_rewrite_as_Integral # For discrete this will be Sum def evaluate_integral(self): return self.rewrite(Integral).doit() evaluate_sum = evaluate_integral class Variance(Expr): """ Symbolic expression for the variance. Examples ======== >>> from sympy import symbols, Integral >>> from sympy.stats import Normal, Expectation, Variance, Probability >>> mu = symbols("mu", positive=True) >>> sigma = symbols("sigma", positive=True) >>> X = Normal("X", mu, sigma) >>> Variance(X) Variance(X) >>> Variance(X).evaluate_integral() sigma**2 Integral representation of the underlying calculations: >>> Variance(X).rewrite(Integral) Integral(sqrt(2)*(X - Integral(sqrt(2)*X*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)))**2*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)) Integral representation, without expanding the PDF: >>> Variance(X).rewrite(Probability) -Integral(x*Probability(Eq(X, x)), (x, -oo, oo))**2 + Integral(x**2*Probability(Eq(X, x)), (x, -oo, oo)) Rewrite the variance in terms of the expectation >>> Variance(X).rewrite(Expectation) -Expectation(X)**2 + Expectation(X**2) Some transformations based on the properties of the variance may happen: >>> from sympy.abc import a >>> Y = Normal("Y", 0, 1) >>> Variance(a*X) Variance(a*X) To expand the variance in its expression, use ``expand()``: >>> Variance(a*X).expand() a**2*Variance(X) >>> Variance(X + Y) Variance(X + Y) >>> Variance(X + Y).expand() 2*Covariance(X, Y) + Variance(X) + Variance(Y) """ def __new__(cls, arg, condition=None, **kwargs): arg = _sympify(arg) if arg.is_Matrix: from sympy.stats.symbolic_multivariate_probability import VarianceMatrix return VarianceMatrix(arg, condition) if condition is None: obj = Expr.__new__(cls, arg) else: condition = _sympify(condition) obj = Expr.__new__(cls, arg, condition) obj._condition = condition return obj def expand(self, **hints): arg = self.args[0] condition = self._condition if not is_random(arg): return S.Zero if isinstance(arg, RandomSymbol): return self elif isinstance(arg, Add): rv = [] for a in arg.args: if is_random(a): rv.append(a) variances = Add(*map(lambda xv: Variance(xv, condition).expand(), rv)) map_to_covar = lambda x: 2*Covariance(*x, condition=condition).expand() covariances = Add(*map(map_to_covar, itertools.combinations(rv, 2))) return variances + covariances elif isinstance(arg, Mul): nonrv = [] rv = [] for a in arg.args: if is_random(a): rv.append(a) else: nonrv.append(a**2) if len(rv) == 0: return S.Zero return Mul.fromiter(nonrv)*Variance(Mul.fromiter(rv), condition) # this expression contains a RandomSymbol somehow: return self def _eval_rewrite_as_Expectation(self, arg, condition=None, **kwargs): e1 = Expectation(arg**2, condition) e2 = Expectation(arg, condition)**2 return e1 - e2 def _eval_rewrite_as_Probability(self, arg, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Probability) def _eval_rewrite_as_Integral(self, arg, condition=None, **kwargs): return variance(self.args[0], self._condition, evaluate=False) _eval_rewrite_as_Sum = _eval_rewrite_as_Integral def evaluate_integral(self): return self.rewrite(Integral).doit() class Covariance(Expr): """ Symbolic expression for the covariance. Examples ======== >>> from sympy.stats import Covariance >>> from sympy.stats import Normal >>> X = Normal("X", 3, 2) >>> Y = Normal("Y", 0, 1) >>> Z = Normal("Z", 0, 1) >>> W = Normal("W", 0, 1) >>> cexpr = Covariance(X, Y) >>> cexpr Covariance(X, Y) Evaluate the covariance, `X` and `Y` are independent, therefore zero is the result: >>> cexpr.evaluate_integral() 0 Rewrite the covariance expression in terms of expectations: >>> from sympy.stats import Expectation >>> cexpr.rewrite(Expectation) Expectation(X*Y) - Expectation(X)*Expectation(Y) In order to expand the argument, use ``expand()``: >>> from sympy.abc import a, b, c, d >>> Covariance(a*X + b*Y, c*Z + d*W) Covariance(a*X + b*Y, c*Z + d*W) >>> Covariance(a*X + b*Y, c*Z + d*W).expand() a*c*Covariance(X, Z) + a*d*Covariance(W, X) + b*c*Covariance(Y, Z) + b*d*Covariance(W, Y) This class is aware of some properties of the covariance: >>> Covariance(X, X).expand() Variance(X) >>> Covariance(a*X, b*Y).expand() a*b*Covariance(X, Y) """ def __new__(cls, arg1, arg2, condition=None, **kwargs): arg1 = _sympify(arg1) arg2 = _sympify(arg2) if arg1.is_Matrix or arg2.is_Matrix: from sympy.stats.symbolic_multivariate_probability import CrossCovarianceMatrix return CrossCovarianceMatrix(arg1, arg2, condition) if kwargs.pop('evaluate', global_parameters.evaluate): arg1, arg2 = sorted([arg1, arg2], key=default_sort_key) if condition is None: obj = Expr.__new__(cls, arg1, arg2) else: condition = _sympify(condition) obj = Expr.__new__(cls, arg1, arg2, condition) obj._condition = condition return obj def expand(self, **hints): arg1 = self.args[0] arg2 = self.args[1] condition = self._condition if arg1 == arg2: return Variance(arg1, condition).expand() if not is_random(arg1): return S.Zero if not is_random(arg2): return S.Zero arg1, arg2 = sorted([arg1, arg2], key=default_sort_key) if isinstance(arg1, RandomSymbol) and isinstance(arg2, RandomSymbol): return Covariance(arg1, arg2, condition) coeff_rv_list1 = self._expand_single_argument(arg1.expand()) coeff_rv_list2 = self._expand_single_argument(arg2.expand()) addends = [a*b*Covariance(*sorted([r1, r2], key=default_sort_key), condition=condition) for (a, r1) in coeff_rv_list1 for (b, r2) in coeff_rv_list2] return Add.fromiter(addends) @classmethod def _expand_single_argument(cls, expr): # return (coefficient, random_symbol) pairs: if isinstance(expr, RandomSymbol): return [(S.One, expr)] elif isinstance(expr, Add): outval = [] for a in expr.args: if isinstance(a, Mul): outval.append(cls._get_mul_nonrv_rv_tuple(a)) elif is_random(a): outval.append((S.One, a)) return outval elif isinstance(expr, Mul): return [cls._get_mul_nonrv_rv_tuple(expr)] elif is_random(expr): return [(S.One, expr)] @classmethod def _get_mul_nonrv_rv_tuple(cls, m): rv = [] nonrv = [] for a in m.args: if is_random(a): rv.append(a) else: nonrv.append(a) return (Mul.fromiter(nonrv), Mul.fromiter(rv)) def _eval_rewrite_as_Expectation(self, arg1, arg2, condition=None, **kwargs): e1 = Expectation(arg1*arg2, condition) e2 = Expectation(arg1, condition)*Expectation(arg2, condition) return e1 - e2 def _eval_rewrite_as_Probability(self, arg1, arg2, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Probability) def _eval_rewrite_as_Integral(self, arg1, arg2, condition=None, **kwargs): return covariance(self.args[0], self.args[1], self._condition, evaluate=False) _eval_rewrite_as_Sum = _eval_rewrite_as_Integral def evaluate_integral(self): return self.rewrite(Integral).doit() class Moment(Expr): """ Symbolic class for Moment Examples ======== >>> from sympy import Symbol, Integral >>> from sympy.stats import Normal, Expectation, Probability, Moment >>> mu = Symbol('mu', real=True) >>> sigma = Symbol('sigma', real=True, positive=True) >>> X = Normal('X', mu, sigma) >>> M = Moment(X, 3, 1) To evaluate the result of Moment use `doit`: >>> M.doit() mu**3 - 3*mu**2 + 3*mu*sigma**2 + 3*mu - 3*sigma**2 - 1 Rewrite the Moment expression in terms of Expectation: >>> M.rewrite(Expectation) Expectation((X - 1)**3) Rewrite the Moment expression in terms of Probability: >>> M.rewrite(Probability) Integral((x - 1)**3*Probability(Eq(X, x)), (x, -oo, oo)) Rewrite the Moment expression in terms of Integral: >>> M.rewrite(Integral) Integral(sqrt(2)*(X - 1)**3*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)) """ def __new__(cls, X, n, c=0, condition=None, **kwargs): X = _sympify(X) n = _sympify(n) c = _sympify(c) if condition is not None: condition = _sympify(condition) return Expr.__new__(cls, X, n, c, condition) def doit(self, **hints): if not is_random(self.args[0]): return self.args[0] return self.rewrite(Expectation).doit(**hints) def _eval_rewrite_as_Expectation(self, X, n, c=0, condition=None, **kwargs): return Expectation((X - c)**n, condition) def _eval_rewrite_as_Probability(self, X, n, c=0, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Probability) def _eval_rewrite_as_Integral(self, X, n, c=0, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Integral) class CentralMoment(Expr): """ Symbolic class Central Moment Examples ======== >>> from sympy import Symbol, Integral >>> from sympy.stats import Normal, Expectation, Probability, CentralMoment >>> mu = Symbol('mu', real=True) >>> sigma = Symbol('sigma', real=True, positive=True) >>> X = Normal('X', mu, sigma) >>> CM = CentralMoment(X, 4) To evaluate the result of CentralMoment use `doit`: >>> CM.doit().simplify() 3*sigma**4 Rewrite the CentralMoment expression in terms of Expectation: >>> CM.rewrite(Expectation) Expectation((X - Expectation(X))**4) Rewrite the CentralMoment expression in terms of Probability: >>> CM.rewrite(Probability) Integral((x - Integral(x*Probability(True), (x, -oo, oo)))**4*Probability(Eq(X, x)), (x, -oo, oo)) Rewrite the CentralMoment expression in terms of Integral: >>> CM.rewrite(Integral) Integral(sqrt(2)*(X - Integral(sqrt(2)*X*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)))**4*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)) """ def __new__(cls, X, n, condition=None, **kwargs): X = _sympify(X) n = _sympify(n) if condition is not None: condition = _sympify(condition) return Expr.__new__(cls, X, n, condition) def doit(self, **hints): if not is_random(self.args[0]): return self.args[0] return self.rewrite(Expectation).doit(**hints) def _eval_rewrite_as_Expectation(self, X, n, condition=None, **kwargs): mu = Expectation(X, condition, **kwargs) return Moment(X, n, mu, condition, **kwargs).rewrite(Expectation) def _eval_rewrite_as_Probability(self, X, n, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Probability) def _eval_rewrite_as_Integral(self, X, n, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Integral)
7dbb6df1de758b78dba278a3b54e2adb528226dd9ff6f38b322ef624d7c7c866
""" 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) from sympy.external import import_module 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. """ libraries = ['scipy', 'numpy', 'pymc3'] if library not in libraries: raise NotImplementedError("Sampling from %s is not supported yet." % str(library)) if not import_module(library): raise ValueError("Failed to import %s" % library) samps = _get_sample_class_frv[library](self.distribution, size, seed) if samps is not None: return {self.value: samps} raise NotImplementedError( "Sampling for %s is not currently implemented from %s" % (self.__class__.__name__, library) ) class SampleFiniteScipy: """Returns the sample from scipy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_scipy(dist, size, seed) @classmethod def _sample_scipy(cls, dist, size, seed): """Sample from SciPy.""" # 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) class SampleFiniteNumpy: """Returns the sample from numpy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_numpy(dist, size, seed) @classmethod def _sample_numpy(cls, dist, size, seed): """Sample from NumPy.""" import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed numpy_rv_map = { 'BinomialDistribution': lambda dist, size: rand_state.binomial(n=int(dist.n), p=float(dist.p), size=size) } dist_list = numpy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None return numpy_rv_map[dist.__class__.__name__](dist, size) class SampleFinitePymc: """Returns the sample from pymc3 of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_pymc3(dist, size, seed) @classmethod def _sample_pymc3(cls, dist, size, seed): """Sample from PyMC3.""" import pymc3 pymc3_rv_map = { 'BernoulliDistribution': lambda dist: pymc3.Bernoulli('X', p=float(dist.p)), 'BinomialDistribution': lambda dist: pymc3.Binomial('X', n=int(dist.n), p=float(dist.p)) } dist_list = pymc3_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None with pymc3.Model(): pymc3_rv_map[dist.__class__.__name__](dist) return pymc3.sample(size, chains=1, progressbar=False, random_seed=seed)[:]['X'] _get_sample_class_frv = { 'scipy': SampleFiniteScipy, 'pymc3': SampleFinitePymc, 'numpy': SampleFiniteNumpy } 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)
eecde8937ad229244a3830324d257be7f943e7975524f3ac39aab1fa498b8d7e
from sympy import Basic from sympy.stats.joint_rv import ProductPSpace from sympy.stats.rv import ProductDomain, _symbol_converter, Distribution class StochasticPSpace(ProductPSpace): """ Represents probability space of stochastic processes and their random variables. Contains mechanics to do computations for queries of stochastic processes. Initialized by symbol, the specific process and distribution(optional) if the random indexed symbols of the process follows any specific distribution, like, in Bernoulli Process, each random indexed symbol follows Bernoulli distribution. For processes with memory, this parameter should not be passed. """ def __new__(cls, sym, process, distribution=None): sym = _symbol_converter(sym) from sympy.stats.stochastic_process_types import StochasticProcess if not isinstance(process, StochasticProcess): raise TypeError("`process` must be an instance of StochasticProcess.") if distribution is None: distribution = Distribution() return Basic.__new__(cls, sym, process, distribution) @property def process(self): """ The associated stochastic process. """ return self.args[1] @property def domain(self): return ProductDomain(self.process.index_set, self.process.state_space) @property def symbol(self): return self.args[0] @property def distribution(self): return self.args[2] def probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Transfers the task of handling queries to the specific stochastic process because every process has their own logic of handling such queries. """ return self.process.probability(condition, given_condition, evaluate, **kwargs) def compute_expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Transfers the task of handling queries to the specific stochastic process because every process has their own logic of handling such queries. """ return self.process.expectation(expr, condition, evaluate, **kwargs)
b1e2489ec781418959f16f477fa139f13e3f52f7c33613439e259b8de1ee63b9
from sympy.core.add import Add from sympy.core.compatibility import is_sequence from sympy.core.containers import Tuple from sympy.core.expr import Expr from sympy.core.mul import Mul from sympy.core.relational import Equality, Relational from sympy.core.singleton import S from sympy.core.symbol import Symbol, Dummy from sympy.core.sympify import sympify from sympy.functions.elementary.piecewise import (piecewise_fold, Piecewise) from sympy.logic.boolalg import BooleanFunction from sympy.tensor.indexed import Idx from sympy.sets.sets import Interval from sympy.sets.fancysets import Range from sympy.utilities import flatten from sympy.utilities.iterables import sift from sympy.utilities.exceptions import SymPyDeprecationWarning def _common_new(cls, function, *symbols, **assumptions): """Return either a special return value or the tuple, (function, limits, orientation). This code is common to both ExprWithLimits and AddWithLimits.""" function = sympify(function) if isinstance(function, Equality): # This transforms e.g. Integral(Eq(x, y)) to Eq(Integral(x), Integral(y)) # but that is only valid for definite integrals. limits, orientation = _process_limits(*symbols) if not (limits and all(len(limit) == 3 for limit in limits)): SymPyDeprecationWarning( feature='Integral(Eq(x, y))', useinstead='Eq(Integral(x, z), Integral(y, z))', issue=18053, deprecated_since_version=1.6, ).warn() lhs = function.lhs rhs = function.rhs return Equality(cls(lhs, *symbols, **assumptions), \ cls(rhs, *symbols, **assumptions)) if function is S.NaN: return S.NaN if symbols: limits, orientation = _process_limits(*symbols) for i, li in enumerate(limits): if len(li) == 4: function = function.subs(li[0], li[-1]) limits[i] = Tuple(*li[:-1]) else: # symbol not provided -- we can still try to compute a general form free = function.free_symbols if len(free) != 1: raise ValueError( "specify dummy variables for %s" % function) limits, orientation = [Tuple(s) for s in free], 1 # denest any nested calls while cls == type(function): limits = list(function.limits) + limits function = function.function # Any embedded piecewise functions need to be brought out to the # top level. We only fold Piecewise that contain the integration # variable. reps = {} symbols_of_integration = {i[0] for i in limits} for p in function.atoms(Piecewise): if not p.has(*symbols_of_integration): reps[p] = Dummy() # mask off those that don't function = function.xreplace(reps) # do the fold function = piecewise_fold(function) # remove the masking function = function.xreplace({v: k for k, v in reps.items()}) return function, limits, orientation def _process_limits(*symbols): """Process the list of symbols and convert them to canonical limits, storing them as Tuple(symbol, lower, upper). The orientation of the function is also returned when the upper limit is missing so (x, 1, None) becomes (x, None, 1) and the orientation is changed. """ limits = [] orientation = 1 for V in symbols: if isinstance(V, (Relational, BooleanFunction)): variable = V.atoms(Symbol).pop() V = (variable, V.as_set()) if isinstance(V, Symbol) or getattr(V, '_diff_wrt', False): if isinstance(V, Idx): if V.lower is None or V.upper is None: limits.append(Tuple(V)) else: limits.append(Tuple(V, V.lower, V.upper)) else: limits.append(Tuple(V)) continue elif is_sequence(V, Tuple): if len(V) == 2 and isinstance(V[1], Range): lo = V[1].inf hi = V[1].sup dx = abs(V[1].step) V = [V[0]] + [0, (hi - lo)//dx, dx*V[0] + lo] V = sympify(flatten(V)) # a list of sympified elements if isinstance(V[0], (Symbol, Idx)) or getattr(V[0], '_diff_wrt', False): newsymbol = V[0] if len(V) == 2 and isinstance(V[1], Interval): # 2 -> 3 # Interval V[1:] = [V[1].start, V[1].end] elif len(V) == 3: # general case if V[2] is None and not V[1] is None: orientation *= -1 V = [newsymbol] + [i for i in V[1:] if i is not None] if not isinstance(newsymbol, Idx) or len(V) == 3: if len(V) == 4: limits.append(Tuple(*V)) continue if len(V) == 3: if isinstance(newsymbol, Idx): # Idx represents an integer which may have # specified values it can take on; if it is # given such a value, an error is raised here # if the summation would try to give it a larger # or smaller value than permitted. None and Symbolic # values will not raise an error. lo, hi = newsymbol.lower, newsymbol.upper try: if lo is not None and not bool(V[1] >= lo): raise ValueError("Summation will set Idx value too low.") except TypeError: pass try: if hi is not None and not bool(V[2] <= hi): raise ValueError("Summation will set Idx value too high.") except TypeError: pass limits.append(Tuple(*V)) continue if len(V) == 1 or (len(V) == 2 and V[1] is None): limits.append(Tuple(newsymbol)) continue elif len(V) == 2: limits.append(Tuple(newsymbol, V[1])) continue raise ValueError('Invalid limits given: %s' % str(symbols)) return limits, orientation class ExprWithLimits(Expr): __slots__ = ('is_commutative',) def __new__(cls, function, *symbols, **assumptions): pre = _common_new(cls, function, *symbols, **assumptions) if type(pre) is tuple: function, limits, _ = pre else: return pre # limits must have upper and lower bounds; the indefinite form # is not supported. This restriction does not apply to AddWithLimits if any(len(l) != 3 or None in l for l in limits): raise ValueError('ExprWithLimits requires values for lower and upper bounds.') obj = Expr.__new__(cls, **assumptions) arglist = [function] arglist.extend(limits) obj._args = tuple(arglist) obj.is_commutative = function.is_commutative # limits already checked return obj @property def function(self): """Return the function applied across limits. Examples ======== >>> from sympy import Integral >>> from sympy.abc import x >>> Integral(x**2, (x,)).function x**2 See Also ======== limits, variables, free_symbols """ return self._args[0] @property def kind(self): return self.function.kind @property def limits(self): """Return the limits of expression. Examples ======== >>> from sympy import Integral >>> from sympy.abc import x, i >>> Integral(x**i, (i, 1, 3)).limits ((i, 1, 3),) See Also ======== function, variables, free_symbols """ return self._args[1:] @property def variables(self): """Return a list of the limit variables. >>> from sympy import Sum >>> from sympy.abc import x, i >>> Sum(x**i, (i, 1, 3)).variables [i] See Also ======== function, limits, free_symbols as_dummy : Rename dummy variables sympy.integrals.integrals.Integral.transform : Perform mapping on the dummy variable """ return [l[0] for l in self.limits] @property def bound_symbols(self): """Return only variables that are dummy variables. Examples ======== >>> from sympy import Integral >>> from sympy.abc import x, i, j, k >>> Integral(x**i, (i, 1, 3), (j, 2), k).bound_symbols [i, j] See Also ======== function, limits, free_symbols as_dummy : Rename dummy variables sympy.integrals.integrals.Integral.transform : Perform mapping on the dummy variable """ return [l[0] for l in self.limits if len(l) != 1] @property def free_symbols(self): """ This method returns the symbols in the object, excluding those that take on a specific value (i.e. the dummy symbols). Examples ======== >>> from sympy import Sum >>> from sympy.abc import x, y >>> Sum(x, (x, y, 1)).free_symbols {y} """ # don't test for any special values -- nominal free symbols # should be returned, e.g. don't return set() if the # function is zero -- treat it like an unevaluated expression. function, limits = self.function, self.limits isyms = function.free_symbols for xab in limits: if len(xab) == 1: isyms.add(xab[0]) continue # take out the target symbol if xab[0] in isyms: isyms.remove(xab[0]) # add in the new symbols for i in xab[1:]: isyms.update(i.free_symbols) return isyms @property def is_number(self): """Return True if the Sum has no free symbols, else False.""" return not self.free_symbols def _eval_interval(self, x, a, b): limits = [(i if i[0] != x else (x, a, b)) for i in self.limits] integrand = self.function return self.func(integrand, *limits) def _eval_subs(self, old, new): """ Perform substitutions over non-dummy variables of an expression with limits. Also, can be used to specify point-evaluation of an abstract antiderivative. Examples ======== >>> from sympy import Sum, oo >>> from sympy.abc import s, n >>> Sum(1/n**s, (n, 1, oo)).subs(s, 2) Sum(n**(-2), (n, 1, oo)) >>> from sympy import Integral >>> from sympy.abc import x, a >>> Integral(a*x**2, x).subs(x, 4) Integral(a*x**2, (x, 4)) See Also ======== variables : Lists the integration variables transform : Perform mapping on the dummy variable for integrals change_index : Perform mapping on the sum and product dummy variables """ from sympy.core.function import AppliedUndef, UndefinedFunction func, limits = self.function, list(self.limits) # If one of the expressions we are replacing is used as a func index # one of two things happens. # - the old variable first appears as a free variable # so we perform all free substitutions before it becomes # a func index. # - the old variable first appears as a func index, in # which case we ignore. See change_index. # Reorder limits to match standard mathematical practice for scoping limits.reverse() if not isinstance(old, Symbol) or \ old.free_symbols.intersection(self.free_symbols): sub_into_func = True for i, xab in enumerate(limits): if 1 == len(xab) and old == xab[0]: if new._diff_wrt: xab = (new,) else: xab = (old, old) limits[i] = Tuple(xab[0], *[l._subs(old, new) for l in xab[1:]]) if len(xab[0].free_symbols.intersection(old.free_symbols)) != 0: sub_into_func = False break if isinstance(old, AppliedUndef) or isinstance(old, UndefinedFunction): sy2 = set(self.variables).intersection(set(new.atoms(Symbol))) sy1 = set(self.variables).intersection(set(old.args)) if not sy2.issubset(sy1): raise ValueError( "substitution can not create dummy dependencies") sub_into_func = True if sub_into_func: func = func.subs(old, new) else: # old is a Symbol and a dummy variable of some limit for i, xab in enumerate(limits): if len(xab) == 3: limits[i] = Tuple(xab[0], *[l._subs(old, new) for l in xab[1:]]) if old == xab[0]: break # simplify redundant limits (x, x) to (x, ) for i, xab in enumerate(limits): if len(xab) == 2 and (xab[0] - xab[1]).is_zero: limits[i] = Tuple(xab[0], ) # Reorder limits back to representation-form limits.reverse() return self.func(func, *limits) @property def has_finite_limits(self): """ Returns True if the limits are known to be finite, either by the explicit bounds, assumptions on the bounds, or assumptions on the variables. False if known to be infinite, based on the bounds. None if not enough information is available to determine. Examples ======== >>> from sympy import Sum, Integral, Product, oo, Symbol >>> x = Symbol('x') >>> Sum(x, (x, 1, 8)).has_finite_limits True >>> Integral(x, (x, 1, oo)).has_finite_limits False >>> M = Symbol('M') >>> Sum(x, (x, 1, M)).has_finite_limits >>> N = Symbol('N', integer=True) >>> Product(x, (x, 1, N)).has_finite_limits True See Also ======== has_reversed_limits """ ret_None = False for lim in self.limits: if len(lim) == 3: if any(l.is_infinite for l in lim[1:]): # Any of the bounds are +/-oo return False elif any(l.is_infinite is None for l in lim[1:]): # Maybe there are assumptions on the variable? if lim[0].is_infinite is None: ret_None = True else: if lim[0].is_infinite is None: ret_None = True if ret_None: return None return True @property def has_reversed_limits(self): """ Returns True if the limits are known to be in reversed order, either by the explicit bounds, assumptions on the bounds, or assumptions on the variables. False if known to be in normal order, based on the bounds. None if not enough information is available to determine. Examples ======== >>> from sympy import Sum, Integral, Product, oo, Symbol >>> x = Symbol('x') >>> Sum(x, (x, 8, 1)).has_reversed_limits True >>> Sum(x, (x, 1, oo)).has_reversed_limits False >>> M = Symbol('M') >>> Integral(x, (x, 1, M)).has_reversed_limits >>> N = Symbol('N', integer=True, positive=True) >>> Sum(x, (x, 1, N)).has_reversed_limits False >>> Product(x, (x, 2, N)).has_reversed_limits >>> Product(x, (x, 2, N)).subs(N, N + 2).has_reversed_limits False See Also ======== sympy.concrete.expr_with_intlimits.ExprWithIntLimits.has_empty_sequence """ ret_None = False for lim in self.limits: if len(lim) == 3: var, a, b = lim dif = b - a if dif.is_extended_negative: return True elif dif.is_extended_nonnegative: continue else: ret_None = True else: return None if ret_None: return None return False class AddWithLimits(ExprWithLimits): r"""Represents unevaluated oriented additions. Parent class for Integral and Sum. """ def __new__(cls, function, *symbols, **assumptions): pre = _common_new(cls, function, *symbols, **assumptions) if type(pre) is tuple: function, limits, orientation = pre else: return pre obj = Expr.__new__(cls, **assumptions) arglist = [orientation*function] # orientation not used in ExprWithLimits arglist.extend(limits) obj._args = tuple(arglist) obj.is_commutative = function.is_commutative # limits already checked return obj def _eval_adjoint(self): if all([x.is_real for x in flatten(self.limits)]): return self.func(self.function.adjoint(), *self.limits) return None def _eval_conjugate(self): if all([x.is_real for x in flatten(self.limits)]): return self.func(self.function.conjugate(), *self.limits) return None def _eval_transpose(self): if all([x.is_real for x in flatten(self.limits)]): return self.func(self.function.transpose(), *self.limits) return None def _eval_factor(self, **hints): if 1 == len(self.limits): summand = self.function.factor(**hints) if summand.is_Mul: out = sift(summand.args, lambda w: w.is_commutative \ and not set(self.variables) & w.free_symbols) return Mul(*out[True])*self.func(Mul(*out[False]), \ *self.limits) else: summand = self.func(self.function, *self.limits[0:-1]).factor() if not summand.has(self.variables[-1]): return self.func(1, [self.limits[-1]]).doit()*summand elif isinstance(summand, Mul): return self.func(summand, self.limits[-1]).factor() return self def _eval_expand_basic(self, **hints): from sympy.matrices.matrices import MatrixBase summand = self.function.expand(**hints) if summand.is_Add and summand.is_commutative: return Add(*[self.func(i, *self.limits) for i in summand.args]) elif isinstance(summand, MatrixBase): return summand.applyfunc(lambda x: self.func(x, *self.limits)) elif summand != self.function: return self.func(summand, *self.limits) return self
93e3f0ce620f75996b12b90c51fa9eeed7ea22dc2866a4f8555abc611885fa00
from sympy.calculus.singularities import is_decreasing from sympy.calculus.util import AccumulationBounds from sympy.concrete.expr_with_limits import AddWithLimits from sympy.concrete.expr_with_intlimits import ExprWithIntLimits from sympy.concrete.gosper import gosper_sum from sympy.core.add import Add from sympy.core.function import Derivative from sympy.core.mul import Mul from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import Dummy, Wild, Symbol from sympy.functions.special.zeta_functions import zeta from sympy.functions.elementary.piecewise import Piecewise from sympy.logic.boolalg import And from sympy.polys import apart, PolynomialError, together from sympy.series.limitseq import limit_seq from sympy.series.order import O from sympy.sets.sets import FiniteSet from sympy.simplify import denom from sympy.simplify.combsimp import combsimp from sympy.simplify.powsimp import powsimp from sympy.solvers import solve from sympy.solvers.solveset import solveset import itertools class Sum(AddWithLimits, ExprWithIntLimits): r""" Represents unevaluated summation. Explanation =========== ``Sum`` represents a finite or infinite series, with the first argument being the general form of terms in the series, and the second argument being ``(dummy_variable, start, end)``, with ``dummy_variable`` taking all integer values from ``start`` through ``end``. In accordance with long-standing mathematical convention, the end term is included in the summation. Finite sums =========== For finite sums (and sums with symbolic limits assumed to be finite) we follow the summation convention described by Karr [1], especially definition 3 of section 1.4. The sum: .. math:: \sum_{m \leq i < n} f(i) has *the obvious meaning* for `m < n`, namely: .. math:: \sum_{m \leq i < n} f(i) = f(m) + f(m+1) + \ldots + f(n-2) + f(n-1) with the upper limit value `f(n)` excluded. The sum over an empty set is zero if and only if `m = n`: .. math:: \sum_{m \leq i < n} f(i) = 0 \quad \mathrm{for} \quad m = n Finally, for all other sums over empty sets we assume the following definition: .. math:: \sum_{m \leq i < n} f(i) = - \sum_{n \leq i < m} f(i) \quad \mathrm{for} \quad m > n It is important to note that Karr defines all sums with the upper limit being exclusive. This is in contrast to the usual mathematical notation, but does not affect the summation convention. Indeed we have: .. math:: \sum_{m \leq i < n} f(i) = \sum_{i = m}^{n - 1} f(i) where the difference in notation is intentional to emphasize the meaning, with limits typeset on the top being inclusive. Examples ======== >>> from sympy.abc import i, k, m, n, x >>> from sympy import Sum, factorial, oo, IndexedBase, Function >>> Sum(k, (k, 1, m)) Sum(k, (k, 1, m)) >>> Sum(k, (k, 1, m)).doit() m**2/2 + m/2 >>> Sum(k**2, (k, 1, m)) Sum(k**2, (k, 1, m)) >>> Sum(k**2, (k, 1, m)).doit() m**3/3 + m**2/2 + m/6 >>> Sum(x**k, (k, 0, oo)) Sum(x**k, (k, 0, oo)) >>> Sum(x**k, (k, 0, oo)).doit() Piecewise((1/(1 - x), Abs(x) < 1), (Sum(x**k, (k, 0, oo)), True)) >>> Sum(x**k/factorial(k), (k, 0, oo)).doit() exp(x) Here are examples to do summation with symbolic indices. You can use either Function of IndexedBase classes: >>> f = Function('f') >>> Sum(f(n), (n, 0, 3)).doit() f(0) + f(1) + f(2) + f(3) >>> Sum(f(n), (n, 0, oo)).doit() Sum(f(n), (n, 0, oo)) >>> f = IndexedBase('f') >>> Sum(f[n]**2, (n, 0, 3)).doit() f[0]**2 + f[1]**2 + f[2]**2 + f[3]**2 An example showing that the symbolic result of a summation is still valid for seemingly nonsensical values of the limits. Then the Karr convention allows us to give a perfectly valid interpretation to those sums by interchanging the limits according to the above rules: >>> S = Sum(i, (i, 1, n)).doit() >>> S n**2/2 + n/2 >>> S.subs(n, -4) 6 >>> Sum(i, (i, 1, -4)).doit() 6 >>> Sum(-i, (i, -3, 0)).doit() 6 An explicit example of the Karr summation convention: >>> S1 = Sum(i**2, (i, m, m+n-1)).doit() >>> S1 m**2*n + m*n**2 - m*n + n**3/3 - n**2/2 + n/6 >>> S2 = Sum(i**2, (i, m+n, m-1)).doit() >>> S2 -m**2*n - m*n**2 + m*n - n**3/3 + n**2/2 - n/6 >>> S1 + S2 0 >>> S3 = Sum(i, (i, m, m-1)).doit() >>> S3 0 See Also ======== summation Product, sympy.concrete.products.product References ========== .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM, Volume 28 Issue 2, April 1981, Pages 305-350 http://dl.acm.org/citation.cfm?doid=322248.322255 .. [2] https://en.wikipedia.org/wiki/Summation#Capital-sigma_notation .. [3] https://en.wikipedia.org/wiki/Empty_sum """ __slots__ = ('is_commutative',) def __new__(cls, function, *symbols, **assumptions): obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions) if not hasattr(obj, 'limits'): return obj if any(len(l) != 3 or None in l for l in obj.limits): raise ValueError('Sum requires values for lower and upper bounds.') return obj def _eval_is_zero(self): # a Sum is only zero if its function is zero or if all terms # cancel out. This only answers whether the summand is zero; if # not then None is returned since we don't analyze whether all # terms cancel out. if self.function.is_zero or self.has_empty_sequence: return True def _eval_is_extended_real(self): if self.has_empty_sequence: return True return self.function.is_extended_real def _eval_is_positive(self): if self.has_finite_limits and self.has_reversed_limits is False: return self.function.is_positive def _eval_is_negative(self): if self.has_finite_limits and self.has_reversed_limits is False: return self.function.is_negative def _eval_is_finite(self): if self.has_finite_limits and self.function.is_finite: return True def doit(self, **hints): if hints.get('deep', True): f = self.function.doit(**hints) else: f = self.function # first make sure any definite limits have summation # variables with matching assumptions reps = {} for xab in self.limits: d = _dummy_with_inherited_properties_concrete(xab) if d: reps[xab[0]] = d if reps: undo = {v: k for k, v in reps.items()} did = self.xreplace(reps).doit(**hints) if type(did) is tuple: # when separate=True did = tuple([i.xreplace(undo) for i in did]) elif did is not None: did = did.xreplace(undo) else: did = self return did if self.function.is_Matrix: expanded = self.expand() if self != expanded: return expanded.doit() return _eval_matrix_sum(self) for n, limit in enumerate(self.limits): i, a, b = limit dif = b - a if dif == -1: # Any summation over an empty set is zero return S.Zero if dif.is_integer and dif.is_negative: a, b = b + 1, a - 1 f = -f newf = eval_sum(f, (i, a, b)) if newf is None: if f == self.function: zeta_function = self.eval_zeta_function(f, (i, a, b)) if zeta_function is not None: return zeta_function return self else: return self.func(f, *self.limits[n:]) f = newf if hints.get('deep', True): # eval_sum could return partially unevaluated # result with Piecewise. In this case we won't # doit() recursively. if not isinstance(f, Piecewise): return f.doit(**hints) return f def eval_zeta_function(self, f, limits): """ Check whether the function matches with the zeta function. If it matches, then return a `Piecewise` expression because zeta function does not converge unless `s > 1` and `q > 0` """ i, a, b = limits w, y, z = Wild('w', exclude=[i]), Wild('y', exclude=[i]), Wild('z', exclude=[i]) result = f.match((w * i + y) ** (-z)) if result is not None and b is S.Infinity: coeff = 1 / result[w] ** result[z] s = result[z] q = result[y] / result[w] + a return Piecewise((coeff * zeta(s, q), And(q > 0, s > 1)), (self, True)) def _eval_derivative(self, x): """ Differentiate wrt x as long as x is not in the free symbols of any of the upper or lower limits. Explanation =========== Sum(a*b*x, (x, 1, a)) can be differentiated wrt x or b but not `a` since the value of the sum is discontinuous in `a`. In a case involving a limit variable, the unevaluated derivative is returned. """ # diff already confirmed that x is in the free symbols of self, but we # don't want to differentiate wrt any free symbol in the upper or lower # limits # XXX remove this test for free_symbols when the default _eval_derivative is in if isinstance(x, Symbol) and x not in self.free_symbols: return S.Zero # get limits and the function f, limits = self.function, list(self.limits) limit = limits.pop(-1) if limits: # f is the argument to a Sum f = self.func(f, *limits) _, a, b = limit if x in a.free_symbols or x in b.free_symbols: return None df = Derivative(f, x, evaluate=True) rv = self.func(df, limit) return rv def _eval_difference_delta(self, n, step): k, _, upper = self.args[-1] new_upper = upper.subs(n, n + step) if len(self.args) == 2: f = self.args[0] else: f = self.func(*self.args[:-1]) return Sum(f, (k, upper + 1, new_upper)).doit() def _eval_simplify(self, **kwargs): from sympy.simplify.simplify import factor_sum, sum_combine from sympy.core.function import expand from sympy.core.mul import Mul # split the function into adds terms = Add.make_args(expand(self.function)) s_t = [] # Sum Terms o_t = [] # Other Terms for term in terms: if term.has(Sum): # if there is an embedded sum here # it is of the form x * (Sum(whatever)) # hence we make a Mul out of it, and simplify all interior sum terms subterms = Mul.make_args(expand(term)) out_terms = [] for subterm in subterms: # go through each term if isinstance(subterm, Sum): # if it's a sum, simplify it out_terms.append(subterm._eval_simplify()) else: # otherwise, add it as is out_terms.append(subterm) # turn it back into a Mul s_t.append(Mul(*out_terms)) else: o_t.append(term) # next try to combine any interior sums for further simplification result = Add(sum_combine(s_t), *o_t) return factor_sum(result, limits=self.limits) def is_convergent(self): r""" Checks for the convergence of a Sum. Explanation =========== We divide the study of convergence of infinite sums and products in two parts. First Part: One part is the question whether all the terms are well defined, i.e., they are finite in a sum and also non-zero in a product. Zero is the analogy of (minus) infinity in products as :math:`e^{-\infty} = 0`. Second Part: The second part is the question of convergence after infinities, and zeros in products, have been omitted assuming that their number is finite. This means that we only consider the tail of the sum or product, starting from some point after which all terms are well defined. For example, in a sum of the form: .. math:: \sum_{1 \leq i < \infty} \frac{1}{n^2 + an + b} where a and b are numbers. The routine will return true, even if there are infinities in the term sequence (at most two). An analogous product would be: .. math:: \prod_{1 \leq i < \infty} e^{\frac{1}{n^2 + an + b}} This is how convergence is interpreted. It is concerned with what happens at the limit. Finding the bad terms is another independent matter. Note: It is responsibility of user to see that the sum or product is well defined. There are various tests employed to check the convergence like divergence test, root test, integral test, alternating series test, comparison tests, Dirichlet tests. It returns true if Sum is convergent and false if divergent and NotImplementedError if it can not be checked. References ========== .. [1] https://en.wikipedia.org/wiki/Convergence_tests Examples ======== >>> from sympy import factorial, S, Sum, Symbol, oo >>> n = Symbol('n', integer=True) >>> Sum(n/(n - 1), (n, 4, 7)).is_convergent() True >>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent() False >>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent() False >>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent() True See Also ======== Sum.is_absolutely_convergent() sympy.concrete.products.Product.is_convergent() """ from sympy import Interval, Integral, log, symbols, simplify p, q, r = symbols('p q r', cls=Wild) sym = self.limits[0][0] lower_limit = self.limits[0][1] upper_limit = self.limits[0][2] sequence_term = self.function.simplify() if len(sequence_term.free_symbols) > 1: raise NotImplementedError("convergence checking for more than one symbol " "containing series is not handled") if lower_limit.is_finite and upper_limit.is_finite: return S.true # transform sym -> -sym and swap the upper_limit = S.Infinity # and lower_limit = - upper_limit if lower_limit is S.NegativeInfinity: if upper_limit is S.Infinity: return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \ Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent() sequence_term = simplify(sequence_term.xreplace({sym: -sym})) lower_limit = -upper_limit upper_limit = S.Infinity sym_ = Dummy(sym.name, integer=True, positive=True) sequence_term = sequence_term.xreplace({sym: sym_}) sym = sym_ interval = Interval(lower_limit, upper_limit) # Piecewise function handle if sequence_term.is_Piecewise: for func, cond in sequence_term.args: # see if it represents something going to oo if cond == True or cond.as_set().sup is S.Infinity: s = Sum(func, (sym, lower_limit, upper_limit)) return s.is_convergent() return S.true ### -------- Divergence test ----------- ### try: lim_val = limit_seq(sequence_term, sym) if lim_val is not None and lim_val.is_zero is False: return S.false except NotImplementedError: pass try: lim_val_abs = limit_seq(abs(sequence_term), sym) if lim_val_abs is not None and lim_val_abs.is_zero is False: return S.false except NotImplementedError: pass order = O(sequence_term, (sym, S.Infinity)) ### --------- p-series test (1/n**p) ---------- ### p_series_test = order.expr.match(sym**p) if p_series_test is not None: if p_series_test[p] < -1: return S.true if p_series_test[p] >= -1: return S.false ### ------------- comparison test ------------- ### # 1/(n**p*log(n)**q*log(log(n))**r) comparison n_log_test = order.expr.match(1/(sym**p*log(sym)**q*log(log(sym))**r)) if n_log_test is not None: if (n_log_test[p] > 1 or (n_log_test[p] == 1 and n_log_test[q] > 1) or (n_log_test[p] == n_log_test[q] == 1 and n_log_test[r] > 1)): return S.true return S.false ### ------------- Limit comparison test -----------### # (1/n) comparison try: lim_comp = limit_seq(sym*sequence_term, sym) if lim_comp is not None and lim_comp.is_number and lim_comp > 0: return S.false except NotImplementedError: pass ### ----------- ratio test ---------------- ### next_sequence_term = sequence_term.xreplace({sym: sym + 1}) ratio = combsimp(powsimp(next_sequence_term/sequence_term)) try: lim_ratio = limit_seq(ratio, sym) if lim_ratio is not None and lim_ratio.is_number: if abs(lim_ratio) > 1: return S.false if abs(lim_ratio) < 1: return S.true except NotImplementedError: lim_ratio = None ### ---------- Raabe's test -------------- ### if lim_ratio == 1: # ratio test inconclusive test_val = sym*(sequence_term/ sequence_term.subs(sym, sym + 1) - 1) test_val = test_val.gammasimp() try: lim_val = limit_seq(test_val, sym) if lim_val is not None and lim_val.is_number: if lim_val > 1: return S.true if lim_val < 1: return S.false except NotImplementedError: pass ### ----------- root test ---------------- ### # lim = Limit(abs(sequence_term)**(1/sym), sym, S.Infinity) try: lim_evaluated = limit_seq(abs(sequence_term)**(1/sym), sym) if lim_evaluated is not None and lim_evaluated.is_number: if lim_evaluated < 1: return S.true if lim_evaluated > 1: return S.false except NotImplementedError: pass ### ------------- alternating series test ----------- ### dict_val = sequence_term.match((-1)**(sym + p)*q) if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval): return S.true ### ------------- integral test -------------- ### check_interval = None maxima = solveset(sequence_term.diff(sym), sym, interval) if not maxima: check_interval = interval elif isinstance(maxima, FiniteSet) and maxima.sup.is_number: check_interval = Interval(maxima.sup, interval.sup) if (check_interval is not None and (is_decreasing(sequence_term, check_interval) or is_decreasing(-sequence_term, check_interval))): integral_val = Integral( sequence_term, (sym, lower_limit, upper_limit)) try: integral_val_evaluated = integral_val.doit() if integral_val_evaluated.is_number: return S(integral_val_evaluated.is_finite) except NotImplementedError: pass ### ----- Dirichlet and bounded times convergent tests ----- ### # TODO # # Dirichlet_test # https://en.wikipedia.org/wiki/Dirichlet%27s_test # # Bounded times convergent test # It is based on comparison theorems for series. # In particular, if the general term of a series can # be written as a product of two terms a_n and b_n # and if a_n is bounded and if Sum(b_n) is absolutely # convergent, then the original series Sum(a_n * b_n) # is absolutely convergent and so convergent. # # The following code can grows like 2**n where n is the # number of args in order.expr # Possibly combined with the potentially slow checks # inside the loop, could make this test extremely slow # for larger summation expressions. if order.expr.is_Mul: args = order.expr.args argset = set(args) ### -------------- Dirichlet tests -------------- ### m = Dummy('m', integer=True) def _dirichlet_test(g_n): try: ing_val = limit_seq(Sum(g_n, (sym, interval.inf, m)).doit(), m) if ing_val is not None and ing_val.is_finite: return S.true except NotImplementedError: pass ### -------- bounded times convergent test ---------### def _bounded_convergent_test(g1_n, g2_n): try: lim_val = limit_seq(g1_n, sym) if lim_val is not None and (lim_val.is_finite or ( isinstance(lim_val, AccumulationBounds) and (lim_val.max - lim_val.min).is_finite)): if Sum(g2_n, (sym, lower_limit, upper_limit)).is_absolutely_convergent(): return S.true except NotImplementedError: pass for n in range(1, len(argset)): for a_tuple in itertools.combinations(args, n): b_set = argset - set(a_tuple) a_n = Mul(*a_tuple) b_n = Mul(*b_set) if is_decreasing(a_n, interval): dirich = _dirichlet_test(b_n) if dirich is not None: return dirich bc_test = _bounded_convergent_test(a_n, b_n) if bc_test is not None: return bc_test _sym = self.limits[0][0] sequence_term = sequence_term.xreplace({sym: _sym}) raise NotImplementedError("The algorithm to find the Sum convergence of %s " "is not yet implemented" % (sequence_term)) def is_absolutely_convergent(self): """ Checks for the absolute convergence of an infinite series. Same as checking convergence of absolute value of sequence_term of an infinite series. References ========== .. [1] https://en.wikipedia.org/wiki/Absolute_convergence Examples ======== >>> from sympy import Sum, Symbol, oo >>> n = Symbol('n', integer=True) >>> Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent() False >>> Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent() True See Also ======== Sum.is_convergent() """ return Sum(abs(self.function), self.limits).is_convergent() def euler_maclaurin(self, m=0, n=0, eps=0, eval_integral=True): """ Return an Euler-Maclaurin approximation of self, where m is the number of leading terms to sum directly and n is the number of terms in the tail. With m = n = 0, this is simply the corresponding integral plus a first-order endpoint correction. Returns (s, e) where s is the Euler-Maclaurin approximation and e is the estimated error (taken to be the magnitude of the first omitted term in the tail): >>> from sympy.abc import k, a, b >>> from sympy import Sum >>> Sum(1/k, (k, 2, 5)).doit().evalf() 1.28333333333333 >>> s, e = Sum(1/k, (k, 2, 5)).euler_maclaurin() >>> s -log(2) + 7/20 + log(5) >>> from sympy import sstr >>> print(sstr((s.evalf(), e.evalf()), full_prec=True)) (1.26629073187415, 0.0175000000000000) The endpoints may be symbolic: >>> s, e = Sum(1/k, (k, a, b)).euler_maclaurin() >>> s -log(a) + log(b) + 1/(2*b) + 1/(2*a) >>> e Abs(1/(12*b**2) - 1/(12*a**2)) If the function is a polynomial of degree at most 2n+1, the Euler-Maclaurin formula becomes exact (and e = 0 is returned): >>> Sum(k, (k, 2, b)).euler_maclaurin() (b**2/2 + b/2 - 1, 0) >>> Sum(k, (k, 2, b)).doit() b**2/2 + b/2 - 1 With a nonzero eps specified, the summation is ended as soon as the remainder term is less than the epsilon. """ from sympy.functions import bernoulli, factorial from sympy.integrals import Integral m = int(m) n = int(n) f = self.function if len(self.limits) != 1: raise ValueError("More than 1 limit") i, a, b = self.limits[0] if (a > b) == True: if a - b == 1: return S.Zero, S.Zero a, b = b + 1, a - 1 f = -f s = S.Zero if m: if b.is_Integer and a.is_Integer: m = min(m, b - a + 1) if not eps or f.is_polynomial(i): for k in range(m): s += f.subs(i, a + k) else: term = f.subs(i, a) if term: test = abs(term.evalf(3)) < eps if test == True: return s, abs(term) elif not (test == False): # a symbolic Relational class, can't go further return term, S.Zero s += term for k in range(1, m): term = f.subs(i, a + k) if abs(term.evalf(3)) < eps and term != 0: return s, abs(term) s += term if b - a + 1 == m: return s, S.Zero a += m x = Dummy('x') I = Integral(f.subs(i, x), (x, a, b)) if eval_integral: I = I.doit() s += I def fpoint(expr): if b is S.Infinity: return expr.subs(i, a), 0 return expr.subs(i, a), expr.subs(i, b) fa, fb = fpoint(f) iterm = (fa + fb)/2 g = f.diff(i) for k in range(1, n + 2): ga, gb = fpoint(g) term = bernoulli(2*k)/factorial(2*k)*(gb - ga) if (eps and term and abs(term.evalf(3)) < eps) or (k > n): break s += term g = g.diff(i, 2, simplify=False) return s + iterm, abs(term) def reverse_order(self, *indices): """ Reverse the order of a limit in a Sum. Explanation =========== ``reverse_order(self, *indices)`` reverses some limits in the expression ``self`` which can be either a ``Sum`` or a ``Product``. The selectors in the argument ``indices`` specify some indices whose limits get reversed. These selectors are either variable names or numerical indices counted starting from the inner-most limit tuple. Examples ======== >>> from sympy import Sum >>> from sympy.abc import x, y, a, b, c, d >>> Sum(x, (x, 0, 3)).reverse_order(x) Sum(-x, (x, 4, -1)) >>> Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(x, y) Sum(x*y, (x, 6, 0), (y, 7, -1)) >>> Sum(x, (x, a, b)).reverse_order(x) Sum(-x, (x, b + 1, a - 1)) >>> Sum(x, (x, a, b)).reverse_order(0) Sum(-x, (x, b + 1, a - 1)) While one should prefer variable names when specifying which limits to reverse, the index counting notation comes in handy in case there are several symbols with the same name. >>> S = Sum(x**2, (x, a, b), (x, c, d)) >>> S Sum(x**2, (x, a, b), (x, c, d)) >>> S0 = S.reverse_order(0) >>> S0 Sum(-x**2, (x, b + 1, a - 1), (x, c, d)) >>> S1 = S0.reverse_order(1) >>> S1 Sum(x**2, (x, b + 1, a - 1), (x, d + 1, c - 1)) Of course we can mix both notations: >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) See Also ======== sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index, reorder_limit, sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder References ========== .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM, Volume 28 Issue 2, April 1981, Pages 305-350 http://dl.acm.org/citation.cfm?doid=322248.322255 """ l_indices = list(indices) for i, indx in enumerate(l_indices): if not isinstance(indx, int): l_indices[i] = self.index(indx) e = 1 limits = [] for i, limit in enumerate(self.limits): l = limit if i in l_indices: e = -e l = (limit[0], limit[2] + 1, limit[1] - 1) limits.append(l) return Sum(e * self.function, *limits) def summation(f, *symbols, **kwargs): r""" Compute the summation of f with respect to symbols. Explanation =========== The notation for symbols is similar to the notation used in Integral. summation(f, (i, a, b)) computes the sum of f with respect to i from a to b, i.e., :: b ____ \ ` summation(f, (i, a, b)) = ) f /___, i = a If it cannot compute the sum, it returns an unevaluated Sum object. Repeated sums can be computed by introducing additional symbols tuples:: Examples ======== >>> from sympy import summation, oo, symbols, log >>> i, n, m = symbols('i n m', integer=True) >>> summation(2*i - 1, (i, 1, n)) n**2 >>> summation(1/2**i, (i, 0, oo)) 2 >>> summation(1/log(n)**n, (n, 2, oo)) Sum(log(n)**(-n), (n, 2, oo)) >>> summation(i, (i, 0, n), (n, 0, m)) m**3/6 + m**2/2 + m/3 >>> from sympy.abc import x >>> from sympy import factorial >>> summation(x**n/factorial(n), (n, 0, oo)) exp(x) See Also ======== Sum Product, sympy.concrete.products.product """ return Sum(f, *symbols, **kwargs).doit(deep=False) def telescopic_direct(L, R, n, limits): """ Returns the direct summation of the terms of a telescopic sum Explanation =========== L is the term with lower index R is the term with higher index n difference between the indexes of L and R Examples ======== >>> from sympy.concrete.summations import telescopic_direct >>> from sympy.abc import k, a, b >>> telescopic_direct(1/k, -1/(k+2), 2, (k, a, b)) -1/(b + 2) - 1/(b + 1) + 1/(a + 1) + 1/a """ (i, a, b) = limits s = 0 for m in range(n): s += L.subs(i, a + m) + R.subs(i, b - m) return s def telescopic(L, R, limits): ''' Tries to perform the summation using the telescopic property. Return None if not possible. ''' (i, a, b) = limits if L.is_Add or R.is_Add: return None # We want to solve(L.subs(i, i + m) + R, m) # First we try a simple match since this does things that # solve doesn't do, e.g. solve(f(k+m)-f(k), m) fails k = Wild("k") sol = (-R).match(L.subs(i, i + k)) s = None if sol and k in sol: s = sol[k] if not (s.is_Integer and L.subs(i, i + s) == -R): # sometimes match fail(f(x+2).match(-f(x+k))->{k: -2 - 2x})) s = None # But there are things that match doesn't do that solve # can do, e.g. determine that 1/(x + m) = 1/(1 - x) when m = 1 if s is None: m = Dummy('m') try: sol = solve(L.subs(i, i + m) + R, m) or [] except NotImplementedError: return None sol = [si for si in sol if si.is_Integer and (L.subs(i, i + si) + R).expand().is_zero] if len(sol) != 1: return None s = sol[0] if s < 0: return telescopic_direct(R, L, abs(s), (i, a, b)) elif s > 0: return telescopic_direct(L, R, s, (i, a, b)) def eval_sum(f, limits): from sympy.concrete.delta import deltasummation, _has_simple_delta from sympy.functions import KroneckerDelta (i, a, b) = limits if f.is_zero: return S.Zero if i not in f.free_symbols: return f*(b - a + 1) if a == b: return f.subs(i, a) if isinstance(f, Piecewise): if not any(i in arg.args[1].free_symbols for arg in f.args): # Piecewise conditions do not depend on the dummy summation variable, # therefore we can fold: Sum(Piecewise((e, c), ...), limits) # --> Piecewise((Sum(e, limits), c), ...) newargs = [] for arg in f.args: newexpr = eval_sum(arg.expr, limits) if newexpr is None: return None newargs.append((newexpr, arg.cond)) return f.func(*newargs) if f.has(KroneckerDelta): f = f.replace( lambda x: isinstance(x, Sum), lambda x: x.factor() ) if _has_simple_delta(f, limits[0]): return deltasummation(f, limits) dif = b - a definite = dif.is_Integer # Doing it directly may be faster if there are very few terms. if definite and (dif < 100): return eval_sum_direct(f, (i, a, b)) if isinstance(f, Piecewise): return None # Try to do it symbolically. Even when the number of terms is known, # this can save time when b-a is big. # We should try to transform to partial fractions value = eval_sum_symbolic(f.expand(), (i, a, b)) if value is not None: return value # Do it directly if definite: return eval_sum_direct(f, (i, a, b)) def eval_sum_direct(expr, limits): """ Evaluate expression directly, but perform some simple checks first to possibly result in a smaller expression and faster execution. """ from sympy.core import Add (i, a, b) = limits dif = b - a # Linearity if expr.is_Mul: # Try factor out everything not including i without_i, with_i = expr.as_independent(i) if without_i != 1: s = eval_sum_direct(with_i, (i, a, b)) if s: r = without_i*s if r is not S.NaN: return r else: # Try term by term L, R = expr.as_two_terms() if not L.has(i): sR = eval_sum_direct(R, (i, a, b)) if sR: return L*sR if not R.has(i): sL = eval_sum_direct(L, (i, a, b)) if sL: return sL*R try: expr = apart(expr, i) # see if it becomes an Add except PolynomialError: pass if expr.is_Add: # Try factor out everything not including i without_i, with_i = expr.as_independent(i) if without_i != 0: s = eval_sum_direct(with_i, (i, a, b)) if s: r = without_i*(dif + 1) + s if r is not S.NaN: return r else: # Try term by term L, R = expr.as_two_terms() lsum = eval_sum_direct(L, (i, a, b)) rsum = eval_sum_direct(R, (i, a, b)) if None not in (lsum, rsum): r = lsum + rsum if r is not S.NaN: return r return Add(*[expr.subs(i, a + j) for j in range(dif + 1)]) def eval_sum_symbolic(f, limits): from sympy.functions import harmonic, bernoulli f_orig = f (i, a, b) = limits if not f.has(i): return f*(b - a + 1) # Linearity if f.is_Mul: # Try factor out everything not including i without_i, with_i = f.as_independent(i) if without_i != 1: s = eval_sum_symbolic(with_i, (i, a, b)) if s: r = without_i*s if r is not S.NaN: return r else: # Try term by term L, R = f.as_two_terms() if not L.has(i): sR = eval_sum_symbolic(R, (i, a, b)) if sR: return L*sR if not R.has(i): sL = eval_sum_symbolic(L, (i, a, b)) if sL: return sL*R try: f = apart(f, i) # see if it becomes an Add except PolynomialError: pass if f.is_Add: L, R = f.as_two_terms() lrsum = telescopic(L, R, (i, a, b)) if lrsum: return lrsum # Try factor out everything not including i without_i, with_i = f.as_independent(i) if without_i != 0: s = eval_sum_symbolic(with_i, (i, a, b)) if s: r = without_i*(b - a + 1) + s if r is not S.NaN: return r else: # Try term by term lsum = eval_sum_symbolic(L, (i, a, b)) rsum = eval_sum_symbolic(R, (i, a, b)) if None not in (lsum, rsum): r = lsum + rsum if r is not S.NaN: return r # Polynomial terms with Faulhaber's formula n = Wild('n') result = f.match(i**n) if result is not None: n = result[n] if n.is_Integer: if n >= 0: if (b is S.Infinity and not a is S.NegativeInfinity) or \ (a is S.NegativeInfinity and not b is S.Infinity): return S.Infinity return ((bernoulli(n + 1, b + 1) - bernoulli(n + 1, a))/(n + 1)).expand() elif a.is_Integer and a >= 1: if n == -1: return harmonic(b) - harmonic(a - 1) else: return harmonic(b, abs(n)) - harmonic(a - 1, abs(n)) if not (a.has(S.Infinity, S.NegativeInfinity) or b.has(S.Infinity, S.NegativeInfinity)): # Geometric terms c1 = Wild('c1', exclude=[i]) c2 = Wild('c2', exclude=[i]) c3 = Wild('c3', exclude=[i]) wexp = Wild('wexp') # Here we first attempt powsimp on f for easier matching with the # exponential pattern, and attempt expansion on the exponent for easier # matching with the linear pattern. e = f.powsimp().match(c1 ** wexp) if e is not None: e_exp = e.pop(wexp).expand().match(c2*i + c3) if e_exp is not None: e.update(e_exp) p = (c1**c3).subs(e) q = (c1**c2).subs(e) r = p*(q**a - q**(b + 1))/(1 - q) l = p*(b - a + 1) return Piecewise((l, Eq(q, S.One)), (r, True)) r = gosper_sum(f, (i, a, b)) if isinstance(r, (Mul,Add)): from sympy import ordered, Tuple non_limit = r.free_symbols - Tuple(*limits[1:]).free_symbols den = denom(together(r)) den_sym = non_limit & den.free_symbols args = [] for v in ordered(den_sym): try: s = solve(den, v) m = Eq(v, s[0]) if s else S.false if m != False: args.append((Sum(f_orig.subs(*m.args), limits).doit(), m)) break except NotImplementedError: continue args.append((r, True)) return Piecewise(*args) if not r in (None, S.NaN): return r h = eval_sum_hyper(f_orig, (i, a, b)) if h is not None: return h factored = f_orig.factor() if factored != f_orig: return eval_sum_symbolic(factored, (i, a, b)) def _eval_sum_hyper(f, i, a): """ Returns (res, cond). Sums from a to oo. """ from sympy.functions import hyper from sympy.simplify import hyperexpand, hypersimp, fraction, simplify from sympy.polys.polytools import Poly, factor from sympy.core.numbers import Float if a != 0: return _eval_sum_hyper(f.subs(i, i + a), i, 0) if f.subs(i, 0) == 0: if simplify(f.subs(i, Dummy('i', integer=True, positive=True))) == 0: return S.Zero, True return _eval_sum_hyper(f.subs(i, i + 1), i, 0) hs = hypersimp(f, i) if hs is None: return None if isinstance(hs, Float): from sympy.simplify.simplify import nsimplify hs = nsimplify(hs) numer, denom = fraction(factor(hs)) top, topl = numer.as_coeff_mul(i) bot, botl = denom.as_coeff_mul(i) ab = [top, bot] factors = [topl, botl] params = [[], []] for k in range(2): for fac in factors[k]: mul = 1 if fac.is_Pow: mul = fac.exp fac = fac.base if not mul.is_Integer: return None p = Poly(fac, i) if p.degree() != 1: return None m, n = p.all_coeffs() ab[k] *= m**mul params[k] += [n/m]*mul # Add "1" to numerator parameters, to account for implicit n! in # hypergeometric series. ap = params[0] + [1] bq = params[1] x = ab[0]/ab[1] h = hyper(ap, bq, x) f = combsimp(f) return f.subs(i, 0)*hyperexpand(h), h.convergence_statement def eval_sum_hyper(f, i_a_b): from sympy.logic.boolalg import And i, a, b = i_a_b if (b - a).is_Integer: # We are never going to do better than doing the sum in the obvious way return None old_sum = Sum(f, (i, a, b)) if b != S.Infinity: if a is S.NegativeInfinity: res = _eval_sum_hyper(f.subs(i, -i), i, -b) if res is not None: return Piecewise(res, (old_sum, True)) else: res1 = _eval_sum_hyper(f, i, a) res2 = _eval_sum_hyper(f, i, b + 1) if res1 is None or res2 is None: return None (res1, cond1), (res2, cond2) = res1, res2 cond = And(cond1, cond2) if cond == False: return None return Piecewise((res1 - res2, cond), (old_sum, True)) if a is S.NegativeInfinity: res1 = _eval_sum_hyper(f.subs(i, -i), i, 1) res2 = _eval_sum_hyper(f, i, 0) if res1 is None or res2 is None: return None res1, cond1 = res1 res2, cond2 = res2 cond = And(cond1, cond2) if cond == False or cond.as_set() == S.EmptySet: return None return Piecewise((res1 + res2, cond), (old_sum, True)) # Now b == oo, a != -oo res = _eval_sum_hyper(f, i, a) if res is not None: r, c = res if c == False: if r.is_number: f = f.subs(i, Dummy('i', integer=True, positive=True) + a) if f.is_positive or f.is_zero: return S.Infinity elif f.is_negative: return S.NegativeInfinity return None return Piecewise(res, (old_sum, True)) def _eval_matrix_sum(expression): f = expression.function for n, limit in enumerate(expression.limits): i, a, b = limit dif = b - a if dif.is_Integer: if (dif < 0) == True: a, b = b + 1, a - 1 f = -f newf = eval_sum_direct(f, (i, a, b)) if newf is not None: return newf.doit() def _dummy_with_inherited_properties_concrete(limits): """ Return a Dummy symbol that inherits as many assumptions as possible from the provided symbol and limits. If the symbol already has all True assumption shared by the limits then return None. """ x, a, b = limits l = [a, b] assumptions_to_consider = ['extended_nonnegative', 'nonnegative', 'extended_nonpositive', 'nonpositive', 'extended_positive', 'positive', 'extended_negative', 'negative', 'integer', 'rational', 'finite', 'zero', 'real', 'extended_real'] assumptions_to_keep = {} assumptions_to_add = {} for assum in assumptions_to_consider: assum_true = x._assumptions.get(assum, None) if assum_true: assumptions_to_keep[assum] = True elif all([getattr(i, 'is_' + assum) for i in l]): assumptions_to_add[assum] = True if assumptions_to_add: assumptions_to_keep.update(assumptions_to_add) return Dummy('d', **assumptions_to_keep)
c21f7ad0687338519c96bef14a6f3e3c18f7630a2f39df8b9f89b58f5193dbbf
""" 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.algebraic | ~Q.rational, Q.antihermitian | ~Q.imaginary, Q.complex | ~Q.algebraic, Q.complex | ~Q.imaginary, Q.complex | ~Q.real, Q.complex | ~Q.transcendental, 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.hermitian | ~Q.real, Q.rational | ~Q.integer, Q.real | ~Q.irrational, Q.real | ~Q.rational, Q.integer | ~Q.even, Q.integer | ~Q.odd, Q.integer | ~Q.prime, ~Q.algebraic | ~Q.transcendental, ~Q.antihermitian | ~Q.hermitian, ~Q.finite | ~Q.infinite, ~Q.imaginary | ~Q.real, ~Q.irrational | ~Q.rational, Q.real | ~Q.negative, Q.real | ~Q.positive, Q.real | ~Q.zero, Q.invertible | Q.singular, Q.infinite | Q.real | ~Q.extended_real, Q.complex_elements | ~Q.real_elements, Q.even | ~Q.zero, Q.fullrank | ~Q.invertible, 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 | ~Q.prime, Q.positive_definite | ~Q.orthogonal, Q.real_elements | ~Q.integer_elements, 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.composite | ~Q.prime, ~Q.even | ~Q.odd, ~Q.invertible | ~Q.singular, ~Q.negative | ~Q.positive, ~Q.negative | ~Q.zero, ~Q.positive | ~Q.zero, ~Q.integer | Q.even | Q.odd, Q.algebraic | Q.transcendental | ~Q.complex | ~Q.finite, Q.irrational | Q.rational | ~Q.finite | ~Q.real, ~Q.real | Q.orthogonal | ~Q.unitary, 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.real | Q.negative | Q.positive | Q.zero ) # -{ 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]), }
1d2023779015e8163640f04d9df8127cf1fdbc5cfc14c70f1dfd09d7f744acf5
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 =========== Gives the form of expr that would be obtained if symbols in it were replaced by explicit numerical expressions satisfying the assumptions. 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 """ 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_Relational(expr, assumptions): """ Handler for Relational. Examples ======== >>> from sympy.assumptions.refine import refine_Relational >>> from sympy.assumptions.ask import Q >>> from sympy.abc import x >>> refine_Relational(x<0, ~Q.is_true(x<0)) False """ return ask(Q.is_true(expr), assumptions) 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, 'Equality': refine_Relational, 'Unequality': refine_Relational, 'GreaterThan': refine_Relational, 'LessThan': refine_Relational, 'StrictGreaterThan': refine_Relational, 'StrictLessThan': refine_Relational, 're': refine_re, 'im': refine_im, 'sign': refine_sign, 'MatrixElement': refine_matrixelement } # type: Dict[str, Callable[[Expr, Boolean], Expr]]
2ab19a51bf313320df06f673532bf489397af056cb9b94c621ab98bb0db2c231
""" A module to implement logical predicates and assumption system. """ from .assume import ( AppliedPredicate, Predicate, AssumptionsContext, assuming, global_assumptions ) from .ask import Q, ask, register_handler, remove_handler from .refine import refine __all__ = [ 'AppliedPredicate', 'Predicate', 'AssumptionsContext', 'assuming', 'global_assumptions', 'Q', 'ask', 'register_handler', 'remove_handler', 'refine', ]
86aaa0855e3a81039e06db504bf242344d1e380f323e6a83ae8a1f67718f707b
"""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.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): 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 """ return Predicate('positive') @memoize_property def negative(self): 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 """ return Predicate('negative') @memoize_property def zero(self): """ 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 """ return Predicate('zero') @memoize_property def nonzero(self): """ 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 """ return Predicate('nonzero') @memoize_property def nonpositive(self): """ 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 """ return Predicate('nonpositive') @memoize_property def nonnegative(self): """ 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 """ return Predicate('nonnegative') @memoize_property def even(self): """ 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 """ return Predicate('even') @memoize_property def odd(self): """ 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 """ return Predicate('odd') @memoize_property def prime(self): """ 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 """ return Predicate('prime') @memoize_property def composite(self): """ 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 """ return Predicate('composite') @memoize_property def commutative(self): """ Commutative predicate. Explanation =========== ``ask(Q.commutative(x))`` is true iff ``x`` commutes with any other object with respect to multiplication operation. """ # TODO: Add examples return Predicate('commutative') @memoize_property def is_true(self): """ 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 """ return Predicate('is_true') @memoize_property def symmetric(self): """ 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. return Predicate('symmetric') @memoize_property def invertible(self): """ 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 """ return Predicate('invertible') @memoize_property def orthogonal(self): """ 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 """ return Predicate('orthogonal') @memoize_property def unitary(self): """ 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 """ return Predicate('unitary') @memoize_property def positive_definite(self): 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 """ return Predicate('positive_definite') @memoize_property def upper_triangular(self): """ 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 """ return Predicate('upper_triangular') @memoize_property def lower_triangular(self): """ 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 """ return Predicate('lower_triangular') @memoize_property def diagonal(self): """ 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 """ return Predicate('diagonal') @memoize_property def fullrank(self): """ 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 """ return Predicate('fullrank') @memoize_property def square(self): """ 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 """ return Predicate('square') @memoize_property def integer_elements(self): """ 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 """ return Predicate('integer_elements') @memoize_property def real_elements(self): """ 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 """ return Predicate('real_elements') @memoize_property def complex_elements(self): """ 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 """ return Predicate('complex_elements') @memoize_property def singular(self): """ 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 """ return Predicate('singular') @memoize_property def normal(self): """ 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 """ return Predicate('normal') @memoize_property def triangular(self): """ 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 """ return Predicate('triangular') @memoize_property def unit_triangular(self): """ 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 """ return Predicate('unit_triangular') 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. 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. """ 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:: >>> from sympy.assumptions import register_handler, ask, Q >>> from sympy.assumptions.handlers import AskHandler >>> class MersenneHandler(AskHandler): ... # Mersenne numbers are in the form 2**n - 1, n integer ... @staticmethod ... def Integer(expr, assumptions): ... from sympy import log ... return ask(Q.integer(log(expr + 1, 2))) >>> register_handler('mersenne', MersenneHandler) >>> ask(Q.mersenne(7)) True """ # Will be deprecated 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""" # Will be deprecated 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) # handlers tells us what ask handler we should use # for a particular key _val_template = 'sympy.assumptions.handlers.%s' _handlers = [ ("commutative", "AskCommutativeHandler"), ("composite", "ntheory.AskCompositeHandler"), ("even", "ntheory.AskEvenHandler"), ("negative", "order.AskNegativeHandler"), ("nonzero", "order.AskNonZeroHandler"), ("nonpositive", "order.AskNonPositiveHandler"), ("nonnegative", "order.AskNonNegativeHandler"), ("zero", "order.AskZeroHandler"), ("positive", "order.AskPositiveHandler"), ("prime", "ntheory.AskPrimeHandler"), ("odd", "ntheory.AskOddHandler"), ("is_true", "common.TautologicalHandler"), ("symmetric", "matrices.AskSymmetricHandler"), ("invertible", "matrices.AskInvertibleHandler"), ("orthogonal", "matrices.AskOrthogonalHandler"), ("unitary", "matrices.AskUnitaryHandler"), ("positive_definite", "matrices.AskPositiveDefiniteHandler"), ("upper_triangular", "matrices.AskUpperTriangularHandler"), ("lower_triangular", "matrices.AskLowerTriangularHandler"), ("diagonal", "matrices.AskDiagonalHandler"), ("fullrank", "matrices.AskFullRankHandler"), ("square", "matrices.AskSquareHandler"), ("integer_elements", "matrices.AskIntegerElementsHandler"), ("real_elements", "matrices.AskRealElementsHandler"), ("complex_elements", "matrices.AskComplexElementsHandler"), ] for name, value in _handlers: register_handler(name, _val_template % value) @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)
beaf9e1d3a39675e29a841fc8ed87dc194769027cf989bf1fb7e61b1ddb4154b
"""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.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): # Will be deprecated self.handlers.append(handler) def remove_handler(self, handler): # Will be deprecated self.handlers.remove(handler) def eval(self, args, assumptions=True): # Support for deprecated design # When old design is removed, this will always return None 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)
5d17ee1c7aee62c205ce663164544da81e2a63a9ddf2b6888d41c884ba5eea0f
""" This module contains functions to: - solve a single equation for a single variable, in any domain either real or complex. - solve a single transcendental equation for a single variable in any domain either real or complex. (currently supports solving in real domain only) - solve a system of linear equations with N variables and M equations. - solve a system of Non Linear Equations with N variables and M equations """ from sympy.core.sympify import sympify from sympy.core import (S, Pow, Dummy, pi, Expr, Wild, Mul, Equality, Add) from sympy.core.containers import Tuple from sympy.core.numbers import I, Number, Rational, oo from sympy.core.function import (Lambda, expand_complex, AppliedUndef, expand_log) from sympy.core.mod import Mod from sympy.core.numbers import igcd from sympy.core.relational import Eq, Ne, Relational from sympy.core.symbol import Symbol, _uniquely_named_symbol from sympy.core.sympify import _sympify from sympy.simplify.simplify import simplify, fraction, trigsimp from sympy.simplify import powdenest, logcombine from sympy.functions import (log, Abs, tan, cot, sin, cos, sec, csc, exp, acos, asin, acsc, asec, arg, piecewise_fold, Piecewise) from sympy.functions.elementary.trigonometric import (TrigonometricFunction, HyperbolicFunction) from sympy.functions.elementary.miscellaneous import real_root from sympy.logic.boolalg import And from sympy.sets import (FiniteSet, EmptySet, imageset, Interval, Intersection, Union, ConditionSet, ImageSet, Complement, Contains) from sympy.sets.sets import Set, ProductSet from sympy.matrices import Matrix, MatrixBase from sympy.ntheory import totient from sympy.ntheory.factor_ import divisors from sympy.ntheory.residue_ntheory import discrete_log, nthroot_mod from sympy.polys import (roots, Poly, degree, together, PolynomialError, RootOf, factor, lcm, gcd) from sympy.polys.polyerrors import CoercionFailed from sympy.polys.polytools import invert from sympy.polys.solvers import (sympy_eqs_to_ring, solve_lin_sys, PolyNonlinearError) from sympy.solvers.solvers import (checksol, denoms, unrad, _simple_dens, recast_to_symbols) from sympy.solvers.polysys import solve_poly_system from sympy.solvers.inequalities import solve_univariate_inequality from sympy.utilities import filldedent from sympy.utilities.iterables import numbered_symbols, has_dups from sympy.calculus.util import periodicity, continuous_domain from sympy.core.compatibility import ordered, default_sort_key, is_sequence from types import GeneratorType from collections import defaultdict class NonlinearError(ValueError): """Raised when unexpectedly encountering nonlinear equations""" pass _rc = Dummy("R", real=True), Dummy("C", complex=True) def _masked(f, *atoms): """Return ``f``, with all objects given by ``atoms`` replaced with Dummy symbols, ``d``, and the list of replacements, ``(d, e)``, where ``e`` is an object of type given by ``atoms`` in which any other instances of atoms have been recursively replaced with Dummy symbols, too. The tuples are ordered so that if they are applied in sequence, the origin ``f`` will be restored. Examples ======== >>> from sympy import cos >>> from sympy.abc import x >>> from sympy.solvers.solveset import _masked >>> f = cos(cos(x) + 1) >>> f, reps = _masked(cos(1 + cos(x)), cos) >>> f _a1 >>> reps [(_a1, cos(_a0 + 1)), (_a0, cos(x))] >>> for d, e in reps: ... f = f.xreplace({d: e}) >>> f cos(cos(x) + 1) """ sym = numbered_symbols('a', cls=Dummy, real=True) mask = [] for a in ordered(f.atoms(*atoms)): for i in mask: a = a.replace(*i) mask.append((a, next(sym))) for i, (o, n) in enumerate(mask): f = f.replace(o, n) mask[i] = (n, o) mask = list(reversed(mask)) return f, mask def _invert(f_x, y, x, domain=S.Complexes): r""" Reduce the complex valued equation ``f(x) = y`` to a set of equations ``{g(x) = h_1(y), g(x) = h_2(y), ..., g(x) = h_n(y) }`` where ``g(x)`` is a simpler function than ``f(x)``. The return value is a tuple ``(g(x), set_h)``, where ``g(x)`` is a function of ``x`` and ``set_h`` is the set of function ``{h_1(y), h_2(y), ..., h_n(y)}``. Here, ``y`` is not necessarily a symbol. The ``set_h`` contains the functions, along with the information about the domain in which they are valid, through set operations. For instance, if ``y = Abs(x) - n`` is inverted in the real domain, then ``set_h`` is not simply `{-n, n}` as the nature of `n` is unknown; rather, it is: `Intersection([0, oo) {n}) U Intersection((-oo, 0], {-n})` By default, the complex domain is used which means that inverting even seemingly simple functions like ``exp(x)`` will give very different results from those obtained in the real domain. (In the case of ``exp(x)``, the inversion via ``log`` is multi-valued in the complex domain, having infinitely many branches.) If you are working with real values only (or you are not sure which function to use) you should probably set the domain to ``S.Reals`` (or use `invert\_real` which does that automatically). Examples ======== >>> from sympy.solvers.solveset import invert_complex, invert_real >>> from sympy.abc import x, y >>> from sympy import exp When does exp(x) == y? >>> invert_complex(exp(x), y, x) (x, ImageSet(Lambda(_n, I*(2*_n*pi + arg(y)) + log(Abs(y))), Integers)) >>> invert_real(exp(x), y, x) (x, Intersection(FiniteSet(log(y)), Reals)) When does exp(x) == 1? >>> invert_complex(exp(x), 1, x) (x, ImageSet(Lambda(_n, 2*_n*I*pi), Integers)) >>> invert_real(exp(x), 1, x) (x, FiniteSet(0)) See Also ======== invert_real, invert_complex """ x = sympify(x) if not x.is_Symbol: raise ValueError("x must be a symbol") f_x = sympify(f_x) if x not in f_x.free_symbols: raise ValueError("Inverse of constant function doesn't exist") y = sympify(y) if x in y.free_symbols: raise ValueError("y should be independent of x ") if domain.is_subset(S.Reals): x1, s = _invert_real(f_x, FiniteSet(y), x) else: x1, s = _invert_complex(f_x, FiniteSet(y), x) if not isinstance(s, FiniteSet) or x1 != x: return x1, s # Avoid adding gratuitous intersections with S.Complexes. Actual # conditions should be handled by the respective inverters. if domain is S.Complexes: return x1, s else: return x1, s.intersection(domain) invert_complex = _invert def invert_real(f_x, y, x, domain=S.Reals): """ Inverts a real-valued function. Same as _invert, but sets the domain to ``S.Reals`` before inverting. """ return _invert(f_x, y, x, domain) def _invert_real(f, g_ys, symbol): """Helper function for _invert.""" if f == symbol: return (f, g_ys) n = Dummy('n', real=True) if hasattr(f, 'inverse') and not isinstance(f, ( TrigonometricFunction, HyperbolicFunction, )): if len(f.args) > 1: raise ValueError("Only functions with one argument are supported.") return _invert_real(f.args[0], imageset(Lambda(n, f.inverse()(n)), g_ys), symbol) if isinstance(f, Abs): return _invert_abs(f.args[0], g_ys, symbol) if f.is_Add: # f = g + h g, h = f.as_independent(symbol) if g is not S.Zero: return _invert_real(h, imageset(Lambda(n, n - g), g_ys), symbol) if f.is_Mul: # f = g*h g, h = f.as_independent(symbol) if g is not S.One: return _invert_real(h, imageset(Lambda(n, n/g), g_ys), symbol) if f.is_Pow: base, expo = f.args base_has_sym = base.has(symbol) expo_has_sym = expo.has(symbol) if not expo_has_sym: res = imageset(Lambda(n, real_root(n, expo)), g_ys) if expo.is_rational: numer, denom = expo.as_numer_denom() if denom % 2 == 0: base_positive = solveset(base >= 0, symbol, S.Reals) res = imageset(Lambda(n, real_root(n, expo) ), g_ys.intersect( Interval.Ropen(S.Zero, S.Infinity))) _inv, _set = _invert_real(base, res, symbol) return (_inv, _set.intersect(base_positive)) elif numer % 2 == 0: n = Dummy('n') neg_res = imageset(Lambda(n, -n), res) return _invert_real(base, res + neg_res, symbol) else: return _invert_real(base, res, symbol) else: if not base.is_positive: raise ValueError("x**w where w is irrational is not " "defined for negative x") return _invert_real(base, res, symbol) if not base_has_sym: rhs = g_ys.args[0] if base.is_positive: return _invert_real(expo, imageset(Lambda(n, log(n, base, evaluate=False)), g_ys), symbol) elif base.is_negative: from sympy.core.power import integer_log s, b = integer_log(rhs, base) if b: return _invert_real(expo, FiniteSet(s), symbol) else: return _invert_real(expo, S.EmptySet, symbol) elif base.is_zero: one = Eq(rhs, 1) if one == S.true: # special case: 0**x - 1 return _invert_real(expo, FiniteSet(0), symbol) elif one == S.false: return _invert_real(expo, S.EmptySet, symbol) if isinstance(f, TrigonometricFunction): if isinstance(g_ys, FiniteSet): def inv(trig): if isinstance(f, (sin, csc)): F = asin if isinstance(f, sin) else acsc return (lambda a: n*pi + (-1)**n*F(a),) if isinstance(f, (cos, sec)): F = acos if isinstance(f, cos) else asec return ( lambda a: 2*n*pi + F(a), lambda a: 2*n*pi - F(a),) if isinstance(f, (tan, cot)): return (lambda a: n*pi + f.inverse()(a),) n = Dummy('n', integer=True) invs = S.EmptySet for L in inv(f): invs += Union(*[imageset(Lambda(n, L(g)), S.Integers) for g in g_ys]) return _invert_real(f.args[0], invs, symbol) return (f, g_ys) def _invert_complex(f, g_ys, symbol): """Helper function for _invert.""" if f == symbol: return (f, g_ys) n = Dummy('n') if f.is_Add: # f = g + h g, h = f.as_independent(symbol) if g is not S.Zero: return _invert_complex(h, imageset(Lambda(n, n - g), g_ys), symbol) if f.is_Mul: # f = g*h g, h = f.as_independent(symbol) if g is not S.One: if g in {S.NegativeInfinity, S.ComplexInfinity, S.Infinity}: return (h, S.EmptySet) return _invert_complex(h, imageset(Lambda(n, n/g), g_ys), symbol) if hasattr(f, 'inverse') and \ not isinstance(f, TrigonometricFunction) and \ not isinstance(f, HyperbolicFunction) and \ not isinstance(f, exp): if len(f.args) > 1: raise ValueError("Only functions with one argument are supported.") return _invert_complex(f.args[0], imageset(Lambda(n, f.inverse()(n)), g_ys), symbol) if isinstance(f, exp): if isinstance(g_ys, FiniteSet): exp_invs = Union(*[imageset(Lambda(n, I*(2*n*pi + arg(g_y)) + log(Abs(g_y))), S.Integers) for g_y in g_ys if g_y != 0]) return _invert_complex(f.args[0], exp_invs, symbol) return (f, g_ys) def _invert_abs(f, g_ys, symbol): """Helper function for inverting absolute value functions. Returns the complete result of inverting an absolute value function along with the conditions which must also be satisfied. If it is certain that all these conditions are met, a `FiniteSet` of all possible solutions is returned. If any condition cannot be satisfied, an `EmptySet` is returned. Otherwise, a `ConditionSet` of the solutions, with all the required conditions specified, is returned. """ if not g_ys.is_FiniteSet: # this could be used for FiniteSet, but the # results are more compact if they aren't, e.g. # ConditionSet(x, Contains(n, Interval(0, oo)), {-n, n}) vs # Union(Intersection(Interval(0, oo), {n}), Intersection(Interval(-oo, 0), {-n})) # for the solution of abs(x) - n pos = Intersection(g_ys, Interval(0, S.Infinity)) parg = _invert_real(f, pos, symbol) narg = _invert_real(-f, pos, symbol) if parg[0] != narg[0]: raise NotImplementedError return parg[0], Union(narg[1], parg[1]) # check conditions: all these must be true. If any are unknown # then return them as conditions which must be satisfied unknown = [] for a in g_ys.args: ok = a.is_nonnegative if a.is_Number else a.is_positive if ok is None: unknown.append(a) elif not ok: return symbol, S.EmptySet if unknown: conditions = And(*[Contains(i, Interval(0, oo)) for i in unknown]) else: conditions = True n = Dummy('n', real=True) # this is slightly different than above: instead of solving # +/-f on positive values, here we solve for f on +/- g_ys g_x, values = _invert_real(f, Union( imageset(Lambda(n, n), g_ys), imageset(Lambda(n, -n), g_ys)), symbol) return g_x, ConditionSet(g_x, conditions, values) def domain_check(f, symbol, p): """Returns False if point p is infinite or any subexpression of f is infinite or becomes so after replacing symbol with p. If none of these conditions is met then True will be returned. Examples ======== >>> from sympy import Mul, oo >>> from sympy.abc import x >>> from sympy.solvers.solveset import domain_check >>> g = 1/(1 + (1/(x + 1))**2) >>> domain_check(g, x, -1) False >>> domain_check(x**2, x, 0) True >>> domain_check(1/x, x, oo) False * The function relies on the assumption that the original form of the equation has not been changed by automatic simplification. >>> domain_check(x/x, x, 0) # x/x is automatically simplified to 1 True * To deal with automatic evaluations use evaluate=False: >>> domain_check(Mul(x, 1/x, evaluate=False), x, 0) False """ f, p = sympify(f), sympify(p) if p.is_infinite: return False return _domain_check(f, symbol, p) def _domain_check(f, symbol, p): # helper for domain check if f.is_Atom and f.is_finite: return True elif f.subs(symbol, p).is_infinite: return False elif isinstance(f, Piecewise): # Check the cases of the Piecewise in turn. There might be invalid # expressions in later cases that don't apply e.g. # solveset(Piecewise((0, Eq(x, 0)), (1/x, True)), x) for expr, cond in f.args: condsubs = cond.subs(symbol, p) if condsubs is S.false: continue elif condsubs is S.true: return _domain_check(expr, symbol, p) else: # We don't know which case of the Piecewise holds. On this # basis we cannot decide whether any solution is in or out of # the domain. Ideally this function would allow returning a # symbolic condition for the validity of the solution that # could be handled in the calling code. In the mean time we'll # give this particular solution the benefit of the doubt and # let it pass. return True else: # TODO : We should not blindly recurse through all args of arbitrary expressions like this return all([_domain_check(g, symbol, p) for g in f.args]) def _is_finite_with_finite_vars(f, domain=S.Complexes): """ Return True if the given expression is finite. For symbols that don't assign a value for `complex` and/or `real`, the domain will be used to assign a value; symbols that don't assign a value for `finite` will be made finite. All other assumptions are left unmodified. """ def assumptions(s): A = s.assumptions0 A.setdefault('finite', A.get('finite', True)) if domain.is_subset(S.Reals): # if this gets set it will make complex=True, too A.setdefault('real', True) else: # don't change 'real' because being complex implies # nothing about being real A.setdefault('complex', True) return A reps = {s: Dummy(**assumptions(s)) for s in f.free_symbols} return f.xreplace(reps).is_finite def _is_function_class_equation(func_class, f, symbol): """ Tests whether the equation is an equation of the given function class. The given equation belongs to the given function class if it is comprised of functions of the function class which are multiplied by or added to expressions independent of the symbol. In addition, the arguments of all such functions must be linear in the symbol as well. Examples ======== >>> from sympy.solvers.solveset import _is_function_class_equation >>> from sympy import tan, sin, tanh, sinh, exp >>> from sympy.abc import x >>> from sympy.functions.elementary.trigonometric import (TrigonometricFunction, ... HyperbolicFunction) >>> _is_function_class_equation(TrigonometricFunction, exp(x) + tan(x), x) False >>> _is_function_class_equation(TrigonometricFunction, tan(x) + sin(x), x) True >>> _is_function_class_equation(TrigonometricFunction, tan(x**2), x) False >>> _is_function_class_equation(TrigonometricFunction, tan(x + 2), x) True >>> _is_function_class_equation(HyperbolicFunction, tanh(x) + sinh(x), x) True """ if f.is_Mul or f.is_Add: return all(_is_function_class_equation(func_class, arg, symbol) for arg in f.args) if f.is_Pow: if not f.exp.has(symbol): return _is_function_class_equation(func_class, f.base, symbol) else: return False if not f.has(symbol): return True if isinstance(f, func_class): try: g = Poly(f.args[0], symbol) return g.degree() <= 1 except PolynomialError: return False else: return False def _solve_as_rational(f, symbol, domain): """ solve rational functions""" f = together(f, deep=True) g, h = fraction(f) if not h.has(symbol): try: return _solve_as_poly(g, symbol, domain) except NotImplementedError: # The polynomial formed from g could end up having # coefficients in a ring over which finding roots # isn't implemented yet, e.g. ZZ[a] for some symbol a return ConditionSet(symbol, Eq(f, 0), domain) except CoercionFailed: # contained oo, zoo or nan return S.EmptySet else: valid_solns = _solveset(g, symbol, domain) invalid_solns = _solveset(h, symbol, domain) return valid_solns - invalid_solns class _SolveTrig1Error(Exception): """Raised when _solve_trig1 heuristics do not apply""" def _solve_trig(f, symbol, domain): """Function to call other helpers to solve trigonometric equations """ sol = None try: sol = _solve_trig1(f, symbol, domain) except _SolveTrig1Error: try: sol = _solve_trig2(f, symbol, domain) except ValueError: raise NotImplementedError(filldedent(''' Solution to this kind of trigonometric equations is yet to be implemented''')) return sol def _solve_trig1(f, symbol, domain): """Primary solver for trigonometric and hyperbolic equations Returns either the solution set as a ConditionSet (auto-evaluated to a union of ImageSets if no variables besides 'symbol' are involved) or raises _SolveTrig1Error if f == 0 can't be solved. Notes ===== Algorithm: 1. Do a change of variable x -> mu*x in arguments to trigonometric and hyperbolic functions, in order to reduce them to small integers. (This step is crucial to keep the degrees of the polynomials of step 4 low.) 2. Rewrite trigonometric/hyperbolic functions as exponentials. 3. Proceed to a 2nd change of variable, replacing exp(I*x) or exp(x) by y. 4. Solve the resulting rational equation. 5. Use invert_complex or invert_real to return to the original variable. 6. If the coefficients of 'symbol' were symbolic in nature, add the necessary consistency conditions in a ConditionSet. """ # Prepare change of variable x = Dummy('x') if _is_function_class_equation(HyperbolicFunction, f, symbol): cov = exp(x) inverter = invert_real if domain.is_subset(S.Reals) else invert_complex else: cov = exp(I*x) inverter = invert_complex f = trigsimp(f) f_original = f trig_functions = f.atoms(TrigonometricFunction, HyperbolicFunction) trig_arguments = [e.args[0] for e in trig_functions] # trigsimp may have reduced the equation to an expression # that is independent of 'symbol' (e.g. cos**2+sin**2) if not any(a.has(symbol) for a in trig_arguments): return solveset(f_original, symbol, domain) denominators = [] numerators = [] for ar in trig_arguments: try: poly_ar = Poly(ar, symbol) except PolynomialError: raise _SolveTrig1Error("trig argument is not a polynomial") if poly_ar.degree() > 1: # degree >1 still bad raise _SolveTrig1Error("degree of variable must not exceed one") if poly_ar.degree() == 0: # degree 0, don't care continue c = poly_ar.all_coeffs()[0] # got the coefficient of 'symbol' numerators.append(fraction(c)[0]) denominators.append(fraction(c)[1]) mu = lcm(denominators)/gcd(numerators) f = f.subs(symbol, mu*x) f = f.rewrite(exp) f = together(f) g, h = fraction(f) y = Dummy('y') g, h = g.expand(), h.expand() g, h = g.subs(cov, y), h.subs(cov, y) if g.has(x) or h.has(x): raise _SolveTrig1Error("change of variable not possible") solns = solveset_complex(g, y) - solveset_complex(h, y) if isinstance(solns, ConditionSet): raise _SolveTrig1Error("polynomial has ConditionSet solution") if isinstance(solns, FiniteSet): if any(isinstance(s, RootOf) for s in solns): raise _SolveTrig1Error("polynomial results in RootOf object") # revert the change of variable cov = cov.subs(x, symbol/mu) result = Union(*[inverter(cov, s, symbol)[1] for s in solns]) # In case of symbolic coefficients, the solution set is only valid # if numerator and denominator of mu are non-zero. if mu.has(Symbol): syms = (mu).atoms(Symbol) munum, muden = fraction(mu) condnum = munum.as_independent(*syms, as_Add=False)[1] condden = muden.as_independent(*syms, as_Add=False)[1] cond = And(Ne(condnum, 0), Ne(condden, 0)) else: cond = True # Actual conditions are returned as part of the ConditionSet. Adding an # intersection with C would only complicate some solution sets due to # current limitations of intersection code. (e.g. #19154) if domain is S.Complexes: # This is a slight abuse of ConditionSet. Ideally this should # be some kind of "PiecewiseSet". (See #19507 discussion) return ConditionSet(symbol, cond, result) else: return ConditionSet(symbol, cond, Intersection(result, domain)) elif solns is S.EmptySet: return S.EmptySet else: raise _SolveTrig1Error("polynomial solutions must form FiniteSet") def _solve_trig2(f, symbol, domain): """Secondary helper to solve trigonometric equations, called when first helper fails """ from sympy import ilcm, expand_trig, degree f = trigsimp(f) f_original = f trig_functions = f.atoms(sin, cos, tan, sec, cot, csc) trig_arguments = [e.args[0] for e in trig_functions] denominators = [] numerators = [] # todo: This solver can be extended to hyperbolics if the # analogous change of variable to tanh (instead of tan) # is used. if not trig_functions: return ConditionSet(symbol, Eq(f_original, 0), domain) # todo: The pre-processing below (extraction of numerators, denominators, # gcd, lcm, mu, etc.) should be updated to the enhanced version in # _solve_trig1. (See #19507) for ar in trig_arguments: try: poly_ar = Poly(ar, symbol) except PolynomialError: raise ValueError("give up, we can't solve if this is not a polynomial in x") if poly_ar.degree() > 1: # degree >1 still bad raise ValueError("degree of variable inside polynomial should not exceed one") if poly_ar.degree() == 0: # degree 0, don't care continue c = poly_ar.all_coeffs()[0] # got the coefficient of 'symbol' try: numerators.append(Rational(c).p) denominators.append(Rational(c).q) except TypeError: return ConditionSet(symbol, Eq(f_original, 0), domain) x = Dummy('x') # ilcm() and igcd() require more than one argument if len(numerators) > 1: mu = Rational(2)*ilcm(*denominators)/igcd(*numerators) else: assert len(numerators) == 1 mu = Rational(2)*denominators[0]/numerators[0] f = f.subs(symbol, mu*x) f = f.rewrite(tan) f = expand_trig(f) f = together(f) g, h = fraction(f) y = Dummy('y') g, h = g.expand(), h.expand() g, h = g.subs(tan(x), y), h.subs(tan(x), y) if g.has(x) or h.has(x): return ConditionSet(symbol, Eq(f_original, 0), domain) solns = solveset(g, y, S.Reals) - solveset(h, y, S.Reals) if isinstance(solns, FiniteSet): result = Union(*[invert_real(tan(symbol/mu), s, symbol)[1] for s in solns]) dsol = invert_real(tan(symbol/mu), oo, symbol)[1] if degree(h) > degree(g): # If degree(denom)>degree(num) then there result = Union(result, dsol) # would be another sol at Lim(denom-->oo) return Intersection(result, domain) elif solns is S.EmptySet: return S.EmptySet else: return ConditionSet(symbol, Eq(f_original, 0), S.Reals) def _solve_as_poly(f, symbol, domain=S.Complexes): """ Solve the equation using polynomial techniques if it already is a polynomial equation or, with a change of variables, can be made so. """ result = None if f.is_polynomial(symbol): solns = roots(f, symbol, cubics=True, quartics=True, quintics=True, domain='EX') num_roots = sum(solns.values()) if degree(f, symbol) <= num_roots: result = FiniteSet(*solns.keys()) else: poly = Poly(f, symbol) solns = poly.all_roots() if poly.degree() <= len(solns): result = FiniteSet(*solns) else: result = ConditionSet(symbol, Eq(f, 0), domain) else: poly = Poly(f) if poly is None: result = ConditionSet(symbol, Eq(f, 0), domain) gens = [g for g in poly.gens if g.has(symbol)] if len(gens) == 1: poly = Poly(poly, gens[0]) gen = poly.gen deg = poly.degree() poly = Poly(poly.as_expr(), poly.gen, composite=True) poly_solns = FiniteSet(*roots(poly, cubics=True, quartics=True, quintics=True).keys()) if len(poly_solns) < deg: result = ConditionSet(symbol, Eq(f, 0), domain) if gen != symbol: y = Dummy('y') inverter = invert_real if domain.is_subset(S.Reals) else invert_complex lhs, rhs_s = inverter(gen, y, symbol) if lhs == symbol: result = Union(*[rhs_s.subs(y, s) for s in poly_solns]) else: result = ConditionSet(symbol, Eq(f, 0), domain) else: result = ConditionSet(symbol, Eq(f, 0), domain) if result is not None: if isinstance(result, FiniteSet): # this is to simplify solutions like -sqrt(-I) to sqrt(2)/2 # - sqrt(2)*I/2. We are not expanding for solution with symbols # or undefined functions because that makes the solution more complicated. # For example, expand_complex(a) returns re(a) + I*im(a) if all([s.atoms(Symbol, AppliedUndef) == set() and not isinstance(s, RootOf) for s in result]): s = Dummy('s') result = imageset(Lambda(s, expand_complex(s)), result) if isinstance(result, FiniteSet) and domain != S.Complexes: # Avoid adding gratuitous intersections with S.Complexes. Actual # conditions should be handled elsewhere. result = result.intersection(domain) return result else: return ConditionSet(symbol, Eq(f, 0), domain) def _has_rational_power(expr, symbol): """ Returns (bool, den) where bool is True if the term has a non-integer rational power and den is the denominator of the expression's exponent. Examples ======== >>> from sympy.solvers.solveset import _has_rational_power >>> from sympy import sqrt >>> from sympy.abc import x >>> _has_rational_power(sqrt(x), x) (True, 2) >>> _has_rational_power(x**2, x) (False, 1) """ a, p, q = Wild('a'), Wild('p'), Wild('q') pattern_match = expr.match(a*p**q) or {} if pattern_match.get(a, S.Zero).is_zero: return (False, S.One) elif p not in pattern_match.keys(): return (False, S.One) elif isinstance(pattern_match[q], Rational) \ and pattern_match[p].has(symbol): if not pattern_match[q].q == S.One: return (True, pattern_match[q].q) if not isinstance(pattern_match[a], Pow) \ or isinstance(pattern_match[a], Mul): return (False, S.One) else: return _has_rational_power(pattern_match[a], symbol) def _solve_radical(f, symbol, solveset_solver): """ Helper function to solve equations with radicals """ res = unrad(f) eq, cov = res if res else (f, []) if not cov: result = solveset_solver(eq, symbol) - \ Union(*[solveset_solver(g, symbol) for g in denoms(f, symbol)]) else: y, yeq = cov if not solveset_solver(y - I, y): yreal = Dummy('yreal', real=True) yeq = yeq.xreplace({y: yreal}) eq = eq.xreplace({y: yreal}) y = yreal g_y_s = solveset_solver(yeq, symbol) f_y_sols = solveset_solver(eq, y) result = Union(*[imageset(Lambda(y, g_y), f_y_sols) for g_y in g_y_s]) if isinstance(result, Complement) or isinstance(result,ConditionSet): solution_set = result else: f_set = [] # solutions for FiniteSet c_set = [] # solutions for ConditionSet for s in result: if checksol(f, symbol, s): f_set.append(s) else: c_set.append(s) solution_set = FiniteSet(*f_set) + ConditionSet(symbol, Eq(f, 0), FiniteSet(*c_set)) return solution_set def _solve_abs(f, symbol, domain): """ Helper function to solve equation involving absolute value function """ if not domain.is_subset(S.Reals): raise ValueError(filldedent(''' Absolute values cannot be inverted in the complex domain.''')) p, q, r = Wild('p'), Wild('q'), Wild('r') pattern_match = f.match(p*Abs(q) + r) or {} f_p, f_q, f_r = [pattern_match.get(i, S.Zero) for i in (p, q, r)] if not (f_p.is_zero or f_q.is_zero): domain = continuous_domain(f_q, symbol, domain) q_pos_cond = solve_univariate_inequality(f_q >= 0, symbol, relational=False, domain=domain, continuous=True) q_neg_cond = q_pos_cond.complement(domain) sols_q_pos = solveset_real(f_p*f_q + f_r, symbol).intersect(q_pos_cond) sols_q_neg = solveset_real(f_p*(-f_q) + f_r, symbol).intersect(q_neg_cond) return Union(sols_q_pos, sols_q_neg) else: return ConditionSet(symbol, Eq(f, 0), domain) def solve_decomposition(f, symbol, domain): """ Function to solve equations via the principle of "Decomposition and Rewriting". Examples ======== >>> from sympy import exp, sin, Symbol, pprint, S >>> from sympy.solvers.solveset import solve_decomposition as sd >>> x = Symbol('x') >>> f1 = exp(2*x) - 3*exp(x) + 2 >>> sd(f1, x, S.Reals) FiniteSet(0, log(2)) >>> f2 = sin(x)**2 + 2*sin(x) + 1 >>> pprint(sd(f2, x, S.Reals), use_unicode=False) 3*pi {2*n*pi + ---- | n in Integers} 2 >>> f3 = sin(x + 2) >>> pprint(sd(f3, x, S.Reals), use_unicode=False) {2*n*pi - 2 | n in Integers} U {2*n*pi - 2 + pi | n in Integers} """ from sympy.solvers.decompogen import decompogen from sympy.calculus.util import function_range # decompose the given function g_s = decompogen(f, symbol) # `y_s` represents the set of values for which the function `g` is to be # solved. # `solutions` represent the solutions of the equations `g = y_s` or # `g = 0` depending on the type of `y_s`. # As we are interested in solving the equation: f = 0 y_s = FiniteSet(0) for g in g_s: frange = function_range(g, symbol, domain) y_s = Intersection(frange, y_s) result = S.EmptySet if isinstance(y_s, FiniteSet): for y in y_s: solutions = solveset(Eq(g, y), symbol, domain) if not isinstance(solutions, ConditionSet): result += solutions else: if isinstance(y_s, ImageSet): iter_iset = (y_s,) elif isinstance(y_s, Union): iter_iset = y_s.args elif y_s is EmptySet: # y_s is not in the range of g in g_s, so no solution exists #in the given domain return EmptySet for iset in iter_iset: new_solutions = solveset(Eq(iset.lamda.expr, g), symbol, domain) dummy_var = tuple(iset.lamda.expr.free_symbols)[0] (base_set,) = iset.base_sets if isinstance(new_solutions, FiniteSet): new_exprs = new_solutions elif isinstance(new_solutions, Intersection): if isinstance(new_solutions.args[1], FiniteSet): new_exprs = new_solutions.args[1] for new_expr in new_exprs: result += ImageSet(Lambda(dummy_var, new_expr), base_set) if result is S.EmptySet: return ConditionSet(symbol, Eq(f, 0), domain) y_s = result return y_s def _solveset(f, symbol, domain, _check=False): """Helper for solveset to return a result from an expression that has already been sympify'ed and is known to contain the given symbol.""" # _check controls whether the answer is checked or not from sympy.simplify.simplify import signsimp from sympy.logic.boolalg import BooleanTrue if isinstance(f, BooleanTrue): return domain orig_f = f if f.is_Mul: coeff, f = f.as_independent(symbol, as_Add=False) if coeff in {S.ComplexInfinity, S.NegativeInfinity, S.Infinity}: f = together(orig_f) elif f.is_Add: a, h = f.as_independent(symbol) m, h = h.as_independent(symbol, as_Add=False) if m not in {S.ComplexInfinity, S.Zero, S.Infinity, S.NegativeInfinity}: f = a/m + h # XXX condition `m != 0` should be added to soln # assign the solvers to use solver = lambda f, x, domain=domain: _solveset(f, x, domain) inverter = lambda f, rhs, symbol: _invert(f, rhs, symbol, domain) result = EmptySet if f.expand().is_zero: return domain elif not f.has(symbol): return EmptySet elif f.is_Mul and all(_is_finite_with_finite_vars(m, domain) for m in f.args): # if f(x) and g(x) are both finite we can say that the solution of # f(x)*g(x) == 0 is same as Union(f(x) == 0, g(x) == 0) is not true in # general. g(x) can grow to infinitely large for the values where # f(x) == 0. To be sure that we are not silently allowing any # wrong solutions we are using this technique only if both f and g are # finite for a finite input. result = Union(*[solver(m, symbol) for m in f.args]) elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \ _is_function_class_equation(HyperbolicFunction, f, symbol): result = _solve_trig(f, symbol, domain) elif isinstance(f, arg): a = f.args[0] result = solveset_real(a > 0, symbol) elif f.is_Piecewise: expr_set_pairs = f.as_expr_set_pairs(domain) for (expr, in_set) in expr_set_pairs: if in_set.is_Relational: in_set = in_set.as_set() solns = solver(expr, symbol, in_set) result += solns elif isinstance(f, Eq): result = solver(Add(f.lhs, - f.rhs, evaluate=False), symbol, domain) elif f.is_Relational: if not domain.is_subset(S.Reals): raise NotImplementedError(filldedent(''' Inequalities in the complex domain are not supported. Try the real domain by setting domain=S.Reals''')) try: result = solve_univariate_inequality( f, symbol, domain=domain, relational=False) except NotImplementedError: result = ConditionSet(symbol, f, domain) return result elif _is_modular(f, symbol): result = _solve_modular(f, symbol, domain) else: lhs, rhs_s = inverter(f, 0, symbol) if lhs == symbol: # do some very minimal simplification since # repeated inversion may have left the result # in a state that other solvers (e.g. poly) # would have simplified; this is done here # rather than in the inverter since here it # is only done once whereas there it would # be repeated for each step of the inversion if isinstance(rhs_s, FiniteSet): rhs_s = FiniteSet(*[Mul(* signsimp(i).as_content_primitive()) for i in rhs_s]) result = rhs_s elif isinstance(rhs_s, FiniteSet): for equation in [lhs - rhs for rhs in rhs_s]: if equation == f: if any(_has_rational_power(g, symbol)[0] for g in equation.args) or _has_rational_power( equation, symbol)[0]: result += _solve_radical(equation, symbol, solver) elif equation.has(Abs): result += _solve_abs(f, symbol, domain) else: result_rational = _solve_as_rational(equation, symbol, domain) if isinstance(result_rational, ConditionSet): # may be a transcendental type equation result += _transolve(equation, symbol, domain) else: result += result_rational else: result += solver(equation, symbol) elif rhs_s is not S.EmptySet: result = ConditionSet(symbol, Eq(f, 0), domain) if isinstance(result, ConditionSet): if isinstance(f, Expr): num, den = f.as_numer_denom() else: num, den = f, S.One if den.has(symbol): _result = _solveset(num, symbol, domain) if not isinstance(_result, ConditionSet): singularities = _solveset(den, symbol, domain) result = _result - singularities if _check: if isinstance(result, ConditionSet): # it wasn't solved or has enumerated all conditions # -- leave it alone return result # whittle away all but the symbol-containing core # to use this for testing if isinstance(orig_f, Expr): fx = orig_f.as_independent(symbol, as_Add=True)[1] fx = fx.as_independent(symbol, as_Add=False)[1] else: fx = orig_f if isinstance(result, FiniteSet): # check the result for invalid solutions result = FiniteSet(*[s for s in result if isinstance(s, RootOf) or domain_check(fx, symbol, s)]) return result def _is_modular(f, symbol): """ Helper function to check below mentioned types of modular equations. ``A - Mod(B, C) = 0`` A -> This can or cannot be a function of symbol. B -> This is surely a function of symbol. C -> It is an integer. Parameters ========== f : Expr The equation to be checked. symbol : Symbol The concerned variable for which the equation is to be checked. Examples ======== >>> from sympy import symbols, exp, Mod >>> from sympy.solvers.solveset import _is_modular as check >>> x, y = symbols('x y') >>> check(Mod(x, 3) - 1, x) True >>> check(Mod(x, 3) - 1, y) False >>> check(Mod(x, 3)**2 - 5, x) False >>> check(Mod(x, 3)**2 - y, x) False >>> check(exp(Mod(x, 3)) - 1, x) False >>> check(Mod(3, y) - 1, y) False """ if not f.has(Mod): return False # extract modterms from f. modterms = list(f.atoms(Mod)) return (len(modterms) == 1 and # only one Mod should be present modterms[0].args[0].has(symbol) and # B-> function of symbol modterms[0].args[1].is_integer and # C-> to be an integer. any(isinstance(term, Mod) for term in list(_term_factors(f))) # free from other funcs ) def _invert_modular(modterm, rhs, n, symbol): """ Helper function to invert modular equation. ``Mod(a, m) - rhs = 0`` Generally it is inverted as (a, ImageSet(Lambda(n, m*n + rhs), S.Integers)). More simplified form will be returned if possible. If it is not invertible then (modterm, rhs) is returned. The following cases arise while inverting equation ``Mod(a, m) - rhs = 0``: 1. If a is symbol then m*n + rhs is the required solution. 2. If a is an instance of ``Add`` then we try to find two symbol independent parts of a and the symbol independent part gets tranferred to the other side and again the ``_invert_modular`` is called on the symbol dependent part. 3. If a is an instance of ``Mul`` then same as we done in ``Add`` we separate out the symbol dependent and symbol independent parts and transfer the symbol independent part to the rhs with the help of invert and again the ``_invert_modular`` is called on the symbol dependent part. 4. If a is an instance of ``Pow`` then two cases arise as following: - If a is of type (symbol_indep)**(symbol_dep) then the remainder is evaluated with the help of discrete_log function and then the least period is being found out with the help of totient function. period*n + remainder is the required solution in this case. For reference: (https://en.wikipedia.org/wiki/Euler's_theorem) - If a is of type (symbol_dep)**(symbol_indep) then we try to find all primitive solutions list with the help of nthroot_mod function. m*n + rem is the general solution where rem belongs to solutions list from nthroot_mod function. Parameters ========== modterm, rhs : Expr The modular equation to be inverted, ``modterm - rhs = 0`` symbol : Symbol The variable in the equation to be inverted. n : Dummy Dummy variable for output g_n. Returns ======= A tuple (f_x, g_n) is being returned where f_x is modular independent function of symbol and g_n being set of values f_x can have. Examples ======== >>> from sympy import symbols, exp, Mod, Dummy, S >>> from sympy.solvers.solveset import _invert_modular as invert_modular >>> x, y = symbols('x y') >>> n = Dummy('n') >>> invert_modular(Mod(exp(x), 7), S(5), n, x) (Mod(exp(x), 7), 5) >>> invert_modular(Mod(x, 7), S(5), n, x) (x, ImageSet(Lambda(_n, 7*_n + 5), Integers)) >>> invert_modular(Mod(3*x + 8, 7), S(5), n, x) (x, ImageSet(Lambda(_n, 7*_n + 6), Integers)) >>> invert_modular(Mod(x**4, 7), S(5), n, x) (x, EmptySet) >>> invert_modular(Mod(2**(x**2 + x + 1), 7), S(2), n, x) (x**2 + x + 1, ImageSet(Lambda(_n, 3*_n + 1), Naturals0)) """ a, m = modterm.args if rhs.is_real is False or any(term.is_real is False for term in list(_term_factors(a))): # Check for complex arguments return modterm, rhs if abs(rhs) >= abs(m): # if rhs has value greater than value of m. return symbol, EmptySet if a == symbol: return symbol, ImageSet(Lambda(n, m*n + rhs), S.Integers) if a.is_Add: # g + h = a g, h = a.as_independent(symbol) if g is not S.Zero: x_indep_term = rhs - Mod(g, m) return _invert_modular(Mod(h, m), Mod(x_indep_term, m), n, symbol) if a.is_Mul: # g*h = a g, h = a.as_independent(symbol) if g is not S.One: x_indep_term = rhs*invert(g, m) return _invert_modular(Mod(h, m), Mod(x_indep_term, m), n, symbol) if a.is_Pow: # base**expo = a base, expo = a.args if expo.has(symbol) and not base.has(symbol): # remainder -> solution independent of n of equation. # m, rhs are made coprime by dividing igcd(m, rhs) try: remainder = discrete_log(m / igcd(m, rhs), rhs, a.base) except ValueError: # log does not exist return modterm, rhs # period -> coefficient of n in the solution and also referred as # the least period of expo in which it is repeats itself. # (a**(totient(m)) - 1) divides m. Here is link of theorem: # (https://en.wikipedia.org/wiki/Euler's_theorem) period = totient(m) for p in divisors(period): # there might a lesser period exist than totient(m). if pow(a.base, p, m / igcd(m, a.base)) == 1: period = p break # recursion is not applied here since _invert_modular is currently # not smart enough to handle infinite rhs as here expo has infinite # rhs = ImageSet(Lambda(n, period*n + remainder), S.Naturals0). return expo, ImageSet(Lambda(n, period*n + remainder), S.Naturals0) elif base.has(symbol) and not expo.has(symbol): try: remainder_list = nthroot_mod(rhs, expo, m, all_roots=True) if remainder_list == []: return symbol, EmptySet except (ValueError, NotImplementedError): return modterm, rhs g_n = EmptySet for rem in remainder_list: g_n += ImageSet(Lambda(n, m*n + rem), S.Integers) return base, g_n return modterm, rhs def _solve_modular(f, symbol, domain): r""" Helper function for solving modular equations of type ``A - Mod(B, C) = 0``, where A can or cannot be a function of symbol, B is surely a function of symbol and C is an integer. Currently ``_solve_modular`` is only able to solve cases where A is not a function of symbol. Parameters ========== f : Expr The modular equation to be solved, ``f = 0`` symbol : Symbol The variable in the equation to be solved. domain : Set A set over which the equation is solved. It has to be a subset of Integers. Returns ======= A set of integer solutions satisfying the given modular equation. A ``ConditionSet`` if the equation is unsolvable. Examples ======== >>> from sympy.solvers.solveset import _solve_modular as solve_modulo >>> from sympy import S, Symbol, sin, Intersection, Interval >>> from sympy.core.mod import Mod >>> x = Symbol('x') >>> solve_modulo(Mod(5*x - 8, 7) - 3, x, S.Integers) ImageSet(Lambda(_n, 7*_n + 5), Integers) >>> solve_modulo(Mod(5*x - 8, 7) - 3, x, S.Reals) # domain should be subset of integers. ConditionSet(x, Eq(Mod(5*x + 6, 7) - 3, 0), Reals) >>> solve_modulo(-7 + Mod(x, 5), x, S.Integers) EmptySet >>> solve_modulo(Mod(12**x, 21) - 18, x, S.Integers) ImageSet(Lambda(_n, 6*_n + 2), Naturals0) >>> solve_modulo(Mod(sin(x), 7) - 3, x, S.Integers) # not solvable ConditionSet(x, Eq(Mod(sin(x), 7) - 3, 0), Integers) >>> solve_modulo(3 - Mod(x, 5), x, Intersection(S.Integers, Interval(0, 100))) Intersection(ImageSet(Lambda(_n, 5*_n + 3), Integers), Range(0, 101, 1)) """ # extract modterm and g_y from f unsolved_result = ConditionSet(symbol, Eq(f, 0), domain) modterm = list(f.atoms(Mod))[0] rhs = -S.One*(f.subs(modterm, S.Zero)) if f.as_coefficients_dict()[modterm].is_negative: # checks if coefficient of modterm is negative in main equation. rhs *= -S.One if not domain.is_subset(S.Integers): return unsolved_result if rhs.has(symbol): # TODO Case: A-> function of symbol, can be extended here # in future. return unsolved_result n = Dummy('n', integer=True) f_x, g_n = _invert_modular(modterm, rhs, n, symbol) if f_x == modterm and g_n == rhs: return unsolved_result if f_x == symbol: if domain is not S.Integers: return domain.intersect(g_n) return g_n if isinstance(g_n, ImageSet): lamda_expr = g_n.lamda.expr lamda_vars = g_n.lamda.variables base_sets = g_n.base_sets sol_set = _solveset(f_x - lamda_expr, symbol, S.Integers) if isinstance(sol_set, FiniteSet): tmp_sol = EmptySet for sol in sol_set: tmp_sol += ImageSet(Lambda(lamda_vars, sol), *base_sets) sol_set = tmp_sol else: sol_set = ImageSet(Lambda(lamda_vars, sol_set), *base_sets) return domain.intersect(sol_set) return unsolved_result def _term_factors(f): """ Iterator to get the factors of all terms present in the given equation. Parameters ========== f : Expr Equation that needs to be addressed Returns ======= Factors of all terms present in the equation. Examples ======== >>> from sympy import symbols >>> from sympy.solvers.solveset import _term_factors >>> x = symbols('x') >>> list(_term_factors(-2 - x**2 + x*(x + 1))) [-2, -1, x**2, x, x + 1] """ for add_arg in Add.make_args(f): yield from Mul.make_args(add_arg) def _solve_exponential(lhs, rhs, symbol, domain): r""" Helper function for solving (supported) exponential equations. Exponential equations are the sum of (currently) at most two terms with one or both of them having a power with a symbol-dependent exponent. For example .. math:: 5^{2x + 3} - 5^{3x - 1} .. math:: 4^{5 - 9x} - e^{2 - x} Parameters ========== lhs, rhs : Expr The exponential equation to be solved, `lhs = rhs` symbol : Symbol The variable in which the equation is solved domain : Set A set over which the equation is solved. Returns ======= A set of solutions satisfying the given equation. A ``ConditionSet`` if the equation is unsolvable or if the assumptions are not properly defined, in that case a different style of ``ConditionSet`` is returned having the solution(s) of the equation with the desired assumptions. Examples ======== >>> from sympy.solvers.solveset import _solve_exponential as solve_expo >>> from sympy import symbols, S >>> x = symbols('x', real=True) >>> a, b = symbols('a b') >>> solve_expo(2**x + 3**x - 5**x, 0, x, S.Reals) # not solvable ConditionSet(x, Eq(2**x + 3**x - 5**x, 0), Reals) >>> solve_expo(a**x - b**x, 0, x, S.Reals) # solvable but incorrect assumptions ConditionSet(x, (a > 0) & (b > 0), FiniteSet(0)) >>> solve_expo(3**(2*x) - 2**(x + 3), 0, x, S.Reals) FiniteSet(-3*log(2)/(-2*log(3) + log(2))) >>> solve_expo(2**x - 4**x, 0, x, S.Reals) FiniteSet(0) * Proof of correctness of the method The logarithm function is the inverse of the exponential function. The defining relation between exponentiation and logarithm is: .. math:: {\log_b x} = y \enspace if \enspace b^y = x Therefore if we are given an equation with exponent terms, we can convert every term to its corresponding logarithmic form. This is achieved by taking logarithms and expanding the equation using logarithmic identities so that it can easily be handled by ``solveset``. For example: .. math:: 3^{2x} = 2^{x + 3} Taking log both sides will reduce the equation to .. math:: (2x)\log(3) = (x + 3)\log(2) This form can be easily handed by ``solveset``. """ unsolved_result = ConditionSet(symbol, Eq(lhs - rhs, 0), domain) newlhs = powdenest(lhs) if lhs != newlhs: # it may also be advantageous to factor the new expr return _solveset(factor(newlhs - rhs), symbol, domain) # try again with _solveset if not (isinstance(lhs, Add) and len(lhs.args) == 2): # solving for the sum of more than two powers is possible # but not yet implemented return unsolved_result if rhs != 0: return unsolved_result a, b = list(ordered(lhs.args)) a_term = a.as_independent(symbol)[1] b_term = b.as_independent(symbol)[1] a_base, a_exp = a_term.base, a_term.exp b_base, b_exp = b_term.base, b_term.exp from sympy.functions.elementary.complexes import im if domain.is_subset(S.Reals): conditions = And( a_base > 0, b_base > 0, Eq(im(a_exp), 0), Eq(im(b_exp), 0)) else: conditions = And( Ne(a_base, 0), Ne(b_base, 0)) L, R = map(lambda i: expand_log(log(i), force=True), (a, -b)) solutions = _solveset(L - R, symbol, domain) return ConditionSet(symbol, conditions, solutions) def _is_exponential(f, symbol): r""" Return ``True`` if one or more terms contain ``symbol`` only in exponents, else ``False``. Parameters ========== f : Expr The equation to be checked symbol : Symbol The variable in which the equation is checked Examples ======== >>> from sympy import symbols, cos, exp >>> from sympy.solvers.solveset import _is_exponential as check >>> x, y = symbols('x y') >>> check(y, y) False >>> check(x**y - 1, y) True >>> check(x**y*2**y - 1, y) True >>> check(exp(x + 3) + 3**x, x) True >>> check(cos(2**x), x) False * Philosophy behind the helper The function extracts each term of the equation and checks if it is of exponential form w.r.t ``symbol``. """ rv = False for expr_arg in _term_factors(f): if symbol not in expr_arg.free_symbols: continue if (isinstance(expr_arg, Pow) and symbol not in expr_arg.base.free_symbols or isinstance(expr_arg, exp)): rv = True # symbol in exponent else: return False # dependent on symbol in non-exponential way return rv def _solve_logarithm(lhs, rhs, symbol, domain): r""" Helper to solve logarithmic equations which are reducible to a single instance of `\log`. Logarithmic equations are (currently) the equations that contains `\log` terms which can be reduced to a single `\log` term or a constant using various logarithmic identities. For example: .. math:: \log(x) + \log(x - 4) can be reduced to: .. math:: \log(x(x - 4)) Parameters ========== lhs, rhs : Expr The logarithmic equation to be solved, `lhs = rhs` symbol : Symbol The variable in which the equation is solved domain : Set A set over which the equation is solved. Returns ======= A set of solutions satisfying the given equation. A ``ConditionSet`` if the equation is unsolvable. Examples ======== >>> from sympy import symbols, log, S >>> from sympy.solvers.solveset import _solve_logarithm as solve_log >>> x = symbols('x') >>> f = log(x - 3) + log(x + 3) >>> solve_log(f, 0, x, S.Reals) FiniteSet(sqrt(10), -sqrt(10)) * Proof of correctness A logarithm is another way to write exponent and is defined by .. math:: {\log_b x} = y \enspace if \enspace b^y = x When one side of the equation contains a single logarithm, the equation can be solved by rewriting the equation as an equivalent exponential equation as defined above. But if one side contains more than one logarithm, we need to use the properties of logarithm to condense it into a single logarithm. Take for example .. math:: \log(2x) - 15 = 0 contains single logarithm, therefore we can directly rewrite it to exponential form as .. math:: x = \frac{e^{15}}{2} But if the equation has more than one logarithm as .. math:: \log(x - 3) + \log(x + 3) = 0 we use logarithmic identities to convert it into a reduced form Using, .. math:: \log(a) + \log(b) = \log(ab) the equation becomes, .. math:: \log((x - 3)(x + 3)) This equation contains one logarithm and can be solved by rewriting to exponents. """ new_lhs = logcombine(lhs, force=True) new_f = new_lhs - rhs return _solveset(new_f, symbol, domain) def _is_logarithmic(f, symbol): r""" Return ``True`` if the equation is in the form `a\log(f(x)) + b\log(g(x)) + ... + c` else ``False``. Parameters ========== f : Expr The equation to be checked symbol : Symbol The variable in which the equation is checked Returns ======= ``True`` if the equation is logarithmic otherwise ``False``. Examples ======== >>> from sympy import symbols, tan, log >>> from sympy.solvers.solveset import _is_logarithmic as check >>> x, y = symbols('x y') >>> check(log(x + 2) - log(x + 3), x) True >>> check(tan(log(2*x)), x) False >>> check(x*log(x), x) False >>> check(x + log(x), x) False >>> check(y + log(x), x) True * Philosophy behind the helper The function extracts each term and checks whether it is logarithmic w.r.t ``symbol``. """ rv = False for term in Add.make_args(f): saw_log = False for term_arg in Mul.make_args(term): if symbol not in term_arg.free_symbols: continue if isinstance(term_arg, log): if saw_log: return False # more than one log in term saw_log = True else: return False # dependent on symbol in non-log way if saw_log: rv = True return rv def _transolve(f, symbol, domain): r""" Function to solve transcendental equations. It is a helper to ``solveset`` and should be used internally. ``_transolve`` currently supports the following class of equations: - Exponential equations - Logarithmic equations Parameters ========== f : Any transcendental equation that needs to be solved. This needs to be an expression, which is assumed to be equal to ``0``. symbol : The variable for which the equation is solved. This needs to be of class ``Symbol``. domain : A set over which the equation is solved. This needs to be of class ``Set``. Returns ======= Set A set of values for ``symbol`` for which ``f`` is equal to zero. An ``EmptySet`` is returned if ``f`` does not have solutions in respective domain. A ``ConditionSet`` is returned as unsolved object if algorithms to evaluate complete solution are not yet implemented. How to use ``_transolve`` ========================= ``_transolve`` should not be used as an independent function, because it assumes that the equation (``f``) and the ``symbol`` comes from ``solveset`` and might have undergone a few modification(s). To use ``_transolve`` as an independent function the equation (``f``) and the ``symbol`` should be passed as they would have been by ``solveset``. Examples ======== >>> from sympy.solvers.solveset import _transolve as transolve >>> from sympy.solvers.solvers import _tsolve as tsolve >>> from sympy import symbols, S, pprint >>> x = symbols('x', real=True) # assumption added >>> transolve(5**(x - 3) - 3**(2*x + 1), x, S.Reals) FiniteSet(-(log(3) + 3*log(5))/(-log(5) + 2*log(3))) How ``_transolve`` works ======================== ``_transolve`` uses two types of helper functions to solve equations of a particular class: Identifying helpers: To determine whether a given equation belongs to a certain class of equation or not. Returns either ``True`` or ``False``. Solving helpers: Once an equation is identified, a corresponding helper either solves the equation or returns a form of the equation that ``solveset`` might better be able to handle. * Philosophy behind the module The purpose of ``_transolve`` is to take equations which are not already polynomial in their generator(s) and to either recast them as such through a valid transformation or to solve them outright. A pair of helper functions for each class of supported transcendental functions are employed for this purpose. One identifies the transcendental form of an equation and the other either solves it or recasts it into a tractable form that can be solved by ``solveset``. For example, an equation in the form `ab^{f(x)} - cd^{g(x)} = 0` can be transformed to `\log(a) + f(x)\log(b) - \log(c) - g(x)\log(d) = 0` (under certain assumptions) and this can be solved with ``solveset`` if `f(x)` and `g(x)` are in polynomial form. How ``_transolve`` is better than ``_tsolve`` ============================================= 1) Better output ``_transolve`` provides expressions in a more simplified form. Consider a simple exponential equation >>> f = 3**(2*x) - 2**(x + 3) >>> pprint(transolve(f, x, S.Reals), use_unicode=False) -3*log(2) {------------------} -2*log(3) + log(2) >>> pprint(tsolve(f, x), use_unicode=False) / 3 \ | --------| | log(2/9)| [-log\2 /] 2) Extensible The API of ``_transolve`` is designed such that it is easily extensible, i.e. the code that solves a given class of equations is encapsulated in a helper and not mixed in with the code of ``_transolve`` itself. 3) Modular ``_transolve`` is designed to be modular i.e, for every class of equation a separate helper for identification and solving is implemented. This makes it easy to change or modify any of the method implemented directly in the helpers without interfering with the actual structure of the API. 4) Faster Computation Solving equation via ``_transolve`` is much faster as compared to ``_tsolve``. In ``solve``, attempts are made computing every possibility to get the solutions. This series of attempts makes solving a bit slow. In ``_transolve``, computation begins only after a particular type of equation is identified. How to add new class of equations ================================= Adding a new class of equation solver is a three-step procedure: - Identify the type of the equations Determine the type of the class of equations to which they belong: it could be of ``Add``, ``Pow``, etc. types. Separate internal functions are used for each type. Write identification and solving helpers and use them from within the routine for the given type of equation (after adding it, if necessary). Something like: .. code-block:: python def add_type(lhs, rhs, x): .... if _is_exponential(lhs, x): new_eq = _solve_exponential(lhs, rhs, x) .... rhs, lhs = eq.as_independent(x) if lhs.is_Add: result = add_type(lhs, rhs, x) - Define the identification helper. - Define the solving helper. Apart from this, a few other things needs to be taken care while adding an equation solver: - Naming conventions: Name of the identification helper should be as ``_is_class`` where class will be the name or abbreviation of the class of equation. The solving helper will be named as ``_solve_class``. For example: for exponential equations it becomes ``_is_exponential`` and ``_solve_expo``. - The identifying helpers should take two input parameters, the equation to be checked and the variable for which a solution is being sought, while solving helpers would require an additional domain parameter. - Be sure to consider corner cases. - Add tests for each helper. - Add a docstring to your helper that describes the method implemented. The documentation of the helpers should identify: - the purpose of the helper, - the method used to identify and solve the equation, - a proof of correctness - the return values of the helpers """ def add_type(lhs, rhs, symbol, domain): """ Helper for ``_transolve`` to handle equations of ``Add`` type, i.e. equations taking the form as ``a*f(x) + b*g(x) + .... = c``. For example: 4**x + 8**x = 0 """ result = ConditionSet(symbol, Eq(lhs - rhs, 0), domain) # check if it is exponential type equation if _is_exponential(lhs, symbol): result = _solve_exponential(lhs, rhs, symbol, domain) # check if it is logarithmic type equation elif _is_logarithmic(lhs, symbol): result = _solve_logarithm(lhs, rhs, symbol, domain) return result result = ConditionSet(symbol, Eq(f, 0), domain) # invert_complex handles the call to the desired inverter based # on the domain specified. lhs, rhs_s = invert_complex(f, 0, symbol, domain) if isinstance(rhs_s, FiniteSet): assert (len(rhs_s.args)) == 1 rhs = rhs_s.args[0] if lhs.is_Add: result = add_type(lhs, rhs, symbol, domain) else: result = rhs_s return result def solveset(f, symbol=None, domain=S.Complexes): r"""Solves a given inequality or equation with set as output Parameters ========== f : Expr or a relational. The target equation or inequality symbol : Symbol The variable for which the equation is solved domain : Set The domain over which the equation is solved Returns ======= Set A set of values for `symbol` for which `f` is True or is equal to zero. An `EmptySet` is returned if `f` is False or nonzero. A `ConditionSet` is returned as unsolved object if algorithms to evaluate complete solution are not yet implemented. `solveset` claims to be complete in the solution set that it returns. Raises ====== NotImplementedError The algorithms to solve inequalities in complex domain are not yet implemented. ValueError The input is not valid. RuntimeError It is a bug, please report to the github issue tracker. Notes ===== Python interprets 0 and 1 as False and True, respectively, but in this function they refer to solutions of an expression. So 0 and 1 return the Domain and EmptySet, respectively, while True and False return the opposite (as they are assumed to be solutions of relational expressions). See Also ======== solveset_real: solver for real domain solveset_complex: solver for complex domain Examples ======== >>> from sympy import exp, sin, Symbol, pprint, S, Eq >>> from sympy.solvers.solveset import solveset, solveset_real * The default domain is complex. Not specifying a domain will lead to the solving of the equation in the complex domain (and this is not affected by the assumptions on the symbol): >>> x = Symbol('x') >>> pprint(solveset(exp(x) - 1, x), use_unicode=False) {2*n*I*pi | n in Integers} >>> x = Symbol('x', real=True) >>> pprint(solveset(exp(x) - 1, x), use_unicode=False) {2*n*I*pi | n in Integers} * If you want to use `solveset` to solve the equation in the real domain, provide a real domain. (Using ``solveset_real`` does this automatically.) >>> R = S.Reals >>> x = Symbol('x') >>> solveset(exp(x) - 1, x, R) FiniteSet(0) >>> solveset_real(exp(x) - 1, x) FiniteSet(0) The solution is unaffected by assumptions on the symbol: >>> p = Symbol('p', positive=True) >>> pprint(solveset(p**2 - 4)) {-2, 2} When a conditionSet is returned, symbols with assumptions that would alter the set are replaced with more generic symbols: >>> i = Symbol('i', imaginary=True) >>> solveset(Eq(i**2 + i*sin(i), 1), i, domain=S.Reals) ConditionSet(_R, Eq(_R**2 + _R*sin(_R) - 1, 0), Reals) * Inequalities can be solved over the real domain only. Use of a complex domain leads to a NotImplementedError. >>> solveset(exp(x) > 1, x, R) Interval.open(0, oo) """ f = sympify(f) symbol = sympify(symbol) if f is S.true: return domain if f is S.false: return S.EmptySet if not isinstance(f, (Expr, Relational, Number)): raise ValueError("%s is not a valid SymPy expression" % f) if not isinstance(symbol, (Expr, Relational)) and symbol is not None: raise ValueError("%s is not a valid SymPy symbol" % symbol) if not isinstance(domain, Set): raise ValueError("%s is not a valid domain" %(domain)) free_symbols = f.free_symbols if symbol is None and not free_symbols: b = Eq(f, 0) if b is S.true: return domain elif b is S.false: return S.EmptySet else: raise NotImplementedError(filldedent(''' relationship between value and 0 is unknown: %s''' % b)) if symbol is None: if len(free_symbols) == 1: symbol = free_symbols.pop() elif free_symbols: raise ValueError(filldedent(''' The independent variable must be specified for a multivariate equation.''')) elif not isinstance(symbol, Symbol): f, s, swap = recast_to_symbols([f], [symbol]) # the xreplace will be needed if a ConditionSet is returned return solveset(f[0], s[0], domain).xreplace(swap) # solveset should ignore assumptions on symbols if symbol not in _rc: x = _rc[0] if domain.is_subset(S.Reals) else _rc[1] rv = solveset(f.xreplace({symbol: x}), x, domain) # try to use the original symbol if possible try: _rv = rv.xreplace({x: symbol}) except TypeError: _rv = rv if rv.dummy_eq(_rv): rv = _rv return rv # Abs has its own handling method which avoids the # rewriting property that the first piece of abs(x) # is for x >= 0 and the 2nd piece for x < 0 -- solutions # can look better if the 2nd condition is x <= 0. Since # the solution is a set, duplication of results is not # an issue, e.g. {y, -y} when y is 0 will be {0} f, mask = _masked(f, Abs) f = f.rewrite(Piecewise) # everything that's not an Abs for d, e in mask: # everything *in* an Abs e = e.func(e.args[0].rewrite(Piecewise)) f = f.xreplace({d: e}) f = piecewise_fold(f) return _solveset(f, symbol, domain, _check=True) def solveset_real(f, symbol): return solveset(f, symbol, S.Reals) def solveset_complex(f, symbol): return solveset(f, symbol, S.Complexes) def _solveset_multi(eqs, syms, domains): '''Basic implementation of a multivariate solveset. For internal use (not ready for public consumption)''' rep = {} for sym, dom in zip(syms, domains): if dom is S.Reals: rep[sym] = Symbol(sym.name, real=True) eqs = [eq.subs(rep) for eq in eqs] syms = [sym.subs(rep) for sym in syms] syms = tuple(syms) if len(eqs) == 0: return ProductSet(*domains) if len(syms) == 1: sym = syms[0] domain = domains[0] solsets = [solveset(eq, sym, domain) for eq in eqs] solset = Intersection(*solsets) return ImageSet(Lambda((sym,), (sym,)), solset).doit() eqs = sorted(eqs, key=lambda eq: len(eq.free_symbols & set(syms))) for n in range(len(eqs)): sols = [] all_handled = True for sym in syms: if sym not in eqs[n].free_symbols: continue sol = solveset(eqs[n], sym, domains[syms.index(sym)]) if isinstance(sol, FiniteSet): i = syms.index(sym) symsp = syms[:i] + syms[i+1:] domainsp = domains[:i] + domains[i+1:] eqsp = eqs[:n] + eqs[n+1:] for s in sol: eqsp_sub = [eq.subs(sym, s) for eq in eqsp] sol_others = _solveset_multi(eqsp_sub, symsp, domainsp) fun = Lambda((symsp,), symsp[:i] + (s,) + symsp[i:]) sols.append(ImageSet(fun, sol_others).doit()) else: all_handled = False if all_handled: return Union(*sols) def solvify(f, symbol, domain): """Solves an equation using solveset and returns the solution in accordance with the `solve` output API. Returns ======= We classify the output based on the type of solution returned by `solveset`. Solution | Output ---------------------------------------- FiniteSet | list ImageSet, | list (if `f` is periodic) Union | EmptySet | empty list Others | None Raises ====== NotImplementedError A ConditionSet is the input. Examples ======== >>> from sympy.solvers.solveset import solvify >>> from sympy.abc import x >>> from sympy import S, tan, sin, exp >>> solvify(x**2 - 9, x, S.Reals) [-3, 3] >>> solvify(sin(x) - 1, x, S.Reals) [pi/2] >>> solvify(tan(x), x, S.Reals) [0] >>> solvify(exp(x) - 1, x, S.Complexes) >>> solvify(exp(x) - 1, x, S.Reals) [0] """ solution_set = solveset(f, symbol, domain) result = None if solution_set is S.EmptySet: result = [] elif isinstance(solution_set, ConditionSet): raise NotImplementedError('solveset is unable to solve this equation.') elif isinstance(solution_set, FiniteSet): result = list(solution_set) else: period = periodicity(f, symbol) if period is not None: solutions = S.EmptySet iter_solutions = () if isinstance(solution_set, ImageSet): iter_solutions = (solution_set,) elif isinstance(solution_set, Union): if all(isinstance(i, ImageSet) for i in solution_set.args): iter_solutions = solution_set.args for solution in iter_solutions: solutions += solution.intersect(Interval(0, period, False, True)) if isinstance(solutions, FiniteSet): result = list(solutions) else: solution = solution_set.intersect(domain) if isinstance(solution, FiniteSet): result += solution return result ############################################################################### ################################ LINSOLVE ##################################### ############################################################################### def linear_coeffs(eq, *syms, **_kw): """Return a list whose elements are the coefficients of the corresponding symbols in the sum of terms in ``eq``. The additive constant is returned as the last element of the list. Raises ====== NonlinearError The equation contains a nonlinear term Examples ======== >>> from sympy.solvers.solveset import linear_coeffs >>> from sympy.abc import x, y, z >>> linear_coeffs(3*x + 2*y - 1, x, y) [3, 2, -1] It is not necessary to expand the expression: >>> linear_coeffs(x + y*(z*(x*3 + 2) + 3), x) [3*y*z + 1, y*(2*z + 3)] But if there are nonlinear or cross terms -- even if they would cancel after simplification -- an error is raised so the situation does not pass silently past the caller's attention: >>> eq = 1/x*(x - 1) + 1/x >>> linear_coeffs(eq.expand(), x) [0, 1] >>> linear_coeffs(eq, x) Traceback (most recent call last): ... NonlinearError: nonlinear term encountered: 1/x >>> linear_coeffs(x*(y + 1) - x*y, x, y) Traceback (most recent call last): ... NonlinearError: nonlinear term encountered: x*(y + 1) """ d = defaultdict(list) eq = _sympify(eq) symset = set(syms) has = eq.free_symbols & symset if not has: return [S.Zero]*len(syms) + [eq] c, terms = eq.as_coeff_add(*has) d[0].extend(Add.make_args(c)) for t in terms: m, f = t.as_coeff_mul(*has) if len(f) != 1: break f = f[0] if f in symset: d[f].append(m) elif f.is_Add: d1 = linear_coeffs(f, *has, **{'dict': True}) d[0].append(m*d1.pop(0)) for xf, vf in d1.items(): d[xf].append(m*vf) else: break else: for k, v in d.items(): d[k] = Add(*v) if not _kw: return [d.get(s, S.Zero) for s in syms] + [d[0]] return d # default is still list but this won't matter raise NonlinearError('nonlinear term encountered: %s' % t) def linear_eq_to_matrix(equations, *symbols): r""" Converts a given System of Equations into Matrix form. Here `equations` must be a linear system of equations in `symbols`. Element M[i, j] corresponds to the coefficient of the jth symbol in the ith equation. The Matrix form corresponds to the augmented matrix form. For example: .. math:: 4x + 2y + 3z = 1 .. math:: 3x + y + z = -6 .. math:: 2x + 4y + 9z = 2 This system would return `A` & `b` as given below: :: [ 4 2 3 ] [ 1 ] A = [ 3 1 1 ] b = [-6 ] [ 2 4 9 ] [ 2 ] The only simplification performed is to convert `Eq(a, b) -> a - b`. Raises ====== NonlinearError The equations contain a nonlinear term. ValueError The symbols are not given or are not unique. Examples ======== >>> from sympy import linear_eq_to_matrix, symbols >>> c, x, y, z = symbols('c, x, y, z') The coefficients (numerical or symbolic) of the symbols will be returned as matrices: >>> eqns = [c*x + z - 1 - c, y + z, x - y] >>> A, b = linear_eq_to_matrix(eqns, [x, y, z]) >>> A Matrix([ [c, 0, 1], [0, 1, 1], [1, -1, 0]]) >>> b Matrix([ [c + 1], [ 0], [ 0]]) This routine does not simplify expressions and will raise an error if nonlinearity is encountered: >>> eqns = [ ... (x**2 - 3*x)/(x - 3) - 3, ... y**2 - 3*y - y*(y - 4) + x - 4] >>> linear_eq_to_matrix(eqns, [x, y]) Traceback (most recent call last): ... NonlinearError: The term (x**2 - 3*x)/(x - 3) is nonlinear in {x, y} Simplifying these equations will discard the removable singularity in the first, reveal the linear structure of the second: >>> [e.simplify() for e in eqns] [x - 3, x + y - 4] Any such simplification needed to eliminate nonlinear terms must be done before calling this routine. """ if not symbols: raise ValueError(filldedent(''' Symbols must be given, for which coefficients are to be found. ''')) if hasattr(symbols[0], '__iter__'): symbols = symbols[0] for i in symbols: if not isinstance(i, Symbol): raise ValueError(filldedent(''' Expecting a Symbol but got %s ''' % i)) if has_dups(symbols): raise ValueError('Symbols must be unique') equations = sympify(equations) if isinstance(equations, MatrixBase): equations = list(equations) elif isinstance(equations, (Expr, Eq)): equations = [equations] elif not is_sequence(equations): raise ValueError(filldedent(''' Equation(s) must be given as a sequence, Expr, Eq or Matrix. ''')) A, b = [], [] for i, f in enumerate(equations): if isinstance(f, Equality): f = f.rewrite(Add, evaluate=False) coeff_list = linear_coeffs(f, *symbols) b.append(-coeff_list.pop()) A.append(coeff_list) A, b = map(Matrix, (A, b)) return A, b def linsolve(system, *symbols): r""" Solve system of N linear equations with M variables; both underdetermined and overdetermined systems are supported. The possible number of solutions is zero, one or infinite. Zero solutions throws a ValueError, whereas infinite solutions are represented parametrically in terms of the given symbols. For unique solution a FiniteSet of ordered tuples is returned. All Standard input formats are supported: For the given set of Equations, the respective input types are given below: .. math:: 3x + 2y - z = 1 .. math:: 2x - 2y + 4z = -2 .. math:: 2x - y + 2z = 0 * Augmented Matrix Form, `system` given below: :: [3 2 -1 1] system = [2 -2 4 -2] [2 -1 2 0] * List Of Equations Form `system = [3x + 2y - z - 1, 2x - 2y + 4z + 2, 2x - y + 2z]` * Input A & b Matrix Form (from Ax = b) are given as below: :: [3 2 -1 ] [ 1 ] A = [2 -2 4 ] b = [ -2 ] [2 -1 2 ] [ 0 ] `system = (A, b)` Symbols can always be passed but are actually only needed when 1) a system of equations is being passed and 2) the system is passed as an underdetermined matrix and one wants to control the name of the free variables in the result. An error is raised if no symbols are used for case 1, but if no symbols are provided for case 2, internally generated symbols will be provided. When providing symbols for case 2, there should be at least as many symbols are there are columns in matrix A. The algorithm used here is Gauss-Jordan elimination, which results, after elimination, in a row echelon form matrix. Returns ======= A FiniteSet containing an ordered tuple of values for the unknowns for which the `system` has a solution. (Wrapping the tuple in FiniteSet is used to maintain a consistent output format throughout solveset.) Returns EmptySet, if the linear system is inconsistent. Raises ====== ValueError The input is not valid. The symbols are not given. Examples ======== >>> from sympy import Matrix, linsolve, symbols >>> x, y, z = symbols("x, y, z") >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) >>> b = Matrix([3, 6, 9]) >>> A Matrix([ [1, 2, 3], [4, 5, 6], [7, 8, 10]]) >>> b Matrix([ [3], [6], [9]]) >>> linsolve((A, b), [x, y, z]) FiniteSet((-1, 2, 0)) * Parametric Solution: In case the system is underdetermined, the function will return a parametric solution in terms of the given symbols. Those that are free will be returned unchanged. e.g. in the system below, `z` is returned as the solution for variable z; it can take on any value. >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> b = Matrix([3, 6, 9]) >>> linsolve((A, b), x, y, z) FiniteSet((z - 1, 2 - 2*z, z)) If no symbols are given, internally generated symbols will be used. The `tau0` in the 3rd position indicates (as before) that the 3rd variable -- whatever it's named -- can take on any value: >>> linsolve((A, b)) FiniteSet((tau0 - 1, 2 - 2*tau0, tau0)) * List of Equations as input >>> Eqns = [3*x + 2*y - z - 1, 2*x - 2*y + 4*z + 2, - x + y/2 - z] >>> linsolve(Eqns, x, y, z) FiniteSet((1, -2, -2)) * Augmented Matrix as input >>> aug = Matrix([[2, 1, 3, 1], [2, 6, 8, 3], [6, 8, 18, 5]]) >>> aug Matrix([ [2, 1, 3, 1], [2, 6, 8, 3], [6, 8, 18, 5]]) >>> linsolve(aug, x, y, z) FiniteSet((3/10, 2/5, 0)) * Solve for symbolic coefficients >>> a, b, c, d, e, f = symbols('a, b, c, d, e, f') >>> eqns = [a*x + b*y - c, d*x + e*y - f] >>> linsolve(eqns, x, y) FiniteSet(((-b*f + c*e)/(a*e - b*d), (a*f - c*d)/(a*e - b*d))) * A degenerate system returns solution as set of given symbols. >>> system = Matrix(([0, 0, 0], [0, 0, 0], [0, 0, 0])) >>> linsolve(system, x, y) FiniteSet((x, y)) * For an empty system linsolve returns empty set >>> linsolve([], x) EmptySet * An error is raised if, after expansion, any nonlinearity is detected: >>> linsolve([x*(1/x - 1), (y - 1)**2 - y**2 + 1], x, y) FiniteSet((1, 1)) >>> linsolve([x**2 - 1], x) Traceback (most recent call last): ... NonlinearError: nonlinear term encountered: x**2 """ if not system: return S.EmptySet # If second argument is an iterable if symbols and hasattr(symbols[0], '__iter__'): symbols = symbols[0] sym_gen = isinstance(symbols, GeneratorType) b = None # if we don't get b the input was bad syms_needed_msg = None # unpack system if hasattr(system, '__iter__'): # 1). (A, b) if len(system) == 2 and isinstance(system[0], MatrixBase): A, b = system # 2). (eq1, eq2, ...) if not isinstance(system[0], MatrixBase): if sym_gen or not symbols: raise ValueError(filldedent(''' When passing a system of equations, the explicit symbols for which a solution is being sought must be given as a sequence, too. ''')) eqs = system try: eqs, ring = sympy_eqs_to_ring(eqs, symbols) except PolynomialError as exc: # e.g. cos(x) contains an element of the set of generators raise NonlinearError(str(exc)) try: sol = solve_lin_sys(eqs, ring, _raw=False) except PolyNonlinearError as exc: raise NonlinearError(str(exc)) if sol is None: return S.EmptySet sol = FiniteSet(Tuple(*(sol.get(sym, sym) for sym in symbols))) return sol elif isinstance(system, MatrixBase) and not ( symbols and not isinstance(symbols, GeneratorType) and isinstance(symbols[0], MatrixBase)): # 3). A augmented with b A, b = system[:, :-1], system[:, -1:] if b is None: raise ValueError("Invalid arguments") syms_needed_msg = syms_needed_msg or 'columns of A' if sym_gen: symbols = [next(symbols) for i in range(A.cols)] if any(set(symbols) & (A.free_symbols | b.free_symbols)): raise ValueError(filldedent(''' At least one of the symbols provided already appears in the system to be solved. One way to avoid this is to use Dummy symbols in the generator, e.g. numbered_symbols('%s', cls=Dummy) ''' % symbols[0].name.rstrip('1234567890'))) if not symbols: symbols = [Dummy() for _ in range(A.cols)] name = _uniquely_named_symbol('tau', (A, b), compare=lambda i: str(i).rstrip('1234567890')).name gen = numbered_symbols(name) else: gen = None # This is just a wrapper for solve_lin_sys eqs = [] rows = A.tolist() for rowi, bi in zip(rows, b): terms = [elem * sym for elem, sym in zip(rowi, symbols) if elem] terms.append(-bi) eqs.append(Add(*terms)) eqs, ring = sympy_eqs_to_ring(eqs, symbols) sol = solve_lin_sys(eqs, ring, _raw=False) if sol is None: return S.EmptySet #sol = {sym:val for sym, val in sol.items() if sym != val} sol = FiniteSet(Tuple(*(sol.get(sym, sym) for sym in symbols))) if gen is not None: solsym = sol.free_symbols rep = {sym: next(gen) for sym in symbols if sym in solsym} sol = sol.subs(rep) return sol ############################################################################## # ------------------------------nonlinsolve ---------------------------------# ############################################################################## def _return_conditionset(eqs, symbols): # return conditionset eqs = (Eq(lhs, 0) for lhs in eqs) condition_set = ConditionSet( Tuple(*symbols), And(*eqs), S.Complexes**len(symbols)) return condition_set def substitution(system, symbols, result=[{}], known_symbols=[], exclude=[], all_symbols=None): r""" Solves the `system` using substitution method. It is used in `nonlinsolve`. This will be called from `nonlinsolve` when any equation(s) is non polynomial equation. Parameters ========== system : list of equations The target system of equations symbols : list of symbols to be solved. The variable(s) for which the system is solved known_symbols : list of solved symbols Values are known for these variable(s) result : An empty list or list of dict If No symbol values is known then empty list otherwise symbol as keys and corresponding value in dict. exclude : Set of expression. Mostly denominator expression(s) of the equations of the system. Final solution should not satisfy these expressions. all_symbols : known_symbols + symbols(unsolved). Returns ======= A FiniteSet of ordered tuple of values of `all_symbols` for which the `system` has solution. Order of values in the tuple is same as symbols present in the parameter `all_symbols`. If parameter `all_symbols` is None then same as symbols present in the parameter `symbols`. Please note that general FiniteSet is unordered, the solution returned here is not simply a FiniteSet of solutions, rather it is a FiniteSet of ordered tuple, i.e. the first & only argument to FiniteSet is a tuple of solutions, which is ordered, & hence the returned solution is ordered. Also note that solution could also have been returned as an ordered tuple, FiniteSet is just a wrapper `{}` around the tuple. It has no other significance except for the fact it is just used to maintain a consistent output format throughout the solveset. Raises ====== ValueError The input is not valid. The symbols are not given. AttributeError The input symbols are not `Symbol` type. Examples ======== >>> from sympy.core.symbol import symbols >>> x, y = symbols('x, y', real=True) >>> from sympy.solvers.solveset import substitution >>> substitution([x + y], [x], [{y: 1}], [y], set([]), [x, y]) FiniteSet((-1, 1)) * when you want soln should not satisfy eq `x + 1 = 0` >>> substitution([x + y], [x], [{y: 1}], [y], set([x + 1]), [y, x]) EmptySet >>> substitution([x + y], [x], [{y: 1}], [y], set([x - 1]), [y, x]) FiniteSet((1, -1)) >>> substitution([x + y - 1, y - x**2 + 5], [x, y]) FiniteSet((-3, 4), (2, -1)) * Returns both real and complex solution >>> x, y, z = symbols('x, y, z') >>> from sympy import exp, sin >>> substitution([exp(x) - sin(y), y**2 - 4], [x, y]) FiniteSet((ImageSet(Lambda(_n, 2*_n*I*pi + log(sin(2))), Integers), 2), (ImageSet(Lambda(_n, I*(2*_n*pi + pi) + log(sin(2))), Integers), -2)) >>> eqs = [z**2 + exp(2*x) - sin(y), -3 + exp(-y)] >>> substitution(eqs, [y, z]) FiniteSet((-log(3), sqrt(-exp(2*x) - sin(log(3)))), (-log(3), -sqrt(-exp(2*x) - sin(log(3)))), (ImageSet(Lambda(_n, 2*_n*I*pi - log(3)), Integers), ImageSet(Lambda(_n, sqrt(-exp(2*x) + sin(2*_n*I*pi - log(3)))), Integers)), (ImageSet(Lambda(_n, 2*_n*I*pi - log(3)), Integers), ImageSet(Lambda(_n, -sqrt(-exp(2*x) + sin(2*_n*I*pi - log(3)))), Integers))) """ from sympy import Complement from sympy.core.compatibility import is_sequence if not system: return S.EmptySet if not symbols: msg = ('Symbols must be given, for which solution of the ' 'system is to be found.') raise ValueError(filldedent(msg)) if not is_sequence(symbols): msg = ('symbols should be given as a sequence, e.g. a list.' 'Not type %s: %s') raise TypeError(filldedent(msg % (type(symbols), symbols))) if not getattr(symbols[0], 'is_Symbol', False): msg = ('Iterable of symbols must be given as ' 'second argument, not type %s: %s') raise ValueError(filldedent(msg % (type(symbols[0]), symbols[0]))) # By default `all_symbols` will be same as `symbols` if all_symbols is None: all_symbols = symbols old_result = result # storing complements and intersection for particular symbol complements = {} intersections = {} # when total_solveset_call equals total_conditionset # it means that solveset failed to solve all eqs. total_conditionset = -1 total_solveset_call = -1 def _unsolved_syms(eq, sort=False): """Returns the unsolved symbol present in the equation `eq`. """ free = eq.free_symbols unsolved = (free - set(known_symbols)) & set(all_symbols) if sort: unsolved = list(unsolved) unsolved.sort(key=default_sort_key) return unsolved # end of _unsolved_syms() # sort such that equation with the fewest potential symbols is first. # means eq with less number of variable first in the list. eqs_in_better_order = list( ordered(system, lambda _: len(_unsolved_syms(_)))) def add_intersection_complement(result, intersection_dict, complement_dict): # If solveset has returned some intersection/complement # for any symbol, it will be added in the final solution. final_result = [] for res in result: res_copy = res for key_res, value_res in res.items(): intersect_set, complement_set = None, None for key_sym, value_sym in intersection_dict.items(): if key_sym == key_res: intersect_set = value_sym for key_sym, value_sym in complement_dict.items(): if key_sym == key_res: complement_set = value_sym if intersect_set or complement_set: new_value = FiniteSet(value_res) if intersect_set and intersect_set != S.Complexes: new_value = Intersection(new_value, intersect_set) if complement_set: new_value = Complement(new_value, complement_set) if new_value is S.EmptySet: res_copy = None break elif new_value.is_FiniteSet and len(new_value) == 1: res_copy[key_res] = set(new_value).pop() else: res_copy[key_res] = new_value if res_copy is not None: final_result.append(res_copy) return final_result # end of def add_intersection_complement() def _extract_main_soln(sym, sol, soln_imageset): """Separate the Complements, Intersections, ImageSet lambda expr and its base_set. """ # if there is union, then need to check # Complement, Intersection, Imageset. # Order should not be changed. if isinstance(sol, Complement): # extract solution and complement complements[sym] = sol.args[1] sol = sol.args[0] # complement will be added at the end # using `add_intersection_complement` method if isinstance(sol, Intersection): # Interval/Set will be at 0th index always if sol.args[0] not in (S.Reals, S.Complexes): # Sometimes solveset returns soln with intersection # S.Reals or S.Complexes. We don't consider that # intersection. intersections[sym] = sol.args[0] sol = sol.args[1] # after intersection and complement Imageset should # be checked. if isinstance(sol, ImageSet): soln_imagest = sol expr2 = sol.lamda.expr sol = FiniteSet(expr2) soln_imageset[expr2] = soln_imagest # if there is union of Imageset or other in soln. # no testcase is written for this if block if isinstance(sol, Union): sol_args = sol.args sol = S.EmptySet # We need in sequence so append finteset elements # and then imageset or other. for sol_arg2 in sol_args: if isinstance(sol_arg2, FiniteSet): sol += sol_arg2 else: # ImageSet, Intersection, complement then # append them directly sol += FiniteSet(sol_arg2) if not isinstance(sol, FiniteSet): sol = FiniteSet(sol) return sol, soln_imageset # end of def _extract_main_soln() # helper function for _append_new_soln def _check_exclude(rnew, imgset_yes): rnew_ = rnew if imgset_yes: # replace all dummy variables (Imageset lambda variables) # with zero before `checksol`. Considering fundamental soln # for `checksol`. rnew_copy = rnew.copy() dummy_n = imgset_yes[0] for key_res, value_res in rnew_copy.items(): rnew_copy[key_res] = value_res.subs(dummy_n, 0) rnew_ = rnew_copy # satisfy_exclude == true if it satisfies the expr of `exclude` list. try: # something like : `Mod(-log(3), 2*I*pi)` can't be # simplified right now, so `checksol` returns `TypeError`. # when this issue is fixed this try block should be # removed. Mod(-log(3), 2*I*pi) == -log(3) satisfy_exclude = any( checksol(d, rnew_) for d in exclude) except TypeError: satisfy_exclude = None return satisfy_exclude # end of def _check_exclude() # helper function for _append_new_soln def _restore_imgset(rnew, original_imageset, newresult): restore_sym = set(rnew.keys()) & \ set(original_imageset.keys()) for key_sym in restore_sym: img = original_imageset[key_sym] rnew[key_sym] = img if rnew not in newresult: newresult.append(rnew) # end of def _restore_imgset() def _append_eq(eq, result, res, delete_soln, n=None): u = Dummy('u') if n: eq = eq.subs(n, 0) satisfy = checksol(u, u, eq, minimal=True) if satisfy is False: delete_soln = True res = {} else: result.append(res) return result, res, delete_soln def _append_new_soln(rnew, sym, sol, imgset_yes, soln_imageset, original_imageset, newresult, eq=None): """If `rnew` (A dict <symbol: soln>) contains valid soln append it to `newresult` list. `imgset_yes` is (base, dummy_var) if there was imageset in previously calculated result(otherwise empty tuple). `original_imageset` is dict of imageset expr and imageset from this result. `soln_imageset` dict of imageset expr and imageset of new soln. """ satisfy_exclude = _check_exclude(rnew, imgset_yes) delete_soln = False # soln should not satisfy expr present in `exclude` list. if not satisfy_exclude: local_n = None # if it is imageset if imgset_yes: local_n = imgset_yes[0] base = imgset_yes[1] if sym and sol: # when `sym` and `sol` is `None` means no new # soln. In that case we will append rnew directly after # substituting original imagesets in rnew values if present # (second last line of this function using _restore_imgset) dummy_list = list(sol.atoms(Dummy)) # use one dummy `n` which is in # previous imageset local_n_list = [ local_n for i in range( 0, len(dummy_list))] dummy_zip = zip(dummy_list, local_n_list) lam = Lambda(local_n, sol.subs(dummy_zip)) rnew[sym] = ImageSet(lam, base) if eq is not None: newresult, rnew, delete_soln = _append_eq( eq, newresult, rnew, delete_soln, local_n) elif eq is not None: newresult, rnew, delete_soln = _append_eq( eq, newresult, rnew, delete_soln) elif soln_imageset: rnew[sym] = soln_imageset[sol] # restore original imageset _restore_imgset(rnew, original_imageset, newresult) else: newresult.append(rnew) elif satisfy_exclude: delete_soln = True rnew = {} _restore_imgset(rnew, original_imageset, newresult) return newresult, delete_soln # end of def _append_new_soln() def _new_order_result(result, eq): # separate first, second priority. `res` that makes `eq` value equals # to zero, should be used first then other result(second priority). # If it is not done then we may miss some soln. first_priority = [] second_priority = [] for res in result: if not any(isinstance(val, ImageSet) for val in res.values()): if eq.subs(res) == 0: first_priority.append(res) else: second_priority.append(res) if first_priority or second_priority: return first_priority + second_priority return result def _solve_using_known_values(result, solver): """Solves the system using already known solution (result contains the dict <symbol: value>). solver is `solveset_complex` or `solveset_real`. """ # stores imageset <expr: imageset(Lambda(n, expr), base)>. soln_imageset = {} total_solvest_call = 0 total_conditionst = 0 # sort such that equation with the fewest potential symbols is first. # means eq with less variable first for index, eq in enumerate(eqs_in_better_order): newresult = [] original_imageset = {} # if imageset expr is used to solve other symbol imgset_yes = False result = _new_order_result(result, eq) for res in result: got_symbol = set() # symbols solved in one iteration if soln_imageset: # find the imageset and use its expr. for key_res, value_res in res.items(): if isinstance(value_res, ImageSet): res[key_res] = value_res.lamda.expr original_imageset[key_res] = value_res dummy_n = value_res.lamda.expr.atoms(Dummy).pop() (base,) = value_res.base_sets imgset_yes = (dummy_n, base) # update eq with everything that is known so far eq2 = eq.subs(res).expand() unsolved_syms = _unsolved_syms(eq2, sort=True) if not unsolved_syms: if res: newresult, delete_res = _append_new_soln( res, None, None, imgset_yes, soln_imageset, original_imageset, newresult, eq2) if delete_res: # `delete_res` is true, means substituting `res` in # eq2 doesn't return `zero` or deleting the `res` # (a soln) since it staisfies expr of `exclude` # list. result.remove(res) continue # skip as it's independent of desired symbols depen1, depen2 = (eq2.rewrite(Add)).as_independent(*unsolved_syms) if (depen1.has(Abs) or depen2.has(Abs)) and solver == solveset_complex: # Absolute values cannot be inverted in the # complex domain continue soln_imageset = {} for sym in unsolved_syms: not_solvable = False try: soln = solver(eq2, sym) total_solvest_call += 1 soln_new = S.EmptySet if isinstance(soln, Complement): # separate solution and complement complements[sym] = soln.args[1] soln = soln.args[0] # complement will be added at the end if isinstance(soln, Intersection): # Interval will be at 0th index always if soln.args[0] != Interval(-oo, oo): # sometimes solveset returns soln # with intersection S.Reals, to confirm that # soln is in domain=S.Reals intersections[sym] = soln.args[0] soln_new += soln.args[1] soln = soln_new if soln_new else soln if index > 0 and solver == solveset_real: # one symbol's real soln , another symbol may have # corresponding complex soln. if not isinstance(soln, (ImageSet, ConditionSet)): soln += solveset_complex(eq2, sym) except NotImplementedError: # If sovleset is not able to solve equation `eq2`. Next # time we may get soln using next equation `eq2` continue if isinstance(soln, ConditionSet): soln = S.EmptySet # don't do `continue` we may get soln # in terms of other symbol(s) not_solvable = True total_conditionst += 1 if soln is not S.EmptySet: soln, soln_imageset = _extract_main_soln( sym, soln, soln_imageset) for sol in soln: # sol is not a `Union` since we checked it # before this loop sol, soln_imageset = _extract_main_soln( sym, sol, soln_imageset) sol = set(sol).pop() free = sol.free_symbols if got_symbol and any([ ss in free for ss in got_symbol ]): # sol depends on previously solved symbols # then continue continue rnew = res.copy() # put each solution in res and append the new result # in the new result list (solution for symbol `s`) # along with old results. for k, v in res.items(): if isinstance(v, Expr): # if any unsolved symbol is present # Then subs known value rnew[k] = v.subs(sym, sol) # and add this new solution if soln_imageset: # replace all lambda variables with 0. imgst = soln_imageset[sol] rnew[sym] = imgst.lamda( *[0 for i in range(0, len( imgst.lamda.variables))]) else: rnew[sym] = sol newresult, delete_res = _append_new_soln( rnew, sym, sol, imgset_yes, soln_imageset, original_imageset, newresult) if delete_res: # deleting the `res` (a soln) since it staisfies # eq of `exclude` list result.remove(res) # solution got for sym if not not_solvable: got_symbol.add(sym) # next time use this new soln if newresult: result = newresult return result, total_solvest_call, total_conditionst # end def _solve_using_know_values() new_result_real, solve_call1, cnd_call1 = _solve_using_known_values( old_result, solveset_real) new_result_complex, solve_call2, cnd_call2 = _solve_using_known_values( old_result, solveset_complex) # when `total_solveset_call` is equals to `total_conditionset` # means solvest fails to solve all the eq. # return conditionset in this case total_conditionset += (cnd_call1 + cnd_call2) total_solveset_call += (solve_call1 + solve_call2) if total_conditionset == total_solveset_call and total_solveset_call != -1: return _return_conditionset(eqs_in_better_order, all_symbols) # overall result result = new_result_real + new_result_complex result_all_variables = [] result_infinite = [] for res in result: if not res: # means {None : None} continue # If length < len(all_symbols) means infinite soln. # Some or all the soln is dependent on 1 symbol. # eg. {x: y+2} then final soln {x: y+2, y: y} if len(res) < len(all_symbols): solved_symbols = res.keys() unsolved = list(filter( lambda x: x not in solved_symbols, all_symbols)) for unsolved_sym in unsolved: res[unsolved_sym] = unsolved_sym result_infinite.append(res) if res not in result_all_variables: result_all_variables.append(res) if result_infinite: # we have general soln # eg : [{x: -1, y : 1}, {x : -y , y: y}] then # return [{x : -y, y : y}] result_all_variables = result_infinite if intersections or complements: result_all_variables = add_intersection_complement( result_all_variables, intersections, complements) # convert to ordered tuple result = S.EmptySet for r in result_all_variables: temp = [r[symb] for symb in all_symbols] result += FiniteSet(tuple(temp)) return result # end of def substitution() def _solveset_work(system, symbols): soln = solveset(system[0], symbols[0]) if isinstance(soln, FiniteSet): _soln = FiniteSet(*[tuple((s,)) for s in soln]) return _soln else: return FiniteSet(tuple(FiniteSet(soln))) def _handle_positive_dimensional(polys, symbols, denominators): from sympy.polys.polytools import groebner # substitution method where new system is groebner basis of the system _symbols = list(symbols) _symbols.sort(key=default_sort_key) basis = groebner(polys, _symbols, polys=True) new_system = [] for poly_eq in basis: new_system.append(poly_eq.as_expr()) result = [{}] result = substitution( new_system, symbols, result, [], denominators) return result # end of def _handle_positive_dimensional() def _handle_zero_dimensional(polys, symbols, system): # solve 0 dimensional poly system using `solve_poly_system` result = solve_poly_system(polys, *symbols) # May be some extra soln is added because # we used `unrad` in `_separate_poly_nonpoly`, so # need to check and remove if it is not a soln. result_update = S.EmptySet for res in result: dict_sym_value = dict(list(zip(symbols, res))) if all(checksol(eq, dict_sym_value) for eq in system): result_update += FiniteSet(res) return result_update # end of def _handle_zero_dimensional() def _separate_poly_nonpoly(system, symbols): polys = [] polys_expr = [] nonpolys = [] denominators = set() poly = None for eq in system: # Store denom expression if it contains symbol denominators.update(_simple_dens(eq, symbols)) # try to remove sqrt and rational power without_radicals = unrad(simplify(eq)) if without_radicals: eq_unrad, cov = without_radicals if not cov: eq = eq_unrad if isinstance(eq, Expr): eq = eq.as_numer_denom()[0] poly = eq.as_poly(*symbols, extension=True) elif simplify(eq).is_number: continue if poly is not None: polys.append(poly) polys_expr.append(poly.as_expr()) else: nonpolys.append(eq) return polys, polys_expr, nonpolys, denominators # end of def _separate_poly_nonpoly() def nonlinsolve(system, *symbols): r""" Solve system of N nonlinear equations with M variables, which means both under and overdetermined systems are supported. Positive dimensional system is also supported (A system with infinitely many solutions is said to be positive-dimensional). In Positive dimensional system solution will be dependent on at least one symbol. Returns both real solution and complex solution(If system have). The possible number of solutions is zero, one or infinite. Parameters ========== system : list of equations The target system of equations symbols : list of Symbols symbols should be given as a sequence eg. list Returns ======= A FiniteSet of ordered tuple of values of `symbols` for which the `system` has solution. Order of values in the tuple is same as symbols present in the parameter `symbols`. Please note that general FiniteSet is unordered, the solution returned here is not simply a FiniteSet of solutions, rather it is a FiniteSet of ordered tuple, i.e. the first & only argument to FiniteSet is a tuple of solutions, which is ordered, & hence the returned solution is ordered. Also note that solution could also have been returned as an ordered tuple, FiniteSet is just a wrapper `{}` around the tuple. It has no other significance except for the fact it is just used to maintain a consistent output format throughout the solveset. For the given set of Equations, the respective input types are given below: .. math:: x*y - 1 = 0 .. math:: 4*x**2 + y**2 - 5 = 0 `system = [x*y - 1, 4*x**2 + y**2 - 5]` `symbols = [x, y]` Raises ====== ValueError The input is not valid. The symbols are not given. AttributeError The input symbols are not `Symbol` type. Examples ======== >>> from sympy.core.symbol import symbols >>> from sympy.solvers.solveset import nonlinsolve >>> x, y, z = symbols('x, y, z', real=True) >>> nonlinsolve([x*y - 1, 4*x**2 + y**2 - 5], [x, y]) FiniteSet((-1, -1), (-1/2, -2), (1/2, 2), (1, 1)) 1. Positive dimensional system and complements: >>> from sympy import pprint >>> from sympy.polys.polytools import is_zero_dimensional >>> a, b, c, d = symbols('a, b, c, d', extended_real=True) >>> eq1 = a + b + c + d >>> eq2 = a*b + b*c + c*d + d*a >>> eq3 = a*b*c + b*c*d + c*d*a + d*a*b >>> eq4 = a*b*c*d - 1 >>> system = [eq1, eq2, eq3, eq4] >>> is_zero_dimensional(system) False >>> pprint(nonlinsolve(system, [a, b, c, d]), use_unicode=False) -1 1 1 -1 {(---, -d, -, {d} \ {0}), (-, -d, ---, {d} \ {0})} d d d d >>> nonlinsolve([(x+y)**2 - 4, x + y - 2], [x, y]) FiniteSet((2 - y, y)) 2. If some of the equations are non-polynomial then `nonlinsolve` will call the `substitution` function and return real and complex solutions, if present. >>> from sympy import exp, sin >>> nonlinsolve([exp(x) - sin(y), y**2 - 4], [x, y]) FiniteSet((ImageSet(Lambda(_n, 2*_n*I*pi + log(sin(2))), Integers), 2), (ImageSet(Lambda(_n, I*(2*_n*pi + pi) + log(sin(2))), Integers), -2)) 3. If system is non-linear polynomial and zero-dimensional then it returns both solution (real and complex solutions, if present) using `solve_poly_system`: >>> from sympy import sqrt >>> nonlinsolve([x**2 - 2*y**2 -2, x*y - 2], [x, y]) FiniteSet((-2, -1), (2, 1), (-sqrt(2)*I, sqrt(2)*I), (sqrt(2)*I, -sqrt(2)*I)) 4. `nonlinsolve` can solve some linear (zero or positive dimensional) system (because it uses the `groebner` function to get the groebner basis and then uses the `substitution` function basis as the new `system`). But it is not recommended to solve linear system using `nonlinsolve`, because `linsolve` is better for general linear systems. >>> nonlinsolve([x + 2*y -z - 3, x - y - 4*z + 9 , y + z - 4], [x, y, z]) FiniteSet((3*z - 5, 4 - z, z)) 5. System having polynomial equations and only real solution is solved using `solve_poly_system`: >>> e1 = sqrt(x**2 + y**2) - 10 >>> e2 = sqrt(y**2 + (-x + 10)**2) - 3 >>> nonlinsolve((e1, e2), (x, y)) FiniteSet((191/20, -3*sqrt(391)/20), (191/20, 3*sqrt(391)/20)) >>> nonlinsolve([x**2 + 2/y - 2, x + y - 3], [x, y]) FiniteSet((1, 2), (1 - sqrt(5), 2 + sqrt(5)), (1 + sqrt(5), 2 - sqrt(5))) >>> nonlinsolve([x**2 + 2/y - 2, x + y - 3], [y, x]) FiniteSet((2, 1), (2 - sqrt(5), 1 + sqrt(5)), (2 + sqrt(5), 1 - sqrt(5))) 6. It is better to use symbols instead of Trigonometric Function or Function (e.g. replace `sin(x)` with symbol, replace `f(x)` with symbol and so on. Get soln from `nonlinsolve` and then using `solveset` get the value of `x`) How nonlinsolve is better than old solver `_solve_system` : =========================================================== 1. A positive dimensional system solver : nonlinsolve can return solution for positive dimensional system. It finds the Groebner Basis of the positive dimensional system(calling it as basis) then we can start solving equation(having least number of variable first in the basis) using solveset and substituting that solved solutions into other equation(of basis) to get solution in terms of minimum variables. Here the important thing is how we are substituting the known values and in which equations. 2. Real and Complex both solutions : nonlinsolve returns both real and complex solution. If all the equations in the system are polynomial then using `solve_poly_system` both real and complex solution is returned. If all the equations in the system are not polynomial equation then goes to `substitution` method with this polynomial and non polynomial equation(s), to solve for unsolved variables. Here to solve for particular variable solveset_real and solveset_complex is used. For both real and complex solution function `_solve_using_know_values` is used inside `substitution` function.(`substitution` function will be called when there is any non polynomial equation(s) is present). When solution is valid then add its general solution in the final result. 3. Complement and Intersection will be added if any : nonlinsolve maintains dict for complements and Intersections. If solveset find complements or/and Intersection with any Interval or set during the execution of `substitution` function ,then complement or/and Intersection for that variable is added before returning final solution. """ from sympy.polys.polytools import is_zero_dimensional if not system: return S.EmptySet if not symbols: msg = ('Symbols must be given, for which solution of the ' 'system is to be found.') raise ValueError(filldedent(msg)) if hasattr(symbols[0], '__iter__'): symbols = symbols[0] if not is_sequence(symbols) or not symbols: msg = ('Symbols must be given, for which solution of the ' 'system is to be found.') raise IndexError(filldedent(msg)) system, symbols, swap = recast_to_symbols(system, symbols) if swap: soln = nonlinsolve(system, symbols) return FiniteSet(*[tuple(i.xreplace(swap) for i in s) for s in soln]) if len(system) == 1 and len(symbols) == 1: return _solveset_work(system, symbols) # main code of def nonlinsolve() starts from here polys, polys_expr, nonpolys, denominators = _separate_poly_nonpoly( system, symbols) if len(symbols) == len(polys): # If all the equations in the system are poly if is_zero_dimensional(polys, symbols): # finite number of soln (Zero dimensional system) try: return _handle_zero_dimensional(polys, symbols, system) except NotImplementedError: # Right now it doesn't fail for any polynomial system of # equation. If `solve_poly_system` fails then `substitution` # method will handle it. result = substitution( polys_expr, symbols, exclude=denominators) return result # positive dimensional system res = _handle_positive_dimensional(polys, symbols, denominators) if res is EmptySet and any(not p.domain.is_Exact for p in polys): raise NotImplementedError("Equation not in exact domain. Try converting to rational") else: return res else: # If all the equations are not polynomial. # Use `substitution` method for the system result = substitution( polys_expr + nonpolys, symbols, exclude=denominators) return result
55754a3d681a4ea31344ef513b8f58e0e1596ccf806ef268abbb4ed7b83af1ef
from functools import partial from sympy.strategies import chain, minimize import sympy.strategies.branch as branch from sympy.strategies.branch import yieldify identity = lambda x: x def treeapply(tree, join, leaf=identity): """ Apply functions onto recursive containers (tree). Explanation =========== join - a dictionary mapping container types to functions e.g. ``{list: minimize, tuple: chain}`` Keys are containers/iterables. Values are functions [a] -> a. Examples ======== >>> from sympy.strategies.tree import treeapply >>> tree = [(3, 2), (4, 1)] >>> treeapply(tree, {list: max, tuple: min}) 2 >>> add = lambda *args: sum(args) >>> def mul(*args): ... total = 1 ... for arg in args: ... total *= arg ... return total >>> treeapply(tree, {list: mul, tuple: add}) 25 """ for typ in join: if isinstance(tree, typ): return join[typ](*map(partial(treeapply, join=join, leaf=leaf), tree)) return leaf(tree) def greedy(tree, objective=identity, **kwargs): """ Execute a strategic tree. Select alternatives greedily Trees ----- Nodes in a tree can be either function - a leaf list - a selection among operations tuple - a sequence of chained operations Textual examples ---------------- Text: Run f, then run g, e.g. ``lambda x: g(f(x))`` Code: ``(f, g)`` Text: Run either f or g, whichever minimizes the objective Code: ``[f, g]`` Textx: Run either f or g, whichever is better, then run h Code: ``([f, g], h)`` Text: Either expand then simplify or try factor then foosimp. Finally print Code: ``([(expand, simplify), (factor, foosimp)], print)`` Objective --------- "Better" is determined by the objective keyword. This function makes choices to minimize the objective. It defaults to the identity. Examples ======== >>> from sympy.strategies.tree import greedy >>> inc = lambda x: x + 1 >>> dec = lambda x: x - 1 >>> double = lambda x: 2*x >>> tree = [inc, (dec, double)] # either inc or dec-then-double >>> fn = greedy(tree) >>> fn(4) # lowest value comes from the inc 5 >>> fn(1) # lowest value comes from dec then double 0 This function selects between options in a tuple. The result is chosen that minimizes the objective function. >>> fn = greedy(tree, objective=lambda x: -x) # maximize >>> fn(4) # highest value comes from the dec then double 6 >>> fn(1) # highest value comes from the inc 2 Greediness ---------- This is a greedy algorithm. In the example: ([a, b], c) # do either a or b, then do c the choice between running ``a`` or ``b`` is made without foresight to c """ optimize = partial(minimize, objective=objective) return treeapply(tree, {list: optimize, tuple: chain}, **kwargs) def allresults(tree, leaf=yieldify): """ Execute a strategic tree. Return all possibilities. Returns a lazy iterator of all possible results Exhaustiveness -------------- This is an exhaustive algorithm. In the example ([a, b], [c, d]) All of the results from (a, c), (b, c), (a, d), (b, d) are returned. This can lead to combinatorial blowup. See sympy.strategies.greedy for details on input """ return treeapply(tree, {list: branch.multiplex, tuple: branch.chain}, leaf=leaf) def brute(tree, objective=identity, **kwargs): return lambda expr: min(tuple(allresults(tree, **kwargs)(expr)), key=objective)
02211fffd3b2f0ecacb98b308aaf2aa27ff622bc05d9cc1f4827c477b2cfc653
from . import rl from .core import do_one, exhaust, switch from .traverse import top_down def subs(d, **kwargs): """ Full simultaneous exact substitution. Examples ======== >>> from sympy.strategies.tools import subs >>> from sympy import Basic >>> mapping = {1: 4, 4: 1, Basic(5): Basic(6, 7)} >>> expr = Basic(1, Basic(2, 3), Basic(4, Basic(5))) >>> subs(mapping)(expr) Basic(4, Basic(2, 3), Basic(1, Basic(6, 7))) """ if d: return top_down(do_one(*map(rl.subs, *zip(*d.items()))), **kwargs) else: return lambda x: x def canon(*rules, **kwargs): """ Strategy for canonicalization. Explanation =========== Apply each rule in a bottom_up fashion through the tree. Do each one in turn. Keep doing this until there is no change. """ return exhaust(top_down(exhaust(do_one(*rules)), **kwargs)) def typed(ruletypes): """ Apply rules based on the expression type inputs: ruletypes -- a dict mapping {Type: rule} Examples ======== >>> from sympy.strategies import rm_id, typed >>> from sympy import Add, Mul >>> rm_zeros = rm_id(lambda x: x==0) >>> rm_ones = rm_id(lambda x: x==1) >>> remove_idents = typed({Add: rm_zeros, Mul: rm_ones}) """ return switch(type, ruletypes)
145db27b89843926005a71d4d29d96a214f43385b69629db24054f746121d2ee
""" Generic Rules for SymPy This file assumes knowledge of Basic and little else. """ from sympy.utilities.iterables import sift from .util import new # Functions that create rules def rm_id(isid, new=new): """ Create a rule to remove identities. isid - fn :: x -> Bool --- whether or not this element is an identity. Examples ======== >>> from sympy.strategies import rm_id >>> from sympy import Basic >>> remove_zeros = rm_id(lambda x: x==0) >>> remove_zeros(Basic(1, 0, 2)) Basic(1, 2) >>> remove_zeros(Basic(0, 0)) # If only identites then we keep one Basic(0) See Also: unpack """ def ident_remove(expr): """ Remove identities """ ids = list(map(isid, expr.args)) if sum(ids) == 0: # No identities. Common case return expr elif sum(ids) != len(ids): # there is at least one non-identity return new(expr.__class__, *[arg for arg, x in zip(expr.args, ids) if not x]) else: return new(expr.__class__, expr.args[0]) return ident_remove def glom(key, count, combine): """ Create a rule to conglomerate identical args. Examples ======== >>> from sympy.strategies import glom >>> from sympy import Add >>> from sympy.abc import x >>> key = lambda x: x.as_coeff_Mul()[1] >>> count = lambda x: x.as_coeff_Mul()[0] >>> combine = lambda cnt, arg: cnt * arg >>> rl = glom(key, count, combine) >>> rl(Add(x, -x, 3*x, 2, 3, evaluate=False)) 3*x + 5 Wait, how are key, count and combine supposed to work? >>> key(2*x) x >>> count(2*x) 2 >>> combine(2, x) 2*x """ def conglomerate(expr): """ Conglomerate together identical args x + x -> 2x """ groups = sift(expr.args, key) counts = {k: sum(map(count, args)) for k, args in groups.items()} newargs = [combine(cnt, mat) for mat, cnt in counts.items()] if set(newargs) != set(expr.args): return new(type(expr), *newargs) else: return expr return conglomerate def sort(key, new=new): """ Create a rule to sort by a key function. Examples ======== >>> from sympy.strategies import sort >>> from sympy import Basic >>> sort_rl = sort(str) >>> sort_rl(Basic(3, 1, 2)) Basic(1, 2, 3) """ def sort_rl(expr): return new(expr.__class__, *sorted(expr.args, key=key)) return sort_rl def distribute(A, B): """ Turns an A containing Bs into a B of As where A, B are container types >>> from sympy.strategies import distribute >>> from sympy import Add, Mul, symbols >>> x, y = symbols('x,y') >>> dist = distribute(Mul, Add) >>> expr = Mul(2, x+y, evaluate=False) >>> expr 2*(x + y) >>> dist(expr) 2*x + 2*y """ def distribute_rl(expr): for i, arg in enumerate(expr.args): if isinstance(arg, B): first, b, tail = expr.args[:i], expr.args[i], expr.args[i+1:] return B(*[A(*(first + (arg,) + tail)) for arg in b.args]) return expr return distribute_rl def subs(a, b): """ Replace expressions exactly """ def subs_rl(expr): if expr == a: return b else: return expr return subs_rl # Functions that are rules def unpack(expr): """ Rule to unpack singleton args >>> from sympy.strategies import unpack >>> from sympy import Basic >>> unpack(Basic(2)) 2 """ if len(expr.args) == 1: return expr.args[0] else: return expr def flatten(expr, new=new): """ Flatten T(a, b, T(c, d), T2(e)) to T(a, b, c, d, T2(e)) """ cls = expr.__class__ args = [] for arg in expr.args: if arg.__class__ == cls: args.extend(arg.args) else: args.append(arg) return new(expr.__class__, *args) def rebuild(expr): """ Rebuild a SymPy tree. Explanation =========== This function recursively calls constructors in the expression tree. This forces canonicalization and removes ugliness introduced by the use of Basic.__new__ """ if expr.is_Atom: return expr else: return expr.func(*list(map(rebuild, expr.args)))
3f43bbd5de0c7b3383e04b7590a7901e43a3fed0bb7f8d46462dec77d860e1aa
""" The objects in this module allow the usage of the MatchPy pattern matching library on SymPy expressions. """ import re from typing import List, Callable from sympy.core.sympify import _sympify from sympy.external import import_module from sympy.functions import (log, sin, cos, tan, cot, csc, sec, erf, gamma, uppergamma) from sympy.functions.elementary.hyperbolic import acosh, asinh, atanh, acoth, acsch, asech, cosh, sinh, tanh, coth, sech, csch from sympy.functions.elementary.trigonometric import atan, acsc, asin, acot, acos, asec from sympy.functions.special.error_functions import fresnelc, fresnels, erfc, erfi, Ei from sympy import (Basic, Mul, Add, Pow, Integral, exp, Symbol, Expr, srepr, Equality, Unequality) from sympy.utilities.decorator import doctest_depends_on matchpy = import_module("matchpy") if matchpy: from matchpy import Operation, CommutativeOperation, AssociativeOperation, OneIdentityOperation from matchpy.expressions.functions import op_iter, create_operation_expression, op_len Operation.register(Integral) Operation.register(Pow) OneIdentityOperation.register(Pow) Operation.register(Add) OneIdentityOperation.register(Add) CommutativeOperation.register(Add) AssociativeOperation.register(Add) Operation.register(Mul) OneIdentityOperation.register(Mul) CommutativeOperation.register(Mul) AssociativeOperation.register(Mul) Operation.register(Equality) CommutativeOperation.register(Equality) Operation.register(Unequality) CommutativeOperation.register(Unequality) Operation.register(exp) Operation.register(log) Operation.register(gamma) Operation.register(uppergamma) Operation.register(fresnels) Operation.register(fresnelc) Operation.register(erf) Operation.register(Ei) Operation.register(erfc) Operation.register(erfi) Operation.register(sin) Operation.register(cos) Operation.register(tan) Operation.register(cot) Operation.register(csc) Operation.register(sec) Operation.register(sinh) Operation.register(cosh) Operation.register(tanh) Operation.register(coth) Operation.register(csch) Operation.register(sech) Operation.register(asin) Operation.register(acos) Operation.register(atan) Operation.register(acot) Operation.register(acsc) Operation.register(asec) Operation.register(asinh) Operation.register(acosh) Operation.register(atanh) Operation.register(acoth) Operation.register(acsch) Operation.register(asech) @op_iter.register(Integral) # type: ignore def _(operation): return iter((operation._args[0],) + operation._args[1]) @op_iter.register(Basic) # type: ignore def _(operation): return iter(operation._args) @op_len.register(Integral) # type: ignore def _(operation): return 1 + len(operation._args[1]) @op_len.register(Basic) # type: ignore def _(operation): return len(operation._args) @create_operation_expression.register(Basic) def sympy_op_factory(old_operation, new_operands, variable_name=True): return type(old_operation)(*new_operands) if matchpy: from matchpy import Wildcard else: class Wildcard: def __init__(self, min_length, fixed_size, variable_name, optional): pass @doctest_depends_on(modules=('matchpy',)) class _WildAbstract(Wildcard, Symbol): min_length = None # abstract field required in subclasses fixed_size = None # abstract field required in subclasses def __init__(self, variable_name=None, optional=None, **assumptions): min_length = self.min_length fixed_size = self.fixed_size if optional is not None: optional = _sympify(optional) Wildcard.__init__(self, min_length, fixed_size, str(variable_name), optional) def __new__(cls, variable_name=None, optional=None, **assumptions): cls._sanitize(assumptions, cls) return _WildAbstract.__xnew__(cls, variable_name, optional, **assumptions) def __getnewargs__(self): return self.min_count, self.fixed_size, self.variable_name, self.optional @staticmethod def __xnew__(cls, variable_name=None, optional=None, **assumptions): obj = Symbol.__xnew__(cls, variable_name, **assumptions) return obj def _hashable_content(self): if self.optional: return super()._hashable_content() + (self.min_count, self.fixed_size, self.variable_name, self.optional) else: return super()._hashable_content() + (self.min_count, self.fixed_size, self.variable_name) def __copy__(self) -> '_WildAbstract': return type(self)(variable_name=self.variable_name, optional=self.optional) def __repr__(self): return str(self) def __str__(self): return self.name @doctest_depends_on(modules=('matchpy',)) class WildDot(_WildAbstract): min_length = 1 fixed_size = True @doctest_depends_on(modules=('matchpy',)) class WildPlus(_WildAbstract): min_length = 1 fixed_size = False @doctest_depends_on(modules=('matchpy',)) class WildStar(_WildAbstract): min_length = 0 fixed_size = False def _get_srepr(expr): s = srepr(expr) s = re.sub(r"WildDot\('(\w+)'\)", r"\1", s) s = re.sub(r"WildPlus\('(\w+)'\)", r"*\1", s) s = re.sub(r"WildStar\('(\w+)'\)", r"*\1", s) return s @doctest_depends_on(modules=('matchpy',)) class Replacer: """ Replacer object to perform multiple pattern matching and subexpression replacements in SymPy expressions. Examples ======== Example to construct a simple first degree equation solver: >>> from sympy.utilities.matchpy_connector import WildDot, Replacer >>> from sympy import Equality, Symbol >>> x = Symbol("x") >>> a_ = WildDot("a_", optional=1) >>> b_ = WildDot("b_", optional=0) The lines above have defined two wildcards, ``a_`` and ``b_``, the coefficients of the equation `a x + b = 0`. The optional values specified indicate which expression to return in case no match is found, they are necessary in equations like `a x = 0` and `x + b = 0`. Create two constraints to make sure that ``a_`` and ``b_`` will not match any expression containing ``x``: >>> from matchpy import CustomConstraint >>> free_x_a = CustomConstraint(lambda a_: not a_.has(x)) >>> free_x_b = CustomConstraint(lambda b_: not b_.has(x)) Now create the rule replacer with the constraints: >>> replacer = Replacer(common_constraints=[free_x_a, free_x_b]) Add the matching rule: >>> replacer.add(Equality(a_*x + b_, 0), -b_/a_) Let's try it: >>> replacer.replace(Equality(3*x + 4, 0)) -4/3 Notice that it won't match equations expressed with other patterns: >>> eq = Equality(3*x, 4) >>> replacer.replace(eq) Eq(3*x, 4) In order to extend the matching patterns, define another one (we also need to clear the cache, because the previous result has already been memorized and the pattern matcher won't iterate again if given the same expression) >>> replacer.add(Equality(a_*x, b_), b_/a_) >>> replacer._replacer.matcher.clear() >>> replacer.replace(eq) 4/3 """ def __init__(self, common_constraints: list = []): self._replacer = matchpy.ManyToOneReplacer() self._common_constraint = common_constraints def _get_lambda(self, lambda_str: str) -> Callable[..., Expr]: exec("from sympy import *") return eval(lambda_str, locals()) def _get_custom_constraint(self, constraint_expr: Expr, condition_template: str) -> Callable[..., Expr]: wilds = list(map(lambda x: x.name, constraint_expr.atoms(_WildAbstract))) lambdaargs = ', '.join(wilds) fullexpr = _get_srepr(constraint_expr) condition = condition_template.format(fullexpr) return matchpy.CustomConstraint( self._get_lambda(f"lambda {lambdaargs}: ({condition})")) def _get_custom_constraint_nonfalse(self, constraint_expr: Expr) -> Callable[..., Expr]: return self._get_custom_constraint(constraint_expr, "({}) != False") def _get_custom_constraint_true(self, constraint_expr: Expr) -> Callable[..., Expr]: return self._get_custom_constraint(constraint_expr, "({}) == True") def add(self, expr: Expr, result: Expr, conditions_true: List[Expr] = [], conditions_nonfalse: List[Expr] = []) -> None: expr = _sympify(expr) result = _sympify(result) lambda_str = f"lambda {', '.join(map(lambda x: x.name, expr.atoms(_WildAbstract)))}: {_get_srepr(result)}" lambda_expr = self._get_lambda(lambda_str) constraints = self._common_constraint[:] constraint_conditions_true = [ self._get_custom_constraint_true(cond) for cond in conditions_true] constraint_conditions_nonfalse = [ self._get_custom_constraint_nonfalse(cond) for cond in conditions_nonfalse] constraints.extend(constraint_conditions_true) constraints.extend(constraint_conditions_nonfalse) self._replacer.add( matchpy.ReplacementRule(matchpy.Pattern(expr, *constraints), lambda_expr)) def replace(self, expr: Expr) -> Expr: return self._replacer.replace(expr)
97cf959d61fa3264ce657cafa84f55a6bb6bb0caa878af16feaa03a6e407ab59
""" A Printer for generating readable representation of most sympy classes. """ from typing import Any, Dict from sympy.core import S, Rational, Pow, Basic, Mul, Number from sympy.core.mul import _keep_coeff from .printer import Printer, print_function from sympy.printing.precedence import precedence, PRECEDENCE from mpmath.libmp import prec_to_dps, to_str as mlib_to_str from sympy.utilities import default_sort_key class StrPrinter(Printer): printmethod = "_sympystr" _default_settings = { "order": None, "full_prec": "auto", "sympy_integers": False, "abbrev": False, "perm_cyclic": True, "min": None, "max": None, } # type: Dict[str, Any] _relationals = dict() # type: Dict[str, str] def parenthesize(self, item, level, strict=False): if (precedence(item) < level) or ((not strict) and precedence(item) <= level): return "(%s)" % self._print(item) else: return self._print(item) def stringify(self, args, sep, level=0): return sep.join([self.parenthesize(item, level) for item in args]) def emptyPrinter(self, expr): if isinstance(expr, str): return expr elif isinstance(expr, Basic): return repr(expr) else: return str(expr) def _print_Add(self, expr, order=None): terms = self._as_ordered_terms(expr, order=order) PREC = precedence(expr) l = [] for term in terms: t = self._print(term) if t.startswith('-'): sign = "-" t = t[1:] else: sign = "+" if precedence(term) < PREC: l.extend([sign, "(%s)" % t]) else: l.extend([sign, t]) sign = l.pop(0) if sign == '+': sign = "" return sign + ' '.join(l) def _print_BooleanTrue(self, expr): return "True" def _print_BooleanFalse(self, expr): return "False" def _print_Not(self, expr): return '~%s' %(self.parenthesize(expr.args[0],PRECEDENCE["Not"])) def _print_And(self, expr): return self.stringify(expr.args, " & ", PRECEDENCE["BitwiseAnd"]) def _print_Or(self, expr): return self.stringify(expr.args, " | ", PRECEDENCE["BitwiseOr"]) def _print_Xor(self, expr): return self.stringify(expr.args, " ^ ", PRECEDENCE["BitwiseXor"]) def _print_AppliedPredicate(self, expr): return '%s(%s)' % ( self._print(expr.function), self.stringify(expr.arguments, ", ")) def _print_Basic(self, expr): l = [self._print(o) for o in expr.args] return expr.__class__.__name__ + "(%s)" % ", ".join(l) def _print_BlockMatrix(self, B): if B.blocks.shape == (1, 1): self._print(B.blocks[0, 0]) return self._print(B.blocks) def _print_Catalan(self, expr): return 'Catalan' def _print_ComplexInfinity(self, expr): return 'zoo' def _print_ConditionSet(self, s): args = tuple([self._print(i) for i in (s.sym, s.condition)]) if s.base_set is S.UniversalSet: return 'ConditionSet(%s, %s)' % args args += (self._print(s.base_set),) return 'ConditionSet(%s, %s, %s)' % args def _print_Derivative(self, expr): dexpr = expr.expr dvars = [i[0] if i[1] == 1 else i for i in expr.variable_count] return 'Derivative(%s)' % ", ".join(map(lambda arg: self._print(arg), [dexpr] + dvars)) def _print_dict(self, d): keys = sorted(d.keys(), key=default_sort_key) items = [] for key in keys: item = "%s: %s" % (self._print(key), self._print(d[key])) items.append(item) return "{%s}" % ", ".join(items) def _print_Dict(self, expr): return self._print_dict(expr) def _print_RandomDomain(self, d): if hasattr(d, 'as_boolean'): return 'Domain: ' + self._print(d.as_boolean()) elif hasattr(d, 'set'): return ('Domain: ' + self._print(d.symbols) + ' in ' + self._print(d.set)) else: return 'Domain on ' + self._print(d.symbols) def _print_Dummy(self, expr): return '_' + expr.name def _print_EulerGamma(self, expr): return 'EulerGamma' def _print_Exp1(self, expr): return 'E' def _print_ExprCondPair(self, expr): return '(%s, %s)' % (self._print(expr.expr), self._print(expr.cond)) def _print_Function(self, expr): return expr.func.__name__ + "(%s)" % self.stringify(expr.args, ", ") def _print_GoldenRatio(self, expr): return 'GoldenRatio' def _print_TribonacciConstant(self, expr): return 'TribonacciConstant' def _print_ImaginaryUnit(self, expr): return 'I' def _print_Infinity(self, expr): return 'oo' def _print_Integral(self, expr): def _xab_tostr(xab): if len(xab) == 1: return self._print(xab[0]) else: return self._print((xab[0],) + tuple(xab[1:])) L = ', '.join([_xab_tostr(l) for l in expr.limits]) return 'Integral(%s, %s)' % (self._print(expr.function), L) def _print_Interval(self, i): fin = 'Interval{m}({a}, {b})' a, b, l, r = i.args if a.is_infinite and b.is_infinite: m = '' elif a.is_infinite and not r: m = '' elif b.is_infinite and not l: m = '' elif not l and not r: m = '' elif l and r: m = '.open' elif l: m = '.Lopen' else: m = '.Ropen' return fin.format(**{'a': a, 'b': b, 'm': m}) def _print_AccumulationBounds(self, i): return "AccumBounds(%s, %s)" % (self._print(i.min), self._print(i.max)) def _print_Inverse(self, I): return "%s**(-1)" % self.parenthesize(I.arg, PRECEDENCE["Pow"]) def _print_Lambda(self, obj): expr = obj.expr sig = obj.signature if len(sig) == 1 and sig[0].is_symbol: sig = sig[0] return "Lambda(%s, %s)" % (self._print(sig), self._print(expr)) def _print_LatticeOp(self, expr): args = sorted(expr.args, key=default_sort_key) return expr.func.__name__ + "(%s)" % ", ".join(self._print(arg) for arg in args) def _print_Limit(self, expr): e, z, z0, dir = expr.args if str(dir) == "+": return "Limit(%s, %s, %s)" % tuple(map(self._print, (e, z, z0))) else: return "Limit(%s, %s, %s, dir='%s')" % tuple(map(self._print, (e, z, z0, dir))) def _print_list(self, expr): return "[%s]" % self.stringify(expr, ", ") def _print_MatrixBase(self, expr): return expr._format_str(self) def _print_MatrixElement(self, expr): return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \ + '[%s, %s]' % (self._print(expr.i), self._print(expr.j)) def _print_MatrixSlice(self, expr): def strslice(x, dim): x = list(x) if x[2] == 1: del x[2] if x[0] == 0: x[0] = '' if x[1] == dim: x[1] = '' return ':'.join(map(lambda arg: self._print(arg), x)) return (self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) + '[' + strslice(expr.rowslice, expr.parent.rows) + ', ' + strslice(expr.colslice, expr.parent.cols) + ']') def _print_DeferredVector(self, expr): return expr.name def _print_Mul(self, expr): prec = precedence(expr) # Check for unevaluated Mul. In this case we need to make sure the # identities are visible, multiple Rational factors are not combined # etc so we display in a straight-forward form that fully preserves all # args and their order. args = expr.args if args[0] is S.One or any(isinstance(arg, Number) for arg in args[1:]): factors = [self.parenthesize(a, prec, strict=False) for a in args] return '*'.join(factors) c, e = expr.as_coeff_Mul() if c < 0: expr = _keep_coeff(-c, e) sign = "-" else: sign = "" a = [] # items in the numerator b = [] # items that are in the denominator (if any) pow_paren = [] # Will collect all pow with more than one base element and exp = -1 if self.order not in ('old', 'none'): args = expr.as_ordered_factors() else: # use make_args in case expr was something like -x -> x args = Mul.make_args(expr) # Gather args for numerator/denominator 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: if len(item.args[0].args) != 1 and isinstance(item.base, Mul): # To avoid situations like #14160 pow_paren.append(item) 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) a = a or [S.One] a_str = [self.parenthesize(x, prec, strict=False) for x in a] b_str = [self.parenthesize(x, prec, strict=False) for x in b] # To parenthesize Pow with exp = -1 and having more than one Symbol for item in pow_paren: if item.base in b: b_str[b.index(item.base)] = "(%s)" % b_str[b.index(item.base)] if not b: return sign + '*'.join(a_str) elif len(b) == 1: return sign + '*'.join(a_str) + "/" + b_str[0] else: return sign + '*'.join(a_str) + "/(%s)" % '*'.join(b_str) def _print_MatMul(self, expr): c, m = expr.as_coeff_mmul() sign = "" if c.is_number: re, im = c.as_real_imag() if im.is_zero and re.is_negative: expr = _keep_coeff(-c, m) sign = "-" elif re.is_zero and im.is_negative: expr = _keep_coeff(-c, m) sign = "-" return sign + '*'.join( [self.parenthesize(arg, precedence(expr)) for arg in expr.args] ) def _print_ElementwiseApplyFunction(self, expr): return "{}.({})".format( expr.function, self._print(expr.expr), ) def _print_NaN(self, expr): return 'nan' def _print_NegativeInfinity(self, expr): return '-oo' def _print_Order(self, expr): if not expr.variables or all(p is S.Zero for p in expr.point): if len(expr.variables) <= 1: return 'O(%s)' % self._print(expr.expr) else: return 'O(%s)' % self.stringify((expr.expr,) + expr.variables, ', ', 0) else: return 'O(%s)' % self.stringify(expr.args, ', ', 0) def _print_Ordinal(self, expr): return expr.__str__() def _print_Cycle(self, expr): return expr.__str__() def _print_Permutation(self, expr): from sympy.combinatorics.permutations import Permutation, Cycle from sympy.utilities.exceptions import SymPyDeprecationWarning perm_cyclic = Permutation.print_cyclic if perm_cyclic is not None: SymPyDeprecationWarning( feature="Permutation.print_cyclic = {}".format(perm_cyclic), useinstead="init_printing(perm_cyclic={})" .format(perm_cyclic), issue=15201, deprecated_since_version="1.6").warn() else: perm_cyclic = self._settings.get("perm_cyclic", True) if perm_cyclic: if not expr.size: return '()' # before taking Cycle notation, see if the last element is # a singleton and move it to the head of the string s = Cycle(expr)(expr.size - 1).__repr__()[len('Cycle'):] last = s.rfind('(') if not last == 0 and ',' not in s[last:]: s = s[last:] + s[:last] s = s.replace(',', '') return s else: s = expr.support() if not s: if expr.size < 5: return 'Permutation(%s)' % self._print(expr.array_form) return 'Permutation([], size=%s)' % self._print(expr.size) trim = self._print(expr.array_form[:s[-1] + 1]) + ', size=%s' % self._print(expr.size) use = full = self._print(expr.array_form) if len(trim) < len(full): use = trim return 'Permutation(%s)' % use def _print_Subs(self, obj): expr, old, new = obj.args if len(obj.point) == 1: old = old[0] new = new[0] return "Subs(%s, %s, %s)" % ( self._print(expr), self._print(old), self._print(new)) def _print_TensorIndex(self, expr): return expr._print() def _print_TensorHead(self, expr): return expr._print() def _print_Tensor(self, expr): return expr._print() def _print_TensMul(self, expr): # prints expressions like "A(a)", "3*A(a)", "(1+x)*A(a)" sign, args = expr._get_args_for_traditional_printer() return sign + "*".join( [self.parenthesize(arg, precedence(expr)) for arg in args] ) def _print_TensAdd(self, expr): return expr._print() def _print_PermutationGroup(self, expr): p = [' %s' % self._print(a) for a in expr.args] return 'PermutationGroup([\n%s])' % ',\n'.join(p) def _print_Pi(self, expr): return 'pi' def _print_PolyRing(self, ring): return "Polynomial ring in %s over %s with %s order" % \ (", ".join(map(lambda rs: self._print(rs), ring.symbols)), self._print(ring.domain), self._print(ring.order)) def _print_FracField(self, field): return "Rational function field in %s over %s with %s order" % \ (", ".join(map(lambda fs: self._print(fs), field.symbols)), self._print(field.domain), self._print(field.order)) def _print_FreeGroupElement(self, elm): return elm.__str__() def _print_GaussianElement(self, poly): return "(%s + %s*I)" % (poly.x, poly.y) def _print_PolyElement(self, poly): return poly.str(self, PRECEDENCE, "%s**%s", "*") def _print_FracElement(self, frac): if frac.denom == 1: return self._print(frac.numer) else: numer = self.parenthesize(frac.numer, PRECEDENCE["Mul"], strict=True) denom = self.parenthesize(frac.denom, PRECEDENCE["Atom"], strict=True) return numer + "/" + denom def _print_Poly(self, expr): ATOM_PREC = PRECEDENCE["Atom"] - 1 terms, gens = [], [ self.parenthesize(s, ATOM_PREC) for s in expr.gens ] for monom, coeff in expr.terms(): s_monom = [] for i, exp in enumerate(monom): if exp > 0: if exp == 1: s_monom.append(gens[i]) else: s_monom.append(gens[i] + "**%d" % exp) s_monom = "*".join(s_monom) if coeff.is_Add: if s_monom: s_coeff = "(" + self._print(coeff) + ")" else: s_coeff = self._print(coeff) else: if s_monom: if coeff is S.One: terms.extend(['+', s_monom]) continue if coeff is S.NegativeOne: terms.extend(['-', s_monom]) continue s_coeff = self._print(coeff) if not s_monom: s_term = s_coeff else: s_term = s_coeff + "*" + s_monom if s_term.startswith('-'): terms.extend(['-', s_term[1:]]) else: terms.extend(['+', s_term]) if terms[0] in ['-', '+']: modifier = terms.pop(0) if modifier == '-': terms[0] = '-' + terms[0] format = expr.__class__.__name__ + "(%s, %s" from sympy.polys.polyerrors import PolynomialError try: format += ", modulus=%s" % expr.get_modulus() except PolynomialError: format += ", domain='%s'" % expr.get_domain() format += ")" for index, item in enumerate(gens): if len(item) > 2 and (item[:1] == "(" and item[len(item) - 1:] == ")"): gens[index] = item[1:len(item) - 1] return format % (' '.join(terms), ', '.join(gens)) def _print_UniversalSet(self, p): return 'UniversalSet' def _print_AlgebraicNumber(self, expr): if expr.is_aliased: return self._print(expr.as_poly().as_expr()) else: return self._print(expr.as_expr()) def _print_Pow(self, expr, rational=False): """Printing helper function for ``Pow`` Parameters ========== rational : bool, optional If ``True``, it will not attempt printing ``sqrt(x)`` or ``x**S.Half`` as ``sqrt``, and will use ``x**(1/2)`` instead. See examples for additional details Examples ======== >>> from sympy.functions import sqrt >>> from sympy.printing.str import StrPrinter >>> from sympy.abc import x How ``rational`` keyword works with ``sqrt``: >>> printer = StrPrinter() >>> printer._print_Pow(sqrt(x), rational=True) 'x**(1/2)' >>> printer._print_Pow(sqrt(x), rational=False) 'sqrt(x)' >>> printer._print_Pow(1/sqrt(x), rational=True) 'x**(-1/2)' >>> printer._print_Pow(1/sqrt(x), rational=False) '1/sqrt(x)' Notes ===== ``sqrt(x)`` is canonicalized as ``Pow(x, S.Half)`` in SymPy, so there is no need of defining a separate printer for ``sqrt``. Instead, it should be handled here as well. """ PREC = precedence(expr) if expr.exp is S.Half and not rational: return "sqrt(%s)" % self._print(expr.base) if expr.is_commutative: if -expr.exp is S.Half and not rational: # Note: Don't test "expr.exp == -S.Half" here, because that will # match -0.5, which we don't want. return "%s/sqrt(%s)" % tuple(map(lambda arg: self._print(arg), (S.One, expr.base))) if expr.exp is -S.One: # Similarly to the S.Half case, don't test with "==" here. return '%s/%s' % (self._print(S.One), self.parenthesize(expr.base, PREC, strict=False)) e = self.parenthesize(expr.exp, PREC, strict=False) if self.printmethod == '_sympyrepr' and expr.exp.is_Rational and expr.exp.q != 1: # the parenthesized exp should be '(Rational(a, b))' so strip parens, # but just check to be sure. if e.startswith('(Rational'): return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e[1:-1]) return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), e) def _print_UnevaluatedExpr(self, expr): return self._print(expr.args[0]) def _print_MatPow(self, expr): PREC = precedence(expr) return '%s**%s' % (self.parenthesize(expr.base, PREC, strict=False), self.parenthesize(expr.exp, PREC, strict=False)) def _print_Integer(self, expr): if self._settings.get("sympy_integers", False): return "S(%s)" % (expr) return str(expr.p) def _print_Integers(self, expr): return 'Integers' def _print_Naturals(self, expr): return 'Naturals' def _print_Naturals0(self, expr): return 'Naturals0' def _print_Rationals(self, expr): return 'Rationals' def _print_Reals(self, expr): return 'Reals' def _print_Complexes(self, expr): return 'Complexes' def _print_EmptySet(self, expr): return 'EmptySet' def _print_EmptySequence(self, expr): return 'EmptySequence' def _print_int(self, expr): return str(expr) def _print_mpz(self, expr): return str(expr) def _print_Rational(self, expr): if expr.q == 1: return str(expr.p) else: if self._settings.get("sympy_integers", False): return "S(%s)/%s" % (expr.p, expr.q) return "%s/%s" % (expr.p, expr.q) def _print_PythonRational(self, expr): if expr.q == 1: return str(expr.p) else: return "%d/%d" % (expr.p, expr.q) def _print_Fraction(self, expr): if expr.denominator == 1: return str(expr.numerator) else: return "%s/%s" % (expr.numerator, expr.denominator) def _print_mpq(self, expr): if expr.denominator == 1: return str(expr.numerator) else: return "%s/%s" % (expr.numerator, expr.denominator) def _print_Float(self, expr): prec = expr._prec if prec < 5: dps = 0 else: dps = prec_to_dps(expr._prec) if self._settings["full_prec"] is True: strip = False elif self._settings["full_prec"] is False: strip = True elif self._settings["full_prec"] == "auto": strip = self._print_level > 1 low = self._settings["min"] if "min" in self._settings else None high = self._settings["max"] if "max" in self._settings else None rv = mlib_to_str(expr._mpf_, dps, strip_zeros=strip, min_fixed=low, max_fixed=high) if rv.startswith('-.0'): rv = '-0.' + rv[3:] elif rv.startswith('.0'): rv = '0.' + rv[2:] if rv.startswith('+'): # e.g., +inf -> inf rv = rv[1:] return rv def _print_Relational(self, expr): charmap = { "==": "Eq", "!=": "Ne", ":=": "Assignment", '+=': "AddAugmentedAssignment", "-=": "SubAugmentedAssignment", "*=": "MulAugmentedAssignment", "/=": "DivAugmentedAssignment", "%=": "ModAugmentedAssignment", } if expr.rel_op in charmap: return '%s(%s, %s)' % (charmap[expr.rel_op], self._print(expr.lhs), self._print(expr.rhs)) return '%s %s %s' % (self.parenthesize(expr.lhs, precedence(expr)), self._relationals.get(expr.rel_op) or expr.rel_op, self.parenthesize(expr.rhs, precedence(expr))) def _print_ComplexRootOf(self, expr): return "CRootOf(%s, %d)" % (self._print_Add(expr.expr, order='lex'), expr.index) def _print_RootSum(self, expr): args = [self._print_Add(expr.expr, order='lex')] if expr.fun is not S.IdentityFunction: args.append(self._print(expr.fun)) return "RootSum(%s)" % ", ".join(args) def _print_GroebnerBasis(self, basis): cls = basis.__class__.__name__ exprs = [self._print_Add(arg, order=basis.order) for arg in basis.exprs] exprs = "[%s]" % ", ".join(exprs) gens = [ self._print(gen) for gen in basis.gens ] domain = "domain='%s'" % self._print(basis.domain) order = "order='%s'" % self._print(basis.order) args = [exprs] + gens + [domain, order] return "%s(%s)" % (cls, ", ".join(args)) def _print_set(self, s): items = sorted(s, key=default_sort_key) args = ', '.join(self._print(item) for item in items) if not args: return "set()" return '{%s}' % args def _print_frozenset(self, s): if not s: return "frozenset()" return "frozenset(%s)" % self._print_set(s) def _print_Sum(self, expr): def _xab_tostr(xab): if len(xab) == 1: return self._print(xab[0]) else: return self._print((xab[0],) + tuple(xab[1:])) L = ', '.join([_xab_tostr(l) for l in expr.limits]) return 'Sum(%s, %s)' % (self._print(expr.function), L) def _print_Symbol(self, expr): return expr.name _print_MatrixSymbol = _print_Symbol _print_RandomSymbol = _print_Symbol def _print_Identity(self, expr): return "I" def _print_ZeroMatrix(self, expr): return "0" def _print_OneMatrix(self, expr): return "1" def _print_Predicate(self, expr): return "Q.%s" % expr.name def _print_str(self, expr): return str(expr) def _print_tuple(self, expr): if len(expr) == 1: return "(%s,)" % self._print(expr[0]) else: return "(%s)" % self.stringify(expr, ", ") def _print_Tuple(self, expr): return self._print_tuple(expr) def _print_Transpose(self, T): return "%s.T" % self.parenthesize(T.arg, PRECEDENCE["Pow"]) def _print_Uniform(self, expr): return "Uniform(%s, %s)" % (self._print(expr.a), self._print(expr.b)) def _print_Quantity(self, expr): if self._settings.get("abbrev", False): return "%s" % expr.abbrev return "%s" % expr.name def _print_Quaternion(self, expr): s = [self.parenthesize(i, PRECEDENCE["Mul"], strict=True) for i in expr.args] a = [s[0]] + [i+"*"+j for i, j in zip(s[1:], "ijk")] return " + ".join(a) def _print_Dimension(self, expr): return str(expr) def _print_Wild(self, expr): return expr.name + '_' def _print_WildFunction(self, expr): return expr.name + '_' def _print_WildDot(self, expr): return expr.name def _print_WildPlus(self, expr): return expr.name def _print_WildStar(self, expr): return expr.name def _print_Zero(self, expr): if self._settings.get("sympy_integers", False): return "S(0)" return "0" def _print_DMP(self, p): from sympy.core.sympify import SympifyError try: if p.ring is not None: # TODO incorporate order return self._print(p.ring.to_sympy(p)) except SympifyError: pass cls = p.__class__.__name__ rep = self._print(p.rep) dom = self._print(p.dom) ring = self._print(p.ring) return "%s(%s, %s, %s)" % (cls, rep, dom, ring) def _print_DMF(self, expr): return self._print_DMP(expr) def _print_Object(self, obj): return 'Object("%s")' % obj.name def _print_IdentityMorphism(self, morphism): return 'IdentityMorphism(%s)' % morphism.domain def _print_NamedMorphism(self, morphism): return 'NamedMorphism(%s, %s, "%s")' % \ (morphism.domain, morphism.codomain, morphism.name) def _print_Category(self, category): return 'Category("%s")' % category.name def _print_Manifold(self, manifold): return manifold.name.name def _print_Patch(self, patch): return patch.name.name def _print_CoordSystem(self, coords): return coords.name.name def _print_BaseScalarField(self, field): return field._coord_sys.symbols[field._index].name def _print_BaseVectorField(self, field): return 'e_%s' % field._coord_sys.symbols[field._index].name def _print_Differential(self, diff): field = diff._form_field if hasattr(field, '_coord_sys'): return 'd%s' % field._coord_sys.symbols[field._index].name else: return 'd(%s)' % self._print(field) def _print_Tr(self, expr): #TODO : Handle indices return "%s(%s)" % ("Tr", self._print(expr.args[0])) def _print_Str(self, s): return self._print(s.name) @print_function(StrPrinter) def sstr(expr, **settings): """Returns the expression as a string. For large expressions where speed is a concern, use the setting order='none'. If abbrev=True setting is used then units are printed in abbreviated form. Examples ======== >>> from sympy import symbols, Eq, sstr >>> a, b = symbols('a b') >>> sstr(Eq(a + b, 0)) 'Eq(a + b, 0)' """ p = StrPrinter(settings) s = p.doprint(expr) return s class StrReprPrinter(StrPrinter): """(internal) -- see sstrrepr""" def _print_str(self, s): return repr(s) def _print_Str(self, s): # Str does not to be printed same as str here return "%s(%s)" % (s.__class__.__name__, self._print(s.name)) @print_function(StrReprPrinter) def sstrrepr(expr, **settings): """return expr in mixed str/repr form i.e. strings are returned in repr form with quotes, and everything else is returned in str form. This function could be useful for hooking into sys.displayhook """ p = StrReprPrinter(settings) s = p.doprint(expr) return s