hash
stringlengths
64
64
content
stringlengths
0
1.51M
2f0ce74a6651250b7fb037aafe5717b145e54b2adc13c27e73082f8bdb1a5038
from functools import reduce import operator from sympy.core import Basic, sympify from sympy.core.add import add, Add, _could_extract_minus_sign from sympy.core.sorting import default_sort_key from sympy.functions import adjoint 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.matrices.expressions._shape import validate_matadd_integer as validate from sympy.utilities.iterables import sift from sympy.utilities.exceptions import sympy_deprecation_warning # 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=None, _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)) if not all(isinstance(arg, MatrixExpr) for arg in args): raise TypeError("Mix of Matrix and Scalar symbols") obj = Basic.__new__(cls, *args) if check is not None: sympy_deprecation_warning( "Passing check to MatAdd is deprecated and the check argument will be removed in a future version.", deprecated_since_version="1.11", active_deprecations_target='remove-check-argument-from-matrix-operations') if check is not False: validate(*args) if evaluate: obj = cls._evaluate(obj) return obj @classmethod def _evaluate(cls, expr): return canonicalize(expr) @property def shape(self): return self.args[0].shape def could_extract_minus_sign(self): return _could_extract_minus_sign(self) def expand(self, **kwargs): expanded = super(MatAdd, self).expand(**kwargs) return self._evaluate(expanded) 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, **hints): deep = hints.get('deep', True) if deep: args = [arg.doit(**hints) 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) 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)))
0e42bf46e20503d1fd1e859c7a0b4f5911df40d835ee1e427ea503dba13cbbc1
from sympy.matrices.expressions import MatrixSymbol, MatAdd, MatPow, MatMul from sympy.matrices.expressions.special import GenericZeroMatrix, ZeroMatrix from sympy.matrices.common import ShapeError from sympy.matrices import eye, ImmutableMatrix from sympy.core import Add, Basic, S from sympy.core.add import add from sympy.testing.pytest import XFAIL, raises X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) def test_evaluate(): assert MatAdd(X, X, evaluate=True) == add(X, X, evaluate=True) == MatAdd(X, X).doit() def test_sort_key(): assert MatAdd(Y, X).doit().args == add(Y, X).doit().args == (X, Y) def test_matadd_sympify(): assert isinstance(MatAdd(eye(1), eye(1)).args[0], Basic) assert isinstance(add(eye(1), eye(1)).args[0], Basic) def test_matadd_of_matrices(): assert MatAdd(eye(2), 4*eye(2), eye(2)).doit() == ImmutableMatrix(6*eye(2)) assert add(eye(2), 4*eye(2), eye(2)).doit() == ImmutableMatrix(6*eye(2)) def test_doit_args(): A = ImmutableMatrix([[1, 2], [3, 4]]) B = ImmutableMatrix([[2, 3], [4, 5]]) assert MatAdd(A, MatPow(B, 2)).doit() == A + B**2 assert MatAdd(A, MatMul(A, B)).doit() == A + A*B assert (MatAdd(A, X, MatMul(A, B), Y, MatAdd(2*A, B)).doit() == add(A, X, MatMul(A, B), Y, add(2*A, B)).doit() == MatAdd(3*A + A*B + B, X, Y)) def test_generic_identity(): assert MatAdd.identity == GenericZeroMatrix() assert MatAdd.identity != S.Zero def test_zero_matrix_add(): assert Add(ZeroMatrix(2, 2), ZeroMatrix(2, 2)) == ZeroMatrix(2, 2) @XFAIL def test_matrix_Add_with_scalar(): raises(TypeError, lambda: Add(0, ZeroMatrix(2, 2))) def test_shape_error(): A = MatrixSymbol('A', 2, 3) B = MatrixSymbol('B', 3, 3) raises(ShapeError, lambda: MatAdd(A, B)) A = MatrixSymbol('A', 3, 2) raises(ShapeError, lambda: MatAdd(A, B))
32e308ccffa8ba2b91b935393e606d53e5e4ff406dbb89b29be0b6d0cf25379f
from sympy.core import I, symbols, Basic, Mul, S from sympy.core.mul import mul from sympy.functions import adjoint, transpose from sympy.matrices.common import ShapeError from sympy.matrices import (Identity, Inverse, Matrix, MatrixSymbol, ZeroMatrix, eye, ImmutableMatrix) from sympy.matrices.expressions import Adjoint, Transpose, det, MatPow from sympy.matrices.expressions.special import GenericIdentity from sympy.matrices.expressions.matmul import (factor_in_front, remove_ids, MatMul, combine_powers, any_zeros, unpack, only_squares) from sympy.strategies import null_safe from sympy.assumptions.ask import Q from sympy.assumptions.refine import refine from sympy.core.symbol import Symbol from sympy.testing.pytest import XFAIL, raises n, m, l, k = symbols('n m l k', integer=True) x = symbols('x') A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', m, l) C = MatrixSymbol('C', n, n) D = MatrixSymbol('D', n, n) E = MatrixSymbol('E', m, n) def test_evaluate(): assert MatMul(C, C, evaluate=True) == MatMul(C, C).doit() def test_adjoint(): assert adjoint(A*B) == Adjoint(B)*Adjoint(A) assert adjoint(2*A*B) == 2*Adjoint(B)*Adjoint(A) assert adjoint(2*I*C) == -2*I*Adjoint(C) M = Matrix(2, 2, [1, 2 + I, 3, 4]) MA = Matrix(2, 2, [1, 3, 2 - I, 4]) assert adjoint(M) == MA assert adjoint(2*M) == 2*MA assert adjoint(MatMul(2, M)) == MatMul(2, MA).doit() def test_transpose(): assert transpose(A*B) == Transpose(B)*Transpose(A) assert transpose(2*A*B) == 2*Transpose(B)*Transpose(A) assert transpose(2*I*C) == 2*I*Transpose(C) M = Matrix(2, 2, [1, 2 + I, 3, 4]) MT = Matrix(2, 2, [1, 3, 2 + I, 4]) assert transpose(M) == MT assert transpose(2*M) == 2*MT assert transpose(x*M) == x*MT assert transpose(MatMul(2, M)) == MatMul(2, MT).doit() def test_factor_in_front(): assert factor_in_front(MatMul(A, 2, B, evaluate=False)) ==\ MatMul(2, A, B, evaluate=False) def test_remove_ids(): assert remove_ids(MatMul(A, Identity(m), B, evaluate=False)) == \ MatMul(A, B, evaluate=False) assert null_safe(remove_ids)(MatMul(Identity(n), evaluate=False)) == \ MatMul(Identity(n), evaluate=False) def test_combine_powers(): assert combine_powers(MatMul(D, Inverse(D), D, evaluate=False)) == \ MatMul(Identity(n), D, evaluate=False) assert combine_powers(MatMul(B.T, Inverse(E*A), E, A, B, evaluate=False)) == \ MatMul(B.T, Identity(m), B, evaluate=False) assert combine_powers(MatMul(A, E, Inverse(A*E), D, evaluate=False)) == \ MatMul(Identity(n), D, evaluate=False) def test_any_zeros(): assert any_zeros(MatMul(A, ZeroMatrix(m, k), evaluate=False)) == \ ZeroMatrix(n, k) def test_unpack(): assert unpack(MatMul(A, evaluate=False)) == A x = MatMul(A, B) assert unpack(x) == x def test_only_squares(): assert only_squares(C) == [C] assert only_squares(C, D) == [C, D] assert only_squares(C, A, A.T, D) == [C, A*A.T, D] def test_determinant(): assert det(2*C) == 2**n*det(C) assert det(2*C*D) == 2**n*det(C)*det(D) assert det(3*C*A*A.T*D) == 3**n*det(C)*det(A*A.T)*det(D) def test_doit(): assert MatMul(C, 2, D).args == (C, 2, D) assert MatMul(C, 2, D).doit().args == (2, C, D) assert MatMul(C, Transpose(D*C)).args == (C, Transpose(D*C)) assert MatMul(C, Transpose(D*C)).doit(deep=True).args == (C, C.T, D.T) def test_doit_drills_down(): X = ImmutableMatrix([[1, 2], [3, 4]]) Y = ImmutableMatrix([[2, 3], [4, 5]]) assert MatMul(X, MatPow(Y, 2)).doit() == X*Y**2 assert MatMul(C, Transpose(D*C)).doit().args == (C, C.T, D.T) def test_doit_deep_false_still_canonical(): assert (MatMul(C, Transpose(D*C), 2).doit(deep=False).args == (2, C, Transpose(D*C))) def test_matmul_scalar_Matrix_doit(): # Issue 9053 X = Matrix([[1, 2], [3, 4]]) assert MatMul(2, X).doit() == 2*X def test_matmul_sympify(): assert isinstance(MatMul(eye(1), eye(1)).args[0], Basic) def test_collapse_MatrixBase(): A = Matrix([[1, 1], [1, 1]]) B = Matrix([[1, 2], [3, 4]]) assert MatMul(A, B).doit() == ImmutableMatrix([[4, 6], [4, 6]]) def test_refine(): assert refine(C*C.T*D, Q.orthogonal(C)).doit() == D kC = k*C assert refine(kC*C.T, Q.orthogonal(C)).doit() == k*Identity(n) assert refine(kC* kC.T, Q.orthogonal(C)).doit() == (k**2)*Identity(n) def test_matmul_no_matrices(): assert MatMul(1) == 1 assert MatMul(n, m) == n*m assert not isinstance(MatMul(n, m), MatMul) def test_matmul_args_cnc(): assert MatMul(n, A, A.T).args_cnc() == [[n], [A, A.T]] assert MatMul(A, A.T).args_cnc() == [[], [A, A.T]] @XFAIL def test_matmul_args_cnc_symbols(): # Not currently supported a, b = symbols('a b', commutative=False) assert MatMul(n, a, b, A, A.T).args_cnc() == [[n], [a, b, A, A.T]] assert MatMul(n, a, A, b, A.T).args_cnc() == [[n], [a, A, b, A.T]] def test_issue_12950(): M = Matrix([[Symbol("x")]]) * MatrixSymbol("A", 1, 1) assert MatrixSymbol("A", 1, 1).as_explicit()[0]*Symbol('x') == M.as_explicit()[0] def test_construction_with_Mul(): assert Mul(C, D) == MatMul(C, D) assert Mul(D, C) == MatMul(D, C) def test_construction_with_mul(): assert mul(C, D) == MatMul(C, D) assert mul(D, C) == MatMul(D, C) assert mul(C, D) != MatMul(D, C) def test_generic_identity(): assert MatMul.identity == GenericIdentity() assert MatMul.identity != S.One def test_issue_23519(): N = Symbol("N", integer=True) M1 = MatrixSymbol("M1", N, N) M2 = MatrixSymbol("M2", N, N) I = Identity(N) z = (M2 + 2 * (M2 + I) * M1 + I) assert z.coeff(M1) == 2*I + 2*M2 def test_shape_error(): A = MatrixSymbol('A', 2, 2) B = MatrixSymbol('B', 3, 3) raises(ShapeError, lambda: MatMul(A, B))
32183bd6f9e38dbe1f9b48d98230e8596f2b0093017a1f1a0c233be608c4a4a4
from sympy.core.add import Add from sympy.core.expr import unchanged from sympy.core.mul import Mul from sympy.core.symbol import symbols from sympy.core.relational import Eq from sympy.concrete.summations import Sum from sympy.functions.elementary.complexes import im, re from sympy.functions.elementary.piecewise import Piecewise from sympy.matrices.immutable import ImmutableDenseMatrix from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.matadd import MatAdd from sympy.matrices.expressions.special import ( ZeroMatrix, GenericZeroMatrix, Identity, GenericIdentity, OneMatrix) from sympy.matrices.expressions.matmul import MatMul from sympy.testing.pytest import raises def test_zero_matrix_creation(): assert unchanged(ZeroMatrix, 2, 2) assert unchanged(ZeroMatrix, 0, 0) raises(ValueError, lambda: ZeroMatrix(-1, 2)) raises(ValueError, lambda: ZeroMatrix(2.0, 2)) raises(ValueError, lambda: ZeroMatrix(2j, 2)) raises(ValueError, lambda: ZeroMatrix(2, -1)) raises(ValueError, lambda: ZeroMatrix(2, 2.0)) raises(ValueError, lambda: ZeroMatrix(2, 2j)) n = symbols('n') assert unchanged(ZeroMatrix, n, n) n = symbols('n', integer=False) raises(ValueError, lambda: ZeroMatrix(n, n)) n = symbols('n', negative=True) raises(ValueError, lambda: ZeroMatrix(n, n)) def test_generic_zero_matrix(): z = GenericZeroMatrix() n = symbols('n', integer=True) A = MatrixSymbol("A", n, n) assert z == z assert z != A assert A != z assert z.is_ZeroMatrix raises(TypeError, lambda: z.shape) raises(TypeError, lambda: z.rows) raises(TypeError, lambda: z.cols) assert MatAdd() == z assert MatAdd(z, A) == MatAdd(A) # Make sure it is hashable hash(z) def test_identity_matrix_creation(): assert Identity(2) assert Identity(0) raises(ValueError, lambda: Identity(-1)) raises(ValueError, lambda: Identity(2.0)) raises(ValueError, lambda: Identity(2j)) n = symbols('n') assert Identity(n) n = symbols('n', integer=False) raises(ValueError, lambda: Identity(n)) n = symbols('n', negative=True) raises(ValueError, lambda: Identity(n)) def test_generic_identity(): I = GenericIdentity() n = symbols('n', integer=True) A = MatrixSymbol("A", n, n) assert I == I assert I != A assert A != I assert I.is_Identity assert I**-1 == I raises(TypeError, lambda: I.shape) raises(TypeError, lambda: I.rows) raises(TypeError, lambda: I.cols) assert MatMul() == I assert MatMul(I, A) == MatMul(A) # Make sure it is hashable hash(I) def test_one_matrix_creation(): assert OneMatrix(2, 2) assert OneMatrix(0, 0) assert Eq(OneMatrix(1, 1), Identity(1)) raises(ValueError, lambda: OneMatrix(-1, 2)) raises(ValueError, lambda: OneMatrix(2.0, 2)) raises(ValueError, lambda: OneMatrix(2j, 2)) raises(ValueError, lambda: OneMatrix(2, -1)) raises(ValueError, lambda: OneMatrix(2, 2.0)) raises(ValueError, lambda: OneMatrix(2, 2j)) n = symbols('n') assert OneMatrix(n, n) n = symbols('n', integer=False) raises(ValueError, lambda: OneMatrix(n, n)) n = symbols('n', negative=True) raises(ValueError, lambda: OneMatrix(n, n)) def test_ZeroMatrix(): n, m = symbols('n m', integer=True) A = MatrixSymbol('A', n, m) Z = ZeroMatrix(n, m) assert A + Z == A assert A*Z.T == ZeroMatrix(n, n) assert Z*A.T == ZeroMatrix(n, n) assert A - A == ZeroMatrix(*A.shape) assert Z assert Z.transpose() == ZeroMatrix(m, n) assert Z.conjugate() == Z assert Z.adjoint() == ZeroMatrix(m, n) assert re(Z) == Z assert im(Z) == Z assert ZeroMatrix(n, n)**0 == Identity(n) assert ZeroMatrix(3, 3).as_explicit() == ImmutableDenseMatrix.zeros(3, 3) def test_ZeroMatrix_doit(): n = symbols('n', integer=True) Znn = ZeroMatrix(Add(n, n, evaluate=False), n) assert isinstance(Znn.rows, Add) assert Znn.doit() == ZeroMatrix(2*n, n) assert isinstance(Znn.doit().rows, Mul) def test_OneMatrix(): n, m = symbols('n m', integer=True) A = MatrixSymbol('A', n, m) U = OneMatrix(n, m) assert U.shape == (n, m) assert isinstance(A + U, Add) assert U.transpose() == OneMatrix(m, n) assert U.conjugate() == U assert U.adjoint() == OneMatrix(m, n) assert re(U) == U assert im(U) == ZeroMatrix(n, m) assert OneMatrix(n, n) ** 0 == Identity(n) U = OneMatrix(n, n) assert U[1, 2] == 1 U = OneMatrix(2, 3) assert U.as_explicit() == ImmutableDenseMatrix.ones(2, 3) def test_OneMatrix_doit(): n = symbols('n', integer=True) Unn = OneMatrix(Add(n, n, evaluate=False), n) assert isinstance(Unn.rows, Add) assert Unn.doit() == OneMatrix(2 * n, n) assert isinstance(Unn.doit().rows, Mul) def test_OneMatrix_mul(): n, m, k = symbols('n m k', integer=True) w = MatrixSymbol('w', n, 1) assert OneMatrix(n, m) * OneMatrix(m, k) == OneMatrix(n, k) * m assert w * OneMatrix(1, 1) == w assert OneMatrix(1, 1) * w.T == w.T def test_Identity(): n, m = symbols('n m', integer=True) A = MatrixSymbol('A', n, m) i, j = symbols('i j') In = Identity(n) Im = Identity(m) assert A*Im == A assert In*A == A assert In.transpose() == In assert In.inverse() == In assert In.conjugate() == In assert In.adjoint() == In assert re(In) == In assert im(In) == ZeroMatrix(n, n) assert In[i, j] != 0 assert Sum(In[i, j], (i, 0, n-1), (j, 0, n-1)).subs(n,3).doit() == 3 assert Sum(Sum(In[i, j], (i, 0, n-1)), (j, 0, n-1)).subs(n,3).doit() == 3 # If range exceeds the limit `(0, n-1)`, do not remove `Piecewise`: expr = Sum(In[i, j], (i, 0, n-1)) assert expr.doit() == 1 expr = Sum(In[i, j], (i, 0, n-2)) assert expr.doit().dummy_eq( Piecewise( (1, (j >= 0) & (j <= n-2)), (0, True) ) ) expr = Sum(In[i, j], (i, 1, n-1)) assert expr.doit().dummy_eq( Piecewise( (1, (j >= 1) & (j <= n-1)), (0, True) ) ) assert Identity(3).as_explicit() == ImmutableDenseMatrix.eye(3) def test_Identity_doit(): n = symbols('n', integer=True) Inn = Identity(Add(n, n, evaluate=False)) assert isinstance(Inn.rows, Add) assert Inn.doit() == Identity(2*n) assert isinstance(Inn.doit().rows, Mul)
941baa582c127af53b24beba7a81d6af12f9808bda5a69268a70e8a859a9c8a0
from sympy.concrete.summations import Sum from sympy.core.exprtools import gcd_terms from sympy.core.function import (diff, expand) from sympy.core.relational import Eq from sympy.core.symbol import (Dummy, Symbol, Str) from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.matrices.dense import zeros from sympy.polys.polytools import factor from sympy.core import (S, symbols, Add, Mul, SympifyError, Rational, Function) from sympy.functions import sin, cos, tan, sqrt, cbrt, exp from sympy.simplify import simplify from sympy.matrices import (ImmutableMatrix, Inverse, MatAdd, MatMul, MatPow, Matrix, MatrixExpr, MatrixSymbol, SparseMatrix, Transpose, Adjoint, MatrixSet) from sympy.matrices.common import NonSquareMatrixError from sympy.matrices.expressions.determinant import Determinant, det from sympy.matrices.expressions.matexpr import MatrixElement from sympy.matrices.expressions.special import ZeroMatrix, Identity from sympy.testing.pytest import raises, XFAIL n, m, l, k, p = symbols('n m l k p', integer=True) x = symbols('x') A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', m, l) C = MatrixSymbol('C', n, n) D = MatrixSymbol('D', n, n) E = MatrixSymbol('E', m, n) w = MatrixSymbol('w', n, 1) def test_matrix_symbol_creation(): assert MatrixSymbol('A', 2, 2) assert MatrixSymbol('A', 0, 0) raises(ValueError, lambda: MatrixSymbol('A', -1, 2)) raises(ValueError, lambda: MatrixSymbol('A', 2.0, 2)) raises(ValueError, lambda: MatrixSymbol('A', 2j, 2)) raises(ValueError, lambda: MatrixSymbol('A', 2, -1)) raises(ValueError, lambda: MatrixSymbol('A', 2, 2.0)) raises(ValueError, lambda: MatrixSymbol('A', 2, 2j)) n = symbols('n') assert MatrixSymbol('A', n, n) n = symbols('n', integer=False) raises(ValueError, lambda: MatrixSymbol('A', n, n)) n = symbols('n', negative=True) raises(ValueError, lambda: MatrixSymbol('A', n, n)) def test_matexpr_properties(): assert A.shape == (n, m) assert (A * B).shape == (n, l) assert A[0, 1].indices == (0, 1) assert A[0, 0].symbol == A assert A[0, 0].symbol.name == 'A' def test_matexpr(): assert (x*A).shape == A.shape assert (x*A).__class__ == MatMul assert 2*A - A - A == ZeroMatrix(*A.shape) assert (A*B).shape == (n, l) def test_matexpr_subs(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', m, l) C = MatrixSymbol('C', m, l) assert A.subs(n, m).shape == (m, m) assert (A*B).subs(B, C) == A*C assert (A*B).subs(l, n).is_square W = MatrixSymbol("W", 3, 3) X = MatrixSymbol("X", 2, 2) Y = MatrixSymbol("Y", 1, 2) Z = MatrixSymbol("Z", n, 2) # no restrictions on Symbol replacement assert X.subs(X, Y) == Y # it might be better to just change the name y = Str('y') assert X.subs(Str("X"), y).args == (y, 2, 2) # it's ok to introduce a wider matrix assert X[1, 1].subs(X, W) == W[1, 1] # but for a given MatrixExpression, only change # name if indexing on the new shape is valid. # Here, X is 2,2; Y is 1,2 and Y[1, 1] is out # of range so an error is raised raises(IndexError, lambda: X[1, 1].subs(X, Y)) # here, [0, 1] is in range so the subs succeeds assert X[0, 1].subs(X, Y) == Y[0, 1] # and here the size of n will accept any index # in the first position assert W[2, 1].subs(W, Z) == Z[2, 1] # but not in the second position raises(IndexError, lambda: W[2, 2].subs(W, Z)) # any matrix should raise if invalid raises(IndexError, lambda: W[2, 2].subs(W, zeros(2))) A = SparseMatrix([[1, 2], [3, 4]]) B = Matrix([[1, 2], [3, 4]]) C, D = MatrixSymbol('C', 2, 2), MatrixSymbol('D', 2, 2) assert (C*D).subs({C: A, D: B}) == MatMul(A, B) def test_addition(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', n, m) assert isinstance(A + B, MatAdd) assert (A + B).shape == A.shape assert isinstance(A - A + 2*B, MatMul) raises(TypeError, lambda: A + 1) raises(TypeError, lambda: 5 + A) raises(TypeError, lambda: 5 - A) assert A + ZeroMatrix(n, m) - A == ZeroMatrix(n, m) raises(TypeError, lambda: ZeroMatrix(n, m) + S.Zero) def test_multiplication(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', m, l) C = MatrixSymbol('C', n, n) assert (2*A*B).shape == (n, l) assert (A*0*B) == ZeroMatrix(n, l) assert (2*A).shape == A.shape assert A * ZeroMatrix(m, m) * B == ZeroMatrix(n, l) assert C * Identity(n) * C.I == Identity(n) assert B/2 == S.Half*B raises(NotImplementedError, lambda: 2/B) A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, n) assert Identity(n) * (A + B) == A + B assert A**2*A == A**3 assert A**2*(A.I)**3 == A.I assert A**3*(A.I)**2 == A def test_MatPow(): A = MatrixSymbol('A', n, n) AA = MatPow(A, 2) assert AA.exp == 2 assert AA.base == A assert (A**n).exp == n assert A**0 == Identity(n) assert A**1 == A assert A**2 == AA assert A**-1 == Inverse(A) assert (A**-1)**-1 == A assert (A**2)**3 == A**6 assert A**S.Half == sqrt(A) assert A**Rational(1, 3) == cbrt(A) raises(NonSquareMatrixError, lambda: MatrixSymbol('B', 3, 2)**2) def test_MatrixSymbol(): n, m, t = symbols('n,m,t') X = MatrixSymbol('X', n, m) assert X.shape == (n, m) raises(TypeError, lambda: MatrixSymbol('X', n, m)(t)) # issue 5855 assert X.doit() == X def test_dense_conversion(): X = MatrixSymbol('X', 2, 2) assert ImmutableMatrix(X) == ImmutableMatrix(2, 2, lambda i, j: X[i, j]) assert Matrix(X) == Matrix(2, 2, lambda i, j: X[i, j]) def test_free_symbols(): assert (C*D).free_symbols == {C, D} def test_zero_matmul(): assert isinstance(S.Zero * MatrixSymbol('X', 2, 2), MatrixExpr) def test_matadd_simplify(): A = MatrixSymbol('A', 1, 1) assert simplify(MatAdd(A, ImmutableMatrix([[sin(x)**2 + cos(x)**2]]))) == \ MatAdd(A, Matrix([[1]])) def test_matmul_simplify(): A = MatrixSymbol('A', 1, 1) assert simplify(MatMul(A, ImmutableMatrix([[sin(x)**2 + cos(x)**2]]))) == \ MatMul(A, Matrix([[1]])) def test_invariants(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', m, l) X = MatrixSymbol('X', n, n) objs = [Identity(n), ZeroMatrix(m, n), A, MatMul(A, B), MatAdd(A, A), Transpose(A), Adjoint(A), Inverse(X), MatPow(X, 2), MatPow(X, -1), MatPow(X, 0)] for obj in objs: assert obj == obj.__class__(*obj.args) def test_matexpr_indexing(): A = MatrixSymbol('A', n, m) A[1, 2] A[l, k] A[l + 1, k + 1] A = MatrixSymbol('A', 2, 1) for i in range(-2, 2): for j in range(-1, 1): A[i, j] def test_single_indexing(): A = MatrixSymbol('A', 2, 3) assert A[1] == A[0, 1] assert A[int(1)] == A[0, 1] assert A[3] == A[1, 0] assert list(A[:2, :2]) == [A[0, 0], A[0, 1], A[1, 0], A[1, 1]] raises(IndexError, lambda: A[6]) raises(IndexError, lambda: A[n]) B = MatrixSymbol('B', n, m) raises(IndexError, lambda: B[1]) B = MatrixSymbol('B', n, 3) assert B[3] == B[1, 0] def test_MatrixElement_commutative(): assert A[0, 1]*A[1, 0] == A[1, 0]*A[0, 1] def test_MatrixSymbol_determinant(): A = MatrixSymbol('A', 4, 4) assert A.as_explicit().det() == A[0, 0]*A[1, 1]*A[2, 2]*A[3, 3] - \ A[0, 0]*A[1, 1]*A[2, 3]*A[3, 2] - A[0, 0]*A[1, 2]*A[2, 1]*A[3, 3] + \ A[0, 0]*A[1, 2]*A[2, 3]*A[3, 1] + A[0, 0]*A[1, 3]*A[2, 1]*A[3, 2] - \ A[0, 0]*A[1, 3]*A[2, 2]*A[3, 1] - A[0, 1]*A[1, 0]*A[2, 2]*A[3, 3] + \ A[0, 1]*A[1, 0]*A[2, 3]*A[3, 2] + A[0, 1]*A[1, 2]*A[2, 0]*A[3, 3] - \ A[0, 1]*A[1, 2]*A[2, 3]*A[3, 0] - A[0, 1]*A[1, 3]*A[2, 0]*A[3, 2] + \ A[0, 1]*A[1, 3]*A[2, 2]*A[3, 0] + A[0, 2]*A[1, 0]*A[2, 1]*A[3, 3] - \ A[0, 2]*A[1, 0]*A[2, 3]*A[3, 1] - A[0, 2]*A[1, 1]*A[2, 0]*A[3, 3] + \ A[0, 2]*A[1, 1]*A[2, 3]*A[3, 0] + A[0, 2]*A[1, 3]*A[2, 0]*A[3, 1] - \ A[0, 2]*A[1, 3]*A[2, 1]*A[3, 0] - A[0, 3]*A[1, 0]*A[2, 1]*A[3, 2] + \ A[0, 3]*A[1, 0]*A[2, 2]*A[3, 1] + A[0, 3]*A[1, 1]*A[2, 0]*A[3, 2] - \ A[0, 3]*A[1, 1]*A[2, 2]*A[3, 0] - A[0, 3]*A[1, 2]*A[2, 0]*A[3, 1] + \ A[0, 3]*A[1, 2]*A[2, 1]*A[3, 0] B = MatrixSymbol('B', 4, 4) assert Determinant(A + B).doit() == det(A + B) == (A + B).det() def test_MatrixElement_diff(): assert (A[3, 0]*A[0, 0]).diff(A[0, 0]) == A[3, 0] def test_MatrixElement_doit(): u = MatrixSymbol('u', 2, 1) v = ImmutableMatrix([3, 5]) assert u[0, 0].subs(u, v).doit() == v[0, 0] def test_identity_powers(): M = Identity(n) assert MatPow(M, 3).doit() == M**3 assert M**n == M assert MatPow(M, 0).doit() == M**2 assert M**-2 == M assert MatPow(M, -2).doit() == M**0 N = Identity(3) assert MatPow(N, 2).doit() == N**n assert MatPow(N, 3).doit() == N assert MatPow(N, -2).doit() == N**4 assert MatPow(N, 2).doit() == N**0 def test_Zero_power(): z1 = ZeroMatrix(n, n) assert z1**4 == z1 raises(ValueError, lambda:z1**-2) assert z1**0 == Identity(n) assert MatPow(z1, 2).doit() == z1**2 raises(ValueError, lambda:MatPow(z1, -2).doit()) z2 = ZeroMatrix(3, 3) assert MatPow(z2, 4).doit() == z2**4 raises(ValueError, lambda:z2**-3) assert z2**3 == MatPow(z2, 3).doit() assert z2**0 == Identity(3) raises(ValueError, lambda:MatPow(z2, -1).doit()) def test_matrixelement_diff(): dexpr = diff((D*w)[k,0], w[p,0]) assert w[k, p].diff(w[k, p]) == 1 assert w[k, p].diff(w[0, 0]) == KroneckerDelta(0, k, (0, n-1))*KroneckerDelta(0, p, (0, 0)) _i_1 = Dummy("_i_1") assert dexpr.dummy_eq(Sum(KroneckerDelta(_i_1, p, (0, n-1))*D[k, _i_1], (_i_1, 0, n - 1))) assert dexpr.doit() == D[k, p] def test_MatrixElement_with_values(): x, y, z, w = symbols("x y z w") M = Matrix([[x, y], [z, w]]) i, j = symbols("i, j") Mij = M[i, j] assert isinstance(Mij, MatrixElement) Ms = SparseMatrix([[2, 3], [4, 5]]) msij = Ms[i, j] assert isinstance(msij, MatrixElement) for oi, oj in [(0, 0), (0, 1), (1, 0), (1, 1)]: assert Mij.subs({i: oi, j: oj}) == M[oi, oj] assert msij.subs({i: oi, j: oj}) == Ms[oi, oj] A = MatrixSymbol("A", 2, 2) assert A[0, 0].subs(A, M) == x assert A[i, j].subs(A, M) == M[i, j] assert M[i, j].subs(M, A) == A[i, j] assert isinstance(M[3*i - 2, j], MatrixElement) assert M[3*i - 2, j].subs({i: 1, j: 0}) == M[1, 0] assert isinstance(M[i, 0], MatrixElement) assert M[i, 0].subs(i, 0) == M[0, 0] assert M[0, i].subs(i, 1) == M[0, 1] assert M[i, j].diff(x) == Matrix([[1, 0], [0, 0]])[i, j] raises(ValueError, lambda: M[i, 2]) raises(ValueError, lambda: M[i, -1]) raises(ValueError, lambda: M[2, i]) raises(ValueError, lambda: M[-1, i]) def test_inv(): B = MatrixSymbol('B', 3, 3) assert B.inv() == B**-1 # https://github.com/sympy/sympy/issues/19162 X = MatrixSymbol('X', 1, 1).as_explicit() assert X.inv() == Matrix([[1/X[0, 0]]]) X = MatrixSymbol('X', 2, 2).as_explicit() detX = X[0, 0]*X[1, 1] - X[0, 1]*X[1, 0] invX = Matrix([[ X[1, 1], -X[0, 1]], [-X[1, 0], X[0, 0]]]) / detX assert X.inv() == invX @XFAIL def test_factor_expand(): A = MatrixSymbol("A", n, n) B = MatrixSymbol("B", n, n) expr1 = (A + B)*(C + D) expr2 = A*C + B*C + A*D + B*D assert expr1 != expr2 assert expand(expr1) == expr2 assert factor(expr2) == expr1 expr = B**(-1)*(A**(-1)*B**(-1) - A**(-1)*C*B**(-1))**(-1)*A**(-1) I = Identity(n) # Ideally we get the first, but we at least don't want a wrong answer assert factor(expr) in [I - C, B**-1*(A**-1*(I - C)*B**-1)**-1*A**-1] def test_issue_2749(): A = MatrixSymbol("A", 5, 2) assert (A.T * A).I.as_explicit() == Matrix([[(A.T * A).I[0, 0], (A.T * A).I[0, 1]], \ [(A.T * A).I[1, 0], (A.T * A).I[1, 1]]]) def test_issue_2750(): x = MatrixSymbol('x', 1, 1) assert (x.T*x).as_explicit()**-1 == Matrix([[x[0, 0]**(-2)]]) def test_issue_7842(): A = MatrixSymbol('A', 3, 1) B = MatrixSymbol('B', 2, 1) assert Eq(A, B) == False assert Eq(A[1,0], B[1, 0]).func is Eq A = ZeroMatrix(2, 3) B = ZeroMatrix(2, 3) assert Eq(A, B) == True def test_issue_21195(): t = symbols('t') x = Function('x')(t) dx = x.diff(t) exp1 = cos(x) + cos(x)*dx exp2 = sin(x) + tan(x)*(dx.diff(t)) exp3 = sin(x)*sin(t)*(dx.diff(t)).diff(t) A = Matrix([[exp1], [exp2], [exp3]]) B = Matrix([[exp1.diff(x)], [exp2.diff(x)], [exp3.diff(x)]]) assert A.diff(x) == B def test_MatMul_postprocessor(): z = zeros(2) z1 = ZeroMatrix(2, 2) assert Mul(0, z) == Mul(z, 0) in [z, z1] M = Matrix([[1, 2], [3, 4]]) Mx = Matrix([[x, 2*x], [3*x, 4*x]]) assert Mul(x, M) == Mul(M, x) == Mx A = MatrixSymbol("A", 2, 2) assert Mul(A, M) == MatMul(A, M) assert Mul(M, A) == MatMul(M, A) # Scalars should be absorbed into constant matrices a = Mul(x, M, A) b = Mul(M, x, A) c = Mul(M, A, x) assert a == b == c == MatMul(Mx, A) a = Mul(x, A, M) b = Mul(A, x, M) c = Mul(A, M, x) assert a == b == c == MatMul(A, Mx) assert Mul(M, M) == M**2 assert Mul(A, M, M) == MatMul(A, M**2) assert Mul(M, M, A) == MatMul(M**2, A) assert Mul(M, A, M) == MatMul(M, A, M) assert Mul(A, x, M, M, x) == MatMul(A, Mx**2) @XFAIL def test_MatAdd_postprocessor_xfail(): # This is difficult to get working because of the way that Add processes # its args. z = zeros(2) assert Add(z, S.NaN) == Add(S.NaN, z) def test_MatAdd_postprocessor(): # Some of these are nonsensical, but we do not raise errors for Add # because that breaks algorithms that want to replace matrices with dummy # symbols. z = zeros(2) assert Add(0, z) == Add(z, 0) == z a = Add(S.Infinity, z) assert a == Add(z, S.Infinity) assert isinstance(a, Add) assert a.args == (S.Infinity, z) a = Add(S.ComplexInfinity, z) assert a == Add(z, S.ComplexInfinity) assert isinstance(a, Add) assert a.args == (S.ComplexInfinity, z) a = Add(z, S.NaN) # assert a == Add(S.NaN, z) # See the XFAIL above assert isinstance(a, Add) assert a.args == (S.NaN, z) M = Matrix([[1, 2], [3, 4]]) a = Add(x, M) assert a == Add(M, x) assert isinstance(a, Add) assert a.args == (x, M) A = MatrixSymbol("A", 2, 2) assert Add(A, M) == Add(M, A) == A + M # Scalars should be absorbed into constant matrices (producing an error) a = Add(x, M, A) assert a == Add(M, x, A) == Add(M, A, x) == Add(x, A, M) == Add(A, x, M) == Add(A, M, x) assert isinstance(a, Add) assert a.args == (x, A + M) assert Add(M, M) == 2*M assert Add(M, A, M) == Add(M, M, A) == Add(A, M, M) == A + 2*M a = Add(A, x, M, M, x) assert isinstance(a, Add) assert a.args == (2*x, A + 2*M) def test_simplify_matrix_expressions(): # Various simplification functions assert type(gcd_terms(C*D + D*C)) == MatAdd a = gcd_terms(2*C*D + 4*D*C) assert type(a) == MatAdd assert a.args == (2*C*D, 4*D*C) def test_exp(): A = MatrixSymbol('A', 2, 2) B = MatrixSymbol('B', 2, 2) expr1 = exp(A)*exp(B) expr2 = exp(B)*exp(A) assert expr1 != expr2 assert expr1 - expr2 != 0 assert not isinstance(expr1, exp) assert not isinstance(expr2, exp) def test_invalid_args(): raises(SympifyError, lambda: MatrixSymbol(1, 2, 'A')) def test_matrixsymbol_from_symbol(): # The label should be preserved during doit and subs A_label = Symbol('A', complex=True) A = MatrixSymbol(A_label, 2, 2) A_1 = A.doit() A_2 = A.subs(2, 3) assert A_1.args == A.args assert A_2.args[0] == A.args[0] def test_as_explicit(): Z = MatrixSymbol('Z', 2, 3) assert Z.as_explicit() == ImmutableMatrix([ [Z[0, 0], Z[0, 1], Z[0, 2]], [Z[1, 0], Z[1, 1], Z[1, 2]], ]) raises(ValueError, lambda: A.as_explicit()) def test_MatrixSet(): M = MatrixSet(2, 2, set=S.Reals) assert M.shape == (2, 2) assert M.set == S.Reals X = Matrix([[1, 2], [3, 4]]) assert X in M X = ZeroMatrix(2, 2) assert X in M raises(TypeError, lambda: A in M) raises(TypeError, lambda: 1 in M) M = MatrixSet(n, m, set=S.Reals) assert A in M raises(TypeError, lambda: C in M) raises(TypeError, lambda: X in M) M = MatrixSet(2, 2, set={1, 2, 3}) X = Matrix([[1, 2], [3, 4]]) Y = Matrix([[1, 2]]) assert (X in M) == S.false assert (Y in M) == S.false raises(ValueError, lambda: MatrixSet(2, -2, S.Reals)) raises(ValueError, lambda: MatrixSet(2.4, -1, S.Reals)) raises(TypeError, lambda: MatrixSet(2, 2, (1, 2, 3))) def test_matrixsymbol_solving(): A = MatrixSymbol('A', 2, 2) B = MatrixSymbol('B', 2, 2) Z = ZeroMatrix(2, 2) assert -(-A + B) - A + B == Z assert (-(-A + B) - A + B).simplify() == Z assert (-(-A + B) - A + B).expand() == Z assert (-(-A + B) - A + B - Z).simplify() == Z assert (-(-A + B) - A + B - Z).expand() == Z assert (A*(A + B) + B*(A.T + B.T)).expand() == A**2 + A*B + B*A.T + B*B.T
9b14c96a807865ee74964fb64e0568a66aeb6ee41b12a52c6707372b51fcc3e4
from sympy.core.symbol import symbols, Dummy from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction from sympy.core.function import Lambda from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.trigonometric import sin from sympy.matrices.dense import Matrix from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.matmul import MatMul from sympy.simplify.simplify import simplify X = MatrixSymbol("X", 3, 3) Y = MatrixSymbol("Y", 3, 3) k = symbols("k") Xk = MatrixSymbol("X", k, k) Xd = X.as_explicit() x, y, z, t = symbols("x y z t") def test_applyfunc_matrix(): x = Dummy('x') double = Lambda(x, x**2) expr = ElementwiseApplyFunction(double, Xd) assert isinstance(expr, ElementwiseApplyFunction) assert expr.doit() == Xd.applyfunc(lambda x: x**2) assert expr.shape == (3, 3) assert expr.func(*expr.args) == expr assert simplify(expr) == expr assert expr[0, 0] == double(Xd[0, 0]) expr = ElementwiseApplyFunction(double, X) assert isinstance(expr, ElementwiseApplyFunction) assert isinstance(expr.doit(), ElementwiseApplyFunction) assert expr == X.applyfunc(double) assert expr.func(*expr.args) == expr expr = ElementwiseApplyFunction(exp, X*Y) assert expr.expr == X*Y assert expr.function.dummy_eq(Lambda(x, exp(x))) assert expr.dummy_eq((X*Y).applyfunc(exp)) assert expr.func(*expr.args) == expr assert isinstance(X*expr, MatMul) assert (X*expr).shape == (3, 3) Z = MatrixSymbol("Z", 2, 3) assert (Z*expr).shape == (2, 3) expr = ElementwiseApplyFunction(exp, Z.T)*ElementwiseApplyFunction(exp, Z) assert expr.shape == (3, 3) expr = ElementwiseApplyFunction(exp, Z)*ElementwiseApplyFunction(exp, Z.T) assert expr.shape == (2, 2) M = Matrix([[x, y], [z, t]]) expr = ElementwiseApplyFunction(sin, M) assert isinstance(expr, ElementwiseApplyFunction) assert expr.function.dummy_eq(Lambda(x, sin(x))) assert expr.expr == M assert expr.doit() == M.applyfunc(sin) assert expr.doit() == Matrix([[sin(x), sin(y)], [sin(z), sin(t)]]) assert expr.func(*expr.args) == expr expr = ElementwiseApplyFunction(double, Xk) assert expr.doit() == expr assert expr.subs(k, 2).shape == (2, 2) assert (expr*expr).shape == (k, k) M = MatrixSymbol("M", k, t) expr2 = M.T*expr*M assert isinstance(expr2, MatMul) assert expr2.args[1] == expr assert expr2.shape == (t, t) expr3 = expr*M assert expr3.shape == (k, t) expr1 = ElementwiseApplyFunction(lambda x: x+1, Xk) expr2 = ElementwiseApplyFunction(lambda x: x, Xk) assert expr1 != expr2 def test_applyfunc_entry(): af = X.applyfunc(sin) assert af[0, 0] == sin(X[0, 0]) af = Xd.applyfunc(sin) assert af[0, 0] == sin(X[0, 0]) def test_applyfunc_as_explicit(): af = X.applyfunc(sin) assert af.as_explicit() == Matrix([ [sin(X[0, 0]), sin(X[0, 1]), sin(X[0, 2])], [sin(X[1, 0]), sin(X[1, 1]), sin(X[1, 2])], [sin(X[2, 0]), sin(X[2, 1]), sin(X[2, 2])], ]) def test_applyfunc_transpose(): af = Xk.applyfunc(sin) assert af.T.dummy_eq(Xk.T.applyfunc(sin)) def test_applyfunc_shape_11_matrices(): M = MatrixSymbol("M", 1, 1) double = Lambda(x, x*2) expr = M.applyfunc(sin) assert isinstance(expr, ElementwiseApplyFunction) expr = M.applyfunc(double) assert isinstance(expr, MatMul) assert expr == 2*M
df7522fef5d904947580c8ab6fc739c470e7c768e95635a856962656e650a098
from sympy.core import symbols, S from sympy.matrices.expressions import MatrixSymbol, Inverse, MatPow, ZeroMatrix, OneMatrix from sympy.matrices.common import NonInvertibleMatrixError, NonSquareMatrixError from sympy.matrices import eye, Identity from sympy.testing.pytest import raises from sympy.assumptions.ask import Q from sympy.assumptions.refine import refine n, m, l = symbols('n m l', integer=True) A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', m, l) C = MatrixSymbol('C', n, n) D = MatrixSymbol('D', n, n) E = MatrixSymbol('E', m, n) def test_inverse(): assert Inverse(C).args == (C, S.NegativeOne) assert Inverse(C).shape == (n, n) assert Inverse(A*E).shape == (n, n) assert Inverse(E*A).shape == (m, m) assert Inverse(C).inverse() == C assert Inverse(Inverse(C)).doit() == C assert isinstance(Inverse(Inverse(C)), Inverse) assert Inverse(*Inverse(E*A).args) == Inverse(E*A) assert C.inverse().inverse() == C assert C.inverse()*C == Identity(C.rows) assert Identity(n).inverse() == Identity(n) assert (3*Identity(n)).inverse() == Identity(n)/3 # Simplifies Muls if possible (i.e. submatrices are square) assert (C*D).inverse() == D.I*C.I # But still works when not possible assert isinstance((A*E).inverse(), Inverse) assert Inverse(C*D).doit(inv_expand=False) == Inverse(C*D) assert Inverse(eye(3)).doit() == eye(3) assert Inverse(eye(3)).doit(deep=False) == eye(3) assert OneMatrix(1, 1).I == Identity(1) assert isinstance(OneMatrix(n, n).I, Inverse) def test_inverse_non_invertible(): raises(NonInvertibleMatrixError, lambda: ZeroMatrix(n, n).I) raises(NonInvertibleMatrixError, lambda: OneMatrix(2, 2).I) def test_refine(): assert refine(C.I, Q.orthogonal(C)) == C.T def test_inverse_matpow_canonicalization(): A = MatrixSymbol('A', 3, 3) assert Inverse(MatPow(A, 3)).doit() == MatPow(Inverse(A), 3).doit() def test_nonsquare_error(): A = MatrixSymbol('A', 3, 4) raises(NonSquareMatrixError, lambda: Inverse(A))
5837a53fb950f4aaac6a538e9561da66adfc9d38a391150c01731c02f538d923
from sympy.matrices.dense import Matrix, eye from sympy.matrices.common import ShapeError from sympy.matrices.expressions.matadd import MatAdd from sympy.matrices.expressions.special import Identity, OneMatrix, ZeroMatrix from sympy.core import symbols from sympy.testing.pytest import raises, warns_deprecated_sympy from sympy.matrices import MatrixSymbol from sympy.matrices.expressions import (HadamardProduct, hadamard_product, HadamardPower, hadamard_power) n, m, k = symbols('n,m,k') Z = MatrixSymbol('Z', n, n) A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', n, m) C = MatrixSymbol('C', m, k) def test_HadamardProduct(): assert HadamardProduct(A, B, A).shape == A.shape raises(TypeError, lambda: HadamardProduct(A, n)) raises(TypeError, lambda: HadamardProduct(A, 1)) assert HadamardProduct(A, 2*B, -A)[1, 1] == \ -2 * A[1, 1] * B[1, 1] * A[1, 1] mix = HadamardProduct(Z*A, B)*C assert mix.shape == (n, k) assert set(HadamardProduct(A, B, A).T.args) == {A.T, A.T, B.T} def test_HadamardProduct_isnt_commutative(): assert HadamardProduct(A, B) != HadamardProduct(B, A) def test_mixed_indexing(): X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) Z = MatrixSymbol('Z', 2, 2) assert (X*HadamardProduct(Y, Z))[0, 0] == \ X[0, 0]*Y[0, 0]*Z[0, 0] + X[0, 1]*Y[1, 0]*Z[1, 0] def test_canonicalize(): X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) with warns_deprecated_sympy(): expr = HadamardProduct(X, check=False) assert isinstance(expr, HadamardProduct) expr2 = expr.doit() # unpack is called assert isinstance(expr2, MatrixSymbol) Z = ZeroMatrix(2, 2) U = OneMatrix(2, 2) assert HadamardProduct(Z, X).doit() == Z assert HadamardProduct(U, X, X, U).doit() == HadamardPower(X, 2) assert HadamardProduct(X, U, Y).doit() == HadamardProduct(X, Y) assert HadamardProduct(X, Z, U, Y).doit() == Z def test_hadamard(): m, n, p = symbols('m, n, p', integer=True) A = MatrixSymbol('A', m, n) B = MatrixSymbol('B', m, n) X = MatrixSymbol('X', m, m) I = Identity(m) raises(TypeError, lambda: hadamard_product()) assert hadamard_product(A) == A assert isinstance(hadamard_product(A, B), HadamardProduct) assert hadamard_product(A, B).doit() == hadamard_product(A, B) assert hadamard_product(X, I) == HadamardProduct(I, X) assert isinstance(hadamard_product(X, I), HadamardProduct) a = MatrixSymbol("a", k, 1) expr = MatAdd(ZeroMatrix(k, 1), OneMatrix(k, 1)) expr = HadamardProduct(expr, a) assert expr.doit() == a raises(ValueError, lambda: HadamardProduct()) def test_hadamard_product_with_explicit_mat(): A = MatrixSymbol("A", 3, 3).as_explicit() B = MatrixSymbol("B", 3, 3).as_explicit() X = MatrixSymbol("X", 3, 3) expr = hadamard_product(A, B) ret = Matrix([i*j for i, j in zip(A, B)]).reshape(3, 3) assert expr == ret expr = hadamard_product(A, X, B) assert expr == HadamardProduct(ret, X) expr = hadamard_product(eye(3), A) assert expr == Matrix([[A[0, 0], 0, 0], [0, A[1, 1], 0], [0, 0, A[2, 2]]]) expr = hadamard_product(eye(3), eye(3)) assert expr == eye(3) def test_hadamard_power(): m, n, p = symbols('m, n, p', integer=True) A = MatrixSymbol('A', m, n) assert hadamard_power(A, 1) == A assert isinstance(hadamard_power(A, 2), HadamardPower) assert hadamard_power(A, n).T == hadamard_power(A.T, n) assert hadamard_power(A, n)[0, 0] == A[0, 0]**n assert hadamard_power(m, n) == m**n raises(ValueError, lambda: hadamard_power(A, A)) def test_hadamard_power_explicit(): A = MatrixSymbol('A', 2, 2) B = MatrixSymbol('B', 2, 2) a, b = symbols('a b') assert HadamardPower(a, b) == a**b assert HadamardPower(a, B).as_explicit() == \ Matrix([ [a**B[0, 0], a**B[0, 1]], [a**B[1, 0], a**B[1, 1]]]) assert HadamardPower(A, b).as_explicit() == \ Matrix([ [A[0, 0]**b, A[0, 1]**b], [A[1, 0]**b, A[1, 1]**b]]) assert HadamardPower(A, B).as_explicit() == \ Matrix([ [A[0, 0]**B[0, 0], A[0, 1]**B[0, 1]], [A[1, 0]**B[1, 0], A[1, 1]**B[1, 1]]]) def test_shape_error(): A = MatrixSymbol('A', 2, 3) B = MatrixSymbol('B', 3, 3) raises(ShapeError, lambda: HadamardProduct(A, B)) raises(ShapeError, lambda: HadamardPower(A, B)) A = MatrixSymbol('A', 3, 2) raises(ShapeError, lambda: HadamardProduct(A, B)) raises(ShapeError, lambda: HadamardPower(A, B))
66f03e06b02446d32b01494f02d9df578928cd059504653ca2850bcce94ba04c
""" 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, 8): raise ImportError("Python version 3.8 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__ from sympy.core.cache import lazy_function 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, bottom_up, use, postorder_traversal, default_sort_key, ordered) 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, round_two, prime_decomp, prime_valuation, 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, EXRAW, construct_domain, swinnerton_dyer_poly, cyclotomic_poly, symmetric_poly, random_poly, interpolating_poly, jacobi_poly, chebyshevt_poly, chebyshevu_poly, hermite_poly, hermite_prob_poly, legendre_poly, laguerre_poly, apart, apart_list, assemble_partfrac_list, Options, ring, xring, vring, sring, field, xfield, vfield, sfield) from .series import (Order, O, limit, Limit, gruntz, series, approximants, residue, EmptySequence, SeqPer, SeqFormula, sequence, SeqAdd, SeqMul, fourier_series, fps, difference_delta, limit_seq) from .functions import (factorial, factorial2, rf, ff, binomial, RisingFactorial, FallingFactorial, subfactorial, carmichael, fibonacci, lucas, motzkin, tribonacci, harmonic, bernoulli, bell, euler, catalan, genocchi, andre, partition, sqrt, root, Min, Max, Id, real_root, Rem, 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, piecewise_exclusive, 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, hermite_prob, 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, riemann_xi, betainc, betainc_regularized) 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, nsimplify, FU, fu, sqrtdenest, cse, 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, Complexes, 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) from .matrices import (ShapeError, NonSquareMatrixError, GramSchmidt, casoratian, diag, eye, hessian, jordan_cell, list2numpy, matrix2numpy, matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2, rot_axis3, symarray, wronskian, zeros, MutableDenseMatrix, DeferredVector, MatrixBase, Matrix, MutableMatrix, MutableSparseMatrix, banded, ImmutableDenseMatrix, ImmutableSparseMatrix, ImmutableMatrix, SparseMatrix, MatrixSlice, BlockDiagMatrix, BlockMatrix, FunctionMatrix, Identity, Inverse, MatAdd, MatMul, MatPow, MatrixExpr, MatrixSymbol, Trace, Transpose, ZeroMatrix, OneMatrix, blockcut, block_collapse, matrix_symbols, Adjoint, hadamard_product, HadamardProduct, HadamardPower, Determinant, det, diagonalize_vector, DiagMatrix, DiagonalMatrix, DiagonalOf, trace, DotProduct, kronecker_product, KroneckerProduct, PermutationMatrix, MatrixPermute, Permanent, per, rot_ccw_axis1, rot_ccw_axis2, rot_ccw_axis3, rot_givens) 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, prefixes, postfixes, sift, topological_sort, unflatten, has_dups, has_variety, reshape, rotations, filldedent, lambdify, threaded, xthreaded, public, memoize_property, timed) from .integrals import (integrate, Integral, line_integrate, mellin_transform, inverse_mellin_transform, MellinTransform, InverseMellinTransform, laplace_transform, inverse_laplace_transform, LaplaceTransform, InverseLaplaceTransform, fourier_transform, inverse_fourier_transform, FourierTransform, InverseFourierTransform, sine_transform, inverse_sine_transform, SineTransform, InverseSineTransform, cosine_transform, inverse_cosine_transform, CosineTransform, InverseCosineTransform, hankel_transform, inverse_hankel_transform, HankelTransform, InverseHankelTransform, singularityintegrate) from .tensor import (IndexedBase, Idx, Indexed, get_contraction_structure, get_indices, shape, MutableDenseNDimArray, ImmutableDenseNDimArray, MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray, tensorproduct, tensorcontraction, tensordiagonal, derive_by_array, permutedims, Array, DenseNDimArray, SparseNDimArray) from .parsing import parse_expr from .calculus import (euler_equations, singularities, is_increasing, is_strictly_increasing, is_decreasing, is_strictly_decreasing, is_monotonic, finite_diff_weights, apply_finite_diff, 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, smtlib_code, 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) test = lazy_function('sympy.testing.runtests', 'test') doctest = lazy_function('sympy.testing.runtests', '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, interactive_traversal evalf._create_evalf_table() __all__ = [ '__version__', # 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', 'bottom_up', 'use', 'postorder_traversal', 'default_sort_key', 'ordered', # 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', 'round_two', 'prime_decomp', 'prime_valuation', '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', 'EXRAW', 'construct_domain', 'swinnerton_dyer_poly', 'cyclotomic_poly', 'symmetric_poly', 'random_poly', 'interpolating_poly', 'jacobi_poly', 'chebyshevt_poly', 'chebyshevu_poly', 'hermite_poly', 'hermite_prob_poly', 'legendre_poly', 'laguerre_poly', 'apart', 'apart_list', 'assemble_partfrac_list', 'Options', 'ring', 'xring', 'vring', 'sring', 'field', 'xfield', 'vfield', 'sfield', # sympy.series 'Order', 'O', 'limit', 'Limit', 'gruntz', 'series', 'approximants', 'residue', 'EmptySequence', 'SeqPer', 'SeqFormula', 'sequence', 'SeqAdd', 'SeqMul', 'fourier_series', 'fps', 'difference_delta', 'limit_seq', # sympy.functions 'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial', 'FallingFactorial', 'subfactorial', 'carmichael', 'fibonacci', 'lucas', 'motzkin', 'tribonacci', 'harmonic', 'bernoulli', 'bell', 'euler', 'catalan', 'genocchi', 'andre', 'partition', 'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root', 'Rem', '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', 'piecewise_exclusive', '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', 'hermite_prob', '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', 'riemann_xi','betainc', 'betainc_regularized', # 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', 'nsimplify', 'FU', 'fu', 'sqrtdenest', 'cse', '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', 'Naturals', 'Naturals0', 'UniversalSet', 'Integers', 'Rationals', 'Complexes', # 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', # sympy.matrices 'ShapeError', 'NonSquareMatrixError', 'GramSchmidt', 'casoratian', 'diag', 'eye', 'hessian', 'jordan_cell', 'list2numpy', 'matrix2numpy', 'matrix_multiply_elementwise', 'ones', 'randMatrix', 'rot_axis1', 'rot_axis2', 'rot_axis3', 'symarray', 'wronskian', 'zeros', 'MutableDenseMatrix', 'DeferredVector', 'MatrixBase', 'Matrix', 'MutableMatrix', 'MutableSparseMatrix', 'banded', 'ImmutableDenseMatrix', 'ImmutableSparseMatrix', 'ImmutableMatrix', 'SparseMatrix', 'MatrixSlice', 'BlockDiagMatrix', 'BlockMatrix', 'FunctionMatrix', 'Identity', 'Inverse', 'MatAdd', 'MatMul', 'MatPow', 'MatrixExpr', 'MatrixSymbol', 'Trace', 'Transpose', 'ZeroMatrix', 'OneMatrix', 'blockcut', 'block_collapse', 'matrix_symbols', 'Adjoint', 'hadamard_product', 'HadamardProduct', 'HadamardPower', 'Determinant', 'det', 'diagonalize_vector', 'DiagMatrix', 'DiagonalMatrix', 'DiagonalOf', 'trace', 'DotProduct', 'kronecker_product', 'KroneckerProduct', 'PermutationMatrix', 'MatrixPermute', 'Permanent', 'per', 'rot_ccw_axis1', 'rot_ccw_axis2', 'rot_ccw_axis3', 'rot_givens', # 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', 'prefixes', 'postfixes', 'sift', 'topological_sort', 'unflatten', 'has_dups', 'has_variety', 'reshape', 'rotations', 'filldedent', 'lambdify', 'threaded', 'xthreaded', 'public', 'memoize_property', 'timed', # sympy.integrals 'integrate', 'Integral', 'line_integrate', 'mellin_transform', 'inverse_mellin_transform', 'MellinTransform', 'InverseMellinTransform', 'laplace_transform', 'inverse_laplace_transform', 'LaplaceTransform', 'InverseLaplaceTransform', 'fourier_transform', 'inverse_fourier_transform', 'FourierTransform', 'InverseFourierTransform', 'sine_transform', 'inverse_sine_transform', 'SineTransform', 'InverseSineTransform', 'cosine_transform', 'inverse_cosine_transform', 'CosineTransform', 'InverseCosineTransform', 'hankel_transform', 'inverse_hankel_transform', 'HankelTransform', 'InverseHankelTransform', 'singularityintegrate', # sympy.tensor 'IndexedBase', 'Idx', 'Indexed', 'get_contraction_structure', 'get_indices', 'shape', 'MutableDenseNDimArray', 'ImmutableDenseNDimArray', 'MutableSparseNDimArray', 'ImmutableSparseNDimArray', 'NDimArray', 'tensorproduct', 'tensorcontraction', 'tensordiagonal', 'derive_by_array', 'permutedims', 'Array', 'DenseNDimArray', 'SparseNDimArray', # sympy.parsing 'parse_expr', # sympy.calculus 'euler_equations', 'singularities', 'is_increasing', 'is_strictly_increasing', 'is_decreasing', 'is_strictly_decreasing', 'is_monotonic', 'finite_diff_weights', 'apply_finite_diff', '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', 'smtlib_code', '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', 'interactive_traversal', # sympy.testing 'test', 'doctest', ] #===========================================================================# # # # 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', 'discrete', 'external', 'functions', 'geometry', 'interactive', 'multipledispatch', 'ntheory', 'parsing', 'plotting', 'polys', 'printing', 'release', 'strategies', 'tensor', 'utilities', ))
6c9ca5fd96bb782eda14e8219ee8f78b735a634dfa902535b0cab521307a2ea0
from sympy.ntheory import sieve, isprime from sympy.core.numbers import mod_inverse from sympy.core.power import integer_log from sympy.utilities.misc import as_int import random rgen = random.Random() #----------------------------------------------------------------------------# # # # Lenstra's Elliptic Curve Factorization # # # #----------------------------------------------------------------------------# class Point: """Montgomery form of Points in an elliptic curve. In this form, the addition and doubling of points does not need any y-coordinate information thus decreasing the number of operations. Using Montgomery form we try to perform point addition and doubling in least amount of multiplications. The elliptic curve used here is of the form (E : b*y**2*z = x**3 + a*x**2*z + x*z**2). The a_24 parameter is equal to (a + 2)/4. References ========== .. [1] http://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdf """ def __init__(self, x_cord, z_cord, a_24, mod): """ Initial parameters for the Point class. Parameters ========== x_cord : X coordinate of the Point z_cord : Z coordinate of the Point a_24 : Parameter of the elliptic curve in Montgomery form mod : modulus """ self.x_cord = x_cord self.z_cord = z_cord self.a_24 = a_24 self.mod = mod def __eq__(self, other): """Two points are equal if X/Z of both points are equal """ if self.a_24 != other.a_24 or self.mod != other.mod: return False return self.x_cord * mod_inverse(self.z_cord, self.mod) % self.mod ==\ other.x_cord * mod_inverse(other.z_cord, self.mod) % self.mod def add(self, Q, diff): """ Add two points self and Q where diff = self - Q. Moreover the assumption is self.x_cord*Q.x_cord*(self.x_cord - Q.x_cord) != 0. This algorithm requires 6 multiplications. Here the difference between the points is already known and using this algorithm speeds up the addition by reducing the number of multiplication required. Also in the mont_ladder algorithm is constructed in a way so that the difference between intermediate points is always equal to the initial point. So, we always know what the difference between the point is. Parameters ========== Q : point on the curve in Montgomery form diff : self - Q Examples ======== >>> from sympy.ntheory.ecm import Point >>> p1 = Point(11, 16, 7, 29) >>> p2 = Point(13, 10, 7, 29) >>> p3 = p2.add(p1, p1) >>> p3.x_cord 23 >>> p3.z_cord 17 """ u = (self.x_cord - self.z_cord)*(Q.x_cord + Q.z_cord) v = (self.x_cord + self.z_cord)*(Q.x_cord - Q.z_cord) add, subt = u + v, u - v x_cord = diff.z_cord * add * add % self.mod z_cord = diff.x_cord * subt * subt % self.mod return Point(x_cord, z_cord, self.a_24, self.mod) def double(self): """ Doubles a point in an elliptic curve in Montgomery form. This algorithm requires 5 multiplications. Examples ======== >>> from sympy.ntheory.ecm import Point >>> p1 = Point(11, 16, 7, 29) >>> p2 = p1.double() >>> p2.x_cord 13 >>> p2.z_cord 10 """ u, v = self.x_cord + self.z_cord, self.x_cord - self.z_cord u, v = u*u, v*v diff = u - v x_cord = u*v % self.mod z_cord = diff*(v + self.a_24*diff) % self.mod return Point(x_cord, z_cord, self.a_24, self.mod) def mont_ladder(self, k): """ Scalar multiplication of a point in Montgomery form using Montgomery Ladder Algorithm. A total of 11 multiplications are required in each step of this algorithm. Parameters ========== k : The positive integer multiplier Examples ======== >>> from sympy.ntheory.ecm import Point >>> p1 = Point(11, 16, 7, 29) >>> p3 = p1.mont_ladder(3) >>> p3.x_cord 23 >>> p3.z_cord 17 """ Q = self R = self.double() for i in bin(k)[3:]: if i == '1': Q = R.add(Q, self) R = R.double() else: R = Q.add(R, self) Q = Q.double() return Q def _ecm_one_factor(n, B1=10000, B2=100000, max_curve=200): """Returns one factor of n using Lenstra's 2 Stage Elliptic curve Factorization with Suyama's Parameterization. Here Montgomery arithmetic is used for fast computation of addition and doubling of points in elliptic curve. This ECM method considers elliptic curves in Montgomery form (E : b*y**2*z = x**3 + a*x**2*z + x*z**2) and involves elliptic curve operations (mod N), where the elements in Z are reduced (mod N). Since N is not a prime, E over FF(N) is not really an elliptic curve but we can still do point additions and doubling as if FF(N) was a field. Stage 1 : The basic algorithm involves taking a random point (P) on an elliptic curve in FF(N). The compute k*P using Montgomery ladder algorithm. Let q be an unknown factor of N. Then the order of the curve E, |E(FF(q))|, might be a smooth number that divides k. Then we have k = l * |E(FF(q))| for some l. For any point belonging to the curve E, |E(FF(q))|*P = O, hence k*P = l*|E(FF(q))|*P. Thus kP.z_cord = 0 (mod q), and the unknownn factor of N (q) can be recovered by taking gcd(kP.z_cord, N). Stage 2 : This is a continuation of Stage 1 if k*P != O. The idea utilize the fact that even if kP != 0, the value of k might miss just one large prime divisor of |E(FF(q))|. In this case we only need to compute the scalar multiplication by p to get p*k*P = O. Here a second bound B2 restrict the size of possible values of p. Parameters ========== n : Number to be Factored B1 : Stage 1 Bound B2 : Stage 2 Bound max_curve : Maximum number of curves generated References ========== .. [1] Carl Pomerance and Richard Crandall "Prime Numbers: A Computational Perspective" (2nd Ed.), page 344 """ n = as_int(n) if B1 % 2 != 0 or B2 % 2 != 0: raise ValueError("The Bounds should be an even integer") sieve.extend(B2) if isprime(n): return n from sympy.functions.elementary.miscellaneous import sqrt from sympy.polys.polytools import gcd curve = 0 D = int(sqrt(B2)) beta = [0]*(D + 1) S = [0]*(D + 1) k = 1 for p in sieve.primerange(1, B1 + 1): k *= pow(p, integer_log(B1, p)[0]) while(curve <= max_curve): curve += 1 #Suyama's Parametrization sigma = rgen.randint(6, n - 1) u = (sigma*sigma - 5) % n v = (4*sigma) % n diff = v - u u_3 = pow(u, 3, n) try: C = (pow(diff, 3, n)*(3*u + v)*mod_inverse(4*u_3*v, n) - 2) % n except ValueError: #If the mod_inverse(4*u_3*v, n) doesn't exist return gcd(4*u_3*v, n) a24 = (C + 2)*mod_inverse(4, n) % n Q = Point(u_3, pow(v, 3, n), a24, n) Q = Q.mont_ladder(k) g = gcd(Q.z_cord, n) #Stage 1 factor if g != 1 and g != n: return g #Stage 1 failure. Q.z = 0, Try another curve elif g == n: continue #Stage 2 - Improved Standard Continuation S[1] = Q.double() S[2] = S[1].double() beta[1] = (S[1].x_cord*S[1].z_cord) % n beta[2] = (S[2].x_cord*S[2].z_cord) % n for d in range(3, D + 1): S[d] = S[d - 1].add(S[1], S[d - 2]) beta[d] = (S[d].x_cord*S[d].z_cord) % n g = 1 B = B1 - 1 T = Q.mont_ladder(B - 2*D) R = Q.mont_ladder(B) for r in range(B, B2, 2*D): alpha = (R.x_cord*R.z_cord) % n for q in sieve.primerange(r + 2, r + 2*D + 1): delta = (q - r) // 2 f = (R.x_cord - S[d].x_cord)*(R.z_cord + S[d].z_cord) -\ alpha + beta[delta] g = (g*f) % n #Swap T, R = R, R.add(S[D], T) g = gcd(n, g) #Stage 2 Factor found if g != 1 and g != n: return g #ECM failed, Increase the bounds raise ValueError("Increase the bounds") def ecm(n, B1=10000, B2=100000, max_curve=200, seed=1234): """Performs factorization using Lenstra's Elliptic curve method. This function repeatedly calls `ecm_one_factor` to compute the factors of n. First all the small factors are taken out using trial division. Then `ecm_one_factor` is used to compute one factor at a time. Parameters ========== n : Number to be Factored B1 : Stage 1 Bound B2 : Stage 2 Bound max_curve : Maximum number of curves generated seed : Initialize pseudorandom generator Examples ======== >>> from sympy.ntheory import ecm >>> ecm(25645121643901801) {5394769, 4753701529} >>> ecm(9804659461513846513) {4641991, 2112166839943} """ _factors = set() for prime in sieve.primerange(1, 100000): if n % prime == 0: _factors.add(prime) while(n % prime == 0): n //= prime rgen.seed(seed) while(n > 1): try: factor = _ecm_one_factor(n, B1, B2, max_curve) except ValueError: raise ValueError("Increase the bounds") _factors.add(factor) n //= factor factors = set() for factor in _factors: if isprime(factor): factors.add(factor) continue factors |= ecm(factor) return factors
4182a776f49f82d63e125ae182c84d2d463ffbdee10ec94ea0ae320ffcb789f1
""" Integral Transforms """ from functools import reduce, wraps from itertools import repeat from sympy.core import S, pi, I from sympy.core.add import Add from sympy.core.function import (AppliedUndef, count_ops, Derivative, expand, expand_complex, expand_mul, expand_trig, Function, Lambda, WildFunction, diff) from sympy.core.mul import Mul, prod from sympy.core.numbers import igcd, ilcm from sympy.core.relational import (_canonical, Ge, Gt, Lt, Unequality, Eq) from sympy.core.sorting import default_sort_key, ordered from sympy.core.symbol import Dummy, symbols, Wild from sympy.core.traversal import postorder_traversal from sympy.functions.combinatorial.factorials import factorial, rf from sympy.functions.elementary.complexes import (re, im, arg, Abs, polar_lift, periodic_argument) from sympy.functions.elementary.exponential import exp, log, exp_polar from sympy.functions.elementary.hyperbolic import cosh, coth, sinh, tanh, asinh from sympy.functions.elementary.integers import ceiling from sympy.functions.elementary.miscellaneous import Max, Min, sqrt from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold from sympy.functions.elementary.trigonometric import cos, cot, sin, tan, atan from sympy.functions.special.bessel import besseli, besselj, besselk, bessely from sympy.functions.special.delta_functions import DiracDelta, Heaviside from sympy.functions.special.error_functions import erf, erfc, Ei from sympy.functions.special.gamma_functions import digamma, gamma, lowergamma from sympy.functions.special.hyper import meijerg from sympy.integrals import integrate, Integral from sympy.integrals.meijerint import _dummy from sympy.logic.boolalg import to_cnf, conjuncts, disjuncts, Or, And from sympy.matrices.matrices import MatrixBase from sympy.polys.matrices.linsolve import _lin_eq2dict from sympy.polys.polyroots import roots from sympy.polys.polytools import factor, Poly from sympy.polys.rationaltools import together from sympy.polys.rootoftools import CRootOf, RootSum from sympy.utilities.exceptions import (sympy_deprecation_warning, SymPyDeprecationWarning, ignore_warnings) from sympy.utilities.iterables import iterable from sympy.utilities.misc import debug ########################################################################## # Helpers / Utilities ########################################################################## class IntegralTransformError(NotImplementedError): """ Exception raised in relation to problems computing transforms. Explanation =========== This class is mostly used internally; if integrals cannot be computed objects representing unevaluated transforms are usually returned. The hint ``needeval=True`` can be used to disable returning transform objects, and instead raise this exception if an integral cannot be computed. """ def __init__(self, transform, function, msg): super().__init__( "%s Transform could not be computed: %s." % (transform, msg)) self.function = function class IntegralTransform(Function): """ Base class for integral transforms. Explanation =========== This class represents unevaluated transforms. To implement a concrete transform, derive from this class and implement the ``_compute_transform(f, x, s, **hints)`` and ``_as_integral(f, x, s)`` functions. If the transform cannot be computed, raise :obj:`IntegralTransformError`. Also set ``cls._name``. For instance, >>> from sympy import LaplaceTransform >>> LaplaceTransform._name 'Laplace' Implement ``self._collapse_extra`` if your function returns more than just a number and possibly a convergence condition. """ @property def function(self): """ The function to be transformed. """ return self.args[0] @property def function_variable(self): """ The dependent variable of the function to be transformed. """ return self.args[1] @property def transform_variable(self): """ The independent transform variable. """ return self.args[2] @property def free_symbols(self): """ This method returns the symbols that will exist when the transform is evaluated. """ return self.function.free_symbols.union({self.transform_variable}) \ - {self.function_variable} def _compute_transform(self, f, x, s, **hints): raise NotImplementedError def _as_integral(self, f, x, s): raise NotImplementedError def _collapse_extra(self, extra): cond = And(*extra) if cond == False: raise IntegralTransformError(self.__class__.name, None, '') return cond def _try_directly(self, **hints): T = None try_directly = not any(func.has(self.function_variable) for func in self.function.atoms(AppliedUndef)) if try_directly: try: T = self._compute_transform(self.function, self.function_variable, self.transform_variable, **hints) except IntegralTransformError: debug('[IT _try ] Caught IntegralTransformError, returns None') T = None fn = self.function if not fn.is_Add: fn = expand_mul(fn) return fn, T def doit(self, **hints): """ Try to evaluate the transform in closed form. Explanation =========== This general function handles linearity, but apart from that leaves pretty much everything to _compute_transform. Standard hints are the following: - ``simplify``: whether or not to simplify the result - ``noconds``: if True, do not return convergence conditions - ``needeval``: if True, raise IntegralTransformError instead of returning IntegralTransform objects The default values of these hints depend on the concrete transform, usually the default is ``(simplify, noconds, needeval) = (True, False, False)``. """ needeval = hints.pop('needeval', False) simplify = hints.pop('simplify', True) hints['simplify'] = simplify fn, T = self._try_directly(**hints) if T is not None: return T if fn.is_Add: hints['needeval'] = needeval res = [self.__class__(*([x] + list(self.args[1:]))).doit(**hints) for x in fn.args] extra = [] ress = [] for x in res: if not isinstance(x, tuple): x = [x] ress.append(x[0]) if len(x) == 2: # only a condition extra.append(x[1]) elif len(x) > 2: # some region parameters and a condition (Mellin, Laplace) extra += [x[1:]] if simplify==True: res = Add(*ress).simplify() else: res = Add(*ress) if not extra: return res try: extra = self._collapse_extra(extra) if iterable(extra): return tuple([res]) + tuple(extra) else: return (res, extra) except IntegralTransformError: pass if needeval: raise IntegralTransformError( self.__class__._name, self.function, 'needeval') # TODO handle derivatives etc # pull out constant coefficients coeff, rest = fn.as_coeff_mul(self.function_variable) return coeff*self.__class__(*([Mul(*rest)] + list(self.args[1:]))) @property def as_integral(self): return self._as_integral(self.function, self.function_variable, self.transform_variable) def _eval_rewrite_as_Integral(self, *args, **kwargs): return self.as_integral def _simplify(expr, doit): if doit: from sympy.simplify import simplify from sympy.simplify.powsimp import powdenest return simplify(powdenest(piecewise_fold(expr), polar=True)) return expr def _noconds_(default): """ This is a decorator generator for dropping convergence conditions. Explanation =========== Suppose you define a function ``transform(*args)`` which returns a tuple of the form ``(result, cond1, cond2, ...)``. Decorating it ``@_noconds_(default)`` will add a new keyword argument ``noconds`` to it. If ``noconds=True``, the return value will be altered to be only ``result``, whereas if ``noconds=False`` the return value will not be altered. The default value of the ``noconds`` keyword will be ``default`` (i.e. the argument of this function). """ def make_wrapper(func): @wraps(func) def wrapper(*args, noconds=default, **kwargs): res = func(*args, **kwargs) if noconds: return res[0] return res return wrapper return make_wrapper _noconds = _noconds_(False) ########################################################################## # Mellin Transform ########################################################################## def _default_integrator(f, x): return integrate(f, (x, S.Zero, S.Infinity)) @_noconds def _mellin_transform(f, x, s_, integrator=_default_integrator, simplify=True): """ Backend function to compute Mellin transforms. """ # We use a fresh dummy, because assumptions on s might drop conditions on # convergence of the integral. s = _dummy('s', 'mellin-transform', f) F = integrator(x**(s - 1) * f, x) if not F.has(Integral): return _simplify(F.subs(s, s_), simplify), (S.NegativeInfinity, S.Infinity), S.true if not F.is_Piecewise: # XXX can this work if integration gives continuous result now? raise IntegralTransformError('Mellin', f, 'could not compute integral') F, cond = F.args[0] if F.has(Integral): raise IntegralTransformError( 'Mellin', f, 'integral in unexpected form') def process_conds(cond): """ Turn ``cond`` into a strip (a, b), and auxiliary conditions. """ from sympy.solvers.inequalities import _solve_inequality a = S.NegativeInfinity b = S.Infinity aux = S.true conds = conjuncts(to_cnf(cond)) t = Dummy('t', real=True) for c in conds: a_ = S.Infinity b_ = S.NegativeInfinity aux_ = [] for d in disjuncts(c): d_ = d.replace( re, lambda x: x.as_real_imag()[0]).subs(re(s), t) if not d.is_Relational or \ d.rel_op in ('==', '!=') \ or d_.has(s) or not d_.has(t): aux_ += [d] continue soln = _solve_inequality(d_, t) if not soln.is_Relational or \ soln.rel_op in ('==', '!='): aux_ += [d] continue if soln.lts == t: b_ = Max(soln.gts, b_) else: a_ = Min(soln.lts, a_) if a_ is not S.Infinity and a_ != b: a = Max(a_, a) elif b_ is not S.NegativeInfinity and b_ != a: b = Min(b_, b) else: aux = And(aux, Or(*aux_)) return a, b, aux conds = [process_conds(c) for c in disjuncts(cond)] conds = [x for x in conds if x[2] != False] conds.sort(key=lambda x: (x[0] - x[1], count_ops(x[2]))) if not conds: raise IntegralTransformError('Mellin', f, 'no convergence found') a, b, aux = conds[0] return _simplify(F.subs(s, s_), simplify), (a, b), aux class MellinTransform(IntegralTransform): """ Class representing unevaluated Mellin transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute Mellin transforms, see the :func:`mellin_transform` docstring. """ _name = 'Mellin' def _compute_transform(self, f, x, s, **hints): return _mellin_transform(f, x, s, **hints) def _as_integral(self, f, x, s): return Integral(f*x**(s - 1), (x, S.Zero, S.Infinity)) def _collapse_extra(self, extra): a = [] b = [] cond = [] for (sa, sb), c in extra: a += [sa] b += [sb] cond += [c] res = (Max(*a), Min(*b)), And(*cond) if (res[0][0] >= res[0][1]) == True or res[1] == False: raise IntegralTransformError( 'Mellin', None, 'no combined convergence.') return res def mellin_transform(f, x, s, **hints): r""" Compute the Mellin transform `F(s)` of `f(x)`, .. math :: F(s) = \int_0^\infty x^{s-1} f(x) \mathrm{d}x. For all "sensible" functions, this converges absolutely in a strip `a < \operatorname{Re}(s) < b`. Explanation =========== The Mellin transform is related via change of variables to the Fourier transform, and also to the (bilateral) Laplace transform. This function returns ``(F, (a, b), cond)`` where ``F`` is the Mellin transform of ``f``, ``(a, b)`` is the fundamental strip (as above), and ``cond`` are auxiliary convergence conditions. If the integral cannot be computed in closed form, this function returns an unevaluated :class:`MellinTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. If ``noconds=False``, then only `F` will be returned (i.e. not ``cond``, and also not the strip ``(a, b)``). Examples ======== >>> from sympy import mellin_transform, exp >>> from sympy.abc import x, s >>> mellin_transform(exp(-x), x, s) (gamma(s), (0, oo), True) See Also ======== inverse_mellin_transform, laplace_transform, fourier_transform hankel_transform, inverse_hankel_transform """ return MellinTransform(f, x, s).doit(**hints) def _rewrite_sin(m_n, s, a, b): """ Re-write the sine function ``sin(m*s + n)`` as gamma functions, compatible with the strip (a, b). Return ``(gamma1, gamma2, fac)`` so that ``f == fac/(gamma1 * gamma2)``. Examples ======== >>> from sympy.integrals.transforms import _rewrite_sin >>> from sympy import pi, S >>> from sympy.abc import s >>> _rewrite_sin((pi, 0), s, 0, 1) (gamma(s), gamma(1 - s), pi) >>> _rewrite_sin((pi, 0), s, 1, 0) (gamma(s - 1), gamma(2 - s), -pi) >>> _rewrite_sin((pi, 0), s, -1, 0) (gamma(s + 1), gamma(-s), -pi) >>> _rewrite_sin((pi, pi/2), s, S(1)/2, S(3)/2) (gamma(s - 1/2), gamma(3/2 - s), -pi) >>> _rewrite_sin((pi, pi), s, 0, 1) (gamma(s), gamma(1 - s), -pi) >>> _rewrite_sin((2*pi, 0), s, 0, S(1)/2) (gamma(2*s), gamma(1 - 2*s), pi) >>> _rewrite_sin((2*pi, 0), s, S(1)/2, 1) (gamma(2*s - 1), gamma(2 - 2*s), -pi) """ # (This is a separate function because it is moderately complicated, # and I want to doctest it.) # We want to use pi/sin(pi*x) = gamma(x)*gamma(1-x). # But there is one comlication: the gamma functions determine the # inegration contour in the definition of the G-function. Usually # it would not matter if this is slightly shifted, unless this way # we create an undefined function! # So we try to write this in such a way that the gammas are # eminently on the right side of the strip. m, n = m_n m = expand_mul(m/pi) n = expand_mul(n/pi) r = ceiling(-m*a - n.as_real_imag()[0]) # Don't use re(n), does not expand return gamma(m*s + n + r), gamma(1 - n - r - m*s), (-1)**r*pi class MellinTransformStripError(ValueError): """ Exception raised by _rewrite_gamma. Mainly for internal use. """ pass def _rewrite_gamma(f, s, a, b): """ Try to rewrite the product f(s) as a product of gamma functions, so that the inverse Mellin transform of f can be expressed as a meijer G function. Explanation =========== Return (an, ap), (bm, bq), arg, exp, fac such that G((an, ap), (bm, bq), arg/z**exp)*fac is the inverse Mellin transform of f(s). Raises IntegralTransformError or MellinTransformStripError on failure. It is asserted that f has no poles in the fundamental strip designated by (a, b). One of a and b is allowed to be None. The fundamental strip is important, because it determines the inversion contour. This function can handle exponentials, linear factors, trigonometric functions. This is a helper function for inverse_mellin_transform that will not attempt any transformations on f. Examples ======== >>> from sympy.integrals.transforms import _rewrite_gamma >>> from sympy.abc import s >>> from sympy import oo >>> _rewrite_gamma(s*(s+3)*(s-1), s, -oo, oo) (([], [-3, 0, 1]), ([-2, 1, 2], []), 1, 1, -1) >>> _rewrite_gamma((s-1)**2, s, -oo, oo) (([], [1, 1]), ([2, 2], []), 1, 1, 1) Importance of the fundamental strip: >>> _rewrite_gamma(1/s, s, 0, oo) (([1], []), ([], [0]), 1, 1, 1) >>> _rewrite_gamma(1/s, s, None, oo) (([1], []), ([], [0]), 1, 1, 1) >>> _rewrite_gamma(1/s, s, 0, None) (([1], []), ([], [0]), 1, 1, 1) >>> _rewrite_gamma(1/s, s, -oo, 0) (([], [1]), ([0], []), 1, 1, -1) >>> _rewrite_gamma(1/s, s, None, 0) (([], [1]), ([0], []), 1, 1, -1) >>> _rewrite_gamma(1/s, s, -oo, None) (([], [1]), ([0], []), 1, 1, -1) >>> _rewrite_gamma(2**(-s+3), s, -oo, oo) (([], []), ([], []), 1/2, 1, 8) """ # Our strategy will be as follows: # 1) Guess a constant c such that the inversion integral should be # performed wrt s'=c*s (instead of plain s). Write s for s'. # 2) Process all factors, rewrite them independently as gamma functions in # argument s, or exponentials of s. # 3) Try to transform all gamma functions s.t. they have argument # a+s or a-s. # 4) Check that the resulting G function parameters are valid. # 5) Combine all the exponentials. a_, b_ = S([a, b]) def left(c, is_numer): """ Decide whether pole at c lies to the left of the fundamental strip. """ # heuristically, this is the best chance for us to solve the inequalities c = expand(re(c)) if a_ is None and b_ is S.Infinity: return True if a_ is None: return c < b_ if b_ is None: return c <= a_ if (c >= b_) == True: return False if (c <= a_) == True: return True if is_numer: return None if a_.free_symbols or b_.free_symbols or c.free_symbols: return None # XXX #raise IntegralTransformError('Inverse Mellin', f, # 'Could not determine position of singularity %s' # ' relative to fundamental strip' % c) raise MellinTransformStripError('Pole inside critical strip?') # 1) s_multipliers = [] for g in f.atoms(gamma): if not g.has(s): continue arg = g.args[0] if arg.is_Add: arg = arg.as_independent(s)[1] coeff, _ = arg.as_coeff_mul(s) s_multipliers += [coeff] for g in f.atoms(sin, cos, tan, cot): if not g.has(s): continue arg = g.args[0] if arg.is_Add: arg = arg.as_independent(s)[1] coeff, _ = arg.as_coeff_mul(s) s_multipliers += [coeff/pi] s_multipliers = [Abs(x) if x.is_extended_real else x for x in s_multipliers] common_coefficient = S.One for x in s_multipliers: if not x.is_Rational: common_coefficient = x break s_multipliers = [x/common_coefficient for x in s_multipliers] if not (all(x.is_Rational for x in s_multipliers) and common_coefficient.is_extended_real): raise IntegralTransformError("Gamma", None, "Nonrational multiplier") s_multiplier = common_coefficient/reduce(ilcm, [S(x.q) for x in s_multipliers], S.One) if s_multiplier == common_coefficient: if len(s_multipliers) == 0: s_multiplier = common_coefficient else: s_multiplier = common_coefficient \ *reduce(igcd, [S(x.p) for x in s_multipliers]) f = f.subs(s, s/s_multiplier) fac = S.One/s_multiplier exponent = S.One/s_multiplier if a_ is not None: a_ *= s_multiplier if b_ is not None: b_ *= s_multiplier # 2) numer, denom = f.as_numer_denom() numer = Mul.make_args(numer) denom = Mul.make_args(denom) args = list(zip(numer, repeat(True))) + list(zip(denom, repeat(False))) facs = [] dfacs = [] # *_gammas will contain pairs (a, c) representing Gamma(a*s + c) numer_gammas = [] denom_gammas = [] # exponentials will contain bases for exponentials of s exponentials = [] def exception(fact): return IntegralTransformError("Inverse Mellin", f, "Unrecognised form '%s'." % fact) while args: fact, is_numer = args.pop() if is_numer: ugammas, lgammas = numer_gammas, denom_gammas ufacs = facs else: ugammas, lgammas = denom_gammas, numer_gammas ufacs = dfacs def linear_arg(arg): """ Test if arg is of form a*s+b, raise exception if not. """ if not arg.is_polynomial(s): raise exception(fact) p = Poly(arg, s) if p.degree() != 1: raise exception(fact) return p.all_coeffs() # constants if not fact.has(s): ufacs += [fact] # exponentials elif fact.is_Pow or isinstance(fact, exp): if fact.is_Pow: base = fact.base exp_ = fact.exp else: base = exp_polar(1) exp_ = fact.exp if exp_.is_Integer: cond = is_numer if exp_ < 0: cond = not cond args += [(base, cond)]*Abs(exp_) continue elif not base.has(s): a, b = linear_arg(exp_) if not is_numer: base = 1/base exponentials += [base**a] facs += [base**b] else: raise exception(fact) # linear factors elif fact.is_polynomial(s): p = Poly(fact, s) if p.degree() != 1: # We completely factor the poly. For this we need the roots. # Now roots() only works in some cases (low degree), and CRootOf # only works without parameters. So try both... coeff = p.LT()[1] rs = roots(p, s) if len(rs) != p.degree(): rs = CRootOf.all_roots(p) ufacs += [coeff] args += [(s - c, is_numer) for c in rs] continue a, c = p.all_coeffs() ufacs += [a] c /= -a # Now need to convert s - c if left(c, is_numer): ugammas += [(S.One, -c + 1)] lgammas += [(S.One, -c)] else: ufacs += [-1] ugammas += [(S.NegativeOne, c + 1)] lgammas += [(S.NegativeOne, c)] elif isinstance(fact, gamma): a, b = linear_arg(fact.args[0]) if is_numer: if (a > 0 and (left(-b/a, is_numer) == False)) or \ (a < 0 and (left(-b/a, is_numer) == True)): raise NotImplementedError( 'Gammas partially over the strip.') ugammas += [(a, b)] elif isinstance(fact, sin): # We try to re-write all trigs as gammas. This is not in # general the best strategy, since sometimes this is impossible, # but rewriting as exponentials would work. However trig functions # in inverse mellin transforms usually all come from simplifying # gamma terms, so this should work. a = fact.args[0] if is_numer: # No problem with the poles. gamma1, gamma2, fac_ = gamma(a/pi), gamma(1 - a/pi), pi else: gamma1, gamma2, fac_ = _rewrite_sin(linear_arg(a), s, a_, b_) args += [(gamma1, not is_numer), (gamma2, not is_numer)] ufacs += [fac_] elif isinstance(fact, tan): a = fact.args[0] args += [(sin(a, evaluate=False), is_numer), (sin(pi/2 - a, evaluate=False), not is_numer)] elif isinstance(fact, cos): a = fact.args[0] args += [(sin(pi/2 - a, evaluate=False), is_numer)] elif isinstance(fact, cot): a = fact.args[0] args += [(sin(pi/2 - a, evaluate=False), is_numer), (sin(a, evaluate=False), not is_numer)] else: raise exception(fact) fac *= Mul(*facs)/Mul(*dfacs) # 3) an, ap, bm, bq = [], [], [], [] for gammas, plus, minus, is_numer in [(numer_gammas, an, bm, True), (denom_gammas, bq, ap, False)]: while gammas: a, c = gammas.pop() if a != -1 and a != +1: # We use the gamma function multiplication theorem. p = Abs(S(a)) newa = a/p newc = c/p if not a.is_Integer: raise TypeError("a is not an integer") for k in range(p): gammas += [(newa, newc + k/p)] if is_numer: fac *= (2*pi)**((1 - p)/2) * p**(c - S.Half) exponentials += [p**a] else: fac /= (2*pi)**((1 - p)/2) * p**(c - S.Half) exponentials += [p**(-a)] continue if a == +1: plus.append(1 - c) else: minus.append(c) # 4) # TODO # 5) arg = Mul(*exponentials) # for testability, sort the arguments an.sort(key=default_sort_key) ap.sort(key=default_sort_key) bm.sort(key=default_sort_key) bq.sort(key=default_sort_key) return (an, ap), (bm, bq), arg, exponent, fac @_noconds_(True) def _inverse_mellin_transform(F, s, x_, strip, as_meijerg=False): """ A helper for the real inverse_mellin_transform function, this one here assumes x to be real and positive. """ x = _dummy('t', 'inverse-mellin-transform', F, positive=True) # Actually, we won't try integration at all. Instead we use the definition # of the Meijer G function as a fairly general inverse mellin transform. F = F.rewrite(gamma) for g in [factor(F), expand_mul(F), expand(F)]: if g.is_Add: # do all terms separately ress = [_inverse_mellin_transform(G, s, x, strip, as_meijerg, noconds=False) for G in g.args] conds = [p[1] for p in ress] ress = [p[0] for p in ress] res = Add(*ress) if not as_meijerg: res = factor(res, gens=res.atoms(Heaviside)) return res.subs(x, x_), And(*conds) try: a, b, C, e, fac = _rewrite_gamma(g, s, strip[0], strip[1]) except IntegralTransformError: continue try: G = meijerg(a, b, C/x**e) except ValueError: continue if as_meijerg: h = G else: try: from sympy.simplify import hyperexpand h = hyperexpand(G) except NotImplementedError: raise IntegralTransformError( 'Inverse Mellin', F, 'Could not calculate integral') if h.is_Piecewise and len(h.args) == 3: # XXX we break modularity here! h = Heaviside(x - Abs(C))*h.args[0].args[0] \ + Heaviside(Abs(C) - x)*h.args[1].args[0] # We must ensure that the integral along the line we want converges, # and return that value. # See [L], 5.2 cond = [Abs(arg(G.argument)) < G.delta*pi] # Note: we allow ">=" here, this corresponds to convergence if we let # limits go to oo symmetrically. ">" corresponds to absolute convergence. cond += [And(Or(len(G.ap) != len(G.bq), 0 >= re(G.nu) + 1), Abs(arg(G.argument)) == G.delta*pi)] cond = Or(*cond) if cond == False: raise IntegralTransformError( 'Inverse Mellin', F, 'does not converge') return (h*fac).subs(x, x_), cond raise IntegralTransformError('Inverse Mellin', F, '') _allowed = None class InverseMellinTransform(IntegralTransform): """ Class representing unevaluated inverse Mellin transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse Mellin transforms, see the :func:`inverse_mellin_transform` docstring. """ _name = 'Inverse Mellin' _none_sentinel = Dummy('None') _c = Dummy('c') def __new__(cls, F, s, x, a, b, **opts): if a is None: a = InverseMellinTransform._none_sentinel if b is None: b = InverseMellinTransform._none_sentinel return IntegralTransform.__new__(cls, F, s, x, a, b, **opts) @property def fundamental_strip(self): a, b = self.args[3], self.args[4] if a is InverseMellinTransform._none_sentinel: a = None if b is InverseMellinTransform._none_sentinel: b = None return a, b def _compute_transform(self, F, s, x, **hints): # IntegralTransform's doit will cause this hint to exist, but # InverseMellinTransform should ignore it hints.pop('simplify', True) global _allowed if _allowed is None: _allowed = { exp, gamma, sin, cos, tan, cot, cosh, sinh, tanh, coth, factorial, rf} for f in postorder_traversal(F): if f.is_Function and f.has(s) and f.func not in _allowed: raise IntegralTransformError('Inverse Mellin', F, 'Component %s not recognised.' % f) strip = self.fundamental_strip return _inverse_mellin_transform(F, s, x, strip, **hints) def _as_integral(self, F, s, x): c = self.__class__._c return Integral(F*x**(-s), (s, c - S.ImaginaryUnit*S.Infinity, c + S.ImaginaryUnit*S.Infinity))/(2*S.Pi*S.ImaginaryUnit) def inverse_mellin_transform(F, s, x, strip, **hints): r""" Compute the inverse Mellin transform of `F(s)` over the fundamental strip given by ``strip=(a, b)``. Explanation =========== This can be defined as .. math:: f(x) = \frac{1}{2\pi i} \int_{c - i\infty}^{c + i\infty} x^{-s} F(s) \mathrm{d}s, for any `c` in the fundamental strip. Under certain regularity conditions on `F` and/or `f`, this recovers `f` from its Mellin transform `F` (and vice versa), for positive real `x`. One of `a` or `b` may be passed as ``None``; a suitable `c` will be inferred. If the integral cannot be computed in closed form, this function returns an unevaluated :class:`InverseMellinTransform` object. Note that this function will assume x to be positive and real, regardless of the SymPy assumptions! For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Examples ======== >>> from sympy import inverse_mellin_transform, oo, gamma >>> from sympy.abc import x, s >>> inverse_mellin_transform(gamma(s), s, x, (0, oo)) exp(-x) The fundamental strip matters: >>> f = 1/(s**2 - 1) >>> inverse_mellin_transform(f, s, x, (-oo, -1)) x*(1 - 1/x**2)*Heaviside(x - 1)/2 >>> inverse_mellin_transform(f, s, x, (-1, 1)) -x*Heaviside(1 - x)/2 - Heaviside(x - 1)/(2*x) >>> inverse_mellin_transform(f, s, x, (1, oo)) (1/2 - x**2/2)*Heaviside(1 - x)/x See Also ======== mellin_transform hankel_transform, inverse_hankel_transform """ return InverseMellinTransform(F, s, x, strip[0], strip[1]).doit(**hints) ########################################################################## # Laplace Transform ########################################################################## def _simplifyconds(expr, s, a): r""" Naively simplify some conditions occurring in ``expr``, given that `\operatorname{Re}(s) > a`. Examples ======== >>> from sympy.integrals.transforms import _simplifyconds as simp >>> from sympy.abc import x >>> from sympy import sympify as S >>> simp(abs(x**2) < 1, x, 1) False >>> simp(abs(x**2) < 1, x, 2) False >>> simp(abs(x**2) < 1, x, 0) Abs(x**2) < 1 >>> simp(abs(1/x**2) < 1, x, 1) True >>> simp(S(1) < abs(x), x, 1) True >>> simp(S(1) < abs(1/x), x, 1) False >>> from sympy import Ne >>> simp(Ne(1, x**3), x, 1) True >>> simp(Ne(1, x**3), x, 2) True >>> simp(Ne(1, x**3), x, 0) Ne(1, x**3) """ def power(ex): if ex == s: return 1 if ex.is_Pow and ex.base == s: return ex.exp return None def bigger(ex1, ex2): """ Return True only if |ex1| > |ex2|, False only if |ex1| < |ex2|. Else return None. """ if ex1.has(s) and ex2.has(s): return None if isinstance(ex1, Abs): ex1 = ex1.args[0] if isinstance(ex2, Abs): ex2 = ex2.args[0] if ex1.has(s): return bigger(1/ex2, 1/ex1) n = power(ex2) if n is None: return None try: if n > 0 and (Abs(ex1) <= Abs(a)**n) == True: return False if n < 0 and (Abs(ex1) >= Abs(a)**n) == True: return True except TypeError: pass def replie(x, y): """ simplify x < y """ if not (x.is_positive or isinstance(x, Abs)) \ or not (y.is_positive or isinstance(y, Abs)): return (x < y) r = bigger(x, y) if r is not None: return not r return (x < y) def replue(x, y): b = bigger(x, y) if b in (True, False): return True return Unequality(x, y) def repl(ex, *args): if ex in (True, False): return bool(ex) return ex.replace(*args) from sympy.simplify.radsimp import collect_abs expr = collect_abs(expr) expr = repl(expr, Lt, replie) expr = repl(expr, Gt, lambda x, y: replie(y, x)) expr = repl(expr, Unequality, replue) return S(expr) def expand_dirac_delta(expr): """ Expand an expression involving DiractDelta to get it as a linear combination of DiracDelta functions. """ return _lin_eq2dict(expr, expr.atoms(DiracDelta)) def _laplace_transform_integration(f, t, s_, simplify=True): """ The backend function for doing Laplace transforms by integration. This backend assumes that the frontend has already split sums such that `f` is to an addition anymore. """ s = Dummy('s') debug('[LT _l_t_i ] started with (%s, %s, %s)'%(f, t, s)) debug('[LT _l_t_i ] and simplify=%s'%(simplify, )) if f.has(DiracDelta): return None F = integrate(f*exp(-s*t), (t, S.Zero, S.Infinity)) debug('[LT _l_t_i ] integrated: %s'%(F, )) if not F.has(Integral): return _simplify(F.subs(s, s_), simplify), S.NegativeInfinity, S.true if not F.is_Piecewise: debug('[LT _l_t_i ] not piecewise.') return None F, cond = F.args[0] if F.has(Integral): debug('[LT _l_t_i ] integral in unexpected form.') return None def process_conds(conds): """ Turn ``conds`` into a strip and auxiliary conditions. """ from sympy.solvers.inequalities import _solve_inequality a = S.NegativeInfinity aux = S.true conds = conjuncts(to_cnf(conds)) p, q, w1, w2, w3, w4, w5 = symbols( 'p q w1 w2 w3 w4 w5', cls=Wild, exclude=[s]) patterns = ( p*Abs(arg((s + w3)*q)) < w2, p*Abs(arg((s + w3)*q)) <= w2, Abs(periodic_argument((s + w3)**p*q, w1)) < w2, Abs(periodic_argument((s + w3)**p*q, w1)) <= w2, Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) < w2, Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) <= w2) for c in conds: a_ = S.Infinity aux_ = [] for d in disjuncts(c): if d.is_Relational and s in d.rhs.free_symbols: d = d.reversed if d.is_Relational and isinstance(d, (Ge, Gt)): d = d.reversedsign for pat in patterns: m = d.match(pat) if m: break if m: if m[q].is_positive and m[w2]/m[p] == pi/2: d = -re(s + m[w3]) < 0 m = d.match(p - cos(w1*Abs(arg(s*w5))*w2)*Abs(s**w3)**w4 < 0) if not m: m = d.match( cos(p - Abs(periodic_argument(s**w1*w5, q))*w2)*Abs(s**w3)**w4 < 0) if not m: m = d.match( p - cos(Abs(periodic_argument(polar_lift(s)**w1*w5, q))*w2 )*Abs(s**w3)**w4 < 0) if m and all(m[wild].is_positive for wild in [w1, w2, w3, w4, w5]): d = re(s) > m[p] d_ = d.replace( re, lambda x: x.expand().as_real_imag()[0]).subs(re(s), t) if not d.is_Relational or \ d.rel_op in ('==', '!=') \ or d_.has(s) or not d_.has(t): aux_ += [d] continue soln = _solve_inequality(d_, t) if not soln.is_Relational or \ soln.rel_op in ('==', '!='): aux_ += [d] continue if soln.lts == t: debug('[LT _l_t_i ] convergence not in half-plane.') return None else: a_ = Min(soln.lts, a_) if a_ is not S.Infinity: a = Max(a_, a) else: aux = And(aux, Or(*aux_)) return a, aux.canonical if aux.is_Relational else aux conds = [process_conds(c) for c in disjuncts(cond)] conds2 = [x for x in conds if x[1] != False and x[0] is not S.NegativeInfinity] if not conds2: conds2 = [x for x in conds if x[1] != False] conds = list(ordered(conds2)) def cnt(expr): if expr in (True, False): return 0 return expr.count_ops() conds.sort(key=lambda x: (-x[0], cnt(x[1]))) if not conds: debug('[LT _l_t_i ] no convergence found.') return None a, aux = conds[0] # XXX is [0] always the right one? def sbs(expr): return expr.subs(s, s_) if simplify: F = _simplifyconds(F, s, a) aux = _simplifyconds(aux, s, a) return _simplify(F.subs(s, s_), simplify), sbs(a), _canonical(sbs(aux)) def _laplace_deep_collect(f, t): """ This is an internal helper function that traverses through the epression tree of `f(t)` and collects arguments. The purpose of it is that anything like `f(w*t-1*t-c)` will be written as `f((w-1)*t-c)` such that it can match `f(a*t+b)`. """ func = f.func args = list(f.args) if len(f.args) == 0: return f else: args = [_laplace_deep_collect(arg, t) for arg in args] if func.is_Add: return func(*args).collect(t) else: return func(*args) def _laplace_build_rules(t, s): """ This is an internal helper function that returns the table of Laplace transform rules in terms of the time variable `t` and the frequency variable `s`. It is used by ``_laplace_apply_rules``. Each entry is a tuple containing: (time domain pattern, frequency-domain replacement, condition for the rule to be applied, convergence plane, preparation function) The preparation function is a function with one argument that is applied to the expression before matching. For most rules it should be ``_laplace_deep_collect``. """ a = Wild('a', exclude=[t]) b = Wild('b', exclude=[t]) n = Wild('n', exclude=[t]) tau = Wild('tau', exclude=[t]) omega = Wild('omega', exclude=[t]) dco = lambda f: _laplace_deep_collect(f, t) laplace_transform_rules = [ (a, a/s, S.true, S.Zero, dco), # 4.2.1 (DiracDelta(a*t-b), exp(-s*b/a)/Abs(a), Or(And(a>0, b>=0), And(a<0, b<=0)), S.NegativeInfinity, dco), # Not in Bateman54 (DiracDelta(a*t-b), S(0), Or(And(a<0, b>=0), And(a>0, b<=0)), S.NegativeInfinity, dco), # Not in Bateman54 (Heaviside(a*t-b), exp(-s*b/a)/s, And(a>0, b>0), S.Zero, dco), # 4.4.1 (Heaviside(a*t-b), (1-exp(-s*b/a))/s, And(a<0, b<0), S.Zero, dco), # 4.4.1 (Heaviside(a*t-b), 1/s, And(a>0, b<=0), S.Zero, dco), # 4.4.1 (Heaviside(a*t-b), 0, And(a<0, b>0), S.Zero, dco), # 4.4.1 (t, 1/s**2, S.true, S.Zero, dco), # 4.2.3 (1/(a*t+b), -exp(-b/a*s)*Ei(-b/a*s)/a, Abs(arg(b/a))<pi, S.Zero, dco), # 4.2.6 (1/sqrt(a*t+b), sqrt(a*pi/s)*exp(b/a*s)*erfc(sqrt(b/a*s))/a, Abs(arg(b/a))<pi, S.Zero, dco), # 4.2.18 ((a*t+b)**(-S(3)/2), 2*b**(-S(1)/2)-2*(pi*s/a)**(S(1)/2)*exp(b/a*s)*\ erfc(sqrt(b/a*s))/a, Abs(arg(b/a))<pi, S.Zero, dco), # 4.2.20 (sqrt(t)/(t+b), sqrt(pi/s)-pi*sqrt(b)*exp(b*s)*erfc(sqrt(b*s)), Abs(arg(b))<pi, S.Zero, dco), # 4.2.22 (1/(a*sqrt(t) + t**(3/2)), pi*a**(S(1)/2)*exp(a*s)*erfc(sqrt(a*s)), S.true, S.Zero, dco), # Not in Bateman54 (t**n, gamma(n+1)/s**(n+1), n>-1, S.Zero, dco), # 4.3.1 ((a*t+b)**n, lowergamma(n+1, b/a*s)*exp(-b/a*s)/s**(n+1)/a, And(n>-1, Abs(arg(b/a))<pi), S.Zero, dco), # 4.3.4 (t**n/(t+a), a**n*gamma(n+1)*lowergamma(-n,a*s), And(n>-1, Abs(arg(a))<pi), S.Zero, dco), # 4.3.7 (exp(a*t-tau), exp(-tau)/(s-a), S.true, a, dco), # 4.5.1 (t*exp(a*t-tau), exp(-tau)/(s-a)**2, S.true, a, dco), # 4.5.2 (t**n*exp(a*t), gamma(n+1)/(s-a)**(n+1), re(n)>-1, a, dco), # 4.5.3 (exp(-a*t**2), sqrt(pi/4/a)*exp(s**2/4/a)*erfc(s/sqrt(4*a)), re(a)>0, S.Zero, dco), # 4.5.21 (t*exp(-a*t**2), 1/(2*a)-2/sqrt(pi)/(4*a)**(S(3)/2)*s*erfc(s/sqrt(4*a)), re(a)>0, S.Zero, dco), # 4.5.22 (exp(-a/t), 2*sqrt(a/s)*besselk(1, 2*sqrt(a*s)), re(a)>=0, S.Zero, dco), # 4.5.25 (sqrt(t)*exp(-a/t), S(1)/2*sqrt(pi/s**3)*(1+2*sqrt(a*s))*exp(-2*sqrt(a*s)), re(a)>=0, S.Zero, dco), # 4.5.26 (exp(-a/t)/sqrt(t), sqrt(pi/s)*exp(-2*sqrt(a*s)), re(a)>=0, S.Zero, dco), # 4.5.27 (exp(-a/t)/(t*sqrt(t)), sqrt(pi/a)*exp(-2*sqrt(a*s)), re(a)>0, S.Zero, dco), # 4.5.28 (t**n*exp(-a/t), 2*(a/s)**((n+1)/2)*besselk(n+1, 2*sqrt(a*s)), re(a)>0, S.Zero, dco), # 4.5.29 (exp(-2*sqrt(a*t)), s**(-1)-sqrt(pi*a)*s**(-S(3)/2)*exp(a/s)*\ erfc(sqrt(a/s)), Abs(arg(a))<pi, S.Zero, dco), # 4.5.31 (exp(-2*sqrt(a*t))/sqrt(t), (pi/s)**(S(1)/2)*exp(a/s)*erfc(sqrt(a/s)), Abs(arg(a))<pi, S.Zero, dco), # 4.5.33 (log(a*t), -log(exp(S.EulerGamma)*s/a)/s, a>0, S.Zero, dco), # 4.6.1 (log(1+a*t), -exp(s/a)/s*Ei(-s/a), Abs(arg(a))<pi, S.Zero, dco), # 4.6.4 (log(a*t+b), (log(b)-exp(s/b/a)/s*a*Ei(-s/b))/s*a, And(a>0,Abs(arg(b))<pi), S.Zero, dco), # 4.6.5 (log(t)/sqrt(t), -sqrt(pi/s)*log(4*s*exp(S.EulerGamma)), S.true, S.Zero, dco), # 4.6.9 (t**n*log(t), gamma(n+1)*s**(-n-1)*(digamma(n+1)-log(s)), re(n)>-1, S.Zero, dco), # 4.6.11 (log(a*t)**2, (log(exp(S.EulerGamma)*s/a)**2+pi**2/6)/s, a>0, S.Zero, dco), # 4.6.13 (sin(omega*t), omega/(s**2+omega**2), S.true, Abs(im(omega)), dco), # 4,7,1 (Abs(sin(omega*t)), omega/(s**2+omega**2)*coth(pi*s/2/omega), omega>0, S.Zero, dco), # 4.7.2 (sin(omega*t)/t, atan(omega/s), S.true, Abs(im(omega)), dco), # 4.7.16 (sin(omega*t)**2/t, log(1+4*omega**2/s**2)/4, S.true, 2*Abs(im(omega)), dco), # 4.7.17 (sin(omega*t)**2/t**2, omega*atan(2*omega/s)-s*log(1+4*omega**2/s**2)/4, S.true, 2*Abs(im(omega)), dco), # 4.7.20 (sin(2*sqrt(a*t)), sqrt(pi*a)/s/sqrt(s)*exp(-a/s), S.true, S.Zero, dco), # 4.7.32 (sin(2*sqrt(a*t))/t, pi*erf(sqrt(a/s)), S.true, S.Zero, dco), # 4.7.34 (cos(omega*t), s/(s**2+omega**2), S.true, Abs(im(omega)), dco), # 4.7.43 (cos(omega*t)**2, (s**2+2*omega**2)/(s**2+4*omega**2)/s, S.true, 2*Abs(im(omega)), dco), # 4.7.45 (sqrt(t)*cos(2*sqrt(a*t)), sqrt(pi)/2*s**(-S(5)/2)*(s-2*a)*exp(-a/s), S.true, S.Zero, dco), # 4.7.66 (cos(2*sqrt(a*t))/sqrt(t), sqrt(pi/s)*exp(-a/s), S.true, S.Zero, dco), # 4.7.67 (sin(a*t)*sin(b*t), 2*a*b*s/(s**2+(a+b)**2)/(s**2+(a-b)**2), S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.78 (cos(a*t)*sin(b*t), b*(s**2-a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2), S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.79 (cos(a*t)*cos(b*t), s*(s**2+a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2), S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.80 (sinh(a*t), a/(s**2-a**2), S.true, Abs(re(a)), dco), # 4.9.1 (cosh(a*t), s/(s**2-a**2), S.true, Abs(re(a)), dco), # 4.9.2 (sinh(a*t)**2, 2*a**2/(s**3-4*a**2*s), S.true, 2*Abs(re(a)), dco), # 4.9.3 (cosh(a*t)**2, (s**2-2*a**2)/(s**3-4*a**2*s), S.true, 2*Abs(re(a)), dco), # 4.9.4 (sinh(a*t)/t, log((s+a)/(s-a))/2, S.true, Abs(re(a)), dco), # 4.9.12 (t**n*sinh(a*t), gamma(n+1)/2*((s-a)**(-n-1)-(s+a)**(-n-1)), n>-2, Abs(a), dco), # 4.9.18 (t**n*cosh(a*t), gamma(n+1)/2*((s-a)**(-n-1)+(s+a)**(-n-1)), n>-1, Abs(a), dco), # 4.9.19 (sinh(2*sqrt(a*t)), sqrt(pi*a)/s/sqrt(s)*exp(a/s), S.true, S.Zero, dco), # 4.9.34 (cosh(2*sqrt(a*t)), 1/s+sqrt(pi*a)/s/sqrt(s)*exp(a/s)*erf(sqrt(a/s)), S.true, S.Zero, dco), # 4.9.35 (sqrt(t)*sinh(2*sqrt(a*t)), pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a)*\ exp(a/s)*erf(sqrt(a/s))-a**(S(1)/2)*s**(-2), S.true, S.Zero, dco), # 4.9.36 (sqrt(t)*cosh(2*sqrt(a*t)), pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a)*exp(a/s), S.true, S.Zero, dco), # 4.9.37 (sinh(2*sqrt(a*t))/sqrt(t), pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s)*\ erf(sqrt(a/s)), S.true, S.Zero, dco), # 4.9.38 (cosh(2*sqrt(a*t))/sqrt(t), pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s), S.true, S.Zero, dco), # 4.9.39 (sinh(sqrt(a*t))**2/sqrt(t), pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)-1), S.true, S.Zero, dco), # 4.9.40 (cosh(sqrt(a*t))**2/sqrt(t), pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)+1), S.true, S.Zero, dco), # 4.9.41 (erf(a*t), exp(s**2/(2*a)**2)*erfc(s/(2*a))/s, 4*Abs(arg(a))<pi, S.Zero, dco), # 4.12.2 (erf(sqrt(a*t)), sqrt(a)/sqrt(s+a)/s, S.true, Max(S.Zero, -re(a)), dco), # 4.12.4 (exp(a*t)*erf(sqrt(a*t)), sqrt(a)/sqrt(s)/(s-a), S.true, Max(S.Zero, re(a)), dco), # 4.12.5 (erf(sqrt(a/t)/2), (1-exp(-sqrt(a*s)))/s, re(a)>0, S.Zero, dco), # 4.12.6 (erfc(sqrt(a*t)), (sqrt(s+a)-sqrt(a))/sqrt(s+a)/s, S.true, -re(a), dco), # 4.12.9 (exp(a*t)*erfc(sqrt(a*t)), 1/(s+sqrt(a*s)), S.true, S.Zero, dco), # 4.12.10 (erfc(sqrt(a/t)/2), exp(-sqrt(a*s))/s, re(a)>0, S.Zero, dco), # 4.2.11 (besselj(n, a*t), a**n/(sqrt(s**2+a**2)*(s+sqrt(s**2+a**2))**n), re(n)>-1, Abs(im(a)), dco), # 4.14.1 (t**b*besselj(n, a*t), 2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2+a**2)**(-n-S.Half), And(re(n)>-S.Half, Eq(b, n)), Abs(im(a)), dco), # 4.14.7 (t**b*besselj(n, a*t), 2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2+a**2)**(-n-S(3)/2), And(re(n)>-1, Eq(b, n+1)), Abs(im(a)), dco), # 4.14.8 (besselj(0, 2*sqrt(a*t)), exp(-a/s)/s, S.true, S.Zero, dco), # 4.14.25 (t**(b)*besselj(n, 2*sqrt(a*t)), a**(n/2)*s**(-n-1)*exp(-a/s), And(re(n)>-1, Eq(b, n*S.Half)), S.Zero, dco), # 4.14.30 (besselj(0, a*sqrt(t**2+b*t)), exp(b*s-b*sqrt(s**2+a**2))/sqrt(s**2+a**2), Abs(arg(b))<pi, Abs(im(a)), dco), # 4.15.19 (besseli(n, a*t), a**n/(sqrt(s**2-a**2)*(s+sqrt(s**2-a**2))**n), re(n)>-1, Abs(re(a)), dco), # 4.16.1 (t**b*besseli(n, a*t), 2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2-a**2)**(-n-S.Half), And(re(n)>-S.Half, Eq(b, n)), Abs(re(a)), dco), # 4.16.6 (t**b*besseli(n, a*t), 2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2-a**2)**(-n-S(3)/2), And(re(n)>-1, Eq(b, n+1)), Abs(re(a)), dco), # 4.16.7 (t**(b)*besseli(n, 2*sqrt(a*t)), a**(n/2)*s**(-n-1)*exp(a/s), And(re(n)>-1, Eq(b, n*S.Half)), S.Zero, dco), # 4.16.18 (bessely(0, a*t), -2/pi*asinh(s/a)/sqrt(s**2+a**2), S.true, Abs(im(a)), dco), # 4.15.44 (besselk(0, a*t), log((s + sqrt(s**2-a**2))/a)/(sqrt(s**2-a**2)), S.true, -re(a), dco) # 4.16.23 ] return laplace_transform_rules def _laplace_rule_timescale(f, t, s): """ This function applies the time-scaling rule of the Laplace transform in a straight-forward way. For example, if it gets ``(f(a*t), t, s)``, it will compute ``LaplaceTransform(f(t)/a, t, s/a)`` if ``a>0``. """ a = Wild('a', exclude=[t]) g = WildFunction('g', nargs=1) ma1 = f.match(g) if ma1: arg = ma1[g].args[0].collect(t) ma2 = arg.match(a*t) if ma2 and ma2[a].is_positive and not ma2[a]==1: debug('_laplace_apply_prog rules match:') debug(' f: %s _ %s, %s )'%(f, ma1, ma2)) debug(' rule: time scaling (4.1.4)') r, pr, cr = _laplace_transform(1/ma2[a]*ma1[g].func(t), t, s/ma2[a], simplify=False) return (r, pr, cr) return None def _laplace_rule_heaviside(f, t, s): """ This function deals with time-shifted Heaviside step functions. If the time shift is positive, it applies the time-shift rule of the Laplace transform. For example, if it gets ``(Heaviside(t-a)*f(t), t, s)``, it will compute ``exp(-a*s)*LaplaceTransform(f(t+a), t, s)``. If the time shift is negative, the Heaviside function is simply removed as it means nothing to the Laplace transform. The function does not remove a factor ``Heaviside(t)``; this is done by the simple rules. """ a = Wild('a', exclude=[t]) y = Wild('y') g = Wild('g') ma1 = f.match(Heaviside(y)*g) if ma1: ma2 = ma1[y].match(t-a) if ma2 and ma2[a].is_positive: debug('_laplace_apply_prog_rules match:') debug(' f: %s ( %s, %s )'%(f, ma1, ma2)) debug(' rule: time shift (4.1.4)') r, pr, cr = _laplace_transform(ma1[g].subs(t, t+ma2[a]), t, s, simplify=False) return (exp(-ma2[a]*s)*r, pr, cr) if ma2 and ma2[a].is_negative: debug('_laplace_apply_prog_rules match:') debug(' f: %s ( %s, %s )'%(f, ma1, ma2)) debug(' rule: Heaviside factor with negative time shift (4.1.4)') r, pr, cr = _laplace_transform(ma1[g], t, s, simplify=False) return (r, pr, cr) return None def _laplace_rule_exp(f, t, s): """ If this function finds a factor ``exp(a*t)``, it applies the frequency-shift rule of the Laplace transform and adjusts the convergence plane accordingly. For example, if it gets ``(exp(-a*t)*f(t), t, s)``, it will compute ``LaplaceTransform(f(t), t, s+a)``. """ a = Wild('a', exclude=[t]) y = Wild('y') z = Wild('z') ma1 = f.match(exp(y)*z) if ma1: ma2 = ma1[y].collect(t).match(a*t) if ma2: debug('_laplace_apply_prog_rules match:') debug(' f: %s ( %s, %s )'%(f, ma1, ma2)) debug(' rule: multiply with exp (4.1.5)') r, pr, cr = _laplace_transform(ma1[z], t, s-ma2[a], simplify=False) return (r, pr+re(ma2[a]), cr) return None def _laplace_rule_delta(f, t, s): """ If this function finds a factor ``DiracDelta(b*t-a)``, it applies the masking property of the delta distribution. For example, if it gets ``(DiracDelta(t-a)*f(t), t, s)``, it will return ``(f(a)*exp(-a*s), -a, True)``. """ # This rule is not in Bateman54 a = Wild('a', exclude=[t]) b = Wild('b', exclude=[t]) y = Wild('y') z = Wild('z') ma1 = f.match(DiracDelta(y)*z) if ma1 and not ma1[z].has(DiracDelta): ma2 = ma1[y].collect(t).match(b*t-a) if ma2: debug('_laplace_apply_prog_rules match:') debug(' f: %s ( %s, %s )'%(f, ma1, ma2)) debug(' rule: multiply with DiracDelta') loc = ma2[a]/ma2[b] if re(loc)>=0 and im(loc)==0: r = exp(-ma2[a]/ma2[b]*s)*ma1[z].subs(t, ma2[a]/ma2[b])/ma2[b] return (r, S.NegativeInfinity, S.true) else: return (0, S.NegativeInfinity, S.true) if ma1[y].is_polynomial(t): ro = roots(ma1[y], t) if not roots is {} and set(ro.values())=={1}: slope = diff(ma1[y], t) r = Add(*[ exp(-x*s)*ma1[z].subs(t, s)/slope.subs(t, x) for x in list(ro.keys()) if im(x)==0 and re(x)>=0 ]) return (r, S.NegativeInfinity, S.true) return None def _laplace_rule_trig(f, t, s, doit=True, **hints): """ This function covers trigonometric factors. All of the rules have a similar form: ``trig(y)*z`` is matched, and then two copies of the Laplace transform of `z` are shifted in the s Domain and added with a weight. The parameters in the tuples are (fm, nu, s1, s2, sd): fm: Function to match nu: Number of the rule, for debug purposes s1: weight of the sum, 'I' for sin and '1' for all others s2: sign of the second copy of the Laplace transform of z sd: shift direction; shift along real or imaginary axis if `1` or `I` The convergence plane is changed only if a frequency shift is done along the real axis. """ # These rules follow from Bateman54, 4.1.5 and Euler's formulas a = Wild('a', exclude=[t]) y = Wild('y') z = Wild('z') trigrules = [(sinh(y), '1.6', 1, -1, 1), (cosh(y), '1.7', 1, 1, 1), (sin(y), '1.8', -I, -1, I), (cos(y), '1.9', 1, 1, I)] for trigrule in trigrules: fm, nu, s1, s2, sd = trigrule ma1 = f.match(z*fm) if ma1: ma2 = ma1[y].collect(t).match(a*t) if ma2: debug('_laplace_apply_rules match:') debug(' f: %s ( %s, %s )'%(f, ma1, ma2)) debug(' rule: multiply with %s (%s)'%(fm.func, nu)) r, pr, cr = _laplace_transform(ma1[z], t, s, simplify=False) if sd==1: cp_shift = Abs(re(ma2[a])) else: cp_shift = Abs(im(ma2[a])) return ((s1*(r.subs(s, s-sd*ma2[a])+\ s2*r.subs(s, s+sd*ma2[a])))/2, pr+cp_shift, cr) return None def _laplace_rule_diff(f, t, s, doit=True, **hints): """ This function looks for derivatives in the time domain and replaces it by factors of `s` and initial conditions in the frequency domain. For example, if it gets ``(diff(f(t), t), t, s)``, it will compute ``s*LaplaceTransform(f(t), t, s) - f(0)``. """ a = Wild('a', exclude=[t]) y = Wild('y') n = Wild('n', exclude=[t]) g = WildFunction('g', nargs=1) ma1 = f.match(a*Derivative(g, (t, n))) if ma1 and ma1[g].args[0] == t and ma1[n].is_integer: debug('_laplace_apply_rules match:') debug(' f, n: %s, %s'%(f, ma1[n])) debug(' rule: time derivative (4.1.8)') d = [] for k in range(ma1[n]): if k==0: y = ma1[g].func(t).subs(t, 0) else: y = Derivative(ma1[g].func(t), (t, k)).subs(t, 0) d.append(s**(ma1[n]-k-1)*y) r, pr, cr = _laplace_transform(ma1[g].func(t), t, s, simplify=False) return (ma1[a]*(s**ma1[n]*r - Add(*d)), pr, cr) return None def _laplace_rule_sdiff(f, t, s, doit=True, **hints): """ This function looks for multiplications with polynoimials in `t` as they correspond to differentiation in the frequency domain. For example, if it gets ``(t*f(t), t, s)``, it will compute ``-Derivative(LaplaceTransform(f(t), t, s), s)``. """ if f.is_Mul: pfac = [1] ofac = [1] for fac in Mul.make_args(f): if fac.is_polynomial(t): pfac.append(fac) else: ofac.append(fac) if len(pfac)>1: pex = prod(pfac) pc = Poly(pex, t).all_coeffs() N = len(pc) if N>1: debug('_laplace_apply_rules match:') debug(' f, n: %s, %s'%(f, pfac)) debug(' rule: frequency derivative (4.1.6)') oex = prod(ofac) r_, p_, c_ = _laplace_transform(oex, t, s, simplify=False) deri = [r_] d1 = False try: d1 = -diff(deri[-1], s) except ValueError: d1 = False if r_.has(LaplaceTransform): for k in range(N-1): deri.append((-1)**(k+1)*Derivative(r_, s, k+1)) else: if d1: deri.append(d1) for k in range(N-2): deri.append(-diff(deri[-1], s)) if d1: r = Add(*[ pc[N-n-1]*deri[n] for n in range(N) ]) return (r, p_, c_) return None def _laplace_expand(f, t, s, doit=True, **hints): """ This function tries to expand its argument with successively stronger methods: first it will expand on the top level, then it will expand any multiplications in depth, then it will try all avilable expansion methods, and finally it will try to expand trigonometric functions. If it can expand, it will then compute the Laplace transform of the expanded term. """ if f.is_Add: return None r = expand(f, deep=False) if r.is_Add: return _laplace_transform(r, t, s, simplify=False) r = expand_mul(f) if r.is_Add: return _laplace_transform(r, t, s, simplify=False) r = expand(f) if r.is_Add: return _laplace_transform(r, t, s, simplify=False) if not r==f: return _laplace_transform(r, t, s, simplify=False) r = expand(expand_trig(f)) if r.is_Add: return _laplace_transform(r, t, s, simplify=False) return None def _laplace_apply_prog_rules(f, t, s): """ This function applies all program rules and returns the result if one of them gives a result. """ prog_rules = [_laplace_rule_heaviside, _laplace_rule_delta, _laplace_rule_timescale, _laplace_rule_exp, _laplace_rule_trig, _laplace_rule_diff, _laplace_rule_sdiff] for p_rule in prog_rules: if (L := p_rule(f, t, s)) is not None: return L return None def _laplace_apply_simple_rules(f, t, s): """ This function applies all simple rules and returns the result if one of them gives a result. """ simple_rules = _laplace_build_rules(t, s) prep_old = '' prep_f = '' for t_dom, s_dom, check, plane, prep in simple_rules: if not prep_old==prep: prep_f = prep(f) prep_old = prep ma = prep_f.match(t_dom) if ma: try: c = check.xreplace(ma) except TypeError: # This may happen if the time function has imaginary # numbers in it. Then we give up. continue if c==True: debug('_laplace_apply_simple_rules match:') debug(' f: %s'%(f,)) debug(' rule: %s o---o %s'%(t_dom, s_dom)) debug(' match: %s'%(ma, )) return (s_dom.xreplace(ma), plane.xreplace(ma), c) return None def _laplace_transform(fn, t_, s_, simplify=True): """ Front-end function of the Laplace transform. It tries to apply all known rules recursively, and if everything else fails, it tries to integrate. """ debug('[LT _l_t] (%s, %s, %s)'%(fn, t_, s_)) terms = Add.make_args(fn) terms_s = [] planes = [] conditions = [] for ff in terms: k, ft = ff.as_independent(t_, as_Add=False) if (r := _laplace_apply_simple_rules(ft, t_, s_)) is not None: pass elif (r := _laplace_apply_prog_rules(ft, t_, s_)) is not None: pass elif (r := _laplace_expand(ft, t_, s_)) is not None: pass elif any(undef.has(t_) for undef in ft.atoms(AppliedUndef)): # If there are undefined functions f(t) then integration is # unlikely to do anything useful so we skip it and given an # unevaluated LaplaceTransform. r = (LaplaceTransform(ft, t_, s_), S.NegativeInfinity, True) elif (r := _laplace_transform_integration(ft, t_, s_, simplify=simplify)) is not None: pass else: r = (LaplaceTransform(ft, t_, s_), S.NegativeInfinity, True) (ri_, pi_, ci_) = r terms_s.append(k*ri_) planes.append(pi_) conditions.append(ci_) result = Add(*terms_s) if simplify: result = result.simplify(doit=False) plane = Max(*planes) condition = And(*conditions) return result, plane, condition class LaplaceTransform(IntegralTransform): """ Class representing unevaluated Laplace transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute Laplace transforms, see the :func:`laplace_transform` docstring. If this is called with ``.doit()``, it returns the Laplace transform as an expression. If it is called with ``.doit(noconds=False)``, it returns a tuple containing the same expression, a convergence plane, and conditions. """ _name = 'Laplace' def _compute_transform(self, f, t, s, **hints): _simplify = hints.get('simplify', False) LT = _laplace_transform_integration(f, t, s, simplify=_simplify) return LT def _as_integral(self, f, t, s): return Integral(f*exp(-s*t), (t, S.Zero, S.Infinity)) def _collapse_extra(self, extra): conds = [] planes = [] for plane, cond in extra: conds.append(cond) planes.append(plane) cond = And(*conds) plane = Max(*planes) if cond == False: raise IntegralTransformError( 'Laplace', None, 'No combined convergence.') return plane, cond def doit(self, **hints): """ Try to evaluate the transform in closed form. Explanation =========== Standard hints are the following: - ``noconds``: if True, do not return convergence conditions. The default setting is `False`. - ``simplify``: if True, it simplifies the final result. This is the default behaviour """ _noconds = hints.get('noconds', True) _simplify = hints.get('simplify', True) debug('[LT doit] (%s, %s, %s)'%(self.function, self.function_variable, self.transform_variable)) t_ = self.function_variable s_ = self.transform_variable fn = self.function r = _laplace_transform(fn, t_, s_, simplify=_simplify) if _noconds: return r[0] else: return r def laplace_transform(f, t, s, legacy_matrix=True, **hints): r""" Compute the Laplace Transform `F(s)` of `f(t)`, .. math :: F(s) = \int_{0^{-}}^\infty e^{-st} f(t) \mathrm{d}t. Explanation =========== For all sensible functions, this converges absolutely in a half-plane .. math :: a < \operatorname{Re}(s) This function returns ``(F, a, cond)`` where ``F`` is the Laplace transform of ``f``, `a` is the half-plane of convergence, and `cond` are auxiliary convergence conditions. The implementation is rule-based, and if you are interested in which rules are applied, and whether integration is attempted, you can switch debug information on by setting ``sympy.SYMPY_DEBUG=True``. The numbers of the rules in the debug information (and the code) refer to Bateman's Tables of Integral Transforms [1]. The lower bound is `0-`, meaning that this bound should be approached from the lower side. This is only necessary if distributions are involved. At present, it is only done if `f(t)` contains ``DiracDelta``, in which case the Laplace transform is computed implicitly as .. math :: F(s) = \lim_{\tau\to 0^{-}} \int_{\tau}^\infty e^{-st} f(t) \mathrm{d}t by applying rules. If the Laplace transform cannot be fully computed in closed form, this function returns expressions containing unevaluated :class:`LaplaceTransform` objects. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. If ``noconds=True``, only `F` will be returned (i.e. not ``cond``, and also not the plane ``a``). .. deprecated:: 1.9 Legacy behavior for matrices where ``laplace_transform`` with ``noconds=False`` (the default) returns a Matrix whose elements are tuples. The behavior of ``laplace_transform`` for matrices will change in a future release of SymPy to return a tuple of the transformed Matrix and the convergence conditions for the matrix as a whole. Use ``legacy_matrix=False`` to enable the new behavior. Examples ======== >>> from sympy import DiracDelta, exp, laplace_transform >>> from sympy.abc import t, s, a >>> laplace_transform(t**4, t, s) (24/s**5, 0, True) >>> laplace_transform(t**a, t, s) (s**(-a - 1)*gamma(a + 1), 0, re(a) > -1) >>> laplace_transform(DiracDelta(t)-a*exp(-a*t), t, s) (s/(a + s), -a, True) References ========== .. [1] Erdelyi, A. (ed.), Tables of Integral Transforms, Volume 1, Bateman Manuscript Prooject, McGraw-Hill (1954), available: https://resolver.caltech.edu/CaltechAUTHORS:20140123-101456353 See Also ======== inverse_laplace_transform, mellin_transform, fourier_transform hankel_transform, inverse_hankel_transform """ _noconds = hints.get('noconds', False) _simplify = hints.get('simplify', True) if isinstance(f, MatrixBase) and hasattr(f, 'applyfunc'): conds = not hints.get('noconds', False) if conds and legacy_matrix: sympy_deprecation_warning( """ Calling laplace_transform() on a Matrix with noconds=False (the default) is deprecated. Either noconds=True or use legacy_matrix=False to get the new behavior. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-laplace-transform-matrix", ) # Temporarily disable the deprecation warning for non-Expr objects # in Matrix with ignore_warnings(SymPyDeprecationWarning): return f.applyfunc(lambda fij: laplace_transform(fij, t, s, **hints)) else: elements_trans = [laplace_transform(fij, t, s, **hints) for fij in f] if conds: elements, avals, conditions = zip(*elements_trans) f_laplace = type(f)(*f.shape, elements) return f_laplace, Max(*avals), And(*conditions) else: return type(f)(*f.shape, elements_trans) LT = LaplaceTransform(f, t, s).doit(noconds=False, simplify=_simplify) if not _noconds: return LT else: return LT[0] @_noconds_(True) def _inverse_laplace_transform(F, s, t_, plane, simplify=True): """ The backend function for inverse Laplace transforms. """ from sympy.integrals.meijerint import meijerint_inversion, _get_coeff_exp # There are two strategies we can try: # 1) Use inverse mellin transforms - related by a simple change of variables. # 2) Use the inversion integral. t = Dummy('t', real=True) def pw_simp(*args): """ Simplify a piecewise expression from hyperexpand. """ # XXX we break modularity here! if len(args) != 3: return Piecewise(*args) arg = args[2].args[0].argument coeff, exponent = _get_coeff_exp(arg, t) e1 = args[0].args[0] e2 = args[1].args[0] return Heaviside(1/Abs(coeff) - t**exponent)*e1 \ + Heaviside(t**exponent - 1/Abs(coeff))*e2 if F.is_rational_function(s): F = F.apart(s) if F.is_Add: f = Add(*[_inverse_laplace_transform(X, s, t, plane, simplify)\ for X in F.args]) return _simplify(f.subs(t, t_), simplify), True try: f, cond = inverse_mellin_transform(F, s, exp(-t), (None, S.Infinity), needeval=True, noconds=False) except IntegralTransformError: f = None if f is None: f = meijerint_inversion(F, s, t) if f is None: raise IntegralTransformError('Inverse Laplace', f, '') if f.is_Piecewise: f, cond = f.args[0] if f.has(Integral): raise IntegralTransformError('Inverse Laplace', f, 'inversion integral of unrecognised form.') else: cond = S.true f = f.replace(Piecewise, pw_simp) if f.is_Piecewise: # many of the functions called below can't work with piecewise # (b/c it has a bool in args) return f.subs(t, t_), cond u = Dummy('u') def simp_heaviside(arg, H0=S.Half): a = arg.subs(exp(-t), u) if a.has(t): return Heaviside(arg, H0) from sympy.solvers.inequalities import _solve_inequality rel = _solve_inequality(a > 0, u) if rel.lts == u: k = log(rel.gts) return Heaviside(t + k, H0) else: k = log(rel.lts) return Heaviside(-(t + k), H0) f = f.replace(Heaviside, simp_heaviside) def simp_exp(arg): return expand_complex(exp(arg)) f = f.replace(exp, simp_exp) # TODO it would be nice to fix cosh and sinh ... simplify messes these # exponentials up return _simplify(f.subs(t, t_), simplify), cond class InverseLaplaceTransform(IntegralTransform): """ Class representing unevaluated inverse Laplace transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse Laplace transforms, see the :func:`inverse_laplace_transform` docstring. """ _name = 'Inverse Laplace' _none_sentinel = Dummy('None') _c = Dummy('c') def __new__(cls, F, s, x, plane, **opts): if plane is None: plane = InverseLaplaceTransform._none_sentinel return IntegralTransform.__new__(cls, F, s, x, plane, **opts) @property def fundamental_plane(self): plane = self.args[3] if plane is InverseLaplaceTransform._none_sentinel: plane = None return plane def _compute_transform(self, F, s, t, **hints): return _inverse_laplace_transform(F, s, t, self.fundamental_plane, **hints) def _as_integral(self, F, s, t): c = self.__class__._c return Integral(exp(s*t)*F, (s, c - S.ImaginaryUnit*S.Infinity, c + S.ImaginaryUnit*S.Infinity))/(2*S.Pi*S.ImaginaryUnit) def inverse_laplace_transform(F, s, t, plane=None, **hints): r""" Compute the inverse Laplace transform of `F(s)`, defined as .. math :: f(t) = \frac{1}{2\pi i} \int_{c-i\infty}^{c+i\infty} e^{st} F(s) \mathrm{d}s, for `c` so large that `F(s)` has no singularites in the half-plane `\operatorname{Re}(s) > c-\epsilon`. Explanation =========== The plane can be specified by argument ``plane``, but will be inferred if passed as None. Under certain regularity conditions, this recovers `f(t)` from its Laplace Transform `F(s)`, for non-negative `t`, and vice versa. If the integral cannot be computed in closed form, this function returns an unevaluated :class:`InverseLaplaceTransform` object. Note that this function will always assume `t` to be real, regardless of the SymPy assumption on `t`. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Examples ======== >>> from sympy import inverse_laplace_transform, exp, Symbol >>> from sympy.abc import s, t >>> a = Symbol('a', positive=True) >>> inverse_laplace_transform(exp(-a*s)/s, s, t) Heaviside(-a + t) See Also ======== laplace_transform, _fast_inverse_laplace hankel_transform, inverse_hankel_transform """ if isinstance(F, MatrixBase) and hasattr(F, 'applyfunc'): return F.applyfunc(lambda Fij: inverse_laplace_transform(Fij, s, t, plane, **hints)) return InverseLaplaceTransform(F, s, t, plane).doit(**hints) def _fast_inverse_laplace(e, s, t): """Fast inverse Laplace transform of rational function including RootSum""" a, b, n = symbols('a, b, n', cls=Wild, exclude=[s]) def _ilt(e): if not e.has(s): return e elif e.is_Add: return _ilt_add(e) elif e.is_Mul: return _ilt_mul(e) elif e.is_Pow: return _ilt_pow(e) elif isinstance(e, RootSum): return _ilt_rootsum(e) else: raise NotImplementedError def _ilt_add(e): return e.func(*map(_ilt, e.args)) def _ilt_mul(e): coeff, expr = e.as_independent(s) if expr.is_Mul: raise NotImplementedError return coeff * _ilt(expr) def _ilt_pow(e): match = e.match((a*s + b)**n) if match is not None: nm, am, bm = match[n], match[a], match[b] if nm.is_Integer and nm < 0: return t**(-nm-1)*exp(-(bm/am)*t)/(am**-nm*gamma(-nm)) if nm == 1: return exp(-(bm/am)*t) / am raise NotImplementedError def _ilt_rootsum(e): expr = e.fun.expr [variable] = e.fun.variables return RootSum(e.poly, Lambda(variable, together(_ilt(expr)))) return _ilt(e) ########################################################################## # Fourier Transform ########################################################################## @_noconds_(True) def _fourier_transform(f, x, k, a, b, name, simplify=True): r""" Compute a general Fourier-type transform .. math:: F(k) = a \int_{-\infty}^{\infty} e^{bixk} f(x)\, dx. For suitable choice of *a* and *b*, this reduces to the standard Fourier and inverse Fourier transforms. """ F = integrate(a*f*exp(b*S.ImaginaryUnit*x*k), (x, S.NegativeInfinity, S.Infinity)) if not F.has(Integral): return _simplify(F, simplify), S.true integral_f = integrate(f, (x, S.NegativeInfinity, S.Infinity)) if integral_f in (S.NegativeInfinity, S.Infinity, S.NaN) or integral_f.has(Integral): raise IntegralTransformError(name, f, 'function not integrable on real axis') if not F.is_Piecewise: raise IntegralTransformError(name, f, 'could not compute integral') F, cond = F.args[0] if F.has(Integral): raise IntegralTransformError(name, f, 'integral in unexpected form') return _simplify(F, simplify), cond class FourierTypeTransform(IntegralTransform): """ Base class for Fourier transforms.""" def a(self): raise NotImplementedError( "Class %s must implement a(self) but does not" % self.__class__) def b(self): raise NotImplementedError( "Class %s must implement b(self) but does not" % self.__class__) def _compute_transform(self, f, x, k, **hints): return _fourier_transform(f, x, k, self.a(), self.b(), self.__class__._name, **hints) def _as_integral(self, f, x, k): a = self.a() b = self.b() return Integral(a*f*exp(b*S.ImaginaryUnit*x*k), (x, S.NegativeInfinity, S.Infinity)) class FourierTransform(FourierTypeTransform): """ Class representing unevaluated Fourier transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute Fourier transforms, see the :func:`fourier_transform` docstring. """ _name = 'Fourier' def a(self): return 1 def b(self): return -2*S.Pi def fourier_transform(f, x, k, **hints): r""" Compute the unitary, ordinary-frequency Fourier transform of ``f``, defined as .. math:: F(k) = \int_{-\infty}^\infty f(x) e^{-2\pi i x k} \mathrm{d} x. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`FourierTransform` object. For other Fourier transform conventions, see the function :func:`sympy.integrals.transforms._fourier_transform`. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import fourier_transform, exp >>> from sympy.abc import x, k >>> fourier_transform(exp(-x**2), x, k) sqrt(pi)*exp(-pi**2*k**2) >>> fourier_transform(exp(-x**2), x, k, noconds=False) (sqrt(pi)*exp(-pi**2*k**2), True) See Also ======== inverse_fourier_transform sine_transform, inverse_sine_transform cosine_transform, inverse_cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return FourierTransform(f, x, k).doit(**hints) class InverseFourierTransform(FourierTypeTransform): """ Class representing unevaluated inverse Fourier transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse Fourier transforms, see the :func:`inverse_fourier_transform` docstring. """ _name = 'Inverse Fourier' def a(self): return 1 def b(self): return 2*S.Pi def inverse_fourier_transform(F, k, x, **hints): r""" Compute the unitary, ordinary-frequency inverse Fourier transform of `F`, defined as .. math:: f(x) = \int_{-\infty}^\infty F(k) e^{2\pi i x k} \mathrm{d} k. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`InverseFourierTransform` object. For other Fourier transform conventions, see the function :func:`sympy.integrals.transforms._fourier_transform`. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import inverse_fourier_transform, exp, sqrt, pi >>> from sympy.abc import x, k >>> inverse_fourier_transform(sqrt(pi)*exp(-(pi*k)**2), k, x) exp(-x**2) >>> inverse_fourier_transform(sqrt(pi)*exp(-(pi*k)**2), k, x, noconds=False) (exp(-x**2), True) See Also ======== fourier_transform sine_transform, inverse_sine_transform cosine_transform, inverse_cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return InverseFourierTransform(F, k, x).doit(**hints) ########################################################################## # Fourier Sine and Cosine Transform ########################################################################## @_noconds_(True) def _sine_cosine_transform(f, x, k, a, b, K, name, simplify=True): """ Compute a general sine or cosine-type transform F(k) = a int_0^oo b*sin(x*k) f(x) dx. F(k) = a int_0^oo b*cos(x*k) f(x) dx. For suitable choice of a and b, this reduces to the standard sine/cosine and inverse sine/cosine transforms. """ F = integrate(a*f*K(b*x*k), (x, S.Zero, S.Infinity)) if not F.has(Integral): return _simplify(F, simplify), S.true if not F.is_Piecewise: raise IntegralTransformError(name, f, 'could not compute integral') F, cond = F.args[0] if F.has(Integral): raise IntegralTransformError(name, f, 'integral in unexpected form') return _simplify(F, simplify), cond class SineCosineTypeTransform(IntegralTransform): """ Base class for sine and cosine transforms. Specify cls._kern. """ def a(self): raise NotImplementedError( "Class %s must implement a(self) but does not" % self.__class__) def b(self): raise NotImplementedError( "Class %s must implement b(self) but does not" % self.__class__) def _compute_transform(self, f, x, k, **hints): return _sine_cosine_transform(f, x, k, self.a(), self.b(), self.__class__._kern, self.__class__._name, **hints) def _as_integral(self, f, x, k): a = self.a() b = self.b() K = self.__class__._kern return Integral(a*f*K(b*x*k), (x, S.Zero, S.Infinity)) class SineTransform(SineCosineTypeTransform): """ Class representing unevaluated sine transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute sine transforms, see the :func:`sine_transform` docstring. """ _name = 'Sine' _kern = sin def a(self): return sqrt(2)/sqrt(pi) def b(self): return S.One def sine_transform(f, x, k, **hints): r""" Compute the unitary, ordinary-frequency sine transform of `f`, defined as .. math:: F(k) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty f(x) \sin(2\pi x k) \mathrm{d} x. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`SineTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import sine_transform, exp >>> from sympy.abc import x, k, a >>> sine_transform(x*exp(-a*x**2), x, k) sqrt(2)*k*exp(-k**2/(4*a))/(4*a**(3/2)) >>> sine_transform(x**(-a), x, k) 2**(1/2 - a)*k**(a - 1)*gamma(1 - a/2)/gamma(a/2 + 1/2) See Also ======== fourier_transform, inverse_fourier_transform inverse_sine_transform cosine_transform, inverse_cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return SineTransform(f, x, k).doit(**hints) class InverseSineTransform(SineCosineTypeTransform): """ Class representing unevaluated inverse sine transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse sine transforms, see the :func:`inverse_sine_transform` docstring. """ _name = 'Inverse Sine' _kern = sin def a(self): return sqrt(2)/sqrt(pi) def b(self): return S.One def inverse_sine_transform(F, k, x, **hints): r""" Compute the unitary, ordinary-frequency inverse sine transform of `F`, defined as .. math:: f(x) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty F(k) \sin(2\pi x k) \mathrm{d} k. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`InverseSineTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import inverse_sine_transform, exp, sqrt, gamma >>> from sympy.abc import x, k, a >>> inverse_sine_transform(2**((1-2*a)/2)*k**(a - 1)* ... gamma(-a/2 + 1)/gamma((a+1)/2), k, x) x**(-a) >>> inverse_sine_transform(sqrt(2)*k*exp(-k**2/(4*a))/(4*sqrt(a)**3), k, x) x*exp(-a*x**2) See Also ======== fourier_transform, inverse_fourier_transform sine_transform cosine_transform, inverse_cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return InverseSineTransform(F, k, x).doit(**hints) class CosineTransform(SineCosineTypeTransform): """ Class representing unevaluated cosine transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute cosine transforms, see the :func:`cosine_transform` docstring. """ _name = 'Cosine' _kern = cos def a(self): return sqrt(2)/sqrt(pi) def b(self): return S.One def cosine_transform(f, x, k, **hints): r""" Compute the unitary, ordinary-frequency cosine transform of `f`, defined as .. math:: F(k) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty f(x) \cos(2\pi x k) \mathrm{d} x. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`CosineTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import cosine_transform, exp, sqrt, cos >>> from sympy.abc import x, k, a >>> cosine_transform(exp(-a*x), x, k) sqrt(2)*a/(sqrt(pi)*(a**2 + k**2)) >>> cosine_transform(exp(-a*sqrt(x))*cos(a*sqrt(x)), x, k) a*exp(-a**2/(2*k))/(2*k**(3/2)) See Also ======== fourier_transform, inverse_fourier_transform, sine_transform, inverse_sine_transform inverse_cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return CosineTransform(f, x, k).doit(**hints) class InverseCosineTransform(SineCosineTypeTransform): """ Class representing unevaluated inverse cosine transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse cosine transforms, see the :func:`inverse_cosine_transform` docstring. """ _name = 'Inverse Cosine' _kern = cos def a(self): return sqrt(2)/sqrt(pi) def b(self): return S.One def inverse_cosine_transform(F, k, x, **hints): r""" Compute the unitary, ordinary-frequency inverse cosine transform of `F`, defined as .. math:: f(x) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty F(k) \cos(2\pi x k) \mathrm{d} k. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`InverseCosineTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import inverse_cosine_transform, sqrt, pi >>> from sympy.abc import x, k, a >>> inverse_cosine_transform(sqrt(2)*a/(sqrt(pi)*(a**2 + k**2)), k, x) exp(-a*x) >>> inverse_cosine_transform(1/sqrt(k), k, x) 1/sqrt(x) See Also ======== fourier_transform, inverse_fourier_transform, sine_transform, inverse_sine_transform cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return InverseCosineTransform(F, k, x).doit(**hints) ########################################################################## # Hankel Transform ########################################################################## @_noconds_(True) def _hankel_transform(f, r, k, nu, name, simplify=True): r""" Compute a general Hankel transform .. math:: F_\nu(k) = \int_{0}^\infty f(r) J_\nu(k r) r \mathrm{d} r. """ F = integrate(f*besselj(nu, k*r)*r, (r, S.Zero, S.Infinity)) if not F.has(Integral): return _simplify(F, simplify), S.true if not F.is_Piecewise: raise IntegralTransformError(name, f, 'could not compute integral') F, cond = F.args[0] if F.has(Integral): raise IntegralTransformError(name, f, 'integral in unexpected form') return _simplify(F, simplify), cond class HankelTypeTransform(IntegralTransform): """ Base class for Hankel transforms. """ def doit(self, **hints): return self._compute_transform(self.function, self.function_variable, self.transform_variable, self.args[3], **hints) def _compute_transform(self, f, r, k, nu, **hints): return _hankel_transform(f, r, k, nu, self._name, **hints) def _as_integral(self, f, r, k, nu): return Integral(f*besselj(nu, k*r)*r, (r, S.Zero, S.Infinity)) @property def as_integral(self): return self._as_integral(self.function, self.function_variable, self.transform_variable, self.args[3]) class HankelTransform(HankelTypeTransform): """ Class representing unevaluated Hankel transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute Hankel transforms, see the :func:`hankel_transform` docstring. """ _name = 'Hankel' def hankel_transform(f, r, k, nu, **hints): r""" Compute the Hankel transform of `f`, defined as .. math:: F_\nu(k) = \int_{0}^\infty f(r) J_\nu(k r) r \mathrm{d} r. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`HankelTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import hankel_transform, inverse_hankel_transform >>> from sympy import exp >>> from sympy.abc import r, k, m, nu, a >>> ht = hankel_transform(1/r**m, r, k, nu) >>> ht 2*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/(2**m*gamma(m/2 + nu/2)) >>> inverse_hankel_transform(ht, k, r, nu) r**(-m) >>> ht = hankel_transform(exp(-a*r), r, k, 0) >>> ht a/(k**3*(a**2/k**2 + 1)**(3/2)) >>> inverse_hankel_transform(ht, k, r, 0) exp(-a*r) See Also ======== fourier_transform, inverse_fourier_transform sine_transform, inverse_sine_transform cosine_transform, inverse_cosine_transform inverse_hankel_transform mellin_transform, laplace_transform """ return HankelTransform(f, r, k, nu).doit(**hints) class InverseHankelTransform(HankelTypeTransform): """ Class representing unevaluated inverse Hankel transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse Hankel transforms, see the :func:`inverse_hankel_transform` docstring. """ _name = 'Inverse Hankel' def inverse_hankel_transform(F, k, r, nu, **hints): r""" Compute the inverse Hankel transform of `F` defined as .. math:: f(r) = \int_{0}^\infty F_\nu(k) J_\nu(k r) k \mathrm{d} k. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`InverseHankelTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import hankel_transform, inverse_hankel_transform >>> from sympy import exp >>> from sympy.abc import r, k, m, nu, a >>> ht = hankel_transform(1/r**m, r, k, nu) >>> ht 2*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/(2**m*gamma(m/2 + nu/2)) >>> inverse_hankel_transform(ht, k, r, nu) r**(-m) >>> ht = hankel_transform(exp(-a*r), r, k, 0) >>> ht a/(k**3*(a**2/k**2 + 1)**(3/2)) >>> inverse_hankel_transform(ht, k, r, 0) exp(-a*r) See Also ======== fourier_transform, inverse_fourier_transform sine_transform, inverse_sine_transform cosine_transform, inverse_cosine_transform hankel_transform mellin_transform, laplace_transform """ return InverseHankelTransform(F, k, r, nu).doit(**hints)
e7ac5e7c2d250cb814e4bec428cac2b85cc0b0e8eef1e9d8483c575867f41cd2
"""Sparse polynomial rings. """ from __future__ import annotations from typing import Any from operator import add, mul, lt, le, gt, ge from functools import reduce from types import GeneratorType from sympy.core.expr import Expr from sympy.core.numbers import igcd, oo from sympy.core.symbol import Symbol, symbols as _symbols from sympy.core.sympify import CantSympify, sympify from sympy.ntheory.multinomial import multinomial_coefficients from sympy.polys.compatibility import IPolys from sympy.polys.constructor import construct_domain from sympy.polys.densebasic import dmp_to_dict, dmp_from_dict from sympy.polys.domains.domainelement import DomainElement from sympy.polys.domains.polynomialring import PolynomialRing from sympy.polys.heuristicgcd import heugcd from sympy.polys.monomials import MonomialOps from sympy.polys.orderings import lex from sympy.polys.polyerrors import ( CoercionFailed, GeneratorsError, ExactQuotientFailed, MultivariatePolynomialError) from sympy.polys.polyoptions import (Domain as DomainOpt, Order as OrderOpt, build_options) from sympy.polys.polyutils import (expr_from_dict, _dict_reorder, _parallel_dict_from_expr) from sympy.printing.defaults import DefaultPrinting from sympy.utilities import public, subsets from sympy.utilities.iterables import is_sequence from sympy.utilities.magic import pollute @public def ring(symbols, domain, order=lex): """Construct a polynomial ring returning ``(ring, x_1, ..., x_n)``. Parameters ========== symbols : str Symbol/Expr or sequence of str, Symbol/Expr (non-empty) domain : :class:`~.Domain` or coercible order : :class:`~.MonomialOrder` or coercible, optional, defaults to ``lex`` Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> from sympy.polys.orderings import lex >>> R, x, y, z = ring("x,y,z", ZZ, lex) >>> R Polynomial ring in x, y, z over ZZ with lex order >>> x + y + z x + y + z >>> type(_) <class 'sympy.polys.rings.PolyElement'> """ _ring = PolyRing(symbols, domain, order) return (_ring,) + _ring.gens @public def xring(symbols, domain, order=lex): """Construct a polynomial ring returning ``(ring, (x_1, ..., x_n))``. Parameters ========== symbols : str Symbol/Expr or sequence of str, Symbol/Expr (non-empty) domain : :class:`~.Domain` or coercible order : :class:`~.MonomialOrder` or coercible, optional, defaults to ``lex`` Examples ======== >>> from sympy.polys.rings import xring >>> from sympy.polys.domains import ZZ >>> from sympy.polys.orderings import lex >>> R, (x, y, z) = xring("x,y,z", ZZ, lex) >>> R Polynomial ring in x, y, z over ZZ with lex order >>> x + y + z x + y + z >>> type(_) <class 'sympy.polys.rings.PolyElement'> """ _ring = PolyRing(symbols, domain, order) return (_ring, _ring.gens) @public def vring(symbols, domain, order=lex): """Construct a polynomial ring and inject ``x_1, ..., x_n`` into the global namespace. Parameters ========== symbols : str Symbol/Expr or sequence of str, Symbol/Expr (non-empty) domain : :class:`~.Domain` or coercible order : :class:`~.MonomialOrder` or coercible, optional, defaults to ``lex`` Examples ======== >>> from sympy.polys.rings import vring >>> from sympy.polys.domains import ZZ >>> from sympy.polys.orderings import lex >>> vring("x,y,z", ZZ, lex) Polynomial ring in x, y, z over ZZ with lex order >>> x + y + z # noqa: x + y + z >>> type(_) <class 'sympy.polys.rings.PolyElement'> """ _ring = PolyRing(symbols, domain, order) pollute([ sym.name for sym in _ring.symbols ], _ring.gens) return _ring @public def sring(exprs, *symbols, **options): """Construct a ring deriving generators and domain from options and input expressions. Parameters ========== exprs : :class:`~.Expr` or sequence of :class:`~.Expr` (sympifiable) symbols : sequence of :class:`~.Symbol`/:class:`~.Expr` options : keyword arguments understood by :class:`~.Options` Examples ======== >>> from sympy import sring, symbols >>> x, y, z = symbols("x,y,z") >>> R, f = sring(x + 2*y + 3*z) >>> R Polynomial ring in x, y, z over ZZ with lex order >>> f x + 2*y + 3*z >>> type(_) <class 'sympy.polys.rings.PolyElement'> """ single = False if not is_sequence(exprs): exprs, single = [exprs], True exprs = list(map(sympify, exprs)) opt = build_options(symbols, options) # TODO: rewrite this so that it doesn't use expand() (see poly()). reps, opt = _parallel_dict_from_expr(exprs, opt) if opt.domain is None: coeffs = sum([ list(rep.values()) for rep in reps ], []) opt.domain, coeffs_dom = construct_domain(coeffs, opt=opt) coeff_map = dict(zip(coeffs, coeffs_dom)) reps = [{m: coeff_map[c] for m, c in rep.items()} for rep in reps] _ring = PolyRing(opt.gens, opt.domain, opt.order) polys = list(map(_ring.from_dict, reps)) if single: return (_ring, polys[0]) else: return (_ring, polys) def _parse_symbols(symbols): if isinstance(symbols, str): return _symbols(symbols, seq=True) if symbols else () elif isinstance(symbols, Expr): return (symbols,) elif is_sequence(symbols): if all(isinstance(s, str) for s in symbols): return _symbols(symbols) elif all(isinstance(s, Expr) for s in symbols): return symbols raise GeneratorsError("expected a string, Symbol or expression or a non-empty sequence of strings, Symbols or expressions") _ring_cache: dict[Any, Any] = {} class PolyRing(DefaultPrinting, IPolys): """Multivariate distributed polynomial ring. """ def __new__(cls, symbols, domain, order=lex): symbols = tuple(_parse_symbols(symbols)) ngens = len(symbols) domain = DomainOpt.preprocess(domain) order = OrderOpt.preprocess(order) _hash_tuple = (cls.__name__, symbols, ngens, domain, order) obj = _ring_cache.get(_hash_tuple) if obj is None: if domain.is_Composite and set(symbols) & set(domain.symbols): raise GeneratorsError("polynomial ring and it's ground domain share generators") obj = object.__new__(cls) obj._hash_tuple = _hash_tuple obj._hash = hash(_hash_tuple) obj.dtype = type("PolyElement", (PolyElement,), {"ring": obj}) obj.symbols = symbols obj.ngens = ngens obj.domain = domain obj.order = order obj.zero_monom = (0,)*ngens obj.gens = obj._gens() obj._gens_set = set(obj.gens) obj._one = [(obj.zero_monom, domain.one)] if ngens: # These expect monomials in at least one variable codegen = MonomialOps(ngens) obj.monomial_mul = codegen.mul() obj.monomial_pow = codegen.pow() obj.monomial_mulpow = codegen.mulpow() obj.monomial_ldiv = codegen.ldiv() obj.monomial_div = codegen.div() obj.monomial_lcm = codegen.lcm() obj.monomial_gcd = codegen.gcd() else: monunit = lambda a, b: () obj.monomial_mul = monunit obj.monomial_pow = monunit obj.monomial_mulpow = lambda a, b, c: () obj.monomial_ldiv = monunit obj.monomial_div = monunit obj.monomial_lcm = monunit obj.monomial_gcd = monunit if order is lex: obj.leading_expv = max else: obj.leading_expv = lambda f: max(f, key=order) for symbol, generator in zip(obj.symbols, obj.gens): if isinstance(symbol, Symbol): name = symbol.name if not hasattr(obj, name): setattr(obj, name, generator) _ring_cache[_hash_tuple] = obj return obj def _gens(self): """Return a list of polynomial generators. """ one = self.domain.one _gens = [] for i in range(self.ngens): expv = self.monomial_basis(i) poly = self.zero poly[expv] = one _gens.append(poly) return tuple(_gens) def __getnewargs__(self): return (self.symbols, self.domain, self.order) def __getstate__(self): state = self.__dict__.copy() del state["leading_expv"] for key, value in state.items(): if key.startswith("monomial_"): del state[key] return state def __hash__(self): return self._hash def __eq__(self, other): return isinstance(other, PolyRing) and \ (self.symbols, self.domain, self.ngens, self.order) == \ (other.symbols, other.domain, other.ngens, other.order) def __ne__(self, other): return not self == other def clone(self, symbols=None, domain=None, order=None): return self.__class__(symbols or self.symbols, domain or self.domain, order or self.order) def monomial_basis(self, i): """Return the ith-basis element. """ basis = [0]*self.ngens basis[i] = 1 return tuple(basis) @property def zero(self): return self.dtype() @property def one(self): return self.dtype(self._one) def domain_new(self, element, orig_domain=None): return self.domain.convert(element, orig_domain) def ground_new(self, coeff): return self.term_new(self.zero_monom, coeff) def term_new(self, monom, coeff): coeff = self.domain_new(coeff) poly = self.zero if coeff: poly[monom] = coeff return poly def ring_new(self, element): if isinstance(element, PolyElement): if self == element.ring: return element elif isinstance(self.domain, PolynomialRing) and self.domain.ring == element.ring: return self.ground_new(element) else: raise NotImplementedError("conversion") elif isinstance(element, str): raise NotImplementedError("parsing") elif isinstance(element, dict): return self.from_dict(element) elif isinstance(element, list): try: return self.from_terms(element) except ValueError: return self.from_list(element) elif isinstance(element, Expr): return self.from_expr(element) else: return self.ground_new(element) __call__ = ring_new def from_dict(self, element, orig_domain=None): domain_new = self.domain_new poly = self.zero for monom, coeff in element.items(): coeff = domain_new(coeff, orig_domain) if coeff: poly[monom] = coeff return poly def from_terms(self, element, orig_domain=None): return self.from_dict(dict(element), orig_domain) def from_list(self, element): return self.from_dict(dmp_to_dict(element, self.ngens-1, self.domain)) def _rebuild_expr(self, expr, mapping): domain = self.domain def _rebuild(expr): generator = mapping.get(expr) if generator is not None: return generator elif expr.is_Add: return reduce(add, list(map(_rebuild, expr.args))) elif expr.is_Mul: return reduce(mul, list(map(_rebuild, expr.args))) else: # XXX: Use as_base_exp() to handle Pow(x, n) and also exp(n) # XXX: E can be a generator e.g. sring([exp(2)]) -> ZZ[E] base, exp = expr.as_base_exp() if exp.is_Integer and exp > 1: return _rebuild(base)**int(exp) else: return self.ground_new(domain.convert(expr)) return _rebuild(sympify(expr)) def from_expr(self, expr): mapping = dict(list(zip(self.symbols, self.gens))) try: poly = self._rebuild_expr(expr, mapping) except CoercionFailed: raise ValueError("expected an expression convertible to a polynomial in %s, got %s" % (self, expr)) else: return self.ring_new(poly) def index(self, gen): """Compute index of ``gen`` in ``self.gens``. """ if gen is None: if self.ngens: i = 0 else: i = -1 # indicate impossible choice elif isinstance(gen, int): i = gen if 0 <= i and i < self.ngens: pass elif -self.ngens <= i and i <= -1: i = -i - 1 else: raise ValueError("invalid generator index: %s" % gen) elif isinstance(gen, self.dtype): try: i = self.gens.index(gen) except ValueError: raise ValueError("invalid generator: %s" % gen) elif isinstance(gen, str): try: i = self.symbols.index(gen) except ValueError: raise ValueError("invalid generator: %s" % gen) else: raise ValueError("expected a polynomial generator, an integer, a string or None, got %s" % gen) return i def drop(self, *gens): """Remove specified generators from this ring. """ indices = set(map(self.index, gens)) symbols = [ s for i, s in enumerate(self.symbols) if i not in indices ] if not symbols: return self.domain else: return self.clone(symbols=symbols) def __getitem__(self, key): symbols = self.symbols[key] if not symbols: return self.domain else: return self.clone(symbols=symbols) def to_ground(self): # TODO: should AlgebraicField be a Composite domain? if self.domain.is_Composite or hasattr(self.domain, 'domain'): return self.clone(domain=self.domain.domain) else: raise ValueError("%s is not a composite domain" % self.domain) def to_domain(self): return PolynomialRing(self) def to_field(self): from sympy.polys.fields import FracField return FracField(self.symbols, self.domain, self.order) @property def is_univariate(self): return len(self.gens) == 1 @property def is_multivariate(self): return len(self.gens) > 1 def add(self, *objs): """ Add a sequence of polynomials or containers of polynomials. Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> R, x = ring("x", ZZ) >>> R.add([ x**2 + 2*i + 3 for i in range(4) ]) 4*x**2 + 24 >>> _.factor_list() (4, [(x**2 + 6, 1)]) """ p = self.zero for obj in objs: if is_sequence(obj, include=GeneratorType): p += self.add(*obj) else: p += obj return p def mul(self, *objs): """ Multiply a sequence of polynomials or containers of polynomials. Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> R, x = ring("x", ZZ) >>> R.mul([ x**2 + 2*i + 3 for i in range(4) ]) x**8 + 24*x**6 + 206*x**4 + 744*x**2 + 945 >>> _.factor_list() (1, [(x**2 + 3, 1), (x**2 + 5, 1), (x**2 + 7, 1), (x**2 + 9, 1)]) """ p = self.one for obj in objs: if is_sequence(obj, include=GeneratorType): p *= self.mul(*obj) else: p *= obj return p def drop_to_ground(self, *gens): r""" Remove specified generators from the ring and inject them into its domain. """ indices = set(map(self.index, gens)) symbols = [s for i, s in enumerate(self.symbols) if i not in indices] gens = [gen for i, gen in enumerate(self.gens) if i not in indices] if not symbols: return self else: return self.clone(symbols=symbols, domain=self.drop(*gens)) def compose(self, other): """Add the generators of ``other`` to ``self``""" if self != other: syms = set(self.symbols).union(set(other.symbols)) return self.clone(symbols=list(syms)) else: return self def add_gens(self, symbols): """Add the elements of ``symbols`` as generators to ``self``""" syms = set(self.symbols).union(set(symbols)) return self.clone(symbols=list(syms)) def symmetric_poly(self, n): """Return the symmetric poly of given degree over this ring's gens.""" if n < 0 or n > self.ngens: raise ValueError("Cannot generate symmetric polynomial of order %s for %s" % (n, self.gens)) elif not n: return self.one else: poly = self.zero for s in subsets(range(self.ngens), int(n)): monom = tuple(int(i in s) for i in range(self.ngens)) poly += self.term_new(monom, self.domain.one) return poly class PolyElement(DomainElement, DefaultPrinting, CantSympify, dict): """Element of multivariate distributed polynomial ring. """ def new(self, init): return self.__class__(init) def parent(self): return self.ring.to_domain() def __getnewargs__(self): return (self.ring, list(self.iterterms())) _hash = None def __hash__(self): # XXX: This computes a hash of a dictionary, but currently we don't # protect dictionary from being changed so any use site modifications # will make hashing go wrong. Use this feature with caution until we # figure out how to make a safe API without compromising speed of this # low-level class. _hash = self._hash if _hash is None: self._hash = _hash = hash((self.ring, frozenset(self.items()))) return _hash def copy(self): """Return a copy of polynomial self. Polynomials are mutable; if one is interested in preserving a polynomial, and one plans to use inplace operations, one can copy the polynomial. This method makes a shallow copy. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.rings import ring >>> R, x, y = ring('x, y', ZZ) >>> p = (x + y)**2 >>> p1 = p.copy() >>> p2 = p >>> p[R.zero_monom] = 3 >>> p x**2 + 2*x*y + y**2 + 3 >>> p1 x**2 + 2*x*y + y**2 >>> p2 x**2 + 2*x*y + y**2 + 3 """ return self.new(self) def set_ring(self, new_ring): if self.ring == new_ring: return self elif self.ring.symbols != new_ring.symbols: terms = list(zip(*_dict_reorder(self, self.ring.symbols, new_ring.symbols))) return new_ring.from_terms(terms, self.ring.domain) else: return new_ring.from_dict(self, self.ring.domain) def as_expr(self, *symbols): if not symbols: symbols = self.ring.symbols elif len(symbols) != self.ring.ngens: raise ValueError( "Wrong number of symbols, expected %s got %s" % (self.ring.ngens, len(symbols)) ) return expr_from_dict(self.as_expr_dict(), *symbols) def as_expr_dict(self): to_sympy = self.ring.domain.to_sympy return {monom: to_sympy(coeff) for monom, coeff in self.iterterms()} def clear_denoms(self): domain = self.ring.domain if not domain.is_Field or not domain.has_assoc_Ring: return domain.one, self ground_ring = domain.get_ring() common = ground_ring.one lcm = ground_ring.lcm denom = domain.denom for coeff in self.values(): common = lcm(common, denom(coeff)) poly = self.new([ (k, v*common) for k, v in self.items() ]) return common, poly def strip_zero(self): """Eliminate monomials with zero coefficient. """ for k, v in list(self.items()): if not v: del self[k] def __eq__(p1, p2): """Equality test for polynomials. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.rings import ring >>> _, x, y = ring('x, y', ZZ) >>> p1 = (x + y)**2 + (x - y)**2 >>> p1 == 4*x*y False >>> p1 == 2*(x**2 + y**2) True """ if not p2: return not p1 elif isinstance(p2, PolyElement) and p2.ring == p1.ring: return dict.__eq__(p1, p2) elif len(p1) > 1: return False else: return p1.get(p1.ring.zero_monom) == p2 def __ne__(p1, p2): return not p1 == p2 def almosteq(p1, p2, tolerance=None): """Approximate equality test for polynomials. """ ring = p1.ring if isinstance(p2, ring.dtype): if set(p1.keys()) != set(p2.keys()): return False almosteq = ring.domain.almosteq for k in p1.keys(): if not almosteq(p1[k], p2[k], tolerance): return False return True elif len(p1) > 1: return False else: try: p2 = ring.domain.convert(p2) except CoercionFailed: return False else: return ring.domain.almosteq(p1.const(), p2, tolerance) def sort_key(self): return (len(self), self.terms()) def _cmp(p1, p2, op): if isinstance(p2, p1.ring.dtype): return op(p1.sort_key(), p2.sort_key()) else: return NotImplemented def __lt__(p1, p2): return p1._cmp(p2, lt) def __le__(p1, p2): return p1._cmp(p2, le) def __gt__(p1, p2): return p1._cmp(p2, gt) def __ge__(p1, p2): return p1._cmp(p2, ge) def _drop(self, gen): ring = self.ring i = ring.index(gen) if ring.ngens == 1: return i, ring.domain else: symbols = list(ring.symbols) del symbols[i] return i, ring.clone(symbols=symbols) def drop(self, gen): i, ring = self._drop(gen) if self.ring.ngens == 1: if self.is_ground: return self.coeff(1) else: raise ValueError("Cannot drop %s" % gen) else: poly = ring.zero for k, v in self.items(): if k[i] == 0: K = list(k) del K[i] poly[tuple(K)] = v else: raise ValueError("Cannot drop %s" % gen) return poly def _drop_to_ground(self, gen): ring = self.ring i = ring.index(gen) symbols = list(ring.symbols) del symbols[i] return i, ring.clone(symbols=symbols, domain=ring[i]) def drop_to_ground(self, gen): if self.ring.ngens == 1: raise ValueError("Cannot drop only generator to ground") i, ring = self._drop_to_ground(gen) poly = ring.zero gen = ring.domain.gens[0] for monom, coeff in self.iterterms(): mon = monom[:i] + monom[i+1:] if mon not in poly: poly[mon] = (gen**monom[i]).mul_ground(coeff) else: poly[mon] += (gen**monom[i]).mul_ground(coeff) return poly def to_dense(self): return dmp_from_dict(self, self.ring.ngens-1, self.ring.domain) def to_dict(self): return dict(self) def str(self, printer, precedence, exp_pattern, mul_symbol): if not self: return printer._print(self.ring.domain.zero) prec_mul = precedence["Mul"] prec_atom = precedence["Atom"] ring = self.ring symbols = ring.symbols ngens = ring.ngens zm = ring.zero_monom sexpvs = [] for expv, coeff in self.terms(): negative = ring.domain.is_negative(coeff) sign = " - " if negative else " + " sexpvs.append(sign) if expv == zm: scoeff = printer._print(coeff) if negative and scoeff.startswith("-"): scoeff = scoeff[1:] else: if negative: coeff = -coeff if coeff != self.ring.domain.one: scoeff = printer.parenthesize(coeff, prec_mul, strict=True) else: scoeff = '' sexpv = [] for i in range(ngens): exp = expv[i] if not exp: continue symbol = printer.parenthesize(symbols[i], prec_atom, strict=True) if exp != 1: if exp != int(exp) or exp < 0: sexp = printer.parenthesize(exp, prec_atom, strict=False) else: sexp = exp sexpv.append(exp_pattern % (symbol, sexp)) else: sexpv.append('%s' % symbol) if scoeff: sexpv = [scoeff] + sexpv sexpvs.append(mul_symbol.join(sexpv)) if sexpvs[0] in [" + ", " - "]: head = sexpvs.pop(0) if head == " - ": sexpvs.insert(0, "-") return "".join(sexpvs) @property def is_generator(self): return self in self.ring._gens_set @property def is_ground(self): return not self or (len(self) == 1 and self.ring.zero_monom in self) @property def is_monomial(self): return not self or (len(self) == 1 and self.LC == 1) @property def is_term(self): return len(self) <= 1 @property def is_negative(self): return self.ring.domain.is_negative(self.LC) @property def is_positive(self): return self.ring.domain.is_positive(self.LC) @property def is_nonnegative(self): return self.ring.domain.is_nonnegative(self.LC) @property def is_nonpositive(self): return self.ring.domain.is_nonpositive(self.LC) @property def is_zero(f): return not f @property def is_one(f): return f == f.ring.one @property def is_monic(f): return f.ring.domain.is_one(f.LC) @property def is_primitive(f): return f.ring.domain.is_one(f.content()) @property def is_linear(f): return all(sum(monom) <= 1 for monom in f.itermonoms()) @property def is_quadratic(f): return all(sum(monom) <= 2 for monom in f.itermonoms()) @property def is_squarefree(f): if not f.ring.ngens: return True return f.ring.dmp_sqf_p(f) @property def is_irreducible(f): if not f.ring.ngens: return True return f.ring.dmp_irreducible_p(f) @property def is_cyclotomic(f): if f.ring.is_univariate: return f.ring.dup_cyclotomic_p(f) else: raise MultivariatePolynomialError("cyclotomic polynomial") def __neg__(self): return self.new([ (monom, -coeff) for monom, coeff in self.iterterms() ]) def __pos__(self): return self def __add__(p1, p2): """Add two polynomials. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.rings import ring >>> _, x, y = ring('x, y', ZZ) >>> (x + y)**2 + (x - y)**2 2*x**2 + 2*y**2 """ if not p2: return p1.copy() ring = p1.ring if isinstance(p2, ring.dtype): p = p1.copy() get = p.get zero = ring.domain.zero for k, v in p2.items(): v = get(k, zero) + v if v: p[k] = v else: del p[k] return p elif isinstance(p2, PolyElement): if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: pass elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: return p2.__radd__(p1) else: return NotImplemented try: cp2 = ring.domain_new(p2) except CoercionFailed: return NotImplemented else: p = p1.copy() if not cp2: return p zm = ring.zero_monom if zm not in p1.keys(): p[zm] = cp2 else: if p2 == -p[zm]: del p[zm] else: p[zm] += cp2 return p def __radd__(p1, n): p = p1.copy() if not n: return p ring = p1.ring try: n = ring.domain_new(n) except CoercionFailed: return NotImplemented else: zm = ring.zero_monom if zm not in p1.keys(): p[zm] = n else: if n == -p[zm]: del p[zm] else: p[zm] += n return p def __sub__(p1, p2): """Subtract polynomial p2 from p1. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.rings import ring >>> _, x, y = ring('x, y', ZZ) >>> p1 = x + y**2 >>> p2 = x*y + y**2 >>> p1 - p2 -x*y + x """ if not p2: return p1.copy() ring = p1.ring if isinstance(p2, ring.dtype): p = p1.copy() get = p.get zero = ring.domain.zero for k, v in p2.items(): v = get(k, zero) - v if v: p[k] = v else: del p[k] return p elif isinstance(p2, PolyElement): if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: pass elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: return p2.__rsub__(p1) else: return NotImplemented try: p2 = ring.domain_new(p2) except CoercionFailed: return NotImplemented else: p = p1.copy() zm = ring.zero_monom if zm not in p1.keys(): p[zm] = -p2 else: if p2 == p[zm]: del p[zm] else: p[zm] -= p2 return p def __rsub__(p1, n): """n - p1 with n convertible to the coefficient domain. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.rings import ring >>> _, x, y = ring('x, y', ZZ) >>> p = x + y >>> 4 - p -x - y + 4 """ ring = p1.ring try: n = ring.domain_new(n) except CoercionFailed: return NotImplemented else: p = ring.zero for expv in p1: p[expv] = -p1[expv] p += n return p def __mul__(p1, p2): """Multiply two polynomials. Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> _, x, y = ring('x, y', QQ) >>> p1 = x + y >>> p2 = x - y >>> p1*p2 x**2 - y**2 """ ring = p1.ring p = ring.zero if not p1 or not p2: return p elif isinstance(p2, ring.dtype): get = p.get zero = ring.domain.zero monomial_mul = ring.monomial_mul p2it = list(p2.items()) for exp1, v1 in p1.items(): for exp2, v2 in p2it: exp = monomial_mul(exp1, exp2) p[exp] = get(exp, zero) + v1*v2 p.strip_zero() return p elif isinstance(p2, PolyElement): if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: pass elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: return p2.__rmul__(p1) else: return NotImplemented try: p2 = ring.domain_new(p2) except CoercionFailed: return NotImplemented else: for exp1, v1 in p1.items(): v = v1*p2 if v: p[exp1] = v return p def __rmul__(p1, p2): """p2 * p1 with p2 in the coefficient domain of p1. Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.rings import ring >>> _, x, y = ring('x, y', ZZ) >>> p = x + y >>> 4 * p 4*x + 4*y """ p = p1.ring.zero if not p2: return p try: p2 = p.ring.domain_new(p2) except CoercionFailed: return NotImplemented else: for exp1, v1 in p1.items(): v = p2*v1 if v: p[exp1] = v return p def __pow__(self, n): """raise polynomial to power `n` Examples ======== >>> from sympy.polys.domains import ZZ >>> from sympy.polys.rings import ring >>> _, x, y = ring('x, y', ZZ) >>> p = x + y**2 >>> p**3 x**3 + 3*x**2*y**2 + 3*x*y**4 + y**6 """ ring = self.ring if not n: if self: return ring.one else: raise ValueError("0**0") elif len(self) == 1: monom, coeff = list(self.items())[0] p = ring.zero if coeff == ring.domain.one: p[ring.monomial_pow(monom, n)] = coeff else: p[ring.monomial_pow(monom, n)] = coeff**n return p # For ring series, we need negative and rational exponent support only # with monomials. n = int(n) if n < 0: raise ValueError("Negative exponent") elif n == 1: return self.copy() elif n == 2: return self.square() elif n == 3: return self*self.square() elif len(self) <= 5: # TODO: use an actual density measure return self._pow_multinomial(n) else: return self._pow_generic(n) def _pow_generic(self, n): p = self.ring.one c = self while True: if n & 1: p = p*c n -= 1 if not n: break c = c.square() n = n // 2 return p def _pow_multinomial(self, n): multinomials = multinomial_coefficients(len(self), n).items() monomial_mulpow = self.ring.monomial_mulpow zero_monom = self.ring.zero_monom terms = self.items() zero = self.ring.domain.zero poly = self.ring.zero for multinomial, multinomial_coeff in multinomials: product_monom = zero_monom product_coeff = multinomial_coeff for exp, (monom, coeff) in zip(multinomial, terms): if exp: product_monom = monomial_mulpow(product_monom, monom, exp) product_coeff *= coeff**exp monom = tuple(product_monom) coeff = product_coeff coeff = poly.get(monom, zero) + coeff if coeff: poly[monom] = coeff elif monom in poly: del poly[monom] return poly def square(self): """square of a polynomial Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y = ring('x, y', ZZ) >>> p = x + y**2 >>> p.square() x**2 + 2*x*y**2 + y**4 """ ring = self.ring p = ring.zero get = p.get keys = list(self.keys()) zero = ring.domain.zero monomial_mul = ring.monomial_mul for i in range(len(keys)): k1 = keys[i] pk = self[k1] for j in range(i): k2 = keys[j] exp = monomial_mul(k1, k2) p[exp] = get(exp, zero) + pk*self[k2] p = p.imul_num(2) get = p.get for k, v in self.items(): k2 = monomial_mul(k, k) p[k2] = get(k2, zero) + v**2 p.strip_zero() return p def __divmod__(p1, p2): ring = p1.ring if not p2: raise ZeroDivisionError("polynomial division") elif isinstance(p2, ring.dtype): return p1.div(p2) elif isinstance(p2, PolyElement): if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: pass elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: return p2.__rdivmod__(p1) else: return NotImplemented try: p2 = ring.domain_new(p2) except CoercionFailed: return NotImplemented else: return (p1.quo_ground(p2), p1.rem_ground(p2)) def __rdivmod__(p1, p2): return NotImplemented def __mod__(p1, p2): ring = p1.ring if not p2: raise ZeroDivisionError("polynomial division") elif isinstance(p2, ring.dtype): return p1.rem(p2) elif isinstance(p2, PolyElement): if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: pass elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: return p2.__rmod__(p1) else: return NotImplemented try: p2 = ring.domain_new(p2) except CoercionFailed: return NotImplemented else: return p1.rem_ground(p2) def __rmod__(p1, p2): return NotImplemented def __truediv__(p1, p2): ring = p1.ring if not p2: raise ZeroDivisionError("polynomial division") elif isinstance(p2, ring.dtype): if p2.is_monomial: return p1*(p2**(-1)) else: return p1.quo(p2) elif isinstance(p2, PolyElement): if isinstance(ring.domain, PolynomialRing) and ring.domain.ring == p2.ring: pass elif isinstance(p2.ring.domain, PolynomialRing) and p2.ring.domain.ring == ring: return p2.__rtruediv__(p1) else: return NotImplemented try: p2 = ring.domain_new(p2) except CoercionFailed: return NotImplemented else: return p1.quo_ground(p2) def __rtruediv__(p1, p2): return NotImplemented __floordiv__ = __truediv__ __rfloordiv__ = __rtruediv__ # TODO: use // (__floordiv__) for exquo()? def _term_div(self): zm = self.ring.zero_monom domain = self.ring.domain domain_quo = domain.quo monomial_div = self.ring.monomial_div if domain.is_Field: def term_div(a_lm_a_lc, b_lm_b_lc): a_lm, a_lc = a_lm_a_lc b_lm, b_lc = b_lm_b_lc if b_lm == zm: # apparently this is a very common case monom = a_lm else: monom = monomial_div(a_lm, b_lm) if monom is not None: return monom, domain_quo(a_lc, b_lc) else: return None else: def term_div(a_lm_a_lc, b_lm_b_lc): a_lm, a_lc = a_lm_a_lc b_lm, b_lc = b_lm_b_lc if b_lm == zm: # apparently this is a very common case monom = a_lm else: monom = monomial_div(a_lm, b_lm) if not (monom is None or a_lc % b_lc): return monom, domain_quo(a_lc, b_lc) else: return None return term_div def div(self, fv): """Division algorithm, see [CLO] p64. fv array of polynomials return qv, r such that self = sum(fv[i]*qv[i]) + r All polynomials are required not to be Laurent polynomials. Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y = ring('x, y', ZZ) >>> f = x**3 >>> f0 = x - y**2 >>> f1 = x - y >>> qv, r = f.div((f0, f1)) >>> qv[0] x**2 + x*y**2 + y**4 >>> qv[1] 0 >>> r y**6 """ ring = self.ring ret_single = False if isinstance(fv, PolyElement): ret_single = True fv = [fv] if not all(fv): raise ZeroDivisionError("polynomial division") if not self: if ret_single: return ring.zero, ring.zero else: return [], ring.zero for f in fv: if f.ring != ring: raise ValueError('self and f must have the same ring') s = len(fv) qv = [ring.zero for i in range(s)] p = self.copy() r = ring.zero term_div = self._term_div() expvs = [fx.leading_expv() for fx in fv] while p: i = 0 divoccurred = 0 while i < s and divoccurred == 0: expv = p.leading_expv() term = term_div((expv, p[expv]), (expvs[i], fv[i][expvs[i]])) if term is not None: expv1, c = term qv[i] = qv[i]._iadd_monom((expv1, c)) p = p._iadd_poly_monom(fv[i], (expv1, -c)) divoccurred = 1 else: i += 1 if not divoccurred: expv = p.leading_expv() r = r._iadd_monom((expv, p[expv])) del p[expv] if expv == ring.zero_monom: r += p if ret_single: if not qv: return ring.zero, r else: return qv[0], r else: return qv, r def rem(self, G): f = self if isinstance(G, PolyElement): G = [G] if not all(G): raise ZeroDivisionError("polynomial division") ring = f.ring domain = ring.domain zero = domain.zero monomial_mul = ring.monomial_mul r = ring.zero term_div = f._term_div() ltf = f.LT f = f.copy() get = f.get while f: for g in G: tq = term_div(ltf, g.LT) if tq is not None: m, c = tq for mg, cg in g.iterterms(): m1 = monomial_mul(mg, m) c1 = get(m1, zero) - c*cg if not c1: del f[m1] else: f[m1] = c1 ltm = f.leading_expv() if ltm is not None: ltf = ltm, f[ltm] break else: ltm, ltc = ltf if ltm in r: r[ltm] += ltc else: r[ltm] = ltc del f[ltm] ltm = f.leading_expv() if ltm is not None: ltf = ltm, f[ltm] return r def quo(f, G): return f.div(G)[0] def exquo(f, G): q, r = f.div(G) if not r: return q else: raise ExactQuotientFailed(f, G) def _iadd_monom(self, mc): """add to self the monomial coeff*x0**i0*x1**i1*... unless self is a generator -- then just return the sum of the two. mc is a tuple, (monom, coeff), where monomial is (i0, i1, ...) Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y = ring('x, y', ZZ) >>> p = x**4 + 2*y >>> m = (1, 2) >>> p1 = p._iadd_monom((m, 5)) >>> p1 x**4 + 5*x*y**2 + 2*y >>> p1 is p True >>> p = x >>> p1 = p._iadd_monom((m, 5)) >>> p1 5*x*y**2 + x >>> p1 is p False """ if self in self.ring._gens_set: cpself = self.copy() else: cpself = self expv, coeff = mc c = cpself.get(expv) if c is None: cpself[expv] = coeff else: c += coeff if c: cpself[expv] = c else: del cpself[expv] return cpself def _iadd_poly_monom(self, p2, mc): """add to self the product of (p)*(coeff*x0**i0*x1**i1*...) unless self is a generator -- then just return the sum of the two. mc is a tuple, (monom, coeff), where monomial is (i0, i1, ...) Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y, z = ring('x, y, z', ZZ) >>> p1 = x**4 + 2*y >>> p2 = y + z >>> m = (1, 2, 3) >>> p1 = p1._iadd_poly_monom(p2, (m, 3)) >>> p1 x**4 + 3*x*y**3*z**3 + 3*x*y**2*z**4 + 2*y """ p1 = self if p1 in p1.ring._gens_set: p1 = p1.copy() (m, c) = mc get = p1.get zero = p1.ring.domain.zero monomial_mul = p1.ring.monomial_mul for k, v in p2.items(): ka = monomial_mul(k, m) coeff = get(ka, zero) + v*c if coeff: p1[ka] = coeff else: del p1[ka] return p1 def degree(f, x=None): """ The leading degree in ``x`` or the main variable. Note that the degree of 0 is negative infinity (the SymPy object -oo). """ i = f.ring.index(x) if not f: return -oo elif i < 0: return 0 else: return max([ monom[i] for monom in f.itermonoms() ]) def degrees(f): """ A tuple containing leading degrees in all variables. Note that the degree of 0 is negative infinity (the SymPy object -oo) """ if not f: return (-oo,)*f.ring.ngens else: return tuple(map(max, list(zip(*f.itermonoms())))) def tail_degree(f, x=None): """ The tail degree in ``x`` or the main variable. Note that the degree of 0 is negative infinity (the SymPy object -oo) """ i = f.ring.index(x) if not f: return -oo elif i < 0: return 0 else: return min([ monom[i] for monom in f.itermonoms() ]) def tail_degrees(f): """ A tuple containing tail degrees in all variables. Note that the degree of 0 is negative infinity (the SymPy object -oo) """ if not f: return (-oo,)*f.ring.ngens else: return tuple(map(min, list(zip(*f.itermonoms())))) def leading_expv(self): """Leading monomial tuple according to the monomial ordering. Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y, z = ring('x, y, z', ZZ) >>> p = x**4 + x**3*y + x**2*z**2 + z**7 >>> p.leading_expv() (4, 0, 0) """ if self: return self.ring.leading_expv(self) else: return None def _get_coeff(self, expv): return self.get(expv, self.ring.domain.zero) def coeff(self, element): """ Returns the coefficient that stands next to the given monomial. Parameters ========== element : PolyElement (with ``is_monomial = True``) or 1 Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y, z = ring("x,y,z", ZZ) >>> f = 3*x**2*y - x*y*z + 7*z**3 + 23 >>> f.coeff(x**2*y) 3 >>> f.coeff(x*y) 0 >>> f.coeff(1) 23 """ if element == 1: return self._get_coeff(self.ring.zero_monom) elif isinstance(element, self.ring.dtype): terms = list(element.iterterms()) if len(terms) == 1: monom, coeff = terms[0] if coeff == self.ring.domain.one: return self._get_coeff(monom) raise ValueError("expected a monomial, got %s" % element) def const(self): """Returns the constant coefficient. """ return self._get_coeff(self.ring.zero_monom) @property def LC(self): return self._get_coeff(self.leading_expv()) @property def LM(self): expv = self.leading_expv() if expv is None: return self.ring.zero_monom else: return expv def leading_monom(self): """ Leading monomial as a polynomial element. Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y = ring('x, y', ZZ) >>> (3*x*y + y**2).leading_monom() x*y """ p = self.ring.zero expv = self.leading_expv() if expv: p[expv] = self.ring.domain.one return p @property def LT(self): expv = self.leading_expv() if expv is None: return (self.ring.zero_monom, self.ring.domain.zero) else: return (expv, self._get_coeff(expv)) def leading_term(self): """Leading term as a polynomial element. Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y = ring('x, y', ZZ) >>> (3*x*y + y**2).leading_term() 3*x*y """ p = self.ring.zero expv = self.leading_expv() if expv is not None: p[expv] = self[expv] return p def _sorted(self, seq, order): if order is None: order = self.ring.order else: order = OrderOpt.preprocess(order) if order is lex: return sorted(seq, key=lambda monom: monom[0], reverse=True) else: return sorted(seq, key=lambda monom: order(monom[0]), reverse=True) def coeffs(self, order=None): """Ordered list of polynomial coefficients. Parameters ========== order : :class:`~.MonomialOrder` or coercible, optional Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> from sympy.polys.orderings import lex, grlex >>> _, x, y = ring("x, y", ZZ, lex) >>> f = x*y**7 + 2*x**2*y**3 >>> f.coeffs() [2, 1] >>> f.coeffs(grlex) [1, 2] """ return [ coeff for _, coeff in self.terms(order) ] def monoms(self, order=None): """Ordered list of polynomial monomials. Parameters ========== order : :class:`~.MonomialOrder` or coercible, optional Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> from sympy.polys.orderings import lex, grlex >>> _, x, y = ring("x, y", ZZ, lex) >>> f = x*y**7 + 2*x**2*y**3 >>> f.monoms() [(2, 3), (1, 7)] >>> f.monoms(grlex) [(1, 7), (2, 3)] """ return [ monom for monom, _ in self.terms(order) ] def terms(self, order=None): """Ordered list of polynomial terms. Parameters ========== order : :class:`~.MonomialOrder` or coercible, optional Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> from sympy.polys.orderings import lex, grlex >>> _, x, y = ring("x, y", ZZ, lex) >>> f = x*y**7 + 2*x**2*y**3 >>> f.terms() [((2, 3), 2), ((1, 7), 1)] >>> f.terms(grlex) [((1, 7), 1), ((2, 3), 2)] """ return self._sorted(list(self.items()), order) def itercoeffs(self): """Iterator over coefficients of a polynomial. """ return iter(self.values()) def itermonoms(self): """Iterator over monomials of a polynomial. """ return iter(self.keys()) def iterterms(self): """Iterator over terms of a polynomial. """ return iter(self.items()) def listcoeffs(self): """Unordered list of polynomial coefficients. """ return list(self.values()) def listmonoms(self): """Unordered list of polynomial monomials. """ return list(self.keys()) def listterms(self): """Unordered list of polynomial terms. """ return list(self.items()) def imul_num(p, c): """multiply inplace the polynomial p by an element in the coefficient ring, provided p is not one of the generators; else multiply not inplace Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y = ring('x, y', ZZ) >>> p = x + y**2 >>> p1 = p.imul_num(3) >>> p1 3*x + 3*y**2 >>> p1 is p True >>> p = x >>> p1 = p.imul_num(3) >>> p1 3*x >>> p1 is p False """ if p in p.ring._gens_set: return p*c if not c: p.clear() return for exp in p: p[exp] *= c return p def content(f): """Returns GCD of polynomial's coefficients. """ domain = f.ring.domain cont = domain.zero gcd = domain.gcd for coeff in f.itercoeffs(): cont = gcd(cont, coeff) return cont def primitive(f): """Returns content and a primitive polynomial. """ cont = f.content() return cont, f.quo_ground(cont) def monic(f): """Divides all coefficients by the leading coefficient. """ if not f: return f else: return f.quo_ground(f.LC) def mul_ground(f, x): if not x: return f.ring.zero terms = [ (monom, coeff*x) for monom, coeff in f.iterterms() ] return f.new(terms) def mul_monom(f, monom): monomial_mul = f.ring.monomial_mul terms = [ (monomial_mul(f_monom, monom), f_coeff) for f_monom, f_coeff in f.items() ] return f.new(terms) def mul_term(f, term): monom, coeff = term if not f or not coeff: return f.ring.zero elif monom == f.ring.zero_monom: return f.mul_ground(coeff) monomial_mul = f.ring.monomial_mul terms = [ (monomial_mul(f_monom, monom), f_coeff*coeff) for f_monom, f_coeff in f.items() ] return f.new(terms) def quo_ground(f, x): domain = f.ring.domain if not x: raise ZeroDivisionError('polynomial division') if not f or x == domain.one: return f if domain.is_Field: quo = domain.quo terms = [ (monom, quo(coeff, x)) for monom, coeff in f.iterterms() ] else: terms = [ (monom, coeff // x) for monom, coeff in f.iterterms() if not (coeff % x) ] return f.new(terms) def quo_term(f, term): monom, coeff = term if not coeff: raise ZeroDivisionError("polynomial division") elif not f: return f.ring.zero elif monom == f.ring.zero_monom: return f.quo_ground(coeff) term_div = f._term_div() terms = [ term_div(t, term) for t in f.iterterms() ] return f.new([ t for t in terms if t is not None ]) def trunc_ground(f, p): if f.ring.domain.is_ZZ: terms = [] for monom, coeff in f.iterterms(): coeff = coeff % p if coeff > p // 2: coeff = coeff - p terms.append((monom, coeff)) else: terms = [ (monom, coeff % p) for monom, coeff in f.iterterms() ] poly = f.new(terms) poly.strip_zero() return poly rem_ground = trunc_ground def extract_ground(self, g): f = self fc = f.content() gc = g.content() gcd = f.ring.domain.gcd(fc, gc) f = f.quo_ground(gcd) g = g.quo_ground(gcd) return gcd, f, g def _norm(f, norm_func): if not f: return f.ring.domain.zero else: ground_abs = f.ring.domain.abs return norm_func([ ground_abs(coeff) for coeff in f.itercoeffs() ]) def max_norm(f): return f._norm(max) def l1_norm(f): return f._norm(sum) def deflate(f, *G): ring = f.ring polys = [f] + list(G) J = [0]*ring.ngens for p in polys: for monom in p.itermonoms(): for i, m in enumerate(monom): J[i] = igcd(J[i], m) for i, b in enumerate(J): if not b: J[i] = 1 J = tuple(J) if all(b == 1 for b in J): return J, polys H = [] for p in polys: h = ring.zero for I, coeff in p.iterterms(): N = [ i // j for i, j in zip(I, J) ] h[tuple(N)] = coeff H.append(h) return J, H def inflate(f, J): poly = f.ring.zero for I, coeff in f.iterterms(): N = [ i*j for i, j in zip(I, J) ] poly[tuple(N)] = coeff return poly def lcm(self, g): f = self domain = f.ring.domain if not domain.is_Field: fc, f = f.primitive() gc, g = g.primitive() c = domain.lcm(fc, gc) h = (f*g).quo(f.gcd(g)) if not domain.is_Field: return h.mul_ground(c) else: return h.monic() def gcd(f, g): return f.cofactors(g)[0] def cofactors(f, g): if not f and not g: zero = f.ring.zero return zero, zero, zero elif not f: h, cff, cfg = f._gcd_zero(g) return h, cff, cfg elif not g: h, cfg, cff = g._gcd_zero(f) return h, cff, cfg elif len(f) == 1: h, cff, cfg = f._gcd_monom(g) return h, cff, cfg elif len(g) == 1: h, cfg, cff = g._gcd_monom(f) return h, cff, cfg J, (f, g) = f.deflate(g) h, cff, cfg = f._gcd(g) return (h.inflate(J), cff.inflate(J), cfg.inflate(J)) def _gcd_zero(f, g): one, zero = f.ring.one, f.ring.zero if g.is_nonnegative: return g, zero, one else: return -g, zero, -one def _gcd_monom(f, g): ring = f.ring ground_gcd = ring.domain.gcd ground_quo = ring.domain.quo monomial_gcd = ring.monomial_gcd monomial_ldiv = ring.monomial_ldiv mf, cf = list(f.iterterms())[0] _mgcd, _cgcd = mf, cf for mg, cg in g.iterterms(): _mgcd = monomial_gcd(_mgcd, mg) _cgcd = ground_gcd(_cgcd, cg) h = f.new([(_mgcd, _cgcd)]) cff = f.new([(monomial_ldiv(mf, _mgcd), ground_quo(cf, _cgcd))]) cfg = f.new([(monomial_ldiv(mg, _mgcd), ground_quo(cg, _cgcd)) for mg, cg in g.iterterms()]) return h, cff, cfg def _gcd(f, g): ring = f.ring if ring.domain.is_QQ: return f._gcd_QQ(g) elif ring.domain.is_ZZ: return f._gcd_ZZ(g) else: # TODO: don't use dense representation (port PRS algorithms) return ring.dmp_inner_gcd(f, g) def _gcd_ZZ(f, g): return heugcd(f, g) def _gcd_QQ(self, g): f = self ring = f.ring new_ring = ring.clone(domain=ring.domain.get_ring()) cf, f = f.clear_denoms() cg, g = g.clear_denoms() f = f.set_ring(new_ring) g = g.set_ring(new_ring) h, cff, cfg = f._gcd_ZZ(g) h = h.set_ring(ring) c, h = h.LC, h.monic() cff = cff.set_ring(ring).mul_ground(ring.domain.quo(c, cf)) cfg = cfg.set_ring(ring).mul_ground(ring.domain.quo(c, cg)) return h, cff, cfg def cancel(self, g): """ Cancel common factors in a rational function ``f/g``. Examples ======== >>> from sympy.polys import ring, ZZ >>> R, x,y = ring("x,y", ZZ) >>> (2*x**2 - 2).cancel(x**2 - 2*x + 1) (2*x + 2, x - 1) """ f = self ring = f.ring if not f: return f, ring.one domain = ring.domain if not (domain.is_Field and domain.has_assoc_Ring): _, p, q = f.cofactors(g) else: new_ring = ring.clone(domain=domain.get_ring()) cq, f = f.clear_denoms() cp, g = g.clear_denoms() f = f.set_ring(new_ring) g = g.set_ring(new_ring) _, p, q = f.cofactors(g) _, cp, cq = new_ring.domain.cofactors(cp, cq) p = p.set_ring(ring) q = q.set_ring(ring) p = p.mul_ground(cp) q = q.mul_ground(cq) # Make canonical with respect to sign or quadrant in the case of ZZ_I # or QQ_I. This ensures that the LC of the denominator is canonical by # multiplying top and bottom by a unit of the ring. u = q.canonical_unit() if u == domain.one: p, q = p, q elif u == -domain.one: p, q = -p, -q else: p = p.mul_ground(u) q = q.mul_ground(u) return p, q def canonical_unit(f): domain = f.ring.domain return domain.canonical_unit(f.LC) def diff(f, x): """Computes partial derivative in ``x``. Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> _, x, y = ring("x,y", ZZ) >>> p = x + x**2*y**3 >>> p.diff(x) 2*x*y**3 + 1 """ ring = f.ring i = ring.index(x) m = ring.monomial_basis(i) g = ring.zero for expv, coeff in f.iterterms(): if expv[i]: e = ring.monomial_ldiv(expv, m) g[e] = ring.domain_new(coeff*expv[i]) return g def __call__(f, *values): if 0 < len(values) <= f.ring.ngens: return f.evaluate(list(zip(f.ring.gens, values))) else: raise ValueError("expected at least 1 and at most %s values, got %s" % (f.ring.ngens, len(values))) def evaluate(self, x, a=None): f = self if isinstance(x, list) and a is None: (X, a), x = x[0], x[1:] f = f.evaluate(X, a) if not x: return f else: x = [ (Y.drop(X), a) for (Y, a) in x ] return f.evaluate(x) ring = f.ring i = ring.index(x) a = ring.domain.convert(a) if ring.ngens == 1: result = ring.domain.zero for (n,), coeff in f.iterterms(): result += coeff*a**n return result else: poly = ring.drop(x).zero for monom, coeff in f.iterterms(): n, monom = monom[i], monom[:i] + monom[i+1:] coeff = coeff*a**n if monom in poly: coeff = coeff + poly[monom] if coeff: poly[monom] = coeff else: del poly[monom] else: if coeff: poly[monom] = coeff return poly def subs(self, x, a=None): f = self if isinstance(x, list) and a is None: for X, a in x: f = f.subs(X, a) return f ring = f.ring i = ring.index(x) a = ring.domain.convert(a) if ring.ngens == 1: result = ring.domain.zero for (n,), coeff in f.iterterms(): result += coeff*a**n return ring.ground_new(result) else: poly = ring.zero for monom, coeff in f.iterterms(): n, monom = monom[i], monom[:i] + (0,) + monom[i+1:] coeff = coeff*a**n if monom in poly: coeff = coeff + poly[monom] if coeff: poly[monom] = coeff else: del poly[monom] else: if coeff: poly[monom] = coeff return poly def symmetrize(self): r""" Rewrite *self* in terms of elementary symmetric polynomials. Explanation =========== If this :py:class:`~.PolyElement` belongs to a ring of $n$ variables, we can try to write it as a function of the elementary symmetric polynomials on $n$ variables. We compute a symmetric part, and a remainder for any part we were not able to symmetrize. Examples ======== >>> from sympy.polys.rings import ring >>> from sympy.polys.domains import ZZ >>> R, x, y = ring("x,y", ZZ) >>> f = x**2 + y**2 >>> f.symmetrize() (x**2 - 2*y, 0, [(x, x + y), (y, x*y)]) >>> f = x**2 - y**2 >>> f.symmetrize() (x**2 - 2*y, -2*y**2, [(x, x + y), (y, x*y)]) Returns ======= Triple ``(p, r, m)`` ``p`` is a :py:class:`~.PolyElement` that represents our attempt to express *self* as a function of elementary symmetric polynomials. Each variable in ``p`` stands for one of the elementary symmetric polynomials. The correspondence is given by ``m``. ``r`` is the remainder. ``m`` is a list of pairs, giving the mapping from variables in ``p`` to elementary symmetric polynomials. The triple satisfies the equation ``p.compose(m) + r == self``. If the remainder ``r`` is zero, *self* is symmetric. If it is nonzero, we were not able to represent *self* as symmetric. See Also ======== sympy.polys.polyfuncs.symmetrize """ f = self.copy() ring = f.ring n = ring.ngens if not n: return f, ring.zero, [] polys = [ring.symmetric_poly(i+1) for i in range(n)] poly_powers = {} def get_poly_power(i, n): if (i, n) not in poly_powers: poly_powers[(i, n)] = polys[i]**n return poly_powers[(i, n)] indices = list(range(n - 1)) weights = list(range(n, 0, -1)) symmetric = ring.zero while f: _height, _monom, _coeff = -1, None, None for i, (monom, coeff) in enumerate(f.terms()): if all(monom[i] >= monom[i + 1] for i in indices): height = max([n*m for n, m in zip(weights, monom)]) if height > _height: _height, _monom, _coeff = height, monom, coeff if _height != -1: monom, coeff = _monom, _coeff else: break exponents = [] for m1, m2 in zip(monom, monom[1:] + (0,)): exponents.append(m1 - m2) symmetric += ring.term_new(tuple(exponents), coeff) product = coeff for i, n in enumerate(exponents): product *= get_poly_power(i, n) f -= product mapping = list(zip(ring.gens, polys)) return symmetric, f, mapping def compose(f, x, a=None): ring = f.ring poly = ring.zero gens_map = dict(zip(ring.gens, range(ring.ngens))) if a is not None: replacements = [(x, a)] else: if isinstance(x, list): replacements = list(x) elif isinstance(x, dict): replacements = sorted(list(x.items()), key=lambda k: gens_map[k[0]]) else: raise ValueError("expected a generator, value pair a sequence of such pairs") for k, (x, g) in enumerate(replacements): replacements[k] = (gens_map[x], ring.ring_new(g)) for monom, coeff in f.iterterms(): monom = list(monom) subpoly = ring.one for i, g in replacements: n, monom[i] = monom[i], 0 if n: subpoly *= g**n subpoly = subpoly.mul_term((tuple(monom), coeff)) poly += subpoly return poly # TODO: following methods should point to polynomial # representation independent algorithm implementations. def pdiv(f, g): return f.ring.dmp_pdiv(f, g) def prem(f, g): return f.ring.dmp_prem(f, g) def pquo(f, g): return f.ring.dmp_quo(f, g) def pexquo(f, g): return f.ring.dmp_exquo(f, g) def half_gcdex(f, g): return f.ring.dmp_half_gcdex(f, g) def gcdex(f, g): return f.ring.dmp_gcdex(f, g) def subresultants(f, g): return f.ring.dmp_subresultants(f, g) def resultant(f, g): return f.ring.dmp_resultant(f, g) def discriminant(f): return f.ring.dmp_discriminant(f) def decompose(f): if f.ring.is_univariate: return f.ring.dup_decompose(f) else: raise MultivariatePolynomialError("polynomial decomposition") def shift(f, a): if f.ring.is_univariate: return f.ring.dup_shift(f, a) else: raise MultivariatePolynomialError("polynomial shift") def sturm(f): if f.ring.is_univariate: return f.ring.dup_sturm(f) else: raise MultivariatePolynomialError("sturm sequence") def gff_list(f): return f.ring.dmp_gff_list(f) def sqf_norm(f): return f.ring.dmp_sqf_norm(f) def sqf_part(f): return f.ring.dmp_sqf_part(f) def sqf_list(f, all=False): return f.ring.dmp_sqf_list(f, all=all) def factor_list(f): return f.ring.dmp_factor_list(f)
3846697587874000c1258a8cc3c240c8de2cc3e8ec27a973547ea6f820a82bc8
"""High-level polynomials manipulation functions. """ from sympy.core import S, Basic, symbols, Dummy from sympy.polys.polyerrors import ( PolificationFailed, ComputationFailed, MultivariatePolynomialError, OptionError) from sympy.polys.polyoptions import allowed_flags, build_options from sympy.polys.polytools import poly_from_expr, Poly from sympy.polys.specialpolys import ( symmetric_poly, interpolating_poly) from sympy.polys.rings import sring from sympy.utilities import numbered_symbols, take, public @public def symmetrize(F, *gens, **args): r""" Rewrite a polynomial in terms of elementary symmetric polynomials. A symmetric polynomial is a multivariate polynomial that remains invariant under any variable permutation, i.e., if `f = f(x_1, x_2, \dots, x_n)`, then `f = f(x_{i_1}, x_{i_2}, \dots, x_{i_n})`, where `(i_1, i_2, \dots, i_n)` is a permutation of `(1, 2, \dots, n)` (an element of the group `S_n`). Returns a tuple of symmetric polynomials ``(f1, f2, ..., fn)`` such that ``f = f1 + f2 + ... + fn``. Examples ======== >>> from sympy.polys.polyfuncs import symmetrize >>> from sympy.abc import x, y >>> symmetrize(x**2 + y**2) (-2*x*y + (x + y)**2, 0) >>> symmetrize(x**2 + y**2, formal=True) (s1**2 - 2*s2, 0, [(s1, x + y), (s2, x*y)]) >>> symmetrize(x**2 - y**2) (-2*x*y + (x + y)**2, -2*y**2) >>> symmetrize(x**2 - y**2, formal=True) (s1**2 - 2*s2, -2*y**2, [(s1, x + y), (s2, x*y)]) """ allowed_flags(args, ['formal', 'symbols']) iterable = True if not hasattr(F, '__iter__'): iterable = False F = [F] R, F = sring(F, *gens, **args) gens = R.symbols opt = build_options(gens, args) symbols = opt.symbols symbols = [next(symbols) for i in range(len(gens))] result = [] for f in F: p, r, m = f.symmetrize() result.append((p.as_expr(*symbols), r.as_expr(*gens))) polys = [(s, g.as_expr()) for s, (_, g) in zip(symbols, m)] if not opt.formal: for i, (sym, non_sym) in enumerate(result): result[i] = (sym.subs(polys), non_sym) if not iterable: result, = result if not opt.formal: return result else: if iterable: return result, polys else: return result + (polys,) @public def horner(f, *gens, **args): """ Rewrite a polynomial in Horner form. Among other applications, evaluation of a polynomial at a point is optimal when it is applied using the Horner scheme ([1]). Examples ======== >>> from sympy.polys.polyfuncs import horner >>> from sympy.abc import x, y, a, b, c, d, e >>> horner(9*x**4 + 8*x**3 + 7*x**2 + 6*x + 5) x*(x*(x*(9*x + 8) + 7) + 6) + 5 >>> horner(a*x**4 + b*x**3 + c*x**2 + d*x + e) e + x*(d + x*(c + x*(a*x + b))) >>> f = 4*x**2*y**2 + 2*x**2*y + 2*x*y**2 + x*y >>> horner(f, wrt=x) x*(x*y*(4*y + 2) + y*(2*y + 1)) >>> horner(f, wrt=y) y*(x*y*(4*x + 2) + x*(2*x + 1)) References ========== [1] - https://en.wikipedia.org/wiki/Horner_scheme """ allowed_flags(args, []) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: return exc.expr form, gen = S.Zero, F.gen if F.is_univariate: for coeff in F.all_coeffs(): form = form*gen + coeff else: F, gens = Poly(F, gen), gens[1:] for coeff in F.all_coeffs(): form = form*gen + horner(coeff, *gens, **args) return form @public def interpolate(data, x): """ Construct an interpolating polynomial for the data points evaluated at point x (which can be symbolic or numeric). Examples ======== >>> from sympy.polys.polyfuncs import interpolate >>> from sympy.abc import a, b, x A list is interpreted as though it were paired with a range starting from 1: >>> interpolate([1, 4, 9, 16], x) x**2 This can be made explicit by giving a list of coordinates: >>> interpolate([(1, 1), (2, 4), (3, 9)], x) x**2 The (x, y) coordinates can also be given as keys and values of a dictionary (and the points need not be equispaced): >>> interpolate([(-1, 2), (1, 2), (2, 5)], x) x**2 + 1 >>> interpolate({-1: 2, 1: 2, 2: 5}, x) x**2 + 1 If the interpolation is going to be used only once then the value of interest can be passed instead of passing a symbol: >>> interpolate([1, 4, 9], 5) 25 Symbolic coordinates are also supported: >>> [(i,interpolate((a, b), i)) for i in range(1, 4)] [(1, a), (2, b), (3, -a + 2*b)] """ n = len(data) if isinstance(data, dict): if x in data: return S(data[x]) X, Y = list(zip(*data.items())) else: if isinstance(data[0], tuple): X, Y = list(zip(*data)) if x in X: return S(Y[X.index(x)]) else: if x in range(1, n + 1): return S(data[x - 1]) Y = list(data) X = list(range(1, n + 1)) try: return interpolating_poly(n, x, X, Y).expand() except ValueError: d = Dummy() return interpolating_poly(n, d, X, Y).expand().subs(d, x) @public def rational_interpolate(data, degnum, X=symbols('x')): """ Returns a rational interpolation, where the data points are element of any integral domain. The first argument contains the data (as a list of coordinates). The ``degnum`` argument is the degree in the numerator of the rational function. Setting it too high will decrease the maximal degree in the denominator for the same amount of data. Examples ======== >>> from sympy.polys.polyfuncs import rational_interpolate >>> data = [(1, -210), (2, -35), (3, 105), (4, 231), (5, 350), (6, 465)] >>> rational_interpolate(data, 2) (105*x**2 - 525)/(x + 1) Values do not need to be integers: >>> from sympy import sympify >>> x = [1, 2, 3, 4, 5, 6] >>> y = sympify("[-1, 0, 2, 22/5, 7, 68/7]") >>> rational_interpolate(zip(x, y), 2) (3*x**2 - 7*x + 2)/(x + 1) The symbol for the variable can be changed if needed: >>> from sympy import symbols >>> z = symbols('z') >>> rational_interpolate(data, 2, X=z) (105*z**2 - 525)/(z + 1) References ========== .. [1] Algorithm is adapted from: http://axiom-wiki.newsynthesis.org/RationalInterpolation """ from sympy.matrices.dense import ones xdata, ydata = list(zip(*data)) k = len(xdata) - degnum - 1 if k < 0: raise OptionError("Too few values for the required degree.") c = ones(degnum + k + 1, degnum + k + 2) for j in range(max(degnum, k)): for i in range(degnum + k + 1): c[i, j + 1] = c[i, j]*xdata[i] for j in range(k + 1): for i in range(degnum + k + 1): c[i, degnum + k + 1 - j] = -c[i, k - j]*ydata[i] r = c.nullspace()[0] return (sum(r[i] * X**i for i in range(degnum + 1)) / sum(r[i + degnum + 1] * X**i for i in range(k + 1))) @public def viete(f, roots=None, *gens, **args): """ Generate Viete's formulas for ``f``. Examples ======== >>> from sympy.polys.polyfuncs import viete >>> from sympy import symbols >>> x, a, b, c, r1, r2 = symbols('x,a:c,r1:3') >>> viete(a*x**2 + b*x + c, [r1, r2], x) [(r1 + r2, -b/a), (r1*r2, c/a)] """ allowed_flags(args, []) if isinstance(roots, Basic): gens, roots = (roots,) + gens, None try: f, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('viete', 1, exc) if f.is_multivariate: raise MultivariatePolynomialError( "multivariate polynomials are not allowed") n = f.degree() if n < 1: raise ValueError( "Cannot derive Viete's formulas for a constant polynomial") if roots is None: roots = numbered_symbols('r', start=1) roots = take(roots, n) if n != len(roots): raise ValueError("required %s roots, got %s" % (n, len(roots))) lc, coeffs = f.LC(), f.all_coeffs() result, sign = [], -1 for i, coeff in enumerate(coeffs[1:]): poly = symmetric_poly(i + 1, roots) coeff = sign*(coeff/lc) result.append((poly, coeff)) sign = -sign return result
0546e028f5174f0beb8436d08e31ba7378c5070990d167d188c4134c59cf2fdd
"""A module that handles matrices. Includes functions for fast creating matrices like zero, one/eye, random matrix, etc. """ from .common import ShapeError, NonSquareMatrixError, MatrixKind from .dense import ( GramSchmidt, casoratian, diag, eye, hessian, jordan_cell, list2numpy, matrix2numpy, matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2, rot_axis3, rot_ccw_axis1, rot_ccw_axis2, rot_ccw_axis3, rot_givens, symarray, wronskian, zeros) from .dense import MutableDenseMatrix from .matrices import DeferredVector, MatrixBase MutableMatrix = MutableDenseMatrix Matrix = MutableMatrix from .sparse import MutableSparseMatrix from .sparsetools import banded from .immutable import ImmutableDenseMatrix, ImmutableSparseMatrix ImmutableMatrix = ImmutableDenseMatrix SparseMatrix = MutableSparseMatrix from .expressions import ( MatrixSlice, BlockDiagMatrix, BlockMatrix, FunctionMatrix, Identity, Inverse, MatAdd, MatMul, MatPow, MatrixExpr, MatrixSymbol, Trace, Transpose, ZeroMatrix, OneMatrix, blockcut, block_collapse, matrix_symbols, Adjoint, hadamard_product, HadamardProduct, HadamardPower, Determinant, det, diagonalize_vector, DiagMatrix, DiagonalMatrix, DiagonalOf, trace, DotProduct, kronecker_product, KroneckerProduct, PermutationMatrix, MatrixPermute, MatrixSet, Permanent, per) from .utilities import dotprodsimp __all__ = [ 'ShapeError', 'NonSquareMatrixError', 'MatrixKind', 'GramSchmidt', 'casoratian', 'diag', 'eye', 'hessian', 'jordan_cell', 'list2numpy', 'matrix2numpy', 'matrix_multiply_elementwise', 'ones', 'randMatrix', 'rot_axis1', 'rot_axis2', 'rot_axis3', 'symarray', 'wronskian', 'zeros', 'rot_ccw_axis1', 'rot_ccw_axis2', 'rot_ccw_axis3', 'rot_givens', 'MutableDenseMatrix', 'DeferredVector', 'MatrixBase', 'Matrix', 'MutableMatrix', 'MutableSparseMatrix', 'banded', 'ImmutableDenseMatrix', 'ImmutableSparseMatrix', 'ImmutableMatrix', 'SparseMatrix', 'MatrixSlice', 'BlockDiagMatrix', 'BlockMatrix', 'FunctionMatrix', 'Identity', 'Inverse', 'MatAdd', 'MatMul', 'MatPow', 'MatrixExpr', 'MatrixSymbol', 'Trace', 'Transpose', 'ZeroMatrix', 'OneMatrix', 'blockcut', 'block_collapse', 'matrix_symbols', 'Adjoint', 'hadamard_product', 'HadamardProduct', 'HadamardPower', 'Determinant', 'det', 'diagonalize_vector', 'DiagMatrix', 'DiagonalMatrix', 'DiagonalOf', 'trace', 'DotProduct', 'kronecker_product', 'KroneckerProduct', 'PermutationMatrix', 'MatrixPermute', 'MatrixSet', 'Permanent', 'per', 'dotprodsimp', ]
8711a10a751906e25a015fe3893a69c31cc26a8ff723be689ff3f320076b1347
import random from sympy.core.basic import Basic 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.utilities.decorator import doctest_depends_on from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import is_sequence from .common import ShapeError from .decompositions import _cholesky, _LDLdecomposition from .matrices import MatrixBase from .repmatrix import MutableRepMatrix, RepMatrix from .solvers import _lower_triangular_solve, _upper_triangular_solve def _iszero(x): """Returns True if x is zero.""" return x.is_zero class DenseMatrix(RepMatrix): """Matrix implementation based on DomainMatrix as the internal representation""" # # DenseMatrix is a superclass for both MutableDenseMatrix and # ImmutableDenseMatrix. Methods shared by both classes but not for the # Sparse classes should be implemented here. # is_MatrixExpr = False # type: bool _op_priority = 10.01 _class_priority = 4 @property def _mat(self): sympy_deprecation_warning( """ The private _mat attribute of Matrix is deprecated. Use the .flat() method instead. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-private-matrix-attributes" ) return self.flat() 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 as_immutable(self): """Returns an Immutable version of this Matrix """ from .immutable import ImmutableDenseMatrix as cls return cls._fromrep(self._rep.copy()) 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 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, MutableRepMatrix): 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 """ from sympy.simplify.simplify import simplify as _simplify for (i, j), element in self.todok().items(): self[i, j] = _simplify(element, **kwargs) MutableMatrix = Matrix = MutableDenseMatrix ########### # Numpy Utility Functions: # list2numpy, matrix2numpy, symmarray ########### 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 ########### # Rotation matrices: # rot_givens, rot_axis[123], rot_ccw_axis[123] ########### def rot_givens(i, j, theta, dim=3): r"""Returns a a Givens rotation matrix, a a rotation in the plane spanned by two coordinates axes. Explanation =========== The Givens rotation corresponds to a generalization of rotation matrices to any number of dimensions, given by: .. math:: G(i, j, \theta) = \begin{bmatrix} 1 & \cdots & 0 & \cdots & 0 & \cdots & 0 \\ \vdots & \ddots & \vdots & & \vdots & & \vdots \\ 0 & \cdots & c & \cdots & -s & \cdots & 0 \\ \vdots & & \vdots & \ddots & \vdots & & \vdots \\ 0 & \cdots & s & \cdots & c & \cdots & 0 \\ \vdots & & \vdots & & \vdots & \ddots & \vdots \\ 0 & \cdots & 0 & \cdots & 0 & \cdots & 1 \end{bmatrix} Where $c = \cos(\theta)$ and $s = \sin(\theta)$ appear at the intersections ``i``\th and ``j``\th rows and columns. For fixed ``i > j``\, the non-zero elements of a Givens matrix are given by: - $g_{kk} = 1$ for $k \ne i,\,j$ - $g_{kk} = c$ for $k = i,\,j$ - $g_{ji} = -g_{ij} = -s$ Parameters ========== i : int between ``0`` and ``dim - 1`` Represents first axis j : int between ``0`` and ``dim - 1`` Represents second axis dim : int bigger than 1 Number of dimentions. Defaults to 3. Examples ======== >>> from sympy import pi, rot_givens A counterclockwise rotation of pi/3 (60 degrees) around the third axis (z-axis): >>> rot_givens(1, 0, pi/3) 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_givens(1, 0, pi/2) Matrix([ [0, -1, 0], [1, 0, 0], [0, 0, 1]]) This can be generalized to any number of dimensions: >>> rot_givens(1, 0, pi/2, dim=4) Matrix([ [0, -1, 0, 0], [1, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) References ========== .. [1] https://en.wikipedia.org/wiki/Givens_rotation See Also ======== rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis (clockwise around the x axis) rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis (clockwise around the y axis) rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis (clockwise around the z axis) rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis (counterclockwise around the x axis) rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis (counterclockwise around the y axis) rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis (counterclockwise around the z axis) """ if not isinstance(dim, int) or dim < 2: raise ValueError('dim must be an integer biggen than one, ' 'got {}.'.format(dim)) if i == j: raise ValueError('i and j must be different, ' 'got ({}, {})'.format(i, j)) for ij in [i, j]: if not isinstance(ij, int) or ij < 0 or ij > dim - 1: raise ValueError('i and j must be integers between 0 and ' '{}, got i={} and j={}.'.format(dim-1, i, j)) theta = sympify(theta) c = cos(theta) s = sin(theta) M = eye(dim) M[i, i] = c M[j, j] = c M[i, j] = s M[j, i] = -s return M def rot_axis3(theta): r"""Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis. Explanation =========== For a right-handed coordinate system, this corresponds to a clockwise rotation around the `z`-axis, given by: .. math:: R = \begin{bmatrix} \cos(\theta) & \sin(\theta) & 0 \\ -\sin(\theta) & \cos(\theta) & 0 \\ 0 & 0 & 1 \end{bmatrix} Examples ======== >>> from sympy import pi, 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_givens: Returns a Givens rotation matrix (generalized rotation for any number of dimensions) rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis (counterclockwise around the z axis) rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis (clockwise around the x axis) rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis (clockwise around the y axis) """ return rot_givens(0, 1, theta, dim=3) def rot_axis2(theta): r"""Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis. Explanation =========== For a right-handed coordinate system, this corresponds to a clockwise rotation around the `y`-axis, given by: .. math:: R = \begin{bmatrix} \cos(\theta) & 0 & -\sin(\theta) \\ 0 & 1 & 0 \\ \sin(\theta) & 0 & \cos(\theta) \end{bmatrix} Examples ======== >>> from sympy import pi, 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_givens: Returns a Givens rotation matrix (generalized rotation for any number of dimensions) rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis (clockwise around the y axis) rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis (counterclockwise around the x axis) rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis (counterclockwise around the z axis) """ return rot_givens(2, 0, theta, dim=3) def rot_axis1(theta): r"""Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis. Explanation =========== For a right-handed coordinate system, this corresponds to a clockwise rotation around the `x`-axis, given by: .. math:: R = \begin{bmatrix} 1 & 0 & 0 \\ 0 & \cos(\theta) & \sin(\theta) \\ 0 & -\sin(\theta) & \cos(\theta) \end{bmatrix} Examples ======== >>> from sympy import pi, 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_givens: Returns a Givens rotation matrix (generalized rotation for any number of dimensions) rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis (counterclockwise around the x axis) rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis (clockwise around the y axis) rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis (clockwise around the z axis) """ return rot_givens(1, 2, theta, dim=3) def rot_ccw_axis3(theta): r"""Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis. Explanation =========== For a right-handed coordinate system, this corresponds to a counterclockwise rotation around the `z`-axis, given by: .. math:: R = \begin{bmatrix} \cos(\theta) & -\sin(\theta) & 0 \\ \sin(\theta) & \cos(\theta) & 0 \\ 0 & 0 & 1 \end{bmatrix} Examples ======== >>> from sympy import pi, rot_ccw_axis3 A rotation of pi/3 (60 degrees): >>> theta = pi/3 >>> rot_ccw_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_ccw_axis3(pi/2) Matrix([ [0, -1, 0], [1, 0, 0], [0, 0, 1]]) See Also ======== rot_givens: Returns a Givens rotation matrix (generalized rotation for any number of dimensions) rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis (clockwise around the z axis) rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis (counterclockwise around the x axis) rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis (counterclockwise around the y axis) """ return rot_givens(1, 0, theta, dim=3) def rot_ccw_axis2(theta): r"""Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis. Explanation =========== For a right-handed coordinate system, this corresponds to a counterclockwise rotation around the `y`-axis, given by: .. math:: R = \begin{bmatrix} \cos(\theta) & 0 & \sin(\theta) \\ 0 & 1 & 0 \\ -\sin(\theta) & 0 & \cos(\theta) \end{bmatrix} Examples ======== >>> from sympy import pi, rot_ccw_axis2 A rotation of pi/3 (60 degrees): >>> theta = pi/3 >>> rot_ccw_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_ccw_axis2(pi/2) Matrix([ [ 0, 0, 1], [ 0, 1, 0], [-1, 0, 0]]) See Also ======== rot_givens: Returns a Givens rotation matrix (generalized rotation for any number of dimensions) rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis (clockwise around the y axis) rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis (counterclockwise around the x axis) rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis (counterclockwise around the z axis) """ return rot_givens(0, 2, theta, dim=3) def rot_ccw_axis1(theta): r"""Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis. Explanation =========== For a right-handed coordinate system, this corresponds to a counterclockwise rotation around the `x`-axis, given by: .. math:: R = \begin{bmatrix} 1 & 0 & 0 \\ 0 & \cos(\theta) & -\sin(\theta) \\ 0 & \sin(\theta) & \cos(\theta) \end{bmatrix} Examples ======== >>> from sympy import pi, rot_ccw_axis1 A rotation of pi/3 (60 degrees): >>> theta = pi/3 >>> rot_ccw_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_ccw_axis1(pi/2) Matrix([ [1, 0, 0], [0, 0, -1], [0, 1, 0]]) See Also ======== rot_givens: Returns a Givens rotation matrix (generalized rotation for any number of dimensions) rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis (clockwise around the x axis) rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis (counterclockwise around the y axis) rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis (counterclockwise around the z axis) """ return rot_givens(2, 1, theta, dim=3) @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 ========== .. [1] 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 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 import Matrix, matrix_multiply_elementwise >>> 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 import randMatrix >>> randMatrix(3) # doctest:+SKIP [25, 45, 27] [44, 54, 9] [23, 96, 46] >>> randMatrix(3, 2) # doctest:+SKIP [87, 29] [23, 37] [90, 26] >>> randMatrix(3, 3, 0, 2) # doctest:+SKIP [0, 2, 0] [2, 0, 1] [0, 0, 1] >>> randMatrix(3, symmetric=True) # doctest:+SKIP [85, 26, 29] [26, 71, 43] [29, 43, 57] >>> A = randMatrix(3, seed=1) >>> B = randMatrix(3, seed=2) >>> A == B False >>> A == randMatrix(3, seed=1) True >>> randMatrix(3, symmetric=True, percent=50) # doctest:+SKIP [77, 70, 0], [70, 0, 0], [ 0, 0, 88] """ # Note that ``Random()`` is equivalent to ``Random(None)`` prng = prng or random.Random(seed) if c is None: c = r if symmetric and r != c: raise ValueError('For symmetric matrices, r must equal c, but %i != %i' % (r, c)) ij = range(r * c) if percent != 100: ij = prng.sample(ij, int(len(ij)*percent // 100)) m = zeros(r, c) if not symmetric: for ijk in ij: i, j = divmod(ijk, c) m[i, j] = prng.randint(min, max) else: for ijk in ij: i, j = divmod(ijk, c) if i <= j: m[i, j] = m[j, i] = prng.randint(min, max) return m def wronskian(functions, var, method='bareiss'): """ Compute Wronskian for [] of functions :: | f1 f2 ... fn | | f1' f2' ... fn' | | . . . . | W(f1, ..., fn) = | . . . . | | . . . . | | (n) (n) (n) | | D (f1) D (f2) ... D (fn) | see: https://en.wikipedia.org/wiki/Wronskian See Also ======== sympy.matrices.matrices.MatrixCalculus.jacobian hessian """ functions = [sympify(f) for f in functions] n = len(functions) if n == 0: return S.One 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)
b7a48a2feb17bf1a481cf4e47eabb377d05b4f876fabe4cb2b652905e359cb27
from sympy.calculus.accumulationbounds import AccumBounds from sympy.core.add import Add from sympy.core.function import (Lambda, diff) from sympy.core.mod import Mod from sympy.core.mul import Mul from sympy.core.numbers import (E, Float, I, Rational, nan, oo, pi, zoo) from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (arg, conjugate, im, re) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import (acoth, asinh, atanh, cosh, coth, sinh, tanh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, acot, acsc, asec, asin, atan, atan2, cos, cot, csc, sec, sin, sinc, tan) from sympy.functions.special.bessel import (besselj, jn) from sympy.functions.special.delta_functions import Heaviside from sympy.matrices.dense import Matrix from sympy.polys.polytools import (cancel, gcd) from sympy.series.limits import limit from sympy.series.order import O from sympy.series.series import series from sympy.sets.fancysets import ImageSet from sympy.sets.sets import (FiniteSet, Interval) from sympy.simplify.simplify import simplify from sympy.core.expr import unchanged from sympy.core.function import ArgumentIndexError from sympy.core.relational import Ne, Eq from sympy.functions.elementary.piecewise import Piecewise from sympy.sets.setexpr import SetExpr from sympy.testing.pytest import XFAIL, slow, raises x, y, z = symbols('x y z') r = Symbol('r', real=True) k, m = symbols('k m', integer=True) p = Symbol('p', positive=True) n = Symbol('n', negative=True) np = Symbol('p', nonpositive=True) nn = Symbol('n', nonnegative=True) nz = Symbol('nz', nonzero=True) ep = Symbol('ep', extended_positive=True) en = Symbol('en', extended_negative=True) enp = Symbol('ep', extended_nonpositive=True) enn = Symbol('en', extended_nonnegative=True) enz = Symbol('enz', extended_nonzero=True) a = Symbol('a', algebraic=True) na = Symbol('na', nonzero=True, algebraic=True) def test_sin(): x, y = symbols('x y') z = symbols('z', imaginary=True) assert sin.nargs == FiniteSet(1) assert sin(nan) is nan assert sin(zoo) is nan assert sin(oo) == AccumBounds(-1, 1) assert sin(oo) - sin(oo) == AccumBounds(-2, 2) assert sin(oo*I) == oo*I assert sin(-oo*I) == -oo*I assert 0*sin(oo) is S.Zero assert 0/sin(oo) is S.Zero assert 0 + sin(oo) == AccumBounds(-1, 1) assert 5 + sin(oo) == AccumBounds(4, 6) assert sin(0) == 0 assert sin(z*I) == I*sinh(z) assert sin(asin(x)) == x assert sin(atan(x)) == x / sqrt(1 + x**2) assert sin(acos(x)) == sqrt(1 - x**2) assert sin(acot(x)) == 1 / (sqrt(1 + 1 / x**2) * x) assert sin(acsc(x)) == 1 / x assert sin(asec(x)) == sqrt(1 - 1 / x**2) assert sin(atan2(y, x)) == y / sqrt(x**2 + y**2) assert sin(pi*I) == sinh(pi)*I assert sin(-pi*I) == -sinh(pi)*I assert sin(-2*I) == -sinh(2)*I assert sin(pi) == 0 assert sin(-pi) == 0 assert sin(2*pi) == 0 assert sin(-2*pi) == 0 assert sin(-3*10**73*pi) == 0 assert sin(7*10**103*pi) == 0 assert sin(pi/2) == 1 assert sin(-pi/2) == -1 assert sin(pi*Rational(5, 2)) == 1 assert sin(pi*Rational(7, 2)) == -1 ne = symbols('ne', integer=True, even=False) e = symbols('e', even=True) assert sin(pi*ne/2) == (-1)**(ne/2 - S.Half) assert sin(pi*k/2).func == sin assert sin(pi*e/2) == 0 assert sin(pi*k) == 0 assert sin(pi*k).subs(k, 3) == sin(pi*k/2).subs(k, 6) # issue 8298 assert sin(pi/3) == S.Half*sqrt(3) assert sin(pi*Rational(-2, 3)) == Rational(-1, 2)*sqrt(3) assert sin(pi/4) == S.Half*sqrt(2) assert sin(-pi/4) == Rational(-1, 2)*sqrt(2) assert sin(pi*Rational(17, 4)) == S.Half*sqrt(2) assert sin(pi*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2) assert sin(pi/6) == S.Half assert sin(-pi/6) == Rational(-1, 2) assert sin(pi*Rational(7, 6)) == Rational(-1, 2) assert sin(pi*Rational(-5, 6)) == Rational(-1, 2) assert sin(pi*Rational(1, 5)) == sqrt((5 - sqrt(5)) / 8) assert sin(pi*Rational(2, 5)) == sqrt((5 + sqrt(5)) / 8) assert sin(pi*Rational(3, 5)) == sin(pi*Rational(2, 5)) assert sin(pi*Rational(4, 5)) == sin(pi*Rational(1, 5)) assert sin(pi*Rational(6, 5)) == -sin(pi*Rational(1, 5)) assert sin(pi*Rational(8, 5)) == -sin(pi*Rational(2, 5)) assert sin(pi*Rational(-1273, 5)) == -sin(pi*Rational(2, 5)) assert sin(pi/8) == sqrt((2 - sqrt(2))/4) assert sin(pi/10) == Rational(-1, 4) + sqrt(5)/4 assert sin(pi/12) == -sqrt(2)/4 + sqrt(6)/4 assert sin(pi*Rational(5, 12)) == sqrt(2)/4 + sqrt(6)/4 assert sin(pi*Rational(-7, 12)) == -sqrt(2)/4 - sqrt(6)/4 assert sin(pi*Rational(-11, 12)) == sqrt(2)/4 - sqrt(6)/4 assert sin(pi*Rational(104, 105)) == sin(pi/105) assert sin(pi*Rational(106, 105)) == -sin(pi/105) assert sin(pi*Rational(-104, 105)) == -sin(pi/105) assert sin(pi*Rational(-106, 105)) == sin(pi/105) assert sin(x*I) == sinh(x)*I assert sin(k*pi) == 0 assert sin(17*k*pi) == 0 assert sin(2*k*pi + 4) == sin(4) assert sin(2*k*pi + m*pi + 1) == (-1)**(m + 2*k)*sin(1) assert sin(k*pi*I) == sinh(k*pi)*I assert sin(r).is_real is True assert sin(0, evaluate=False).is_algebraic assert sin(a).is_algebraic is None assert sin(na).is_algebraic is False q = Symbol('q', rational=True) assert sin(pi*q).is_algebraic qn = Symbol('qn', rational=True, nonzero=True) assert sin(qn).is_rational is False assert sin(q).is_rational is None # issue 8653 assert isinstance(sin( re(x) - im(y)), sin) is True assert isinstance(sin(-re(x) + im(y)), sin) is False assert sin(SetExpr(Interval(0, 1))) == SetExpr(ImageSet(Lambda(x, sin(x)), Interval(0, 1))) for d in list(range(1, 22)) + [60, 85]: for n in range(d*2 + 1): x = n*pi/d e = abs( float(sin(x)) - sin(float(x)) ) assert e < 1e-12 assert sin(0, evaluate=False).is_zero is True assert sin(k*pi, evaluate=False).is_zero is True assert sin(Add(1, -1, evaluate=False), evaluate=False).is_zero is True def test_sin_cos(): for d in [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 24, 30, 40, 60, 120]: # list is not exhaustive... for n in range(-2*d, d*2): x = n*pi/d assert sin(x + pi/2) == cos(x), "fails for %d*pi/%d" % (n, d) assert sin(x - pi/2) == -cos(x), "fails for %d*pi/%d" % (n, d) assert sin(x) == cos(x - pi/2), "fails for %d*pi/%d" % (n, d) assert -sin(x) == cos(x + pi/2), "fails for %d*pi/%d" % (n, d) def test_sin_series(): assert sin(x).series(x, 0, 9) == \ x - x**3/6 + x**5/120 - x**7/5040 + O(x**9) def test_sin_rewrite(): assert sin(x).rewrite(exp) == -I*(exp(I*x) - exp(-I*x))/2 assert sin(x).rewrite(tan) == 2*tan(x/2)/(1 + tan(x/2)**2) assert sin(x).rewrite(cot) == \ Piecewise((0, Eq(im(x), 0) & Eq(Mod(x, pi), 0)), (2*cot(x/2)/(cot(x/2)**2 + 1), True)) assert sin(sinh(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, sinh(3)).n() assert sin(cosh(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cosh(3)).n() assert sin(tanh(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, tanh(3)).n() assert sin(coth(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, coth(3)).n() assert sin(sin(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, sin(3)).n() assert sin(cos(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cos(3)).n() assert sin(tan(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, tan(3)).n() assert sin(cot(x)).rewrite( exp).subs(x, 3).n() == sin(x).rewrite(exp).subs(x, cot(3)).n() assert sin(log(x)).rewrite(Pow) == I*x**-I / 2 - I*x**I /2 assert sin(x).rewrite(csc) == 1/csc(x) assert sin(x).rewrite(cos) == cos(x - pi / 2, evaluate=False) assert sin(x).rewrite(sec) == 1 / sec(x - pi / 2, evaluate=False) assert sin(cos(x)).rewrite(Pow) == sin(cos(x)) def _test_extrig(f, i, e): from sympy.core.function import expand_trig assert unchanged(f, i) assert expand_trig(f(i)) == f(i) # testing directly instead of with .expand(trig=True) # because the other expansions undo the unevaluated Mul assert expand_trig(f(Mul(i, 1, evaluate=False))) == e assert abs(f(i) - e).n() < 1e-10 def test_sin_expansion(): # Note: these formulas are not unique. The ones here come from the # Chebyshev formulas. assert sin(x + y).expand(trig=True) == sin(x)*cos(y) + cos(x)*sin(y) assert sin(x - y).expand(trig=True) == sin(x)*cos(y) - cos(x)*sin(y) assert sin(y - x).expand(trig=True) == cos(x)*sin(y) - sin(x)*cos(y) assert sin(2*x).expand(trig=True) == 2*sin(x)*cos(x) assert sin(3*x).expand(trig=True) == -4*sin(x)**3 + 3*sin(x) assert sin(4*x).expand(trig=True) == -8*sin(x)**3*cos(x) + 4*sin(x)*cos(x) _test_extrig(sin, 2, 2*sin(1)*cos(1)) _test_extrig(sin, 3, -4*sin(1)**3 + 3*sin(1)) def test_sin_AccumBounds(): assert sin(AccumBounds(-oo, oo)) == AccumBounds(-1, 1) assert sin(AccumBounds(0, oo)) == AccumBounds(-1, 1) assert sin(AccumBounds(-oo, 0)) == AccumBounds(-1, 1) assert sin(AccumBounds(0, 2*S.Pi)) == AccumBounds(-1, 1) assert sin(AccumBounds(0, S.Pi*Rational(3, 4))) == AccumBounds(0, 1) assert sin(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(7, 4))) == AccumBounds(-1, sin(S.Pi*Rational(3, 4))) assert sin(AccumBounds(S.Pi/4, S.Pi/3)) == AccumBounds(sin(S.Pi/4), sin(S.Pi/3)) assert sin(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(5, 6))) == AccumBounds(sin(S.Pi*Rational(5, 6)), sin(S.Pi*Rational(3, 4))) def test_sin_fdiff(): assert sin(x).fdiff() == cos(x) raises(ArgumentIndexError, lambda: sin(x).fdiff(2)) def test_trig_symmetry(): assert sin(-x) == -sin(x) assert cos(-x) == cos(x) assert tan(-x) == -tan(x) assert cot(-x) == -cot(x) assert sin(x + pi) == -sin(x) assert sin(x + 2*pi) == sin(x) assert sin(x + 3*pi) == -sin(x) assert sin(x + 4*pi) == sin(x) assert sin(x - 5*pi) == -sin(x) assert cos(x + pi) == -cos(x) assert cos(x + 2*pi) == cos(x) assert cos(x + 3*pi) == -cos(x) assert cos(x + 4*pi) == cos(x) assert cos(x - 5*pi) == -cos(x) assert tan(x + pi) == tan(x) assert tan(x - 3*pi) == tan(x) assert cot(x + pi) == cot(x) assert cot(x - 3*pi) == cot(x) assert sin(pi/2 - x) == cos(x) assert sin(pi*Rational(3, 2) - x) == -cos(x) assert sin(pi*Rational(5, 2) - x) == cos(x) assert cos(pi/2 - x) == sin(x) assert cos(pi*Rational(3, 2) - x) == -sin(x) assert cos(pi*Rational(5, 2) - x) == sin(x) assert tan(pi/2 - x) == cot(x) assert tan(pi*Rational(3, 2) - x) == cot(x) assert tan(pi*Rational(5, 2) - x) == cot(x) assert cot(pi/2 - x) == tan(x) assert cot(pi*Rational(3, 2) - x) == tan(x) assert cot(pi*Rational(5, 2) - x) == tan(x) assert sin(pi/2 + x) == cos(x) assert cos(pi/2 + x) == -sin(x) assert tan(pi/2 + x) == -cot(x) assert cot(pi/2 + x) == -tan(x) def test_cos(): x, y = symbols('x y') assert cos.nargs == FiniteSet(1) assert cos(nan) is nan assert cos(oo) == AccumBounds(-1, 1) assert cos(oo) - cos(oo) == AccumBounds(-2, 2) assert cos(oo*I) is oo assert cos(-oo*I) is oo assert cos(zoo) is nan assert cos(0) == 1 assert cos(acos(x)) == x assert cos(atan(x)) == 1 / sqrt(1 + x**2) assert cos(asin(x)) == sqrt(1 - x**2) assert cos(acot(x)) == 1 / sqrt(1 + 1 / x**2) assert cos(acsc(x)) == sqrt(1 - 1 / x**2) assert cos(asec(x)) == 1 / x assert cos(atan2(y, x)) == x / sqrt(x**2 + y**2) assert cos(pi*I) == cosh(pi) assert cos(-pi*I) == cosh(pi) assert cos(-2*I) == cosh(2) assert cos(pi/2) == 0 assert cos(-pi/2) == 0 assert cos(pi/2) == 0 assert cos(-pi/2) == 0 assert cos((-3*10**73 + 1)*pi/2) == 0 assert cos((7*10**103 + 1)*pi/2) == 0 n = symbols('n', integer=True, even=False) e = symbols('e', even=True) assert cos(pi*n/2) == 0 assert cos(pi*e/2) == (-1)**(e/2) assert cos(pi) == -1 assert cos(-pi) == -1 assert cos(2*pi) == 1 assert cos(5*pi) == -1 assert cos(8*pi) == 1 assert cos(pi/3) == S.Half assert cos(pi*Rational(-2, 3)) == Rational(-1, 2) assert cos(pi/4) == S.Half*sqrt(2) assert cos(-pi/4) == S.Half*sqrt(2) assert cos(pi*Rational(11, 4)) == Rational(-1, 2)*sqrt(2) assert cos(pi*Rational(-3, 4)) == Rational(-1, 2)*sqrt(2) assert cos(pi/6) == S.Half*sqrt(3) assert cos(-pi/6) == S.Half*sqrt(3) assert cos(pi*Rational(7, 6)) == Rational(-1, 2)*sqrt(3) assert cos(pi*Rational(-5, 6)) == Rational(-1, 2)*sqrt(3) assert cos(pi*Rational(1, 5)) == (sqrt(5) + 1)/4 assert cos(pi*Rational(2, 5)) == (sqrt(5) - 1)/4 assert cos(pi*Rational(3, 5)) == -cos(pi*Rational(2, 5)) assert cos(pi*Rational(4, 5)) == -cos(pi*Rational(1, 5)) assert cos(pi*Rational(6, 5)) == -cos(pi*Rational(1, 5)) assert cos(pi*Rational(8, 5)) == cos(pi*Rational(2, 5)) assert cos(pi*Rational(-1273, 5)) == -cos(pi*Rational(2, 5)) assert cos(pi/8) == sqrt((2 + sqrt(2))/4) assert cos(pi/12) == sqrt(2)/4 + sqrt(6)/4 assert cos(pi*Rational(5, 12)) == -sqrt(2)/4 + sqrt(6)/4 assert cos(pi*Rational(7, 12)) == sqrt(2)/4 - sqrt(6)/4 assert cos(pi*Rational(11, 12)) == -sqrt(2)/4 - sqrt(6)/4 assert cos(pi*Rational(104, 105)) == -cos(pi/105) assert cos(pi*Rational(106, 105)) == -cos(pi/105) assert cos(pi*Rational(-104, 105)) == -cos(pi/105) assert cos(pi*Rational(-106, 105)) == -cos(pi/105) assert cos(x*I) == cosh(x) assert cos(k*pi*I) == cosh(k*pi) assert cos(r).is_real is True assert cos(0, evaluate=False).is_algebraic assert cos(a).is_algebraic is None assert cos(na).is_algebraic is False q = Symbol('q', rational=True) assert cos(pi*q).is_algebraic assert cos(pi*Rational(2, 7)).is_algebraic assert cos(k*pi) == (-1)**k assert cos(2*k*pi) == 1 assert cos(0, evaluate=False).is_zero is False assert cos(Rational(1, 2)).is_zero is False # The following test will return None as the result, but really it should # be True even if it is not always possible to resolve an assumptions query. assert cos(asin(-1, evaluate=False), evaluate=False).is_zero is None for d in list(range(1, 22)) + [60, 85]: for n in range(2*d + 1): x = n*pi/d e = abs( float(cos(x)) - cos(float(x)) ) assert e < 1e-12 def test_issue_6190(): c = Float('123456789012345678901234567890.25', '') for cls in [sin, cos, tan, cot]: assert cls(c*pi) == cls(pi/4) assert cls(4.125*pi) == cls(pi/8) assert cls(4.7*pi) == cls((4.7 % 2)*pi) def test_cos_series(): assert cos(x).series(x, 0, 9) == \ 1 - x**2/2 + x**4/24 - x**6/720 + x**8/40320 + O(x**9) def test_cos_rewrite(): assert cos(x).rewrite(exp) == exp(I*x)/2 + exp(-I*x)/2 assert cos(x).rewrite(tan) == (1 - tan(x/2)**2)/(1 + tan(x/2)**2) assert cos(x).rewrite(cot) == \ Piecewise((1, Eq(im(x), 0) & Eq(Mod(x, 2*pi), 0)), ((cot(x/2)**2 - 1)/(cot(x/2)**2 + 1), True)) assert cos(sinh(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, sinh(3)).n() assert cos(cosh(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cosh(3)).n() assert cos(tanh(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, tanh(3)).n() assert cos(coth(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, coth(3)).n() assert cos(sin(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, sin(3)).n() assert cos(cos(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cos(3)).n() assert cos(tan(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, tan(3)).n() assert cos(cot(x)).rewrite( exp).subs(x, 3).n() == cos(x).rewrite(exp).subs(x, cot(3)).n() assert cos(log(x)).rewrite(Pow) == x**I/2 + x**-I/2 assert cos(x).rewrite(sec) == 1/sec(x) assert cos(x).rewrite(sin) == sin(x + pi/2, evaluate=False) assert cos(x).rewrite(csc) == 1/csc(-x + pi/2, evaluate=False) assert cos(sin(x)).rewrite(Pow) == cos(sin(x)) def test_cos_expansion(): assert cos(x + y).expand(trig=True) == cos(x)*cos(y) - sin(x)*sin(y) assert cos(x - y).expand(trig=True) == cos(x)*cos(y) + sin(x)*sin(y) assert cos(y - x).expand(trig=True) == cos(x)*cos(y) + sin(x)*sin(y) assert cos(2*x).expand(trig=True) == 2*cos(x)**2 - 1 assert cos(3*x).expand(trig=True) == 4*cos(x)**3 - 3*cos(x) assert cos(4*x).expand(trig=True) == 8*cos(x)**4 - 8*cos(x)**2 + 1 _test_extrig(cos, 2, 2*cos(1)**2 - 1) _test_extrig(cos, 3, 4*cos(1)**3 - 3*cos(1)) def test_cos_AccumBounds(): assert cos(AccumBounds(-oo, oo)) == AccumBounds(-1, 1) assert cos(AccumBounds(0, oo)) == AccumBounds(-1, 1) assert cos(AccumBounds(-oo, 0)) == AccumBounds(-1, 1) assert cos(AccumBounds(0, 2*S.Pi)) == AccumBounds(-1, 1) assert cos(AccumBounds(-S.Pi/3, S.Pi/4)) == AccumBounds(cos(-S.Pi/3), 1) assert cos(AccumBounds(S.Pi*Rational(3, 4), S.Pi*Rational(5, 4))) == AccumBounds(-1, cos(S.Pi*Rational(3, 4))) assert cos(AccumBounds(S.Pi*Rational(5, 4), S.Pi*Rational(4, 3))) == AccumBounds(cos(S.Pi*Rational(5, 4)), cos(S.Pi*Rational(4, 3))) assert cos(AccumBounds(S.Pi/4, S.Pi/3)) == AccumBounds(cos(S.Pi/3), cos(S.Pi/4)) def test_cos_fdiff(): assert cos(x).fdiff() == -sin(x) raises(ArgumentIndexError, lambda: cos(x).fdiff(2)) def test_tan(): assert tan(nan) is nan assert tan(zoo) is nan assert tan(oo) == AccumBounds(-oo, oo) assert tan(oo) - tan(oo) == AccumBounds(-oo, oo) assert tan.nargs == FiniteSet(1) assert tan(oo*I) == I assert tan(-oo*I) == -I assert tan(0) == 0 assert tan(atan(x)) == x assert tan(asin(x)) == x / sqrt(1 - x**2) assert tan(acos(x)) == sqrt(1 - x**2) / x assert tan(acot(x)) == 1 / x assert tan(acsc(x)) == 1 / (sqrt(1 - 1 / x**2) * x) assert tan(asec(x)) == sqrt(1 - 1 / x**2) * x assert tan(atan2(y, x)) == y/x assert tan(pi*I) == tanh(pi)*I assert tan(-pi*I) == -tanh(pi)*I assert tan(-2*I) == -tanh(2)*I assert tan(pi) == 0 assert tan(-pi) == 0 assert tan(2*pi) == 0 assert tan(-2*pi) == 0 assert tan(-3*10**73*pi) == 0 assert tan(pi/2) is zoo assert tan(pi*Rational(3, 2)) is zoo assert tan(pi/3) == sqrt(3) assert tan(pi*Rational(-2, 3)) == sqrt(3) assert tan(pi/4) is S.One assert tan(-pi/4) is S.NegativeOne assert tan(pi*Rational(17, 4)) is S.One assert tan(pi*Rational(-3, 4)) is S.One assert tan(pi/5) == sqrt(5 - 2*sqrt(5)) assert tan(pi*Rational(2, 5)) == sqrt(5 + 2*sqrt(5)) assert tan(pi*Rational(18, 5)) == -sqrt(5 + 2*sqrt(5)) assert tan(pi*Rational(-16, 5)) == -sqrt(5 - 2*sqrt(5)) assert tan(pi/6) == 1/sqrt(3) assert tan(-pi/6) == -1/sqrt(3) assert tan(pi*Rational(7, 6)) == 1/sqrt(3) assert tan(pi*Rational(-5, 6)) == 1/sqrt(3) assert tan(pi/8) == -1 + sqrt(2) assert tan(pi*Rational(3, 8)) == 1 + sqrt(2) # issue 15959 assert tan(pi*Rational(5, 8)) == -1 - sqrt(2) assert tan(pi*Rational(7, 8)) == 1 - sqrt(2) assert tan(pi/10) == sqrt(1 - 2*sqrt(5)/5) assert tan(pi*Rational(3, 10)) == sqrt(1 + 2*sqrt(5)/5) assert tan(pi*Rational(17, 10)) == -sqrt(1 + 2*sqrt(5)/5) assert tan(pi*Rational(-31, 10)) == -sqrt(1 - 2*sqrt(5)/5) assert tan(pi/12) == -sqrt(3) + 2 assert tan(pi*Rational(5, 12)) == sqrt(3) + 2 assert tan(pi*Rational(7, 12)) == -sqrt(3) - 2 assert tan(pi*Rational(11, 12)) == sqrt(3) - 2 assert tan(pi/24).radsimp() == -2 - sqrt(3) + sqrt(2) + sqrt(6) assert tan(pi*Rational(5, 24)).radsimp() == -2 + sqrt(3) - sqrt(2) + sqrt(6) assert tan(pi*Rational(7, 24)).radsimp() == 2 - sqrt(3) - sqrt(2) + sqrt(6) assert tan(pi*Rational(11, 24)).radsimp() == 2 + sqrt(3) + sqrt(2) + sqrt(6) assert tan(pi*Rational(13, 24)).radsimp() == -2 - sqrt(3) - sqrt(2) - sqrt(6) assert tan(pi*Rational(17, 24)).radsimp() == -2 + sqrt(3) + sqrt(2) - sqrt(6) assert tan(pi*Rational(19, 24)).radsimp() == 2 - sqrt(3) + sqrt(2) - sqrt(6) assert tan(pi*Rational(23, 24)).radsimp() == 2 + sqrt(3) - sqrt(2) - sqrt(6) assert tan(x*I) == tanh(x)*I assert tan(k*pi) == 0 assert tan(17*k*pi) == 0 assert tan(k*pi*I) == tanh(k*pi)*I assert tan(r).is_real is None assert tan(r).is_extended_real is True assert tan(0, evaluate=False).is_algebraic assert tan(a).is_algebraic is None assert tan(na).is_algebraic is False assert tan(pi*Rational(10, 7)) == tan(pi*Rational(3, 7)) assert tan(pi*Rational(11, 7)) == -tan(pi*Rational(3, 7)) assert tan(pi*Rational(-11, 7)) == tan(pi*Rational(3, 7)) assert tan(pi*Rational(15, 14)) == tan(pi/14) assert tan(pi*Rational(-15, 14)) == -tan(pi/14) assert tan(r).is_finite is None assert tan(I*r).is_finite is True # https://github.com/sympy/sympy/issues/21177 f = tan(pi*(x + S(3)/2))/(3*x) assert f.as_leading_term(x) == -1/(3*pi*x**2) def test_tan_series(): assert tan(x).series(x, 0, 9) == \ x + x**3/3 + 2*x**5/15 + 17*x**7/315 + O(x**9) def test_tan_rewrite(): neg_exp, pos_exp = exp(-x*I), exp(x*I) assert tan(x).rewrite(exp) == I*(neg_exp - pos_exp)/(neg_exp + pos_exp) assert tan(x).rewrite(sin) == 2*sin(x)**2/sin(2*x) assert tan(x).rewrite(cos) == cos(x - S.Pi/2, evaluate=False)/cos(x) assert tan(x).rewrite(cot) == 1/cot(x) assert tan(sinh(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sinh(3)).n() assert tan(cosh(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cosh(3)).n() assert tan(tanh(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tanh(3)).n() assert tan(coth(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, coth(3)).n() assert tan(sin(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, sin(3)).n() assert tan(cos(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cos(3)).n() assert tan(tan(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, tan(3)).n() assert tan(cot(x)).rewrite(exp).subs(x, 3).n() == tan(x).rewrite(exp).subs(x, cot(3)).n() assert tan(log(x)).rewrite(Pow) == I*(x**-I - x**I)/(x**-I + x**I) assert tan(x).rewrite(sec) == sec(x)/sec(x - pi/2, evaluate=False) assert tan(x).rewrite(csc) == csc(-x + pi/2, evaluate=False)/csc(x) assert tan(sin(x)).rewrite(Pow) == tan(sin(x)) @slow def test_tan_rewrite_slow(): assert 0 == (cos(pi/34)*tan(pi/34) - sin(pi/34)).rewrite(pow) assert 0 == (cos(pi/17)*tan(pi/17) - sin(pi/17)).rewrite(pow) assert tan(pi/19).rewrite(pow) == tan(pi/19) assert tan(pi*Rational(8, 19)).rewrite(sqrt) == tan(pi*Rational(8, 19)) assert tan(pi*Rational(2, 5), evaluate=False).rewrite(sqrt) == sqrt(sqrt(5)/8 + Rational(5, 8))/(Rational(-1, 4) + sqrt(5)/4) def test_tan_subs(): assert tan(x).subs(tan(x), y) == y assert tan(x).subs(x, y) == tan(y) assert tan(x).subs(x, S.Pi/2) is zoo assert tan(x).subs(x, S.Pi*Rational(3, 2)) is zoo def test_tan_expansion(): assert tan(x + y).expand(trig=True) == ((tan(x) + tan(y))/(1 - tan(x)*tan(y))).expand() assert tan(x - y).expand(trig=True) == ((tan(x) - tan(y))/(1 + tan(x)*tan(y))).expand() assert tan(x + y + z).expand(trig=True) == ( (tan(x) + tan(y) + tan(z) - tan(x)*tan(y)*tan(z))/ (1 - tan(x)*tan(y) - tan(x)*tan(z) - tan(y)*tan(z))).expand() assert 0 == tan(2*x).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 7))])*24 - 7 assert 0 == tan(3*x).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 5))])*55 - 37 assert 0 == tan(4*x - pi/4).expand(trig=True).rewrite(tan).subs([(tan(x), Rational(1, 5))])*239 - 1 _test_extrig(tan, 2, 2*tan(1)/(1 - tan(1)**2)) _test_extrig(tan, 3, (-tan(1)**3 + 3*tan(1))/(1 - 3*tan(1)**2)) def test_tan_AccumBounds(): assert tan(AccumBounds(-oo, oo)) == AccumBounds(-oo, oo) assert tan(AccumBounds(S.Pi/3, S.Pi*Rational(2, 3))) == AccumBounds(-oo, oo) assert tan(AccumBounds(S.Pi/6, S.Pi/3)) == AccumBounds(tan(S.Pi/6), tan(S.Pi/3)) def test_tan_fdiff(): assert tan(x).fdiff() == tan(x)**2 + 1 raises(ArgumentIndexError, lambda: tan(x).fdiff(2)) def test_cot(): assert cot(nan) is nan assert cot.nargs == FiniteSet(1) assert cot(oo*I) == -I assert cot(-oo*I) == I assert cot(zoo) is nan assert cot(0) is zoo assert cot(2*pi) is zoo assert cot(acot(x)) == x assert cot(atan(x)) == 1 / x assert cot(asin(x)) == sqrt(1 - x**2) / x assert cot(acos(x)) == x / sqrt(1 - x**2) assert cot(acsc(x)) == sqrt(1 - 1 / x**2) * x assert cot(asec(x)) == 1 / (sqrt(1 - 1 / x**2) * x) assert cot(atan2(y, x)) == x/y assert cot(pi*I) == -coth(pi)*I assert cot(-pi*I) == coth(pi)*I assert cot(-2*I) == coth(2)*I assert cot(pi) == cot(2*pi) == cot(3*pi) assert cot(-pi) == cot(-2*pi) == cot(-3*pi) assert cot(pi/2) == 0 assert cot(-pi/2) == 0 assert cot(pi*Rational(5, 2)) == 0 assert cot(pi*Rational(7, 2)) == 0 assert cot(pi/3) == 1/sqrt(3) assert cot(pi*Rational(-2, 3)) == 1/sqrt(3) assert cot(pi/4) is S.One assert cot(-pi/4) is S.NegativeOne assert cot(pi*Rational(17, 4)) is S.One assert cot(pi*Rational(-3, 4)) is S.One assert cot(pi/6) == sqrt(3) assert cot(-pi/6) == -sqrt(3) assert cot(pi*Rational(7, 6)) == sqrt(3) assert cot(pi*Rational(-5, 6)) == sqrt(3) assert cot(pi/8) == 1 + sqrt(2) assert cot(pi*Rational(3, 8)) == -1 + sqrt(2) assert cot(pi*Rational(5, 8)) == 1 - sqrt(2) assert cot(pi*Rational(7, 8)) == -1 - sqrt(2) assert cot(pi/12) == sqrt(3) + 2 assert cot(pi*Rational(5, 12)) == -sqrt(3) + 2 assert cot(pi*Rational(7, 12)) == sqrt(3) - 2 assert cot(pi*Rational(11, 12)) == -sqrt(3) - 2 assert cot(pi/24).radsimp() == sqrt(2) + sqrt(3) + 2 + sqrt(6) assert cot(pi*Rational(5, 24)).radsimp() == -sqrt(2) - sqrt(3) + 2 + sqrt(6) assert cot(pi*Rational(7, 24)).radsimp() == -sqrt(2) + sqrt(3) - 2 + sqrt(6) assert cot(pi*Rational(11, 24)).radsimp() == sqrt(2) - sqrt(3) - 2 + sqrt(6) assert cot(pi*Rational(13, 24)).radsimp() == -sqrt(2) + sqrt(3) + 2 - sqrt(6) assert cot(pi*Rational(17, 24)).radsimp() == sqrt(2) - sqrt(3) + 2 - sqrt(6) assert cot(pi*Rational(19, 24)).radsimp() == sqrt(2) + sqrt(3) - 2 - sqrt(6) assert cot(pi*Rational(23, 24)).radsimp() == -sqrt(2) - sqrt(3) - 2 - sqrt(6) assert cot(x*I) == -coth(x)*I assert cot(k*pi*I) == -coth(k*pi)*I assert cot(r).is_real is None assert cot(r).is_extended_real is True assert cot(a).is_algebraic is None assert cot(na).is_algebraic is False assert cot(pi*Rational(10, 7)) == cot(pi*Rational(3, 7)) assert cot(pi*Rational(11, 7)) == -cot(pi*Rational(3, 7)) assert cot(pi*Rational(-11, 7)) == cot(pi*Rational(3, 7)) assert cot(pi*Rational(39, 34)) == cot(pi*Rational(5, 34)) assert cot(pi*Rational(-41, 34)) == -cot(pi*Rational(7, 34)) assert cot(x).is_finite is None assert cot(r).is_finite is None i = Symbol('i', imaginary=True) assert cot(i).is_finite is True assert cot(x).subs(x, 3*pi) is zoo # https://github.com/sympy/sympy/issues/21177 f = cot(pi*(x + 4))/(3*x) assert f.as_leading_term(x) == 1/(3*pi*x**2) def test_tan_cot_sin_cos_evalf(): assert abs((tan(pi*Rational(8, 15))*cos(pi*Rational(8, 15))/sin(pi*Rational(8, 15)) - 1).evalf()) < 1e-14 assert abs((cot(pi*Rational(4, 15))*sin(pi*Rational(4, 15))/cos(pi*Rational(4, 15)) - 1).evalf()) < 1e-14 @XFAIL def test_tan_cot_sin_cos_ratsimp(): assert 1 == (tan(pi*Rational(8, 15))*cos(pi*Rational(8, 15))/sin(pi*Rational(8, 15))).ratsimp() assert 1 == (cot(pi*Rational(4, 15))*sin(pi*Rational(4, 15))/cos(pi*Rational(4, 15))).ratsimp() def test_cot_series(): assert cot(x).series(x, 0, 9) == \ 1/x - x/3 - x**3/45 - 2*x**5/945 - x**7/4725 + O(x**9) # issue 6210 assert cot(x**4 + x**5).series(x, 0, 1) == \ x**(-4) - 1/x**3 + x**(-2) - 1/x + 1 + O(x) assert cot(pi*(1-x)).series(x, 0, 3) == -1/(pi*x) + pi*x/3 + O(x**3) assert cot(x).taylor_term(0, x) == 1/x assert cot(x).taylor_term(2, x) is S.Zero assert cot(x).taylor_term(3, x) == -x**3/45 def test_cot_rewrite(): neg_exp, pos_exp = exp(-x*I), exp(x*I) assert cot(x).rewrite(exp) == I*(pos_exp + neg_exp)/(pos_exp - neg_exp) assert cot(x).rewrite(sin) == sin(2*x)/(2*(sin(x)**2)) assert cot(x).rewrite(cos) == cos(x)/cos(x - pi/2, evaluate=False) assert cot(x).rewrite(tan) == 1/tan(x) def check(func): z = cot(func(x)).rewrite(exp) - cot(x).rewrite(exp).subs(x, func(x)) assert z.rewrite(exp).expand() == 0 check(sinh) check(cosh) check(tanh) check(coth) check(sin) check(cos) check(tan) assert cot(log(x)).rewrite(Pow) == -I*(x**-I + x**I)/(x**-I - x**I) assert cot(x).rewrite(sec) == sec(x - pi / 2, evaluate=False) / sec(x) assert cot(x).rewrite(csc) == csc(x) / csc(- x + pi / 2, evaluate=False) assert cot(sin(x)).rewrite(Pow) == cot(sin(x)) @slow def test_cot_rewrite_slow(): assert cot(pi*Rational(4, 34)).rewrite(pow).ratsimp() == \ (cos(pi*Rational(4, 34))/sin(pi*Rational(4, 34))).rewrite(pow).ratsimp() assert cot(pi*Rational(4, 17)).rewrite(pow) == \ (cos(pi*Rational(4, 17))/sin(pi*Rational(4, 17))).rewrite(pow) assert cot(pi/19).rewrite(pow) == cot(pi/19) assert cot(pi/19).rewrite(sqrt) == cot(pi/19) assert cot(pi*Rational(2, 5), evaluate=False).rewrite(sqrt) == \ (Rational(-1, 4) + sqrt(5)/4) / sqrt(sqrt(5)/8 + Rational(5, 8)) def test_cot_subs(): assert cot(x).subs(cot(x), y) == y assert cot(x).subs(x, y) == cot(y) assert cot(x).subs(x, 0) is zoo assert cot(x).subs(x, S.Pi) is zoo def test_cot_expansion(): assert cot(x + y).expand(trig=True).together() == ( (cot(x)*cot(y) - 1)/(cot(x) + cot(y))) assert cot(x - y).expand(trig=True).together() == ( cot(x)*cot(-y) - 1)/(cot(x) + cot(-y)) assert cot(x + y + z).expand(trig=True).together() == ( (cot(x)*cot(y)*cot(z) - cot(x) - cot(y) - cot(z))/ (-1 + cot(x)*cot(y) + cot(x)*cot(z) + cot(y)*cot(z))) assert cot(3*x).expand(trig=True).together() == ( (cot(x)**2 - 3)*cot(x)/(3*cot(x)**2 - 1)) assert cot(2*x).expand(trig=True) == cot(x)/2 - 1/(2*cot(x)) assert cot(3*x).expand(trig=True).together() == ( cot(x)**2 - 3)*cot(x)/(3*cot(x)**2 - 1) assert cot(4*x - pi/4).expand(trig=True).cancel() == ( -tan(x)**4 + 4*tan(x)**3 + 6*tan(x)**2 - 4*tan(x) - 1 )/(tan(x)**4 + 4*tan(x)**3 - 6*tan(x)**2 - 4*tan(x) + 1) _test_extrig(cot, 2, (-1 + cot(1)**2)/(2*cot(1))) _test_extrig(cot, 3, (-3*cot(1) + cot(1)**3)/(-1 + 3*cot(1)**2)) def test_cot_AccumBounds(): assert cot(AccumBounds(-oo, oo)) == AccumBounds(-oo, oo) assert cot(AccumBounds(-S.Pi/3, S.Pi/3)) == AccumBounds(-oo, oo) assert cot(AccumBounds(S.Pi/6, S.Pi/3)) == AccumBounds(cot(S.Pi/3), cot(S.Pi/6)) def test_cot_fdiff(): assert cot(x).fdiff() == -cot(x)**2 - 1 raises(ArgumentIndexError, lambda: cot(x).fdiff(2)) def test_sinc(): assert isinstance(sinc(x), sinc) s = Symbol('s', zero=True) assert sinc(s) is S.One assert sinc(S.Infinity) is S.Zero assert sinc(S.NegativeInfinity) is S.Zero assert sinc(S.NaN) is S.NaN assert sinc(S.ComplexInfinity) is S.NaN n = Symbol('n', integer=True, nonzero=True) assert sinc(n*pi) is S.Zero assert sinc(-n*pi) is S.Zero assert sinc(pi/2) == 2 / pi assert sinc(-pi/2) == 2 / pi assert sinc(pi*Rational(5, 2)) == 2 / (5*pi) assert sinc(pi*Rational(7, 2)) == -2 / (7*pi) assert sinc(-x) == sinc(x) assert sinc(x).diff(x) == cos(x)/x - sin(x)/x**2 assert sinc(x).diff(x) == (sin(x)/x).diff(x) assert sinc(x).diff(x, x) == (-sin(x) - 2*cos(x)/x + 2*sin(x)/x**2)/x assert sinc(x).diff(x, x) == (sin(x)/x).diff(x, x) assert limit(sinc(x).diff(x), x, 0) == 0 assert limit(sinc(x).diff(x, x), x, 0) == -S(1)/3 # https://github.com/sympy/sympy/issues/11402 # # assert sinc(x).diff(x) == Piecewise(((x*cos(x) - sin(x)) / x**2, Ne(x, 0)), (0, True)) # # assert sinc(x).diff(x).equals(sinc(x).rewrite(sin).diff(x)) # # assert sinc(x).diff(x).subs(x, 0) is S.Zero assert sinc(x).series() == 1 - x**2/6 + x**4/120 + O(x**6) assert sinc(x).rewrite(jn) == jn(0, x) assert sinc(x).rewrite(sin) == Piecewise((sin(x)/x, Ne(x, 0)), (1, True)) assert sinc(pi, evaluate=False).is_zero is True assert sinc(0, evaluate=False).is_zero is False assert sinc(n*pi, evaluate=False).is_zero is True assert sinc(x).is_zero is None xr = Symbol('xr', real=True, nonzero=True) assert sinc(x).is_real is None assert sinc(xr).is_real is True assert sinc(I*xr).is_real is True assert sinc(I*100).is_real is True assert sinc(x).is_finite is None assert sinc(xr).is_finite is True def test_asin(): assert asin(nan) is nan assert asin.nargs == FiniteSet(1) assert asin(oo) == -I*oo assert asin(-oo) == I*oo assert asin(zoo) is zoo # Note: asin(-x) = - asin(x) assert asin(0) == 0 assert asin(1) == pi/2 assert asin(-1) == -pi/2 assert asin(sqrt(3)/2) == pi/3 assert asin(-sqrt(3)/2) == -pi/3 assert asin(sqrt(2)/2) == pi/4 assert asin(-sqrt(2)/2) == -pi/4 assert asin(sqrt((5 - sqrt(5))/8)) == pi/5 assert asin(-sqrt((5 - sqrt(5))/8)) == -pi/5 assert asin(S.Half) == pi/6 assert asin(Rational(-1, 2)) == -pi/6 assert asin((sqrt(2 - sqrt(2)))/2) == pi/8 assert asin(-(sqrt(2 - sqrt(2)))/2) == -pi/8 assert asin((sqrt(5) - 1)/4) == pi/10 assert asin(-(sqrt(5) - 1)/4) == -pi/10 assert asin((sqrt(3) - 1)/sqrt(2**3)) == pi/12 assert asin(-(sqrt(3) - 1)/sqrt(2**3)) == -pi/12 # check round-trip for exact values: for d in [5, 6, 8, 10, 12]: for n in range(-(d//2), d//2 + 1): if gcd(n, d) == 1: assert asin(sin(n*pi/d)) == n*pi/d assert asin(x).diff(x) == 1/sqrt(1 - x**2) assert asin(0.2, evaluate=False).is_real is True assert asin(-2).is_real is False assert asin(r).is_real is None assert asin(-2*I) == -I*asinh(2) assert asin(Rational(1, 7), evaluate=False).is_positive is True assert asin(Rational(-1, 7), evaluate=False).is_positive is False assert asin(p).is_positive is None assert asin(sin(Rational(7, 2))) == Rational(-7, 2) + pi assert asin(sin(Rational(-7, 4))) == Rational(7, 4) - pi assert unchanged(asin, cos(x)) def test_asin_series(): assert asin(x).series(x, 0, 9) == \ x + x**3/6 + 3*x**5/40 + 5*x**7/112 + O(x**9) t5 = asin(x).taylor_term(5, x) assert t5 == 3*x**5/40 assert asin(x).taylor_term(7, x, t5, 0) == 5*x**7/112 def test_asin_leading_term(): assert asin(x).as_leading_term(x) == x # Tests concerning branch points assert asin(x + 1).as_leading_term(x) == pi/2 assert asin(x - 1).as_leading_term(x) == -pi/2 assert asin(1/x).as_leading_term(x, cdir=1) == I*log(x) + pi/2 - I*log(2) assert asin(1/x).as_leading_term(x, cdir=-1) == -I*log(x) - 3*pi/2 + I*log(2) # Tests concerning points lying on branch cuts assert asin(I*x + 2).as_leading_term(x, cdir=1) == pi - asin(2) assert asin(-I*x + 2).as_leading_term(x, cdir=1) == asin(2) assert asin(I*x - 2).as_leading_term(x, cdir=1) == -asin(2) assert asin(-I*x - 2).as_leading_term(x, cdir=1) == -pi + asin(2) # Tests concerning im(ndir) == 0 assert asin(-I*x**2 + x - 2).as_leading_term(x, cdir=1) == -pi/2 + I*log(2 - sqrt(3)) assert asin(-I*x**2 + x - 2).as_leading_term(x, cdir=-1) == -pi/2 + I*log(2 - sqrt(3)) def test_asin_rewrite(): assert asin(x).rewrite(log) == -I*log(I*x + sqrt(1 - x**2)) assert asin(x).rewrite(atan) == 2*atan(x/(1 + sqrt(1 - x**2))) assert asin(x).rewrite(acos) == S.Pi/2 - acos(x) assert asin(x).rewrite(acot) == 2*acot((sqrt(-x**2 + 1) + 1)/x) assert asin(x).rewrite(asec) == -asec(1/x) + pi/2 assert asin(x).rewrite(acsc) == acsc(1/x) def test_asin_fdiff(): assert asin(x).fdiff() == 1/sqrt(1 - x**2) raises(ArgumentIndexError, lambda: asin(x).fdiff(2)) def test_acos(): assert acos(nan) is nan assert acos(zoo) is zoo assert acos.nargs == FiniteSet(1) assert acos(oo) == I*oo assert acos(-oo) == -I*oo # Note: acos(-x) = pi - acos(x) assert acos(0) == pi/2 assert acos(S.Half) == pi/3 assert acos(Rational(-1, 2)) == pi*Rational(2, 3) assert acos(1) == 0 assert acos(-1) == pi assert acos(sqrt(2)/2) == pi/4 assert acos(-sqrt(2)/2) == pi*Rational(3, 4) # check round-trip for exact values: for d in [5, 6, 8, 10, 12]: for num in range(d): if gcd(num, d) == 1: assert acos(cos(num*pi/d)) == num*pi/d assert acos(2*I) == pi/2 - asin(2*I) assert acos(x).diff(x) == -1/sqrt(1 - x**2) assert acos(0.2).is_real is True assert acos(-2).is_real is False assert acos(r).is_real is None assert acos(Rational(1, 7), evaluate=False).is_positive is True assert acos(Rational(-1, 7), evaluate=False).is_positive is True assert acos(Rational(3, 2), evaluate=False).is_positive is False assert acos(p).is_positive is None assert acos(2 + p).conjugate() != acos(10 + p) assert acos(-3 + n).conjugate() != acos(-3 + n) assert acos(Rational(1, 3)).conjugate() == acos(Rational(1, 3)) assert acos(Rational(-1, 3)).conjugate() == acos(Rational(-1, 3)) assert acos(p + n*I).conjugate() == acos(p - n*I) assert acos(z).conjugate() != acos(conjugate(z)) def test_acos_leading_term(): assert acos(x).as_leading_term(x) == pi/2 # Tests concerning branch points assert acos(x + 1).as_leading_term(x) == sqrt(2)*sqrt(-x) assert acos(x - 1).as_leading_term(x) == pi assert acos(1/x).as_leading_term(x, cdir=1) == -I*log(x) + I*log(2) assert acos(1/x).as_leading_term(x, cdir=-1) == I*log(x) + 2*pi - I*log(2) # Tests concerning points lying on branch cuts assert acos(I*x + 2).as_leading_term(x, cdir=1) == -acos(2) assert acos(-I*x + 2).as_leading_term(x, cdir=1) == acos(2) assert acos(I*x - 2).as_leading_term(x, cdir=1) == acos(-2) assert acos(-I*x - 2).as_leading_term(x, cdir=1) == 2*pi - acos(-2) # Tests concerning im(ndir) == 0 assert acos(-I*x**2 + x - 2).as_leading_term(x, cdir=1) == pi + I*log(sqrt(3) + 2) assert acos(-I*x**2 + x - 2).as_leading_term(x, cdir=-1) == pi + I*log(sqrt(3) + 2) def test_acos_series(): assert acos(x).series(x, 0, 8) == \ pi/2 - x - x**3/6 - 3*x**5/40 - 5*x**7/112 + O(x**8) assert acos(x).series(x, 0, 8) == pi/2 - asin(x).series(x, 0, 8) t5 = acos(x).taylor_term(5, x) assert t5 == -3*x**5/40 assert acos(x).taylor_term(7, x, t5, 0) == -5*x**7/112 assert acos(x).taylor_term(0, x) == pi/2 assert acos(x).taylor_term(2, x) is S.Zero def test_acos_rewrite(): assert acos(x).rewrite(log) == pi/2 + I*log(I*x + sqrt(1 - x**2)) assert acos(x).rewrite(atan) == pi*(-x*sqrt(x**(-2)) + 1)/2 + atan(sqrt(1 - x**2)/x) assert acos(0).rewrite(atan) == S.Pi/2 assert acos(0.5).rewrite(atan) == acos(0.5).rewrite(log) assert acos(x).rewrite(asin) == S.Pi/2 - asin(x) assert acos(x).rewrite(acot) == -2*acot((sqrt(-x**2 + 1) + 1)/x) + pi/2 assert acos(x).rewrite(asec) == asec(1/x) assert acos(x).rewrite(acsc) == -acsc(1/x) + pi/2 def test_acos_fdiff(): assert acos(x).fdiff() == -1/sqrt(1 - x**2) raises(ArgumentIndexError, lambda: acos(x).fdiff(2)) def test_atan(): assert atan(nan) is nan assert atan.nargs == FiniteSet(1) assert atan(oo) == pi/2 assert atan(-oo) == -pi/2 assert atan(zoo) == AccumBounds(-pi/2, pi/2) assert atan(0) == 0 assert atan(1) == pi/4 assert atan(sqrt(3)) == pi/3 assert atan(-(1 + sqrt(2))) == pi*Rational(-3, 8) assert atan(sqrt(5 - 2 * sqrt(5))) == pi/5 assert atan(-sqrt(1 - 2 * sqrt(5)/ 5)) == -pi/10 assert atan(sqrt(1 + 2 * sqrt(5) / 5)) == pi*Rational(3, 10) assert atan(-2 + sqrt(3)) == -pi/12 assert atan(2 + sqrt(3)) == pi*Rational(5, 12) assert atan(-2 - sqrt(3)) == pi*Rational(-5, 12) # check round-trip for exact values: for d in [5, 6, 8, 10, 12]: for num in range(-(d//2), d//2 + 1): if gcd(num, d) == 1: assert atan(tan(num*pi/d)) == num*pi/d assert atan(oo) == pi/2 assert atan(x).diff(x) == 1/(1 + x**2) assert atan(r).is_real is True assert atan(-2*I) == -I*atanh(2) assert unchanged(atan, cot(x)) assert atan(cot(Rational(1, 4))) == Rational(-1, 4) + pi/2 assert acot(Rational(1, 4)).is_rational is False for s in (x, p, n, np, nn, nz, ep, en, enp, enn, enz): if s.is_real or s.is_extended_real is None: assert s.is_nonzero is atan(s).is_nonzero assert s.is_positive is atan(s).is_positive assert s.is_negative is atan(s).is_negative assert s.is_nonpositive is atan(s).is_nonpositive assert s.is_nonnegative is atan(s).is_nonnegative else: assert s.is_extended_nonzero is atan(s).is_nonzero assert s.is_extended_positive is atan(s).is_positive assert s.is_extended_negative is atan(s).is_negative assert s.is_extended_nonpositive is atan(s).is_nonpositive assert s.is_extended_nonnegative is atan(s).is_nonnegative assert s.is_extended_nonzero is atan(s).is_extended_nonzero assert s.is_extended_positive is atan(s).is_extended_positive assert s.is_extended_negative is atan(s).is_extended_negative assert s.is_extended_nonpositive is atan(s).is_extended_nonpositive assert s.is_extended_nonnegative is atan(s).is_extended_nonnegative def test_atan_rewrite(): assert atan(x).rewrite(log) == I*(log(1 - I*x)-log(1 + I*x))/2 assert atan(x).rewrite(asin) == (-asin(1/sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x assert atan(x).rewrite(acos) == sqrt(x**2)*acos(1/sqrt(x**2 + 1))/x assert atan(x).rewrite(acot) == acot(1/x) assert atan(x).rewrite(asec) == sqrt(x**2)*asec(sqrt(x**2 + 1))/x assert atan(x).rewrite(acsc) == (-acsc(sqrt(x**2 + 1)) + pi/2)*sqrt(x**2)/x assert atan(-5*I).evalf() == atan(x).rewrite(log).evalf(subs={x:-5*I}) assert atan(5*I).evalf() == atan(x).rewrite(log).evalf(subs={x:5*I}) def test_atan_fdiff(): assert atan(x).fdiff() == 1/(x**2 + 1) raises(ArgumentIndexError, lambda: atan(x).fdiff(2)) def test_atan_leading_term(): assert atan(x).as_leading_term(x) == x assert atan(1/x).as_leading_term(x, cdir=1) == pi/2 assert atan(1/x).as_leading_term(x, cdir=-1) == -pi/2 # Tests concerning branch points assert atan(x + I).as_leading_term(x, cdir=1) == -I*log(x)/2 + pi/4 + I*log(2)/2 assert atan(x + I).as_leading_term(x, cdir=-1) == -I*log(x)/2 - 3*pi/4 + I*log(2)/2 assert atan(x - I).as_leading_term(x, cdir=1) == I*log(x)/2 + pi/4 - I*log(2)/2 assert atan(x - I).as_leading_term(x, cdir=-1) == I*log(x)/2 + pi/4 - I*log(2)/2 # Tests concerning points lying on branch cuts assert atan(x + 2*I).as_leading_term(x, cdir=1) == I*atanh(2) assert atan(x + 2*I).as_leading_term(x, cdir=-1) == -pi + I*atanh(2) assert atan(x - 2*I).as_leading_term(x, cdir=1) == pi - I*atanh(2) assert atan(x - 2*I).as_leading_term(x, cdir=-1) == -I*atanh(2) # Tests concerning re(ndir) == 0 assert atan(2*I - I*x - x**2).as_leading_term(x, cdir=1) == -pi/2 + I*log(3)/2 assert atan(2*I - I*x - x**2).as_leading_term(x, cdir=-1) == -pi/2 + I*log(3)/2 def test_atan2(): assert atan2.nargs == FiniteSet(2) assert atan2(0, 0) is S.NaN assert atan2(0, 1) == 0 assert atan2(1, 1) == pi/4 assert atan2(1, 0) == pi/2 assert atan2(1, -1) == pi*Rational(3, 4) assert atan2(0, -1) == pi assert atan2(-1, -1) == pi*Rational(-3, 4) assert atan2(-1, 0) == -pi/2 assert atan2(-1, 1) == -pi/4 i = symbols('i', imaginary=True) r = symbols('r', real=True) eq = atan2(r, i) ans = -I*log((i + I*r)/sqrt(i**2 + r**2)) reps = ((r, 2), (i, I)) assert eq.subs(reps) == ans.subs(reps) x = Symbol('x', negative=True) y = Symbol('y', negative=True) assert atan2(y, x) == atan(y/x) - pi y = Symbol('y', nonnegative=True) assert atan2(y, x) == atan(y/x) + pi y = Symbol('y') assert atan2(y, x) == atan2(y, x, evaluate=False) u = Symbol("u", positive=True) assert atan2(0, u) == 0 u = Symbol("u", negative=True) assert atan2(0, u) == pi assert atan2(y, oo) == 0 assert atan2(y, -oo)== 2*pi*Heaviside(re(y), S.Half) - pi assert atan2(y, x).rewrite(log) == -I*log((x + I*y)/sqrt(x**2 + y**2)) assert atan2(0, 0) is S.NaN ex = atan2(y, x) - arg(x + I*y) assert ex.subs({x:2, y:3}).rewrite(arg) == 0 assert ex.subs({x:2, y:3*I}).rewrite(arg) == -pi - I*log(sqrt(5)*I/5) assert ex.subs({x:2*I, y:3}).rewrite(arg) == -pi/2 - I*log(sqrt(5)*I) assert ex.subs({x:2*I, y:3*I}).rewrite(arg) == -pi + atan(Rational(2, 3)) + atan(Rational(3, 2)) i = symbols('i', imaginary=True) r = symbols('r', real=True) e = atan2(i, r) rewrite = e.rewrite(arg) reps = {i: I, r: -2} assert rewrite == -I*log(abs(I*i + r)/sqrt(abs(i**2 + r**2))) + arg((I*i + r)/sqrt(i**2 + r**2)) assert (e - rewrite).subs(reps).equals(0) assert atan2(0, x).rewrite(atan) == Piecewise((pi, re(x) < 0), (0, Ne(x, 0)), (nan, True)) assert atan2(0, r).rewrite(atan) == Piecewise((pi, r < 0), (0, Ne(r, 0)), (S.NaN, True)) assert atan2(0, i),rewrite(atan) == 0 assert atan2(0, r + i).rewrite(atan) == Piecewise((pi, r < 0), (0, True)) assert atan2(y, x).rewrite(atan) == Piecewise( (2*atan(y/(x + sqrt(x**2 + y**2))), Ne(y, 0)), (pi, re(x) < 0), (0, (re(x) > 0) | Ne(im(x), 0)), (nan, True)) assert conjugate(atan2(x, y)) == atan2(conjugate(x), conjugate(y)) assert diff(atan2(y, x), x) == -y/(x**2 + y**2) assert diff(atan2(y, x), y) == x/(x**2 + y**2) assert simplify(diff(atan2(y, x).rewrite(log), x)) == -y/(x**2 + y**2) assert simplify(diff(atan2(y, x).rewrite(log), y)) == x/(x**2 + y**2) assert str(atan2(1, 2).evalf(5)) == '0.46365' raises(ArgumentIndexError, lambda: atan2(x, y).fdiff(3)) def test_issue_17461(): class A(Symbol): is_extended_real = True def _eval_evalf(self, prec): return Float(5.0) x = A('X') y = A('Y') assert abs(atan2(x, y).evalf() - 0.785398163397448) <= 1e-10 def test_acot(): assert acot(nan) is nan assert acot.nargs == FiniteSet(1) assert acot(-oo) == 0 assert acot(oo) == 0 assert acot(zoo) == 0 assert acot(1) == pi/4 assert acot(0) == pi/2 assert acot(sqrt(3)/3) == pi/3 assert acot(1/sqrt(3)) == pi/3 assert acot(-1/sqrt(3)) == -pi/3 assert acot(x).diff(x) == -1/(1 + x**2) assert acot(r).is_extended_real is True assert acot(I*pi) == -I*acoth(pi) assert acot(-2*I) == I*acoth(2) assert acot(x).is_positive is None assert acot(n).is_positive is False assert acot(p).is_positive is True assert acot(I).is_positive is False assert acot(Rational(1, 4)).is_rational is False assert unchanged(acot, cot(x)) assert unchanged(acot, tan(x)) assert acot(cot(Rational(1, 4))) == Rational(1, 4) assert acot(tan(Rational(-1, 4))) == Rational(1, 4) - pi/2 def test_acot_rewrite(): assert acot(x).rewrite(log) == I*(log(1 - I/x)-log(1 + I/x))/2 assert acot(x).rewrite(asin) == x*(-asin(sqrt(-x**2)/sqrt(-x**2 - 1)) + pi/2)*sqrt(x**(-2)) assert acot(x).rewrite(acos) == x*sqrt(x**(-2))*acos(sqrt(-x**2)/sqrt(-x**2 - 1)) assert acot(x).rewrite(atan) == atan(1/x) assert acot(x).rewrite(asec) == x*sqrt(x**(-2))*asec(sqrt((x**2 + 1)/x**2)) assert acot(x).rewrite(acsc) == x*(-acsc(sqrt((x**2 + 1)/x**2)) + pi/2)*sqrt(x**(-2)) assert acot(-I/5).evalf() == acot(x).rewrite(log).evalf(subs={x:-I/5}) assert acot(I/5).evalf() == acot(x).rewrite(log).evalf(subs={x:I/5}) def test_acot_fdiff(): assert acot(x).fdiff() == -1/(x**2 + 1) raises(ArgumentIndexError, lambda: acot(x).fdiff(2)) def test_acot_leading_term(): assert acot(1/x).as_leading_term(x) == x # Tests concerning branch points assert acot(x + I).as_leading_term(x, cdir=1) == I*log(x)/2 + pi/4 - I*log(2)/2 assert acot(x + I).as_leading_term(x, cdir=-1) == I*log(x)/2 + pi/4 - I*log(2)/2 assert acot(x - I).as_leading_term(x, cdir=1) == -I*log(x)/2 + pi/4 + I*log(2)/2 assert acot(x - I).as_leading_term(x, cdir=-1) == -I*log(x)/2 - 3*pi/4 + I*log(2)/2 # Tests concerning points lying on branch cuts assert acot(x).as_leading_term(x, cdir=1) == pi/2 assert acot(x).as_leading_term(x, cdir=-1) == -pi/2 assert acot(x + I/2).as_leading_term(x, cdir=1) == pi - I*acoth(S(1)/2) assert acot(x + I/2).as_leading_term(x, cdir=-1) == -I*acoth(S(1)/2) assert acot(x - I/2).as_leading_term(x, cdir=1) == I*acoth(S(1)/2) assert acot(x - I/2).as_leading_term(x, cdir=-1) == -pi + I*acoth(S(1)/2) # Tests concerning re(ndir) == 0 assert acot(I/2 - I*x - x**2).as_leading_term(x, cdir=1) == -pi/2 - I*log(3)/2 assert acot(I/2 - I*x - x**2).as_leading_term(x, cdir=-1) == -pi/2 - I*log(3)/2 def test_attributes(): assert sin(x).args == (x,) def test_sincos_rewrite(): assert sin(pi/2 - x) == cos(x) assert sin(pi - x) == sin(x) assert cos(pi/2 - x) == sin(x) assert cos(pi - x) == -cos(x) def _check_even_rewrite(func, arg): """Checks that the expr has been rewritten using f(-x) -> f(x) arg : -x """ return func(arg).args[0] == -arg def _check_odd_rewrite(func, arg): """Checks that the expr has been rewritten using f(-x) -> -f(x) arg : -x """ return func(arg).func.is_Mul def _check_no_rewrite(func, arg): """Checks that the expr is not rewritten""" return func(arg).args[0] == arg def test_evenodd_rewrite(): a = cos(2) # negative b = sin(1) # positive even = [cos] odd = [sin, tan, cot, asin, atan, acot] with_minus = [-1, -2**1024 * E, -pi/105, -x*y, -x - y] for func in even: for expr in with_minus: assert _check_even_rewrite(func, expr) assert _check_no_rewrite(func, a*b) assert func( x - y) == func(y - x) # it doesn't matter which form is canonical for func in odd: for expr in with_minus: assert _check_odd_rewrite(func, expr) assert _check_no_rewrite(func, a*b) assert func( x - y) == -func(y - x) # it doesn't matter which form is canonical def test_as_leading_term_issue_5272(): assert sin(x).as_leading_term(x) == x assert cos(x).as_leading_term(x) == 1 assert tan(x).as_leading_term(x) == x assert cot(x).as_leading_term(x) == 1/x def test_leading_terms(): assert sin(1/x).as_leading_term(x) == AccumBounds(-1, 1) assert sin(S.Half).as_leading_term(x) == sin(S.Half) assert cos(1/x).as_leading_term(x) == AccumBounds(-1, 1) assert cos(S.Half).as_leading_term(x) == cos(S.Half) assert sec(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity) assert csc(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity) assert tan(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity) assert cot(1/x).as_leading_term(x) == AccumBounds(S.NegativeInfinity, S.Infinity) # https://github.com/sympy/sympy/issues/21038 f = sin(pi*(x + 4))/(3*x) assert f.as_leading_term(x) == pi/3 def test_atan2_expansion(): assert cancel(atan2(x**2, x + 1).diff(x) - atan(x**2/(x + 1)).diff(x)) == 0 assert cancel(atan(y/x).series(y, 0, 5) - atan2(y, x).series(y, 0, 5) + atan2(0, x) - atan(0)) == O(y**5) assert cancel(atan(y/x).series(x, 1, 4) - atan2(y, x).series(x, 1, 4) + atan2(y, 1) - atan(y)) == O((x - 1)**4, (x, 1)) assert cancel(atan((y + x)/x).series(x, 1, 3) - atan2(y + x, x).series(x, 1, 3) + atan2(1 + y, 1) - atan(1 + y)) == O((x - 1)**3, (x, 1)) assert Matrix([atan2(y, x)]).jacobian([y, x]) == \ Matrix([[x/(y**2 + x**2), -y/(y**2 + x**2)]]) def test_aseries(): def t(n, v, d, e): assert abs( n(1/v).evalf() - n(1/x).series(x, dir=d).removeO().subs(x, v)) < e t(atan, 0.1, '+', 1e-5) t(atan, -0.1, '-', 1e-5) t(acot, 0.1, '+', 1e-5) t(acot, -0.1, '-', 1e-5) def test_issue_4420(): i = Symbol('i', integer=True) e = Symbol('e', even=True) o = Symbol('o', odd=True) # unknown parity for variable assert cos(4*i*pi) == 1 assert sin(4*i*pi) == 0 assert tan(4*i*pi) == 0 assert cot(4*i*pi) is zoo assert cos(3*i*pi) == cos(pi*i) # +/-1 assert sin(3*i*pi) == 0 assert tan(3*i*pi) == 0 assert cot(3*i*pi) is zoo assert cos(4.0*i*pi) == 1 assert sin(4.0*i*pi) == 0 assert tan(4.0*i*pi) == 0 assert cot(4.0*i*pi) is zoo assert cos(3.0*i*pi) == cos(pi*i) # +/-1 assert sin(3.0*i*pi) == 0 assert tan(3.0*i*pi) == 0 assert cot(3.0*i*pi) is zoo assert cos(4.5*i*pi) == cos(0.5*pi*i) assert sin(4.5*i*pi) == sin(0.5*pi*i) assert tan(4.5*i*pi) == tan(0.5*pi*i) assert cot(4.5*i*pi) == cot(0.5*pi*i) # parity of variable is known assert cos(4*e*pi) == 1 assert sin(4*e*pi) == 0 assert tan(4*e*pi) == 0 assert cot(4*e*pi) is zoo assert cos(3*e*pi) == 1 assert sin(3*e*pi) == 0 assert tan(3*e*pi) == 0 assert cot(3*e*pi) is zoo assert cos(4.0*e*pi) == 1 assert sin(4.0*e*pi) == 0 assert tan(4.0*e*pi) == 0 assert cot(4.0*e*pi) is zoo assert cos(3.0*e*pi) == 1 assert sin(3.0*e*pi) == 0 assert tan(3.0*e*pi) == 0 assert cot(3.0*e*pi) is zoo assert cos(4.5*e*pi) == cos(0.5*pi*e) assert sin(4.5*e*pi) == sin(0.5*pi*e) assert tan(4.5*e*pi) == tan(0.5*pi*e) assert cot(4.5*e*pi) == cot(0.5*pi*e) assert cos(4*o*pi) == 1 assert sin(4*o*pi) == 0 assert tan(4*o*pi) == 0 assert cot(4*o*pi) is zoo assert cos(3*o*pi) == -1 assert sin(3*o*pi) == 0 assert tan(3*o*pi) == 0 assert cot(3*o*pi) is zoo assert cos(4.0*o*pi) == 1 assert sin(4.0*o*pi) == 0 assert tan(4.0*o*pi) == 0 assert cot(4.0*o*pi) is zoo assert cos(3.0*o*pi) == -1 assert sin(3.0*o*pi) == 0 assert tan(3.0*o*pi) == 0 assert cot(3.0*o*pi) is zoo assert cos(4.5*o*pi) == cos(0.5*pi*o) assert sin(4.5*o*pi) == sin(0.5*pi*o) assert tan(4.5*o*pi) == tan(0.5*pi*o) assert cot(4.5*o*pi) == cot(0.5*pi*o) # x could be imaginary assert cos(4*x*pi) == cos(4*pi*x) assert sin(4*x*pi) == sin(4*pi*x) assert tan(4*x*pi) == tan(4*pi*x) assert cot(4*x*pi) == cot(4*pi*x) assert cos(3*x*pi) == cos(3*pi*x) assert sin(3*x*pi) == sin(3*pi*x) assert tan(3*x*pi) == tan(3*pi*x) assert cot(3*x*pi) == cot(3*pi*x) assert cos(4.0*x*pi) == cos(4.0*pi*x) assert sin(4.0*x*pi) == sin(4.0*pi*x) assert tan(4.0*x*pi) == tan(4.0*pi*x) assert cot(4.0*x*pi) == cot(4.0*pi*x) assert cos(3.0*x*pi) == cos(3.0*pi*x) assert sin(3.0*x*pi) == sin(3.0*pi*x) assert tan(3.0*x*pi) == tan(3.0*pi*x) assert cot(3.0*x*pi) == cot(3.0*pi*x) assert cos(4.5*x*pi) == cos(4.5*pi*x) assert sin(4.5*x*pi) == sin(4.5*pi*x) assert tan(4.5*x*pi) == tan(4.5*pi*x) assert cot(4.5*x*pi) == cot(4.5*pi*x) def test_inverses(): raises(AttributeError, lambda: sin(x).inverse()) raises(AttributeError, lambda: cos(x).inverse()) assert tan(x).inverse() == atan assert cot(x).inverse() == acot raises(AttributeError, lambda: csc(x).inverse()) raises(AttributeError, lambda: sec(x).inverse()) assert asin(x).inverse() == sin assert acos(x).inverse() == cos assert atan(x).inverse() == tan assert acot(x).inverse() == cot def test_real_imag(): a, b = symbols('a b', real=True) z = a + b*I for deep in [True, False]: assert sin( z).as_real_imag(deep=deep) == (sin(a)*cosh(b), cos(a)*sinh(b)) assert cos( z).as_real_imag(deep=deep) == (cos(a)*cosh(b), -sin(a)*sinh(b)) assert tan(z).as_real_imag(deep=deep) == (sin(2*a)/(cos(2*a) + cosh(2*b)), sinh(2*b)/(cos(2*a) + cosh(2*b))) assert cot(z).as_real_imag(deep=deep) == (-sin(2*a)/(cos(2*a) - cosh(2*b)), sinh(2*b)/(cos(2*a) - cosh(2*b))) assert sin(a).as_real_imag(deep=deep) == (sin(a), 0) assert cos(a).as_real_imag(deep=deep) == (cos(a), 0) assert tan(a).as_real_imag(deep=deep) == (tan(a), 0) assert cot(a).as_real_imag(deep=deep) == (cot(a), 0) @XFAIL def test_sin_cos_with_infinity(): # Test for issue 5196 # https://github.com/sympy/sympy/issues/5196 assert sin(oo) is S.NaN assert cos(oo) is S.NaN @slow def test_sincos_rewrite_sqrt(): # equivalent to testing rewrite(pow) for p in [1, 3, 5, 17]: for t in [1, 8]: n = t*p # The vertices `exp(i*pi/n)` of a regular `n`-gon can # be expressed by means of nested square roots if and # only if `n` is a product of Fermat primes, `p`, and # powers of 2, `t'. The code aims to check all vertices # not belonging to an `m`-gon for `m < n`(`gcd(i, n) == 1`). # For large `n` this makes the test too slow, therefore # the vertices are limited to those of index `i < 10`. for i in range(1, min((n + 1)//2 + 1, 10)): if 1 == gcd(i, n): x = i*pi/n s1 = sin(x).rewrite(sqrt) c1 = cos(x).rewrite(sqrt) assert not s1.has(cos, sin), "fails for %d*pi/%d" % (i, n) assert not c1.has(cos, sin), "fails for %d*pi/%d" % (i, n) assert 1e-3 > abs(sin(x.evalf(5)) - s1.evalf(2)), "fails for %d*pi/%d" % (i, n) assert 1e-3 > abs(cos(x.evalf(5)) - c1.evalf(2)), "fails for %d*pi/%d" % (i, n) assert cos(pi/14).rewrite(sqrt) == sqrt(cos(pi/7)/2 + S.Half) assert cos(pi/257).rewrite(sqrt).evalf(64) == cos(pi/257).evalf(64) assert cos(pi*Rational(-15, 2)/11, evaluate=False).rewrite( sqrt) == -sqrt(-cos(pi*Rational(4, 11))/2 + S.Half) assert cos(Mul(2, pi, S.Half, evaluate=False), evaluate=False).rewrite( sqrt) == -1 e = cos(pi/3/17) # don't use pi/15 since that is caught at instantiation a = ( -3*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17) + 17)/64 - 3*sqrt(34)*sqrt(sqrt(17) + 17)/128 - sqrt(sqrt(17) + 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 - sqrt(-sqrt(17) + 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 - Rational(1, 32) + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 + 3*sqrt(2)*sqrt(sqrt(17) + 17)/128 + sqrt(34)*sqrt(-sqrt(17) + 17)/128 + 13*sqrt(2)*sqrt(-sqrt(17) + 17)/128 + sqrt(17)*sqrt(-sqrt(17) + 17)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/128 + 5*sqrt(17)/32 + sqrt(3)*sqrt(-sqrt(2)*sqrt(sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/8 - 5*sqrt(2)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 - 3*sqrt(2)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/32 + sqrt(34)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/64 + sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/2 + S.Half + sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + sqrt(34)*sqrt(-sqrt(17) + 17)*sqrt(sqrt(17)/32 + sqrt(2)*sqrt(-sqrt(17) + 17)/32 + sqrt(2)*sqrt(-8*sqrt(2)*sqrt(sqrt(17) + 17) - sqrt(2)*sqrt(-sqrt(17) + 17) + sqrt(34)*sqrt(-sqrt(17) + 17) + 6*sqrt(17) + 34)/32 + Rational(15, 32))/32)/2) assert e.rewrite(sqrt) == a assert e.n() == a.n() # coverage of fermatCoords: multiplicity > 1; the following could be # different but that portion of the code should be tested in some way assert cos(pi/9/17).rewrite(sqrt) == \ sin(pi/9)*sin(pi*Rational(2, 17)) + cos(pi/9)*cos(pi*Rational(2, 17)) @slow def test_tancot_rewrite_sqrt(): # equivalent to testing rewrite(pow) for p in [1, 3, 5, 17]: for t in [1, 8]: n = t*p for i in range(1, min((n + 1)//2 + 1, 10)): if 1 == gcd(i, n): x = i*pi/n if 2*i != n and 3*i != 2*n: t1 = tan(x).rewrite(sqrt) assert not t1.has(cot, tan), "fails for %d*pi/%d" % (i, n) assert 1e-3 > abs( tan(x.evalf(7)) - t1.evalf(4) ), "fails for %d*pi/%d" % (i, n) if i != 0 and i != n: c1 = cot(x).rewrite(sqrt) assert not c1.has(cot, tan), "fails for %d*pi/%d" % (i, n) assert 1e-3 > abs( cot(x.evalf(7)) - c1.evalf(4) ), "fails for %d*pi/%d" % (i, n) def test_sec(): x = symbols('x', real=True) z = symbols('z') assert sec.nargs == FiniteSet(1) assert sec(zoo) is nan assert sec(0) == 1 assert sec(pi) == -1 assert sec(pi/2) is zoo assert sec(-pi/2) is zoo assert sec(pi/6) == 2*sqrt(3)/3 assert sec(pi/3) == 2 assert sec(pi*Rational(5, 2)) is zoo assert sec(pi*Rational(9, 7)) == -sec(pi*Rational(2, 7)) assert sec(pi*Rational(3, 4)) == -sqrt(2) # issue 8421 assert sec(I) == 1/cosh(1) assert sec(x*I) == 1/cosh(x) assert sec(-x) == sec(x) assert sec(asec(x)) == x assert sec(z).conjugate() == sec(conjugate(z)) assert (sec(z).as_real_imag() == (cos(re(z))*cosh(im(z))/(sin(re(z))**2*sinh(im(z))**2 + cos(re(z))**2*cosh(im(z))**2), sin(re(z))*sinh(im(z))/(sin(re(z))**2*sinh(im(z))**2 + cos(re(z))**2*cosh(im(z))**2))) assert sec(x).expand(trig=True) == 1/cos(x) assert sec(2*x).expand(trig=True) == 1/(2*cos(x)**2 - 1) assert sec(x).is_extended_real == True assert sec(z).is_real == None assert sec(a).is_algebraic is None assert sec(na).is_algebraic is False assert sec(x).as_leading_term() == sec(x) assert sec(0, evaluate=False).is_finite == True assert sec(x).is_finite == None assert sec(pi/2, evaluate=False).is_finite == False assert series(sec(x), x, x0=0, n=6) == 1 + x**2/2 + 5*x**4/24 + O(x**6) # https://github.com/sympy/sympy/issues/7166 assert series(sqrt(sec(x))) == 1 + x**2/4 + 7*x**4/96 + O(x**6) # https://github.com/sympy/sympy/issues/7167 assert (series(sqrt(sec(x)), x, x0=pi*3/2, n=4) == 1/sqrt(x - pi*Rational(3, 2)) + (x - pi*Rational(3, 2))**Rational(3, 2)/12 + (x - pi*Rational(3, 2))**Rational(7, 2)/160 + O((x - pi*Rational(3, 2))**4, (x, pi*Rational(3, 2)))) assert sec(x).diff(x) == tan(x)*sec(x) # Taylor Term checks assert sec(z).taylor_term(4, z) == 5*z**4/24 assert sec(z).taylor_term(6, z) == 61*z**6/720 assert sec(z).taylor_term(5, z) == 0 def test_sec_rewrite(): assert sec(x).rewrite(exp) == 1/(exp(I*x)/2 + exp(-I*x)/2) assert sec(x).rewrite(cos) == 1/cos(x) assert sec(x).rewrite(tan) == (tan(x/2)**2 + 1)/(-tan(x/2)**2 + 1) assert sec(x).rewrite(pow) == sec(x) assert sec(x).rewrite(sqrt) == sec(x) assert sec(z).rewrite(cot) == (cot(z/2)**2 + 1)/(cot(z/2)**2 - 1) assert sec(x).rewrite(sin) == 1 / sin(x + pi / 2, evaluate=False) assert sec(x).rewrite(tan) == (tan(x / 2)**2 + 1) / (-tan(x / 2)**2 + 1) assert sec(x).rewrite(csc) == csc(-x + pi/2, evaluate=False) def test_sec_fdiff(): assert sec(x).fdiff() == tan(x)*sec(x) raises(ArgumentIndexError, lambda: sec(x).fdiff(2)) def test_csc(): x = symbols('x', real=True) z = symbols('z') # https://github.com/sympy/sympy/issues/6707 cosecant = csc('x') alternate = 1/sin('x') assert cosecant.equals(alternate) == True assert alternate.equals(cosecant) == True assert csc.nargs == FiniteSet(1) assert csc(0) is zoo assert csc(pi) is zoo assert csc(zoo) is nan assert csc(pi/2) == 1 assert csc(-pi/2) == -1 assert csc(pi/6) == 2 assert csc(pi/3) == 2*sqrt(3)/3 assert csc(pi*Rational(5, 2)) == 1 assert csc(pi*Rational(9, 7)) == -csc(pi*Rational(2, 7)) assert csc(pi*Rational(3, 4)) == sqrt(2) # issue 8421 assert csc(I) == -I/sinh(1) assert csc(x*I) == -I/sinh(x) assert csc(-x) == -csc(x) assert csc(acsc(x)) == x assert csc(z).conjugate() == csc(conjugate(z)) assert (csc(z).as_real_imag() == (sin(re(z))*cosh(im(z))/(sin(re(z))**2*cosh(im(z))**2 + cos(re(z))**2*sinh(im(z))**2), -cos(re(z))*sinh(im(z))/(sin(re(z))**2*cosh(im(z))**2 + cos(re(z))**2*sinh(im(z))**2))) assert csc(x).expand(trig=True) == 1/sin(x) assert csc(2*x).expand(trig=True) == 1/(2*sin(x)*cos(x)) assert csc(x).is_extended_real == True assert csc(z).is_real == None assert csc(a).is_algebraic is None assert csc(na).is_algebraic is False assert csc(x).as_leading_term() == csc(x) assert csc(0, evaluate=False).is_finite == False assert csc(x).is_finite == None assert csc(pi/2, evaluate=False).is_finite == True assert series(csc(x), x, x0=pi/2, n=6) == \ 1 + (x - pi/2)**2/2 + 5*(x - pi/2)**4/24 + O((x - pi/2)**6, (x, pi/2)) assert series(csc(x), x, x0=0, n=6) == \ 1/x + x/6 + 7*x**3/360 + 31*x**5/15120 + O(x**6) assert csc(x).diff(x) == -cot(x)*csc(x) assert csc(x).taylor_term(2, x) == 0 assert csc(x).taylor_term(3, x) == 7*x**3/360 assert csc(x).taylor_term(5, x) == 31*x**5/15120 raises(ArgumentIndexError, lambda: csc(x).fdiff(2)) def test_asec(): z = Symbol('z', zero=True) assert asec(z) is zoo assert asec(nan) is nan assert asec(1) == 0 assert asec(-1) == pi assert asec(oo) == pi/2 assert asec(-oo) == pi/2 assert asec(zoo) == pi/2 assert asec(sec(pi*Rational(13, 4))) == pi*Rational(3, 4) assert asec(1 + sqrt(5)) == pi*Rational(2, 5) assert asec(2/sqrt(3)) == pi/6 assert asec(sqrt(4 - 2*sqrt(2))) == pi/8 assert asec(-sqrt(4 + 2*sqrt(2))) == pi*Rational(5, 8) assert asec(sqrt(2 + 2*sqrt(5)/5)) == pi*Rational(3, 10) assert asec(-sqrt(2 + 2*sqrt(5)/5)) == pi*Rational(7, 10) assert asec(sqrt(2) - sqrt(6)) == pi*Rational(11, 12) assert asec(x).diff(x) == 1/(x**2*sqrt(1 - 1/x**2)) assert asec(x).rewrite(log) == I*log(sqrt(1 - 1/x**2) + I/x) + pi/2 assert asec(x).rewrite(asin) == -asin(1/x) + pi/2 assert asec(x).rewrite(acos) == acos(1/x) assert asec(x).rewrite(atan) == \ pi*(1 - sqrt(x**2)/x)/2 + sqrt(x**2)*atan(sqrt(x**2 - 1))/x assert asec(x).rewrite(acot) == \ pi*(1 - sqrt(x**2)/x)/2 + sqrt(x**2)*acot(1/sqrt(x**2 - 1))/x assert asec(x).rewrite(acsc) == -acsc(x) + pi/2 raises(ArgumentIndexError, lambda: asec(x).fdiff(2)) def test_asec_is_real(): assert asec(S.Half).is_real is False n = Symbol('n', positive=True, integer=True) assert asec(n).is_extended_real is True assert asec(x).is_real is None assert asec(r).is_real is None t = Symbol('t', real=False, finite=True) assert asec(t).is_real is False def test_asec_leading_term(): assert asec(1/x).as_leading_term(x) == pi/2 # Tests concerning branch points assert asec(x + 1).as_leading_term(x) == sqrt(2)*sqrt(x) assert asec(x - 1).as_leading_term(x) == pi # Tests concerning points lying on branch cuts assert asec(x).as_leading_term(x, cdir=1) == -I*log(x) + I*log(2) assert asec(x).as_leading_term(x, cdir=-1) == I*log(x) + 2*pi - I*log(2) assert asec(I*x + 1/2).as_leading_term(x, cdir=1) == asec(1/2) assert asec(-I*x + 1/2).as_leading_term(x, cdir=1) == -asec(1/2) assert asec(I*x - 1/2).as_leading_term(x, cdir=1) == 2*pi - asec(-1/2) assert asec(-I*x - 1/2).as_leading_term(x, cdir=1) == asec(-1/2) # Tests concerning im(ndir) == 0 assert asec(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=1) == pi + I*log(2 - sqrt(3)) assert asec(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=-1) == pi + I*log(2 - sqrt(3)) def test_asec_series(): assert asec(x).series(x, 0, 9) == \ I*log(2) - I*log(x) - I*x**2/4 - 3*I*x**4/32 \ - 5*I*x**6/96 - 35*I*x**8/1024 + O(x**9) t4 = asec(x).taylor_term(4, x) assert t4 == -3*I*x**4/32 assert asec(x).taylor_term(6, x, t4, 0) == -5*I*x**6/96 def test_acsc(): assert acsc(nan) is nan assert acsc(1) == pi/2 assert acsc(-1) == -pi/2 assert acsc(oo) == 0 assert acsc(-oo) == 0 assert acsc(zoo) == 0 assert acsc(0) is zoo assert acsc(csc(3)) == -3 + pi assert acsc(csc(4)) == -4 + pi assert acsc(csc(6)) == 6 - 2*pi assert unchanged(acsc, csc(x)) assert unchanged(acsc, sec(x)) assert acsc(2/sqrt(3)) == pi/3 assert acsc(csc(pi*Rational(13, 4))) == -pi/4 assert acsc(sqrt(2 + 2*sqrt(5)/5)) == pi/5 assert acsc(-sqrt(2 + 2*sqrt(5)/5)) == -pi/5 assert acsc(-2) == -pi/6 assert acsc(-sqrt(4 + 2*sqrt(2))) == -pi/8 assert acsc(sqrt(4 - 2*sqrt(2))) == pi*Rational(3, 8) assert acsc(1 + sqrt(5)) == pi/10 assert acsc(sqrt(2) - sqrt(6)) == pi*Rational(-5, 12) assert acsc(x).diff(x) == -1/(x**2*sqrt(1 - 1/x**2)) assert acsc(x).rewrite(log) == -I*log(sqrt(1 - 1/x**2) + I/x) assert acsc(x).rewrite(asin) == asin(1/x) assert acsc(x).rewrite(acos) == -acos(1/x) + pi/2 assert acsc(x).rewrite(atan) == \ (-atan(sqrt(x**2 - 1)) + pi/2)*sqrt(x**2)/x assert acsc(x).rewrite(acot) == (-acot(1/sqrt(x**2 - 1)) + pi/2)*sqrt(x**2)/x assert acsc(x).rewrite(asec) == -asec(x) + pi/2 raises(ArgumentIndexError, lambda: acsc(x).fdiff(2)) def test_csc_rewrite(): assert csc(x).rewrite(pow) == csc(x) assert csc(x).rewrite(sqrt) == csc(x) assert csc(x).rewrite(exp) == 2*I/(exp(I*x) - exp(-I*x)) assert csc(x).rewrite(sin) == 1/sin(x) assert csc(x).rewrite(tan) == (tan(x/2)**2 + 1)/(2*tan(x/2)) assert csc(x).rewrite(cot) == (cot(x/2)**2 + 1)/(2*cot(x/2)) assert csc(x).rewrite(cos) == 1/cos(x - pi/2, evaluate=False) assert csc(x).rewrite(sec) == sec(-x + pi/2, evaluate=False) # issue 17349 assert csc(1 - exp(-besselj(I, I))).rewrite(cos) == \ -1/cos(-pi/2 - 1 + cos(I*besselj(I, I)) + I*cos(-pi/2 + I*besselj(I, I), evaluate=False), evaluate=False) def test_acsc_leading_term(): assert acsc(1/x).as_leading_term(x) == x # Tests concerning branch points assert acsc(x + 1).as_leading_term(x) == pi/2 assert acsc(x - 1).as_leading_term(x) == -pi/2 # Tests concerning points lying on branch cuts assert acsc(x).as_leading_term(x, cdir=1) == I*log(x) + pi/2 - I*log(2) assert acsc(x).as_leading_term(x, cdir=-1) == -I*log(x) - 3*pi/2 + I*log(2) assert acsc(I*x + 1/2).as_leading_term(x, cdir=1) == acsc(1/2) assert acsc(-I*x + 1/2).as_leading_term(x, cdir=1) == pi - acsc(1/2) assert acsc(I*x - 1/2).as_leading_term(x, cdir=1) == -pi - acsc(-1/2) assert acsc(-I*x - 1/2).as_leading_term(x, cdir=1) == -acsc(1/2) # Tests concerning im(ndir) == 0 assert acsc(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=1) == -pi/2 + I*log(sqrt(3) + 2) assert acsc(-I*x**2 + x - S(1)/2).as_leading_term(x, cdir=-1) == -pi/2 + I*log(sqrt(3) + 2) def test_acsc_series(): assert acsc(x).series(x, 0, 9) == \ -I*log(2) + pi/2 + I*log(x) + I*x**2/4 \ + 3*I*x**4/32 + 5*I*x**6/96 + 35*I*x**8/1024 + O(x**9) t6 = acsc(x).taylor_term(6, x) assert t6 == 5*I*x**6/96 assert acsc(x).taylor_term(8, x, t6, 0) == 35*I*x**8/1024 def test_asin_nseries(): assert asin(x + 2)._eval_nseries(x, 4, None, I) == -asin(2) + pi + \ sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4) assert asin(x + 2)._eval_nseries(x, 4, None, -I) == asin(2) - \ sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4) assert asin(x - 2)._eval_nseries(x, 4, None, I) == -asin(2) - \ sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4) assert asin(x - 2)._eval_nseries(x, 4, None, -I) == asin(2) - pi + \ sqrt(3)*I*x/3 + sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4) # testing nseries for asin at branch points assert asin(1 + x)._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(-x) - \ sqrt(2)*(-x)**(S(3)/2)/12 - 3*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3) assert asin(-1 + x)._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(x) + \ sqrt(2)*x**(S(3)/2)/12 + 3*sqrt(2)*x**(S(5)/2)/160 + O(x**3) assert asin(exp(x))._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(-x) + \ sqrt(2)*(-x)**(S(3)/2)/6 - sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3) assert asin(-exp(x))._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(-x) - \ sqrt(2)*(-x)**(S(3)/2)/6 + sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3) def test_acos_nseries(): assert acos(x + 2)._eval_nseries(x, 4, None, I) == -acos(2) - sqrt(3)*I*x/3 + \ sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4) assert acos(x + 2)._eval_nseries(x, 4, None, -I) == acos(2) + sqrt(3)*I*x/3 - \ sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4) assert acos(x - 2)._eval_nseries(x, 4, None, I) == acos(-2) + sqrt(3)*I*x/3 + \ sqrt(3)*I*x**2/9 + sqrt(3)*I*x**3/18 + O(x**4) assert acos(x - 2)._eval_nseries(x, 4, None, -I) == -acos(-2) + 2*pi - \ sqrt(3)*I*x/3 - sqrt(3)*I*x**2/9 - sqrt(3)*I*x**3/18 + O(x**4) # testing nseries for acos at branch points assert acos(1 + x)._eval_nseries(x, 3, None) == sqrt(2)*sqrt(-x) + \ sqrt(2)*(-x)**(S(3)/2)/12 + 3*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3) assert acos(-1 + x)._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(x) - \ sqrt(2)*x**(S(3)/2)/12 - 3*sqrt(2)*x**(S(5)/2)/160 + O(x**3) assert acos(exp(x))._eval_nseries(x, 3, None) == sqrt(2)*sqrt(-x) - \ sqrt(2)*(-x)**(S(3)/2)/6 + sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3) assert acos(-exp(x))._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(-x) + \ sqrt(2)*(-x)**(S(3)/2)/6 - sqrt(2)*(-x)**(S(5)/2)/120 + O(x**3) def test_atan_nseries(): assert atan(x + 2*I)._eval_nseries(x, 4, None, 1) == I*atanh(2) - x/3 - \ 2*I*x**2/9 + 13*x**3/81 + O(x**4) assert atan(x + 2*I)._eval_nseries(x, 4, None, -1) == I*atanh(2) - pi - \ x/3 - 2*I*x**2/9 + 13*x**3/81 + O(x**4) assert atan(x - 2*I)._eval_nseries(x, 4, None, 1) == -I*atanh(2) + pi - \ x/3 + 2*I*x**2/9 + 13*x**3/81 + O(x**4) assert atan(x - 2*I)._eval_nseries(x, 4, None, -1) == -I*atanh(2) - x/3 + \ 2*I*x**2/9 + 13*x**3/81 + O(x**4) assert atan(1/x)._eval_nseries(x, 2, None, 1) == pi/2 - x + O(x**2) assert atan(1/x)._eval_nseries(x, 2, None, -1) == -pi/2 - x + O(x**2) # testing nseries for atan at branch points assert atan(x + I)._eval_nseries(x, 4, None) == I*log(2)/2 + pi/4 - \ I*log(x)/2 + x/4 + I*x**2/16 - x**3/48 + O(x**4) assert atan(x - I)._eval_nseries(x, 4, None) == -I*log(2)/2 + pi/4 + \ I*log(x)/2 + x/4 - I*x**2/16 - x**3/48 + O(x**4) def test_acot_nseries(): assert acot(x + S(1)/2*I)._eval_nseries(x, 4, None, 1) == -I*acoth(S(1)/2) + \ pi - 4*x/3 + 8*I*x**2/9 + 112*x**3/81 + O(x**4) assert acot(x + S(1)/2*I)._eval_nseries(x, 4, None, -1) == -I*acoth(S(1)/2) - \ 4*x/3 + 8*I*x**2/9 + 112*x**3/81 + O(x**4) assert acot(x - S(1)/2*I)._eval_nseries(x, 4, None, 1) == I*acoth(S(1)/2) - \ 4*x/3 - 8*I*x**2/9 + 112*x**3/81 + O(x**4) assert acot(x - S(1)/2*I)._eval_nseries(x, 4, None, -1) == I*acoth(S(1)/2) - \ pi - 4*x/3 - 8*I*x**2/9 + 112*x**3/81 + O(x**4) assert acot(x)._eval_nseries(x, 2, None, 1) == pi/2 - x + O(x**2) assert acot(x)._eval_nseries(x, 2, None, -1) == -pi/2 - x + O(x**2) # testing nseries for acot at branch points assert acot(x + I)._eval_nseries(x, 4, None) == -I*log(2)/2 + pi/4 + \ I*log(x)/2 - x/4 - I*x**2/16 + x**3/48 + O(x**4) assert acot(x - I)._eval_nseries(x, 4, None) == I*log(2)/2 + pi/4 - \ I*log(x)/2 - x/4 + I*x**2/16 + x**3/48 + O(x**4) def test_asec_nseries(): assert asec(x + S(1)/2)._eval_nseries(x, 4, None, I) == asec(S(1)/2) - \ 4*sqrt(3)*I*x/3 + 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4) assert asec(x + S(1)/2)._eval_nseries(x, 4, None, -I) == -asec(S(1)/2) + \ 4*sqrt(3)*I*x/3 - 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4) assert asec(x - S(1)/2)._eval_nseries(x, 4, None, I) == -asec(-S(1)/2) + \ 2*pi + 4*sqrt(3)*I*x/3 + 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4) assert asec(x - S(1)/2)._eval_nseries(x, 4, None, -I) == asec(-S(1)/2) - \ 4*sqrt(3)*I*x/3 - 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4) # testing nseries for asec at branch points assert asec(1 + x)._eval_nseries(x, 3, None) == sqrt(2)*sqrt(x) - \ 5*sqrt(2)*x**(S(3)/2)/12 + 43*sqrt(2)*x**(S(5)/2)/160 + O(x**3) assert asec(-1 + x)._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(-x) + \ 5*sqrt(2)*(-x)**(S(3)/2)/12 - 43*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3) assert asec(exp(x))._eval_nseries(x, 3, None) == sqrt(2)*sqrt(x) - \ sqrt(2)*x**(S(3)/2)/6 + sqrt(2)*x**(S(5)/2)/120 + O(x**3) assert asec(-exp(x))._eval_nseries(x, 3, None) == pi - sqrt(2)*sqrt(x) + \ sqrt(2)*x**(S(3)/2)/6 - sqrt(2)*x**(S(5)/2)/120 + O(x**3) def test_acsc_nseries(): assert acsc(x + S(1)/2)._eval_nseries(x, 4, None, I) == acsc(S(1)/2) + \ 4*sqrt(3)*I*x/3 - 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4) assert acsc(x + S(1)/2)._eval_nseries(x, 4, None, -I) == -acsc(S(1)/2) + \ pi - 4*sqrt(3)*I*x/3 + 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4) assert acsc(x - S(1)/2)._eval_nseries(x, 4, None, I) == acsc(S(1)/2) - pi -\ 4*sqrt(3)*I*x/3 - 8*sqrt(3)*I*x**2/9 - 16*sqrt(3)*I*x**3/9 + O(x**4) assert acsc(x - S(1)/2)._eval_nseries(x, 4, None, -I) == -acsc(S(1)/2) + \ 4*sqrt(3)*I*x/3 + 8*sqrt(3)*I*x**2/9 + 16*sqrt(3)*I*x**3/9 + O(x**4) # testing nseries for acsc at branch points assert acsc(1 + x)._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(x) + \ 5*sqrt(2)*x**(S(3)/2)/12 - 43*sqrt(2)*x**(S(5)/2)/160 + O(x**3) assert acsc(-1 + x)._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(-x) - \ 5*sqrt(2)*(-x)**(S(3)/2)/12 + 43*sqrt(2)*(-x)**(S(5)/2)/160 + O(x**3) assert acsc(exp(x))._eval_nseries(x, 3, None) == pi/2 - sqrt(2)*sqrt(x) + \ sqrt(2)*x**(S(3)/2)/6 - sqrt(2)*x**(S(5)/2)/120 + O(x**3) assert acsc(-exp(x))._eval_nseries(x, 3, None) == -pi/2 + sqrt(2)*sqrt(x) - \ sqrt(2)*x**(S(3)/2)/6 + sqrt(2)*x**(S(5)/2)/120 + O(x**3) def test_issue_8653(): n = Symbol('n', integer=True) assert sin(n).is_irrational is None assert cos(n).is_irrational is None assert tan(n).is_irrational is None def test_issue_9157(): n = Symbol('n', integer=True, positive=True) assert atan(n - 1).is_nonnegative is True def test_trig_period(): x, y = symbols('x, y') assert sin(x).period() == 2*pi assert cos(x).period() == 2*pi assert tan(x).period() == pi assert cot(x).period() == pi assert sec(x).period() == 2*pi assert csc(x).period() == 2*pi assert sin(2*x).period() == pi assert cot(4*x - 6).period() == pi/4 assert cos((-3)*x).period() == pi*Rational(2, 3) assert cos(x*y).period(x) == 2*pi/abs(y) assert sin(3*x*y + 2*pi).period(y) == 2*pi/abs(3*x) assert tan(3*x).period(y) is S.Zero raises(NotImplementedError, lambda: sin(x**2).period(x)) def test_issue_7171(): assert sin(x).rewrite(sqrt) == sin(x) assert sin(x).rewrite(pow) == sin(x) def test_issue_11864(): w, k = symbols('w, k', real=True) F = Piecewise((1, Eq(2*pi*k, 0)), (sin(pi*k)/(pi*k), True)) soln = Piecewise((1, Eq(2*pi*k, 0)), (sinc(pi*k), True)) assert F.rewrite(sinc) == soln def test_real_assumptions(): z = Symbol('z', real=False, finite=True) assert sin(z).is_real is None assert cos(z).is_real is None assert tan(z).is_real is False assert sec(z).is_real is None assert csc(z).is_real is None assert cot(z).is_real is False assert asin(p).is_real is None assert asin(n).is_real is None assert asec(p).is_real is None assert asec(n).is_real is None assert acos(p).is_real is None assert acos(n).is_real is None assert acsc(p).is_real is None assert acsc(n).is_real is None assert atan(p).is_positive is True assert atan(n).is_negative is True assert acot(p).is_positive is True assert acot(n).is_negative is True def test_issue_14320(): assert asin(sin(2)) == -2 + pi and (-pi/2 <= -2 + pi <= pi/2) and sin(2) == sin(-2 + pi) assert asin(cos(2)) == -2 + pi/2 and (-pi/2 <= -2 + pi/2 <= pi/2) and cos(2) == sin(-2 + pi/2) assert acos(sin(2)) == -pi/2 + 2 and (0 <= -pi/2 + 2 <= pi) and sin(2) == cos(-pi/2 + 2) assert acos(cos(20)) == -6*pi + 20 and (0 <= -6*pi + 20 <= pi) and cos(20) == cos(-6*pi + 20) assert acos(cos(30)) == -30 + 10*pi and (0 <= -30 + 10*pi <= pi) and cos(30) == cos(-30 + 10*pi) assert atan(tan(17)) == -5*pi + 17 and (-pi/2 < -5*pi + 17 < pi/2) and tan(17) == tan(-5*pi + 17) assert atan(tan(15)) == -5*pi + 15 and (-pi/2 < -5*pi + 15 < pi/2) and tan(15) == tan(-5*pi + 15) assert atan(cot(12)) == -12 + pi*Rational(7, 2) and (-pi/2 < -12 + pi*Rational(7, 2) < pi/2) and cot(12) == tan(-12 + pi*Rational(7, 2)) assert acot(cot(15)) == -5*pi + 15 and (-pi/2 < -5*pi + 15 <= pi/2) and cot(15) == cot(-5*pi + 15) assert acot(tan(19)) == -19 + pi*Rational(13, 2) and (-pi/2 < -19 + pi*Rational(13, 2) <= pi/2) and tan(19) == cot(-19 + pi*Rational(13, 2)) assert asec(sec(11)) == -11 + 4*pi and (0 <= -11 + 4*pi <= pi) and cos(11) == cos(-11 + 4*pi) assert asec(csc(13)) == -13 + pi*Rational(9, 2) and (0 <= -13 + pi*Rational(9, 2) <= pi) and sin(13) == cos(-13 + pi*Rational(9, 2)) assert acsc(csc(14)) == -4*pi + 14 and (-pi/2 <= -4*pi + 14 <= pi/2) and sin(14) == sin(-4*pi + 14) assert acsc(sec(10)) == pi*Rational(-7, 2) + 10 and (-pi/2 <= pi*Rational(-7, 2) + 10 <= pi/2) and cos(10) == sin(pi*Rational(-7, 2) + 10) def test_issue_14543(): assert sec(2*pi + 11) == sec(11) assert sec(2*pi - 11) == sec(11) assert sec(pi + 11) == -sec(11) assert sec(pi - 11) == -sec(11) assert csc(2*pi + 17) == csc(17) assert csc(2*pi - 17) == -csc(17) assert csc(pi + 17) == -csc(17) assert csc(pi - 17) == csc(17) x = Symbol('x') assert csc(pi/2 + x) == sec(x) assert csc(pi/2 - x) == sec(x) assert csc(pi*Rational(3, 2) + x) == -sec(x) assert csc(pi*Rational(3, 2) - x) == -sec(x) assert sec(pi/2 - x) == csc(x) assert sec(pi/2 + x) == -csc(x) assert sec(pi*Rational(3, 2) + x) == csc(x) assert sec(pi*Rational(3, 2) - x) == -csc(x) def test_as_real_imag(): # This is for https://github.com/sympy/sympy/issues/17142 # If it start failing again in irrelevant builds or in the master # please open up the issue again. expr = atan(I/(I + I*tan(1))) assert expr.as_real_imag() == (expr, 0) def test_issue_18746(): e3 = cos(S.Pi*(x/4 + 1/4)) assert e3.period() == 8
3de4617a7bcd88558d3db3bf28b92c7250a0993126445fd70b338746983d17d4
""" Tests from Michael Wester's 1999 paper "Review of CAS mathematical capabilities". http://www.math.unm.edu/~wester/cas/book/Wester.pdf See also http://math.unm.edu/~wester/cas_review.html for detailed output of each tested system. """ from sympy.assumptions.ask import Q, ask from sympy.assumptions.refine import refine from sympy.concrete.products import product from sympy.core import EulerGamma from sympy.core.evalf import N from sympy.core.function import (Derivative, Function, Lambda, Subs, diff, expand, expand_func) from sympy.core.mul import Mul from sympy.core.numbers import (AlgebraicNumber, E, I, Rational, igcd, nan, oo, pi, zoo) from sympy.core.relational import Eq, Lt from sympy.core.singleton import S from sympy.core.symbol import Dummy, Symbol, symbols from sympy.functions.combinatorial.factorials import (rf, binomial, factorial, factorial2) from sympy.functions.combinatorial.numbers import bernoulli, fibonacci from sympy.functions.elementary.complexes import (conjugate, im, re, sign) from sympy.functions.elementary.exponential import LambertW, exp, log from sympy.functions.elementary.hyperbolic import (asinh, cosh, sinh, tanh) from sympy.functions.elementary.integers import ceiling, floor from sympy.functions.elementary.miscellaneous import Max, Min, sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (acos, acot, asin, atan, cos, cot, csc, sec, sin, tan) from sympy.functions.special.bessel import besselj from sympy.functions.special.delta_functions import DiracDelta from sympy.functions.special.elliptic_integrals import (elliptic_e, elliptic_f) from sympy.functions.special.gamma_functions import gamma, polygamma from sympy.functions.special.hyper import hyper from sympy.functions.special.polynomials import (assoc_legendre, chebyshevt) from sympy.functions.special.zeta_functions import polylog from sympy.geometry.util import idiff from sympy.logic.boolalg import And from sympy.matrices.dense import hessian, wronskian from sympy.matrices.expressions.matmul import MatMul from sympy.ntheory.continued_fraction import ( continued_fraction_convergents as cf_c, continued_fraction_iterator as cf_i, continued_fraction_periodic as cf_p, continued_fraction_reduce as cf_r) from sympy.ntheory.factor_ import factorint, totient from sympy.ntheory.generate import primerange from sympy.ntheory.partitions_ import npartitions from sympy.polys.domains.integerring import ZZ from sympy.polys.orthopolys import legendre_poly from sympy.polys.partfrac import apart from sympy.polys.polytools import Poly, factor, gcd, resultant from sympy.series.limits import limit from sympy.series.order import O from sympy.series.residues import residue from sympy.series.series import series from sympy.sets.fancysets import ImageSet from sympy.sets.sets import FiniteSet, Intersection, Interval, Union from sympy.simplify.combsimp import combsimp from sympy.simplify.hyperexpand import hyperexpand from sympy.simplify.powsimp import powdenest, powsimp from sympy.simplify.radsimp import radsimp from sympy.simplify.simplify import logcombine, simplify from sympy.simplify.sqrtdenest import sqrtdenest from sympy.simplify.trigsimp import trigsimp from sympy.solvers.solvers import solve import mpmath from sympy.functions.combinatorial.numbers import stirling from sympy.functions.special.delta_functions import Heaviside from sympy.functions.special.error_functions import Ci, Si, erf from sympy.functions.special.zeta_functions import zeta from sympy.testing.pytest import (XFAIL, slow, SKIP, skip, ON_CI, raises) from sympy.utilities.iterables import partitions from mpmath import mpi, mpc from sympy.matrices import Matrix, GramSchmidt, eye from sympy.matrices.expressions.blockmatrix import BlockMatrix, block_collapse from sympy.matrices.expressions import MatrixSymbol, ZeroMatrix from sympy.physics.quantum import Commutator from sympy.polys.rings import PolyRing from sympy.polys.fields import FracField from sympy.polys.solvers import solve_lin_sys from sympy.concrete import Sum from sympy.concrete.products import Product from sympy.integrals import integrate from sympy.integrals.transforms import laplace_transform,\ inverse_laplace_transform, LaplaceTransform, fourier_transform,\ mellin_transform from sympy.solvers.recurr import rsolve from sympy.solvers.solveset import solveset, solveset_real, linsolve from sympy.solvers.ode import dsolve from sympy.core.relational import Equality from itertools import islice, takewhile from sympy.series.formal import fps from sympy.series.fourier import fourier_series from sympy.calculus.util import minimum EmptySet = S.EmptySet R = Rational x, y, z = symbols('x y z') i, j, k, l, m, n = symbols('i j k l m n', integer=True) f = Function('f') g = Function('g') # A. Boolean Logic and Quantifier Elimination # Not implemented. # B. Set Theory def test_B1(): assert (FiniteSet(i, j, j, k, k, k) | FiniteSet(l, k, j) | FiniteSet(j, m, j)) == FiniteSet(i, j, k, l, m) def test_B2(): assert (FiniteSet(i, j, j, k, k, k) & FiniteSet(l, k, j) & FiniteSet(j, m, j)) == Intersection({j, m}, {i, j, k}, {j, k, l}) # Previous output below. Not sure why that should be the expected output. # There should probably be a way to rewrite Intersections that way but I # don't see why an Intersection should evaluate like that: # # == Union({j}, Intersection({m}, Union({j, k}, Intersection({i}, {l})))) def test_B3(): assert (FiniteSet(i, j, k, l, m) - FiniteSet(j) == FiniteSet(i, k, l, m)) def test_B4(): assert (FiniteSet(*(FiniteSet(i, j)*FiniteSet(k, l))) == FiniteSet((i, k), (i, l), (j, k), (j, l))) # C. Numbers def test_C1(): assert (factorial(50) == 30414093201713378043612608166064768844377641568960512000000000000) def test_C2(): assert (factorint(factorial(50)) == {2: 47, 3: 22, 5: 12, 7: 8, 11: 4, 13: 3, 17: 2, 19: 2, 23: 2, 29: 1, 31: 1, 37: 1, 41: 1, 43: 1, 47: 1}) def test_C3(): assert (factorial2(10), factorial2(9)) == (3840, 945) # Base conversions; not really implemented by SymPy # Whatever. Take credit! def test_C4(): assert 0xABC == 2748 def test_C5(): assert 123 == int('234', 7) def test_C6(): assert int('677', 8) == int('1BF', 16) == 447 def test_C7(): assert log(32768, 8) == 5 def test_C8(): # Modular multiplicative inverse. Would be nice if divmod could do this. assert ZZ.invert(5, 7) == 3 assert ZZ.invert(5, 6) == 5 def test_C9(): assert igcd(igcd(1776, 1554), 5698) == 74 def test_C10(): x = 0 for n in range(2, 11): x += R(1, n) assert x == R(4861, 2520) def test_C11(): assert R(1, 7) == S('0.[142857]') def test_C12(): assert R(7, 11) * R(22, 7) == 2 def test_C13(): test = R(10, 7) * (1 + R(29, 1000)) ** R(1, 3) good = 3 ** R(1, 3) assert test == good def test_C14(): assert sqrtdenest(sqrt(2*sqrt(3) + 4)) == 1 + sqrt(3) def test_C15(): test = sqrtdenest(sqrt(14 + 3*sqrt(3 + 2*sqrt(5 - 12*sqrt(3 - 2*sqrt(2)))))) good = sqrt(2) + 3 assert test == good def test_C16(): test = sqrtdenest(sqrt(10 + 2*sqrt(6) + 2*sqrt(10) + 2*sqrt(15))) good = sqrt(2) + sqrt(3) + sqrt(5) assert test == good def test_C17(): test = radsimp((sqrt(3) + sqrt(2)) / (sqrt(3) - sqrt(2))) good = 5 + 2*sqrt(6) assert test == good def test_C18(): assert simplify((sqrt(-2 + sqrt(-5)) * sqrt(-2 - sqrt(-5))).expand(complex=True)) == 3 @XFAIL def test_C19(): assert radsimp(simplify((90 + 34*sqrt(7)) ** R(1, 3))) == 3 + sqrt(7) def test_C20(): inside = (135 + 78*sqrt(3)) test = AlgebraicNumber((inside**R(2, 3) + 3) * sqrt(3) / inside**R(1, 3)) assert simplify(test) == AlgebraicNumber(12) def test_C21(): assert simplify(AlgebraicNumber((41 + 29*sqrt(2)) ** R(1, 5))) == \ AlgebraicNumber(1 + sqrt(2)) @XFAIL def test_C22(): test = simplify(((6 - 4*sqrt(2))*log(3 - 2*sqrt(2)) + (3 - 2*sqrt(2))*log(17 - 12*sqrt(2)) + 32 - 24*sqrt(2)) / (48*sqrt(2) - 72)) good = sqrt(2)/3 - log(sqrt(2) - 1)/3 assert test == good def test_C23(): assert 2 * oo - 3 is oo @XFAIL def test_C24(): raise NotImplementedError("2**aleph_null == aleph_1") # D. Numerical Analysis def test_D1(): assert 0.0 / sqrt(2) == 0.0 def test_D2(): assert str(exp(-1000000).evalf()) == '3.29683147808856e-434295' def test_D3(): assert exp(pi*sqrt(163)).evalf(50).num.ae(262537412640768744) def test_D4(): assert floor(R(-5, 3)) == -2 assert ceiling(R(-5, 3)) == -1 @XFAIL def test_D5(): raise NotImplementedError("cubic_spline([1, 2, 4, 5], [1, 4, 2, 3], x)(3) == 27/8") @XFAIL def test_D6(): raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to FORTRAN") @XFAIL def test_D7(): raise NotImplementedError("translate sum(a[i]*x**i, (i,1,n)) to C") @XFAIL def test_D8(): # One way is to cheat by converting the sum to a string, # and replacing the '[' and ']' with ''. # E.g., horner(S(str(_).replace('[','').replace(']',''))) raise NotImplementedError("apply Horner's rule to sum(a[i]*x**i, (i,1,5))") @XFAIL def test_D9(): raise NotImplementedError("translate D8 to FORTRAN") @XFAIL def test_D10(): raise NotImplementedError("translate D8 to C") @XFAIL def test_D11(): #Is there a way to use count_ops? raise NotImplementedError("flops(sum(product(f[i][k], (i,1,k)), (k,1,n)))") @XFAIL def test_D12(): assert (mpi(-4, 2) * x + mpi(1, 3)) ** 2 == mpi(-8, 16)*x**2 + mpi(-24, 12)*x + mpi(1, 9) @XFAIL def test_D13(): raise NotImplementedError("discretize a PDE: diff(f(x,t),t) == diff(diff(f(x,t),x),x)") # E. Statistics # See scipy; all of this is numerical. # F. Combinatorial Theory. def test_F1(): assert rf(x, 3) == x*(1 + x)*(2 + x) def test_F2(): assert expand_func(binomial(n, 3)) == n*(n - 1)*(n - 2)/6 @XFAIL def test_F3(): assert combsimp(2**n * factorial(n) * factorial2(2*n - 1)) == factorial(2*n) @XFAIL def test_F4(): assert combsimp(2**n * factorial(n) * product(2*k - 1, (k, 1, n))) == factorial(2*n) @XFAIL def test_F5(): assert gamma(n + R(1, 2)) / sqrt(pi) / factorial(n) == factorial(2*n)/2**(2*n)/factorial(n)**2 def test_F6(): partTest = [p.copy() for p in partitions(4)] partDesired = [{4: 1}, {1: 1, 3: 1}, {2: 2}, {1: 2, 2:1}, {1: 4}] assert partTest == partDesired def test_F7(): assert npartitions(4) == 5 def test_F8(): assert stirling(5, 2, signed=True) == -50 # if signed, then kind=1 def test_F9(): assert totient(1776) == 576 # G. Number Theory def test_G1(): assert list(primerange(999983, 1000004)) == [999983, 1000003] @XFAIL def test_G2(): raise NotImplementedError("find the primitive root of 191 == 19") @XFAIL def test_G3(): raise NotImplementedError("(a+b)**p mod p == a**p + b**p mod p; p prime") # ... G14 Modular equations are not implemented. def test_G15(): assert Rational(sqrt(3).evalf()).limit_denominator(15) == R(26, 15) assert list(takewhile(lambda x: x.q <= 15, cf_c(cf_i(sqrt(3)))))[-1] == \ R(26, 15) def test_G16(): assert list(islice(cf_i(pi),10)) == [3, 7, 15, 1, 292, 1, 1, 1, 2, 1] def test_G17(): assert cf_p(0, 1, 23) == [4, [1, 3, 1, 8]] def test_G18(): assert cf_p(1, 2, 5) == [[1]] assert cf_r([[1]]).expand() == S.Half + sqrt(5)/2 @XFAIL def test_G19(): s = symbols('s', integer=True, positive=True) it = cf_i((exp(1/s) - 1)/(exp(1/s) + 1)) assert list(islice(it, 5)) == [0, 2*s, 6*s, 10*s, 14*s] def test_G20(): s = symbols('s', integer=True, positive=True) # Wester erroneously has this as -s + sqrt(s**2 + 1) assert cf_r([[2*s]]) == s + sqrt(s**2 + 1) @XFAIL def test_G20b(): s = symbols('s', integer=True, positive=True) assert cf_p(s, 1, s**2 + 1) == [[2*s]] # H. Algebra def test_H1(): assert simplify(2*2**n) == simplify(2**(n + 1)) assert powdenest(2*2**n) == simplify(2**(n + 1)) def test_H2(): assert powsimp(4 * 2**n) == 2**(n + 2) def test_H3(): assert (-1)**(n*(n + 1)) == 1 def test_H4(): expr = factor(6*x - 10) assert type(expr) is Mul assert expr.args[0] == 2 assert expr.args[1] == 3*x - 5 p1 = 64*x**34 - 21*x**47 - 126*x**8 - 46*x**5 - 16*x**60 - 81 p2 = 72*x**60 - 25*x**25 - 19*x**23 - 22*x**39 - 83*x**52 + 54*x**10 + 81 q = 34*x**19 - 25*x**16 + 70*x**7 + 20*x**3 - 91*x - 86 def test_H5(): assert gcd(p1, p2, x) == 1 def test_H6(): assert gcd(expand(p1 * q), expand(p2 * q)) == q def test_H7(): p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z assert gcd(p1, p2, x, y, z) == 1 def test_H8(): p1 = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 p2 = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z q = 11*x**12*y**7*z**13 - 23*x**2*y**8*z**10 + 47*x**17*y**5*z**8 assert gcd(p1 * q, p2 * q, x, y, z) == q def test_H9(): x = Symbol('x', zero=False) p1 = 2*x**(n + 4) - x**(n + 2) p2 = 4*x**(n + 1) + 3*x**n assert gcd(p1, p2) == x**n def test_H10(): p1 = 3*x**4 + 3*x**3 + x**2 - x - 2 p2 = x**3 - 3*x**2 + x + 5 assert resultant(p1, p2, x) == 0 def test_H11(): assert resultant(p1 * q, p2 * q, x) == 0 def test_H12(): num = x**2 - 4 den = x**2 + 4*x + 4 assert simplify(num/den) == (x - 2)/(x + 2) @XFAIL def test_H13(): assert simplify((exp(x) - 1) / (exp(x/2) + 1)) == exp(x/2) - 1 def test_H14(): p = (x + 1) ** 20 ep = expand(p) assert ep == (1 + 20*x + 190*x**2 + 1140*x**3 + 4845*x**4 + 15504*x**5 + 38760*x**6 + 77520*x**7 + 125970*x**8 + 167960*x**9 + 184756*x**10 + 167960*x**11 + 125970*x**12 + 77520*x**13 + 38760*x**14 + 15504*x**15 + 4845*x**16 + 1140*x**17 + 190*x**18 + 20*x**19 + x**20) dep = diff(ep, x) assert dep == (20 + 380*x + 3420*x**2 + 19380*x**3 + 77520*x**4 + 232560*x**5 + 542640*x**6 + 1007760*x**7 + 1511640*x**8 + 1847560*x**9 + 1847560*x**10 + 1511640*x**11 + 1007760*x**12 + 542640*x**13 + 232560*x**14 + 77520*x**15 + 19380*x**16 + 3420*x**17 + 380*x**18 + 20*x**19) assert factor(dep) == 20*(1 + x)**19 def test_H15(): assert simplify(Mul(*[x - r for r in solveset(x**3 + x**2 - 7)])) == x**3 + x**2 - 7 def test_H16(): assert factor(x**100 - 1) == ((x - 1)*(x + 1)*(x**2 + 1)*(x**4 - x**3 + x**2 - x + 1)*(x**4 + x**3 + x**2 + x + 1)*(x**8 - x**6 + x**4 - x**2 + 1)*(x**20 - x**15 + x**10 - x**5 + 1)*(x**20 + x**15 + x**10 + x**5 + 1)*(x**40 - x**30 + x**20 - x**10 + 1)) def test_H17(): assert simplify(factor(expand(p1 * p2)) - p1*p2) == 0 @XFAIL def test_H18(): # Factor over complex rationals. test = factor(4*x**4 + 8*x**3 + 77*x**2 + 18*x + 153) good = (2*x + 3*I)*(2*x - 3*I)*(x + 1 - 4*I)*(x + 1 + 4*I) assert test == good def test_H19(): a = symbols('a') # The idea is to let a**2 == 2, then solve 1/(a-1). Answer is a+1") assert Poly(a - 1).invert(Poly(a**2 - 2)) == a + 1 @XFAIL def test_H20(): raise NotImplementedError("let a**2==2; (x**3 + (a-2)*x**2 - " + "(2*a+3)*x - 3*a) / (x**2-2) = (x**2 - 2*x - 3) / (x-a)") @XFAIL def test_H21(): raise NotImplementedError("evaluate (b+c)**4 assuming b**3==2, c**2==3. \ Answer is 2*b + 8*c + 18*b**2 + 12*b*c + 9") def test_H22(): assert factor(x**4 - 3*x**2 + 1, modulus=5) == (x - 2)**2 * (x + 2)**2 def test_H23(): f = x**11 + x + 1 g = (x**2 + x + 1) * (x**9 - x**8 + x**6 - x**5 + x**3 - x**2 + 1) assert factor(f, modulus=65537) == g def test_H24(): phi = AlgebraicNumber(S.GoldenRatio.expand(func=True), alias='phi') assert factor(x**4 - 3*x**2 + 1, extension=phi) == \ (x - phi)*(x + 1 - phi)*(x - 1 + phi)*(x + phi) def test_H25(): e = (x - 2*y**2 + 3*z**3) ** 20 assert factor(expand(e)) == e def test_H26(): g = expand((sin(x) - 2*cos(y)**2 + 3*tan(z)**3)**20) assert factor(g, expand=False) == (-sin(x) + 2*cos(y)**2 - 3*tan(z)**3)**20 def test_H27(): f = 24*x*y**19*z**8 - 47*x**17*y**5*z**8 + 6*x**15*y**9*z**2 - 3*x**22 + 5 g = 34*x**5*y**8*z**13 + 20*x**7*y**7*z**7 + 12*x**9*y**16*z**4 + 80*y**14*z h = -2*z*y**7 \ *(6*x**9*y**9*z**3 + 10*x**7*z**6 + 17*y*x**5*z**12 + 40*y**7) \ *(3*x**22 + 47*x**17*y**5*z**8 - 6*x**15*y**9*z**2 - 24*x*y**19*z**8 - 5) assert factor(expand(f*g)) == h @XFAIL def test_H28(): raise NotImplementedError("expand ((1 - c**2)**5 * (1 - s**2)**5 * " + "(c**2 + s**2)**10) with c**2 + s**2 = 1. Answer is c**10*s**10.") @XFAIL def test_H29(): assert factor(4*x**2 - 21*x*y + 20*y**2, modulus=3) == (x + y)*(x - y) def test_H30(): test = factor(x**3 + y**3, extension=sqrt(-3)) answer = (x + y)*(x + y*(-R(1, 2) - sqrt(3)/2*I))*(x + y*(-R(1, 2) + sqrt(3)/2*I)) assert answer == test def test_H31(): f = (x**2 + 2*x + 3)/(x**3 + 4*x**2 + 5*x + 2) g = 2 / (x + 1)**2 - 2 / (x + 1) + 3 / (x + 2) assert apart(f) == g @XFAIL def test_H32(): # issue 6558 raise NotImplementedError("[A*B*C - (A*B*C)**(-1)]*A*C*B (product \ of a non-commuting product and its inverse)") def test_H33(): A, B, C = symbols('A, B, C', commutative=False) assert (Commutator(A, Commutator(B, C)) + Commutator(B, Commutator(C, A)) + Commutator(C, Commutator(A, B))).doit().expand() == 0 # I. Trigonometry def test_I1(): assert tan(pi*R(7, 10)) == -sqrt(1 + 2/sqrt(5)) @XFAIL def test_I2(): assert sqrt((1 + cos(6))/2) == -cos(3) def test_I3(): assert cos(n*pi) + sin((4*n - 1)*pi/2) == (-1)**n - 1 def test_I4(): assert refine(cos(pi*cos(n*pi)) + sin(pi/2*cos(n*pi)), Q.integer(n)) == (-1)**n - 1 @XFAIL def test_I5(): assert sin((n**5/5 + n**4/2 + n**3/3 - n/30) * pi) == 0 @XFAIL def test_I6(): raise NotImplementedError("assuming -3*pi<x<-5*pi/2, abs(cos(x)) == -cos(x), abs(sin(x)) == -sin(x)") @XFAIL def test_I7(): assert cos(3*x)/cos(x) == cos(x)**2 - 3*sin(x)**2 @XFAIL def test_I8(): assert cos(3*x)/cos(x) == 2*cos(2*x) - 1 @XFAIL def test_I9(): # Supposed to do this with rewrite rules. assert cos(3*x)/cos(x) == cos(x)**2 - 3*sin(x)**2 def test_I10(): assert trigsimp((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1)) is nan @SKIP("hangs") @XFAIL def test_I11(): assert limit((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1), x, 0) != 0 @XFAIL def test_I12(): # This should fail or return nan or something. res = diff((tan(x)**2 + 1 - cos(x)**-2) / (sin(x)**2 + cos(x)**2 - 1), x) assert res is nan # trigsimp(res) gives nan # J. Special functions. def test_J1(): assert bernoulli(16) == R(-3617, 510) def test_J2(): assert diff(elliptic_e(x, y**2), y) == (elliptic_e(x, y**2) - elliptic_f(x, y**2))/y @XFAIL def test_J3(): raise NotImplementedError("Jacobi elliptic functions: diff(dn(u,k), u) == -k**2*sn(u,k)*cn(u,k)") def test_J4(): assert gamma(R(-1, 2)) == -2*sqrt(pi) def test_J5(): assert polygamma(0, R(1, 3)) == -log(3) - sqrt(3)*pi/6 - EulerGamma - log(sqrt(3)) def test_J6(): assert mpmath.besselj(2, 1 + 1j).ae(mpc('0.04157988694396212', '0.24739764151330632')) def test_J7(): assert simplify(besselj(R(-5,2), pi/2)) == 12/(pi**2) def test_J8(): p = besselj(R(3,2), z) q = (sin(z)/z - cos(z))/sqrt(pi*z/2) assert simplify(expand_func(p) -q) == 0 def test_J9(): assert besselj(0, z).diff(z) == - besselj(1, z) def test_J10(): mu, nu = symbols('mu, nu', integer=True) assert assoc_legendre(nu, mu, 0) == 2**mu*sqrt(pi)/gamma((nu - mu)/2 + 1)/gamma((-nu - mu + 1)/2) def test_J11(): assert simplify(assoc_legendre(3, 1, x)) == simplify(-R(3, 2)*sqrt(1 - x**2)*(5*x**2 - 1)) @slow def test_J12(): assert simplify(chebyshevt(1008, x) - 2*x*chebyshevt(1007, x) + chebyshevt(1006, x)) == 0 def test_J13(): a = symbols('a', integer=True, negative=False) assert chebyshevt(a, -1) == (-1)**a def test_J14(): p = hyper([S.Half, S.Half], [R(3, 2)], z**2) assert hyperexpand(p) == asin(z)/z @XFAIL def test_J15(): raise NotImplementedError("F((n+2)/2,-(n-2)/2,R(3,2),sin(z)**2) == sin(n*z)/(n*sin(z)*cos(z)); F(.) is hypergeometric function") @XFAIL def test_J16(): raise NotImplementedError("diff(zeta(x), x) @ x=0 == -log(2*pi)/2") def test_J17(): assert integrate(f((x + 2)/5)*DiracDelta((x - 2)/3) - g(x)*diff(DiracDelta(x - 1), x), (x, 0, 3)) == 3*f(R(4, 5)) + Subs(Derivative(g(x), x), x, 1) @XFAIL def test_J18(): raise NotImplementedError("define an antisymmetric function") # K. The Complex Domain def test_K1(): z1, z2 = symbols('z1, z2', complex=True) assert re(z1 + I*z2) == -im(z2) + re(z1) assert im(z1 + I*z2) == im(z1) + re(z2) def test_K2(): assert abs(3 - sqrt(7) + I*sqrt(6*sqrt(7) - 15)) == 1 @XFAIL def test_K3(): a, b = symbols('a, b', real=True) assert simplify(abs(1/(a + I/a + I*b))) == 1/sqrt(a**2 + (I/a + b)**2) def test_K4(): assert log(3 + 4*I).expand(complex=True) == log(5) + I*atan(R(4, 3)) def test_K5(): x, y = symbols('x, y', real=True) assert tan(x + I*y).expand(complex=True) == (sin(2*x)/(cos(2*x) + cosh(2*y)) + I*sinh(2*y)/(cos(2*x) + cosh(2*y))) def test_K6(): assert sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z)) == sqrt(x*y)/sqrt(x) assert sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z)) != sqrt(y) def test_K7(): y = symbols('y', real=True, negative=False) expr = sqrt(x*y*abs(z)**2)/(sqrt(x)*abs(z)) sexpr = simplify(expr) assert sexpr == sqrt(y) def test_K8(): z = symbols('z', complex=True) assert simplify(sqrt(1/z) - 1/sqrt(z)) != 0 # Passes z = symbols('z', complex=True, negative=False) assert simplify(sqrt(1/z) - 1/sqrt(z)) == 0 # Fails def test_K9(): z = symbols('z', positive=True) assert simplify(sqrt(1/z) - 1/sqrt(z)) == 0 def test_K10(): z = symbols('z', negative=True) assert simplify(sqrt(1/z) + 1/sqrt(z)) == 0 # This goes up to K25 # L. Determining Zero Equivalence def test_L1(): assert sqrt(997) - (997**3)**R(1, 6) == 0 def test_L2(): assert sqrt(999983) - (999983**3)**R(1, 6) == 0 def test_L3(): assert simplify((2**R(1, 3) + 4**R(1, 3))**3 - 6*(2**R(1, 3) + 4**R(1, 3)) - 6) == 0 def test_L4(): assert trigsimp(cos(x)**3 + cos(x)*sin(x)**2 - cos(x)) == 0 @XFAIL def test_L5(): assert log(tan(R(1, 2)*x + pi/4)) - asinh(tan(x)) == 0 def test_L6(): assert (log(tan(x/2 + pi/4)) - asinh(tan(x))).diff(x).subs({x: 0}) == 0 @XFAIL def test_L7(): assert simplify(log((2*sqrt(x) + 1)/(sqrt(4*x + 4*sqrt(x) + 1)))) == 0 @XFAIL def test_L8(): assert simplify((4*x + 4*sqrt(x) + 1)**(sqrt(x)/(2*sqrt(x) + 1)) \ *(2*sqrt(x) + 1)**(1/(2*sqrt(x) + 1)) - 2*sqrt(x) - 1) == 0 @XFAIL def test_L9(): z = symbols('z', complex=True) assert simplify(2**(1 - z)*gamma(z)*zeta(z)*cos(z*pi/2) - pi**2*zeta(1 - z)) == 0 # M. Equations @XFAIL def test_M1(): assert Equality(x, 2)/2 + Equality(1, 1) == Equality(x/2 + 1, 2) def test_M2(): # The roots of this equation should all be real. Note that this # doesn't test that they are correct. sol = solveset(3*x**3 - 18*x**2 + 33*x - 19, x) assert all(s.expand(complex=True).is_real for s in sol) @XFAIL def test_M5(): assert solveset(x**6 - 9*x**4 - 4*x**3 + 27*x**2 - 36*x - 23, x) == FiniteSet(2**(1/3) + sqrt(3), 2**(1/3) - sqrt(3), +sqrt(3) - 1/2**(2/3) + I*sqrt(3)/2**(2/3), +sqrt(3) - 1/2**(2/3) - I*sqrt(3)/2**(2/3), -sqrt(3) - 1/2**(2/3) + I*sqrt(3)/2**(2/3), -sqrt(3) - 1/2**(2/3) - I*sqrt(3)/2**(2/3)) def test_M6(): assert set(solveset(x**7 - 1, x)) == \ {cos(n*pi*R(2, 7)) + I*sin(n*pi*R(2, 7)) for n in range(0, 7)} # The paper asks for exp terms, but sin's and cos's may be acceptable; # if the results are simplified, exp terms appear for all but # -sin(pi/14) - I*cos(pi/14) and -sin(pi/14) + I*cos(pi/14) which # will simplify if you apply the transformation foo.rewrite(exp).expand() def test_M7(): # TODO: Replace solve with solveset, as of now test fails for solveset assert set(solve(x**8 - 8*x**7 + 34*x**6 - 92*x**5 + 175*x**4 - 236*x**3 + 226*x**2 - 140*x + 46, x)) == set([ 1 - sqrt(2)*I*sqrt(-sqrt(-3 + 4*sqrt(3)) + 3)/2, 1 - sqrt(2)*sqrt(-3 + I*sqrt(3 + 4*sqrt(3)))/2, 1 - sqrt(2)*I*sqrt(sqrt(-3 + 4*sqrt(3)) + 3)/2, 1 - sqrt(2)*sqrt(-3 - I*sqrt(3 + 4*sqrt(3)))/2, 1 + sqrt(2)*I*sqrt(sqrt(-3 + 4*sqrt(3)) + 3)/2, 1 + sqrt(2)*sqrt(-3 - I*sqrt(3 + 4*sqrt(3)))/2, 1 + sqrt(2)*sqrt(-3 + I*sqrt(3 + 4*sqrt(3)))/2, 1 + sqrt(2)*I*sqrt(-sqrt(-3 + 4*sqrt(3)) + 3)/2, ]) @XFAIL # There are an infinite number of solutions. def test_M8(): x = Symbol('x') z = symbols('z', complex=True) assert solveset(exp(2*x) + 2*exp(x) + 1 - z, x, S.Reals) == \ FiniteSet(log(1 + z - 2*sqrt(z))/2, log(1 + z + 2*sqrt(z))/2) # This one could be simplified better (the 1/2 could be pulled into the log # as a sqrt, and the function inside the log can be factored as a square, # giving [log(sqrt(z) - 1), log(sqrt(z) + 1)]). Also, there should be an # infinite number of solutions. # x = {log(sqrt(z) - 1), log(sqrt(z) + 1) + i pi} [+ n 2 pi i, + n 2 pi i] # where n is an arbitrary integer. See url of detailed output above. @XFAIL def test_M9(): # x = symbols('x') raise NotImplementedError("solveset(exp(2-x**2)-exp(-x),x) has complex solutions.") def test_M10(): # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(exp(x) - x, x) == [-LambertW(-1)] @XFAIL def test_M11(): assert solveset(x**x - x, x) == FiniteSet(-1, 1) def test_M12(): # TODO: x = [-1, 2*(+/-asinh(1)*I + n*pi}, 3*(pi/6 + n*pi/3)] # TODO: Replace solve with solveset, as of now test fails for solveset assert solve((x + 1)*(sin(x)**2 + 1)**2*cos(3*x)**3, x) == [ -1, pi/6, pi/2, - I*log(1 + sqrt(2)), I*log(1 + sqrt(2)), pi - I*log(1 + sqrt(2)), pi + I*log(1 + sqrt(2)), ] @XFAIL def test_M13(): n = Dummy('n') assert solveset_real(sin(x) - cos(x), x) == ImageSet(Lambda(n, n*pi - pi*R(7, 4)), S.Integers) @XFAIL def test_M14(): n = Dummy('n') assert solveset_real(tan(x) - 1, x) == ImageSet(Lambda(n, n*pi + pi/4), S.Integers) def test_M15(): n = Dummy('n') got = solveset(sin(x) - S.Half) assert any(got.dummy_eq(i) for i in ( Union(ImageSet(Lambda(n, 2*n*pi + pi/6), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi*R(5, 6)), S.Integers)), Union(ImageSet(Lambda(n, 2*n*pi + pi*R(5, 6)), S.Integers), ImageSet(Lambda(n, 2*n*pi + pi/6), S.Integers)))) @XFAIL def test_M16(): n = Dummy('n') assert solveset(sin(x) - tan(x), x) == ImageSet(Lambda(n, n*pi), S.Integers) @XFAIL def test_M17(): assert solveset_real(asin(x) - atan(x), x) == FiniteSet(0) @XFAIL def test_M18(): assert solveset_real(acos(x) - atan(x), x) == FiniteSet(sqrt((sqrt(5) - 1)/2)) def test_M19(): # TODO: Replace solve with solveset, as of now test fails for solveset assert solve((x - 2)/x**R(1, 3), x) == [2] def test_M20(): assert solveset(sqrt(x**2 + 1) - x + 2, x) == EmptySet def test_M21(): assert solveset(x + sqrt(x) - 2) == FiniteSet(1) def test_M22(): assert solveset(2*sqrt(x) + 3*x**R(1, 4) - 2) == FiniteSet(R(1, 16)) def test_M23(): x = symbols('x', complex=True) # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(x - 1/sqrt(1 + x**2)) == [ -I*sqrt(S.Half + sqrt(5)/2), sqrt(Rational(-1, 2) + sqrt(5)/2)] def test_M24(): # TODO: Replace solve with solveset, as of now test fails for solveset solution = solve(1 - binomial(m, 2)*2**k, k) answer = log(2/(m*(m - 1)), 2) assert solution[0].expand() == answer.expand() def test_M25(): a, b, c, d = symbols(':d', positive=True) x = symbols('x') # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(a*b**x - c*d**x, x)[0].expand() == (log(c/a)/log(b/d)).expand() def test_M26(): # TODO: Replace solve with solveset, as of now test fails for solveset assert solve(sqrt(log(x)) - log(sqrt(x))) == [1, exp(4)] def test_M27(): x = symbols('x', real=True) b = symbols('b', real=True) # TODO: Replace solve with solveset which gives both [+/- current answer] # note that there is a typo in this test in the wester.pdf; there is no # real solution for the equation as it appears in wester.pdf assert solve(log(acos(asin(x**R(2, 3) - b)) - 1) + 2, x ) == [(b + sin(cos(exp(-2) + 1)))**R(3, 2)] @XFAIL def test_M28(): assert solveset_real(5*x + exp((x - 5)/2) - 8*x**3, x, assume=Q.real(x)) == [-0.784966, -0.016291, 0.802557] def test_M29(): x = symbols('x') assert solveset(abs(x - 1) - 2, domain=S.Reals) == FiniteSet(-1, 3) def test_M30(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions # assert solve(abs(2*x + 5) - abs(x - 2),x, assume=Q.real(x)) == [-1, -7] assert solveset_real(abs(2*x + 5) - abs(x - 2), x) == FiniteSet(-1, -7) def test_M31(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions # assert solve(1 - abs(x) - max(-x - 2, x - 2),x, assume=Q.real(x)) == [-3/2, 3/2] assert solveset_real(1 - abs(x) - Max(-x - 2, x - 2), x) == FiniteSet(R(-3, 2), R(3, 2)) @XFAIL def test_M32(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions assert solveset_real(Max(2 - x**2, x)- Max(-x, (x**3)/9), x) == FiniteSet(-1, 3) @XFAIL def test_M33(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports assumptions # Second answer can be written in another form. The second answer is the root of x**3 + 9*x**2 - 18 = 0 in the interval (-2, -1). assert solveset_real(Max(2 - x**2, x) - x**3/9, x) == FiniteSet(-3, -1.554894, 3) @XFAIL def test_M34(): z = symbols('z', complex=True) assert solveset((1 + I) * z + (2 - I) * conjugate(z) + 3*I, z) == FiniteSet(2 + 3*I) def test_M35(): x, y = symbols('x y', real=True) assert linsolve((3*x - 2*y - I*y + 3*I).as_real_imag(), y, x) == FiniteSet((3, 2)) def test_M36(): # TODO: Replace solve with solveset, as of now # solveset doesn't supports solving for function # assert solve(f**2 + f - 2, x) == [Eq(f(x), 1), Eq(f(x), -2)] assert solveset(f(x)**2 + f(x) - 2, f(x)) == FiniteSet(-2, 1) def test_M37(): assert linsolve([x + y + z - 6, 2*x + y + 2*z - 10, x + 3*y + z - 10 ], x, y, z) == \ FiniteSet((-z + 4, 2, z)) def test_M38(): a, b, c = symbols('a, b, c') domain = FracField([a, b, c], ZZ).to_domain() ring = PolyRing('k1:50', domain) (k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k20, k21, k22, k23, k24, k25, k26, k27, k28, k29, k30, k31, k32, k33, k34, k35, k36, k37, k38, k39, k40, k41, k42, k43, k44, k45, k46, k47, k48, k49) = ring.gens system = [ -b*k8/a + c*k8/a, -b*k11/a + c*k11/a, -b*k10/a + c*k10/a + k2, -k3 - b*k9/a + c*k9/a, -b*k14/a + c*k14/a, -b*k15/a + c*k15/a, -b*k18/a + c*k18/a - k2, -b*k17/a + c*k17/a, -b*k16/a + c*k16/a + k4, -b*k13/a + c*k13/a - b*k21/a + c*k21/a + b*k5/a - c*k5/a, b*k44/a - c*k44/a, -b*k45/a + c*k45/a, -b*k20/a + c*k20/a, -b*k44/a + c*k44/a, b*k46/a - c*k46/a, b**2*k47/a**2 - 2*b*c*k47/a**2 + c**2*k47/a**2, k3, -k4, -b*k12/a + c*k12/a - a*k6/b + c*k6/b, -b*k19/a + c*k19/a + a*k7/c - b*k7/c, b*k45/a - c*k45/a, -b*k46/a + c*k46/a, -k48 + c*k48/a + c*k48/b - c**2*k48/(a*b), -k49 + b*k49/a + b*k49/c - b**2*k49/(a*c), a*k1/b - c*k1/b, a*k4/b - c*k4/b, a*k3/b - c*k3/b + k9, -k10 + a*k2/b - c*k2/b, a*k7/b - c*k7/b, -k9, k11, b*k12/a - c*k12/a + a*k6/b - c*k6/b, a*k15/b - c*k15/b, k10 + a*k18/b - c*k18/b, -k11 + a*k17/b - c*k17/b, a*k16/b - c*k16/b, -a*k13/b + c*k13/b + a*k21/b - c*k21/b + a*k5/b - c*k5/b, -a*k44/b + c*k44/b, a*k45/b - c*k45/b, a*k14/c - b*k14/c + a*k20/b - c*k20/b, a*k44/b - c*k44/b, -a*k46/b + c*k46/b, -k47 + c*k47/a + c*k47/b - c**2*k47/(a*b), a*k19/b - c*k19/b, -a*k45/b + c*k45/b, a*k46/b - c*k46/b, a**2*k48/b**2 - 2*a*c*k48/b**2 + c**2*k48/b**2, -k49 + a*k49/b + a*k49/c - a**2*k49/(b*c), k16, -k17, -a*k1/c + b*k1/c, -k16 - a*k4/c + b*k4/c, -a*k3/c + b*k3/c, k18 - a*k2/c + b*k2/c, b*k19/a - c*k19/a - a*k7/c + b*k7/c, -a*k6/c + b*k6/c, -a*k8/c + b*k8/c, -a*k11/c + b*k11/c + k17, -a*k10/c + b*k10/c - k18, -a*k9/c + b*k9/c, -a*k14/c + b*k14/c - a*k20/b + c*k20/b, -a*k13/c + b*k13/c + a*k21/c - b*k21/c - a*k5/c + b*k5/c, a*k44/c - b*k44/c, -a*k45/c + b*k45/c, -a*k44/c + b*k44/c, a*k46/c - b*k46/c, -k47 + b*k47/a + b*k47/c - b**2*k47/(a*c), -a*k12/c + b*k12/c, a*k45/c - b*k45/c, -a*k46/c + b*k46/c, -k48 + a*k48/b + a*k48/c - a**2*k48/(b*c), a**2*k49/c**2 - 2*a*b*k49/c**2 + b**2*k49/c**2, k8, k11, -k15, k10 - k18, -k17, k9, -k16, -k29, k14 - k32, -k21 + k23 - k31, -k24 - k30, -k35, k44, -k45, k36, k13 - k23 + k39, -k20 + k38, k25 + k37, b*k26/a - c*k26/a - k34 + k42, -2*k44, k45, k46, b*k47/a - c*k47/a, k41, k44, -k46, -b*k47/a + c*k47/a, k12 + k24, -k19 - k25, -a*k27/b + c*k27/b - k33, k45, -k46, -a*k48/b + c*k48/b, a*k28/c - b*k28/c + k40, -k45, k46, a*k48/b - c*k48/b, a*k49/c - b*k49/c, -a*k49/c + b*k49/c, -k1, -k4, -k3, k15, k18 - k2, k17, k16, k22, k25 - k7, k24 + k30, k21 + k23 - k31, k28, -k44, k45, -k30 - k6, k20 + k32, k27 + b*k33/a - c*k33/a, k44, -k46, -b*k47/a + c*k47/a, -k36, k31 - k39 - k5, -k32 - k38, k19 - k37, k26 - a*k34/b + c*k34/b - k42, k44, -2*k45, k46, a*k48/b - c*k48/b, a*k35/c - b*k35/c - k41, -k44, k46, b*k47/a - c*k47/a, -a*k49/c + b*k49/c, -k40, k45, -k46, -a*k48/b + c*k48/b, a*k49/c - b*k49/c, k1, k4, k3, -k8, -k11, -k10 + k2, -k9, k37 + k7, -k14 - k38, -k22, -k25 - k37, -k24 + k6, -k13 - k23 + k39, -k28 + b*k40/a - c*k40/a, k44, -k45, -k27, -k44, k46, b*k47/a - c*k47/a, k29, k32 + k38, k31 - k39 + k5, -k12 + k30, k35 - a*k41/b + c*k41/b, -k44, k45, -k26 + k34 + a*k42/c - b*k42/c, k44, k45, -2*k46, -b*k47/a + c*k47/a, -a*k48/b + c*k48/b, a*k49/c - b*k49/c, k33, -k45, k46, a*k48/b - c*k48/b, -a*k49/c + b*k49/c ] solution = { k49: 0, k48: 0, k47: 0, k46: 0, k45: 0, k44: 0, k41: 0, k40: 0, k38: 0, k37: 0, k36: 0, k35: 0, k33: 0, k32: 0, k30: 0, k29: 0, k28: 0, k27: 0, k25: 0, k24: 0, k22: 0, k21: 0, k20: 0, k19: 0, k18: 0, k17: 0, k16: 0, k15: 0, k14: 0, k13: 0, k12: 0, k11: 0, k10: 0, k9: 0, k8: 0, k7: 0, k6: 0, k5: 0, k4: 0, k3: 0, k2: 0, k1: 0, k34: b/c*k42, k31: k39, k26: a/c*k42, k23: k39 } assert solve_lin_sys(system, ring) == solution def test_M39(): x, y, z = symbols('x y z', complex=True) # TODO: Replace solve with solveset, as of now # solveset doesn't supports non-linear multivariate assert solve([x**2*y + 3*y*z - 4, -3*x**2*z + 2*y**2 + 1, 2*y*z**2 - z**2 - 1 ]) ==\ [{y: 1, z: 1, x: -1}, {y: 1, z: 1, x: 1},\ {y: sqrt(2)*I, z: R(1,3) - sqrt(2)*I/3, x: -sqrt(-1 - sqrt(2)*I)},\ {y: sqrt(2)*I, z: R(1,3) - sqrt(2)*I/3, x: sqrt(-1 - sqrt(2)*I)},\ {y: -sqrt(2)*I, z: R(1,3) + sqrt(2)*I/3, x: -sqrt(-1 + sqrt(2)*I)},\ {y: -sqrt(2)*I, z: R(1,3) + sqrt(2)*I/3, x: sqrt(-1 + sqrt(2)*I)}] # N. Inequalities def test_N1(): assert ask(E**pi > pi**E) @XFAIL def test_N2(): x = symbols('x', real=True) assert ask(x**4 - x + 1 > 0) is True assert ask(x**4 - x + 1 > 1) is False @XFAIL def test_N3(): x = symbols('x', real=True) assert ask(And(Lt(-1, x), Lt(x, 1)), abs(x) < 1 ) @XFAIL def test_N4(): x, y = symbols('x y', real=True) assert ask(2*x**2 > 2*y**2, (x > y) & (y > 0)) is True @XFAIL def test_N5(): x, y, k = symbols('x y k', real=True) assert ask(k*x**2 > k*y**2, (x > y) & (y > 0) & (k > 0)) is True @slow @XFAIL def test_N6(): x, y, k, n = symbols('x y k n', real=True) assert ask(k*x**n > k*y**n, (x > y) & (y > 0) & (k > 0) & (n > 0)) is True @XFAIL def test_N7(): x, y = symbols('x y', real=True) assert ask(y > 0, (x > 1) & (y >= x - 1)) is True @XFAIL @slow def test_N8(): x, y, z = symbols('x y z', real=True) assert ask(Eq(x, y) & Eq(y, z), (x >= y) & (y >= z) & (z >= x)) def test_N9(): x = Symbol('x') assert solveset(abs(x - 1) > 2, domain=S.Reals) == Union(Interval(-oo, -1, False, True), Interval(3, oo, True)) def test_N10(): x = Symbol('x') p = (x - 1)*(x - 2)*(x - 3)*(x - 4)*(x - 5) assert solveset(expand(p) < 0, domain=S.Reals) == Union(Interval(-oo, 1, True, True), Interval(2, 3, True, True), Interval(4, 5, True, True)) def test_N11(): x = Symbol('x') assert solveset(6/(x - 3) <= 3, domain=S.Reals) == Union(Interval(-oo, 3, True, True), Interval(5, oo)) def test_N12(): x = Symbol('x') assert solveset(sqrt(x) < 2, domain=S.Reals) == Interval(0, 4, False, True) def test_N13(): x = Symbol('x') assert solveset(sin(x) < 2, domain=S.Reals) == S.Reals @XFAIL def test_N14(): x = Symbol('x') # Gives 'Union(Interval(Integer(0), Mul(Rational(1, 2), pi), false, true), # Interval(Mul(Rational(1, 2), pi), Mul(Integer(2), pi), true, false))' # which is not the correct answer, but the provided also seems wrong. assert solveset(sin(x) < 1, x, domain=S.Reals) == Union(Interval(-oo, pi/2, True, True), Interval(pi/2, oo, True, True)) def test_N15(): r, t = symbols('r t') # raises NotImplementedError: only univariate inequalities are supported solveset(abs(2*r*(cos(t) - 1) + 1) <= 1, r, S.Reals) def test_N16(): r, t = symbols('r t') solveset((r**2)*((cos(t) - 4)**2)*sin(t)**2 < 9, r, S.Reals) @XFAIL def test_N17(): # currently only univariate inequalities are supported assert solveset((x + y > 0, x - y < 0), (x, y)) == (abs(x) < y) def test_O1(): M = Matrix((1 + I, -2, 3*I)) assert sqrt(expand(M.dot(M.H))) == sqrt(15) def test_O2(): assert Matrix((2, 2, -3)).cross(Matrix((1, 3, 1))) == Matrix([[11], [-5], [4]]) # The vector module has no way of representing vectors symbolically (without # respect to a basis) @XFAIL def test_O3(): # assert (va ^ vb) | (vc ^ vd) == -(va | vc)*(vb | vd) + (va | vd)*(vb | vc) raise NotImplementedError("""The vector module has no way of representing vectors symbolically (without respect to a basis)""") def test_O4(): from sympy.vector import CoordSys3D, Del N = CoordSys3D("N") delop = Del() i, j, k = N.base_vectors() x, y, z = N.base_scalars() F = i*(x*y*z) + j*((x*y*z)**2) + k*((y**2)*(z**3)) assert delop.cross(F).doit() == (-2*x**2*y**2*z + 2*y*z**3)*i + x*y*j + (2*x*y**2*z**2 - x*z)*k @XFAIL def test_O5(): #assert grad|(f^g)-g|(grad^f)+f|(grad^g) == 0 raise NotImplementedError("""The vector module has no way of representing vectors symbolically (without respect to a basis)""") #testO8-O9 MISSING!! def test_O10(): L = [Matrix([2, 3, 5]), Matrix([3, 6, 2]), Matrix([8, 3, 6])] assert GramSchmidt(L) == [Matrix([ [2], [3], [5]]), Matrix([ [R(23, 19)], [R(63, 19)], [R(-47, 19)]]), Matrix([ [R(1692, 353)], [R(-1551, 706)], [R(-423, 706)]])] def test_P1(): assert Matrix(3, 3, lambda i, j: j - i).diagonal(-1) == Matrix( 1, 2, [-1, -1]) def test_P2(): M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) M.row_del(1) M.col_del(2) assert M == Matrix([[1, 2], [7, 8]]) def test_P3(): A = Matrix([ [11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]) A11 = A[0:3, 1:4] A12 = A[(0, 1, 3), (2, 0, 3)] A21 = A A221 = -A[0:2, 2:4] A222 = -A[(3, 0), (2, 1)] A22 = BlockMatrix([[A221, A222]]).T rows = [[-A11, A12], [A21, A22]] raises(ValueError, lambda: BlockMatrix(rows)) B = Matrix(rows) assert B == Matrix([ [-12, -13, -14, 13, 11, 14], [-22, -23, -24, 23, 21, 24], [-32, -33, -34, 43, 41, 44], [11, 12, 13, 14, -13, -23], [21, 22, 23, 24, -14, -24], [31, 32, 33, 34, -43, -13], [41, 42, 43, 44, -42, -12]]) @XFAIL def test_P4(): raise NotImplementedError("Block matrix diagonalization not supported") def test_P5(): M = Matrix([[7, 11], [3, 8]]) assert M % 2 == Matrix([[1, 1], [1, 0]]) def test_P6(): M = Matrix([[cos(x), sin(x)], [-sin(x), cos(x)]]) assert M.diff(x, 2) == Matrix([[-cos(x), -sin(x)], [sin(x), -cos(x)]]) def test_P7(): M = Matrix([[x, y]])*( z*Matrix([[1, 3, 5], [2, 4, 6]]) + Matrix([[7, -9, 11], [-8, 10, -12]])) assert M == Matrix([[x*(z + 7) + y*(2*z - 8), x*(3*z - 9) + y*(4*z + 10), x*(5*z + 11) + y*(6*z - 12)]]) def test_P8(): M = Matrix([[1, -2*I], [-3*I, 4]]) assert M.norm(ord=S.Infinity) == 7 def test_P9(): a, b, c = symbols('a b c', nonzero=True) M = Matrix([[a/(b*c), 1/c, 1/b], [1/c, b/(a*c), 1/a], [1/b, 1/a, c/(a*b)]]) assert factor(M.norm('fro')) == (a**2 + b**2 + c**2)/(abs(a)*abs(b)*abs(c)) @XFAIL def test_P10(): M = Matrix([[1, 2 + 3*I], [f(4 - 5*I), 6]]) # conjugate(f(4 - 5*i)) is not simplified to f(4+5*I) assert M.H == Matrix([[1, f(4 + 5*I)], [2 + 3*I, 6]]) @XFAIL def test_P11(): # raises NotImplementedError("Matrix([[x,y],[1,x*y]]).inv() # not simplifying to extract common factor") assert Matrix([[x, y], [1, x*y]]).inv() == (1/(x**2 - 1))*Matrix([[x, -1], [-1/y, x/y]]) def test_P11_workaround(): # This test was changed to inverse method ADJ because it depended on the # specific form of inverse returned from the 'GE' method which has changed. M = Matrix([[x, y], [1, x*y]]).inv('ADJ') c = gcd(tuple(M)) assert MatMul(c, M/c, evaluate=False) == MatMul(c, Matrix([ [x*y, -y], [ -1, x]]), evaluate=False) def test_P12(): A11 = MatrixSymbol('A11', n, n) A12 = MatrixSymbol('A12', n, n) A22 = MatrixSymbol('A22', n, n) B = BlockMatrix([[A11, A12], [ZeroMatrix(n, n), A22]]) assert block_collapse(B.I) == BlockMatrix([[A11.I, (-1)*A11.I*A12*A22.I], [ZeroMatrix(n, n), A22.I]]) def test_P13(): M = Matrix([[1, x - 2, x - 3], [x - 1, x**2 - 3*x + 6, x**2 - 3*x - 2], [x - 2, x**2 - 8, 2*(x**2) - 12*x + 14]]) L, U, _ = M.LUdecomposition() assert simplify(L) == Matrix([[1, 0, 0], [x - 1, 1, 0], [x - 2, x - 3, 1]]) assert simplify(U) == Matrix([[1, x - 2, x - 3], [0, 4, x - 5], [0, 0, x - 7]]) def test_P14(): M = Matrix([[1, 2, 3, 1, 3], [3, 2, 1, 1, 7], [0, 2, 4, 1, 1], [1, 1, 1, 1, 4]]) R, _ = M.rref() assert R == Matrix([[1, 0, -1, 0, 2], [0, 1, 2, 0, -1], [0, 0, 0, 1, 3], [0, 0, 0, 0, 0]]) def test_P15(): M = Matrix([[-1, 3, 7, -5], [4, -2, 1, 3], [2, 4, 15, -7]]) assert M.rank() == 2 def test_P16(): M = Matrix([[2*sqrt(2), 8], [6*sqrt(6), 24*sqrt(3)]]) assert M.rank() == 1 def test_P17(): t = symbols('t', real=True) M=Matrix([ [sin(2*t), cos(2*t)], [2*(1 - (cos(t)**2))*cos(t), (1 - 2*(sin(t)**2))*sin(t)]]) assert M.rank() == 1 def test_P18(): M = Matrix([[1, 0, -2, 0], [-2, 1, 0, 3], [-1, 2, -6, 6]]) assert M.nullspace() == [Matrix([[2], [4], [1], [0]]), Matrix([[0], [-3], [0], [1]])] def test_P19(): w = symbols('w') M = Matrix([[1, 1, 1, 1], [w, x, y, z], [w**2, x**2, y**2, z**2], [w**3, x**3, y**3, z**3]]) assert M.det() == (w**3*x**2*y - w**3*x**2*z - w**3*x*y**2 + w**3*x*z**2 + w**3*y**2*z - w**3*y*z**2 - w**2*x**3*y + w**2*x**3*z + w**2*x*y**3 - w**2*x*z**3 - w**2*y**3*z + w**2*y*z**3 + w*x**3*y**2 - w*x**3*z**2 - w*x**2*y**3 + w*x**2*z**3 + w*y**3*z**2 - w*y**2*z**3 - x**3*y**2*z + x**3*y*z**2 + x**2*y**3*z - x**2*y*z**3 - x*y**3*z**2 + x*y**2*z**3 ) @XFAIL def test_P20(): raise NotImplementedError("Matrix minimal polynomial not supported") def test_P21(): M = Matrix([[5, -3, -7], [-2, 1, 2], [2, -3, -4]]) assert M.charpoly(x).as_expr() == x**3 - 2*x**2 - 5*x + 6 def test_P22(): d = 100 M = (2 - x)*eye(d) assert M.eigenvals() == {-x + 2: d} def test_P23(): M = Matrix([ [2, 1, 0, 0, 0], [1, 2, 1, 0, 0], [0, 1, 2, 1, 0], [0, 0, 1, 2, 1], [0, 0, 0, 1, 2]]) assert M.eigenvals() == { S('1'): 1, S('2'): 1, S('3'): 1, S('sqrt(3) + 2'): 1, S('-sqrt(3) + 2'): 1} def test_P24(): M = Matrix([[611, 196, -192, 407, -8, -52, -49, 29], [196, 899, 113, -192, -71, -43, -8, -44], [-192, 113, 899, 196, 61, 49, 8, 52], [ 407, -192, 196, 611, 8, 44, 59, -23], [ -8, -71, 61, 8, 411, -599, 208, 208], [ -52, -43, 49, 44, -599, 411, 208, 208], [ -49, -8, 8, 59, 208, 208, 99, -911], [ 29, -44, 52, -23, 208, 208, -911, 99]]) assert M.eigenvals() == { S('0'): 1, S('10*sqrt(10405)'): 1, S('100*sqrt(26) + 510'): 1, S('1000'): 2, S('-100*sqrt(26) + 510'): 1, S('-10*sqrt(10405)'): 1, S('1020'): 1} def test_P25(): MF = N(Matrix([[ 611, 196, -192, 407, -8, -52, -49, 29], [ 196, 899, 113, -192, -71, -43, -8, -44], [-192, 113, 899, 196, 61, 49, 8, 52], [ 407, -192, 196, 611, 8, 44, 59, -23], [ -8, -71, 61, 8, 411, -599, 208, 208], [ -52, -43, 49, 44, -599, 411, 208, 208], [ -49, -8, 8, 59, 208, 208, 99, -911], [ 29, -44, 52, -23, 208, 208, -911, 99]])) ev_1 = sorted(MF.eigenvals(multiple=True)) ev_2 = sorted( [-1020.0490184299969, 0.0, 0.09804864072151699, 1000.0, 1000.0, 1019.9019513592784, 1020.0, 1020.0490184299969]) for x, y in zip(ev_1, ev_2): assert abs(x - y) < 1e-12 def test_P26(): a0, a1, a2, a3, a4 = symbols('a0 a1 a2 a3 a4') M = Matrix([[-a4, -a3, -a2, -a1, -a0, 0, 0, 0, 0], [ 1, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 1, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 1, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 1, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, -1, -1, 0, 0], [ 0, 0, 0, 0, 0, 1, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 1, -1, -1], [ 0, 0, 0, 0, 0, 0, 0, 1, 0]]) assert M.eigenvals(error_when_incomplete=False) == { S('-1/2 - sqrt(3)*I/2'): 2, S('-1/2 + sqrt(3)*I/2'): 2} def test_P27(): a = symbols('a') M = Matrix([[a, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, a, 0, 0], [0, 0, 0, a, 0], [0, -2, 0, 0, 2]]) assert M.eigenvects() == [ (a, 3, [ Matrix([1, 0, 0, 0, 0]), Matrix([0, 0, 1, 0, 0]), Matrix([0, 0, 0, 1, 0]) ]), (1 - I, 1, [ Matrix([0, (1 + I)/2, 0, 0, 1]) ]), (1 + I, 1, [ Matrix([0, (1 - I)/2, 0, 0, 1]) ]), ] @XFAIL def test_P28(): raise NotImplementedError("Generalized eigenvectors not supported \ https://github.com/sympy/sympy/issues/5293") @XFAIL def test_P29(): raise NotImplementedError("Generalized eigenvectors not supported \ https://github.com/sympy/sympy/issues/5293") def test_P30(): M = Matrix([[1, 0, 0, 1, -1], [0, 1, -2, 3, -3], [0, 0, -1, 2, -2], [1, -1, 1, 0, 1], [1, -1, 1, -1, 2]]) _, J = M.jordan_form() assert J == Matrix([[-1, 0, 0, 0, 0], [0, 1, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 0, 1]]) @XFAIL def test_P31(): raise NotImplementedError("Smith normal form not implemented") def test_P32(): M = Matrix([[1, -2], [2, 1]]) assert exp(M).rewrite(cos).simplify() == Matrix([[E*cos(2), -E*sin(2)], [E*sin(2), E*cos(2)]]) def test_P33(): w, t = symbols('w t') M = Matrix([[0, 1, 0, 0], [0, 0, 0, 2*w], [0, 0, 0, 1], [0, -2*w, 3*w**2, 0]]) assert exp(M*t).rewrite(cos).expand() == Matrix([ [1, -3*t + 4*sin(t*w)/w, 6*t*w - 6*sin(t*w), -2*cos(t*w)/w + 2/w], [0, 4*cos(t*w) - 3, -6*w*cos(t*w) + 6*w, 2*sin(t*w)], [0, 2*cos(t*w)/w - 2/w, -3*cos(t*w) + 4, sin(t*w)/w], [0, -2*sin(t*w), 3*w*sin(t*w), cos(t*w)]]) @XFAIL def test_P34(): a, b, c = symbols('a b c', real=True) M = Matrix([[a, 1, 0, 0, 0, 0], [0, a, 0, 0, 0, 0], [0, 0, b, 0, 0, 0], [0, 0, 0, c, 1, 0], [0, 0, 0, 0, c, 1], [0, 0, 0, 0, 0, c]]) # raises exception, sin(M) not supported. exp(M*I) also not supported # https://github.com/sympy/sympy/issues/6218 assert sin(M) == Matrix([[sin(a), cos(a), 0, 0, 0, 0], [0, sin(a), 0, 0, 0, 0], [0, 0, sin(b), 0, 0, 0], [0, 0, 0, sin(c), cos(c), -sin(c)/2], [0, 0, 0, 0, sin(c), cos(c)], [0, 0, 0, 0, 0, sin(c)]]) @XFAIL def test_P35(): M = pi/2*Matrix([[2, 1, 1], [2, 3, 2], [1, 1, 2]]) # raises exception, sin(M) not supported. exp(M*I) also not supported # https://github.com/sympy/sympy/issues/6218 assert sin(M) == eye(3) @XFAIL def test_P36(): M = Matrix([[10, 7], [7, 17]]) assert sqrt(M) == Matrix([[3, 1], [1, 4]]) def test_P37(): M = Matrix([[1, 1, 0], [0, 1, 0], [0, 0, 1]]) assert M**S.Half == Matrix([[1, R(1, 2), 0], [0, 1, 0], [0, 0, 1]]) @XFAIL def test_P38(): M=Matrix([[0, 1, 0], [0, 0, 0], [0, 0, 0]]) with raises(AssertionError): # raises ValueError: Matrix det == 0; not invertible M**S.Half # if it doesn't raise then this assertion will be # raised and the test will be flagged as not XFAILing assert None @XFAIL def test_P39(): """ M=Matrix([ [1, 1], [2, 2], [3, 3]]) M.SVD() """ raise NotImplementedError("Singular value decomposition not implemented") def test_P40(): r, t = symbols('r t', real=True) M = Matrix([r*cos(t), r*sin(t)]) assert M.jacobian(Matrix([r, t])) == Matrix([[cos(t), -r*sin(t)], [sin(t), r*cos(t)]]) def test_P41(): r, t = symbols('r t', real=True) assert hessian(r**2*sin(t),(r,t)) == Matrix([[ 2*sin(t), 2*r*cos(t)], [2*r*cos(t), -r**2*sin(t)]]) def test_P42(): assert wronskian([cos(x), sin(x)], x).simplify() == 1 def test_P43(): def __my_jacobian(M, Y): return Matrix([M.diff(v).T for v in Y]).T r, t = symbols('r t', real=True) M = Matrix([r*cos(t), r*sin(t)]) assert __my_jacobian(M,[r,t]) == Matrix([[cos(t), -r*sin(t)], [sin(t), r*cos(t)]]) def test_P44(): def __my_hessian(f, Y): V = Matrix([diff(f, v) for v in Y]) return Matrix([V.T.diff(v) for v in Y]) r, t = symbols('r t', real=True) assert __my_hessian(r**2*sin(t), (r, t)) == Matrix([ [ 2*sin(t), 2*r*cos(t)], [2*r*cos(t), -r**2*sin(t)]]) def test_P45(): def __my_wronskian(Y, v): M = Matrix([Matrix(Y).T.diff(x, n) for n in range(0, len(Y))]) return M.det() assert __my_wronskian([cos(x), sin(x)], x).simplify() == 1 # Q1-Q6 Tensor tests missing @XFAIL def test_R1(): i, j, n = symbols('i j n', integer=True, positive=True) xn = MatrixSymbol('xn', n, 1) Sm = Sum((xn[i, 0] - Sum(xn[j, 0], (j, 0, n - 1))/n)**2, (i, 0, n - 1)) # sum does not calculate # Unknown result Sm.doit() raise NotImplementedError('Unknown result') @XFAIL def test_R2(): m, b = symbols('m b') i, n = symbols('i n', integer=True, positive=True) xn = MatrixSymbol('xn', n, 1) yn = MatrixSymbol('yn', n, 1) f = Sum((yn[i, 0] - m*xn[i, 0] - b)**2, (i, 0, n - 1)) f1 = diff(f, m) f2 = diff(f, b) # raises TypeError: solveset() takes at most 2 arguments (3 given) solveset((f1, f2), (m, b), domain=S.Reals) @XFAIL def test_R3(): n, k = symbols('n k', integer=True, positive=True) sk = ((-1)**k) * (binomial(2*n, k))**2 Sm = Sum(sk, (k, 1, oo)) T = Sm.doit() T2 = T.combsimp() # returns -((-1)**n*factorial(2*n) # - (factorial(n))**2)*exp_polar(-I*pi)/(factorial(n))**2 assert T2 == (-1)**n*binomial(2*n, n) @XFAIL def test_R4(): # Macsyma indefinite sum test case: #(c15) /* Check whether the full Gosper algorithm is implemented # => 1/2^(n + 1) binomial(n, k - 1) */ #closedform(indefsum(binomial(n, k)/2^n - binomial(n + 1, k)/2^(n + 1), k)); #Time= 2690 msecs # (- n + k - 1) binomial(n + 1, k) #(d15) - -------------------------------- # n # 2 2 (n + 1) # #(c16) factcomb(makefact(%)); #Time= 220 msecs # n! #(d16) ---------------- # n # 2 k! 2 (n - k)! # Might be possible after fixing https://github.com/sympy/sympy/pull/1879 raise NotImplementedError("Indefinite sum not supported") @XFAIL def test_R5(): a, b, c, n, k = symbols('a b c n k', integer=True, positive=True) sk = ((-1)**k)*(binomial(a + b, a + k) *binomial(b + c, b + k)*binomial(c + a, c + k)) Sm = Sum(sk, (k, 1, oo)) T = Sm.doit() # hypergeometric series not calculated assert T == factorial(a+b+c)/(factorial(a)*factorial(b)*factorial(c)) def test_R6(): n, k = symbols('n k', integer=True, positive=True) gn = MatrixSymbol('gn', n + 2, 1) Sm = Sum(gn[k, 0] - gn[k - 1, 0], (k, 1, n + 1)) assert Sm.doit() == -gn[0, 0] + gn[n + 1, 0] def test_R7(): n, k = symbols('n k', integer=True, positive=True) T = Sum(k**3,(k,1,n)).doit() assert T.factor() == n**2*(n + 1)**2/4 @XFAIL def test_R8(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(k**2*binomial(n, k), (k, 1, n)) T = Sm.doit() #returns Piecewise function assert T.combsimp() == n*(n + 1)*2**(n - 2) def test_R9(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(binomial(n, k - 1)/k, (k, 1, n + 1)) assert Sm.doit().simplify() == (2**(n + 1) - 1)/(n + 1) @XFAIL def test_R10(): n, m, r, k = symbols('n m r k', integer=True, positive=True) Sm = Sum(binomial(n, k)*binomial(m, r - k), (k, 0, r)) T = Sm.doit() T2 = T.combsimp().rewrite(factorial) assert T2 == factorial(m + n)/(factorial(r)*factorial(m + n - r)) assert T2 == binomial(m + n, r).rewrite(factorial) # rewrite(binomial) is not working. # https://github.com/sympy/sympy/issues/7135 T3 = T2.rewrite(binomial) assert T3 == binomial(m + n, r) @XFAIL def test_R11(): n, k = symbols('n k', integer=True, positive=True) sk = binomial(n, k)*fibonacci(k) Sm = Sum(sk, (k, 0, n)) T = Sm.doit() # Fibonacci simplification not implemented # https://github.com/sympy/sympy/issues/7134 assert T == fibonacci(2*n) @XFAIL def test_R12(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(fibonacci(k)**2, (k, 0, n)) T = Sm.doit() assert T == fibonacci(n)*fibonacci(n + 1) @XFAIL def test_R13(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(sin(k*x), (k, 1, n)) T = Sm.doit() # Sum is not calculated assert T.simplify() == cot(x/2)/2 - cos(x*(2*n + 1)/2)/(2*sin(x/2)) @XFAIL def test_R14(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(sin((2*k - 1)*x), (k, 1, n)) T = Sm.doit() # Sum is not calculated assert T.simplify() == sin(n*x)**2/sin(x) @XFAIL def test_R15(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(binomial(n - k, k), (k, 0, floor(n/2))) T = Sm.doit() # Sum is not calculated assert T.simplify() == fibonacci(n + 1) def test_R16(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/k**2 + 1/k**3, (k, 1, oo)) assert Sm.doit() == zeta(3) + pi**2/6 def test_R17(): k = symbols('k', integer=True, positive=True) assert abs(float(Sum(1/k**2 + 1/k**3, (k, 1, oo))) - 2.8469909700078206) < 1e-15 def test_R18(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/(2**k*k**2), (k, 1, oo)) T = Sm.doit() assert T.simplify() == -log(2)**2/2 + pi**2/12 @slow @XFAIL def test_R19(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/((3*k + 1)*(3*k + 2)*(3*k + 3)), (k, 0, oo)) T = Sm.doit() # assert fails, T not simplified assert T.simplify() == -log(3)/4 + sqrt(3)*pi/12 @XFAIL def test_R20(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(binomial(n, 4*k), (k, 0, oo)) T = Sm.doit() # assert fails, T not simplified assert T.simplify() == 2**(n/2)*cos(pi*n/4)/2 + 2**(n - 1)/2 @XFAIL def test_R21(): k = symbols('k', integer=True, positive=True) Sm = Sum(1/(sqrt(k*(k + 1)) * (sqrt(k) + sqrt(k + 1))), (k, 1, oo)) T = Sm.doit() # Sum not calculated assert T.simplify() == 1 # test_R22 answer not available in Wester samples # Sum(Sum(binomial(n, k)*binomial(n - k, n - 2*k)*x**n*y**(n - 2*k), # (k, 0, floor(n/2))), (n, 0, oo)) with abs(x*y)<1? @XFAIL def test_R23(): n, k = symbols('n k', integer=True, positive=True) Sm = Sum(Sum((factorial(n)/(factorial(k)**2*factorial(n - 2*k)))* (x/y)**k*(x*y)**(n - k), (n, 2*k, oo)), (k, 0, oo)) # Missing how to express constraint abs(x*y)<1? T = Sm.doit() # Sum not calculated assert T == -1/sqrt(x**2*y**2 - 4*x**2 - 2*x*y + 1) def test_R24(): m, k = symbols('m k', integer=True, positive=True) Sm = Sum(Product(k/(2*k - 1), (k, 1, m)), (m, 2, oo)) assert Sm.doit() == pi/2 def test_S1(): k = symbols('k', integer=True, positive=True) Pr = Product(gamma(k/3), (k, 1, 8)) assert Pr.doit().simplify() == 640*sqrt(3)*pi**3/6561 def test_S2(): n, k = symbols('n k', integer=True, positive=True) assert Product(k, (k, 1, n)).doit() == factorial(n) def test_S3(): n, k = symbols('n k', integer=True, positive=True) assert Product(x**k, (k, 1, n)).doit().simplify() == x**(n*(n + 1)/2) def test_S4(): n, k = symbols('n k', integer=True, positive=True) assert Product(1 + 1/k, (k, 1, n -1)).doit().simplify() == n def test_S5(): n, k = symbols('n k', integer=True, positive=True) assert (Product((2*k - 1)/(2*k), (k, 1, n)).doit().gammasimp() == gamma(n + S.Half)/(sqrt(pi)*gamma(n + 1))) @XFAIL def test_S6(): n, k = symbols('n k', integer=True, positive=True) # Product does not evaluate assert (Product(x**2 -2*x*cos(k*pi/n) + 1, (k, 1, n - 1)).doit().simplify() == (x**(2*n) - 1)/(x**2 - 1)) @XFAIL def test_S7(): k = symbols('k', integer=True, positive=True) Pr = Product((k**3 - 1)/(k**3 + 1), (k, 2, oo)) T = Pr.doit() # Product does not evaluate assert T.simplify() == R(2, 3) @XFAIL def test_S8(): k = symbols('k', integer=True, positive=True) Pr = Product(1 - 1/(2*k)**2, (k, 1, oo)) T = Pr.doit() # Product does not evaluate assert T.simplify() == 2/pi @XFAIL def test_S9(): k = symbols('k', integer=True, positive=True) Pr = Product(1 + (-1)**(k + 1)/(2*k - 1), (k, 1, oo)) T = Pr.doit() # Product produces 0 # https://github.com/sympy/sympy/issues/7133 assert T.simplify() == sqrt(2) @XFAIL def test_S10(): k = symbols('k', integer=True, positive=True) Pr = Product((k*(k + 1) + 1 + I)/(k*(k + 1) + 1 - I), (k, 0, oo)) T = Pr.doit() # Product does not evaluate assert T.simplify() == -1 def test_T1(): assert limit((1 + 1/n)**n, n, oo) == E assert limit((1 - cos(x))/x**2, x, 0) == S.Half def test_T2(): assert limit((3**x + 5**x)**(1/x), x, oo) == 5 def test_T3(): assert limit(log(x)/(log(x) + sin(x)), x, oo) == 1 def test_T4(): assert limit((exp(x*exp(-x)/(exp(-x) + exp(-2*x**2/(x + 1)))) - exp(x))/x, x, oo) == -exp(2) def test_T5(): assert limit(x*log(x)*log(x*exp(x) - x**2)**2/log(log(x**2 + 2*exp(exp(3*x**3*log(x))))), x, oo) == R(1, 3) def test_T6(): assert limit(1/n * factorial(n)**(1/n), n, oo) == exp(-1) def test_T7(): limit(1/n * gamma(n + 1)**(1/n), n, oo) def test_T8(): a, z = symbols('a z', positive=True) assert limit(gamma(z + a)/gamma(z)*exp(-a*log(z)), z, oo) == 1 @XFAIL def test_T9(): z, k = symbols('z k', positive=True) # raises NotImplementedError: # Don't know how to calculate the mrv of '(1, k)' assert limit(hyper((1, k), (1,), z/k), k, oo) == exp(z) @XFAIL def test_T10(): # No longer raises PoleError, but should return euler-mascheroni constant assert limit(zeta(x) - 1/(x - 1), x, 1) == integrate(-1/x + 1/floor(x), (x, 1, oo)) @XFAIL def test_T11(): n, k = symbols('n k', integer=True, positive=True) # evaluates to 0 assert limit(n**x/(x*product((1 + x/k), (k, 1, n))), n, oo) == gamma(x) def test_T12(): x, t = symbols('x t', real=True) # Does not evaluate the limit but returns an expression with erf assert limit(x * integrate(exp(-t**2), (t, 0, x))/(1 - exp(-x**2)), x, 0) == 1 def test_T13(): x = symbols('x', real=True) assert [limit(x/abs(x), x, 0, dir='-'), limit(x/abs(x), x, 0, dir='+')] == [-1, 1] def test_T14(): x = symbols('x', real=True) assert limit(atan(-log(x)), x, 0, dir='+') == pi/2 def test_U1(): x = symbols('x', real=True) assert diff(abs(x), x) == sign(x) def test_U2(): f = Lambda(x, Piecewise((-x, x < 0), (x, x >= 0))) assert diff(f(x), x) == Piecewise((-1, x < 0), (1, x >= 0)) def test_U3(): f = Lambda(x, Piecewise((x**2 - 1, x == 1), (x**3, x != 1))) f1 = Lambda(x, diff(f(x), x)) assert f1(x) == 3*x**2 assert f1(1) == 3 @XFAIL def test_U4(): n = symbols('n', integer=True, positive=True) x = symbols('x', real=True) d = diff(x**n, x, n) assert d.rewrite(factorial) == factorial(n) def test_U5(): # issue 6681 t = symbols('t') ans = ( Derivative(f(g(t)), g(t))*Derivative(g(t), (t, 2)) + Derivative(f(g(t)), (g(t), 2))*Derivative(g(t), t)**2) assert f(g(t)).diff(t, 2) == ans assert ans.doit() == ans def test_U6(): h = Function('h') T = integrate(f(y), (y, h(x), g(x))) assert T.diff(x) == ( f(g(x))*Derivative(g(x), x) - f(h(x))*Derivative(h(x), x)) @XFAIL def test_U7(): p, t = symbols('p t', real=True) # Exact differential => d(V(P, T)) => dV/dP DP + dV/dT DT # raises ValueError: Since there is more than one variable in the # expression, the variable(s) of differentiation must be supplied to # differentiate f(p,t) diff(f(p, t)) def test_U8(): x, y = symbols('x y', real=True) eq = cos(x*y) + x # If SymPy had implicit_diff() function this hack could be avoided # TODO: Replace solve with solveset, current test fails for solveset assert idiff(y - eq, y, x) == (-y*sin(x*y) + 1)/(x*sin(x*y) + 1) def test_U9(): # Wester sample case for Maple: # O29 := diff(f(x, y), x) + diff(f(x, y), y); # /d \ /d \ # |-- f(x, y)| + |-- f(x, y)| # \dx / \dy / # # O30 := factor(subs(f(x, y) = g(x^2 + y^2), %)); # 2 2 # 2 D(g)(x + y ) (x + y) x, y = symbols('x y', real=True) su = diff(f(x, y), x) + diff(f(x, y), y) s2 = su.subs(f(x, y), g(x**2 + y**2)) s3 = s2.doit().factor() # Subs not performed, s3 = 2*(x + y)*Subs(Derivative( # g(_xi_1), _xi_1), _xi_1, x**2 + y**2) # Derivative(g(x*2 + y**2), x**2 + y**2) is not valid in SymPy, # and probably will remain that way. You can take derivatives with respect # to other expressions only if they are atomic, like a symbol or a # function. # D operator should be added to SymPy # See https://github.com/sympy/sympy/issues/4719. assert s3 == (x + y)*Subs(Derivative(g(x), x), x, x**2 + y**2)*2 def test_U10(): # see issue 2519: assert residue((z**3 + 5)/((z**4 - 1)*(z + 1)), z, -1) == R(-9, 4) @XFAIL def test_U11(): # assert (2*dx + dz) ^ (3*dx + dy + dz) ^ (dx + dy + 4*dz) == 8*dx ^ dy ^dz raise NotImplementedError @XFAIL def test_U12(): # Wester sample case: # (c41) /* d(3 x^5 dy /\ dz + 5 x y^2 dz /\ dx + 8 z dx /\ dy) # => (15 x^4 + 10 x y + 8) dx /\ dy /\ dz */ # factor(ext_diff(3*x^5 * dy ~ dz + 5*x*y^2 * dz ~ dx + 8*z * dx ~ dy)); # 4 # (d41) (10 x y + 15 x + 8) dx dy dz raise NotImplementedError( "External diff of differential form not supported") def test_U13(): assert minimum(x**4 - x + 1, x) == -3*2**R(1,3)/8 + 1 @XFAIL def test_U14(): #f = 1/(x**2 + y**2 + 1) #assert [minimize(f), maximize(f)] == [0,1] raise NotImplementedError("minimize(), maximize() not supported") @XFAIL def test_U15(): raise NotImplementedError("minimize() not supported and also solve does \ not support multivariate inequalities") @XFAIL def test_U16(): raise NotImplementedError("minimize() not supported in SymPy and also \ solve does not support multivariate inequalities") @XFAIL def test_U17(): raise NotImplementedError("Linear programming, symbolic simplex not \ supported in SymPy") def test_V1(): x = symbols('x', real=True) assert integrate(abs(x), x) == Piecewise((-x**2/2, x <= 0), (x**2/2, True)) def test_V2(): assert integrate(Piecewise((-x, x < 0), (x, x >= 0)), x ) == Piecewise((-x**2/2, x < 0), (x**2/2, True)) def test_V3(): assert integrate(1/(x**3 + 2),x).diff().simplify() == 1/(x**3 + 2) def test_V4(): assert integrate(2**x/sqrt(1 + 4**x), x) == asinh(2**x)/log(2) @XFAIL def test_V5(): # Returns (-45*x**2 + 80*x - 41)/(5*sqrt(2*x - 1)*(4*x**2 - 4*x + 1)) assert (integrate((3*x - 5)**2/(2*x - 1)**R(7, 2), x).simplify() == (-41 + 80*x - 45*x**2)/(5*(2*x - 1)**R(5, 2))) @XFAIL def test_V6(): # returns RootSum(40*_z**2 - 1, Lambda(_i, _i*log(-4*_i + exp(-m*x))))/m assert (integrate(1/(2*exp(m*x) - 5*exp(-m*x)), x) == sqrt(10)*( log(2*exp(m*x) - sqrt(10)) - log(2*exp(m*x) + sqrt(10)))/(20*m)) def test_V7(): r1 = integrate(sinh(x)**4/cosh(x)**2) assert r1.simplify() == x*R(-3, 2) + sinh(x)**3/(2*cosh(x)) + 3*tanh(x)/2 @XFAIL def test_V8_V9(): #Macsyma test case: #(c27) /* This example involves several symbolic parameters # => 1/sqrt(b^2 - a^2) log([sqrt(b^2 - a^2) tan(x/2) + a + b]/ # [sqrt(b^2 - a^2) tan(x/2) - a - b]) (a^2 < b^2) # [Gradshteyn and Ryzhik 2.553(3)] */ #assume(b^2 > a^2)$ #(c28) integrate(1/(a + b*cos(x)), x); #(c29) trigsimp(ratsimp(diff(%, x))); # 1 #(d29) ------------ # b cos(x) + a raise NotImplementedError( "Integrate with assumption not supported") def test_V10(): assert integrate(1/(3 + 3*cos(x) + 4*sin(x)), x) == log(4*tan(x/2) + 3)/4 def test_V11(): r1 = integrate(1/(4 + 3*cos(x) + 4*sin(x)), x) r2 = factor(r1) assert (logcombine(r2, force=True) == log(((tan(x/2) + 1)/(tan(x/2) + 7))**R(1, 3))) def test_V12(): r1 = integrate(1/(5 + 3*cos(x) + 4*sin(x)), x) assert r1 == -1/(tan(x/2) + 2) @XFAIL def test_V13(): r1 = integrate(1/(6 + 3*cos(x) + 4*sin(x)), x) # expression not simplified, returns: -sqrt(11)*I*log(tan(x/2) + 4/3 # - sqrt(11)*I/3)/11 + sqrt(11)*I*log(tan(x/2) + 4/3 + sqrt(11)*I/3)/11 assert r1.simplify() == 2*sqrt(11)*atan(sqrt(11)*(3*tan(x/2) + 4)/11)/11 @slow @XFAIL def test_V14(): r1 = integrate(log(abs(x**2 - y**2)), x) # Piecewise result does not simplify to the desired result. assert (r1.simplify() == x*log(abs(x**2 - y**2)) + y*log(x + y) - y*log(x - y) - 2*x) def test_V15(): r1 = integrate(x*acot(x/y), x) assert simplify(r1 - (x*y + (x**2 + y**2)*acot(x/y))/2) == 0 @XFAIL def test_V16(): # Integral not calculated assert integrate(cos(5*x)*Ci(2*x), x) == Ci(2*x)*sin(5*x)/5 - (Si(3*x) + Si(7*x))/10 @XFAIL def test_V17(): r1 = integrate((diff(f(x), x)*g(x) - f(x)*diff(g(x), x))/(f(x)**2 - g(x)**2), x) # integral not calculated assert simplify(r1 - (f(x) - g(x))/(f(x) + g(x))/2) == 0 @XFAIL def test_W1(): # The function has a pole at y. # The integral has a Cauchy principal value of zero but SymPy returns -I*pi # https://github.com/sympy/sympy/issues/7159 assert integrate(1/(x - y), (x, y - 1, y + 1)) == 0 @XFAIL def test_W2(): # The function has a pole at y. # The integral is divergent but SymPy returns -2 # https://github.com/sympy/sympy/issues/7160 # Test case in Macsyma: # (c6) errcatch(integrate(1/(x - a)^2, x, a - 1, a + 1)); # Integral is divergent assert integrate(1/(x - y)**2, (x, y - 1, y + 1)) is zoo @XFAIL @slow def test_W3(): # integral is not calculated # https://github.com/sympy/sympy/issues/7161 assert integrate(sqrt(x + 1/x - 2), (x, 0, 1)) == R(4, 3) @XFAIL @slow def test_W4(): # integral is not calculated assert integrate(sqrt(x + 1/x - 2), (x, 1, 2)) == -2*sqrt(2)/3 + R(4, 3) @XFAIL @slow def test_W5(): # integral is not calculated assert integrate(sqrt(x + 1/x - 2), (x, 0, 2)) == -2*sqrt(2)/3 + R(8, 3) @XFAIL @slow def test_W6(): # integral is not calculated assert integrate(sqrt(2 - 2*cos(2*x))/2, (x, pi*R(-3, 4), -pi/4)) == sqrt(2) def test_W7(): a = symbols('a', positive=True) r1 = integrate(cos(x)/(x**2 + a**2), (x, -oo, oo)) assert r1.simplify() == pi*exp(-a)/a @XFAIL def test_W8(): # Test case in Mathematica: # In[19]:= Integrate[t^(a - 1)/(1 + t), {t, 0, Infinity}, # Assumptions -> 0 < a < 1] # Out[19]= Pi Csc[a Pi] raise NotImplementedError( "Integrate with assumption 0 < a < 1 not supported") @XFAIL @slow def test_W9(): # Integrand with a residue at infinity => -2 pi [sin(pi/5) + sin(2pi/5)] # (principal value) [Levinson and Redheffer, p. 234] *) r1 = integrate(5*x**3/(1 + x + x**2 + x**3 + x**4), (x, -oo, oo)) r2 = r1.doit() assert r2 == -2*pi*(sqrt(-sqrt(5)/8 + 5/8) + sqrt(sqrt(5)/8 + 5/8)) @XFAIL def test_W10(): # integrate(1/[1 + x + x^2 + ... + x^(2 n)], x = -infinity..infinity) = # 2 pi/(2 n + 1) [1 + cos(pi/[2 n + 1])] csc(2 pi/[2 n + 1]) # [Levinson and Redheffer, p. 255] => 2 pi/5 [1 + cos(pi/5)] csc(2 pi/5) */ r1 = integrate(x/(1 + x + x**2 + x**4), (x, -oo, oo)) r2 = r1.doit() assert r2 == 2*pi*(sqrt(5)/4 + 5/4)*csc(pi*R(2, 5))/5 @XFAIL def test_W11(): # integral not calculated assert (integrate(sqrt(1 - x**2)/(1 + x**2), (x, -1, 1)) == pi*(-1 + sqrt(2))) def test_W12(): p = symbols('p', positive=True) q = symbols('q', real=True) r1 = integrate(x*exp(-p*x**2 + 2*q*x), (x, -oo, oo)) assert r1.simplify() == sqrt(pi)*q*exp(q**2/p)/p**R(3, 2) @XFAIL def test_W13(): # Integral not calculated. Expected result is 2*(Euler_mascheroni_constant) r1 = integrate(1/log(x) + 1/(1 - x) - log(log(1/x)), (x, 0, 1)) assert r1 == 2*EulerGamma def test_W14(): assert integrate(sin(x)/x*exp(2*I*x), (x, -oo, oo)) == 0 @XFAIL def test_W15(): # integral not calculated assert integrate(log(gamma(x))*cos(6*pi*x), (x, 0, 1)) == R(1, 12) def test_W16(): assert integrate((1 + x)**3*legendre_poly(1, x)*legendre_poly(2, x), (x, -1, 1)) == R(36, 35) def test_W17(): a, b = symbols('a b', positive=True) assert integrate(exp(-a*x)*besselj(0, b*x), (x, 0, oo)) == 1/(b*sqrt(a**2/b**2 + 1)) def test_W18(): assert integrate((besselj(1, x)/x)**2, (x, 0, oo)) == 4/(3*pi) @XFAIL def test_W19(): # Integral not calculated # Expected result is (cos 7 - 1)/7 [Gradshteyn and Ryzhik 6.782(3)] assert integrate(Ci(x)*besselj(0, 2*sqrt(7*x)), (x, 0, oo)) == (cos(7) - 1)/7 @XFAIL def test_W20(): # integral not calculated assert (integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1)) == -pi**2/36 - R(17, 108) + zeta(3)/4 + (-pi**2/2 - 4*log(2) + log(2)**2 + 35/3)*log(2)/9) def test_W21(): assert abs(N(integrate(x**2*polylog(3, 1/(x + 1)), (x, 0, 1))) - 0.210882859565594) < 1e-15 def test_W22(): t, u = symbols('t u', real=True) s = Lambda(x, Piecewise((1, And(x >= 1, x <= 2)), (0, True))) assert integrate(s(t)*cos(t), (t, 0, u)) == Piecewise( (0, u < 0), (-sin(Min(1, u)) + sin(Min(2, u)), True)) @slow def test_W23(): a, b = symbols('a b', positive=True) r1 = integrate(integrate(x/(x**2 + y**2), (x, a, b)), (y, -oo, oo)) assert r1.collect(pi).cancel() == -pi*a + pi*b def test_W23b(): # like W23 but limits are reversed a, b = symbols('a b', positive=True) r2 = integrate(integrate(x/(x**2 + y**2), (y, -oo, oo)), (x, a, b)) assert r2.collect(pi) == pi*(-a + b) @XFAIL @slow def test_W24(): if ON_CI: skip("Too slow for CI.") # Not that slow, but does not fully evaluate so simplify is slow. # Maybe also require doit() x, y = symbols('x y', real=True) r1 = integrate(integrate(sqrt(x**2 + y**2), (x, 0, 1)), (y, 0, 1)) assert (r1 - (sqrt(2) + asinh(1))/3).simplify() == 0 @XFAIL @slow def test_W25(): if ON_CI: skip("Too slow for CI.") a, x, y = symbols('a x y', real=True) i1 = integrate( sin(a)*sin(y)/sqrt(1 - sin(a)**2*sin(x)**2*sin(y)**2), (x, 0, pi/2)) i2 = integrate(i1, (y, 0, pi/2)) assert (i2 - pi*a/2).simplify() == 0 def test_W26(): x, y = symbols('x y', real=True) assert integrate(integrate(abs(y - x**2), (y, 0, 2)), (x, -1, 1)) == R(46, 15) def test_W27(): a, b, c = symbols('a b c') assert integrate(integrate(integrate(1, (z, 0, c*(1 - x/a - y/b))), (y, 0, b*(1 - x/a))), (x, 0, a)) == a*b*c/6 def test_X1(): v, c = symbols('v c', real=True) assert (series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8) == 5*v**6/(16*c**6) + 3*v**4/(8*c**4) + v**2/(2*c**2) + 1 + O(v**8)) def test_X2(): v, c = symbols('v c', real=True) s1 = series(1/sqrt(1 - (v/c)**2), v, x0=0, n=8) assert (1/s1**2).series(v, x0=0, n=8) == -v**2/c**2 + 1 + O(v**8) def test_X3(): s1 = (sin(x).series()/cos(x).series()).series() s2 = tan(x).series() assert s2 == x + x**3/3 + 2*x**5/15 + O(x**6) assert s1 == s2 def test_X4(): s1 = log(sin(x)/x).series() assert s1 == -x**2/6 - x**4/180 + O(x**6) assert log(series(sin(x)/x)).series() == s1 @XFAIL def test_X5(): # test case in Mathematica syntax: # In[21]:= (* => [a f'(a d) + g(b d) + integrate(h(c y), y = 0..d)] # + [a^2 f''(a d) + b g'(b d) + h(c d)] (x - d) *) # In[22]:= D[f[a*x], x] + g[b*x] + Integrate[h[c*y], {y, 0, x}] # Out[22]= g[b x] + Integrate[h[c y], {y, 0, x}] + a f'[a x] # In[23]:= Series[%, {x, d, 1}] # Out[23]= (g[b d] + Integrate[h[c y], {y, 0, d}] + a f'[a d]) + # 2 2 # (h[c d] + b g'[b d] + a f''[a d]) (-d + x) + O[-d + x] h = Function('h') a, b, c, d = symbols('a b c d', real=True) # series() raises NotImplementedError: # The _eval_nseries method should be added to <class # 'sympy.core.function.Subs'> to give terms up to O(x**n) at x=0 series(diff(f(a*x), x) + g(b*x) + integrate(h(c*y), (y, 0, x)), x, x0=d, n=2) # assert missing, until exception is removed def test_X6(): # Taylor series of nonscalar objects (noncommutative multiplication) # expected result => (B A - A B) t^2/2 + O(t^3) [Stanly Steinberg] a, b = symbols('a b', commutative=False, scalar=False) assert (series(exp((a + b)*x) - exp(a*x) * exp(b*x), x, x0=0, n=3) == x**2*(-a*b/2 + b*a/2) + O(x**3)) def test_X7(): # => sum( Bernoulli[k]/k! x^(k - 2), k = 1..infinity ) # = 1/x^2 - 1/(2 x) + 1/12 - x^2/720 + x^4/30240 + O(x^6) # [Levinson and Redheffer, p. 173] assert (series(1/(x*(exp(x) - 1)), x, 0, 7) == x**(-2) - 1/(2*x) + R(1, 12) - x**2/720 + x**4/30240 - x**6/1209600 + O(x**7)) def test_X8(): # Puiseux series (terms with fractional degree): # => 1/sqrt(x - 3/2 pi) + (x - 3/2 pi)^(3/2) / 12 + O([x - 3/2 pi]^(7/2)) # see issue 7167: x = symbols('x', real=True) assert (series(sqrt(sec(x)), x, x0=pi*3/2, n=4) == 1/sqrt(x - pi*R(3, 2)) + (x - pi*R(3, 2))**R(3, 2)/12 + (x - pi*R(3, 2))**R(7, 2)/160 + O((x - pi*R(3, 2))**4, (x, pi*R(3, 2)))) def test_X9(): assert (series(x**x, x, x0=0, n=4) == 1 + x*log(x) + x**2*log(x)**2/2 + x**3*log(x)**3/6 + O(x**4*log(x)**4)) def test_X10(): z, w = symbols('z w') assert (series(log(sinh(z)) + log(cosh(z + w)), z, x0=0, n=2) == log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2)) def test_X11(): z, w = symbols('z w') assert (series(log(sinh(z) * cosh(z + w)), z, x0=0, n=2) == log(cosh(w)) + log(z) + z*sinh(w)/cosh(w) + O(z**2)) @XFAIL def test_X12(): # Look at the generalized Taylor series around x = 1 # Result => (x - 1)^a/e^b [1 - (a + 2 b) (x - 1) / 2 + O((x - 1)^2)] a, b, x = symbols('a b x', real=True) # series returns O(log(x-1)**2) # https://github.com/sympy/sympy/issues/7168 assert (series(log(x)**a*exp(-b*x), x, x0=1, n=2) == (x - 1)**a/exp(b)*(1 - (a + 2*b)*(x - 1)/2 + O((x - 1)**2))) def test_X13(): assert series(sqrt(2*x**2 + 1), x, x0=oo, n=1) == sqrt(2)*x + O(1/x, (x, oo)) @XFAIL def test_X14(): # Wallis' product => 1/sqrt(pi n) + ... [Knopp, p. 385] assert series(1/2**(2*n)*binomial(2*n, n), n, x==oo, n=1) == 1/(sqrt(pi)*sqrt(n)) + O(1/x, (x, oo)) @SKIP("https://github.com/sympy/sympy/issues/7164") def test_X15(): # => 0!/x - 1!/x^2 + 2!/x^3 - 3!/x^4 + O(1/x^5) [Knopp, p. 544] x, t = symbols('x t', real=True) # raises RuntimeError: maximum recursion depth exceeded # https://github.com/sympy/sympy/issues/7164 # 2019-02-17: Raises # PoleError: # Asymptotic expansion of Ei around [-oo] is not implemented. e1 = integrate(exp(-t)/t, (t, x, oo)) assert (series(e1, x, x0=oo, n=5) == 6/x**4 + 2/x**3 - 1/x**2 + 1/x + O(x**(-5), (x, oo))) def test_X16(): # Multivariate Taylor series expansion => 1 - (x^2 + 2 x y + y^2)/2 + O(x^4) assert (series(cos(x + y), x + y, x0=0, n=4) == 1 - (x + y)**2/2 + O(x**4 + x**3*y + x**2*y**2 + x*y**3 + y**4, x, y)) @XFAIL def test_X17(): # Power series (compute the general formula) # (c41) powerseries(log(sin(x)/x), x, 0); # /aquarius/data2/opt/local/macsyma_422/library1/trgred.so being loaded. # inf # ==== i1 2 i1 2 i1 # \ (- 1) 2 bern(2 i1) x # (d41) > ------------------------------ # / 2 i1 (2 i1)! # ==== # i1 = 1 # fps does not calculate assert fps(log(sin(x)/x)) == \ Sum((-1)**k*2**(2*k - 1)*bernoulli(2*k)*x**(2*k)/(k*factorial(2*k)), (k, 1, oo)) @XFAIL def test_X18(): # Power series (compute the general formula). Maple FPS: # > FormalPowerSeries(exp(-x)*sin(x), x = 0); # infinity # ----- (1/2 k) k # \ 2 sin(3/4 k Pi) x # ) ------------------------- # / k! # ----- # # Now, SymPy returns # oo # _____ # \ ` # \ / k k\ # \ k |I*(-1 - I) I*(-1 + I) | # \ x *|----------- - -----------| # / \ 2 2 / # / ------------------------------ # / k! # /____, # k = 0 k = Dummy('k') assert fps(exp(-x)*sin(x)) == \ Sum(2**(S.Half*k)*sin(R(3, 4)*k*pi)*x**k/factorial(k), (k, 0, oo)) @XFAIL def test_X19(): # (c45) /* Derive an explicit Taylor series solution of y as a function of # x from the following implicit relation: # y = x - 1 + (x - 1)^2/2 + 2/3 (x - 1)^3 + (x - 1)^4 + # 17/10 (x - 1)^5 + ... # */ # x = sin(y) + cos(y); # Time= 0 msecs # (d45) x = sin(y) + cos(y) # # (c46) taylor_revert(%, y, 7); raise NotImplementedError("Solve using series not supported. \ Inverse Taylor series expansion also not supported") @XFAIL def test_X20(): # Pade (rational function) approximation => (2 - x)/(2 + x) # > numapprox[pade](exp(-x), x = 0, [1, 1]); # bytes used=9019816, alloc=3669344, time=13.12 # 1 - 1/2 x # --------- # 1 + 1/2 x # mpmath support numeric Pade approximant but there is # no symbolic implementation in SymPy # https://en.wikipedia.org/wiki/Pad%C3%A9_approximant raise NotImplementedError("Symbolic Pade approximant not supported") def test_X21(): """ Test whether `fourier_series` of x periodical on the [-p, p] interval equals `- (2 p / pi) sum( (-1)^n / n sin(n pi x / p), n = 1..infinity )`. """ p = symbols('p', positive=True) n = symbols('n', positive=True, integer=True) s = fourier_series(x, (x, -p, p)) # All cosine coefficients are equal to 0 assert s.an.formula == 0 # Check for sine coefficients assert s.bn.formula.subs(s.bn.variables[0], 0) == 0 assert s.bn.formula.subs(s.bn.variables[0], n) == \ -2*p/pi * (-1)**n / n * sin(n*pi*x/p) @XFAIL def test_X22(): # (c52) /* => p / 2 # - (2 p / pi^2) sum( [1 - (-1)^n] cos(n pi x / p) / n^2, # n = 1..infinity ) */ # fourier_series(abs(x), x, p); # p # (e52) a = - # 0 2 # # %nn # (2 (- 1) - 2) p # (e53) a = ------------------ # %nn 2 2 # %pi %nn # # (e54) b = 0 # %nn # # Time= 5290 msecs # inf %nn %pi %nn x # ==== (2 (- 1) - 2) cos(---------) # \ p # p > ------------------------------- # / 2 # ==== %nn # %nn = 1 p # (d54) ----------------------------------------- + - # 2 2 # %pi raise NotImplementedError("Fourier series not supported") def test_Y1(): t = symbols('t', positive=True) w = symbols('w', real=True) s = symbols('s') F, _, _ = laplace_transform(cos((w - 1)*t), t, s) assert F == s/(s**2 + (w - 1)**2) def test_Y2(): t = symbols('t', positive=True) w = symbols('w', real=True) s = symbols('s') f = inverse_laplace_transform(s/(s**2 + (w - 1)**2), s, t) assert f == cos(t*(w - 1)) def test_Y3(): t = symbols('t', positive=True) w = symbols('w', real=True) s = symbols('s') F, _, _ = laplace_transform(sinh(w*t)*cosh(w*t), t, s, simplify=True) assert F == w/(s**2 - 4*w**2) def test_Y4(): t = symbols('t', positive=True) s = symbols('s') F, _, _ = laplace_transform(erf(3/sqrt(t)), t, s, simplify=True) assert F == 1/s - exp(-6*sqrt(s))/s def test_Y5_Y6(): # Solve y'' + y = 4 [H(t - 1) - H(t - 2)], y(0) = 1, y'(0) = 0 where H is the # Heaviside (unit step) function (the RHS describes a pulse of magnitude 4 and # duration 1). See David A. Sanchez, Richard C. Allen, Jr. and Walter T. # Kyner, _Differential Equations: An Introduction_, Addison-Wesley Publishing # Company, 1983, p. 211. First, take the Laplace transform of the ODE # => s^2 Y(s) - s + Y(s) = 4/s [e^(-s) - e^(-2 s)] # where Y(s) is the Laplace transform of y(t) t = symbols('t', positive=True) s = symbols('s') y = Function('y') F, _, _ = laplace_transform(diff(y(t), t, 2) + y(t) - 4*(Heaviside(t - 1) - Heaviside(t - 2)), t, s, simplify=True) D = (F - (s**2*LaplaceTransform(y(t), t, s) - s*y(0) + LaplaceTransform(y(t), t, s) - Subs(Derivative(y(t), t), t, 0) + 4*(1 - exp(s))*exp(-2*s)/s)).simplify(doit=False) assert D == 0 # TODO implement second part of test case # Now, solve for Y(s) and then take the inverse Laplace transform # => Y(s) = s/(s^2 + 1) + 4 [1/s - s/(s^2 + 1)] [e^(-s) - e^(-2 s)] # => y(t) = cos t + 4 {[1 - cos(t - 1)] H(t - 1) - [1 - cos(t - 2)] H(t - 2)} @XFAIL def test_Y7(): # What is the Laplace transform of an infinite square wave? # => 1/s + 2 sum( (-1)^n e^(- s n a)/s, n = 1..infinity ) # [Sanchez, Allen and Kyner, p. 213] t = symbols('t', positive=True) a = symbols('a', real=True) s = symbols('s') F, _, _ = laplace_transform(1 + 2*Sum((-1)**n*Heaviside(t - n*a), (n, 1, oo)), t, s) # returns 2*LaplaceTransform(Sum((-1)**n*Heaviside(-a*n + t), # (n, 1, oo)), t, s) + 1/s # https://github.com/sympy/sympy/issues/7177 assert F == 2*Sum((-1)**n*exp(-a*n*s)/s, (n, 1, oo)) + 1/s @XFAIL def test_Y8(): assert fourier_transform(1, x, z) == DiracDelta(z) def test_Y9(): assert (fourier_transform(exp(-9*x**2), x, z) == sqrt(pi)*exp(-pi**2*z**2/9)/3) def test_Y10(): assert (fourier_transform(abs(x)*exp(-3*abs(x)), x, z).cancel() == (-8*pi**2*z**2 + 18)/(16*pi**4*z**4 + 72*pi**2*z**2 + 81)) @SKIP("https://github.com/sympy/sympy/issues/7181") @slow def test_Y11(): # => pi cot(pi s) (0 < Re s < 1) [Gradshteyn and Ryzhik 17.43(5)] x, s = symbols('x s') # raises RuntimeError: maximum recursion depth exceeded # https://github.com/sympy/sympy/issues/7181 # Update 2019-02-17 raises: # TypeError: cannot unpack non-iterable MellinTransform object F, _, _ = mellin_transform(1/(1 - x), x, s) assert F == pi*cot(pi*s) @XFAIL def test_Y12(): # => 2^(s - 4) gamma(s/2)/gamma(4 - s/2) (0 < Re s < 1) # [Gradshteyn and Ryzhik 17.43(16)] x, s = symbols('x s') # returns Wrong value -2**(s - 4)*gamma(s/2 - 3)/gamma(-s/2 + 1) # https://github.com/sympy/sympy/issues/7182 F, _, _ = mellin_transform(besselj(3, x)/x**3, x, s) assert F == -2**(s - 4)*gamma(s/2)/gamma(-s/2 + 4) @XFAIL def test_Y13(): # Z[H(t - m T)] => z/[z^m (z - 1)] (H is the Heaviside (unit step) function) z raise NotImplementedError("z-transform not supported") @XFAIL def test_Y14(): # Z[H(t - m T)] => z/[z^m (z - 1)] (H is the Heaviside (unit step) function) raise NotImplementedError("z-transform not supported") def test_Z1(): r = Function('r') assert (rsolve(r(n + 2) - 2*r(n + 1) + r(n) - 2, r(n), {r(0): 1, r(1): m}).simplify() == n**2 + n*(m - 2) + 1) def test_Z2(): r = Function('r') assert (rsolve(r(n) - (5*r(n - 1) - 6*r(n - 2)), r(n), {r(0): 0, r(1): 1}) == -2**n + 3**n) def test_Z3(): # => r(n) = Fibonacci[n + 1] [Cohen, p. 83] r = Function('r') # recurrence solution is correct, Wester expects it to be simplified to # fibonacci(n+1), but that is quite hard expected = ((S(1)/2 - sqrt(5)/2)**n*(S(1)/2 - sqrt(5)/10) + (S(1)/2 + sqrt(5)/2)**n*(sqrt(5)/10 + S(1)/2)) sol = rsolve(r(n) - (r(n - 1) + r(n - 2)), r(n), {r(1): 1, r(2): 2}) assert sol == expected @XFAIL def test_Z4(): # => [c^(n+1) [c^(n+1) - 2 c - 2] + (n+1) c^2 + 2 c - n] / [(c-1)^3 (c+1)] # [Joan Z. Yu and Robert Israel in sci.math.symbolic] r = Function('r') c = symbols('c') # raises ValueError: Polynomial or rational function expected, # got '(c**2 - c**n)/(c - c**n) s = rsolve(r(n) - ((1 + c - c**(n-1) - c**(n+1))/(1 - c**n)*r(n - 1) - c*(1 - c**(n-2))/(1 - c**(n-1))*r(n - 2) + 1), r(n), {r(1): 1, r(2): (2 + 2*c + c**2)/(1 + c)}) assert (s - (c*(n + 1)*(c*(n + 1) - 2*c - 2) + (n + 1)*c**2 + 2*c - n)/((c-1)**3*(c+1)) == 0) @XFAIL def test_Z5(): # Second order ODE with initial conditions---solve directly # transform: f(t) = sin(2 t)/8 - t cos(2 t)/4 C1, C2 = symbols('C1 C2') # initial conditions not supported, this is a manual workaround # https://github.com/sympy/sympy/issues/4720 eq = Derivative(f(x), x, 2) + 4*f(x) - sin(2*x) sol = dsolve(eq, f(x)) f0 = Lambda(x, sol.rhs) assert f0(x) == C2*sin(2*x) + (C1 - x/4)*cos(2*x) f1 = Lambda(x, diff(f0(x), x)) # TODO: Replace solve with solveset, when it works for solveset const_dict = solve((f0(0), f1(0))) result = f0(x).subs(C1, const_dict[C1]).subs(C2, const_dict[C2]) assert result == -x*cos(2*x)/4 + sin(2*x)/8 # Result is OK, but ODE solving with initial conditions should be # supported without all this manual work raise NotImplementedError('ODE solving with initial conditions \ not supported') @XFAIL def test_Z6(): # Second order ODE with initial conditions---solve using Laplace # transform: f(t) = sin(2 t)/8 - t cos(2 t)/4 t = symbols('t', positive=True) s = symbols('s') eq = Derivative(f(t), t, 2) + 4*f(t) - sin(2*t) F, _, _ = laplace_transform(eq, t, s) # Laplace transform for diff() not calculated # https://github.com/sympy/sympy/issues/7176 assert (F == s**2*LaplaceTransform(f(t), t, s) + 4*LaplaceTransform(f(t), t, s) - 2/(s**2 + 4)) # rest of test case not implemented
c2a2f9beabf4799c81aa15f96e6a9d0dfc9754758b58d802c31d81a42d897ad2
from sympy.integrals.transforms import (mellin_transform, inverse_mellin_transform, laplace_transform, inverse_laplace_transform, fourier_transform, inverse_fourier_transform, sine_transform, inverse_sine_transform, cosine_transform, inverse_cosine_transform, hankel_transform, inverse_hankel_transform, LaplaceTransform, FourierTransform, SineTransform, CosineTransform, InverseLaplaceTransform, InverseFourierTransform, InverseSineTransform, InverseCosineTransform, IntegralTransformError) from sympy.core.function import (Function, expand_mul) from sympy.core import EulerGamma, Subs, Derivative, diff from sympy.core.numbers import (I, Rational, oo, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import (Abs, re, unpolarify) from sympy.functions.elementary.exponential import (exp, exp_polar, log) from sympy.functions.elementary.hyperbolic import (cosh, sinh, coth, asinh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (atan, atan2, cos, sin, tan) from sympy.functions.special.bessel import (besseli, besselj, besselk, bessely) from sympy.functions.special.delta_functions import Heaviside from sympy.functions.special.error_functions import (erf, erfc, expint, Ei) from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import meijerg from sympy.simplify.gammasimp import gammasimp from sympy.simplify.hyperexpand import hyperexpand from sympy.simplify.trigsimp import trigsimp from sympy.testing.pytest import XFAIL, slow, skip, raises, warns_deprecated_sympy from sympy.matrices import Matrix, eye from sympy.abc import x, s, a, b, c, d nu, beta, rho = symbols('nu beta rho') def test_undefined_function(): from sympy.integrals.transforms import MellinTransform f = Function('f') assert mellin_transform(f(x), x, s) == MellinTransform(f(x), x, s) assert mellin_transform(f(x) + exp(-x), x, s) == \ (MellinTransform(f(x), x, s) + gamma(s + 1)/s, (0, oo), True) def test_free_symbols(): f = Function('f') assert mellin_transform(f(x), x, s).free_symbols == {s} assert mellin_transform(f(x)*a, x, s).free_symbols == {s, a} def test_as_integral(): from sympy.integrals.integrals import Integral f = Function('f') assert mellin_transform(f(x), x, s).rewrite('Integral') == \ Integral(x**(s - 1)*f(x), (x, 0, oo)) assert fourier_transform(f(x), x, s).rewrite('Integral') == \ Integral(f(x)*exp(-2*I*pi*s*x), (x, -oo, oo)) assert laplace_transform(f(x), x, s, noconds=True).rewrite('Integral') == \ Integral(f(x)*exp(-s*x), (x, 0, oo)) assert str(2*pi*I*inverse_mellin_transform(f(s), s, x, (a, b)).rewrite('Integral')) \ == "Integral(f(s)/x**s, (s, _c - oo*I, _c + oo*I))" assert str(2*pi*I*inverse_laplace_transform(f(s), s, x).rewrite('Integral')) == \ "Integral(f(s)*exp(s*x), (s, _c - oo*I, _c + oo*I))" assert inverse_fourier_transform(f(s), s, x).rewrite('Integral') == \ Integral(f(s)*exp(2*I*pi*s*x), (s, -oo, oo)) # NOTE this is stuck in risch because meijerint cannot handle it @slow @XFAIL def test_mellin_transform_fail(): skip("Risch takes forever.") MT = mellin_transform bpos = symbols('b', positive=True) # bneg = symbols('b', negative=True) expr = (sqrt(x + b**2) + b)**a/sqrt(x + b**2) # TODO does not work with bneg, argument wrong. Needs changes to matching. assert MT(expr.subs(b, -bpos), x, s) == \ ((-1)**(a + 1)*2**(a + 2*s)*bpos**(a + 2*s - 1)*gamma(a + s) *gamma(1 - a - 2*s)/gamma(1 - s), (-re(a), -re(a)/2 + S.Half), True) expr = (sqrt(x + b**2) + b)**a assert MT(expr.subs(b, -bpos), x, s) == \ ( 2**(a + 2*s)*a*bpos**(a + 2*s)*gamma(-a - 2* s)*gamma(a + s)/gamma(-s + 1), (-re(a), -re(a)/2), True) # Test exponent 1: assert MT(expr.subs({b: -bpos, a: 1}), x, s) == \ (-bpos**(2*s + 1)*gamma(s)*gamma(-s - S.Half)/(2*sqrt(pi)), (-1, Rational(-1, 2)), True) def test_mellin_transform(): from sympy.functions.elementary.miscellaneous import (Max, Min) MT = mellin_transform bpos = symbols('b', positive=True) # 8.4.2 assert MT(x**nu*Heaviside(x - 1), x, s) == \ (-1/(nu + s), (-oo, -re(nu)), True) assert MT(x**nu*Heaviside(1 - x), x, s) == \ (1/(nu + s), (-re(nu), oo), True) assert MT((1 - x)**(beta - 1)*Heaviside(1 - x), x, s) == \ (gamma(beta)*gamma(s)/gamma(beta + s), (0, oo), re(beta) > 0) assert MT((x - 1)**(beta - 1)*Heaviside(x - 1), x, s) == \ (gamma(beta)*gamma(1 - beta - s)/gamma(1 - s), (-oo, 1 - re(beta)), re(beta) > 0) assert MT((1 + x)**(-rho), x, s) == \ (gamma(s)*gamma(rho - s)/gamma(rho), (0, re(rho)), True) assert MT(abs(1 - x)**(-rho), x, s) == ( 2*sin(pi*rho/2)*gamma(1 - rho)* cos(pi*(s - rho/2))*gamma(s)*gamma(rho-s)/pi, (0, re(rho)), re(rho) < 1) mt = MT((1 - x)**(beta - 1)*Heaviside(1 - x) + a*(x - 1)**(beta - 1)*Heaviside(x - 1), x, s) assert mt[1], mt[2] == ((0, -re(beta) + 1), re(beta) > 0) assert MT((x**a - b**a)/(x - b), x, s)[0] == \ pi*b**(a + s - 1)*sin(pi*a)/(sin(pi*s)*sin(pi*(a + s))) assert MT((x**a - bpos**a)/(x - bpos), x, s) == \ (pi*bpos**(a + s - 1)*sin(pi*a)/(sin(pi*s)*sin(pi*(a + s))), (Max(0, -re(a)), Min(1, 1 - re(a))), True) expr = (sqrt(x + b**2) + b)**a assert MT(expr.subs(b, bpos), x, s) == \ (-a*(2*bpos)**(a + 2*s)*gamma(s)*gamma(-a - 2*s)/gamma(-a - s + 1), (0, -re(a)/2), True) expr = (sqrt(x + b**2) + b)**a/sqrt(x + b**2) assert MT(expr.subs(b, bpos), x, s) == \ (2**(a + 2*s)*bpos**(a + 2*s - 1)*gamma(s) *gamma(1 - a - 2*s)/gamma(1 - a - s), (0, -re(a)/2 + S.Half), True) # 8.4.2 assert MT(exp(-x), x, s) == (gamma(s), (0, oo), True) assert MT(exp(-1/x), x, s) == (gamma(-s), (-oo, 0), True) # 8.4.5 assert MT(log(x)**4*Heaviside(1 - x), x, s) == (24/s**5, (0, oo), True) assert MT(log(x)**3*Heaviside(x - 1), x, s) == (6/s**4, (-oo, 0), True) assert MT(log(x + 1), x, s) == (pi/(s*sin(pi*s)), (-1, 0), True) assert MT(log(1/x + 1), x, s) == (pi/(s*sin(pi*s)), (0, 1), True) assert MT(log(abs(1 - x)), x, s) == (pi/(s*tan(pi*s)), (-1, 0), True) assert MT(log(abs(1 - 1/x)), x, s) == (pi/(s*tan(pi*s)), (0, 1), True) # 8.4.14 assert MT(erf(sqrt(x)), x, s) == \ (-gamma(s + S.Half)/(sqrt(pi)*s), (Rational(-1, 2), 0), True) def test_mellin_transform2(): MT = mellin_transform # TODO we cannot currently do these (needs summation of 3F2(-1)) # this also implies that they cannot be written as a single g-function # (although this is possible) mt = MT(log(x)/(x + 1), x, s) assert mt[1:] == ((0, 1), True) assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg) mt = MT(log(x)**2/(x + 1), x, s) assert mt[1:] == ((0, 1), True) assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg) mt = MT(log(x)/(x + 1)**2, x, s) assert mt[1:] == ((0, 2), True) assert not hyperexpand(mt[0], allow_hyper=True).has(meijerg) @slow def test_mellin_transform_bessel(): from sympy.functions.elementary.miscellaneous import Max MT = mellin_transform # 8.4.19 assert MT(besselj(a, 2*sqrt(x)), x, s) == \ (gamma(a/2 + s)/gamma(a/2 - s + 1), (-re(a)/2, Rational(3, 4)), True) assert MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s) == \ (2**a*gamma(-2*s + S.Half)*gamma(a/2 + s + S.Half)/( gamma(-a/2 - s + 1)*gamma(a - 2*s + 1)), ( -re(a)/2 - S.Half, Rational(1, 4)), True) assert MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s) == \ (2**a*gamma(a/2 + s)*gamma(-2*s + S.Half)/( gamma(-a/2 - s + S.Half)*gamma(a - 2*s + 1)), ( -re(a)/2, Rational(1, 4)), True) assert MT(besselj(a, sqrt(x))**2, x, s) == \ (gamma(a + s)*gamma(S.Half - s) / (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)), (-re(a), S.Half), True) assert MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s) == \ (gamma(s)*gamma(S.Half - s) / (sqrt(pi)*gamma(1 - a - s)*gamma(1 + a - s)), (0, S.Half), True) # NOTE: prudnikov gives the strip below as (1/2 - re(a), 1). As far as # I can see this is wrong (since besselj(z) ~ 1/sqrt(z) for z large) assert MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s) == \ (gamma(1 - s)*gamma(a + s - S.Half) / (sqrt(pi)*gamma(Rational(3, 2) - s)*gamma(a - s + S.Half)), (S.Half - re(a), S.Half), True) assert MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s) == \ (4**s*gamma(1 - 2*s)*gamma((a + b)/2 + s) / (gamma(1 - s + (b - a)/2)*gamma(1 - s + (a - b)/2) *gamma( 1 - s + (a + b)/2)), (-(re(a) + re(b))/2, S.Half), True) assert MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)[1:] == \ ((Max(re(a), -re(a)), S.Half), True) # Section 8.4.20 assert MT(bessely(a, 2*sqrt(x)), x, s) == \ (-cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)/pi, (Max(-re(a)/2, re(a)/2), Rational(3, 4)), True) assert MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s) == \ (-4**s*sin(pi*(a/2 - s))*gamma(S.Half - 2*s) * gamma((1 - a)/2 + s)*gamma((1 + a)/2 + s) / (sqrt(pi)*gamma(1 - s - a/2)*gamma(1 - s + a/2)), (Max(-(re(a) + 1)/2, (re(a) - 1)/2), Rational(1, 4)), True) assert MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s) == \ (-4**s*cos(pi*(a/2 - s))*gamma(s - a/2)*gamma(s + a/2)*gamma(S.Half - 2*s) / (sqrt(pi)*gamma(S.Half - s - a/2)*gamma(S.Half - s + a/2)), (Max(-re(a)/2, re(a)/2), Rational(1, 4)), True) assert MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s) == \ (-cos(pi*s)*gamma(s)*gamma(a + s)*gamma(S.Half - s) / (pi**S('3/2')*gamma(1 + a - s)), (Max(-re(a), 0), S.Half), True) assert MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s) == \ (-4**s*cos(pi*(a/2 - b/2 + s))*gamma(1 - 2*s) * gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s) / (pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)), (Max((-re(a) + re(b))/2, (-re(a) - re(b))/2), S.Half), True) # NOTE bessely(a, sqrt(x))**2 and bessely(a, sqrt(x))*bessely(b, sqrt(x)) # are a mess (no matter what way you look at it ...) assert MT(bessely(a, sqrt(x))**2, x, s)[1:] == \ ((Max(-re(a), 0, re(a)), S.Half), True) # Section 8.4.22 # TODO we can't do any of these (delicate cancellation) # Section 8.4.23 assert MT(besselk(a, 2*sqrt(x)), x, s) == \ (gamma( s - a/2)*gamma(s + a/2)/2, (Max(-re(a)/2, re(a)/2), oo), True) assert MT(besselj(a, 2*sqrt(2*sqrt(x)))*besselk( a, 2*sqrt(2*sqrt(x))), x, s) == (4**(-s)*gamma(2*s)* gamma(a/2 + s)/(2*gamma(a/2 - s + 1)), (Max(0, -re(a)/2), oo), True) # TODO bessely(a, x)*besselk(a, x) is a mess assert MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s) == \ (gamma(s)*gamma( a + s)*gamma(-s + S.Half)/(2*sqrt(pi)*gamma(a - s + 1)), (Max(-re(a), 0), S.Half), True) assert MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s) == \ (2**(2*s - 1)*gamma(-2*s + 1)*gamma(-a/2 + b/2 + s)* \ gamma(a/2 + b/2 + s)/(gamma(-a/2 + b/2 - s + 1)* \ gamma(a/2 + b/2 - s + 1)), (Max(-re(a)/2 - re(b)/2, \ re(a)/2 - re(b)/2), S.Half), True) # TODO products of besselk are a mess mt = MT(exp(-x/2)*besselk(a, x/2), x, s) mt0 = gammasimp(trigsimp(gammasimp(mt[0].expand(func=True)))) assert mt0 == 2*pi**Rational(3, 2)*cos(pi*s)*gamma(S.Half - s)/( (cos(2*pi*a) - cos(2*pi*s))*gamma(-a - s + 1)*gamma(a - s + 1)) assert mt[1:] == ((Max(-re(a), re(a)), oo), True) # TODO exp(x/2)*besselk(a, x/2) [etc] cannot currently be done # TODO various strange products of special orders @slow def test_expint(): from sympy.functions.elementary.miscellaneous import Max from sympy.functions.special.error_functions import (Ci, E1, Ei, Si) from sympy.functions.special.zeta_functions import lerchphi from sympy.simplify.simplify import simplify aneg = Symbol('a', negative=True) u = Symbol('u', polar=True) assert mellin_transform(E1(x), x, s) == (gamma(s)/s, (0, oo), True) assert inverse_mellin_transform(gamma(s)/s, s, x, (0, oo)).rewrite(expint).expand() == E1(x) assert mellin_transform(expint(a, x), x, s) == \ (gamma(s)/(a + s - 1), (Max(1 - re(a), 0), oo), True) # XXX IMT has hickups with complicated strips ... assert simplify(unpolarify( inverse_mellin_transform(gamma(s)/(aneg + s - 1), s, x, (1 - aneg, oo)).rewrite(expint).expand(func=True))) == \ expint(aneg, x) assert mellin_transform(Si(x), x, s) == \ (-2**s*sqrt(pi)*gamma(s/2 + S.Half)/( 2*s*gamma(-s/2 + 1)), (-1, 0), True) assert inverse_mellin_transform(-2**s*sqrt(pi)*gamma((s + 1)/2) /(2*s*gamma(-s/2 + 1)), s, x, (-1, 0)) \ == Si(x) assert mellin_transform(Ci(sqrt(x)), x, s) == \ (-2**(2*s - 1)*sqrt(pi)*gamma(s)/(s*gamma(-s + S.Half)), (0, 1), True) assert inverse_mellin_transform( -4**s*sqrt(pi)*gamma(s)/(2*s*gamma(-s + S.Half)), s, u, (0, 1)).expand() == Ci(sqrt(u)) # TODO LT of Si, Shi, Chi is a mess ... assert laplace_transform(Ci(x), x, s) == (-log(1 + s**2)/2/s, 0, True) assert laplace_transform(expint(a, x), x, s, simplify=True) == \ (lerchphi(s*exp_polar(I*pi), 1, a), 0, re(a) > S.Zero) assert laplace_transform(expint(1, x), x, s, simplify=True) == \ (log(s + 1)/s, 0, True) assert laplace_transform(expint(2, x), x, s, simplify=True) == \ ((s - log(s + 1))/s**2, 0, True) assert inverse_laplace_transform(-log(1 + s**2)/2/s, s, u).expand() == \ Heaviside(u)*Ci(u) assert inverse_laplace_transform(log(s + 1)/s, s, x).rewrite(expint) == \ Heaviside(x)*E1(x) assert inverse_laplace_transform((s - log(s + 1))/s**2, s, x).rewrite(expint).expand() == \ (expint(2, x)*Heaviside(x)).rewrite(Ei).rewrite(expint).expand() @slow def test_inverse_mellin_transform(): from sympy.core.function import expand from sympy.functions.elementary.miscellaneous import (Max, Min) from sympy.functions.elementary.trigonometric import cot from sympy.simplify.powsimp import powsimp from sympy.simplify.simplify import simplify IMT = inverse_mellin_transform assert IMT(gamma(s), s, x, (0, oo)) == exp(-x) assert IMT(gamma(-s), s, x, (-oo, 0)) == exp(-1/x) assert simplify(IMT(s/(2*s**2 - 2), s, x, (2, oo))) == \ (x**2 + 1)*Heaviside(1 - x)/(4*x) # test passing "None" assert IMT(1/(s**2 - 1), s, x, (-1, None)) == \ -x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x) assert IMT(1/(s**2 - 1), s, x, (None, 1)) == \ -x*Heaviside(-x + 1)/2 - Heaviside(x - 1)/(2*x) # test expansion of sums assert IMT(gamma(s) + gamma(s - 1), s, x, (1, oo)) == (x + 1)*exp(-x)/x # test factorisation of polys r = symbols('r', real=True) assert IMT(1/(s**2 + 1), s, exp(-x), (None, oo) ).subs(x, r).rewrite(sin).simplify() \ == sin(r)*Heaviside(1 - exp(-r)) # test multiplicative substitution _a, _b = symbols('a b', positive=True) assert IMT(_b**(-s/_a)*factorial(s/_a)/s, s, x, (0, oo)) == exp(-_b*x**_a) assert IMT(factorial(_a/_b + s/_b)/(_a + s), s, x, (-_a, oo)) == x**_a*exp(-x**_b) def simp_pows(expr): return simplify(powsimp(expand_mul(expr, deep=False), force=True)).replace(exp_polar, exp) # Now test the inverses of all direct transforms tested above # Section 8.4.2 nu = symbols('nu', real=True) assert IMT(-1/(nu + s), s, x, (-oo, None)) == x**nu*Heaviside(x - 1) assert IMT(1/(nu + s), s, x, (None, oo)) == x**nu*Heaviside(1 - x) assert simp_pows(IMT(gamma(beta)*gamma(s)/gamma(s + beta), s, x, (0, oo))) \ == (1 - x)**(beta - 1)*Heaviside(1 - x) assert simp_pows(IMT(gamma(beta)*gamma(1 - beta - s)/gamma(1 - s), s, x, (-oo, None))) \ == (x - 1)**(beta - 1)*Heaviside(x - 1) assert simp_pows(IMT(gamma(s)*gamma(rho - s)/gamma(rho), s, x, (0, None))) \ == (1/(x + 1))**rho assert simp_pows(IMT(d**c*d**(s - 1)*sin(pi*c) *gamma(s)*gamma(s + c)*gamma(1 - s)*gamma(1 - s - c)/pi, s, x, (Max(-re(c), 0), Min(1 - re(c), 1)))) \ == (x**c - d**c)/(x - d) assert simplify(IMT(1/sqrt(pi)*(-c/2)*gamma(s)*gamma((1 - c)/2 - s) *gamma(-c/2 - s)/gamma(1 - c - s), s, x, (0, -re(c)/2))) == \ (1 + sqrt(x + 1))**c assert simplify(IMT(2**(a + 2*s)*b**(a + 2*s - 1)*gamma(s)*gamma(1 - a - 2*s) /gamma(1 - a - s), s, x, (0, (-re(a) + 1)/2))) == \ b**(a - 1)*(b**2*(sqrt(1 + x/b**2) + 1)**a + x*(sqrt(1 + x/b**2) + 1 )**(a - 1))/(b**2 + x) assert simplify(IMT(-2**(c + 2*s)*c*b**(c + 2*s)*gamma(s)*gamma(-c - 2*s) / gamma(-c - s + 1), s, x, (0, -re(c)/2))) == \ b**c*(sqrt(1 + x/b**2) + 1)**c # Section 8.4.5 assert IMT(24/s**5, s, x, (0, oo)) == log(x)**4*Heaviside(1 - x) assert expand(IMT(6/s**4, s, x, (-oo, 0)), force=True) == \ log(x)**3*Heaviside(x - 1) assert IMT(pi/(s*sin(pi*s)), s, x, (-1, 0)) == log(x + 1) assert IMT(pi/(s*sin(pi*s/2)), s, x, (-2, 0)) == log(x**2 + 1) assert IMT(pi/(s*sin(2*pi*s)), s, x, (Rational(-1, 2), 0)) == log(sqrt(x) + 1) assert IMT(pi/(s*sin(pi*s)), s, x, (0, 1)) == log(1 + 1/x) # TODO def mysimp(expr): from sympy.core.function import expand from sympy.simplify.powsimp import powsimp from sympy.simplify.simplify import logcombine return expand( powsimp(logcombine(expr, force=True), force=True, deep=True), force=True).replace(exp_polar, exp) assert mysimp(mysimp(IMT(pi/(s*tan(pi*s)), s, x, (-1, 0)))) in [ log(1 - x)*Heaviside(1 - x) + log(x - 1)*Heaviside(x - 1), log(x)*Heaviside(x - 1) + log(1 - 1/x)*Heaviside(x - 1) + log(-x + 1)*Heaviside(-x + 1)] # test passing cot assert mysimp(IMT(pi*cot(pi*s)/s, s, x, (0, 1))) in [ log(1/x - 1)*Heaviside(1 - x) + log(1 - 1/x)*Heaviside(x - 1), -log(x)*Heaviside(-x + 1) + log(1 - 1/x)*Heaviside(x - 1) + log(-x + 1)*Heaviside(-x + 1), ] # 8.4.14 assert IMT(-gamma(s + S.Half)/(sqrt(pi)*s), s, x, (Rational(-1, 2), 0)) == \ erf(sqrt(x)) # 8.4.19 assert simplify(IMT(gamma(a/2 + s)/gamma(a/2 - s + 1), s, x, (-re(a)/2, Rational(3, 4)))) \ == besselj(a, 2*sqrt(x)) assert simplify(IMT(2**a*gamma(S.Half - 2*s)*gamma(s + (a + 1)/2) / (gamma(1 - s - a/2)*gamma(1 - 2*s + a)), s, x, (-(re(a) + 1)/2, Rational(1, 4)))) == \ sin(sqrt(x))*besselj(a, sqrt(x)) assert simplify(IMT(2**a*gamma(a/2 + s)*gamma(S.Half - 2*s) / (gamma(S.Half - s - a/2)*gamma(1 - 2*s + a)), s, x, (-re(a)/2, Rational(1, 4)))) == \ cos(sqrt(x))*besselj(a, sqrt(x)) # TODO this comes out as an amazing mess, but simplifies nicely assert simplify(IMT(gamma(a + s)*gamma(S.Half - s) / (sqrt(pi)*gamma(1 - s)*gamma(1 + a - s)), s, x, (-re(a), S.Half))) == \ besselj(a, sqrt(x))**2 assert simplify(IMT(gamma(s)*gamma(S.Half - s) / (sqrt(pi)*gamma(1 - s - a)*gamma(1 + a - s)), s, x, (0, S.Half))) == \ besselj(-a, sqrt(x))*besselj(a, sqrt(x)) assert simplify(IMT(4**s*gamma(-2*s + 1)*gamma(a/2 + b/2 + s) / (gamma(-a/2 + b/2 - s + 1)*gamma(a/2 - b/2 - s + 1) *gamma(a/2 + b/2 - s + 1)), s, x, (-(re(a) + re(b))/2, S.Half))) == \ besselj(a, sqrt(x))*besselj(b, sqrt(x)) # Section 8.4.20 # TODO this can be further simplified! assert simplify(IMT(-2**(2*s)*cos(pi*a/2 - pi*b/2 + pi*s)*gamma(-2*s + 1) * gamma(a/2 - b/2 + s)*gamma(a/2 + b/2 + s) / (pi*gamma(a/2 - b/2 - s + 1)*gamma(a/2 + b/2 - s + 1)), s, x, (Max(-re(a)/2 - re(b)/2, -re(a)/2 + re(b)/2), S.Half))) == \ besselj(a, sqrt(x))*-(besselj(-b, sqrt(x)) - besselj(b, sqrt(x))*cos(pi*b))/sin(pi*b) # TODO more # for coverage assert IMT(pi/cos(pi*s), s, x, (0, S.Half)) == sqrt(x)/(x + 1) @slow def test_laplace_transform(): from sympy import lowergamma from sympy.functions.special.delta_functions import DiracDelta from sympy.functions.special.error_functions import (fresnelc, fresnels) LT = laplace_transform a, b, c, = symbols('a, b, c', positive=True) t, w, x = symbols('t, w, x') f = Function("f") g = Function("g") # Test whether `noconds=True` in `doit`: assert (2*LaplaceTransform(exp(t), t, s) - 1).doit() == -1 + 2/(s - 1) assert LT(a*t+t**2+t**(S(5)/2), t, s) ==\ (a/s**2 + 2/s**3 + 15*sqrt(pi)/(8*s**(S(7)/2)), 0, True) assert LT(b/(t+a), t, s) == (-b*exp(-a*s)*Ei(-a*s), 0, True) assert LT(1/sqrt(t+a), t, s) ==\ (sqrt(pi)*sqrt(1/s)*exp(a*s)*erfc(sqrt(a)*sqrt(s)), 0, True) assert LT(sqrt(t)/(t+a), t, s) ==\ (-pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + sqrt(pi)*sqrt(1/s), 0, True) assert LT((t+a)**(-S(3)/2), t, s) ==\ (-2*sqrt(pi)*sqrt(s)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + 2/sqrt(a), 0, True) assert LT(t**(S(1)/2)*(t+a)**(-1), t, s) ==\ (-pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)) + sqrt(pi)*sqrt(1/s), 0, True) assert LT(1/(a*sqrt(t) + t**(3/2)), t, s) ==\ (pi*sqrt(a)*exp(a*s)*erfc(sqrt(a)*sqrt(s)), 0, True) assert LT((t+a)**b, t, s) ==\ (s**(-b - 1)*exp(-a*s)*lowergamma(b + 1, a*s), 0, True) assert LT(t**5/(t+a), t, s) == (120*a**5*lowergamma(-5, a*s), 0, True) assert LT(exp(t), t, s) == (1/(s - 1), 1, True) assert LT(exp(2*t), t, s) == (1/(s - 2), 2, True) assert LT(exp(a*t), t, s) == (1/(s - a), a, True) assert LT(exp(a*(t-b)), t, s) == (exp(-a*b)/(-a + s), a, True) assert LT(t*exp(-a*(t)), t, s) == ((a + s)**(-2), -a, True) assert LT(t*exp(-a*(t-b)), t, s) == (exp(a*b)/(a + s)**2, -a, True) assert LT(b*t*exp(-a*t), t, s) == (b/(a + s)**2, -a, True) assert LT(t**(S(7)/4)*exp(-8*t)/gamma(S(11)/4), t, s) ==\ ((s + 8)**(-S(11)/4), -8, True) assert LT(t**(S(3)/2)*exp(-8*t), t, s) ==\ (3*sqrt(pi)/(4*(s + 8)**(S(5)/2)), -8, True) assert LT(t**a*exp(-a*t), t, s) == ((a+s)**(-a-1)*gamma(a+1), -a, True) assert LT(b*exp(-a*t**2), t, s) ==\ (sqrt(pi)*b*exp(s**2/(4*a))*erfc(s/(2*sqrt(a)))/(2*sqrt(a)), 0, True) assert LT(exp(-2*t**2), t, s) ==\ (sqrt(2)*sqrt(pi)*exp(s**2/8)*erfc(sqrt(2)*s/4)/4, 0, True) assert LT(b*exp(2*t**2), t, s) ==\ (b*LaplaceTransform(exp(2*t**2), t, s), -oo, True) assert LT(t*exp(-a*t**2), t, s) ==\ (1/(2*a) - s*erfc(s/(2*sqrt(a)))/(4*sqrt(pi)*a**(S(3)/2)), 0, True) assert LT(exp(-a/t), t, s) ==\ (2*sqrt(a)*sqrt(1/s)*besselk(1, 2*sqrt(a)*sqrt(s)), 0, True) assert LT(sqrt(t)*exp(-a/t), t, s, simplify=True) ==\ (sqrt(pi)*(sqrt(a)*sqrt(s) + 1/S(2))*sqrt(s**(-3))*exp(-2*sqrt(a)*sqrt(s)), 0, True) assert LT(exp(-a/t)/sqrt(t), t, s) ==\ (sqrt(pi)*sqrt(1/s)*exp(-2*sqrt(a)*sqrt(s)), 0, True) assert LT( exp(-a/t)/(t*sqrt(t)), t, s) ==\ (sqrt(pi)*sqrt(1/a)*exp(-2*sqrt(a)*sqrt(s)), 0, True) assert LT(exp(-2*sqrt(a*t)), t, s) ==\ ( 1/s -sqrt(pi)*sqrt(a) * exp(a/s)*erfc(sqrt(a)*sqrt(1/s))/\ s**(S(3)/2), 0, True) assert LT(exp(-2*sqrt(a*t))/sqrt(t), t, s) == (exp(a/s)*erfc(sqrt(a)*\ sqrt(1/s))*(sqrt(pi)*sqrt(1/s)), 0, True) assert LT(t**4*exp(-2/t), t, s) ==\ (8*sqrt(2)*(1/s)**(S(5)/2)*besselk(5, 2*sqrt(2)*sqrt(s)), 0, True) assert LT(sinh(a*t), t, s) == (a/(-a**2 + s**2), a, True) assert LT(b*sinh(a*t)**2, t, s, simplify=True) ==\ (2*a**2*b/(s*(-4*a**2 + s**2)), 2*a, True) # The following line confirms that issue #21202 is solved assert LT(cosh(2*t), t, s) == (s/(-4 + s**2), 2, True) assert LT(cosh(a*t), t, s) == (s/(-a**2 + s**2), a, True) assert LT(cosh(a*t)**2, t, s, simplify=True) ==\ ((2*a**2 - s**2)/(s*(4*a**2 - s**2)), 2*a, True) assert LT(sinh(x+3), x, s, simplify=True) ==\ ((s*sinh(3) + cosh(3))/(s**2 - 1), 1, True) # The following line replaces the old test test_issue_7173() assert LT(sinh(a*t)*cosh(a*t), t, s, simplify=True) == (a/(-4*a**2 + s**2), 2*a, True) assert LT(sinh(a*t)/t, t, s) == (log((a + s)/(-a + s))/2, a, True) assert LT(t**(-S(3)/2)*sinh(a*t), t, s) ==\ (sqrt(pi)*(-sqrt(-a + s) + sqrt(a + s)), a, True) assert LT(sinh(2*sqrt(a*t)), t, s) ==\ (sqrt(pi)*sqrt(a)*exp(a/s)/s**(S(3)/2), 0, True) assert LT(sqrt(t)*sinh(2*sqrt(a*t)), t, s, simplify=True) ==\ ((-sqrt(a)*s**(S(5)/2) + sqrt(pi)*s**2*(2*a + s)*exp(a/s)*\ erf(sqrt(a)*sqrt(1/s))/2)/s**(S(9)/2), 0, True) assert LT(sinh(2*sqrt(a*t))/sqrt(t), t, s) ==\ (sqrt(pi)*exp(a/s)*erf(sqrt(a)*sqrt(1/s))/sqrt(s), 0, True) assert LT(sinh(sqrt(a*t))**2/sqrt(t), t, s) ==\ (sqrt(pi)*(exp(a/s) - 1)/(2*sqrt(s)), 0, True) assert LT(t**(S(3)/7)*cosh(a*t), t, s) ==\ (((a + s)**(-S(10)/7) + (-a+s)**(-S(10)/7))*gamma(S(10)/7)/2, a, True) assert LT(cosh(2*sqrt(a*t)), t, s) ==\ (sqrt(pi)*sqrt(a)*exp(a/s)*erf(sqrt(a)*sqrt(1/s))/s**(S(3)/2) + 1/s, 0, True) assert LT(sqrt(t)*cosh(2*sqrt(a*t)), t, s) ==\ (sqrt(pi)*(a + s/2)*exp(a/s)/s**(S(5)/2), 0, True) assert LT(cosh(2*sqrt(a*t))/sqrt(t), t, s) ==\ (sqrt(pi)*exp(a/s)/sqrt(s), 0, True) assert LT(cosh(sqrt(a*t))**2/sqrt(t), t, s) ==\ (sqrt(pi)*(exp(a/s) + 1)/(2*sqrt(s)), 0, True) assert LT(log(t), t, s, simplify=True) == ((-log(s) - EulerGamma)/s, 0, True) assert LT(-log(t/a), t, s, simplify=True) ==\ ((log(a) + log(s) + EulerGamma)/s, 0, True) assert LT(log(1+a*t), t, s) == (-exp(s/a)*Ei(-s/a)/s, 0, True) assert LT(log(t+a), t, s, simplify=True) ==\ ((s*log(a) - exp(s/a)*Ei(-s/a))/s**2, 0, True) assert LT(log(t)/sqrt(t), t, s, simplify=True) ==\ (sqrt(pi)*(-log(s) - log(4) - EulerGamma)/sqrt(s), 0, True) assert LT(t**(S(5)/2)*log(t), t, s, simplify=True) ==\ (sqrt(pi)*(-15*log(s) - log(1073741824) - 15*EulerGamma + 46)/\ (8*s**(S(7)/2)), 0, True) assert (LT(t**3*log(t), t, s, noconds=True, simplify=True)-\ 6*(-log(s) - S.EulerGamma + S(11)/6)/s**4).simplify() == S.Zero assert LT(log(t)**2, t, s, simplify=True) ==\ (((log(s) + EulerGamma)**2 + pi**2/6)/s, 0, True) assert LT(exp(-a*t)*log(t), t, s, simplify=True) ==\ ((-log(a + s) - EulerGamma)/(a + s), -a, True) assert LT(sin(a*t), t, s) == (a/(a**2 + s**2), 0, True) assert LT(Abs(sin(a*t)), t, s) ==\ (a*coth(pi*s/(2*a))/(a**2 + s**2), 0, True) assert LT(sin(a*t)/t, t, s) == (atan(a/s), 0, True) assert LT(sin(a*t)**2/t, t, s) == (log(4*a**2/s**2 + 1)/4, 0, True) assert LT(sin(a*t)**2/t**2, t, s) ==\ (a*atan(2*a/s) - s*log(4*a**2/s**2 + 1)/4, 0, True) assert LT(sin(2*sqrt(a*t)), t, s) ==\ (sqrt(pi)*sqrt(a)*exp(-a/s)/s**(S(3)/2), 0, True) assert LT(sin(2*sqrt(a*t))/t, t, s) == (pi*erf(sqrt(a)*sqrt(1/s)), 0, True) assert LT(cos(a*t), t, s) == (s/(a**2 + s**2), 0, True) assert LT(cos(a*t)**2, t, s) ==\ ((2*a**2 + s**2)/(s*(4*a**2 + s**2)), 0, True) assert LT(sqrt(t)*cos(2*sqrt(a*t)), t, s, simplify=True) ==\ (sqrt(pi)*(-a + s/2)*exp(-a/s)/s**(S(5)/2), 0, True) assert LT(cos(2*sqrt(a*t))/sqrt(t), t, s) ==\ (sqrt(pi)*sqrt(1/s)*exp(-a/s), 0, True) assert LT(sin(a*t)*sin(b*t), t, s) ==\ (2*a*b*s/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)), 0, True) assert LT(cos(a*t)*sin(b*t), t, s) ==\ (b*(-a**2 + b**2 + s**2)/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)), 0, True) assert LT(cos(a*t)*cos(b*t), t, s) ==\ (s*(a**2 + b**2 + s**2)/((s**2 + (a - b)**2)*(s**2 + (a + b)**2)), 0, True) assert LT(-a*t*cos(a*t) + sin(a*t), t, s, simplify=True) ==\ (2*a**3/(a**4 + 2*a**2*s**2 + s**4), 0, True) assert LT(c*exp(-b*t)*sin(a*t), t, s) == (a*c/(a**2 + (b + s)**2), -b, True) assert LT(c*exp(-b*t)*cos(a*t), t, s) == ((b + s)*c/(a**2 + (b + s)**2), -b, True) assert LT(cos(x + 3), x, s, simplify=True) ==\ ((s*cos(3) - sin(3))/(s**2 + 1), 0, True) # Error functions (laplace7.pdf) assert LT(erf(a*t), t, s) == (exp(s**2/(4*a**2))*erfc(s/(2*a))/s, 0, True) assert LT(erf(sqrt(a*t)), t, s) == (sqrt(a)/(s*sqrt(a + s)), 0, True) assert LT(exp(a*t)*erf(sqrt(a*t)), t, s, simplify=True) ==\ (-sqrt(a)/(sqrt(s)*(a - s)), a, True) assert LT(erf(sqrt(a/t)/2), t, s, simplify=True) ==\ (1/s - exp(-sqrt(a)*sqrt(s))/s, 0, True) assert LT(erfc(sqrt(a*t)), t, s, simplify=True) ==\ (-sqrt(a)/(s*sqrt(a + s)) + 1/s, -a, True) assert LT(exp(a*t)*erfc(sqrt(a*t)), t, s) ==\ (1/(sqrt(a)*sqrt(s) + s), 0, True) assert LT(erfc(sqrt(a/t)/2), t, s) == (exp(-sqrt(a)*sqrt(s))/s, 0, True) # Bessel functions (laplace8.pdf) assert LT(besselj(0, a*t), t, s) == (1/sqrt(a**2 + s**2), 0, True) assert LT(besselj(1, a*t), t, s, simplify=True) ==\ (a/(a**2 + s**2 + s*sqrt(a**2 + s**2)), 0, True) assert LT(besselj(2, a*t), t, s, simplify=True) ==\ (a**2/(sqrt(a**2 + s**2)*(s + sqrt(a**2 + s**2))**2), 0, True) assert LT(t*besselj(0, a*t), t, s) ==\ (s/(a**2 + s**2)**(S(3)/2), 0, True) assert LT(t*besselj(1, a*t), t, s) ==\ (a/(a**2 + s**2)**(S(3)/2), 0, True) assert LT(t**2*besselj(2, a*t), t, s) ==\ (3*a**2/(a**2 + s**2)**(S(5)/2), 0, True) assert LT(besselj(0, 2*sqrt(a*t)), t, s) == (exp(-a/s)/s, 0, True) assert LT(t**(S(3)/2)*besselj(3, 2*sqrt(a*t)), t, s) ==\ (a**(S(3)/2)*exp(-a/s)/s**4, 0, True) assert LT(besselj(0, a*sqrt(t**2+b*t)), t, s, simplify=True) ==\ (exp(b*(s - sqrt(a**2 + s**2)))/sqrt(a**2 + s**2), 0, True) assert LT(besseli(0, a*t), t, s) == (1/sqrt(-a**2 + s**2), a, True) assert LT(besseli(1, a*t), t, s, simplify=True) ==\ (a/(-a**2 + s**2 + s*sqrt(-a**2 + s**2)), a, True) assert LT(besseli(2, a*t), t, s, simplify=True) ==\ (a**2/(sqrt(-a**2 + s**2)*(s + sqrt(-a**2 + s**2))**2), a, True) assert LT(t*besseli(0, a*t), t, s) == (s/(-a**2 + s**2)**(S(3)/2), a, True) assert LT(t*besseli(1, a*t), t, s) == (a/(-a**2 + s**2)**(S(3)/2), a, True) assert LT(t**2*besseli(2, a*t), t, s) ==\ (3*a**2/(-a**2 + s**2)**(S(5)/2), a, True) assert LT(t**(S(3)/2)*besseli(3, 2*sqrt(a*t)), t, s) ==\ (a**(S(3)/2)*exp(a/s)/s**4, 0, True) assert LT(bessely(0, a*t), t, s) ==\ (-2*asinh(s/a)/(pi*sqrt(a**2 + s**2)), 0, True) assert LT(besselk(0, a*t), t, s) ==\ (log((s + sqrt(-a**2 + s**2))/a)/sqrt(-a**2 + s**2), -a, True) assert LT(sin(a*t)**8, t, s, simplify=True) ==\ (40320*a**8/(s*(147456*a**8 + 52480*a**6*s**2 + 4368*a**4*s**4 +\ 120*a**2*s**6 + s**8)), 0, True) # Test general rules and unevaluated forms # These all also test whether issue #7219 is solved. assert LT(Heaviside(t-1)*cos(t-1), t, s) == (s*exp(-s)/(s**2 + 1), 0, True) assert LT(a*f(t), t, w) == (a*LaplaceTransform(f(t), t, w), -oo, True) assert LT(a*Heaviside(t+1)*f(t+1), t, s) ==\ (a*LaplaceTransform(f(t + 1), t, s), -oo, True) assert LT(a*Heaviside(t-1)*f(t-1), t, s) ==\ (a*LaplaceTransform(f(t), t, s)*exp(-s), -oo, True) assert LT(b*f(t/a), t, s) == (a*b*LaplaceTransform(f(t), t, a*s), -oo, True) assert LT(exp(-f(x)*t), t, s) == (1/(s + f(x)), -f(x), True) assert LT(exp(-a*t)*f(t), t, s) ==\ (LaplaceTransform(f(t), t, a + s), -oo, True) assert LT(exp(-a*t)*erfc(sqrt(b/t)/2), t, s) ==\ (exp(-sqrt(b)*sqrt(a + s))/(a + s), -a, True) assert LT(sinh(a*t)*f(t), t, s) ==\ (LaplaceTransform(f(t), t, -a + s)/2 -\ LaplaceTransform(f(t), t, a + s)/2, -oo, True) assert LT(sinh(a*t)*t, t, s, simplify=True) ==\ (2*a*s/(a**4 - 2*a**2*s**2 + s**4), a, True) assert LT(cosh(a*t)*f(t), t, s) ==\ (LaplaceTransform(f(t), t, -a + s)/2 +\ LaplaceTransform(f(t), t, a + s)/2, -oo, True) assert LT(cosh(a*t)*t, t, s, simplify=True) ==\ (1/(2*(a + s)**2) + 1/(2*(a - s)**2), a, True) assert LT(sin(a*t)*f(t), t, s, simplify=True) ==\ (I*(-LaplaceTransform(f(t), t, -I*a + s) +\ LaplaceTransform(f(t), t, I*a + s))/2, -oo, True) assert LT(sin(a*t)*t, t, s, simplify=True) ==\ (2*a*s/(a**4 + 2*a**2*s**2 + s**4), 0, True) assert LT(cos(a*t)*f(t), t, s) ==\ (LaplaceTransform(f(t), t, -I*a + s)/2 +\ LaplaceTransform(f(t), t, I*a + s)/2, -oo, True) assert LT(cos(a*t)*t, t, s, simplify=True) ==\ ((-a**2 + s**2)/(a**4 + 2*a**2*s**2 + s**4), 0, True) assert LT(t**2*exp(-t**2), t, s) ==\ (sqrt(pi)*s**2*exp(s**2/4)*erfc(s/2)/8 - s/4 +\ sqrt(pi)*exp(s**2/4)*erfc(s/2)/4, 0, True) assert LT((a*t**2 + b*t + c)*f(t), t, s) ==\ (a*Derivative(LaplaceTransform(f(t), t, s), (s, 2)) -\ b*Derivative(LaplaceTransform(f(t), t, s), s) +\ c*LaplaceTransform(f(t), t, s), -oo, True) # The following two lines test whether issues #5813 and #7176 are solved. assert LT(diff(f(t), (t, 1)), t, s, noconds=True) ==\ s*LaplaceTransform(f(t), t, s) - f(0) assert LT(diff(f(t), (t, 3)), t, s, noconds=True) ==\ s**3*LaplaceTransform(f(t), t, s) - s**2*f(0) -\ s*Subs(Derivative(f(t), t), t, 0) -\ Subs(Derivative(f(t), (t, 2)), t, 0) # Issue #23307 assert LT(10*diff(f(t), (t, 1)), t, s, noconds=True) ==\ 10*s*LaplaceTransform(f(t), t, s) - 10*f(0) assert LT(a*f(b*t)+g(c*t), t, s, noconds=True) ==\ a*LaplaceTransform(f(t), t, s/b)/b + LaplaceTransform(g(t), t, s/c)/c assert inverse_laplace_transform( f(w), w, t, plane=0) == InverseLaplaceTransform(f(w), w, t, 0) assert LT(f(t)*g(t), t, s, noconds=True) ==\ LaplaceTransform(f(t)*g(t), t, s) # Issue #24294 assert LT(b*f(a*t), t, s, noconds=True) ==\ b*LaplaceTransform(f(t), t, s/a)/a assert LT(3*exp(t)*Heaviside(t), t, s) == (3/(s - 1), 1, True) assert LT(2*sin(t)*Heaviside(t), t, s, simplify=True) == (2/(s**2 + 1), 0, True) # additional basic tests from wikipedia assert LT((t - a)**b*exp(-c*(t - a))*Heaviside(t - a), t, s) == \ ((c + s)**(-b - 1)*exp(-a*s)*gamma(b + 1), -c, True) assert LT((exp(2*t)-1)*exp(-b-t)*Heaviside(t)/2, t, s, noconds=True, simplify=True) == exp(-b)/(s**2 - 1) # DiracDelta function: standard cases assert LT(DiracDelta(t), t, s) == (1, -oo, True) assert LT(DiracDelta(a*t), t, s) == (1/a, -oo, True) assert LT(DiracDelta(t/42), t, s) == (42, -oo, True) assert LT(DiracDelta(t+42), t, s) == (0, -oo, True) assert LT(DiracDelta(t)+DiracDelta(t-42), t, s) == \ (1 + exp(-42*s), -oo, True) assert LT(DiracDelta(t)-a*exp(-a*t), t, s, simplify=True) == \ (s/(a + s), -a, True) assert LT(exp(-t)*(DiracDelta(t)+DiracDelta(t-42)), t, s, simplify=True) == \ (exp(-42*s - 42) + 1, -oo, True) assert LT(f(t)*DiracDelta(t-42), t, s) == (f(42)*exp(-42*s), -oo, True) assert LT(f(t)*DiracDelta(b*t-a), t, s) == (f(a/b)*exp(-a*s/b)/b, -oo, True) assert LT(f(t)*DiracDelta(b*t+a), t, s) == (0, -oo, True) # Collection of cases that cannot be fully evaluated and/or would catch # some common implementation errors assert LT(DiracDelta(t**2), t, s, noconds=True) ==\ LaplaceTransform(DiracDelta(t**2), t, s) assert LT(DiracDelta(t**2 - 1), t, s) == (exp(-s)/2, -oo, True) assert LT(DiracDelta(t*(1 - t)), t, s) == (1 - exp(-s), -oo, True) assert LT((DiracDelta(t) + 1)*(DiracDelta(t - 1) + 1), t, s) == \ (LaplaceTransform(DiracDelta(t)*DiracDelta(t - 1), t, s) + \ 1 + exp(-s) + 1/s, 0, True) assert LT(DiracDelta(2*t-2*exp(a)), t, s) == (exp(-s*exp(a))/2, -oo, True) assert LT(DiracDelta(-2*t+2*exp(a)), t, s) == (exp(-s*exp(a))/2, -oo, True) # Heaviside tests assert LT(Heaviside(t), t, s) == (1/s, 0, True) assert LT(Heaviside(t - a), t, s) == (exp(-a*s)/s, 0, True) assert LT(Heaviside(t-1), t, s) == (exp(-s)/s, 0, True) assert LT(Heaviside(2*t-4), t, s) == (exp(-2*s)/s, 0, True) assert LT(Heaviside(2*t+4), t, s) == (1/s, 0, True) assert LT(Heaviside(-2*t+4), t, s, simplify=True) == (1/s - exp(-2*s)/s, 0, True) assert LT(g(t)*Heaviside(t - w), t, s) ==\ (LaplaceTransform(g(t)*Heaviside(t - w), t, s), -oo, True) # Fresnel functions assert laplace_transform(fresnels(t), t, s, simplify=True) == \ ((-sin(s**2/(2*pi))*fresnels(s/pi) + sqrt(2)*sin(s**2/(2*pi) + pi/4)/2\ - cos(s**2/(2*pi))*fresnelc(s/pi))/s, 0, True) assert laplace_transform(fresnelc(t), t, s, simplify=True) == \ ((sin(s**2/(2*pi))*fresnelc(s/pi) - cos(s**2/(2*pi))*fresnels(s/pi)\ + sqrt(2)*cos(s**2/(2*pi) + pi/4)/2)/s, 0, True) # Matrix tests Mt = Matrix([[exp(t), t*exp(-t)], [t*exp(-t), exp(t)]]) Ms = Matrix([[ 1/(s - 1), (s + 1)**(-2)], [(s + 1)**(-2), 1/(s - 1)]]) # The default behaviour for Laplace transform of a Matrix returns a Matrix # of Tuples and is deprecated: with warns_deprecated_sympy(): Ms_conds = Matrix([[(1/(s - 1), 1, True), ((s + 1)**(-2), -1, True)], [((s + 1)**(-2), -1, True), (1/(s - 1), 1, True)]]) with warns_deprecated_sympy(): assert LT(Mt, t, s) == Ms_conds # The new behavior is to return a tuple of a Matrix and the convergence # conditions for the matrix as a whole: assert LT(Mt, t, s, legacy_matrix=False) == (Ms, 1, True) # With noconds=True the transformed matrix is returned without conditions # either way: assert LT(Mt, t, s, noconds=True) == Ms assert LT(Mt, t, s, legacy_matrix=False, noconds=True) == Ms @slow def test_inverse_laplace_transform(): from sympy.core.exprtools import factor_terms from sympy.functions.special.delta_functions import DiracDelta from sympy.simplify.simplify import simplify ILT = inverse_laplace_transform a, b, c, = symbols('a b c', positive=True) t = symbols('t') def simp_hyp(expr): return factor_terms(expand_mul(expr)).rewrite(sin) assert ILT(1, s, t) == DiracDelta(t) assert ILT(1/s, s, t) == Heaviside(t) assert ILT(a/(a + s), s, t) == a*exp(-a*t)*Heaviside(t) assert ILT(s/(a + s), s, t) == -a*exp(-a*t)*Heaviside(t) + DiracDelta(t) assert ILT((a + s)**(-2), s, t) == t*exp(-a*t)*Heaviside(t) assert ILT((a + s)**(-5), s, t) == t**4*exp(-a*t)*Heaviside(t)/24 assert ILT(a/(a**2 + s**2), s, t) == sin(a*t)*Heaviside(t) assert ILT(s/(s**2 + a**2), s, t) == cos(a*t)*Heaviside(t) assert ILT(b/(b**2 + (a + s)**2), s, t) == exp(-a*t)*sin(b*t)*Heaviside(t) assert ILT(b*s/(b**2 + (a + s)**2), s, t) +\ (a*sin(b*t) - b*cos(b*t))*exp(-a*t)*Heaviside(t) == 0 assert ILT(exp(-a*s)/s, s, t) == Heaviside(-a + t) assert ILT(exp(-a*s)/(b + s), s, t) == exp(b*(a - t))*Heaviside(-a + t) assert ILT((b + s)/(a**2 + (b + s)**2), s, t) == \ exp(-b*t)*cos(a*t)*Heaviside(t) assert ILT(exp(-a*s)/s**b, s, t) == \ (-a + t)**(b - 1)*Heaviside(-a + t)/gamma(b) assert ILT(exp(-a*s)/sqrt(s**2 + 1), s, t) == \ Heaviside(-a + t)*besselj(0, a - t) assert ILT(1/(s*sqrt(s + 1)), s, t) == Heaviside(t)*erf(sqrt(t)) assert ILT(1/(s**2*(s**2 + 1)), s, t) == (t - sin(t))*Heaviside(t) assert ILT(s**2/(s**2 + 1), s, t) == -sin(t)*Heaviside(t) + DiracDelta(t) assert ILT(1 - 1/(s**2 + 1), s, t) == -sin(t)*Heaviside(t) + DiracDelta(t) assert ILT(1/s**2, s, t) == t*Heaviside(t) assert ILT(1/s**5, s, t) == t**4*Heaviside(t)/24 assert simp_hyp(ILT(a/(s**2 - a**2), s, t)) == sinh(a*t)*Heaviside(t) assert simp_hyp(ILT(s/(s**2 - a**2), s, t)) == cosh(a*t)*Heaviside(t) # TODO sinh/cosh shifted come out a mess. also delayed trig is a mess # TODO should this simplify further? assert ILT(exp(-a*s)/s**b, s, t) == \ (t - a)**(b - 1)*Heaviside(t - a)/gamma(b) assert ILT(exp(-a*s)/sqrt(1 + s**2), s, t) == \ Heaviside(t - a)*besselj(0, a - t) # note: besselj(0, x) is even # XXX ILT turns these branch factor into trig functions ... assert simplify(ILT(a**b*(s + sqrt(s**2 - a**2))**(-b)/sqrt(s**2 - a**2), s, t).rewrite(exp)) == \ Heaviside(t)*besseli(b, a*t) assert ILT(a**b*(s + sqrt(s**2 + a**2))**(-b)/sqrt(s**2 + a**2), s, t).rewrite(exp) == \ Heaviside(t)*besselj(b, a*t) assert ILT(1/(s*sqrt(s + 1)), s, t) == Heaviside(t)*erf(sqrt(t)) # TODO can we make erf(t) work? assert ILT(1/(s**2*(s**2 + 1)),s,t) == (t - sin(t))*Heaviside(t) assert ILT( (s * eye(2) - Matrix([[1, 0], [0, 2]])).inv(), s, t) ==\ Matrix([[exp(t)*Heaviside(t), 0], [0, exp(2*t)*Heaviside(t)]]) def test_inverse_laplace_transform_delta(): from sympy.functions.special.delta_functions import DiracDelta ILT = inverse_laplace_transform t = symbols('t') assert ILT(2, s, t) == 2*DiracDelta(t) assert ILT(2*exp(3*s) - 5*exp(-7*s), s, t) == \ 2*DiracDelta(t + 3) - 5*DiracDelta(t - 7) a = cos(sin(7)/2) assert ILT(a*exp(-3*s), s, t) == a*DiracDelta(t - 3) assert ILT(exp(2*s), s, t) == DiracDelta(t + 2) r = Symbol('r', real=True) assert ILT(exp(r*s), s, t) == DiracDelta(t + r) def test_inverse_laplace_transform_delta_cond(): from sympy.functions.elementary.complexes import im from sympy.functions.special.delta_functions import DiracDelta ILT = inverse_laplace_transform t = symbols('t') r = Symbol('r', real=True) assert ILT(exp(r*s), s, t, noconds=False) == (DiracDelta(t + r), True) z = Symbol('z') assert ILT(exp(z*s), s, t, noconds=False) == \ (DiracDelta(t + z), Eq(im(z), 0)) # inversion does not exist: verify it doesn't evaluate to DiracDelta for z in (Symbol('z', extended_real=False), Symbol('z', imaginary=True, zero=False)): f = ILT(exp(z*s), s, t, noconds=False) f = f[0] if isinstance(f, tuple) else f assert f.func != DiracDelta # issue 15043 assert ILT(1/s + exp(r*s)/s, s, t, noconds=False) == ( Heaviside(t) + Heaviside(r + t), True) def test_fourier_transform(): from sympy.core.function import (expand, expand_complex, expand_trig) from sympy.polys.polytools import factor from sympy.simplify.simplify import simplify FT = fourier_transform IFT = inverse_fourier_transform def simp(x): return simplify(expand_trig(expand_complex(expand(x)))) def sinc(x): return sin(pi*x)/(pi*x) k = symbols('k', real=True) f = Function("f") # TODO for this to work with real a, need to expand abs(a*x) to abs(a)*abs(x) a = symbols('a', positive=True) b = symbols('b', positive=True) posk = symbols('posk', positive=True) # Test unevaluated form assert fourier_transform(f(x), x, k) == FourierTransform(f(x), x, k) assert inverse_fourier_transform( f(k), k, x) == InverseFourierTransform(f(k), k, x) # basic examples from wikipedia assert simp(FT(Heaviside(1 - abs(2*a*x)), x, k)) == sinc(k/a)/a # TODO IFT is a *mess* assert simp(FT(Heaviside(1 - abs(a*x))*(1 - abs(a*x)), x, k)) == sinc(k/a)**2/a # TODO IFT assert factor(FT(exp(-a*x)*Heaviside(x), x, k), extension=I) == \ 1/(a + 2*pi*I*k) # NOTE: the ift comes out in pieces assert IFT(1/(a + 2*pi*I*x), x, posk, noconds=False) == (exp(-a*posk), True) assert IFT(1/(a + 2*pi*I*x), x, -posk, noconds=False) == (0, True) assert IFT(1/(a + 2*pi*I*x), x, symbols('k', negative=True), noconds=False) == (0, True) # TODO IFT without factoring comes out as meijer g assert factor(FT(x*exp(-a*x)*Heaviside(x), x, k), extension=I) == \ 1/(a + 2*pi*I*k)**2 assert FT(exp(-a*x)*sin(b*x)*Heaviside(x), x, k) == \ b/(b**2 + (a + 2*I*pi*k)**2) assert FT(exp(-a*x**2), x, k) == sqrt(pi)*exp(-pi**2*k**2/a)/sqrt(a) assert IFT(sqrt(pi/a)*exp(-(pi*k)**2/a), k, x) == exp(-a*x**2) assert FT(exp(-a*abs(x)), x, k) == 2*a/(a**2 + 4*pi**2*k**2) # TODO IFT (comes out as meijer G) # TODO besselj(n, x), n an integer > 0 actually can be done... # TODO are there other common transforms (no distributions!)? def test_sine_transform(): t = symbols("t") w = symbols("w") a = symbols("a") f = Function("f") # Test unevaluated form assert sine_transform(f(t), t, w) == SineTransform(f(t), t, w) assert inverse_sine_transform( f(w), w, t) == InverseSineTransform(f(w), w, t) assert sine_transform(1/sqrt(t), t, w) == 1/sqrt(w) assert inverse_sine_transform(1/sqrt(w), w, t) == 1/sqrt(t) assert sine_transform((1/sqrt(t))**3, t, w) == 2*sqrt(w) assert sine_transform(t**(-a), t, w) == 2**( -a + S.Half)*w**(a - 1)*gamma(-a/2 + 1)/gamma((a + 1)/2) assert inverse_sine_transform(2**(-a + S( 1)/2)*w**(a - 1)*gamma(-a/2 + 1)/gamma(a/2 + S.Half), w, t) == t**(-a) assert sine_transform( exp(-a*t), t, w) == sqrt(2)*w/(sqrt(pi)*(a**2 + w**2)) assert inverse_sine_transform( sqrt(2)*w/(sqrt(pi)*(a**2 + w**2)), w, t) == exp(-a*t) assert sine_transform( log(t)/t, t, w) == sqrt(2)*sqrt(pi)*-(log(w**2) + 2*EulerGamma)/4 assert sine_transform( t*exp(-a*t**2), t, w) == sqrt(2)*w*exp(-w**2/(4*a))/(4*a**Rational(3, 2)) assert inverse_sine_transform( sqrt(2)*w*exp(-w**2/(4*a))/(4*a**Rational(3, 2)), w, t) == t*exp(-a*t**2) def test_cosine_transform(): from sympy.functions.special.error_functions import (Ci, Si) t = symbols("t") w = symbols("w") a = symbols("a") f = Function("f") # Test unevaluated form assert cosine_transform(f(t), t, w) == CosineTransform(f(t), t, w) assert inverse_cosine_transform( f(w), w, t) == InverseCosineTransform(f(w), w, t) assert cosine_transform(1/sqrt(t), t, w) == 1/sqrt(w) assert inverse_cosine_transform(1/sqrt(w), w, t) == 1/sqrt(t) assert cosine_transform(1/( a**2 + t**2), t, w) == sqrt(2)*sqrt(pi)*exp(-a*w)/(2*a) assert cosine_transform(t**( -a), t, w) == 2**(-a + S.Half)*w**(a - 1)*gamma((-a + 1)/2)/gamma(a/2) assert inverse_cosine_transform(2**(-a + S( 1)/2)*w**(a - 1)*gamma(-a/2 + S.Half)/gamma(a/2), w, t) == t**(-a) assert cosine_transform( exp(-a*t), t, w) == sqrt(2)*a/(sqrt(pi)*(a**2 + w**2)) assert inverse_cosine_transform( sqrt(2)*a/(sqrt(pi)*(a**2 + w**2)), w, t) == exp(-a*t) assert cosine_transform(exp(-a*sqrt(t))*cos(a*sqrt( t)), t, w) == a*exp(-a**2/(2*w))/(2*w**Rational(3, 2)) assert cosine_transform(1/(a + t), t, w) == sqrt(2)*( (-2*Si(a*w) + pi)*sin(a*w)/2 - cos(a*w)*Ci(a*w))/sqrt(pi) assert inverse_cosine_transform(sqrt(2)*meijerg(((S.Half, 0), ()), ( (S.Half, 0, 0), (S.Half,)), a**2*w**2/4)/(2*pi), w, t) == 1/(a + t) assert cosine_transform(1/sqrt(a**2 + t**2), t, w) == sqrt(2)*meijerg( ((S.Half,), ()), ((0, 0), (S.Half,)), a**2*w**2/4)/(2*sqrt(pi)) assert inverse_cosine_transform(sqrt(2)*meijerg(((S.Half,), ()), ((0, 0), (S.Half,)), a**2*w**2/4)/(2*sqrt(pi)), w, t) == 1/(t*sqrt(a**2/t**2 + 1)) def test_hankel_transform(): r = Symbol("r") k = Symbol("k") nu = Symbol("nu") m = Symbol("m") a = symbols("a") assert hankel_transform(1/r, r, k, 0) == 1/k assert inverse_hankel_transform(1/k, k, r, 0) == 1/r assert hankel_transform( 1/r**m, r, k, 0) == 2**(-m + 1)*k**(m - 2)*gamma(-m/2 + 1)/gamma(m/2) assert inverse_hankel_transform( 2**(-m + 1)*k**(m - 2)*gamma(-m/2 + 1)/gamma(m/2), k, r, 0) == r**(-m) assert hankel_transform(1/r**m, r, k, nu) == ( 2*2**(-m)*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/gamma(m/2 + nu/2)) assert inverse_hankel_transform(2**(-m + 1)*k**( m - 2)*gamma(-m/2 + nu/2 + 1)/gamma(m/2 + nu/2), k, r, nu) == r**(-m) assert hankel_transform(r**nu*exp(-a*r), r, k, nu) == \ 2**(nu + 1)*a*k**(-nu - 3)*(a**2/k**2 + 1)**(-nu - S( 3)/2)*gamma(nu + Rational(3, 2))/sqrt(pi) assert inverse_hankel_transform( 2**(nu + 1)*a*k**(-nu - 3)*(a**2/k**2 + 1)**(-nu - Rational(3, 2))*gamma( nu + Rational(3, 2))/sqrt(pi), k, r, nu) == r**nu*exp(-a*r) def test_issue_7181(): assert mellin_transform(1/(1 - x), x, s) != None def test_issue_8882(): # This is the original test. # from sympy import diff, Integral, integrate # r = Symbol('r') # psi = 1/r*sin(r)*exp(-(a0*r)) # h = -1/2*diff(psi, r, r) - 1/r*psi # f = 4*pi*psi*h*r**2 # assert integrate(f, (r, -oo, 3), meijerg=True).has(Integral) == True # To save time, only the critical part is included. F = -a**(-s + 1)*(4 + 1/a**2)**(-s/2)*sqrt(1/a**2)*exp(-s*I*pi)* \ sin(s*atan(sqrt(1/a**2)/2))*gamma(s) raises(IntegralTransformError, lambda: inverse_mellin_transform(F, s, x, (-1, oo), **{'as_meijerg': True, 'needeval': True})) def test_issue_8514(): from sympy.simplify.simplify import simplify a, b, c, = symbols('a b c', positive=True) t = symbols('t', positive=True) ft = simplify(inverse_laplace_transform(1/(a*s**2+b*s+c),s, t)) assert ft == (I*exp(t*cos(atan2(0, -4*a*c + b**2)/2)*sqrt(Abs(4*a*c - b**2))/a)*sin(t*sin(atan2(0, -4*a*c + b**2)/2)*sqrt(Abs( 4*a*c - b**2))/(2*a)) + exp(t*cos(atan2(0, -4*a*c + b**2) /2)*sqrt(Abs(4*a*c - b**2))/a)*cos(t*sin(atan2(0, -4*a*c + b**2)/2)*sqrt(Abs(4*a*c - b**2))/(2*a)) + I*sin(t*sin( atan2(0, -4*a*c + b**2)/2)*sqrt(Abs(4*a*c - b**2))/(2*a)) - cos(t*sin(atan2(0, -4*a*c + b**2)/2)*sqrt(Abs(4*a*c - b**2))/(2*a)))*exp(-t*(b + cos(atan2(0, -4*a*c + b**2)/2) *sqrt(Abs(4*a*c - b**2)))/(2*a))/sqrt(-4*a*c + b**2) def test_issue_12591(): x, y = symbols("x y", real=True) assert fourier_transform(exp(x), x, y) == FourierTransform(exp(x), x, y)
9ee65ed7b40462382825aa2fc442d04bc715f764b7d5da491bd220b84f471454
"""Test sparse polynomials. """ from functools import reduce from operator import add, mul from sympy.polys.rings import ring, xring, sring, PolyRing, PolyElement from sympy.polys.fields import field, FracField from sympy.polys.domains import ZZ, QQ, RR, FF, EX from sympy.polys.orderings import lex, grlex from sympy.polys.polyerrors import GeneratorsError, \ ExactQuotientFailed, MultivariatePolynomialError, CoercionFailed from sympy.testing.pytest import raises from sympy.core import Symbol, symbols from sympy.core.numbers import (oo, pi) from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt def test_PolyRing___init__(): x, y, z, t = map(Symbol, "xyzt") assert len(PolyRing("x,y,z", ZZ, lex).gens) == 3 assert len(PolyRing(x, ZZ, lex).gens) == 1 assert len(PolyRing(("x", "y", "z"), ZZ, lex).gens) == 3 assert len(PolyRing((x, y, z), ZZ, lex).gens) == 3 assert len(PolyRing("", ZZ, lex).gens) == 0 assert len(PolyRing([], ZZ, lex).gens) == 0 raises(GeneratorsError, lambda: PolyRing(0, ZZ, lex)) assert PolyRing("x", ZZ[t], lex).domain == ZZ[t] assert PolyRing("x", 'ZZ[t]', lex).domain == ZZ[t] assert PolyRing("x", PolyRing("t", ZZ, lex), lex).domain == ZZ[t] raises(GeneratorsError, lambda: PolyRing("x", PolyRing("x", ZZ, lex), lex)) _lex = Symbol("lex") assert PolyRing("x", ZZ, lex).order == lex assert PolyRing("x", ZZ, _lex).order == lex assert PolyRing("x", ZZ, 'lex').order == lex R1 = PolyRing("x,y", ZZ, lex) R2 = PolyRing("x,y", ZZ, lex) R3 = PolyRing("x,y,z", ZZ, lex) assert R1.x == R1.gens[0] assert R1.y == R1.gens[1] assert R1.x == R2.x assert R1.y == R2.y assert R1.x != R3.x assert R1.y != R3.y def test_PolyRing___hash__(): R, x, y, z = ring("x,y,z", QQ) assert hash(R) def test_PolyRing___eq__(): assert ring("x,y,z", QQ)[0] == ring("x,y,z", QQ)[0] assert ring("x,y,z", QQ)[0] is ring("x,y,z", QQ)[0] assert ring("x,y,z", QQ)[0] != ring("x,y,z", ZZ)[0] assert ring("x,y,z", QQ)[0] is not ring("x,y,z", ZZ)[0] assert ring("x,y,z", ZZ)[0] != ring("x,y,z", QQ)[0] assert ring("x,y,z", ZZ)[0] is not ring("x,y,z", QQ)[0] assert ring("x,y,z", QQ)[0] != ring("x,y", QQ)[0] assert ring("x,y,z", QQ)[0] is not ring("x,y", QQ)[0] assert ring("x,y", QQ)[0] != ring("x,y,z", QQ)[0] assert ring("x,y", QQ)[0] is not ring("x,y,z", QQ)[0] def test_PolyRing_ring_new(): R, x, y, z = ring("x,y,z", QQ) assert R.ring_new(7) == R(7) assert R.ring_new(7*x*y*z) == 7*x*y*z f = x**2 + 2*x*y + 3*x + 4*z**2 + 5*z + 6 assert R.ring_new([[[1]], [[2], [3]], [[4, 5, 6]]]) == f assert R.ring_new({(2, 0, 0): 1, (1, 1, 0): 2, (1, 0, 0): 3, (0, 0, 2): 4, (0, 0, 1): 5, (0, 0, 0): 6}) == f assert R.ring_new([((2, 0, 0), 1), ((1, 1, 0), 2), ((1, 0, 0), 3), ((0, 0, 2), 4), ((0, 0, 1), 5), ((0, 0, 0), 6)]) == f R, = ring("", QQ) assert R.ring_new([((), 7)]) == R(7) def test_PolyRing_drop(): R, x,y,z = ring("x,y,z", ZZ) assert R.drop(x) == PolyRing("y,z", ZZ, lex) assert R.drop(y) == PolyRing("x,z", ZZ, lex) assert R.drop(z) == PolyRing("x,y", ZZ, lex) assert R.drop(0) == PolyRing("y,z", ZZ, lex) assert R.drop(0).drop(0) == PolyRing("z", ZZ, lex) assert R.drop(0).drop(0).drop(0) == ZZ assert R.drop(1) == PolyRing("x,z", ZZ, lex) assert R.drop(2) == PolyRing("x,y", ZZ, lex) assert R.drop(2).drop(1) == PolyRing("x", ZZ, lex) assert R.drop(2).drop(1).drop(0) == ZZ raises(ValueError, lambda: R.drop(3)) raises(ValueError, lambda: R.drop(x).drop(y)) def test_PolyRing___getitem__(): R, x,y,z = ring("x,y,z", ZZ) assert R[0:] == PolyRing("x,y,z", ZZ, lex) assert R[1:] == PolyRing("y,z", ZZ, lex) assert R[2:] == PolyRing("z", ZZ, lex) assert R[3:] == ZZ def test_PolyRing_is_(): R = PolyRing("x", QQ, lex) assert R.is_univariate is True assert R.is_multivariate is False R = PolyRing("x,y,z", QQ, lex) assert R.is_univariate is False assert R.is_multivariate is True R = PolyRing("", QQ, lex) assert R.is_univariate is False assert R.is_multivariate is False def test_PolyRing_add(): R, x = ring("x", ZZ) F = [ x**2 + 2*i + 3 for i in range(4) ] assert R.add(F) == reduce(add, F) == 4*x**2 + 24 R, = ring("", ZZ) assert R.add([2, 5, 7]) == 14 def test_PolyRing_mul(): R, x = ring("x", ZZ) F = [ x**2 + 2*i + 3 for i in range(4) ] assert R.mul(F) == reduce(mul, F) == x**8 + 24*x**6 + 206*x**4 + 744*x**2 + 945 R, = ring("", ZZ) assert R.mul([2, 3, 5]) == 30 def test_PolyRing_symmetric_poly(): R, x, y, z, t = ring("x,y,z,t", ZZ) raises(ValueError, lambda: R.symmetric_poly(-1)) raises(ValueError, lambda: R.symmetric_poly(5)) assert R.symmetric_poly(0) == R.one assert R.symmetric_poly(1) == x + y + z + t assert R.symmetric_poly(2) == x*y + x*z + x*t + y*z + y*t + z*t assert R.symmetric_poly(3) == x*y*z + x*y*t + x*z*t + y*z*t assert R.symmetric_poly(4) == x*y*z*t def test_sring(): x, y, z, t = symbols("x,y,z,t") R = PolyRing("x,y,z", ZZ, lex) assert sring(x + 2*y + 3*z) == (R, R.x + 2*R.y + 3*R.z) R = PolyRing("x,y,z", QQ, lex) assert sring(x + 2*y + z/3) == (R, R.x + 2*R.y + R.z/3) assert sring([x, 2*y, z/3]) == (R, [R.x, 2*R.y, R.z/3]) Rt = PolyRing("t", ZZ, lex) R = PolyRing("x,y,z", Rt, lex) assert sring(x + 2*t*y + 3*t**2*z, x, y, z) == (R, R.x + 2*Rt.t*R.y + 3*Rt.t**2*R.z) Rt = PolyRing("t", QQ, lex) R = PolyRing("x,y,z", Rt, lex) assert sring(x + t*y/2 + t**2*z/3, x, y, z) == (R, R.x + Rt.t*R.y/2 + Rt.t**2*R.z/3) Rt = FracField("t", ZZ, lex) R = PolyRing("x,y,z", Rt, lex) assert sring(x + 2*y/t + t**2*z/3, x, y, z) == (R, R.x + 2*R.y/Rt.t + Rt.t**2*R.z/3) r = sqrt(2) - sqrt(3) R, a = sring(r, extension=True) assert R.domain == QQ.algebraic_field(sqrt(2) + sqrt(3)) assert R.gens == () assert a == R.domain.from_sympy(r) def test_PolyElement___hash__(): R, x, y, z = ring("x,y,z", QQ) assert hash(x*y*z) def test_PolyElement___eq__(): R, x, y = ring("x,y", ZZ, lex) assert ((x*y + 5*x*y) == 6) == False assert ((x*y + 5*x*y) == 6*x*y) == True assert (6 == (x*y + 5*x*y)) == False assert (6*x*y == (x*y + 5*x*y)) == True assert ((x*y - x*y) == 0) == True assert (0 == (x*y - x*y)) == True assert ((x*y - x*y) == 1) == False assert (1 == (x*y - x*y)) == False assert ((x*y - x*y) == 1) == False assert (1 == (x*y - x*y)) == False assert ((x*y + 5*x*y) != 6) == True assert ((x*y + 5*x*y) != 6*x*y) == False assert (6 != (x*y + 5*x*y)) == True assert (6*x*y != (x*y + 5*x*y)) == False assert ((x*y - x*y) != 0) == False assert (0 != (x*y - x*y)) == False assert ((x*y - x*y) != 1) == True assert (1 != (x*y - x*y)) == True assert R.one == QQ(1, 1) == R.one assert R.one == 1 == R.one Rt, t = ring("t", ZZ) R, x, y = ring("x,y", Rt) assert (t**3*x/x == t**3) == True assert (t**3*x/x == t**4) == False def test_PolyElement__lt_le_gt_ge__(): R, x, y = ring("x,y", ZZ) assert R(1) < x < x**2 < x**3 assert R(1) <= x <= x**2 <= x**3 assert x**3 > x**2 > x > R(1) assert x**3 >= x**2 >= x >= R(1) def test_PolyElement__str__(): x, y = symbols('x, y') for dom in [ZZ, QQ, ZZ[x], ZZ[x,y], ZZ[x][y]]: R, t = ring('t', dom) assert str(2*t**2 + 1) == '2*t**2 + 1' for dom in [EX, EX[x]]: R, t = ring('t', dom) assert str(2*t**2 + 1) == 'EX(2)*t**2 + EX(1)' def test_PolyElement_copy(): R, x, y, z = ring("x,y,z", ZZ) f = x*y + 3*z g = f.copy() assert f == g g[(1, 1, 1)] = 7 assert f != g def test_PolyElement_as_expr(): R, x, y, z = ring("x,y,z", ZZ) f = 3*x**2*y - x*y*z + 7*z**3 + 1 X, Y, Z = R.symbols g = 3*X**2*Y - X*Y*Z + 7*Z**3 + 1 assert f != g assert f.as_expr() == g U, V, W = symbols("u,v,w") g = 3*U**2*V - U*V*W + 7*W**3 + 1 assert f != g assert f.as_expr(U, V, W) == g raises(ValueError, lambda: f.as_expr(X)) R, = ring("", ZZ) assert R(3).as_expr() == 3 def test_PolyElement_from_expr(): x, y, z = symbols("x,y,z") R, X, Y, Z = ring((x, y, z), ZZ) f = R.from_expr(1) assert f == 1 and isinstance(f, R.dtype) f = R.from_expr(x) assert f == X and isinstance(f, R.dtype) f = R.from_expr(x*y*z) assert f == X*Y*Z and isinstance(f, R.dtype) f = R.from_expr(x*y*z + x*y + x) assert f == X*Y*Z + X*Y + X and isinstance(f, R.dtype) f = R.from_expr(x**3*y*z + x**2*y**7 + 1) assert f == X**3*Y*Z + X**2*Y**7 + 1 and isinstance(f, R.dtype) r, F = sring([exp(2)]) f = r.from_expr(exp(2)) assert f == F[0] and isinstance(f, r.dtype) raises(ValueError, lambda: R.from_expr(1/x)) raises(ValueError, lambda: R.from_expr(2**x)) raises(ValueError, lambda: R.from_expr(7*x + sqrt(2))) R, = ring("", ZZ) f = R.from_expr(1) assert f == 1 and isinstance(f, R.dtype) def test_PolyElement_degree(): R, x,y,z = ring("x,y,z", ZZ) assert R(0).degree() is -oo assert R(1).degree() == 0 assert (x + 1).degree() == 1 assert (2*y**3 + z).degree() == 0 assert (x*y**3 + z).degree() == 1 assert (x**5*y**3 + z).degree() == 5 assert R(0).degree(x) is -oo assert R(1).degree(x) == 0 assert (x + 1).degree(x) == 1 assert (2*y**3 + z).degree(x) == 0 assert (x*y**3 + z).degree(x) == 1 assert (7*x**5*y**3 + z).degree(x) == 5 assert R(0).degree(y) is -oo assert R(1).degree(y) == 0 assert (x + 1).degree(y) == 0 assert (2*y**3 + z).degree(y) == 3 assert (x*y**3 + z).degree(y) == 3 assert (7*x**5*y**3 + z).degree(y) == 3 assert R(0).degree(z) is -oo assert R(1).degree(z) == 0 assert (x + 1).degree(z) == 0 assert (2*y**3 + z).degree(z) == 1 assert (x*y**3 + z).degree(z) == 1 assert (7*x**5*y**3 + z).degree(z) == 1 R, = ring("", ZZ) assert R(0).degree() is -oo assert R(1).degree() == 0 def test_PolyElement_tail_degree(): R, x,y,z = ring("x,y,z", ZZ) assert R(0).tail_degree() is -oo assert R(1).tail_degree() == 0 assert (x + 1).tail_degree() == 0 assert (2*y**3 + x**3*z).tail_degree() == 0 assert (x*y**3 + x**3*z).tail_degree() == 1 assert (x**5*y**3 + x**3*z).tail_degree() == 3 assert R(0).tail_degree(x) is -oo assert R(1).tail_degree(x) == 0 assert (x + 1).tail_degree(x) == 0 assert (2*y**3 + x**3*z).tail_degree(x) == 0 assert (x*y**3 + x**3*z).tail_degree(x) == 1 assert (7*x**5*y**3 + x**3*z).tail_degree(x) == 3 assert R(0).tail_degree(y) is -oo assert R(1).tail_degree(y) == 0 assert (x + 1).tail_degree(y) == 0 assert (2*y**3 + x**3*z).tail_degree(y) == 0 assert (x*y**3 + x**3*z).tail_degree(y) == 0 assert (7*x**5*y**3 + x**3*z).tail_degree(y) == 0 assert R(0).tail_degree(z) is -oo assert R(1).tail_degree(z) == 0 assert (x + 1).tail_degree(z) == 0 assert (2*y**3 + x**3*z).tail_degree(z) == 0 assert (x*y**3 + x**3*z).tail_degree(z) == 0 assert (7*x**5*y**3 + x**3*z).tail_degree(z) == 0 R, = ring("", ZZ) assert R(0).tail_degree() is -oo assert R(1).tail_degree() == 0 def test_PolyElement_degrees(): R, x,y,z = ring("x,y,z", ZZ) assert R(0).degrees() == (-oo, -oo, -oo) assert R(1).degrees() == (0, 0, 0) assert (x**2*y + x**3*z**2).degrees() == (3, 1, 2) def test_PolyElement_tail_degrees(): R, x,y,z = ring("x,y,z", ZZ) assert R(0).tail_degrees() == (-oo, -oo, -oo) assert R(1).tail_degrees() == (0, 0, 0) assert (x**2*y + x**3*z**2).tail_degrees() == (2, 0, 0) def test_PolyElement_coeff(): R, x, y, z = ring("x,y,z", ZZ, lex) f = 3*x**2*y - x*y*z + 7*z**3 + 23 assert f.coeff(1) == 23 raises(ValueError, lambda: f.coeff(3)) assert f.coeff(x) == 0 assert f.coeff(y) == 0 assert f.coeff(z) == 0 assert f.coeff(x**2*y) == 3 assert f.coeff(x*y*z) == -1 assert f.coeff(z**3) == 7 raises(ValueError, lambda: f.coeff(3*x**2*y)) raises(ValueError, lambda: f.coeff(-x*y*z)) raises(ValueError, lambda: f.coeff(7*z**3)) R, = ring("", ZZ) assert R(3).coeff(1) == 3 def test_PolyElement_LC(): R, x, y = ring("x,y", QQ, lex) assert R(0).LC == QQ(0) assert (QQ(1,2)*x).LC == QQ(1, 2) assert (QQ(1,4)*x*y + QQ(1,2)*x).LC == QQ(1, 4) def test_PolyElement_LM(): R, x, y = ring("x,y", QQ, lex) assert R(0).LM == (0, 0) assert (QQ(1,2)*x).LM == (1, 0) assert (QQ(1,4)*x*y + QQ(1,2)*x).LM == (1, 1) def test_PolyElement_LT(): R, x, y = ring("x,y", QQ, lex) assert R(0).LT == ((0, 0), QQ(0)) assert (QQ(1,2)*x).LT == ((1, 0), QQ(1, 2)) assert (QQ(1,4)*x*y + QQ(1,2)*x).LT == ((1, 1), QQ(1, 4)) R, = ring("", ZZ) assert R(0).LT == ((), 0) assert R(1).LT == ((), 1) def test_PolyElement_leading_monom(): R, x, y = ring("x,y", QQ, lex) assert R(0).leading_monom() == 0 assert (QQ(1,2)*x).leading_monom() == x assert (QQ(1,4)*x*y + QQ(1,2)*x).leading_monom() == x*y def test_PolyElement_leading_term(): R, x, y = ring("x,y", QQ, lex) assert R(0).leading_term() == 0 assert (QQ(1,2)*x).leading_term() == QQ(1,2)*x assert (QQ(1,4)*x*y + QQ(1,2)*x).leading_term() == QQ(1,4)*x*y def test_PolyElement_terms(): R, x,y,z = ring("x,y,z", QQ) terms = (x**2/3 + y**3/4 + z**4/5).terms() assert terms == [((2,0,0), QQ(1,3)), ((0,3,0), QQ(1,4)), ((0,0,4), QQ(1,5))] R, x,y = ring("x,y", ZZ, lex) f = x*y**7 + 2*x**2*y**3 assert f.terms() == f.terms(lex) == f.terms('lex') == [((2, 3), 2), ((1, 7), 1)] assert f.terms(grlex) == f.terms('grlex') == [((1, 7), 1), ((2, 3), 2)] R, x,y = ring("x,y", ZZ, grlex) f = x*y**7 + 2*x**2*y**3 assert f.terms() == f.terms(grlex) == f.terms('grlex') == [((1, 7), 1), ((2, 3), 2)] assert f.terms(lex) == f.terms('lex') == [((2, 3), 2), ((1, 7), 1)] R, = ring("", ZZ) assert R(3).terms() == [((), 3)] def test_PolyElement_monoms(): R, x,y,z = ring("x,y,z", QQ) monoms = (x**2/3 + y**3/4 + z**4/5).monoms() assert monoms == [(2,0,0), (0,3,0), (0,0,4)] R, x,y = ring("x,y", ZZ, lex) f = x*y**7 + 2*x**2*y**3 assert f.monoms() == f.monoms(lex) == f.monoms('lex') == [(2, 3), (1, 7)] assert f.monoms(grlex) == f.monoms('grlex') == [(1, 7), (2, 3)] R, x,y = ring("x,y", ZZ, grlex) f = x*y**7 + 2*x**2*y**3 assert f.monoms() == f.monoms(grlex) == f.monoms('grlex') == [(1, 7), (2, 3)] assert f.monoms(lex) == f.monoms('lex') == [(2, 3), (1, 7)] def test_PolyElement_coeffs(): R, x,y,z = ring("x,y,z", QQ) coeffs = (x**2/3 + y**3/4 + z**4/5).coeffs() assert coeffs == [QQ(1,3), QQ(1,4), QQ(1,5)] R, x,y = ring("x,y", ZZ, lex) f = x*y**7 + 2*x**2*y**3 assert f.coeffs() == f.coeffs(lex) == f.coeffs('lex') == [2, 1] assert f.coeffs(grlex) == f.coeffs('grlex') == [1, 2] R, x,y = ring("x,y", ZZ, grlex) f = x*y**7 + 2*x**2*y**3 assert f.coeffs() == f.coeffs(grlex) == f.coeffs('grlex') == [1, 2] assert f.coeffs(lex) == f.coeffs('lex') == [2, 1] def test_PolyElement___add__(): Rt, t = ring("t", ZZ) Ruv, u,v = ring("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Ruv) assert dict(x + 3*y) == {(1, 0, 0): 1, (0, 1, 0): 3} assert dict(u + x) == dict(x + u) == {(1, 0, 0): 1, (0, 0, 0): u} assert dict(u + x*y) == dict(x*y + u) == {(1, 1, 0): 1, (0, 0, 0): u} assert dict(u + x*y + z) == dict(x*y + z + u) == {(1, 1, 0): 1, (0, 0, 1): 1, (0, 0, 0): u} assert dict(u*x + x) == dict(x + u*x) == {(1, 0, 0): u + 1} assert dict(u*x + x*y) == dict(x*y + u*x) == {(1, 1, 0): 1, (1, 0, 0): u} assert dict(u*x + x*y + z) == dict(x*y + z + u*x) == {(1, 1, 0): 1, (0, 0, 1): 1, (1, 0, 0): u} raises(TypeError, lambda: t + x) raises(TypeError, lambda: x + t) raises(TypeError, lambda: t + u) raises(TypeError, lambda: u + t) Fuv, u,v = field("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Fuv) assert dict(u + x) == dict(x + u) == {(1, 0, 0): 1, (0, 0, 0): u} Rxyz, x,y,z = ring("x,y,z", EX) assert dict(EX(pi) + x*y*z) == dict(x*y*z + EX(pi)) == {(1, 1, 1): EX(1), (0, 0, 0): EX(pi)} def test_PolyElement___sub__(): Rt, t = ring("t", ZZ) Ruv, u,v = ring("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Ruv) assert dict(x - 3*y) == {(1, 0, 0): 1, (0, 1, 0): -3} assert dict(-u + x) == dict(x - u) == {(1, 0, 0): 1, (0, 0, 0): -u} assert dict(-u + x*y) == dict(x*y - u) == {(1, 1, 0): 1, (0, 0, 0): -u} assert dict(-u + x*y + z) == dict(x*y + z - u) == {(1, 1, 0): 1, (0, 0, 1): 1, (0, 0, 0): -u} assert dict(-u*x + x) == dict(x - u*x) == {(1, 0, 0): -u + 1} assert dict(-u*x + x*y) == dict(x*y - u*x) == {(1, 1, 0): 1, (1, 0, 0): -u} assert dict(-u*x + x*y + z) == dict(x*y + z - u*x) == {(1, 1, 0): 1, (0, 0, 1): 1, (1, 0, 0): -u} raises(TypeError, lambda: t - x) raises(TypeError, lambda: x - t) raises(TypeError, lambda: t - u) raises(TypeError, lambda: u - t) Fuv, u,v = field("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Fuv) assert dict(-u + x) == dict(x - u) == {(1, 0, 0): 1, (0, 0, 0): -u} Rxyz, x,y,z = ring("x,y,z", EX) assert dict(-EX(pi) + x*y*z) == dict(x*y*z - EX(pi)) == {(1, 1, 1): EX(1), (0, 0, 0): -EX(pi)} def test_PolyElement___mul__(): Rt, t = ring("t", ZZ) Ruv, u,v = ring("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Ruv) assert dict(u*x) == dict(x*u) == {(1, 0, 0): u} assert dict(2*u*x + z) == dict(x*2*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1} assert dict(u*2*x + z) == dict(2*x*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1} assert dict(2*u*x + z) == dict(x*2*u + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1} assert dict(u*x*2 + z) == dict(x*u*2 + z) == {(1, 0, 0): 2*u, (0, 0, 1): 1} assert dict(2*u*x*y + z) == dict(x*y*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(u*2*x*y + z) == dict(2*x*y*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(2*u*x*y + z) == dict(x*y*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(u*x*y*2 + z) == dict(x*y*u*2 + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(2*u*y*x + z) == dict(y*x*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(u*2*y*x + z) == dict(2*y*x*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(2*u*y*x + z) == dict(y*x*2*u + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(u*y*x*2 + z) == dict(y*x*u*2 + z) == {(1, 1, 0): 2*u, (0, 0, 1): 1} assert dict(3*u*(x + y) + z) == dict((x + y)*3*u + z) == {(1, 0, 0): 3*u, (0, 1, 0): 3*u, (0, 0, 1): 1} raises(TypeError, lambda: t*x + z) raises(TypeError, lambda: x*t + z) raises(TypeError, lambda: t*u + z) raises(TypeError, lambda: u*t + z) Fuv, u,v = field("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Fuv) assert dict(u*x) == dict(x*u) == {(1, 0, 0): u} Rxyz, x,y,z = ring("x,y,z", EX) assert dict(EX(pi)*x*y*z) == dict(x*y*z*EX(pi)) == {(1, 1, 1): EX(pi)} def test_PolyElement___truediv__(): R, x,y,z = ring("x,y,z", ZZ) assert (2*x**2 - 4)/2 == x**2 - 2 assert (2*x**2 - 3)/2 == x**2 assert (x**2 - 1).quo(x) == x assert (x**2 - x).quo(x) == x - 1 assert (x**2 - 1)/x == x - x**(-1) assert (x**2 - x)/x == x - 1 assert (x**2 - 1)/(2*x) == x/2 - x**(-1)/2 assert (x**2 - 1).quo(2*x) == 0 assert (x**2 - x)/(x - 1) == (x**2 - x).quo(x - 1) == x R, x,y,z = ring("x,y,z", ZZ) assert len((x**2/3 + y**3/4 + z**4/5).terms()) == 0 R, x,y,z = ring("x,y,z", QQ) assert len((x**2/3 + y**3/4 + z**4/5).terms()) == 3 Rt, t = ring("t", ZZ) Ruv, u,v = ring("u,v", ZZ) Rxyz, x,y,z = ring("x,y,z", Ruv) assert dict((u**2*x + u)/u) == {(1, 0, 0): u, (0, 0, 0): 1} raises(TypeError, lambda: u/(u**2*x + u)) raises(TypeError, lambda: t/x) raises(TypeError, lambda: x/t) raises(TypeError, lambda: t/u) raises(TypeError, lambda: u/t) R, x = ring("x", ZZ) f, g = x**2 + 2*x + 3, R(0) raises(ZeroDivisionError, lambda: f.div(g)) raises(ZeroDivisionError, lambda: divmod(f, g)) raises(ZeroDivisionError, lambda: f.rem(g)) raises(ZeroDivisionError, lambda: f % g) raises(ZeroDivisionError, lambda: f.quo(g)) raises(ZeroDivisionError, lambda: f / g) raises(ZeroDivisionError, lambda: f.exquo(g)) R, x, y = ring("x,y", ZZ) f, g = x*y + 2*x + 3, R(0) raises(ZeroDivisionError, lambda: f.div(g)) raises(ZeroDivisionError, lambda: divmod(f, g)) raises(ZeroDivisionError, lambda: f.rem(g)) raises(ZeroDivisionError, lambda: f % g) raises(ZeroDivisionError, lambda: f.quo(g)) raises(ZeroDivisionError, lambda: f / g) raises(ZeroDivisionError, lambda: f.exquo(g)) R, x = ring("x", ZZ) f, g = x**2 + 1, 2*x - 4 q, r = R(0), x**2 + 1 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = 3*x**3 + x**2 + x + 5, 5*x**2 - 3*x + 1 q, r = R(0), f assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = 5*x**4 + 4*x**3 + 3*x**2 + 2*x + 1, x**2 + 2*x + 3 q, r = 5*x**2 - 6*x, 20*x + 1 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = 5*x**5 + 4*x**4 + 3*x**3 + 2*x**2 + x, x**4 + 2*x**3 + 9 q, r = 5*x - 6, 15*x**3 + 2*x**2 - 44*x + 54 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) R, x = ring("x", QQ) f, g = x**2 + 1, 2*x - 4 q, r = x/2 + 1, R(5) assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = 3*x**3 + x**2 + x + 5, 5*x**2 - 3*x + 1 q, r = QQ(3, 5)*x + QQ(14, 25), QQ(52, 25)*x + QQ(111, 25) assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) R, x,y = ring("x,y", ZZ) f, g = x**2 - y**2, x - y q, r = x + y, R(0) assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q assert f.exquo(g) == q f, g = x**2 + y**2, x - y q, r = x + y, 2*y**2 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = x**2 + y**2, -x + y q, r = -x - y, 2*y**2 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = x**2 + y**2, 2*x - 2*y q, r = R(0), f assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) R, x,y = ring("x,y", QQ) f, g = x**2 - y**2, x - y q, r = x + y, R(0) assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q assert f.exquo(g) == q f, g = x**2 + y**2, x - y q, r = x + y, 2*y**2 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = x**2 + y**2, -x + y q, r = -x - y, 2*y**2 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) f, g = x**2 + y**2, 2*x - 2*y q, r = x/2 + y/2, 2*y**2 assert f.div(g) == divmod(f, g) == (q, r) assert f.rem(g) == f % g == r assert f.quo(g) == f / g == q raises(ExactQuotientFailed, lambda: f.exquo(g)) def test_PolyElement___pow__(): R, x = ring("x", ZZ, grlex) f = 2*x + 3 assert f**0 == 1 assert f**1 == f raises(ValueError, lambda: f**(-1)) assert x**(-1) == x**(-1) assert f**2 == f._pow_generic(2) == f._pow_multinomial(2) == 4*x**2 + 12*x + 9 assert f**3 == f._pow_generic(3) == f._pow_multinomial(3) == 8*x**3 + 36*x**2 + 54*x + 27 assert f**4 == f._pow_generic(4) == f._pow_multinomial(4) == 16*x**4 + 96*x**3 + 216*x**2 + 216*x + 81 assert f**5 == f._pow_generic(5) == f._pow_multinomial(5) == 32*x**5 + 240*x**4 + 720*x**3 + 1080*x**2 + 810*x + 243 R, x,y,z = ring("x,y,z", ZZ, grlex) f = x**3*y - 2*x*y**2 - 3*z + 1 g = x**6*y**2 - 4*x**4*y**3 - 6*x**3*y*z + 2*x**3*y + 4*x**2*y**4 + 12*x*y**2*z - 4*x*y**2 + 9*z**2 - 6*z + 1 assert f**2 == f._pow_generic(2) == f._pow_multinomial(2) == g R, t = ring("t", ZZ) f = -11200*t**4 - 2604*t**2 + 49 g = 15735193600000000*t**16 + 14633730048000000*t**14 + 4828147466240000*t**12 \ + 598976863027200*t**10 + 3130812416256*t**8 - 2620523775744*t**6 \ + 92413760096*t**4 - 1225431984*t**2 + 5764801 assert f**4 == f._pow_generic(4) == f._pow_multinomial(4) == g def test_PolyElement_div(): R, x = ring("x", ZZ, grlex) f = x**3 - 12*x**2 - 42 g = x - 3 q = x**2 - 9*x - 27 r = -123 assert f.div([g]) == ([q], r) R, x = ring("x", ZZ, grlex) f = x**2 + 2*x + 2 assert f.div([R(1)]) == ([f], 0) R, x = ring("x", QQ, grlex) f = x**2 + 2*x + 2 assert f.div([R(2)]) == ([QQ(1,2)*x**2 + x + 1], 0) R, x,y = ring("x,y", ZZ, grlex) f = 4*x**2*y - 2*x*y + 4*x - 2*y + 8 assert f.div([R(2)]) == ([2*x**2*y - x*y + 2*x - y + 4], 0) assert f.div([2*y]) == ([2*x**2 - x - 1], 4*x + 8) f = x - 1 g = y - 1 assert f.div([g]) == ([0], f) f = x*y**2 + 1 G = [x*y + 1, y + 1] Q = [y, -1] r = 2 assert f.div(G) == (Q, r) f = x**2*y + x*y**2 + y**2 G = [x*y - 1, y**2 - 1] Q = [x + y, 1] r = x + y + 1 assert f.div(G) == (Q, r) G = [y**2 - 1, x*y - 1] Q = [x + 1, x] r = 2*x + 1 assert f.div(G) == (Q, r) R, = ring("", ZZ) assert R(3).div(R(2)) == (0, 3) R, = ring("", QQ) assert R(3).div(R(2)) == (QQ(3, 2), 0) def test_PolyElement_rem(): R, x = ring("x", ZZ, grlex) f = x**3 - 12*x**2 - 42 g = x - 3 r = -123 assert f.rem([g]) == f.div([g])[1] == r R, x,y = ring("x,y", ZZ, grlex) f = 4*x**2*y - 2*x*y + 4*x - 2*y + 8 assert f.rem([R(2)]) == f.div([R(2)])[1] == 0 assert f.rem([2*y]) == f.div([2*y])[1] == 4*x + 8 f = x - 1 g = y - 1 assert f.rem([g]) == f.div([g])[1] == f f = x*y**2 + 1 G = [x*y + 1, y + 1] r = 2 assert f.rem(G) == f.div(G)[1] == r f = x**2*y + x*y**2 + y**2 G = [x*y - 1, y**2 - 1] r = x + y + 1 assert f.rem(G) == f.div(G)[1] == r G = [y**2 - 1, x*y - 1] r = 2*x + 1 assert f.rem(G) == f.div(G)[1] == r def test_PolyElement_deflate(): R, x = ring("x", ZZ) assert (2*x**2).deflate(x**4 + 4*x**2 + 1) == ((2,), [2*x, x**2 + 4*x + 1]) R, x,y = ring("x,y", ZZ) assert R(0).deflate(R(0)) == ((1, 1), [0, 0]) assert R(1).deflate(R(0)) == ((1, 1), [1, 0]) assert R(1).deflate(R(2)) == ((1, 1), [1, 2]) assert R(1).deflate(2*y) == ((1, 1), [1, 2*y]) assert (2*y).deflate(2*y) == ((1, 1), [2*y, 2*y]) assert R(2).deflate(2*y**2) == ((1, 2), [2, 2*y]) assert (2*y**2).deflate(2*y**2) == ((1, 2), [2*y, 2*y]) f = x**4*y**2 + x**2*y + 1 g = x**2*y**3 + x**2*y + 1 assert f.deflate(g) == ((2, 1), [x**2*y**2 + x*y + 1, x*y**3 + x*y + 1]) def test_PolyElement_clear_denoms(): R, x,y = ring("x,y", QQ) assert R(1).clear_denoms() == (ZZ(1), 1) assert R(7).clear_denoms() == (ZZ(1), 7) assert R(QQ(7,3)).clear_denoms() == (3, 7) assert R(QQ(7,3)).clear_denoms() == (3, 7) assert (3*x**2 + x).clear_denoms() == (1, 3*x**2 + x) assert (x**2 + QQ(1,2)*x).clear_denoms() == (2, 2*x**2 + x) rQQ, x,t = ring("x,t", QQ, lex) rZZ, X,T = ring("x,t", ZZ, lex) F = [x - QQ(17824537287975195925064602467992950991718052713078834557692023531499318507213727406844943097,413954288007559433755329699713866804710749652268151059918115348815925474842910720000)*t**7 - QQ(4882321164854282623427463828745855894130208215961904469205260756604820743234704900167747753,12936071500236232304854053116058337647210926633379720622441104650497671088840960000)*t**6 - QQ(36398103304520066098365558157422127347455927422509913596393052633155821154626830576085097433,25872143000472464609708106232116675294421853266759441244882209300995342177681920000)*t**5 - QQ(168108082231614049052707339295479262031324376786405372698857619250210703675982492356828810819,58212321751063045371843239022262519412449169850208742800984970927239519899784320000)*t**4 - QQ(5694176899498574510667890423110567593477487855183144378347226247962949388653159751849449037,1617008937529529038106756639507292205901365829172465077805138081312208886105120000)*t**3 - QQ(154482622347268833757819824809033388503591365487934245386958884099214649755244381307907779,60637835157357338929003373981523457721301218593967440417692678049207833228942000)*t**2 - QQ(2452813096069528207645703151222478123259511586701148682951852876484544822947007791153163,2425513406294293557160134959260938308852048743758697616707707121968313329157680)*t - QQ(34305265428126440542854669008203683099323146152358231964773310260498715579162112959703,202126117191191129763344579938411525737670728646558134725642260164026110763140), t**8 + QQ(693749860237914515552,67859264524169150569)*t**7 + QQ(27761407182086143225024,610733380717522355121)*t**6 + QQ(7785127652157884044288,67859264524169150569)*t**5 + QQ(36567075214771261409792,203577793572507451707)*t**4 + QQ(36336335165196147384320,203577793572507451707)*t**3 + QQ(7452455676042754048000,67859264524169150569)*t**2 + QQ(2593331082514399232000,67859264524169150569)*t + QQ(390399197427343360000,67859264524169150569)] G = [3725588592068034903797967297424801242396746870413359539263038139343329273586196480000*X - 160420835591776763325581422211936558925462474417709511019228211783493866564923546661604487873*T**7 - 1406108495478033395547109582678806497509499966197028487131115097902188374051595011248311352864*T**6 - 5241326875850889518164640374668786338033653548841427557880599579174438246266263602956254030352*T**5 - 10758917262823299139373269714910672770004760114329943852726887632013485035262879510837043892416*T**4 - 13119383576444715672578819534846747735372132018341964647712009275306635391456880068261130581248*T**3 - 9491412317016197146080450036267011389660653495578680036574753839055748080962214787557853941760*T**2 - 3767520915562795326943800040277726397326609797172964377014046018280260848046603967211258368000*T - 632314652371226552085897259159210286886724229880266931574701654721512325555116066073245696000, 610733380717522355121*T**8 + 6243748742141230639968*T**7 + 27761407182086143225024*T**6 + 70066148869420956398592*T**5 + 109701225644313784229376*T**4 + 109009005495588442152960*T**3 + 67072101084384786432000*T**2 + 23339979742629593088000*T + 3513592776846090240000] assert [ f.clear_denoms()[1].set_ring(rZZ) for f in F ] == G def test_PolyElement_cofactors(): R, x, y = ring("x,y", ZZ) f, g = R(0), R(0) assert f.cofactors(g) == (0, 0, 0) f, g = R(2), R(0) assert f.cofactors(g) == (2, 1, 0) f, g = R(-2), R(0) assert f.cofactors(g) == (2, -1, 0) f, g = R(0), R(-2) assert f.cofactors(g) == (2, 0, -1) f, g = R(0), 2*x + 4 assert f.cofactors(g) == (2*x + 4, 0, 1) f, g = 2*x + 4, R(0) assert f.cofactors(g) == (2*x + 4, 1, 0) f, g = R(2), R(2) assert f.cofactors(g) == (2, 1, 1) f, g = R(-2), R(2) assert f.cofactors(g) == (2, -1, 1) f, g = R(2), R(-2) assert f.cofactors(g) == (2, 1, -1) f, g = R(-2), R(-2) assert f.cofactors(g) == (2, -1, -1) f, g = x**2 + 2*x + 1, R(1) assert f.cofactors(g) == (1, x**2 + 2*x + 1, 1) f, g = x**2 + 2*x + 1, R(2) assert f.cofactors(g) == (1, x**2 + 2*x + 1, 2) f, g = 2*x**2 + 4*x + 2, R(2) assert f.cofactors(g) == (2, x**2 + 2*x + 1, 1) f, g = R(2), 2*x**2 + 4*x + 2 assert f.cofactors(g) == (2, 1, x**2 + 2*x + 1) f, g = 2*x**2 + 4*x + 2, x + 1 assert f.cofactors(g) == (x + 1, 2*x + 2, 1) f, g = x + 1, 2*x**2 + 4*x + 2 assert f.cofactors(g) == (x + 1, 1, 2*x + 2) R, x, y, z, t = ring("x,y,z,t", ZZ) f, g = t**2 + 2*t + 1, 2*t + 2 assert f.cofactors(g) == (t + 1, t + 1, 2) f, g = z**2*t**2 + 2*z**2*t + z**2 + z*t + z, t**2 + 2*t + 1 h, cff, cfg = t + 1, z**2*t + z**2 + z, t + 1 assert f.cofactors(g) == (h, cff, cfg) assert g.cofactors(f) == (h, cfg, cff) R, x, y = ring("x,y", QQ) f = QQ(1,2)*x**2 + x + QQ(1,2) g = QQ(1,2)*x + QQ(1,2) h = x + 1 assert f.cofactors(g) == (h, g, QQ(1,2)) assert g.cofactors(f) == (h, QQ(1,2), g) R, x, y = ring("x,y", RR) f = 2.1*x*y**2 - 2.1*x*y + 2.1*x g = 2.1*x**3 h = 1.0*x assert f.cofactors(g) == (h, f/h, g/h) assert g.cofactors(f) == (h, g/h, f/h) def test_PolyElement_gcd(): R, x, y = ring("x,y", QQ) f = QQ(1,2)*x**2 + x + QQ(1,2) g = QQ(1,2)*x + QQ(1,2) assert f.gcd(g) == x + 1 def test_PolyElement_cancel(): R, x, y = ring("x,y", ZZ) f = 2*x**3 + 4*x**2 + 2*x g = 3*x**2 + 3*x F = 2*x + 2 G = 3 assert f.cancel(g) == (F, G) assert (-f).cancel(g) == (-F, G) assert f.cancel(-g) == (-F, G) R, x, y = ring("x,y", QQ) f = QQ(1,2)*x**3 + x**2 + QQ(1,2)*x g = QQ(1,3)*x**2 + QQ(1,3)*x F = 3*x + 3 G = 2 assert f.cancel(g) == (F, G) assert (-f).cancel(g) == (-F, G) assert f.cancel(-g) == (-F, G) Fx, x = field("x", ZZ) Rt, t = ring("t", Fx) f = (-x**2 - 4)/4*t g = t**2 + (x**2 + 2)/2 assert f.cancel(g) == ((-x**2 - 4)*t, 4*t**2 + 2*x**2 + 4) def test_PolyElement_max_norm(): R, x, y = ring("x,y", ZZ) assert R(0).max_norm() == 0 assert R(1).max_norm() == 1 assert (x**3 + 4*x**2 + 2*x + 3).max_norm() == 4 def test_PolyElement_l1_norm(): R, x, y = ring("x,y", ZZ) assert R(0).l1_norm() == 0 assert R(1).l1_norm() == 1 assert (x**3 + 4*x**2 + 2*x + 3).l1_norm() == 10 def test_PolyElement_diff(): R, X = xring("x:11", QQ) f = QQ(288,5)*X[0]**8*X[1]**6*X[4]**3*X[10]**2 + 8*X[0]**2*X[2]**3*X[4]**3 +2*X[0]**2 - 2*X[1]**2 assert f.diff(X[0]) == QQ(2304,5)*X[0]**7*X[1]**6*X[4]**3*X[10]**2 + 16*X[0]*X[2]**3*X[4]**3 + 4*X[0] assert f.diff(X[4]) == QQ(864,5)*X[0]**8*X[1]**6*X[4]**2*X[10]**2 + 24*X[0]**2*X[2]**3*X[4]**2 assert f.diff(X[10]) == QQ(576,5)*X[0]**8*X[1]**6*X[4]**3*X[10] def test_PolyElement___call__(): R, x = ring("x", ZZ) f = 3*x + 1 assert f(0) == 1 assert f(1) == 4 raises(ValueError, lambda: f()) raises(ValueError, lambda: f(0, 1)) raises(CoercionFailed, lambda: f(QQ(1,7))) R, x,y = ring("x,y", ZZ) f = 3*x + y**2 + 1 assert f(0, 0) == 1 assert f(1, 7) == 53 Ry = R.drop(x) assert f(0) == Ry.y**2 + 1 assert f(1) == Ry.y**2 + 4 raises(ValueError, lambda: f()) raises(ValueError, lambda: f(0, 1, 2)) raises(CoercionFailed, lambda: f(1, QQ(1,7))) raises(CoercionFailed, lambda: f(QQ(1,7), 1)) raises(CoercionFailed, lambda: f(QQ(1,7), QQ(1,7))) def test_PolyElement_evaluate(): R, x = ring("x", ZZ) f = x**3 + 4*x**2 + 2*x + 3 r = f.evaluate(x, 0) assert r == 3 and not isinstance(r, PolyElement) raises(CoercionFailed, lambda: f.evaluate(x, QQ(1,7))) R, x, y, z = ring("x,y,z", ZZ) f = (x*y)**3 + 4*(x*y)**2 + 2*x*y + 3 r = f.evaluate(x, 0) assert r == 3 and isinstance(r, R.drop(x).dtype) r = f.evaluate([(x, 0), (y, 0)]) assert r == 3 and isinstance(r, R.drop(x, y).dtype) r = f.evaluate(y, 0) assert r == 3 and isinstance(r, R.drop(y).dtype) r = f.evaluate([(y, 0), (x, 0)]) assert r == 3 and isinstance(r, R.drop(y, x).dtype) r = f.evaluate([(x, 0), (y, 0), (z, 0)]) assert r == 3 and not isinstance(r, PolyElement) raises(CoercionFailed, lambda: f.evaluate([(x, 1), (y, QQ(1,7))])) raises(CoercionFailed, lambda: f.evaluate([(x, QQ(1,7)), (y, 1)])) raises(CoercionFailed, lambda: f.evaluate([(x, QQ(1,7)), (y, QQ(1,7))])) def test_PolyElement_subs(): R, x = ring("x", ZZ) f = x**3 + 4*x**2 + 2*x + 3 r = f.subs(x, 0) assert r == 3 and isinstance(r, R.dtype) raises(CoercionFailed, lambda: f.subs(x, QQ(1,7))) R, x, y, z = ring("x,y,z", ZZ) f = x**3 + 4*x**2 + 2*x + 3 r = f.subs(x, 0) assert r == 3 and isinstance(r, R.dtype) r = f.subs([(x, 0), (y, 0)]) assert r == 3 and isinstance(r, R.dtype) raises(CoercionFailed, lambda: f.subs([(x, 1), (y, QQ(1,7))])) raises(CoercionFailed, lambda: f.subs([(x, QQ(1,7)), (y, 1)])) raises(CoercionFailed, lambda: f.subs([(x, QQ(1,7)), (y, QQ(1,7))])) def test_PolyElement_symmetrize(): R, x, y = ring("x,y", ZZ) # Homogeneous, symmetric f = x**2 + y**2 sym, rem, m = f.symmetrize() assert rem == 0 assert sym.compose(m) + rem == f # Homogeneous, asymmetric f = x**2 - y**2 sym, rem, m = f.symmetrize() assert rem != 0 assert sym.compose(m) + rem == f # Inhomogeneous, symmetric f = x*y + 7 sym, rem, m = f.symmetrize() assert rem == 0 assert sym.compose(m) + rem == f # Inhomogeneous, asymmetric f = y + 7 sym, rem, m = f.symmetrize() assert rem != 0 assert sym.compose(m) + rem == f # Constant f = R.from_expr(3) sym, rem, m = f.symmetrize() assert rem == 0 assert sym.compose(m) + rem == f # Constant constructed from sring R, f = sring(3) sym, rem, m = f.symmetrize() assert rem == 0 assert sym.compose(m) + rem == f def test_PolyElement_compose(): R, x = ring("x", ZZ) f = x**3 + 4*x**2 + 2*x + 3 r = f.compose(x, 0) assert r == 3 and isinstance(r, R.dtype) assert f.compose(x, x) == f assert f.compose(x, x**2) == x**6 + 4*x**4 + 2*x**2 + 3 raises(CoercionFailed, lambda: f.compose(x, QQ(1,7))) R, x, y, z = ring("x,y,z", ZZ) f = x**3 + 4*x**2 + 2*x + 3 r = f.compose(x, 0) assert r == 3 and isinstance(r, R.dtype) r = f.compose([(x, 0), (y, 0)]) assert r == 3 and isinstance(r, R.dtype) r = (x**3 + 4*x**2 + 2*x*y*z + 3).compose(x, y*z**2 - 1) q = (y*z**2 - 1)**3 + 4*(y*z**2 - 1)**2 + 2*(y*z**2 - 1)*y*z + 3 assert r == q and isinstance(r, R.dtype) def test_PolyElement_is_(): R, x,y,z = ring("x,y,z", QQ) assert (x - x).is_generator == False assert (x - x).is_ground == True assert (x - x).is_monomial == True assert (x - x).is_term == True assert (x - x + 1).is_generator == False assert (x - x + 1).is_ground == True assert (x - x + 1).is_monomial == True assert (x - x + 1).is_term == True assert x.is_generator == True assert x.is_ground == False assert x.is_monomial == True assert x.is_term == True assert (x*y).is_generator == False assert (x*y).is_ground == False assert (x*y).is_monomial == True assert (x*y).is_term == True assert (3*x).is_generator == False assert (3*x).is_ground == False assert (3*x).is_monomial == False assert (3*x).is_term == True assert (3*x + 1).is_generator == False assert (3*x + 1).is_ground == False assert (3*x + 1).is_monomial == False assert (3*x + 1).is_term == False assert R(0).is_zero is True assert R(1).is_zero is False assert R(0).is_one is False assert R(1).is_one is True assert (x - 1).is_monic is True assert (2*x - 1).is_monic is False assert (3*x + 2).is_primitive is True assert (4*x + 2).is_primitive is False assert (x + y + z + 1).is_linear is True assert (x*y*z + 1).is_linear is False assert (x*y + z + 1).is_quadratic is True assert (x*y*z + 1).is_quadratic is False assert (x - 1).is_squarefree is True assert ((x - 1)**2).is_squarefree is False assert (x**2 + x + 1).is_irreducible is True assert (x**2 + 2*x + 1).is_irreducible is False _, t = ring("t", FF(11)) assert (7*t + 3).is_irreducible is True assert (7*t**2 + 3*t + 1).is_irreducible is False _, u = ring("u", ZZ) f = u**16 + u**14 - u**10 - u**8 - u**6 + u**2 assert f.is_cyclotomic is False assert (f + 1).is_cyclotomic is True raises(MultivariatePolynomialError, lambda: x.is_cyclotomic) R, = ring("", ZZ) assert R(4).is_squarefree is True assert R(6).is_irreducible is True def test_PolyElement_drop(): R, x,y,z = ring("x,y,z", ZZ) assert R(1).drop(0).ring == PolyRing("y,z", ZZ, lex) assert R(1).drop(0).drop(0).ring == PolyRing("z", ZZ, lex) assert isinstance(R(1).drop(0).drop(0).drop(0), R.dtype) is False raises(ValueError, lambda: z.drop(0).drop(0).drop(0)) raises(ValueError, lambda: x.drop(0)) def test_PolyElement_pdiv(): _, x, y = ring("x,y", ZZ) f, g = x**2 - y**2, x - y q, r = x + y, 0 assert f.pdiv(g) == (q, r) assert f.prem(g) == r assert f.pquo(g) == q assert f.pexquo(g) == q def test_PolyElement_gcdex(): _, x = ring("x", QQ) f, g = 2*x, x**2 - 16 s, t, h = x/32, -QQ(1, 16), 1 assert f.half_gcdex(g) == (s, h) assert f.gcdex(g) == (s, t, h) def test_PolyElement_subresultants(): _, x = ring("x", ZZ) f, g, h = x**2 - 2*x + 1, x**2 - 1, 2*x - 2 assert f.subresultants(g) == [f, g, h] def test_PolyElement_resultant(): _, x = ring("x", ZZ) f, g, h = x**2 - 2*x + 1, x**2 - 1, 0 assert f.resultant(g) == h def test_PolyElement_discriminant(): _, x = ring("x", ZZ) f, g = x**3 + 3*x**2 + 9*x - 13, -11664 assert f.discriminant() == g F, a, b, c = ring("a,b,c", ZZ) _, x = ring("x", F) f, g = a*x**2 + b*x + c, b**2 - 4*a*c assert f.discriminant() == g def test_PolyElement_decompose(): _, x = ring("x", ZZ) f = x**12 + 20*x**10 + 150*x**8 + 500*x**6 + 625*x**4 - 2*x**3 - 10*x + 9 g = x**4 - 2*x + 9 h = x**3 + 5*x assert g.compose(x, h) == f assert f.decompose() == [g, h] def test_PolyElement_shift(): _, x = ring("x", ZZ) assert (x**2 - 2*x + 1).shift(2) == x**2 + 2*x + 1 def test_PolyElement_sturm(): F, t = field("t", ZZ) _, x = ring("x", F) f = 1024/(15625*t**8)*x**5 - 4096/(625*t**8)*x**4 + 32/(15625*t**4)*x**3 - 128/(625*t**4)*x**2 + F(1)/62500*x - F(1)/625 assert f.sturm() == [ x**3 - 100*x**2 + t**4/64*x - 25*t**4/16, 3*x**2 - 200*x + t**4/64, (-t**4/96 + F(20000)/9)*x + 25*t**4/18, (-9*t**12 - 11520000*t**8 - 3686400000000*t**4)/(576*t**8 - 245760000*t**4 + 26214400000000), ] def test_PolyElement_gff_list(): _, x = ring("x", ZZ) f = x**5 + 2*x**4 - x**3 - 2*x**2 assert f.gff_list() == [(x, 1), (x + 2, 4)] f = x*(x - 1)**3*(x - 2)**2*(x - 4)**2*(x - 5) assert f.gff_list() == [(x**2 - 5*x + 4, 1), (x**2 - 5*x + 4, 2), (x, 3)] def test_PolyElement_sqf_norm(): R, x = ring("x", QQ.algebraic_field(sqrt(3))) X = R.to_ground().x assert (x**2 - 2).sqf_norm() == (1, x**2 - 2*sqrt(3)*x + 1, X**4 - 10*X**2 + 1) R, x = ring("x", QQ.algebraic_field(sqrt(2))) X = R.to_ground().x assert (x**2 - 3).sqf_norm() == (1, x**2 - 2*sqrt(2)*x - 1, X**4 - 10*X**2 + 1) def test_PolyElement_sqf_list(): _, x = ring("x", ZZ) f = x**5 - x**3 - x**2 + 1 g = x**3 + 2*x**2 + 2*x + 1 h = x - 1 p = x**4 + x**3 - x - 1 assert f.sqf_part() == p assert f.sqf_list() == (1, [(g, 1), (h, 2)]) def test_PolyElement_factor_list(): _, x = ring("x", ZZ) f = x**5 - x**3 - x**2 + 1 u = x + 1 v = x - 1 w = x**2 + x + 1 assert f.factor_list() == (1, [(u, 1), (v, 2), (w, 1)]) def test_issue_21410(): R, x = ring('x', FF(2)) p = x**6 + x**5 + x**4 + x**3 + 1 assert p._pow_multinomial(4) == x**24 + x**20 + x**16 + x**12 + 1
ee3571a4a6b141f1764ca80c886184b41ba2da9aacc2e053ce01bef7e19010a1
from sympy.ntheory import sieve, isprime from sympy.core.numbers import mod_inverse from sympy.core.power import integer_log from sympy.utilities.misc import as_int import random rgen = random.Random() #----------------------------------------------------------------------------# # # # Lenstra's Elliptic Curve Factorization # # # #----------------------------------------------------------------------------# class Point: """Montgomery form of Points in an elliptic curve. In this form, the addition and doubling of points does not need any y-coordinate information thus decreasing the number of operations. Using Montgomery form we try to perform point addition and doubling in least amount of multiplications. The elliptic curve used here is of the form (E : b*y**2*z = x**3 + a*x**2*z + x*z**2). The a_24 parameter is equal to (a + 2)/4. References ========== .. [1] http://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdf """ def __init__(self, x_cord, z_cord, a_24, mod): """ Initial parameters for the Point class. Parameters ========== x_cord : X coordinate of the Point z_cord : Z coordinate of the Point a_24 : Parameter of the elliptic curve in Montgomery form mod : modulus """ self.x_cord = x_cord self.z_cord = z_cord self.a_24 = a_24 self.mod = mod def __eq__(self, other): """Two points are equal if X/Z of both points are equal """ if self.a_24 != other.a_24 or self.mod != other.mod: return False return self.x_cord * other.z_cord % self.mod ==\ other.x_cord * self.z_cord % self.mod def add(self, Q, diff): """ Add two points self and Q where diff = self - Q. Moreover the assumption is self.x_cord*Q.x_cord*(self.x_cord - Q.x_cord) != 0. This algorithm requires 6 multiplications. Here the difference between the points is already known and using this algorithm speeds up the addition by reducing the number of multiplication required. Also in the mont_ladder algorithm is constructed in a way so that the difference between intermediate points is always equal to the initial point. So, we always know what the difference between the point is. Parameters ========== Q : point on the curve in Montgomery form diff : self - Q Examples ======== >>> from sympy.ntheory.ecm import Point >>> p1 = Point(11, 16, 7, 29) >>> p2 = Point(13, 10, 7, 29) >>> p3 = p2.add(p1, p1) >>> p3.x_cord 23 >>> p3.z_cord 17 """ u = (self.x_cord - self.z_cord)*(Q.x_cord + Q.z_cord) v = (self.x_cord + self.z_cord)*(Q.x_cord - Q.z_cord) add, subt = u + v, u - v x_cord = diff.z_cord * add * add % self.mod z_cord = diff.x_cord * subt * subt % self.mod return Point(x_cord, z_cord, self.a_24, self.mod) def double(self): """ Doubles a point in an elliptic curve in Montgomery form. This algorithm requires 5 multiplications. Examples ======== >>> from sympy.ntheory.ecm import Point >>> p1 = Point(11, 16, 7, 29) >>> p2 = p1.double() >>> p2.x_cord 13 >>> p2.z_cord 10 """ u = pow(self.x_cord + self.z_cord, 2, self.mod) v = pow(self.x_cord - self.z_cord, 2, self.mod) diff = u - v x_cord = u*v % self.mod z_cord = diff*(v + self.a_24*diff) % self.mod return Point(x_cord, z_cord, self.a_24, self.mod) def mont_ladder(self, k): """ Scalar multiplication of a point in Montgomery form using Montgomery Ladder Algorithm. A total of 11 multiplications are required in each step of this algorithm. Parameters ========== k : The positive integer multiplier Examples ======== >>> from sympy.ntheory.ecm import Point >>> p1 = Point(11, 16, 7, 29) >>> p3 = p1.mont_ladder(3) >>> p3.x_cord 23 >>> p3.z_cord 17 """ Q = self R = self.double() for i in bin(k)[3:]: if i == '1': Q = R.add(Q, self) R = R.double() else: R = Q.add(R, self) Q = Q.double() return Q def _ecm_one_factor(n, B1=10000, B2=100000, max_curve=200): """Returns one factor of n using Lenstra's 2 Stage Elliptic curve Factorization with Suyama's Parameterization. Here Montgomery arithmetic is used for fast computation of addition and doubling of points in elliptic curve. This ECM method considers elliptic curves in Montgomery form (E : b*y**2*z = x**3 + a*x**2*z + x*z**2) and involves elliptic curve operations (mod N), where the elements in Z are reduced (mod N). Since N is not a prime, E over FF(N) is not really an elliptic curve but we can still do point additions and doubling as if FF(N) was a field. Stage 1 : The basic algorithm involves taking a random point (P) on an elliptic curve in FF(N). The compute k*P using Montgomery ladder algorithm. Let q be an unknown factor of N. Then the order of the curve E, |E(FF(q))|, might be a smooth number that divides k. Then we have k = l * |E(FF(q))| for some l. For any point belonging to the curve E, |E(FF(q))|*P = O, hence k*P = l*|E(FF(q))|*P. Thus kP.z_cord = 0 (mod q), and the unknownn factor of N (q) can be recovered by taking gcd(kP.z_cord, N). Stage 2 : This is a continuation of Stage 1 if k*P != O. The idea utilize the fact that even if kP != 0, the value of k might miss just one large prime divisor of |E(FF(q))|. In this case we only need to compute the scalar multiplication by p to get p*k*P = O. Here a second bound B2 restrict the size of possible values of p. Parameters ========== n : Number to be Factored B1 : Stage 1 Bound B2 : Stage 2 Bound max_curve : Maximum number of curves generated References ========== .. [1] Carl Pomerance and Richard Crandall "Prime Numbers: A Computational Perspective" (2nd Ed.), page 344 """ n = as_int(n) if B1 % 2 != 0 or B2 % 2 != 0: raise ValueError("The Bounds should be an even integer") sieve.extend(B2) if isprime(n): return n from sympy.functions.elementary.miscellaneous import sqrt from sympy.polys.polytools import gcd D = int(sqrt(B2)) beta = [0]*(D + 1) S = [0]*(D + 1) k = 1 for p in sieve.primerange(1, B1 + 1): k *= pow(p, integer_log(B1, p)[0]) for _ in range(max_curve): #Suyama's Parametrization sigma = rgen.randint(6, n - 1) u = (sigma*sigma - 5) % n v = (4*sigma) % n diff = v - u u_3 = pow(u, 3, n) try: C = (pow(diff, 3, n)*(3*u + v)*mod_inverse(4*u_3*v, n) - 2) % n except ValueError: #If the mod_inverse(4*u_3*v, n) doesn't exist (i.e., g != 1) g = gcd(4*u_3*v, n) #If g = n, try another curve if g == n: continue return g a24 = (C + 2)*mod_inverse(4, n) % n Q = Point(u_3, pow(v, 3, n), a24, n) Q = Q.mont_ladder(k) g = gcd(Q.z_cord, n) #Stage 1 factor if g != 1 and g != n: return g #Stage 1 failure. Q.z = 0, Try another curve elif g == n: continue #Stage 2 - Improved Standard Continuation S[1] = Q.double() S[2] = S[1].double() beta[1] = (S[1].x_cord*S[1].z_cord) % n beta[2] = (S[2].x_cord*S[2].z_cord) % n for d in range(3, D + 1): S[d] = S[d - 1].add(S[1], S[d - 2]) beta[d] = (S[d].x_cord*S[d].z_cord) % n g = 1 B = B1 - 1 T = Q.mont_ladder(B - 2*D) R = Q.mont_ladder(B) for r in range(B, B2, 2*D): alpha = (R.x_cord*R.z_cord) % n for q in sieve.primerange(r + 2, r + 2*D + 1): delta = (q - r) // 2 # We want to calculate # f = R.x_cord * S[delta].z_cord - S[delta].x_cord * R.z_cord f = (R.x_cord - S[delta].x_cord)*\ (R.z_cord + S[delta].z_cord) - alpha + beta[delta] g = (g*f) % n #Swap T, R = R, R.add(S[D], T) g = gcd(n, g) #Stage 2 Factor found if g != 1 and g != n: return g #ECM failed, Increase the bounds raise ValueError("Increase the bounds") def ecm(n, B1=10000, B2=100000, max_curve=200, seed=1234): """Performs factorization using Lenstra's Elliptic curve method. This function repeatedly calls `ecm_one_factor` to compute the factors of n. First all the small factors are taken out using trial division. Then `ecm_one_factor` is used to compute one factor at a time. Parameters ========== n : Number to be Factored B1 : Stage 1 Bound B2 : Stage 2 Bound max_curve : Maximum number of curves generated seed : Initialize pseudorandom generator Examples ======== >>> from sympy.ntheory import ecm >>> ecm(25645121643901801) {5394769, 4753701529} >>> ecm(9804659461513846513) {4641991, 2112166839943} """ _factors = set() for prime in sieve.primerange(1, 100000): if n % prime == 0: _factors.add(prime) while(n % prime == 0): n //= prime rgen.seed(seed) while(n > 1): try: factor = _ecm_one_factor(n, B1, B2, max_curve) except ValueError: raise ValueError("Increase the bounds") _factors.add(factor) n //= factor factors = set() for factor in _factors: if isprime(factor): factors.add(factor) continue factors |= ecm(factor) return factors
5dcf4b68777a9cea71194d6980531d80a15563e7eaf2bb51f0afa4ae87a2257d
from __future__ import annotations from sympy.core.function import Function from sympy.core.numbers import igcd, igcdex, mod_inverse from sympy.core.power import isqrt from sympy.core.singleton import S from sympy.polys import Poly from sympy.polys.domains import ZZ from sympy.polys.galoistools import gf_crt1, gf_crt2, linear_congruence from .primetest import isprime from .factor_ import factorint, trailing, totient, multiplicity from sympy.utilities.misc import as_int from sympy.core.random import _randint, randint from itertools import cycle, product def n_order(a, n): """Returns the order of ``a`` modulo ``n``. The order of ``a`` modulo ``n`` is the smallest integer ``k`` such that ``a**k`` leaves a remainder of 1 with ``n``. Examples ======== >>> from sympy.ntheory import n_order >>> n_order(3, 7) 6 >>> n_order(4, 7) 3 """ from collections import defaultdict a, n = as_int(a), as_int(n) if igcd(a, n) != 1: raise ValueError("The two numbers should be relatively prime") factors = defaultdict(int) f = factorint(n) for px, kx in f.items(): if kx > 1: factors[px] += kx - 1 fpx = factorint(px - 1) for py, ky in fpx.items(): factors[py] += ky group_order = 1 for px, kx in factors.items(): group_order *= px**kx order = 1 if a > n: a = a % n for p, e in factors.items(): exponent = group_order for f in range(e + 1): if pow(a, exponent, n) != 1: order *= p ** (e - f + 1) break exponent = exponent // p return order def _primitive_root_prime_iter(p): """ Generates the primitive roots for a prime ``p`` Examples ======== >>> from sympy.ntheory.residue_ntheory import _primitive_root_prime_iter >>> list(_primitive_root_prime_iter(19)) [2, 3, 10, 13, 14, 15] References ========== .. [1] W. Stein "Elementary Number Theory" (2011), page 44 """ # it is assumed that p is an int v = [(p - 1) // i for i in factorint(p - 1).keys()] a = 2 while a < p: for pw in v: # a TypeError below may indicate that p was not an int if pow(a, pw, p) == 1: break else: yield a a += 1 def primitive_root(p): """ Returns the smallest primitive root or None. Parameters ========== p : positive integer Examples ======== >>> from sympy.ntheory.residue_ntheory import primitive_root >>> primitive_root(19) 2 References ========== .. [1] W. Stein "Elementary Number Theory" (2011), page 44 .. [2] P. Hackman "Elementary Number Theory" (2009), Chapter C """ p = as_int(p) if p < 1: raise ValueError('p is required to be positive') if p <= 2: return 1 f = factorint(p) if len(f) > 2: return None if len(f) == 2: if 2 not in f or f[2] > 1: return None # case p = 2*p1**k, p1 prime for p1, e1 in f.items(): if p1 != 2: break i = 1 while i < p: i += 2 if i % p1 == 0: continue if is_primitive_root(i, p): return i else: if 2 in f: if p == 4: return 3 return None p1, n = list(f.items())[0] if n > 1: # see Ref [2], page 81 g = primitive_root(p1) if is_primitive_root(g, p1**2): return g else: for i in range(2, g + p1 + 1): if igcd(i, p) == 1 and is_primitive_root(i, p): return i return next(_primitive_root_prime_iter(p)) def is_primitive_root(a, p): """ Returns True if ``a`` is a primitive root of ``p``. ``a`` is said to be the primitive root of ``p`` if gcd(a, p) == 1 and totient(p) is the smallest positive number s.t. a**totient(p) cong 1 mod(p) Examples ======== >>> from sympy.ntheory import is_primitive_root, n_order, totient >>> is_primitive_root(3, 10) True >>> is_primitive_root(9, 10) False >>> n_order(3, 10) == totient(10) True >>> n_order(9, 10) == totient(10) False """ a, p = as_int(a), as_int(p) if igcd(a, p) != 1: raise ValueError("The two numbers should be relatively prime") if a > p: a = a % p return n_order(a, p) == totient(p) def _sqrt_mod_tonelli_shanks(a, p): """ Returns the square root in the case of ``p`` prime with ``p == 1 (mod 8)`` References ========== .. [1] R. Crandall and C. Pomerance "Prime Numbers", 2nt Ed., page 101 """ s = trailing(p - 1) t = p >> s # find a non-quadratic residue while 1: d = randint(2, p - 1) r = legendre_symbol(d, p) if r == -1: break #assert legendre_symbol(d, p) == -1 A = pow(a, t, p) D = pow(d, t, p) m = 0 for i in range(s): adm = A*pow(D, m, p) % p adm = pow(adm, 2**(s - 1 - i), p) if adm % p == p - 1: m += 2**i #assert A*pow(D, m, p) % p == 1 x = pow(a, (t + 1)//2, p)*pow(D, m//2, p) % p return x def sqrt_mod(a, p, all_roots=False): """ Find a root of ``x**2 = a mod p``. Parameters ========== a : integer p : positive integer all_roots : if True the list of roots is returned or None Notes ===== If there is no root it is returned None; else the returned root is less or equal to ``p // 2``; in general is not the smallest one. It is returned ``p // 2`` only if it is the only root. Use ``all_roots`` only when it is expected that all the roots fit in memory; otherwise use ``sqrt_mod_iter``. Examples ======== >>> from sympy.ntheory import sqrt_mod >>> sqrt_mod(11, 43) 21 >>> sqrt_mod(17, 32, True) [7, 9, 23, 25] """ if all_roots: return sorted(list(sqrt_mod_iter(a, p))) try: p = abs(as_int(p)) it = sqrt_mod_iter(a, p) r = next(it) if r > p // 2: return p - r elif r < p // 2: return r else: try: r = next(it) if r > p // 2: return p - r except StopIteration: pass return r except StopIteration: return None def _product(*iters): """ Cartesian product generator Notes ===== Unlike itertools.product, it works also with iterables which do not fit in memory. See http://bugs.python.org/issue10109 Author: Fernando Sumudu with small changes """ inf_iters = tuple(cycle(enumerate(it)) for it in iters) num_iters = len(inf_iters) cur_val = [None]*num_iters first_v = True while True: i, p = 0, num_iters while p and not i: p -= 1 i, cur_val[p] = next(inf_iters[p]) if not p and not i: if first_v: first_v = False else: break yield cur_val def sqrt_mod_iter(a, p, domain=int): """ Iterate over solutions to ``x**2 = a mod p``. Parameters ========== a : integer p : positive integer domain : integer domain, ``int``, ``ZZ`` or ``Integer`` Examples ======== >>> from sympy.ntheory.residue_ntheory import sqrt_mod_iter >>> list(sqrt_mod_iter(11, 43)) [21, 22] """ a, p = as_int(a), abs(as_int(p)) if isprime(p): a = a % p if a == 0: res = _sqrt_mod1(a, p, 1) else: res = _sqrt_mod_prime_power(a, p, 1) if res: if domain is ZZ: yield from res else: for x in res: yield domain(x) else: f = factorint(p) v = [] pv = [] for px, ex in f.items(): if a % px == 0: rx = _sqrt_mod1(a, px, ex) if not rx: return else: rx = _sqrt_mod_prime_power(a, px, ex) if not rx: return v.append(rx) pv.append(px**ex) mm, e, s = gf_crt1(pv, ZZ) if domain is ZZ: for vx in _product(*v): r = gf_crt2(vx, pv, mm, e, s, ZZ) yield r else: for vx in _product(*v): r = gf_crt2(vx, pv, mm, e, s, ZZ) yield domain(r) def _sqrt_mod_prime_power(a, p, k): """ Find the solutions to ``x**2 = a mod p**k`` when ``a % p != 0`` Parameters ========== a : integer p : prime number k : positive integer Examples ======== >>> from sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power >>> _sqrt_mod_prime_power(11, 43, 1) [21, 22] References ========== .. [1] P. Hackman "Elementary Number Theory" (2009), page 160 .. [2] http://www.numbertheory.org/php/squareroot.html .. [3] [Gathen99]_ """ pk = p**k a = a % pk if k == 1: if p == 2: return [ZZ(a)] if not (a % p < 2 or pow(a, (p - 1) // 2, p) == 1): return None if p % 4 == 3: res = pow(a, (p + 1) // 4, p) elif p % 8 == 5: sign = pow(a, (p - 1) // 4, p) if sign == 1: res = pow(a, (p + 3) // 8, p) else: b = pow(4*a, (p - 5) // 8, p) x = (2*a*b) % p if pow(x, 2, p) == a: res = x else: res = _sqrt_mod_tonelli_shanks(a, p) # ``_sqrt_mod_tonelli_shanks(a, p)`` is not deterministic; # sort to get always the same result return sorted([ZZ(res), ZZ(p - res)]) if k > 1: # see Ref.[2] if p == 2: if a % 8 != 1: return None if k <= 3: s = set() for i in range(0, pk, 4): s.add(1 + i) s.add(-1 + i) return list(s) # according to Ref.[2] for k > 2 there are two solutions # (mod 2**k-1), that is four solutions (mod 2**k), which can be # obtained from the roots of x**2 = 0 (mod 8) rv = [ZZ(1), ZZ(3), ZZ(5), ZZ(7)] # hensel lift them to solutions of x**2 = 0 (mod 2**k) # if r**2 - a = 0 mod 2**nx but not mod 2**(nx+1) # then r + 2**(nx - 1) is a root mod 2**(nx+1) n = 3 res = [] for r in rv: nx = n while nx < k: r1 = (r**2 - a) >> nx if r1 % 2: r = r + (1 << (nx - 1)) #assert (r**2 - a)% (1 << (nx + 1)) == 0 nx += 1 if r not in res: res.append(r) x = r + (1 << (k - 1)) #assert (x**2 - a) % pk == 0 if x < (1 << nx) and x not in res: if (x**2 - a) % pk == 0: res.append(x) return res rv = _sqrt_mod_prime_power(a, p, 1) if not rv: return None r = rv[0] fr = r**2 - a # hensel lifting with Newton iteration, see Ref.[3] chapter 9 # with f(x) = x**2 - a; one has f'(a) != 0 (mod p) for p != 2 n = 1 px = p while 1: n1 = n n1 *= 2 if n1 > k: break n = n1 px = px**2 frinv = igcdex(2*r, px)[0] r = (r - fr*frinv) % px fr = r**2 - a if n < k: px = p**k frinv = igcdex(2*r, px)[0] r = (r - fr*frinv) % px return [r, px - r] def _sqrt_mod1(a, p, n): """ Find solution to ``x**2 == a mod p**n`` when ``a % p == 0`` see http://www.numbertheory.org/php/squareroot.html """ pn = p**n a = a % pn if a == 0: # case gcd(a, p**k) = p**n m = n // 2 if n % 2 == 1: pm1 = p**(m + 1) def _iter0a(): i = 0 while i < pn: yield i i += pm1 return _iter0a() else: pm = p**m def _iter0b(): i = 0 while i < pn: yield i i += pm return _iter0b() # case gcd(a, p**k) = p**r, r < n f = factorint(a) r = f[p] if r % 2 == 1: return None m = r // 2 a1 = a >> r if p == 2: if n - r == 1: pnm1 = 1 << (n - m + 1) pm1 = 1 << (m + 1) def _iter1(): k = 1 << (m + 2) i = 1 << m while i < pnm1: j = i while j < pn: yield j j += k i += pm1 return _iter1() if n - r == 2: res = _sqrt_mod_prime_power(a1, p, n - r) if res is None: return None pnm = 1 << (n - m) def _iter2(): s = set() for r in res: i = 0 while i < pn: x = (r << m) + i if x not in s: s.add(x) yield x i += pnm return _iter2() if n - r > 2: res = _sqrt_mod_prime_power(a1, p, n - r) if res is None: return None pnm1 = 1 << (n - m - 1) def _iter3(): s = set() for r in res: i = 0 while i < pn: x = ((r << m) + i) % pn if x not in s: s.add(x) yield x i += pnm1 return _iter3() else: m = r // 2 a1 = a // p**r res1 = _sqrt_mod_prime_power(a1, p, n - r) if res1 is None: return None pm = p**m pnr = p**(n-r) pnm = p**(n-m) def _iter4(): s = set() pm = p**m for rx in res1: i = 0 while i < pnm: x = ((rx + i) % pn) if x not in s: s.add(x) yield x*pm i += pnr return _iter4() def is_quad_residue(a, p): """ Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``, i.e a % p in set([i**2 % p for i in range(p)]). Examples ======== If ``p`` is an odd prime, an iterative method is used to make the determination: >>> from sympy.ntheory import is_quad_residue >>> sorted(set([i**2 % 7 for i in range(7)])) [0, 1, 2, 4] >>> [j for j in range(7) if is_quad_residue(j, 7)] [0, 1, 2, 4] See Also ======== legendre_symbol, jacobi_symbol """ a, p = as_int(a), as_int(p) if p < 1: raise ValueError('p must be > 0') if a >= p or a < 0: a = a % p if a < 2 or p < 3: return True if not isprime(p): if p % 2 and jacobi_symbol(a, p) == -1: return False r = sqrt_mod(a, p) if r is None: return False else: return True return pow(a, (p - 1) // 2, p) == 1 def is_nthpow_residue(a, n, m): """ Returns True if ``x**n == a (mod m)`` has solutions. References ========== .. [1] P. Hackman "Elementary Number Theory" (2009), page 76 """ a = a % m a, n, m = as_int(a), as_int(n), as_int(m) if m <= 0: raise ValueError('m must be > 0') if n < 0: raise ValueError('n must be >= 0') if n == 0: if m == 1: return False return a == 1 if a == 0: return True if n == 1: return True if n == 2: return is_quad_residue(a, m) return _is_nthpow_residue_bign(a, n, m) def _is_nthpow_residue_bign(a, n, m): r"""Returns True if `x^n = a \pmod{n}` has solutions for `n > 2`.""" # assert n > 2 # assert a > 0 and m > 0 if primitive_root(m) is None or igcd(a, m) != 1: # assert m >= 8 for prime, power in factorint(m).items(): if not _is_nthpow_residue_bign_prime_power(a, n, prime, power): return False return True f = totient(m) k = int(f // igcd(f, n)) return pow(a, k, int(m)) == 1 def _is_nthpow_residue_bign_prime_power(a, n, p, k): r"""Returns True/False if a solution for `x^n = a \pmod{p^k}` does/does not exist.""" # assert a > 0 # assert n > 2 # assert p is prime # assert k > 0 if a % p: if p != 2: return _is_nthpow_residue_bign(a, n, pow(p, k)) if n & 1: return True c = trailing(n) return a % pow(2, min(c + 2, k)) == 1 else: a %= pow(p, k) if not a: return True mu = multiplicity(p, a) if mu % n: return False pm = pow(p, mu) return _is_nthpow_residue_bign_prime_power(a//pm, n, p, k - mu) def _nthroot_mod2(s, q, p): f = factorint(q) v = [] for b, e in f.items(): v.extend([b]*e) for qx in v: s = _nthroot_mod1(s, qx, p, False) return s def _nthroot_mod1(s, q, p, all_roots): """ Root of ``x**q = s mod p``, ``p`` prime and ``q`` divides ``p - 1`` References ========== .. [1] A. M. Johnston "A Generalized qth Root Algorithm" """ g = primitive_root(p) if not isprime(q): r = _nthroot_mod2(s, q, p) else: f = p - 1 assert (p - 1) % q == 0 # determine k k = 0 while f % q == 0: k += 1 f = f // q # find z, x, r1 f1 = igcdex(-f, q)[0] % q z = f*f1 x = (1 + z) // q r1 = pow(s, x, p) s1 = pow(s, f, p) h = pow(g, f*q, p) t = discrete_log(p, s1, h) g2 = pow(g, z*t, p) g3 = igcdex(g2, p)[0] r = r1*g3 % p #assert pow(r, q, p) == s res = [r] h = pow(g, (p - 1) // q, p) #assert pow(h, q, p) == 1 hx = r for i in range(q - 1): hx = (hx*h) % p res.append(hx) if all_roots: res.sort() return res return min(res) def _help(m, prime_modulo_method, diff_method, expr_val): """ Helper function for _nthroot_mod_composite and polynomial_congruence. Parameters ========== m : positive integer prime_modulo_method : function to calculate the root of the congruence equation for the prime divisors of m diff_method : function to calculate derivative of expression at any given point expr_val : function to calculate value of the expression at any given point """ from sympy.ntheory.modular import crt f = factorint(m) dd = {} for p, e in f.items(): tot_roots = set() if e == 1: tot_roots.update(prime_modulo_method(p)) else: for root in prime_modulo_method(p): diff = diff_method(root, p) if diff != 0: ppow = p m_inv = mod_inverse(diff, p) for j in range(1, e): ppow *= p root = (root - expr_val(root, ppow) * m_inv) % ppow tot_roots.add(root) else: new_base = p roots_in_base = {root} while new_base < pow(p, e): new_base *= p new_roots = set() for k in roots_in_base: if expr_val(k, new_base)!= 0: continue while k not in new_roots: new_roots.add(k) k = (k + (new_base // p)) % new_base roots_in_base = new_roots tot_roots = tot_roots | roots_in_base if tot_roots == set(): return [] dd[pow(p, e)] = tot_roots a = [] m = [] for x, y in dd.items(): m.append(x) a.append(list(y)) return sorted({crt(m, list(i))[0] for i in product(*a)}) def _nthroot_mod_composite(a, n, m): """ Find the solutions to ``x**n = a mod m`` when m is not prime. """ return _help(m, lambda p: nthroot_mod(a, n, p, True), lambda root, p: (pow(root, n - 1, p) * (n % p)) % p, lambda root, p: (pow(root, n, p) - a) % p) def nthroot_mod(a, n, p, all_roots=False): """ Find the solutions to ``x**n = a mod p``. Parameters ========== a : integer n : positive integer p : positive integer all_roots : if False returns the smallest root, else the list of roots Examples ======== >>> from sympy.ntheory.residue_ntheory import nthroot_mod >>> nthroot_mod(11, 4, 19) 8 >>> nthroot_mod(11, 4, 19, True) [8, 11] >>> nthroot_mod(68, 3, 109) 23 """ a = a % p a, n, p = as_int(a), as_int(n), as_int(p) if n == 2: return sqrt_mod(a, p, all_roots) # see Hackman "Elementary Number Theory" (2009), page 76 if not isprime(p): return _nthroot_mod_composite(a, n, p) if a % p == 0: return [0] if not is_nthpow_residue(a, n, p): return [] if all_roots else None if (p - 1) % n == 0: return _nthroot_mod1(a, n, p, all_roots) # The roots of ``x**n - a = 0 (mod p)`` are roots of # ``gcd(x**n - a, x**(p - 1) - 1) = 0 (mod p)`` pa = n pb = p - 1 b = 1 if pa < pb: a, pa, b, pb = b, pb, a, pa while pb: # x**pa - a = 0; x**pb - b = 0 # x**pa - a = x**(q*pb + r) - a = (x**pb)**q * x**r - a = # b**q * x**r - a; x**r - c = 0; c = b**-q * a mod p q, r = divmod(pa, pb) c = pow(b, q, p) c = igcdex(c, p)[0] c = (c * a) % p pa, pb = pb, r a, b = b, c if pa == 1: if all_roots: res = [a] else: res = a elif pa == 2: return sqrt_mod(a, p, all_roots) else: res = _nthroot_mod1(a, pa, p, all_roots) return res def quadratic_residues(p) -> list[int]: """ Returns the list of quadratic residues. Examples ======== >>> from sympy.ntheory.residue_ntheory import quadratic_residues >>> quadratic_residues(7) [0, 1, 2, 4] """ p = as_int(p) r = {pow(i, 2, p) for i in range(p // 2 + 1)} return sorted(r) def legendre_symbol(a, p): r""" Returns the Legendre symbol `(a / p)`. For an integer ``a`` and an odd prime ``p``, the Legendre symbol is defined as .. math :: \genfrac(){}{}{a}{p} = \begin{cases} 0 & \text{if } p \text{ divides } a\\ 1 & \text{if } a \text{ is a quadratic residue modulo } p\\ -1 & \text{if } a \text{ is a quadratic nonresidue modulo } p \end{cases} Parameters ========== a : integer p : odd prime Examples ======== >>> from sympy.ntheory import legendre_symbol >>> [legendre_symbol(i, 7) for i in range(7)] [0, 1, 1, -1, 1, -1, -1] >>> sorted(set([i**2 % 7 for i in range(7)])) [0, 1, 2, 4] See Also ======== is_quad_residue, jacobi_symbol """ a, p = as_int(a), as_int(p) if not isprime(p) or p == 2: raise ValueError("p should be an odd prime") a = a % p if not a: return 0 if pow(a, (p - 1) // 2, p) == 1: return 1 return -1 def jacobi_symbol(m, n): r""" Returns the Jacobi symbol `(m / n)`. For any integer ``m`` and any positive odd integer ``n`` the Jacobi symbol is defined as the product of the Legendre symbols corresponding to the prime factors of ``n``: .. math :: \genfrac(){}{}{m}{n} = \genfrac(){}{}{m}{p^{1}}^{\alpha_1} \genfrac(){}{}{m}{p^{2}}^{\alpha_2} ... \genfrac(){}{}{m}{p^{k}}^{\alpha_k} \text{ where } n = p_1^{\alpha_1} p_2^{\alpha_2} ... p_k^{\alpha_k} Like the Legendre symbol, if the Jacobi symbol `\genfrac(){}{}{m}{n} = -1` then ``m`` is a quadratic nonresidue modulo ``n``. But, unlike the Legendre symbol, if the Jacobi symbol `\genfrac(){}{}{m}{n} = 1` then ``m`` may or may not be a quadratic residue modulo ``n``. Parameters ========== m : integer n : odd positive integer Examples ======== >>> from sympy.ntheory import jacobi_symbol, legendre_symbol >>> from sympy import S >>> jacobi_symbol(45, 77) -1 >>> jacobi_symbol(60, 121) 1 The relationship between the ``jacobi_symbol`` and ``legendre_symbol`` can be demonstrated as follows: >>> L = legendre_symbol >>> S(45).factors() {3: 2, 5: 1} >>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1 True See Also ======== is_quad_residue, legendre_symbol """ m, n = as_int(m), as_int(n) if n < 0 or not n % 2: raise ValueError("n should be an odd positive integer") if m < 0 or m > n: m %= n if not m: return int(n == 1) if n == 1 or m == 1: return 1 if igcd(m, n) != 1: return 0 j = 1 while m != 0: while m % 2 == 0 and m > 0: m >>= 1 if n % 8 in [3, 5]: j = -j m, n = n, m if m % 4 == n % 4 == 3: j = -j m %= n return j class mobius(Function): """ Mobius function maps natural number to {-1, 0, 1} It is defined as follows: 1) `1` if `n = 1`. 2) `0` if `n` has a squared prime factor. 3) `(-1)^k` if `n` is a square-free positive integer with `k` number of prime factors. It is an important multiplicative function in number theory and combinatorics. It has applications in mathematical series, algebraic number theory and also physics (Fermion operator has very concrete realization with Mobius Function model). Parameters ========== n : positive integer Examples ======== >>> from sympy.ntheory import mobius >>> mobius(13*7) 1 >>> mobius(1) 1 >>> mobius(13*7*5) -1 >>> mobius(13**2) 0 References ========== .. [1] https://en.wikipedia.org/wiki/M%C3%B6bius_function .. [2] Thomas Koshy "Elementary Number Theory with Applications" """ @classmethod def eval(cls, n): if n.is_integer: if n.is_positive is not True: raise ValueError("n should be a positive integer") else: raise TypeError("n should be an integer") if n.is_prime: return S.NegativeOne elif n is S.One: return S.One elif n.is_Integer: a = factorint(n) if any(i > 1 for i in a.values()): return S.Zero return S.NegativeOne**len(a) def _discrete_log_trial_mul(n, a, b, order=None): """ Trial multiplication algorithm for computing the discrete logarithm of ``a`` to the base ``b`` modulo ``n``. The algorithm finds the discrete logarithm using exhaustive search. This naive method is used as fallback algorithm of ``discrete_log`` when the group order is very small. Examples ======== >>> from sympy.ntheory.residue_ntheory import _discrete_log_trial_mul >>> _discrete_log_trial_mul(41, 15, 7) 3 See Also ======== discrete_log References ========== .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & Vanstone, S. A. (1997). """ a %= n b %= n if order is None: order = n x = 1 for i in range(order): if x == a: return i x = x * b % n raise ValueError("Log does not exist") def _discrete_log_shanks_steps(n, a, b, order=None): """ Baby-step giant-step algorithm for computing the discrete logarithm of ``a`` to the base ``b`` modulo ``n``. The algorithm is a time-memory trade-off of the method of exhaustive search. It uses `O(sqrt(m))` memory, where `m` is the group order. Examples ======== >>> from sympy.ntheory.residue_ntheory import _discrete_log_shanks_steps >>> _discrete_log_shanks_steps(41, 15, 7) 3 See Also ======== discrete_log References ========== .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & Vanstone, S. A. (1997). """ a %= n b %= n if order is None: order = n_order(b, n) m = isqrt(order) + 1 T = {} x = 1 for i in range(m): T[x] = i x = x * b % n z = mod_inverse(b, n) z = pow(z, m, n) x = a for i in range(m): if x in T: return i * m + T[x] x = x * z % n raise ValueError("Log does not exist") def _discrete_log_pollard_rho(n, a, b, order=None, retries=10, rseed=None): """ Pollard's Rho algorithm for computing the discrete logarithm of ``a`` to the base ``b`` modulo ``n``. It is a randomized algorithm with the same expected running time as ``_discrete_log_shanks_steps``, but requires a negligible amount of memory. Examples ======== >>> from sympy.ntheory.residue_ntheory import _discrete_log_pollard_rho >>> _discrete_log_pollard_rho(227, 3**7, 3) 7 See Also ======== discrete_log References ========== .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & Vanstone, S. A. (1997). """ a %= n b %= n if order is None: order = n_order(b, n) randint = _randint(rseed) for i in range(retries): aa = randint(1, order - 1) ba = randint(1, order - 1) xa = pow(b, aa, n) * pow(a, ba, n) % n c = xa % 3 if c == 0: xb = a * xa % n ab = aa bb = (ba + 1) % order elif c == 1: xb = xa * xa % n ab = (aa + aa) % order bb = (ba + ba) % order else: xb = b * xa % n ab = (aa + 1) % order bb = ba for j in range(order): c = xa % 3 if c == 0: xa = a * xa % n ba = (ba + 1) % order elif c == 1: xa = xa * xa % n aa = (aa + aa) % order ba = (ba + ba) % order else: xa = b * xa % n aa = (aa + 1) % order c = xb % 3 if c == 0: xb = a * xb % n bb = (bb + 1) % order elif c == 1: xb = xb * xb % n ab = (ab + ab) % order bb = (bb + bb) % order else: xb = b * xb % n ab = (ab + 1) % order c = xb % 3 if c == 0: xb = a * xb % n bb = (bb + 1) % order elif c == 1: xb = xb * xb % n ab = (ab + ab) % order bb = (bb + bb) % order else: xb = b * xb % n ab = (ab + 1) % order if xa == xb: r = (ba - bb) % order try: e = mod_inverse(r, order) * (ab - aa) % order if (pow(b, e, n) - a) % n == 0: return e except ValueError: pass break raise ValueError("Pollard's Rho failed to find logarithm") def _discrete_log_pohlig_hellman(n, a, b, order=None): """ Pohlig-Hellman algorithm for computing the discrete logarithm of ``a`` to the base ``b`` modulo ``n``. In order to compute the discrete logarithm, the algorithm takes advantage of the factorization of the group order. It is more efficient when the group order factors into many small primes. Examples ======== >>> from sympy.ntheory.residue_ntheory import _discrete_log_pohlig_hellman >>> _discrete_log_pohlig_hellman(251, 210, 71) 197 See Also ======== discrete_log References ========== .. [1] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & Vanstone, S. A. (1997). """ from .modular import crt a %= n b %= n if order is None: order = n_order(b, n) f = factorint(order) l = [0] * len(f) for i, (pi, ri) in enumerate(f.items()): for j in range(ri): gj = pow(b, l[i], n) aj = pow(a * mod_inverse(gj, n), order // pi**(j + 1), n) bj = pow(b, order // pi, n) cj = discrete_log(n, aj, bj, pi, True) l[i] += cj * pi**j d, _ = crt([pi**ri for pi, ri in f.items()], l) return d def discrete_log(n, a, b, order=None, prime_order=None): """ Compute the discrete logarithm of ``a`` to the base ``b`` modulo ``n``. This is a recursive function to reduce the discrete logarithm problem in cyclic groups of composite order to the problem in cyclic groups of prime order. It employs different algorithms depending on the problem (subgroup order size, prime order or not): * Trial multiplication * Baby-step giant-step * Pollard's Rho * Pohlig-Hellman Examples ======== >>> from sympy.ntheory import discrete_log >>> discrete_log(41, 15, 7) 3 References ========== .. [1] http://mathworld.wolfram.com/DiscreteLogarithm.html .. [2] "Handbook of applied cryptography", Menezes, A. J., Van, O. P. C., & Vanstone, S. A. (1997). """ n, a, b = as_int(n), as_int(a), as_int(b) if order is None: order = n_order(b, n) if prime_order is None: prime_order = isprime(order) if order < 1000: return _discrete_log_trial_mul(n, a, b, order) elif prime_order: if order < 1000000000000: return _discrete_log_shanks_steps(n, a, b, order) return _discrete_log_pollard_rho(n, a, b, order) return _discrete_log_pohlig_hellman(n, a, b, order) def quadratic_congruence(a, b, c, p): """ Find the solutions to ``a x**2 + b x + c = 0 mod p. Parameters ========== a : int b : int c : int p : int A positive integer. """ a = as_int(a) b = as_int(b) c = as_int(c) p = as_int(p) a = a % p b = b % p c = c % p if a == 0: return linear_congruence(b, -c, p) if p == 2: roots = [] if c % 2 == 0: roots.append(0) if (a + b + c) % 2 == 0: roots.append(1) return roots if isprime(p): inv_a = mod_inverse(a, p) b *= inv_a c *= inv_a if b % 2 == 1: b = b + p d = ((b * b) // 4 - c) % p y = sqrt_mod(d, p, all_roots=True) res = set() for i in y: res.add((i - b // 2) % p) return sorted(res) y = sqrt_mod(b * b - 4 * a * c, 4 * a * p, all_roots=True) res = set() for i in y: root = linear_congruence(2 * a, i - b, 4 * a * p) for j in root: res.add(j % p) return sorted(res) def _polynomial_congruence_prime(coefficients, p): """A helper function used by polynomial_congruence. It returns the root of a polynomial modulo prime number by naive search from [0, p). Parameters ========== coefficients : list of integers p : prime number """ roots = [] rank = len(coefficients) for i in range(0, p): f_val = 0 for coeff in range(0,rank - 1): f_val = (f_val + pow(i, int(rank - coeff - 1), p) * coefficients[coeff]) % p f_val = f_val + coefficients[-1] if f_val % p == 0: roots.append(i) return roots def _diff_poly(root, coefficients, p): """A helper function used by polynomial_congruence. It returns the derivative of the polynomial evaluated at the root (mod p). Parameters ========== coefficients : list of integers p : prime number root : integer """ diff = 0 rank = len(coefficients) for coeff in range(0, rank - 1): if not coefficients[coeff]: continue diff = (diff + pow(root, rank - coeff - 2, p)*(rank - coeff - 1)* coefficients[coeff]) % p return diff % p def _val_poly(root, coefficients, p): """A helper function used by polynomial_congruence. It returns value of the polynomial at root (mod p). Parameters ========== coefficients : list of integers p : prime number root : integer """ rank = len(coefficients) f_val = 0 for coeff in range(0, rank - 1): f_val = (f_val + pow(root, rank - coeff - 1, p)* coefficients[coeff]) % p f_val = f_val + coefficients[-1] return f_val % p def _valid_expr(expr): """ return coefficients of expr if it is a univariate polynomial with integer coefficients else raise a ValueError. """ if not expr.is_polynomial(): raise ValueError("The expression should be a polynomial") polynomial = Poly(expr) if not polynomial.is_univariate: raise ValueError("The expression should be univariate") if not polynomial.domain == ZZ: raise ValueError("The expression should should have integer coefficients") return polynomial.all_coeffs() def polynomial_congruence(expr, m): """ Find the solutions to a polynomial congruence equation modulo m. Parameters ========== coefficients : Coefficients of the Polynomial m : positive integer Examples ======== >>> from sympy.ntheory import polynomial_congruence >>> from sympy.abc import x >>> expr = x**6 - 2*x**5 -35 >>> polynomial_congruence(expr, 6125) [3257] """ coefficients = _valid_expr(expr) coefficients = [num % m for num in coefficients] rank = len(coefficients) if rank == 3: return quadratic_congruence(*coefficients, m) if rank == 2: return quadratic_congruence(0, *coefficients, m) if coefficients[0] == 1 and 1 + coefficients[-1] == sum(coefficients): return nthroot_mod(-coefficients[-1], rank - 1, m, True) if isprime(m): return _polynomial_congruence_prime(coefficients, m) return _help(m, lambda p: _polynomial_congruence_prime(coefficients, p), lambda root, p: _diff_poly(root, coefficients, p), lambda root, p: _val_poly(root, coefficients, p))
bc04c51434947cdd2cf98bccd1dda067e6f9de6c0f112f3a4513271614fd0e9b
from typing import Tuple as tTuple from sympy.calculus.singularities import is_decreasing from sympy.calculus.accumulationbounds import AccumulationBounds from .expr_with_intlimits import ExprWithIntLimits from .expr_with_limits import AddWithLimits from .gosper import gosper_sum from sympy.core.expr import Expr from sympy.core.add import Add from sympy.core.containers import Tuple from sympy.core.function import Derivative, expand from sympy.core.mul import Mul from sympy.core.numbers import Float, _illegal from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.sorting import ordered from sympy.core.symbol import Dummy, Wild, Symbol, symbols from sympy.functions.combinatorial.factorials import factorial from sympy.functions.combinatorial.numbers import bernoulli, harmonic from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import cot, csc from sympy.functions.special.hyper import hyper from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.functions.special.zeta_functions import zeta from sympy.integrals.integrals import Integral from sympy.logic.boolalg import And from sympy.polys.partfrac import apart from sympy.polys.polyerrors import PolynomialError, PolificationFailed from sympy.polys.polytools import parallel_poly_from_expr, Poly, factor from sympy.polys.rationaltools import together from sympy.series.limitseq import limit_seq from sympy.series.order import O from sympy.series.residues import residue from sympy.sets.sets import FiniteSet, Interval from sympy.utilities.iterables import sift import itertools class Sum(AddWithLimits, ExprWithIntLimits): r""" Represents unevaluated summation. Explanation =========== ``Sum`` represents a finite or infinite series, with the first argument being the general form of terms in the series, and the second argument being ``(dummy_variable, start, end)``, with ``dummy_variable`` taking all integer values from ``start`` through ``end``. In accordance with long-standing mathematical convention, the end term is included in the summation. Finite sums =========== For finite sums (and sums with symbolic limits assumed to be finite) we follow the summation convention described by Karr [1], especially definition 3 of section 1.4. The sum: .. math:: \sum_{m \leq i < n} f(i) has *the obvious meaning* for `m < n`, namely: .. math:: \sum_{m \leq i < n} f(i) = f(m) + f(m+1) + \ldots + f(n-2) + f(n-1) with the upper limit value `f(n)` excluded. The sum over an empty set is zero if and only if `m = n`: .. math:: \sum_{m \leq i < n} f(i) = 0 \quad \mathrm{for} \quad m = n Finally, for all other sums over empty sets we assume the following definition: .. math:: \sum_{m \leq i < n} f(i) = - \sum_{n \leq i < m} f(i) \quad \mathrm{for} \quad m > n It is important to note that Karr defines all sums with the upper limit being exclusive. This is in contrast to the usual mathematical notation, but does not affect the summation convention. Indeed we have: .. math:: \sum_{m \leq i < n} f(i) = \sum_{i = m}^{n - 1} f(i) where the difference in notation is intentional to emphasize the meaning, with limits typeset on the top being inclusive. Examples ======== >>> from sympy.abc import i, k, m, n, x >>> from sympy import Sum, factorial, oo, IndexedBase, Function >>> Sum(k, (k, 1, m)) Sum(k, (k, 1, m)) >>> Sum(k, (k, 1, m)).doit() m**2/2 + m/2 >>> Sum(k**2, (k, 1, m)) Sum(k**2, (k, 1, m)) >>> Sum(k**2, (k, 1, m)).doit() m**3/3 + m**2/2 + m/6 >>> Sum(x**k, (k, 0, oo)) Sum(x**k, (k, 0, oo)) >>> Sum(x**k, (k, 0, oo)).doit() Piecewise((1/(1 - x), Abs(x) < 1), (Sum(x**k, (k, 0, oo)), True)) >>> Sum(x**k/factorial(k), (k, 0, oo)).doit() exp(x) Here are examples to do summation with symbolic indices. You can use either Function of IndexedBase classes: >>> f = Function('f') >>> Sum(f(n), (n, 0, 3)).doit() f(0) + f(1) + f(2) + f(3) >>> Sum(f(n), (n, 0, oo)).doit() Sum(f(n), (n, 0, oo)) >>> f = IndexedBase('f') >>> Sum(f[n]**2, (n, 0, 3)).doit() f[0]**2 + f[1]**2 + f[2]**2 + f[3]**2 An example showing that the symbolic result of a summation is still valid for seemingly nonsensical values of the limits. Then the Karr convention allows us to give a perfectly valid interpretation to those sums by interchanging the limits according to the above rules: >>> S = Sum(i, (i, 1, n)).doit() >>> S n**2/2 + n/2 >>> S.subs(n, -4) 6 >>> Sum(i, (i, 1, -4)).doit() 6 >>> Sum(-i, (i, -3, 0)).doit() 6 An explicit example of the Karr summation convention: >>> S1 = Sum(i**2, (i, m, m+n-1)).doit() >>> S1 m**2*n + m*n**2 - m*n + n**3/3 - n**2/2 + n/6 >>> S2 = Sum(i**2, (i, m+n, m-1)).doit() >>> S2 -m**2*n - m*n**2 + m*n - n**3/3 + n**2/2 - n/6 >>> S1 + S2 0 >>> S3 = Sum(i, (i, m, m-1)).doit() >>> S3 0 See Also ======== summation Product, sympy.concrete.products.product References ========== .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM, Volume 28 Issue 2, April 1981, Pages 305-350 http://dl.acm.org/citation.cfm?doid=322248.322255 .. [2] https://en.wikipedia.org/wiki/Summation#Capital-sigma_notation .. [3] https://en.wikipedia.org/wiki/Empty_sum """ __slots__ = () limits: tTuple[tTuple[Symbol, Expr, Expr]] def __new__(cls, function, *symbols, **assumptions): obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions) if not hasattr(obj, 'limits'): return obj if any(len(l) != 3 or None in l for l in obj.limits): raise ValueError('Sum requires values for lower and upper bounds.') return obj def _eval_is_zero(self): # a Sum is only zero if its function is zero or if all terms # cancel out. This only answers whether the summand is zero; if # not then None is returned since we don't analyze whether all # terms cancel out. if self.function.is_zero or self.has_empty_sequence: return True def _eval_is_extended_real(self): if self.has_empty_sequence: return True return self.function.is_extended_real def _eval_is_positive(self): if self.has_finite_limits and self.has_reversed_limits is False: return self.function.is_positive def _eval_is_negative(self): if self.has_finite_limits and self.has_reversed_limits is False: return self.function.is_negative def _eval_is_finite(self): if self.has_finite_limits and self.function.is_finite: return True def doit(self, **hints): if hints.get('deep', True): f = self.function.doit(**hints) else: f = self.function # first make sure any definite limits have summation # variables with matching assumptions reps = {} for xab in self.limits: d = _dummy_with_inherited_properties_concrete(xab) if d: reps[xab[0]] = d if reps: undo = {v: k for k, v in reps.items()} did = self.xreplace(reps).doit(**hints) if isinstance(did, tuple): # when separate=True did = tuple([i.xreplace(undo) for i in did]) elif did is not None: did = did.xreplace(undo) else: did = self return did if self.function.is_Matrix: expanded = self.expand() if self != expanded: return expanded.doit() return _eval_matrix_sum(self) for n, limit in enumerate(self.limits): i, a, b = limit dif = b - a if dif == -1: # Any summation over an empty set is zero return S.Zero if dif.is_integer and dif.is_negative: a, b = b + 1, a - 1 f = -f newf = eval_sum(f, (i, a, b)) if newf is None: if f == self.function: zeta_function = self.eval_zeta_function(f, (i, a, b)) if zeta_function is not None: return zeta_function return self else: return self.func(f, *self.limits[n:]) f = newf if hints.get('deep', True): # eval_sum could return partially unevaluated # result with Piecewise. In this case we won't # doit() recursively. if not isinstance(f, Piecewise): return f.doit(**hints) return f def eval_zeta_function(self, f, limits): """ Check whether the function matches with the zeta function. If it matches, then return a `Piecewise` expression because zeta function does not converge unless `s > 1` and `q > 0` """ i, a, b = limits w, y, z = Wild('w', exclude=[i]), Wild('y', exclude=[i]), Wild('z', exclude=[i]) result = f.match((w * i + y) ** (-z)) if result is not None and b is S.Infinity: coeff = 1 / result[w] ** result[z] s = result[z] q = result[y] / result[w] + a return Piecewise((coeff * zeta(s, q), And(q > 0, s > 1)), (self, True)) def _eval_derivative(self, x): """ Differentiate wrt x as long as x is not in the free symbols of any of the upper or lower limits. Explanation =========== Sum(a*b*x, (x, 1, a)) can be differentiated wrt x or b but not `a` since the value of the sum is discontinuous in `a`. In a case involving a limit variable, the unevaluated derivative is returned. """ # diff already confirmed that x is in the free symbols of self, but we # don't want to differentiate wrt any free symbol in the upper or lower # limits # XXX remove this test for free_symbols when the default _eval_derivative is in if isinstance(x, Symbol) and x not in self.free_symbols: return S.Zero # get limits and the function f, limits = self.function, list(self.limits) limit = limits.pop(-1) if limits: # f is the argument to a Sum f = self.func(f, *limits) _, a, b = limit if x in a.free_symbols or x in b.free_symbols: return None df = Derivative(f, x, evaluate=True) rv = self.func(df, limit) return rv def _eval_difference_delta(self, n, step): k, _, upper = self.args[-1] new_upper = upper.subs(n, n + step) if len(self.args) == 2: f = self.args[0] else: f = self.func(*self.args[:-1]) return Sum(f, (k, upper + 1, new_upper)).doit() def _eval_simplify(self, **kwargs): function = self.function if kwargs.get('deep', True): function = function.simplify(**kwargs) # split the function into adds terms = Add.make_args(expand(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(**kwargs)) else: # otherwise, add it as is out_terms.append(subterm) # turn it back into a Mul s_t.append(Mul(*out_terms)) else: o_t.append(term) # next try to combine any interior sums for further simplification from sympy.simplify.simplify import factor_sum, sum_combine result = Add(sum_combine(s_t), *o_t) return factor_sum(result, limits=self.limits) def is_convergent(self): r""" Checks for the convergence of a Sum. Explanation =========== We divide the study of convergence of infinite sums and products in two parts. First Part: One part is the question whether all the terms are well defined, i.e., they are finite in a sum and also non-zero in a product. Zero is the analogy of (minus) infinity in products as :math:`e^{-\infty} = 0`. Second Part: The second part is the question of convergence after infinities, and zeros in products, have been omitted assuming that their number is finite. This means that we only consider the tail of the sum or product, starting from some point after which all terms are well defined. For example, in a sum of the form: .. math:: \sum_{1 \leq i < \infty} \frac{1}{n^2 + an + b} where a and b are numbers. The routine will return true, even if there are infinities in the term sequence (at most two). An analogous product would be: .. math:: \prod_{1 \leq i < \infty} e^{\frac{1}{n^2 + an + b}} This is how convergence is interpreted. It is concerned with what happens at the limit. Finding the bad terms is another independent matter. Note: It is responsibility of user to see that the sum or product is well defined. There are various tests employed to check the convergence like divergence test, root test, integral test, alternating series test, comparison tests, Dirichlet tests. It returns true if Sum is convergent and false if divergent and NotImplementedError if it cannot be checked. References ========== .. [1] https://en.wikipedia.org/wiki/Convergence_tests Examples ======== >>> from sympy import factorial, S, Sum, Symbol, oo >>> n = Symbol('n', integer=True) >>> Sum(n/(n - 1), (n, 4, 7)).is_convergent() True >>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent() False >>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent() False >>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent() True See Also ======== Sum.is_absolutely_convergent sympy.concrete.products.Product.is_convergent """ p, q, r = symbols('p q r', cls=Wild) sym = self.limits[0][0] lower_limit = self.limits[0][1] upper_limit = self.limits[0][2] sequence_term = self.function.simplify() if len(sequence_term.free_symbols) > 1: raise NotImplementedError("convergence checking for more than one symbol " "containing series is not handled") if lower_limit.is_finite and upper_limit.is_finite: return S.true # transform sym -> -sym and swap the upper_limit = S.Infinity # and lower_limit = - upper_limit if lower_limit is S.NegativeInfinity: if upper_limit is S.Infinity: return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \ Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent() from sympy.simplify.simplify import simplify sequence_term = simplify(sequence_term.xreplace({sym: -sym})) lower_limit = -upper_limit upper_limit = S.Infinity sym_ = Dummy(sym.name, integer=True, positive=True) sequence_term = sequence_term.xreplace({sym: sym_}) sym = sym_ interval = Interval(lower_limit, upper_limit) # Piecewise function handle if sequence_term.is_Piecewise: for func, cond in sequence_term.args: # see if it represents something going to oo if cond == True or cond.as_set().sup is S.Infinity: s = Sum(func, (sym, lower_limit, upper_limit)) return s.is_convergent() return S.true ### -------- Divergence test ----------- ### try: lim_val = limit_seq(sequence_term, sym) if lim_val is not None and lim_val.is_zero is False: return S.false except NotImplementedError: pass try: lim_val_abs = limit_seq(abs(sequence_term), sym) if lim_val_abs is not None and lim_val_abs.is_zero is False: return S.false except NotImplementedError: pass order = O(sequence_term, (sym, S.Infinity)) ### --------- p-series test (1/n**p) ---------- ### p_series_test = order.expr.match(sym**p) if p_series_test is not None: if p_series_test[p] < -1: return S.true if p_series_test[p] >= -1: return S.false ### ------------- comparison test ------------- ### # 1/(n**p*log(n)**q*log(log(n))**r) comparison n_log_test = (order.expr.match(1/(sym**p*log(1/sym)**q*log(-log(1/sym))**r)) or order.expr.match(1/(sym**p*(-log(1/sym))**q*log(-log(1/sym))**r))) if n_log_test is not None: if (n_log_test[p] > 1 or (n_log_test[p] == 1 and n_log_test[q] > 1) or (n_log_test[p] == n_log_test[q] == 1 and n_log_test[r] > 1)): return S.true return S.false ### ------------- Limit comparison test -----------### # (1/n) comparison try: lim_comp = limit_seq(sym*sequence_term, sym) if lim_comp is not None and lim_comp.is_number and lim_comp > 0: return S.false except NotImplementedError: pass ### ----------- ratio test ---------------- ### next_sequence_term = sequence_term.xreplace({sym: sym + 1}) from sympy.simplify.combsimp import combsimp from sympy.simplify.powsimp import powsimp ratio = combsimp(powsimp(next_sequence_term/sequence_term)) try: lim_ratio = limit_seq(ratio, sym) if lim_ratio is not None and lim_ratio.is_number: if abs(lim_ratio) > 1: return S.false if abs(lim_ratio) < 1: return S.true except NotImplementedError: lim_ratio = None ### ---------- Raabe's test -------------- ### if lim_ratio == 1: # ratio test inconclusive test_val = sym*(sequence_term/ sequence_term.subs(sym, sym + 1) - 1) test_val = test_val.gammasimp() try: lim_val = limit_seq(test_val, sym) if lim_val is not None and lim_val.is_number: if lim_val > 1: return S.true if lim_val < 1: return S.false except NotImplementedError: pass ### ----------- root test ---------------- ### # lim = Limit(abs(sequence_term)**(1/sym), sym, S.Infinity) try: lim_evaluated = limit_seq(abs(sequence_term)**(1/sym), sym) if lim_evaluated is not None and lim_evaluated.is_number: if lim_evaluated < 1: return S.true if lim_evaluated > 1: return S.false except NotImplementedError: pass ### ------------- alternating series test ----------- ### dict_val = sequence_term.match(S.NegativeOne**(sym + p)*q) if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval): return S.true ### ------------- integral test -------------- ### check_interval = None from sympy.solvers.solveset import solveset maxima = solveset(sequence_term.diff(sym), sym, interval) if not maxima: check_interval = interval elif isinstance(maxima, FiniteSet) and maxima.sup.is_number: check_interval = Interval(maxima.sup, interval.sup) if (check_interval is not None and (is_decreasing(sequence_term, check_interval) or is_decreasing(-sequence_term, check_interval))): integral_val = Integral( sequence_term, (sym, lower_limit, upper_limit)) try: integral_val_evaluated = integral_val.doit() if integral_val_evaluated.is_number: return S(integral_val_evaluated.is_finite) except NotImplementedError: pass ### ----- Dirichlet and bounded times convergent tests ----- ### # TODO # # Dirichlet_test # https://en.wikipedia.org/wiki/Dirichlet%27s_test # # Bounded times convergent test # It is based on comparison theorems for series. # In particular, if the general term of a series can # be written as a product of two terms a_n and b_n # and if a_n is bounded and if Sum(b_n) is absolutely # convergent, then the original series Sum(a_n * b_n) # is absolutely convergent and so convergent. # # The following code can grows like 2**n where n is the # number of args in order.expr # Possibly combined with the potentially slow checks # inside the loop, could make this test extremely slow # for larger summation expressions. if order.expr.is_Mul: args = order.expr.args argset = set(args) ### -------------- Dirichlet tests -------------- ### m = Dummy('m', integer=True) def _dirichlet_test(g_n): try: ing_val = limit_seq(Sum(g_n, (sym, interval.inf, m)).doit(), m) if ing_val is not None and ing_val.is_finite: return S.true except NotImplementedError: pass ### -------- bounded times convergent test ---------### def _bounded_convergent_test(g1_n, g2_n): try: lim_val = limit_seq(g1_n, sym) if lim_val is not None and (lim_val.is_finite or ( isinstance(lim_val, AccumulationBounds) and (lim_val.max - lim_val.min).is_finite)): if Sum(g2_n, (sym, lower_limit, upper_limit)).is_absolutely_convergent(): return S.true except NotImplementedError: pass for n in range(1, len(argset)): for a_tuple in itertools.combinations(args, n): b_set = argset - set(a_tuple) a_n = Mul(*a_tuple) b_n = Mul(*b_set) if is_decreasing(a_n, interval): dirich = _dirichlet_test(b_n) if dirich is not None: return dirich bc_test = _bounded_convergent_test(a_n, b_n) if bc_test is not None: return bc_test _sym = self.limits[0][0] sequence_term = sequence_term.xreplace({sym: _sym}) raise NotImplementedError("The algorithm to find the Sum convergence of %s " "is not yet implemented" % (sequence_term)) def is_absolutely_convergent(self): """ Checks for the absolute convergence of an infinite series. Same as checking convergence of absolute value of sequence_term of an infinite series. References ========== .. [1] https://en.wikipedia.org/wiki/Absolute_convergence Examples ======== >>> from sympy import Sum, Symbol, oo >>> n = Symbol('n', integer=True) >>> Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent() False >>> Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent() True See Also ======== Sum.is_convergent """ return Sum(abs(self.function), self.limits).is_convergent() def euler_maclaurin(self, m=0, n=0, eps=0, eval_integral=True): """ Return an Euler-Maclaurin approximation of self, where m is the number of leading terms to sum directly and n is the number of terms in the tail. With m = n = 0, this is simply the corresponding integral plus a first-order endpoint correction. Returns (s, e) where s is the Euler-Maclaurin approximation and e is the estimated error (taken to be the magnitude of the first omitted term in the tail): >>> from sympy.abc import k, a, b >>> from sympy import Sum >>> Sum(1/k, (k, 2, 5)).doit().evalf() 1.28333333333333 >>> s, e = Sum(1/k, (k, 2, 5)).euler_maclaurin() >>> s -log(2) + 7/20 + log(5) >>> from sympy import sstr >>> print(sstr((s.evalf(), e.evalf()), full_prec=True)) (1.26629073187415, 0.0175000000000000) The endpoints may be symbolic: >>> s, e = Sum(1/k, (k, a, b)).euler_maclaurin() >>> s -log(a) + log(b) + 1/(2*b) + 1/(2*a) >>> e Abs(1/(12*b**2) - 1/(12*a**2)) If the function is a polynomial of degree at most 2n+1, the Euler-Maclaurin formula becomes exact (and e = 0 is returned): >>> Sum(k, (k, 2, b)).euler_maclaurin() (b**2/2 + b/2 - 1, 0) >>> Sum(k, (k, 2, b)).doit() b**2/2 + b/2 - 1 With a nonzero eps specified, the summation is ended as soon as the remainder term is less than the epsilon. """ m = int(m) n = int(n) f = self.function if len(self.limits) != 1: raise ValueError("More than 1 limit") i, a, b = self.limits[0] if (a > b) == True: if a - b == 1: return S.Zero, S.Zero a, b = b + 1, a - 1 f = -f s = S.Zero if m: if b.is_Integer and a.is_Integer: m = min(m, b - a + 1) if not eps or f.is_polynomial(i): s = Add(*[f.subs(i, a + k) for k in range(m)]) else: term = f.subs(i, a) if term: test = abs(term.evalf(3)) < eps if test == True: return s, abs(term) elif not (test == False): # a symbolic Relational class, can't go further return term, S.Zero s = term for k in range(1, m): term = f.subs(i, a + k) if abs(term.evalf(3)) < eps and term != 0: return s, abs(term) s += term if b - a + 1 == m: return s, S.Zero a += m x = Dummy('x') I = Integral(f.subs(i, x), (x, a, b)) if eval_integral: I = I.doit() s += I def fpoint(expr): if b is S.Infinity: return expr.subs(i, a), 0 return expr.subs(i, a), expr.subs(i, b) fa, fb = fpoint(f) iterm = (fa + fb)/2 g = f.diff(i) for k in range(1, n + 2): ga, gb = fpoint(g) term = bernoulli(2*k)/factorial(2*k)*(gb - ga) if k > n: break if eps and term: term_evalf = term.evalf(3) if term_evalf is S.NaN: return S.NaN, S.NaN if abs(term_evalf) < eps: break s += term g = g.diff(i, 2, simplify=False) return s + iterm, abs(term) def reverse_order(self, *indices): """ Reverse the order of a limit in a Sum. Explanation =========== ``reverse_order(self, *indices)`` reverses some limits in the expression ``self`` which can be either a ``Sum`` or a ``Product``. The selectors in the argument ``indices`` specify some indices whose limits get reversed. These selectors are either variable names or numerical indices counted starting from the inner-most limit tuple. Examples ======== >>> from sympy import Sum >>> from sympy.abc import x, y, a, b, c, d >>> Sum(x, (x, 0, 3)).reverse_order(x) Sum(-x, (x, 4, -1)) >>> Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(x, y) Sum(x*y, (x, 6, 0), (y, 7, -1)) >>> Sum(x, (x, a, b)).reverse_order(x) Sum(-x, (x, b + 1, a - 1)) >>> Sum(x, (x, a, b)).reverse_order(0) Sum(-x, (x, b + 1, a - 1)) While one should prefer variable names when specifying which limits to reverse, the index counting notation comes in handy in case there are several symbols with the same name. >>> S = Sum(x**2, (x, a, b), (x, c, d)) >>> S Sum(x**2, (x, a, b), (x, c, d)) >>> S0 = S.reverse_order(0) >>> S0 Sum(-x**2, (x, b + 1, a - 1), (x, c, d)) >>> S1 = S0.reverse_order(1) >>> S1 Sum(x**2, (x, b + 1, a - 1), (x, d + 1, c - 1)) Of course we can mix both notations: >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) See Also ======== sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index, reorder_limit, sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder References ========== .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM, Volume 28 Issue 2, April 1981, Pages 305-350 http://dl.acm.org/citation.cfm?doid=322248.322255 """ l_indices = list(indices) for i, indx in enumerate(l_indices): if not isinstance(indx, int): l_indices[i] = self.index(indx) e = 1 limits = [] for i, limit in enumerate(self.limits): l = limit if i in l_indices: e = -e l = (limit[0], limit[2] + 1, limit[1] - 1) limits.append(l) return Sum(e * self.function, *limits) def _eval_rewrite_as_Product(self, *args, **kwargs): from sympy.concrete.products import Product if self.function.is_extended_real: return log(Product(exp(self.function), *self.limits)) def summation(f, *symbols, **kwargs): r""" Compute the summation of f with respect to symbols. Explanation =========== The notation for symbols is similar to the notation used in Integral. summation(f, (i, a, b)) computes the sum of f with respect to i from a to b, i.e., :: b ____ \ ` summation(f, (i, a, b)) = ) f /___, i = a If it cannot compute the sum, it returns an unevaluated Sum object. Repeated sums can be computed by introducing additional symbols tuples:: Examples ======== >>> from sympy import summation, oo, symbols, log >>> i, n, m = symbols('i n m', integer=True) >>> summation(2*i - 1, (i, 1, n)) n**2 >>> summation(1/2**i, (i, 0, oo)) 2 >>> summation(1/log(n)**n, (n, 2, oo)) Sum(log(n)**(-n), (n, 2, oo)) >>> summation(i, (i, 0, n), (n, 0, m)) m**3/6 + m**2/2 + m/3 >>> from sympy.abc import x >>> from sympy import factorial >>> summation(x**n/factorial(n), (n, 0, oo)) exp(x) See Also ======== Sum Product, sympy.concrete.products.product """ return Sum(f, *symbols, **kwargs).doit(deep=False) def telescopic_direct(L, R, n, limits): """ Returns the direct summation of the terms of a telescopic sum Explanation =========== L is the term with lower index R is the term with higher index n difference between the indexes of L and R Examples ======== >>> from sympy.concrete.summations import telescopic_direct >>> from sympy.abc import k, a, b >>> telescopic_direct(1/k, -1/(k+2), 2, (k, a, b)) -1/(b + 2) - 1/(b + 1) + 1/(a + 1) + 1/a """ (i, a, b) = limits return Add(*[L.subs(i, a + m) + R.subs(i, b - m) for m in range(n)]) def telescopic(L, R, limits): ''' Tries to perform the summation using the telescopic property. Return None if not possible. ''' (i, a, b) = limits if L.is_Add or R.is_Add: return None # We want to solve(L.subs(i, i + m) + R, m) # First we try a simple match since this does things that # solve doesn't do, e.g. solve(cos(k+m)-cos(k), m) gives # a more complicated solution than m == 0. k = Wild("k") sol = (-R).match(L.subs(i, i + k)) s = None if sol and k in sol: s = sol[k] if not (s.is_Integer and L.subs(i, i + s) + R == 0): # invalid match or match didn't work s = None # But there are things that match doesn't do that solve # can do, e.g. determine that 1/(x + m) = 1/(1 - x) when m = 1 if s is None: m = Dummy('m') try: from sympy.solvers.solvers import solve sol = solve(L.subs(i, i + m) + R, m) or [] except NotImplementedError: return None sol = [si for si in sol if si.is_Integer and (L.subs(i, i + si) + R).expand().is_zero] if len(sol) != 1: return None s = sol[0] if s < 0: return telescopic_direct(R, L, abs(s), (i, a, b)) elif s > 0: return telescopic_direct(L, R, s, (i, a, b)) def eval_sum(f, limits): (i, a, b) = limits if f.is_zero: return S.Zero if i not in f.free_symbols: return f*(b - a + 1) if a == b: return f.subs(i, a) if isinstance(f, Piecewise): if not any(i in arg.args[1].free_symbols for arg in f.args): # Piecewise conditions do not depend on the dummy summation variable, # therefore we can fold: Sum(Piecewise((e, c), ...), limits) # --> Piecewise((Sum(e, limits), c), ...) newargs = [] for arg in f.args: newexpr = eval_sum(arg.expr, limits) if newexpr is None: return None newargs.append((newexpr, arg.cond)) return f.func(*newargs) if f.has(KroneckerDelta): from .delta import deltasummation, _has_simple_delta f = f.replace( lambda x: isinstance(x, Sum), lambda x: x.factor() ) if _has_simple_delta(f, limits[0]): return deltasummation(f, limits) dif = b - a definite = dif.is_Integer # Doing it directly may be faster if there are very few terms. if definite and (dif < 100): return eval_sum_direct(f, (i, a, b)) if isinstance(f, Piecewise): return None # Try to do it symbolically. Even when the number of terms is # known, this can save time when b-a is big. value = eval_sum_symbolic(f.expand(), (i, a, b)) if value is not None: return value # Do it directly if definite: return eval_sum_direct(f, (i, a, b)) def eval_sum_direct(expr, limits): """ Evaluate expression directly, but perform some simple checks first to possibly result in a smaller expression and faster execution. """ (i, a, b) = limits dif = b - a # Linearity if expr.is_Mul: # Try factor out everything not including i without_i, with_i = expr.as_independent(i) if without_i != 1: s = eval_sum_direct(with_i, (i, a, b)) if s: r = without_i*s if r is not S.NaN: return r else: # Try term by term L, R = expr.as_two_terms() if not L.has(i): sR = eval_sum_direct(R, (i, a, b)) if sR: return L*sR if not R.has(i): sL = eval_sum_direct(L, (i, a, b)) if sL: return sL*R # do this whether its an Add or Mul # e.g. apart(1/(25*i**2 + 45*i + 14)) and # apart(1/((5*i + 2)*(5*i + 7))) -> # -1/(5*(5*i + 7)) + 1/(5*(5*i + 2)) try: expr = apart(expr, i) # see if it becomes an Add except PolynomialError: pass if expr.is_Add: # Try factor out everything not including i without_i, with_i = expr.as_independent(i) if without_i != 0: s = eval_sum_direct(with_i, (i, a, b)) if s: r = without_i*(dif + 1) + s if r is not S.NaN: return r else: # Try term by term L, R = expr.as_two_terms() lsum = eval_sum_direct(L, (i, a, b)) rsum = eval_sum_direct(R, (i, a, b)) if None not in (lsum, rsum): r = lsum + rsum if r is not S.NaN: return r return Add(*[expr.subs(i, a + j) for j in range(dif + 1)]) def eval_sum_symbolic(f, limits): f_orig = f (i, a, b) = limits if not f.has(i): return f*(b - a + 1) # Linearity if f.is_Mul: # Try factor out everything not including i without_i, with_i = f.as_independent(i) if without_i != 1: s = eval_sum_symbolic(with_i, (i, a, b)) if s: r = without_i*s if r is not S.NaN: return r else: # Try term by term L, R = f.as_two_terms() if not L.has(i): sR = eval_sum_symbolic(R, (i, a, b)) if sR: return L*sR if not R.has(i): sL = eval_sum_symbolic(L, (i, a, b)) if sL: return sL*R # do this whether its an Add or Mul # e.g. apart(1/(25*i**2 + 45*i + 14)) and # apart(1/((5*i + 2)*(5*i + 7))) -> # -1/(5*(5*i + 7)) + 1/(5*(5*i + 2)) try: f = apart(f, i) except PolynomialError: pass if f.is_Add: L, R = f.as_two_terms() lrsum = telescopic(L, R, (i, a, b)) if lrsum: return lrsum # Try factor out everything not including i without_i, with_i = f.as_independent(i) if without_i != 0: s = eval_sum_symbolic(with_i, (i, a, b)) if s: r = without_i*(b - a + 1) + s if r is not S.NaN: return r else: # Try term by term lsum = eval_sum_symbolic(L, (i, a, b)) rsum = eval_sum_symbolic(R, (i, a, b)) if None not in (lsum, rsum): r = lsum + rsum if r is not S.NaN: return r # Polynomial terms with Faulhaber's formula n = Wild('n') result = f.match(i**n) if result is not None: n = result[n] if n.is_Integer: if n >= 0: if (b is S.Infinity and a is not S.NegativeInfinity) or \ (a is S.NegativeInfinity and b is not S.Infinity): return S.Infinity return ((bernoulli(n + 1, b + 1) - bernoulli(n + 1, a))/(n + 1)).expand() elif a.is_Integer and a >= 1: if n == -1: return harmonic(b) - harmonic(a - 1) else: return harmonic(b, abs(n)) - harmonic(a - 1, abs(n)) if not (a.has(S.Infinity, S.NegativeInfinity) or b.has(S.Infinity, S.NegativeInfinity)): # Geometric terms c1 = Wild('c1', exclude=[i]) c2 = Wild('c2', exclude=[i]) c3 = Wild('c3', exclude=[i]) wexp = Wild('wexp') # Here we first attempt powsimp on f for easier matching with the # exponential pattern, and attempt expansion on the exponent for easier # matching with the linear pattern. e = f.powsimp().match(c1 ** wexp) if e is not None: e_exp = e.pop(wexp).expand().match(c2*i + c3) if e_exp is not None: e.update(e_exp) p = (c1**c3).subs(e) q = (c1**c2).subs(e) r = p*(q**a - q**(b + 1))/(1 - q) l = p*(b - a + 1) return Piecewise((l, Eq(q, S.One)), (r, True)) r = gosper_sum(f, (i, a, b)) if isinstance(r, (Mul,Add)): from sympy.simplify.radsimp import denom from sympy.solvers.solvers import solve non_limit = r.free_symbols - Tuple(*limits[1:]).free_symbols den = denom(together(r)) den_sym = non_limit & den.free_symbols args = [] for v in ordered(den_sym): try: s = solve(den, v) m = Eq(v, s[0]) if s else S.false if m != False: args.append((Sum(f_orig.subs(*m.args), limits).doit(), m)) break except NotImplementedError: continue args.append((r, True)) return Piecewise(*args) if r not in (None, S.NaN): return r h = eval_sum_hyper(f_orig, (i, a, b)) if h is not None: return h r = eval_sum_residue(f_orig, (i, a, b)) if r is not None: return r factored = f_orig.factor() if factored != f_orig: return eval_sum_symbolic(factored, (i, a, b)) def _eval_sum_hyper(f, i, a): """ Returns (res, cond). Sums from a to oo. """ if a != 0: return _eval_sum_hyper(f.subs(i, i + a), i, 0) if f.subs(i, 0) == 0: from sympy.simplify.simplify import simplify if simplify(f.subs(i, Dummy('i', integer=True, positive=True))) == 0: return S.Zero, True return _eval_sum_hyper(f.subs(i, i + 1), i, 0) from sympy.simplify.simplify import hypersimp hs = hypersimp(f, i) if hs is None: return None if isinstance(hs, Float): from sympy.simplify.simplify import nsimplify hs = nsimplify(hs) from sympy.simplify.combsimp import combsimp from sympy.simplify.hyperexpand import hyperexpand from sympy.simplify.radsimp import fraction numer, denom = fraction(factor(hs)) top, topl = numer.as_coeff_mul(i) bot, botl = denom.as_coeff_mul(i) ab = [top, bot] factors = [topl, botl] params = [[], []] for k in range(2): for fac in factors[k]: mul = 1 if fac.is_Pow: mul = fac.exp fac = fac.base if not mul.is_Integer: return None p = Poly(fac, i) if p.degree() != 1: return None m, n = p.all_coeffs() ab[k] *= m**mul params[k] += [n/m]*mul # Add "1" to numerator parameters, to account for implicit n! in # hypergeometric series. ap = params[0] + [1] bq = params[1] x = ab[0]/ab[1] h = hyper(ap, bq, x) f = combsimp(f) return f.subs(i, 0)*hyperexpand(h), h.convergence_statement def eval_sum_hyper(f, i_a_b): i, a, b = i_a_b if f.is_hypergeometric(i) is False: return if (b - a).is_Integer: # We are never going to do better than doing the sum in the obvious way return None old_sum = Sum(f, (i, a, b)) if b != S.Infinity: if a is S.NegativeInfinity: res = _eval_sum_hyper(f.subs(i, -i), i, -b) if res is not None: return Piecewise(res, (old_sum, True)) else: n_illegal = lambda x: sum(x.count(_) for _ in _illegal) had = n_illegal(f) # check that no extra illegals are introduced res1 = _eval_sum_hyper(f, i, a) if res1 is None or n_illegal(res1) > had: return res2 = _eval_sum_hyper(f, i, b + 1) if res2 is None or n_illegal(res2) > had: return (res1, cond1), (res2, cond2) = res1, res2 cond = And(cond1, cond2) if cond == False: return None return Piecewise((res1 - res2, cond), (old_sum, True)) if a is S.NegativeInfinity: res1 = _eval_sum_hyper(f.subs(i, -i), i, 1) res2 = _eval_sum_hyper(f, i, 0) if res1 is None or res2 is None: return None res1, cond1 = res1 res2, cond2 = res2 cond = And(cond1, cond2) if cond == False or cond.as_set() == S.EmptySet: return None return Piecewise((res1 + res2, cond), (old_sum, True)) # Now b == oo, a != -oo res = _eval_sum_hyper(f, i, a) if res is not None: r, c = res if c == False: if r.is_number: f = f.subs(i, Dummy('i', integer=True, positive=True) + a) if f.is_positive or f.is_zero: return S.Infinity elif f.is_negative: return S.NegativeInfinity return None return Piecewise(res, (old_sum, True)) def eval_sum_residue(f, i_a_b): r"""Compute the infinite summation with residues Notes ===== If $f(n), g(n)$ are polynomials with $\deg(g(n)) - \deg(f(n)) \ge 2$, some infinite summations can be computed by the following residue evaluations. .. math:: \sum_{n=-\infty, g(n) \ne 0}^{\infty} \frac{f(n)}{g(n)} = -\pi \sum_{\alpha|g(\alpha)=0} \text{Res}(\cot(\pi x) \frac{f(x)}{g(x)}, \alpha) .. math:: \sum_{n=-\infty, g(n) \ne 0}^{\infty} (-1)^n \frac{f(n)}{g(n)} = -\pi \sum_{\alpha|g(\alpha)=0} \text{Res}(\csc(\pi x) \frac{f(x)}{g(x)}, \alpha) Examples ======== >>> from sympy import Sum, oo, Symbol >>> x = Symbol('x') Doubly infinite series of rational functions. >>> Sum(1 / (x**2 + 1), (x, -oo, oo)).doit() pi/tanh(pi) Doubly infinite alternating series of rational functions. >>> Sum((-1)**x / (x**2 + 1), (x, -oo, oo)).doit() pi/sinh(pi) Infinite series of even rational functions. >>> Sum(1 / (x**2 + 1), (x, 0, oo)).doit() 1/2 + pi/(2*tanh(pi)) Infinite series of alternating even rational functions. >>> Sum((-1)**x / (x**2 + 1), (x, 0, oo)).doit() pi/(2*sinh(pi)) + 1/2 This also have heuristics to transform arbitrarily shifted summand or arbitrarily shifted summation range to the canonical problem the formula can handle. >>> Sum(1 / (x**2 + 2*x + 2), (x, -1, oo)).doit() 1/2 + pi/(2*tanh(pi)) >>> Sum(1 / (x**2 + 4*x + 5), (x, -2, oo)).doit() 1/2 + pi/(2*tanh(pi)) >>> Sum(1 / (x**2 + 1), (x, 1, oo)).doit() -1/2 + pi/(2*tanh(pi)) >>> Sum(1 / (x**2 + 1), (x, 2, oo)).doit() -1 + pi/(2*tanh(pi)) References ========== .. [#] http://www.supermath.info/InfiniteSeriesandtheResidueTheorem.pdf .. [#] Asmar N.H., Grafakos L. (2018) Residue Theory. In: Complex Analysis with Applications. Undergraduate Texts in Mathematics. Springer, Cham. https://doi.org/10.1007/978-3-319-94063-2_5 """ i, a, b = i_a_b def is_even_function(numer, denom): """Test if the rational function is an even function""" numer_even = all(i % 2 == 0 for (i,) in numer.monoms()) denom_even = all(i % 2 == 0 for (i,) in denom.monoms()) numer_odd = all(i % 2 == 1 for (i,) in numer.monoms()) denom_odd = all(i % 2 == 1 for (i,) in denom.monoms()) return (numer_even and denom_even) or (numer_odd and denom_odd) def match_rational(f, i): numer, denom = f.as_numer_denom() try: (numer, denom), opt = parallel_poly_from_expr((numer, denom), i) except (PolificationFailed, PolynomialError): return None return numer, denom def get_poles(denom): roots = denom.sqf_part().all_roots() roots = sift(roots, lambda x: x.is_integer) if None in roots: return None int_roots, nonint_roots = roots[True], roots[False] return int_roots, nonint_roots def get_shift(denom): n = denom.degree(i) a = denom.coeff_monomial(i**n) b = denom.coeff_monomial(i**(n-1)) shift = - b / a / n return shift #Need a dummy symbol with no assumptions set for get_residue_factor z = Dummy('z') def get_residue_factor(numer, denom, alternating): residue_factor = (numer.as_expr() / denom.as_expr()).subs(i, z) if not alternating: residue_factor *= cot(S.Pi * z) else: residue_factor *= csc(S.Pi * z) return residue_factor # We don't know how to deal with symbolic constants in summand if f.free_symbols - set([i]): return None if not (a.is_Integer or a in (S.Infinity, S.NegativeInfinity)): return None if not (b.is_Integer or b in (S.Infinity, S.NegativeInfinity)): return None # Quick exit heuristic for the sums which doesn't have infinite range if a != S.NegativeInfinity and b != S.Infinity: return None match = match_rational(f, i) if match: alternating = False numer, denom = match else: match = match_rational(f / S.NegativeOne**i, i) if match: alternating = True numer, denom = match else: return None if denom.degree(i) - numer.degree(i) < 2: return None if (a, b) == (S.NegativeInfinity, S.Infinity): poles = get_poles(denom) if poles is None: return None int_roots, nonint_roots = poles if int_roots: return None residue_factor = get_residue_factor(numer, denom, alternating) residues = [residue(residue_factor, z, root) for root in nonint_roots] return -S.Pi * sum(residues) if not (a.is_finite and b is S.Infinity): return None if not is_even_function(numer, denom): # Try shifting summation and check if the summand can be made # and even function from the origin. # Sum(f(n), (n, a, b)) => Sum(f(n + s), (n, a - s, b - s)) shift = get_shift(denom) if not shift.is_Integer: return None if shift == 0: return None numer = numer.shift(shift) denom = denom.shift(shift) if not is_even_function(numer, denom): return None if alternating: f = S.NegativeOne**i * (S.NegativeOne**shift * numer.as_expr() / denom.as_expr()) else: f = numer.as_expr() / denom.as_expr() return eval_sum_residue(f, (i, a-shift, b-shift)) poles = get_poles(denom) if poles is None: return None int_roots, nonint_roots = poles if int_roots: int_roots = [int(root) for root in int_roots] int_roots_max = max(int_roots) int_roots_min = min(int_roots) # Integer valued poles must be next to each other # and also symmetric from origin (Because the function is even) if not len(int_roots) == int_roots_max - int_roots_min + 1: return None # Check whether the summation indices contain poles if a <= max(int_roots): return None residue_factor = get_residue_factor(numer, denom, alternating) residues = [residue(residue_factor, z, root) for root in int_roots + nonint_roots] full_sum = -S.Pi * sum(residues) if not int_roots: # Compute Sum(f, (i, 0, oo)) by adding a extraneous evaluation # at the origin. half_sum = (full_sum + f.xreplace({i: 0})) / 2 # Add and subtract extraneous evaluations extraneous_neg = [f.xreplace({i: i0}) for i0 in range(int(a), 0)] extraneous_pos = [f.xreplace({i: i0}) for i0 in range(0, int(a))] result = half_sum + sum(extraneous_neg) - sum(extraneous_pos) return result # Compute Sum(f, (i, min(poles) + 1, oo)) half_sum = full_sum / 2 # Subtract extraneous evaluations extraneous = [f.xreplace({i: i0}) for i0 in range(max(int_roots) + 1, int(a))] result = half_sum - sum(extraneous) return result def _eval_matrix_sum(expression): f = expression.function for n, limit in enumerate(expression.limits): i, a, b = limit dif = b - a if dif.is_Integer: if (dif < 0) == True: a, b = b + 1, a - 1 f = -f newf = eval_sum_direct(f, (i, a, b)) if newf is not None: return newf.doit() def _dummy_with_inherited_properties_concrete(limits): """ Return a Dummy symbol that inherits as many assumptions as possible from the provided symbol and limits. If the symbol already has all True assumption shared by the limits then return None. """ x, a, b = limits l = [a, b] assumptions_to_consider = ['extended_nonnegative', 'nonnegative', 'extended_nonpositive', 'nonpositive', 'extended_positive', 'positive', 'extended_negative', 'negative', 'integer', 'rational', 'finite', 'zero', 'real', 'extended_real'] assumptions_to_keep = {} assumptions_to_add = {} for assum in assumptions_to_consider: assum_true = x._assumptions.get(assum, None) if assum_true: assumptions_to_keep[assum] = True elif all(getattr(i, 'is_' + assum) for i in l): assumptions_to_add[assum] = True if assumptions_to_add: assumptions_to_keep.update(assumptions_to_add) return Dummy('d', **assumptions_to_keep)
b44fa11eea16eb64091c30375a14655da4e4a24080383b35bd78238ab84e6224
from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.polys.polytools import lcm from sympy.utilities import public @public def approximants(l, X=Symbol('x'), simplify=False): """ Return a generator for consecutive Pade approximants for a series. It can also be used for computing the rational generating function of a series when possible, since the last approximant returned by the generator will be the generating function (if any). Explanation =========== The input list can contain more complex expressions than integer or rational numbers; symbols may also be involved in the computation. An example below show how to compute the generating function of the whole Pascal triangle. The generator can be asked to apply the sympy.simplify function on each generated term, which will make the computation slower; however it may be useful when symbols are involved in the expressions. Examples ======== >>> from sympy.series import approximants >>> from sympy import lucas, fibonacci, symbols, binomial >>> g = [lucas(k) for k in range(16)] >>> [e for e in approximants(g)] [2, -4/(x - 2), (5*x - 2)/(3*x - 1), (x - 2)/(x**2 + x - 1)] >>> h = [fibonacci(k) for k in range(16)] >>> [e for e in approximants(h)] [x, -x/(x - 1), (x**2 - x)/(2*x - 1), -x/(x**2 + x - 1)] >>> x, t = symbols("x,t") >>> p=[sum(binomial(k,i)*x**i for i in range(k+1)) for k in range(16)] >>> y = approximants(p, t) >>> for k in range(3): print(next(y)) 1 (x + 1)/((-x - 1)*(t*(x + 1) + (x + 1)/(-x - 1))) nan >>> y = approximants(p, t, simplify=True) >>> for k in range(3): print(next(y)) 1 -1/(t*(x + 1) - 1) nan See Also ======== sympy.concrete.guess.guess_generating_function_rational mpmath.pade """ from sympy.simplify import simplify as simp from sympy.simplify.radsimp import denom p1, q1 = [S.One], [S.Zero] p2, q2 = [S.Zero], [S.One] while len(l): b = 0 while l[b]==0: b += 1 if b == len(l): return m = [S.One/l[b]] for k in range(b+1, len(l)): s = 0 for j in range(b, k): s -= l[j+1] * m[b-j-1] m.append(s/l[b]) l = m a, l[0] = l[0], 0 p = [0] * max(len(p2), b+len(p1)) q = [0] * max(len(q2), b+len(q1)) for k in range(len(p2)): p[k] = a*p2[k] for k in range(b, b+len(p1)): p[k] += p1[k-b] for k in range(len(q2)): q[k] = a*q2[k] for k in range(b, b+len(q1)): q[k] += q1[k-b] while p[-1]==0: p.pop() while q[-1]==0: q.pop() p1, p2 = p2, p q1, q2 = q2, q # yield result c = 1 for x in p: c = lcm(c, denom(x)) for x in q: c = lcm(c, denom(x)) out = ( sum(c*e*X**k for k, e in enumerate(p)) / sum(c*e*X**k for k, e in enumerate(q)) ) if simplify: yield(simp(out)) else: yield out return
4e1aeb613108c109ddd5c39fc3efe9eb27516f57b6fbb2b9094edd2695d3c7e6
from collections import defaultdict from functools import reduce from math import prod from sympy.core.function import expand_log, count_ops, _coeff_isneg from sympy.core import sympify, Basic, Dummy, S, Add, Mul, Pow, expand_mul, factor_terms from sympy.core.sorting import ordered, default_sort_key from sympy.core.numbers import Integer, Rational from sympy.core.mul import _keep_coeff from sympy.core.rules import Transform from sympy.functions import exp_polar, exp, log, root, polarify, unpolarify from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.polys import lcm, gcd from sympy.ntheory.factor_ import multiplicity def powsimp(expr, deep=False, combine='all', force=False, measure=count_ops): """ Reduce expression by combining powers with similar bases and exponents. Explanation =========== If ``deep`` is ``True`` then powsimp() will also simplify arguments of functions. By default ``deep`` is set to ``False``. If ``force`` is ``True`` then bases will be combined without checking for assumptions, e.g. sqrt(x)*sqrt(y) -> sqrt(x*y) which is not true if x and y are both negative. You can make powsimp() only combine bases or only combine exponents by changing combine='base' or combine='exp'. By default, combine='all', which does both. combine='base' will only combine:: a a a 2x x x * y => (x*y) as well as things like 2 => 4 and combine='exp' will only combine :: a b (a + b) x * x => x combine='exp' will strictly only combine exponents in the way that used to be automatic. Also use deep=True if you need the old behavior. When combine='all', 'exp' is evaluated first. Consider the first example below for when there could be an ambiguity relating to this. This is done so things like the second example can be completely combined. If you want 'base' combined first, do something like powsimp(powsimp(expr, combine='base'), combine='exp'). Examples ======== >>> from sympy import powsimp, exp, log, symbols >>> from sympy.abc import x, y, z, n >>> powsimp(x**y*x**z*y**z, combine='all') x**(y + z)*y**z >>> powsimp(x**y*x**z*y**z, combine='exp') x**(y + z)*y**z >>> powsimp(x**y*x**z*y**z, combine='base', force=True) x**y*(x*y)**z >>> powsimp(x**z*x**y*n**z*n**y, combine='all', force=True) (n*x)**(y + z) >>> powsimp(x**z*x**y*n**z*n**y, combine='exp') n**(y + z)*x**(y + z) >>> powsimp(x**z*x**y*n**z*n**y, combine='base', force=True) (n*x)**y*(n*x)**z >>> x, y = symbols('x y', positive=True) >>> powsimp(log(exp(x)*exp(y))) log(exp(x)*exp(y)) >>> powsimp(log(exp(x)*exp(y)), deep=True) x + y Radicals with Mul bases will be combined if combine='exp' >>> from sympy import sqrt >>> x, y = symbols('x y') Two radicals are automatically joined through Mul: >>> a=sqrt(x*sqrt(y)) >>> a*a**3 == a**4 True But if an integer power of that radical has been autoexpanded then Mul does not join the resulting factors: >>> a**4 # auto expands to a Mul, no longer a Pow x**2*y >>> _*a # so Mul doesn't combine them x**2*y*sqrt(x*sqrt(y)) >>> powsimp(_) # but powsimp will (x*sqrt(y))**(5/2) >>> powsimp(x*y*a) # but won't when doing so would violate assumptions x*y*sqrt(x*sqrt(y)) """ def recurse(arg, **kwargs): _deep = kwargs.get('deep', deep) _combine = kwargs.get('combine', combine) _force = kwargs.get('force', force) _measure = kwargs.get('measure', measure) return powsimp(arg, _deep, _combine, _force, _measure) expr = sympify(expr) if (not isinstance(expr, Basic) or isinstance(expr, MatrixSymbol) or ( expr.is_Atom or expr in (exp_polar(0), exp_polar(1)))): return expr if deep or expr.is_Add or expr.is_Mul and _y not in expr.args: expr = expr.func(*[recurse(w) for w in expr.args]) if expr.is_Pow: return recurse(expr*_y, deep=False)/_y if not expr.is_Mul: return expr # handle the Mul if combine in ('exp', 'all'): # Collect base/exp data, while maintaining order in the # non-commutative parts of the product c_powers = defaultdict(list) nc_part = [] newexpr = [] coeff = S.One for term in expr.args: if term.is_Rational: coeff *= term continue if term.is_Pow: term = _denest_pow(term) if term.is_commutative: b, e = term.as_base_exp() if deep: b, e = [recurse(i) for i in [b, e]] if b.is_Pow or isinstance(b, exp): # don't let smthg like sqrt(x**a) split into x**a, 1/2 # or else it will be joined as x**(a/2) later b, e = b**e, S.One c_powers[b].append(e) else: # This is the logic that combines exponents for equal, # but non-commutative bases: A**x*A**y == A**(x+y). if nc_part: b1, e1 = nc_part[-1].as_base_exp() b2, e2 = term.as_base_exp() if (b1 == b2 and e1.is_commutative and e2.is_commutative): nc_part[-1] = Pow(b1, Add(e1, e2)) continue nc_part.append(term) # add up exponents of common bases for b, e in ordered(iter(c_powers.items())): # allow 2**x/4 -> 2**(x - 2); don't do this when b and e are # Numbers since autoevaluation will undo it, e.g. # 2**(1/3)/4 -> 2**(1/3 - 2) -> 2**(1/3)/4 if (b and b.is_Rational and not all(ei.is_Number for ei in e) and \ coeff is not S.One and b not in (S.One, S.NegativeOne)): m = multiplicity(abs(b), abs(coeff)) if m: e.append(m) coeff /= b**m c_powers[b] = Add(*e) if coeff is not S.One: if coeff in c_powers: c_powers[coeff] += S.One else: c_powers[coeff] = S.One # convert to plain dictionary c_powers = dict(c_powers) # check for base and inverted base pairs be = list(c_powers.items()) skip = set() # skip if we already saw them for b, e in be: if b in skip: continue bpos = b.is_positive or b.is_polar if bpos: binv = 1/b if b != binv and binv in c_powers: if b.as_numer_denom()[0] is S.One: c_powers.pop(b) c_powers[binv] -= e else: skip.add(binv) e = c_powers.pop(binv) c_powers[b] -= e # check for base and negated base pairs be = list(c_powers.items()) _n = S.NegativeOne for b, e in be: if (b.is_Symbol or b.is_Add) and -b in c_powers and b in c_powers: if (b.is_positive is not None or e.is_integer): if e.is_integer or b.is_negative: c_powers[-b] += c_powers.pop(b) else: # (-b).is_positive so use its e e = c_powers.pop(-b) c_powers[b] += e if _n in c_powers: c_powers[_n] += e else: c_powers[_n] = e # filter c_powers and convert to a list c_powers = [(b, e) for b, e in c_powers.items() if e] # ============================================================== # check for Mul bases of Rational powers that can be combined with # separated bases, e.g. x*sqrt(x*y)*sqrt(x*sqrt(x*y)) -> # (x*sqrt(x*y))**(3/2) # ---------------- helper functions def ratq(x): '''Return Rational part of x's exponent as it appears in the bkey. ''' return bkey(x)[0][1] def bkey(b, e=None): '''Return (b**s, c.q), c.p where e -> c*s. If e is not given then it will be taken by using as_base_exp() on the input b. e.g. x**3/2 -> (x, 2), 3 x**y -> (x**y, 1), 1 x**(2*y/3) -> (x**y, 3), 2 exp(x/2) -> (exp(a), 2), 1 ''' if e is not None: # coming from c_powers or from below if e.is_Integer: return (b, S.One), e elif e.is_Rational: return (b, Integer(e.q)), Integer(e.p) else: c, m = e.as_coeff_Mul(rational=True) if c is not S.One: if m.is_integer: return (b, Integer(c.q)), m*Integer(c.p) return (b**m, Integer(c.q)), Integer(c.p) else: return (b**e, S.One), S.One else: return bkey(*b.as_base_exp()) def update(b): '''Decide what to do with base, b. If its exponent is now an integer multiple of the Rational denominator, then remove it and put the factors of its base in the common_b dictionary or update the existing bases if necessary. If it has been zeroed out, simply remove the base. ''' newe, r = divmod(common_b[b], b[1]) if not r: common_b.pop(b) if newe: for m in Mul.make_args(b[0]**newe): b, e = bkey(m) if b not in common_b: common_b[b] = 0 common_b[b] += e if b[1] != 1: bases.append(b) # ---------------- end of helper functions # assemble a dictionary of the factors having a Rational power common_b = {} done = [] bases = [] for b, e in c_powers: b, e = bkey(b, e) if b in common_b: common_b[b] = common_b[b] + e else: common_b[b] = e if b[1] != 1 and b[0].is_Mul: bases.append(b) bases.sort(key=default_sort_key) # this makes tie-breaking canonical bases.sort(key=measure, reverse=True) # handle longest first for base in bases: if base not in common_b: # it may have been removed already continue b, exponent = base last = False # True when no factor of base is a radical qlcm = 1 # the lcm of the radical denominators while True: bstart = b qstart = qlcm bb = [] # list of factors ee = [] # (factor's expo. and it's current value in common_b) for bi in Mul.make_args(b): bib, bie = bkey(bi) if bib not in common_b or common_b[bib] < bie: ee = bb = [] # failed break ee.append([bie, common_b[bib]]) bb.append(bib) if ee: # find the number of integral extractions possible # e.g. [(1, 2), (2, 2)] -> min(2/1, 2/2) -> 1 min1 = ee[0][1]//ee[0][0] for i in range(1, len(ee)): rat = ee[i][1]//ee[i][0] if rat < 1: break min1 = min(min1, rat) else: # update base factor counts # e.g. if ee = [(2, 5), (3, 6)] then min1 = 2 # and the new base counts will be 5-2*2 and 6-2*3 for i in range(len(bb)): common_b[bb[i]] -= min1*ee[i][0] update(bb[i]) # update the count of the base # e.g. x**2*y*sqrt(x*sqrt(y)) the count of x*sqrt(y) # will increase by 4 to give bkey (x*sqrt(y), 2, 5) common_b[base] += min1*qstart*exponent if (last # no more radicals in base or len(common_b) == 1 # nothing left to join with or all(k[1] == 1 for k in common_b) # no rad's in common_b ): break # see what we can exponentiate base by to remove any radicals # so we know what to search for # e.g. if base were x**(1/2)*y**(1/3) then we should # exponentiate by 6 and look for powers of x and y in the ratio # of 2 to 3 qlcm = lcm([ratq(bi) for bi in Mul.make_args(bstart)]) if qlcm == 1: break # we are done b = bstart**qlcm qlcm *= qstart if all(ratq(bi) == 1 for bi in Mul.make_args(b)): last = True # we are going to be done after this next pass # this base no longer can find anything to join with and # since it was longer than any other we are done with it b, q = base done.append((b, common_b.pop(base)*Rational(1, q))) # update c_powers and get ready to continue with powsimp c_powers = done # there may be terms still in common_b that were bases that were # identified as needing processing, so remove those, too for (b, q), e in common_b.items(): if (b.is_Pow or isinstance(b, exp)) and \ q is not S.One and not b.exp.is_Rational: b, be = b.as_base_exp() b = b**(be/q) else: b = root(b, q) c_powers.append((b, e)) check = len(c_powers) c_powers = dict(c_powers) assert len(c_powers) == check # there should have been no duplicates # ============================================================== # rebuild the expression newexpr = expr.func(*(newexpr + [Pow(b, e) for b, e in c_powers.items()])) if combine == 'exp': return expr.func(newexpr, expr.func(*nc_part)) else: return recurse(expr.func(*nc_part), combine='base') * \ recurse(newexpr, combine='base') elif combine == 'base': # Build c_powers and nc_part. These must both be lists not # dicts because exp's are not combined. c_powers = [] nc_part = [] for term in expr.args: if term.is_commutative: c_powers.append(list(term.as_base_exp())) else: nc_part.append(term) # Pull out numerical coefficients from exponent if assumptions allow # e.g., 2**(2*x) => 4**x for i in range(len(c_powers)): b, e = c_powers[i] if not (all(x.is_nonnegative for x in b.as_numer_denom()) or e.is_integer or force or b.is_polar): continue exp_c, exp_t = e.as_coeff_Mul(rational=True) if exp_c is not S.One and exp_t is not S.One: c_powers[i] = [Pow(b, exp_c), exp_t] # Combine bases whenever they have the same exponent and # assumptions allow # first gather the potential bases under the common exponent c_exp = defaultdict(list) for b, e in c_powers: if deep: e = recurse(e) if e.is_Add and (b.is_positive or e.is_integer): e = factor_terms(e) if _coeff_isneg(e): e = -e b = 1/b c_exp[e].append(b) del c_powers # Merge back in the results of the above to form a new product c_powers = defaultdict(list) for e in c_exp: bases = c_exp[e] # calculate the new base for e if len(bases) == 1: new_base = bases[0] elif e.is_integer or force: new_base = expr.func(*bases) else: # see which ones can be joined unk = [] nonneg = [] neg = [] for bi in bases: if bi.is_negative: neg.append(bi) elif bi.is_nonnegative: nonneg.append(bi) elif bi.is_polar: nonneg.append( bi) # polar can be treated like non-negative else: unk.append(bi) if len(unk) == 1 and not neg or len(neg) == 1 and not unk: # a single neg or a single unk can join the rest nonneg.extend(unk + neg) unk = neg = [] elif neg: # their negative signs cancel in groups of 2*q if we know # that e = p/q else we have to treat them as unknown israt = False if e.is_Rational: israt = True else: p, d = e.as_numer_denom() if p.is_integer and d.is_integer: israt = True if israt: neg = [-w for w in neg] unk.extend([S.NegativeOne]*len(neg)) else: unk.extend(neg) neg = [] del israt # these shouldn't be joined for b in unk: c_powers[b].append(e) # here is a new joined base new_base = expr.func(*(nonneg + neg)) # if there are positive parts they will just get separated # again unless some change is made def _terms(e): # return the number of terms of this expression # when multiplied out -- assuming no joining of terms if e.is_Add: return sum([_terms(ai) for ai in e.args]) if e.is_Mul: return prod([_terms(mi) for mi in e.args]) return 1 xnew_base = expand_mul(new_base, deep=False) if len(Add.make_args(xnew_base)) < _terms(new_base): new_base = factor_terms(xnew_base) c_powers[new_base].append(e) # break out the powers from c_powers now c_part = [Pow(b, ei) for b, e in c_powers.items() for ei in e] # we're done return expr.func(*(c_part + nc_part)) else: raise ValueError("combine must be one of ('all', 'exp', 'base').") def powdenest(eq, force=False, polar=False): r""" Collect exponents on powers as assumptions allow. Explanation =========== Given ``(bb**be)**e``, this can be simplified as follows: * if ``bb`` is positive, or * ``e`` is an integer, or * ``|be| < 1`` then this simplifies to ``bb**(be*e)`` Given a product of powers raised to a power, ``(bb1**be1 * bb2**be2...)**e``, simplification can be done as follows: - if e is positive, the gcd of all bei can be joined with e; - all non-negative bb can be separated from those that are negative and their gcd can be joined with e; autosimplification already handles this separation. - integer factors from powers that have integers in the denominator of the exponent can be removed from any term and the gcd of such integers can be joined with e Setting ``force`` to ``True`` will make symbols that are not explicitly negative behave as though they are positive, resulting in more denesting. Setting ``polar`` to ``True`` will do simplifications on the Riemann surface of the logarithm, also resulting in more denestings. When there are sums of logs in exp() then a product of powers may be obtained e.g. ``exp(3*(log(a) + 2*log(b)))`` - > ``a**3*b**6``. Examples ======== >>> from sympy.abc import a, b, x, y, z >>> from sympy import Symbol, exp, log, sqrt, symbols, powdenest >>> powdenest((x**(2*a/3))**(3*x)) (x**(2*a/3))**(3*x) >>> powdenest(exp(3*x*log(2))) 2**(3*x) Assumptions may prevent expansion: >>> powdenest(sqrt(x**2)) sqrt(x**2) >>> p = symbols('p', positive=True) >>> powdenest(sqrt(p**2)) p No other expansion is done. >>> i, j = symbols('i,j', integer=True) >>> powdenest((x**x)**(i + j)) # -X-> (x**x)**i*(x**x)**j x**(x*(i + j)) But exp() will be denested by moving all non-log terms outside of the function; this may result in the collapsing of the exp to a power with a different base: >>> powdenest(exp(3*y*log(x))) x**(3*y) >>> powdenest(exp(y*(log(a) + log(b)))) (a*b)**y >>> powdenest(exp(3*(log(a) + log(b)))) a**3*b**3 If assumptions allow, symbols can also be moved to the outermost exponent: >>> i = Symbol('i', integer=True) >>> powdenest(((x**(2*i))**(3*y))**x) ((x**(2*i))**(3*y))**x >>> powdenest(((x**(2*i))**(3*y))**x, force=True) x**(6*i*x*y) >>> powdenest(((x**(2*a/3))**(3*y/i))**x) ((x**(2*a/3))**(3*y/i))**x >>> powdenest((x**(2*i)*y**(4*i))**z, force=True) (x*y**2)**(2*i*z) >>> n = Symbol('n', negative=True) >>> powdenest((x**i)**y, force=True) x**(i*y) >>> powdenest((n**i)**x, force=True) (n**i)**x """ from sympy.simplify.simplify import posify if force: def _denest(b, e): if not isinstance(b, (Pow, exp)): return b.is_positive, Pow(b, e, evaluate=False) return _denest(b.base, b.exp*e) reps = [] for p in eq.atoms(Pow, exp): if isinstance(p.base, (Pow, exp)): ok, dp = _denest(*p.args) if ok is not False: reps.append((p, dp)) if reps: eq = eq.subs(reps) eq, reps = posify(eq) return powdenest(eq, force=False, polar=polar).xreplace(reps) if polar: eq, rep = polarify(eq) return unpolarify(powdenest(unpolarify(eq, exponents_only=True)), rep) new = powsimp(eq) return new.xreplace(Transform( _denest_pow, filter=lambda m: m.is_Pow or isinstance(m, exp))) _y = Dummy('y') def _denest_pow(eq): """ Denest powers. This is a helper function for powdenest that performs the actual transformation. """ from sympy.simplify.simplify import logcombine b, e = eq.as_base_exp() if b.is_Pow or isinstance(b, exp) and e != 1: new = b._eval_power(e) if new is not None: eq = new b, e = new.as_base_exp() # denest exp with log terms in exponent if b is S.Exp1 and e.is_Mul: logs = [] other = [] for ei in e.args: if any(isinstance(ai, log) for ai in Add.make_args(ei)): logs.append(ei) else: other.append(ei) logs = logcombine(Mul(*logs)) return Pow(exp(logs), Mul(*other)) _, be = b.as_base_exp() if be is S.One and not (b.is_Mul or b.is_Rational and b.q != 1 or b.is_positive): return eq # denest eq which is either pos**e or Pow**e or Mul**e or # Mul(b1**e1, b2**e2) # handle polar numbers specially polars, nonpolars = [], [] for bb in Mul.make_args(b): if bb.is_polar: polars.append(bb.as_base_exp()) else: nonpolars.append(bb) if len(polars) == 1 and not polars[0][0].is_Mul: return Pow(polars[0][0], polars[0][1]*e)*powdenest(Mul(*nonpolars)**e) elif polars: return Mul(*[powdenest(bb**(ee*e)) for (bb, ee) in polars]) \ *powdenest(Mul(*nonpolars)**e) if b.is_Integer: # use log to see if there is a power here logb = expand_log(log(b)) if logb.is_Mul: c, logb = logb.args e *= c base = logb.args[0] return Pow(base, e) # if b is not a Mul or any factor is an atom then there is nothing to do if not b.is_Mul or any(s.is_Atom for s in Mul.make_args(b)): return eq # let log handle the case of the base of the argument being a Mul, e.g. # sqrt(x**(2*i)*y**(6*i)) -> x**i*y**(3**i) if x and y are positive; we # will take the log, expand it, and then factor out the common powers that # now appear as coefficient. We do this manually since terms_gcd pulls out # fractions, terms_gcd(x+x*y/2) -> x*(y + 2)/2 and we don't want the 1/2; # gcd won't pull out numerators from a fraction: gcd(3*x, 9*x/2) -> x but # we want 3*x. Neither work with noncommutatives. def nc_gcd(aa, bb): a, b = [i.as_coeff_Mul() for i in [aa, bb]] c = gcd(a[0], b[0]).as_numer_denom()[0] g = Mul(*(a[1].args_cnc(cset=True)[0] & b[1].args_cnc(cset=True)[0])) return _keep_coeff(c, g) glogb = expand_log(log(b)) if glogb.is_Add: args = glogb.args g = reduce(nc_gcd, args) if g != 1: cg, rg = g.as_coeff_Mul() glogb = _keep_coeff(cg, rg*Add(*[a/g for a in args])) # now put the log back together again if isinstance(glogb, log) or not glogb.is_Mul: if glogb.args[0].is_Pow or isinstance(glogb.args[0], exp): glogb = _denest_pow(glogb.args[0]) if (abs(glogb.exp) < 1) == True: return Pow(glogb.base, glogb.exp*e) return eq # the log(b) was a Mul so join any adds with logcombine add = [] other = [] for a in glogb.args: if a.is_Add: add.append(a) else: other.append(a) return Pow(exp(logcombine(Mul(*add))), e*Mul(*other))
09ab01de638c9e229b362043254f928f2205c4d08a21692014b12c6ce6254520
from collections import defaultdict from functools import reduce from sympy.core import (sympify, Basic, S, Expr, factor_terms, Mul, Add, bottom_up) from sympy.core.cache import cacheit from sympy.core.function import (count_ops, _mexpand, FunctionClass, expand, expand_mul, _coeff_isneg, Derivative) from sympy.core.numbers import I, Integer, igcd from sympy.core.sorting import _nodes from sympy.core.symbol import Dummy, symbols, Wild from sympy.external.gmpy import SYMPY_INTS from sympy.functions import sin, cos, exp, cosh, tanh, sinh, tan, cot, coth from sympy.functions import atan2 from sympy.functions.elementary.hyperbolic import HyperbolicFunction from sympy.functions.elementary.trigonometric import TrigonometricFunction from sympy.polys import Poly, factor, cancel, parallel_poly_from_expr from sympy.polys.domains import ZZ from sympy.polys.polyerrors import PolificationFailed from sympy.polys.polytools import groebner from sympy.simplify.cse_main import cse from sympy.strategies.core import identity from sympy.strategies.tree import greedy from sympy.utilities.iterables import iterable from sympy.utilities.misc import debug def trigsimp_groebner(expr, hints=[], quick=False, order="grlex", polynomial=False): """ Simplify trigonometric expressions using a groebner basis algorithm. Explanation =========== This routine takes a fraction involving trigonometric or hyperbolic expressions, and tries to simplify it. The primary metric is the total degree. Some attempts are made to choose the simplest possible expression of the minimal degree, but this is non-rigorous, and also very slow (see the ``quick=True`` option). If ``polynomial`` is set to True, instead of simplifying numerator and denominator together, this function just brings numerator and denominator into a canonical form. This is much faster, but has potentially worse results. However, if the input is a polynomial, then the result is guaranteed to be an equivalent polynomial of minimal degree. The most important option is hints. Its entries can be any of the following: - a natural number - a function - an iterable of the form (func, var1, var2, ...) - anything else, interpreted as a generator A number is used to indicate that the search space should be increased. A function is used to indicate that said function is likely to occur in a simplified expression. An iterable is used indicate that func(var1 + var2 + ...) is likely to occur in a simplified . An additional generator also indicates that it is likely to occur. (See examples below). This routine carries out various computationally intensive algorithms. The option ``quick=True`` can be used to suppress one particularly slow step (at the expense of potentially more complicated results, but never at the expense of increased total degree). Examples ======== >>> from sympy.abc import x, y >>> from sympy import sin, tan, cos, sinh, cosh, tanh >>> from sympy.simplify.trigsimp import trigsimp_groebner Suppose you want to simplify ``sin(x)*cos(x)``. Naively, nothing happens: >>> ex = sin(x)*cos(x) >>> trigsimp_groebner(ex) sin(x)*cos(x) This is because ``trigsimp_groebner`` only looks for a simplification involving just ``sin(x)`` and ``cos(x)``. You can tell it to also try ``2*x`` by passing ``hints=[2]``: >>> trigsimp_groebner(ex, hints=[2]) sin(2*x)/2 >>> trigsimp_groebner(sin(x)**2 - cos(x)**2, hints=[2]) -cos(2*x) Increasing the search space this way can quickly become expensive. A much faster way is to give a specific expression that is likely to occur: >>> trigsimp_groebner(ex, hints=[sin(2*x)]) sin(2*x)/2 Hyperbolic expressions are similarly supported: >>> trigsimp_groebner(sinh(2*x)/sinh(x)) 2*cosh(x) Note how no hints had to be passed, since the expression already involved ``2*x``. The tangent function is also supported. You can either pass ``tan`` in the hints, to indicate that tan should be tried whenever cosine or sine are, or you can pass a specific generator: >>> trigsimp_groebner(sin(x)/cos(x), hints=[tan]) tan(x) >>> trigsimp_groebner(sinh(x)/cosh(x), hints=[tanh(x)]) tanh(x) Finally, you can use the iterable form to suggest that angle sum formulae should be tried: >>> ex = (tan(x) + tan(y))/(1 - tan(x)*tan(y)) >>> trigsimp_groebner(ex, hints=[(tan, x, y)]) tan(x + y) """ # TODO # - preprocess by replacing everything by funcs we can handle # - optionally use cot instead of tan # - more intelligent hinting. # For example, if the ideal is small, and we have sin(x), sin(y), # add sin(x + y) automatically... ? # - algebraic numbers ... # - expressions of lowest degree are not distinguished properly # e.g. 1 - sin(x)**2 # - we could try to order the generators intelligently, so as to influence # which monomials appear in the quotient basis # THEORY # ------ # Ratsimpmodprime above can be used to "simplify" a rational function # modulo a prime ideal. "Simplify" mainly means finding an equivalent # expression of lower total degree. # # We intend to use this to simplify trigonometric functions. To do that, # we need to decide (a) which ring to use, and (b) modulo which ideal to # simplify. In practice, (a) means settling on a list of "generators" # a, b, c, ..., such that the fraction we want to simplify is a rational # function in a, b, c, ..., with coefficients in ZZ (integers). # (2) means that we have to decide what relations to impose on the # generators. There are two practical problems: # (1) The ideal has to be *prime* (a technical term). # (2) The relations have to be polynomials in the generators. # # We typically have two kinds of generators: # - trigonometric expressions, like sin(x), cos(5*x), etc # - "everything else", like gamma(x), pi, etc. # # Since this function is trigsimp, we will concentrate on what to do with # trigonometric expressions. We can also simplify hyperbolic expressions, # but the extensions should be clear. # # One crucial point is that all *other* generators really should behave # like indeterminates. In particular if (say) "I" is one of them, then # in fact I**2 + 1 = 0 and we may and will compute non-sensical # expressions. However, we can work with a dummy and add the relation # I**2 + 1 = 0 to our ideal, then substitute back in the end. # # Now regarding trigonometric generators. We split them into groups, # according to the argument of the trigonometric functions. We want to # organise this in such a way that most trigonometric identities apply in # the same group. For example, given sin(x), cos(2*x) and cos(y), we would # group as [sin(x), cos(2*x)] and [cos(y)]. # # Our prime ideal will be built in three steps: # (1) For each group, compute a "geometrically prime" ideal of relations. # Geometrically prime means that it generates a prime ideal in # CC[gens], not just ZZ[gens]. # (2) Take the union of all the generators of the ideals for all groups. # By the geometric primality condition, this is still prime. # (3) Add further inter-group relations which preserve primality. # # Step (1) works as follows. We will isolate common factors in the # argument, so that all our generators are of the form sin(n*x), cos(n*x) # or tan(n*x), with n an integer. Suppose first there are no tan terms. # The ideal [sin(x)**2 + cos(x)**2 - 1] is geometrically prime, since # X**2 + Y**2 - 1 is irreducible over CC. # Now, if we have a generator sin(n*x), than we can, using trig identities, # express sin(n*x) as a polynomial in sin(x) and cos(x). We can add this # relation to the ideal, preserving geometric primality, since the quotient # ring is unchanged. # Thus we have treated all sin and cos terms. # For tan(n*x), we add a relation tan(n*x)*cos(n*x) - sin(n*x) = 0. # (This requires of course that we already have relations for cos(n*x) and # sin(n*x).) It is not obvious, but it seems that this preserves geometric # primality. # XXX A real proof would be nice. HELP! # Sketch that <S**2 + C**2 - 1, C*T - S> is a prime ideal of # CC[S, C, T]: # - it suffices to show that the projective closure in CP**3 is # irreducible # - using the half-angle substitutions, we can express sin(x), tan(x), # cos(x) as rational functions in tan(x/2) # - from this, we get a rational map from CP**1 to our curve # - this is a morphism, hence the curve is prime # # Step (2) is trivial. # # Step (3) works by adding selected relations of the form # sin(x + y) - sin(x)*cos(y) - sin(y)*cos(x), etc. Geometric primality is # preserved by the same argument as before. def parse_hints(hints): """Split hints into (n, funcs, iterables, gens).""" n = 1 funcs, iterables, gens = [], [], [] for e in hints: if isinstance(e, (SYMPY_INTS, Integer)): n = e elif isinstance(e, FunctionClass): funcs.append(e) elif iterable(e): iterables.append((e[0], e[1:])) # XXX sin(x+2y)? # Note: we go through polys so e.g. # sin(-x) -> -sin(x) -> sin(x) gens.extend(parallel_poly_from_expr( [e[0](x) for x in e[1:]] + [e[0](Add(*e[1:]))])[1].gens) else: gens.append(e) return n, funcs, iterables, gens def build_ideal(x, terms): """ Build generators for our ideal. ``Terms`` is an iterable with elements of the form (fn, coeff), indicating that we have a generator fn(coeff*x). If any of the terms is trigonometric, sin(x) and cos(x) are guaranteed to appear in terms. Similarly for hyperbolic functions. For tan(n*x), sin(n*x) and cos(n*x) are guaranteed. """ I = [] y = Dummy('y') for fn, coeff in terms: for c, s, t, rel in ( [cos, sin, tan, cos(x)**2 + sin(x)**2 - 1], [cosh, sinh, tanh, cosh(x)**2 - sinh(x)**2 - 1]): if coeff == 1 and fn in [c, s]: I.append(rel) elif fn == t: I.append(t(coeff*x)*c(coeff*x) - s(coeff*x)) elif fn in [c, s]: cn = fn(coeff*y).expand(trig=True).subs(y, x) I.append(fn(coeff*x) - cn) return list(set(I)) def analyse_gens(gens, hints): """ Analyse the generators ``gens``, using the hints ``hints``. The meaning of ``hints`` is described in the main docstring. Return a new list of generators, and also the ideal we should work with. """ # First parse the hints n, funcs, iterables, extragens = parse_hints(hints) debug('n=%s funcs: %s iterables: %s extragens: %s', (funcs, iterables, extragens)) # We just add the extragens to gens and analyse them as before gens = list(gens) gens.extend(extragens) # remove duplicates funcs = list(set(funcs)) iterables = list(set(iterables)) gens = list(set(gens)) # all the functions we can do anything with allfuncs = {sin, cos, tan, sinh, cosh, tanh} # sin(3*x) -> ((3, x), sin) trigterms = [(g.args[0].as_coeff_mul(), g.func) for g in gens if g.func in allfuncs] # Our list of new generators - start with anything that we cannot # work with (i.e. is not a trigonometric term) freegens = [g for g in gens if g.func not in allfuncs] newgens = [] trigdict = {} for (coeff, var), fn in trigterms: trigdict.setdefault(var, []).append((coeff, fn)) res = [] # the ideal for key, val in trigdict.items(): # We have now assembeled a dictionary. Its keys are common # arguments in trigonometric expressions, and values are lists of # pairs (fn, coeff). x0, (fn, coeff) in trigdict means that we # need to deal with fn(coeff*x0). We take the rational gcd of the # coeffs, call it ``gcd``. We then use x = x0/gcd as "base symbol", # all other arguments are integral multiples thereof. # We will build an ideal which works with sin(x), cos(x). # If hint tan is provided, also work with tan(x). Moreover, if # n > 1, also work with sin(k*x) for k <= n, and similarly for cos # (and tan if the hint is provided). Finally, any generators which # the ideal does not work with but we need to accommodate (either # because it was in expr or because it was provided as a hint) # we also build into the ideal. # This selection process is expressed in the list ``terms``. # build_ideal then generates the actual relations in our ideal, # from this list. fns = [x[1] for x in val] val = [x[0] for x in val] gcd = reduce(igcd, val) terms = [(fn, v/gcd) for (fn, v) in zip(fns, val)] fs = set(funcs + fns) for c, s, t in ([cos, sin, tan], [cosh, sinh, tanh]): if any(x in fs for x in (c, s, t)): fs.add(c) fs.add(s) for fn in fs: for k in range(1, n + 1): terms.append((fn, k)) extra = [] for fn, v in terms: if fn == tan: extra.append((sin, v)) extra.append((cos, v)) if fn in [sin, cos] and tan in fs: extra.append((tan, v)) if fn == tanh: extra.append((sinh, v)) extra.append((cosh, v)) if fn in [sinh, cosh] and tanh in fs: extra.append((tanh, v)) terms.extend(extra) x = gcd*Mul(*key) r = build_ideal(x, terms) res.extend(r) newgens.extend({fn(v*x) for fn, v in terms}) # Add generators for compound expressions from iterables for fn, args in iterables: if fn == tan: # Tan expressions are recovered from sin and cos. iterables.extend([(sin, args), (cos, args)]) elif fn == tanh: # Tanh expressions are recovered from sihn and cosh. iterables.extend([(sinh, args), (cosh, args)]) else: dummys = symbols('d:%i' % len(args), cls=Dummy) expr = fn( Add(*dummys)).expand(trig=True).subs(list(zip(dummys, args))) res.append(fn(Add(*args)) - expr) if myI in gens: res.append(myI**2 + 1) freegens.remove(myI) newgens.append(myI) return res, freegens, newgens myI = Dummy('I') expr = expr.subs(S.ImaginaryUnit, myI) subs = [(myI, S.ImaginaryUnit)] num, denom = cancel(expr).as_numer_denom() try: (pnum, pdenom), opt = parallel_poly_from_expr([num, denom]) except PolificationFailed: return expr debug('initial gens:', opt.gens) ideal, freegens, gens = analyse_gens(opt.gens, hints) debug('ideal:', ideal) debug('new gens:', gens, " -- len", len(gens)) debug('free gens:', freegens, " -- len", len(gens)) # NOTE we force the domain to be ZZ to stop polys from injecting generators # (which is usually a sign of a bug in the way we build the ideal) if not gens: return expr G = groebner(ideal, order=order, gens=gens, domain=ZZ) debug('groebner basis:', list(G), " -- len", len(G)) # If our fraction is a polynomial in the free generators, simplify all # coefficients separately: from sympy.simplify.ratsimp import ratsimpmodprime if freegens and pdenom.has_only_gens(*set(gens).intersection(pdenom.gens)): num = Poly(num, gens=gens+freegens).eject(*gens) res = [] for monom, coeff in num.terms(): ourgens = set(parallel_poly_from_expr([coeff, denom])[1].gens) # We compute the transitive closure of all generators that can # be reached from our generators through relations in the ideal. changed = True while changed: changed = False for p in ideal: p = Poly(p) if not ourgens.issuperset(p.gens) and \ not p.has_only_gens(*set(p.gens).difference(ourgens)): changed = True ourgens.update(p.exclude().gens) # NOTE preserve order! realgens = [x for x in gens if x in ourgens] # The generators of the ideal have now been (implicitly) split # into two groups: those involving ourgens and those that don't. # Since we took the transitive closure above, these two groups # live in subgrings generated by a *disjoint* set of variables. # Any sensible groebner basis algorithm will preserve this disjoint # structure (i.e. the elements of the groebner basis can be split # similarly), and and the two subsets of the groebner basis then # form groebner bases by themselves. (For the smaller generating # sets, of course.) ourG = [g.as_expr() for g in G.polys if g.has_only_gens(*ourgens.intersection(g.gens))] res.append(Mul(*[a**b for a, b in zip(freegens, monom)]) * \ ratsimpmodprime(coeff/denom, ourG, order=order, gens=realgens, quick=quick, domain=ZZ, polynomial=polynomial).subs(subs)) return Add(*res) # NOTE The following is simpler and has less assumptions on the # groebner basis algorithm. If the above turns out to be broken, # use this. return Add(*[Mul(*[a**b for a, b in zip(freegens, monom)]) * \ ratsimpmodprime(coeff/denom, list(G), order=order, gens=gens, quick=quick, domain=ZZ) for monom, coeff in num.terms()]) else: return ratsimpmodprime( expr, list(G), order=order, gens=freegens+gens, quick=quick, domain=ZZ, polynomial=polynomial).subs(subs) _trigs = (TrigonometricFunction, HyperbolicFunction) def _trigsimp_inverse(rv): def check_args(x, y): try: return x.args[0] == y.args[0] except IndexError: return False def f(rv): # for simple functions g = getattr(rv, 'inverse', None) if (g is not None and isinstance(rv.args[0], g()) and isinstance(g()(1), TrigonometricFunction)): return rv.args[0].args[0] # for atan2 simplifications, harder because atan2 has 2 args if isinstance(rv, atan2): y, x = rv.args if _coeff_isneg(y): return -f(atan2(-y, x)) elif _coeff_isneg(x): return S.Pi - f(atan2(y, -x)) if check_args(x, y): if isinstance(y, sin) and isinstance(x, cos): return x.args[0] if isinstance(y, cos) and isinstance(x, sin): return S.Pi / 2 - x.args[0] return rv return bottom_up(rv, f) def trigsimp(expr, inverse=False, **opts): """Returns a reduced expression by using known trig identities. Parameters ========== inverse : bool, optional If ``inverse=True``, it will be assumed that a composition of inverse functions, such as sin and asin, can be cancelled in any order. For example, ``asin(sin(x))`` will yield ``x`` without checking whether x belongs to the set where this relation is true. The default is False. Default : True method : string, optional Specifies the method to use. Valid choices are: - ``'matching'``, default - ``'groebner'`` - ``'combined'`` - ``'fu'`` - ``'old'`` If ``'matching'``, simplify the expression recursively by targeting common patterns. If ``'groebner'``, apply an experimental groebner basis algorithm. In this case further options are forwarded to ``trigsimp_groebner``, please refer to its docstring. If ``'combined'``, it first runs the groebner basis algorithm with small default parameters, then runs the ``'matching'`` algorithm. If ``'fu'``, run the collection of trigonometric transformations described by Fu, et al. (see the :py:func:`~sympy.simplify.fu.fu` docstring). If ``'old'``, the original SymPy trig simplification function is run. opts : Optional keyword arguments passed to the method. See each method's function docstring for details. Examples ======== >>> from sympy import trigsimp, sin, cos, log >>> from sympy.abc import x >>> e = 2*sin(x)**2 + 2*cos(x)**2 >>> trigsimp(e) 2 Simplification occurs wherever trigonometric functions are located. >>> trigsimp(log(e)) log(2) Using ``method='groebner'`` (or ``method='combined'``) might lead to greater simplification. The old trigsimp routine can be accessed as with method ``method='old'``. >>> from sympy import coth, tanh >>> t = 3*tanh(x)**7 - 2/coth(x)**7 >>> trigsimp(t, method='old') == t True >>> trigsimp(t) tanh(x)**7 """ from sympy.simplify.fu import fu expr = sympify(expr) _eval_trigsimp = getattr(expr, '_eval_trigsimp', None) if _eval_trigsimp is not None: return _eval_trigsimp(**opts) old = opts.pop('old', False) if not old: opts.pop('deep', None) opts.pop('recursive', None) method = opts.pop('method', 'matching') else: method = 'old' def groebnersimp(ex, **opts): def traverse(e): if e.is_Atom: return e args = [traverse(x) for x in e.args] if e.is_Function or e.is_Pow: args = [trigsimp_groebner(x, **opts) for x in args] return e.func(*args) new = traverse(ex) if not isinstance(new, Expr): return new return trigsimp_groebner(new, **opts) trigsimpfunc = { 'fu': (lambda x: fu(x, **opts)), 'matching': (lambda x: futrig(x)), 'groebner': (lambda x: groebnersimp(x, **opts)), 'combined': (lambda x: futrig(groebnersimp(x, polynomial=True, hints=[2, tan]))), 'old': lambda x: trigsimp_old(x, **opts), }[method] expr_simplified = trigsimpfunc(expr) if inverse: expr_simplified = _trigsimp_inverse(expr_simplified) return expr_simplified def exptrigsimp(expr): """ Simplifies exponential / trigonometric / hyperbolic functions. Examples ======== >>> from sympy import exptrigsimp, exp, cosh, sinh >>> from sympy.abc import z >>> exptrigsimp(exp(z) + exp(-z)) 2*cosh(z) >>> exptrigsimp(cosh(z) - sinh(z)) exp(-z) """ from sympy.simplify.fu import hyper_as_trig, TR2i def exp_trig(e): # select the better of e, and e rewritten in terms of exp or trig # functions choices = [e] if e.has(*_trigs): choices.append(e.rewrite(exp)) choices.append(e.rewrite(cos)) return min(*choices, key=count_ops) newexpr = bottom_up(expr, exp_trig) def f(rv): if not rv.is_Mul: return rv commutative_part, noncommutative_part = rv.args_cnc() # Since as_powers_dict loses order information, # if there is more than one noncommutative factor, # it should only be used to simplify the commutative part. if (len(noncommutative_part) > 1): return f(Mul(*commutative_part))*Mul(*noncommutative_part) rvd = rv.as_powers_dict() newd = rvd.copy() def signlog(expr, sign=S.One): if expr is S.Exp1: return sign, S.One elif isinstance(expr, exp) or (expr.is_Pow and expr.base == S.Exp1): return sign, expr.exp elif sign is S.One: return signlog(-expr, sign=-S.One) else: return None, None ee = rvd[S.Exp1] for k in rvd: if k.is_Add and len(k.args) == 2: # k == c*(1 + sign*E**x) c = k.args[0] sign, x = signlog(k.args[1]/c) if not x: continue m = rvd[k] newd[k] -= m if ee == -x*m/2: # sinh and cosh newd[S.Exp1] -= ee ee = 0 if sign == 1: newd[2*c*cosh(x/2)] += m else: newd[-2*c*sinh(x/2)] += m elif newd[1 - sign*S.Exp1**x] == -m: # tanh del newd[1 - sign*S.Exp1**x] if sign == 1: newd[-c/tanh(x/2)] += m else: newd[-c*tanh(x/2)] += m else: newd[1 + sign*S.Exp1**x] += m newd[c] += m return Mul(*[k**newd[k] for k in newd]) newexpr = bottom_up(newexpr, f) # sin/cos and sinh/cosh ratios to tan and tanh, respectively if newexpr.has(HyperbolicFunction): e, f = hyper_as_trig(newexpr) newexpr = f(TR2i(e)) if newexpr.has(TrigonometricFunction): newexpr = TR2i(newexpr) # can we ever generate an I where there was none previously? if not (newexpr.has(I) and not expr.has(I)): expr = newexpr return expr #-------------------- the old trigsimp routines --------------------- def trigsimp_old(expr, *, first=True, **opts): """ Reduces expression by using known trig identities. Notes ===== deep: - Apply trigsimp inside all objects with arguments recursive: - Use common subexpression elimination (cse()) and apply trigsimp recursively (this is quite expensive if the expression is large) method: - Determine the method to use. Valid choices are 'matching' (default), 'groebner', 'combined', 'fu' and 'futrig'. If 'matching', simplify the expression recursively by pattern matching. If 'groebner', apply an experimental groebner basis algorithm. In this case further options are forwarded to ``trigsimp_groebner``, please refer to its docstring. If 'combined', first run the groebner basis algorithm with small default parameters, then run the 'matching' algorithm. 'fu' runs the collection of trigonometric transformations described by Fu, et al. (see the `fu` docstring) while `futrig` runs a subset of Fu-transforms that mimic the behavior of `trigsimp`. compare: - show input and output from `trigsimp` and `futrig` when different, but returns the `trigsimp` value. Examples ======== >>> from sympy import trigsimp, sin, cos, log, cot >>> from sympy.abc import x >>> e = 2*sin(x)**2 + 2*cos(x)**2 >>> trigsimp(e, old=True) 2 >>> trigsimp(log(e), old=True) log(2*sin(x)**2 + 2*cos(x)**2) >>> trigsimp(log(e), deep=True, old=True) log(2) Using `method="groebner"` (or `"combined"`) can sometimes lead to a lot more simplification: >>> e = (-sin(x) + 1)/cos(x) + cos(x)/(-sin(x) + 1) >>> trigsimp(e, old=True) (1 - sin(x))/cos(x) + cos(x)/(1 - sin(x)) >>> trigsimp(e, method="groebner", old=True) 2/cos(x) >>> trigsimp(1/cot(x)**2, compare=True, old=True) futrig: tan(x)**2 cot(x)**(-2) """ old = expr if first: if not expr.has(*_trigs): return expr trigsyms = set().union(*[t.free_symbols for t in expr.atoms(*_trigs)]) if len(trigsyms) > 1: from sympy.simplify.simplify import separatevars d = separatevars(expr) if d.is_Mul: d = separatevars(d, dict=True) or d if isinstance(d, dict): expr = 1 for k, v in d.items(): # remove hollow factoring was = v v = expand_mul(v) opts['first'] = False vnew = trigsimp(v, **opts) if vnew == v: vnew = was expr *= vnew old = expr else: if d.is_Add: for s in trigsyms: r, e = expr.as_independent(s) if r: opts['first'] = False expr = r + trigsimp(e, **opts) if not expr.is_Add: break old = expr recursive = opts.pop('recursive', False) deep = opts.pop('deep', False) method = opts.pop('method', 'matching') def groebnersimp(ex, deep, **opts): def traverse(e): if e.is_Atom: return e args = [traverse(x) for x in e.args] if e.is_Function or e.is_Pow: args = [trigsimp_groebner(x, **opts) for x in args] return e.func(*args) if deep: ex = traverse(ex) return trigsimp_groebner(ex, **opts) trigsimpfunc = { 'matching': (lambda x, d: _trigsimp(x, d)), 'groebner': (lambda x, d: groebnersimp(x, d, **opts)), 'combined': (lambda x, d: _trigsimp(groebnersimp(x, d, polynomial=True, hints=[2, tan]), d)) }[method] if recursive: w, g = cse(expr) g = trigsimpfunc(g[0], deep) for sub in reversed(w): g = g.subs(sub[0], sub[1]) g = trigsimpfunc(g, deep) result = g else: result = trigsimpfunc(expr, deep) if opts.get('compare', False): f = futrig(old) if f != result: print('\tfutrig:', f) return result def _dotrig(a, b): """Helper to tell whether ``a`` and ``b`` have the same sorts of symbols in them -- no need to test hyperbolic patterns against expressions that have no hyperbolics in them.""" return a.func == b.func and ( a.has(TrigonometricFunction) and b.has(TrigonometricFunction) or a.has(HyperbolicFunction) and b.has(HyperbolicFunction)) _trigpat = None def _trigpats(): global _trigpat a, b, c = symbols('a b c', cls=Wild) d = Wild('d', commutative=False) # for the simplifications like sinh/cosh -> tanh: # DO NOT REORDER THE FIRST 14 since these are assumed to be in this # order in _match_div_rewrite. matchers_division = ( (a*sin(b)**c/cos(b)**c, a*tan(b)**c, sin(b), cos(b)), (a*tan(b)**c*cos(b)**c, a*sin(b)**c, sin(b), cos(b)), (a*cot(b)**c*sin(b)**c, a*cos(b)**c, sin(b), cos(b)), (a*tan(b)**c/sin(b)**c, a/cos(b)**c, sin(b), cos(b)), (a*cot(b)**c/cos(b)**c, a/sin(b)**c, sin(b), cos(b)), (a*cot(b)**c*tan(b)**c, a, sin(b), cos(b)), (a*(cos(b) + 1)**c*(cos(b) - 1)**c, a*(-sin(b)**2)**c, cos(b) + 1, cos(b) - 1), (a*(sin(b) + 1)**c*(sin(b) - 1)**c, a*(-cos(b)**2)**c, sin(b) + 1, sin(b) - 1), (a*sinh(b)**c/cosh(b)**c, a*tanh(b)**c, S.One, S.One), (a*tanh(b)**c*cosh(b)**c, a*sinh(b)**c, S.One, S.One), (a*coth(b)**c*sinh(b)**c, a*cosh(b)**c, S.One, S.One), (a*tanh(b)**c/sinh(b)**c, a/cosh(b)**c, S.One, S.One), (a*coth(b)**c/cosh(b)**c, a/sinh(b)**c, S.One, S.One), (a*coth(b)**c*tanh(b)**c, a, S.One, S.One), (c*(tanh(a) + tanh(b))/(1 + tanh(a)*tanh(b)), tanh(a + b)*c, S.One, S.One), ) matchers_add = ( (c*sin(a)*cos(b) + c*cos(a)*sin(b) + d, sin(a + b)*c + d), (c*cos(a)*cos(b) - c*sin(a)*sin(b) + d, cos(a + b)*c + d), (c*sin(a)*cos(b) - c*cos(a)*sin(b) + d, sin(a - b)*c + d), (c*cos(a)*cos(b) + c*sin(a)*sin(b) + d, cos(a - b)*c + d), (c*sinh(a)*cosh(b) + c*sinh(b)*cosh(a) + d, sinh(a + b)*c + d), (c*cosh(a)*cosh(b) + c*sinh(a)*sinh(b) + d, cosh(a + b)*c + d), ) # for cos(x)**2 + sin(x)**2 -> 1 matchers_identity = ( (a*sin(b)**2, a - a*cos(b)**2), (a*tan(b)**2, a*(1/cos(b))**2 - a), (a*cot(b)**2, a*(1/sin(b))**2 - a), (a*sin(b + c), a*(sin(b)*cos(c) + sin(c)*cos(b))), (a*cos(b + c), a*(cos(b)*cos(c) - sin(b)*sin(c))), (a*tan(b + c), a*((tan(b) + tan(c))/(1 - tan(b)*tan(c)))), (a*sinh(b)**2, a*cosh(b)**2 - a), (a*tanh(b)**2, a - a*(1/cosh(b))**2), (a*coth(b)**2, a + a*(1/sinh(b))**2), (a*sinh(b + c), a*(sinh(b)*cosh(c) + sinh(c)*cosh(b))), (a*cosh(b + c), a*(cosh(b)*cosh(c) + sinh(b)*sinh(c))), (a*tanh(b + c), a*((tanh(b) + tanh(c))/(1 + tanh(b)*tanh(c)))), ) # Reduce any lingering artifacts, such as sin(x)**2 changing # to 1-cos(x)**2 when sin(x)**2 was "simpler" artifacts = ( (a - a*cos(b)**2 + c, a*sin(b)**2 + c, cos), (a - a*(1/cos(b))**2 + c, -a*tan(b)**2 + c, cos), (a - a*(1/sin(b))**2 + c, -a*cot(b)**2 + c, sin), (a - a*cosh(b)**2 + c, -a*sinh(b)**2 + c, cosh), (a - a*(1/cosh(b))**2 + c, a*tanh(b)**2 + c, cosh), (a + a*(1/sinh(b))**2 + c, a*coth(b)**2 + c, sinh), # same as above but with noncommutative prefactor (a*d - a*d*cos(b)**2 + c, a*d*sin(b)**2 + c, cos), (a*d - a*d*(1/cos(b))**2 + c, -a*d*tan(b)**2 + c, cos), (a*d - a*d*(1/sin(b))**2 + c, -a*d*cot(b)**2 + c, sin), (a*d - a*d*cosh(b)**2 + c, -a*d*sinh(b)**2 + c, cosh), (a*d - a*d*(1/cosh(b))**2 + c, a*d*tanh(b)**2 + c, cosh), (a*d + a*d*(1/sinh(b))**2 + c, a*d*coth(b)**2 + c, sinh), ) _trigpat = (a, b, c, d, matchers_division, matchers_add, matchers_identity, artifacts) return _trigpat def _replace_mul_fpowxgpow(expr, f, g, rexp, h, rexph): """Helper for _match_div_rewrite. Replace f(b_)**c_*g(b_)**(rexp(c_)) with h(b)**rexph(c) if f(b_) and g(b_) are both positive or if c_ is an integer. """ # assert expr.is_Mul and expr.is_commutative and f != g fargs = defaultdict(int) gargs = defaultdict(int) args = [] for x in expr.args: if x.is_Pow or x.func in (f, g): b, e = x.as_base_exp() if b.is_positive or e.is_integer: if b.func == f: fargs[b.args[0]] += e continue elif b.func == g: gargs[b.args[0]] += e continue args.append(x) common = set(fargs) & set(gargs) hit = False while common: key = common.pop() fe = fargs.pop(key) ge = gargs.pop(key) if fe == rexp(ge): args.append(h(key)**rexph(fe)) hit = True else: fargs[key] = fe gargs[key] = ge if not hit: return expr while fargs: key, e = fargs.popitem() args.append(f(key)**e) while gargs: key, e = gargs.popitem() args.append(g(key)**e) return Mul(*args) _idn = lambda x: x _midn = lambda x: -x _one = lambda x: S.One def _match_div_rewrite(expr, i): """helper for __trigsimp""" if i == 0: expr = _replace_mul_fpowxgpow(expr, sin, cos, _midn, tan, _idn) elif i == 1: expr = _replace_mul_fpowxgpow(expr, tan, cos, _idn, sin, _idn) elif i == 2: expr = _replace_mul_fpowxgpow(expr, cot, sin, _idn, cos, _idn) elif i == 3: expr = _replace_mul_fpowxgpow(expr, tan, sin, _midn, cos, _midn) elif i == 4: expr = _replace_mul_fpowxgpow(expr, cot, cos, _midn, sin, _midn) elif i == 5: expr = _replace_mul_fpowxgpow(expr, cot, tan, _idn, _one, _idn) # i in (6, 7) is skipped elif i == 8: expr = _replace_mul_fpowxgpow(expr, sinh, cosh, _midn, tanh, _idn) elif i == 9: expr = _replace_mul_fpowxgpow(expr, tanh, cosh, _idn, sinh, _idn) elif i == 10: expr = _replace_mul_fpowxgpow(expr, coth, sinh, _idn, cosh, _idn) elif i == 11: expr = _replace_mul_fpowxgpow(expr, tanh, sinh, _midn, cosh, _midn) elif i == 12: expr = _replace_mul_fpowxgpow(expr, coth, cosh, _midn, sinh, _midn) elif i == 13: expr = _replace_mul_fpowxgpow(expr, coth, tanh, _idn, _one, _idn) else: return None return expr def _trigsimp(expr, deep=False): # protect the cache from non-trig patterns; we only allow # trig patterns to enter the cache if expr.has(*_trigs): return __trigsimp(expr, deep) return expr @cacheit def __trigsimp(expr, deep=False): """recursive helper for trigsimp""" from sympy.simplify.fu import TR10i if _trigpat is None: _trigpats() a, b, c, d, matchers_division, matchers_add, \ matchers_identity, artifacts = _trigpat if expr.is_Mul: # do some simplifications like sin/cos -> tan: if not expr.is_commutative: com, nc = expr.args_cnc() expr = _trigsimp(Mul._from_args(com), deep)*Mul._from_args(nc) else: for i, (pattern, simp, ok1, ok2) in enumerate(matchers_division): if not _dotrig(expr, pattern): continue newexpr = _match_div_rewrite(expr, i) if newexpr is not None: if newexpr != expr: expr = newexpr break else: continue # use SymPy matching instead res = expr.match(pattern) if res and res.get(c, 0): if not res[c].is_integer: ok = ok1.subs(res) if not ok.is_positive: continue ok = ok2.subs(res) if not ok.is_positive: continue # if "a" contains any of trig or hyperbolic funcs with # argument "b" then skip the simplification if any(w.args[0] == res[b] for w in res[a].atoms( TrigonometricFunction, HyperbolicFunction)): continue # simplify and finish: expr = simp.subs(res) break # process below if expr.is_Add: args = [] for term in expr.args: if not term.is_commutative: com, nc = term.args_cnc() nc = Mul._from_args(nc) term = Mul._from_args(com) else: nc = S.One term = _trigsimp(term, deep) for pattern, result in matchers_identity: res = term.match(pattern) if res is not None: term = result.subs(res) break args.append(term*nc) if args != expr.args: expr = Add(*args) expr = min(expr, expand(expr), key=count_ops) if expr.is_Add: for pattern, result in matchers_add: if not _dotrig(expr, pattern): continue expr = TR10i(expr) if expr.has(HyperbolicFunction): res = expr.match(pattern) # if "d" contains any trig or hyperbolic funcs with # argument "a" or "b" then skip the simplification; # this isn't perfect -- see tests if res is None or not (a in res and b in res) or any( w.args[0] in (res[a], res[b]) for w in res[d].atoms( TrigonometricFunction, HyperbolicFunction)): continue expr = result.subs(res) break # Reduce any lingering artifacts, such as sin(x)**2 changing # to 1 - cos(x)**2 when sin(x)**2 was "simpler" for pattern, result, ex in artifacts: if not _dotrig(expr, pattern): continue # Substitute a new wild that excludes some function(s) # to help influence a better match. This is because # sometimes, for example, 'a' would match sec(x)**2 a_t = Wild('a', exclude=[ex]) pattern = pattern.subs(a, a_t) result = result.subs(a, a_t) m = expr.match(pattern) was = None while m and was != expr: was = expr if m[a_t] == 0 or \ -m[a_t] in m[c].args or m[a_t] + m[c] == 0: break if d in m and m[a_t]*m[d] + m[c] == 0: break expr = result.subs(m) m = expr.match(pattern) m.setdefault(c, S.Zero) elif expr.is_Mul or expr.is_Pow or deep and expr.args: expr = expr.func(*[_trigsimp(a, deep) for a in expr.args]) try: if not expr.has(*_trigs): raise TypeError e = expr.atoms(exp) new = expr.rewrite(exp, deep=deep) if new == e: raise TypeError fnew = factor(new) if fnew != new: new = sorted([new, factor(new)], key=count_ops)[0] # if all exp that were introduced disappeared then accept it if not (new.atoms(exp) - e): expr = new except TypeError: pass return expr #------------------- end of old trigsimp routines -------------------- def futrig(e, *, hyper=True, **kwargs): """Return simplified ``e`` using Fu-like transformations. This is not the "Fu" algorithm. This is called by default from ``trigsimp``. By default, hyperbolics subexpressions will be simplified, but this can be disabled by setting ``hyper=False``. Examples ======== >>> from sympy import trigsimp, tan, sinh, tanh >>> from sympy.simplify.trigsimp import futrig >>> from sympy.abc import x >>> trigsimp(1/tan(x)**2) tan(x)**(-2) >>> futrig(sinh(x)/tanh(x)) cosh(x) """ from sympy.simplify.fu import hyper_as_trig e = sympify(e) if not isinstance(e, Basic): return e if not e.args: return e old = e e = bottom_up(e, _futrig) if hyper and e.has(HyperbolicFunction): e, f = hyper_as_trig(e) e = f(bottom_up(e, _futrig)) if e != old and e.is_Mul and e.args[0].is_Rational: # redistribute leading coeff on 2-arg Add e = Mul(*e.as_coeff_Mul()) return e def _futrig(e): """Helper for futrig.""" from sympy.simplify.fu import ( TR1, TR2, TR3, TR2i, TR10, L, TR10i, TR8, TR6, TR15, TR16, TR111, TR5, TRmorrie, TR11, _TR11, TR14, TR22, TR12) if not e.has(TrigonometricFunction): return e if e.is_Mul: coeff, e = e.as_independent(TrigonometricFunction) else: coeff = None Lops = lambda x: (L(x), x.count_ops(), _nodes(x), len(x.args), x.is_Add) trigs = lambda x: x.has(TrigonometricFunction) tree = [identity, ( TR3, # canonical angles TR1, # sec-csc -> cos-sin TR12, # expand tan of sum lambda x: _eapply(factor, x, trigs), TR2, # tan-cot -> sin-cos [identity, lambda x: _eapply(_mexpand, x, trigs)], TR2i, # sin-cos ratio -> tan lambda x: _eapply(lambda i: factor(i.normal()), x, trigs), TR14, # factored identities TR5, # sin-pow -> cos_pow TR10, # sin-cos of sums -> sin-cos prod TR11, _TR11, TR6, # reduce double angles and rewrite cos pows lambda x: _eapply(factor, x, trigs), TR14, # factored powers of identities [identity, lambda x: _eapply(_mexpand, x, trigs)], TR10i, # sin-cos products > sin-cos of sums TRmorrie, [identity, TR8], # sin-cos products -> sin-cos of sums [identity, lambda x: TR2i(TR2(x))], # tan -> sin-cos -> tan [ lambda x: _eapply(expand_mul, TR5(x), trigs), lambda x: _eapply( expand_mul, TR15(x), trigs)], # pos/neg powers of sin [ lambda x: _eapply(expand_mul, TR6(x), trigs), lambda x: _eapply( expand_mul, TR16(x), trigs)], # pos/neg powers of cos TR111, # tan, sin, cos to neg power -> cot, csc, sec [identity, TR2i], # sin-cos ratio to tan [identity, lambda x: _eapply( expand_mul, TR22(x), trigs)], # tan-cot to sec-csc TR1, TR2, TR2i, [identity, lambda x: _eapply( factor_terms, TR12(x), trigs)], # expand tan of sum )] e = greedy(tree, objective=Lops)(e) if coeff is not None: e = coeff * e return e def _is_Expr(e): """_eapply helper to tell whether ``e`` and all its args are Exprs.""" if isinstance(e, Derivative): return _is_Expr(e.expr) if not isinstance(e, Expr): return False return all(_is_Expr(i) for i in e.args) def _eapply(func, e, cond=None): """Apply ``func`` to ``e`` if all args are Exprs else only apply it to those args that *are* Exprs.""" if not isinstance(e, Expr): return e if _is_Expr(e) or not e.args: return func(e) return e.func(*[ _eapply(func, ei) if (cond is None or cond(ei)) else ei for ei in e.args])
b3c2b98e6c6f3e8630f03548a56d3e87e6eb1e55a2ddadd78fb0d0a0a2548e5f
from itertools import combinations_with_replacement from sympy.core import symbols, Add, Dummy from sympy.core.numbers import Rational from sympy.polys import cancel, ComputationFailed, parallel_poly_from_expr, reduced, Poly from sympy.polys.monomials import Monomial, monomial_div from sympy.polys.polyerrors import DomainError, PolificationFailed from sympy.utilities.misc import debug, debugf def ratsimp(expr): """ Put an expression over a common denominator, cancel and reduce. Examples ======== >>> from sympy import ratsimp >>> from sympy.abc import x, y >>> ratsimp(1/x + 1/y) (x + y)/(x*y) """ f, g = cancel(expr).as_numer_denom() try: Q, r = reduced(f, [g], field=True, expand=False) except ComputationFailed: return f/g return Add(*Q) + cancel(r/g) def ratsimpmodprime(expr, G, *gens, quick=True, polynomial=False, **args): """ Simplifies a rational expression ``expr`` modulo the prime ideal generated by ``G``. ``G`` should be a Groebner basis of the ideal. Examples ======== >>> from sympy.simplify.ratsimp import ratsimpmodprime >>> from sympy.abc import x, y >>> eq = (x + y**5 + y)/(x - y) >>> ratsimpmodprime(eq, [x*y**5 - x - y], x, y, order='lex') (-x**2 - x*y - x - y)/(-x**2 + x*y) If ``polynomial`` is ``False``, the algorithm computes a rational simplification which minimizes the sum of the total degrees of the numerator and the denominator. If ``polynomial`` is ``True``, this function just brings numerator and denominator into a canonical form. This is much faster, but has potentially worse results. References ========== .. [1] M. Monagan, R. Pearce, Rational Simplification Modulo a Polynomial Ideal, https://dl.acm.org/doi/pdf/10.1145/1145768.1145809 (specifically, the second algorithm) """ from sympy.solvers.solvers import solve debug('ratsimpmodprime', expr) # usual preparation of polynomials: num, denom = cancel(expr).as_numer_denom() try: polys, opt = parallel_poly_from_expr([num, denom] + G, *gens, **args) except PolificationFailed: return expr domain = opt.domain if domain.has_assoc_Field: opt.domain = domain.get_field() else: raise DomainError( "Cannot compute rational simplification over %s" % domain) # compute only once leading_monomials = [g.LM(opt.order) for g in polys[2:]] tested = set() def staircase(n): """ Compute all monomials with degree less than ``n`` that are not divisible by any element of ``leading_monomials``. """ if n == 0: return [1] S = [] for mi in combinations_with_replacement(range(len(opt.gens)), n): m = [0]*len(opt.gens) for i in mi: m[i] += 1 if all(monomial_div(m, lmg) is None for lmg in leading_monomials): S.append(m) return [Monomial(s).as_expr(*opt.gens) for s in S] + staircase(n - 1) def _ratsimpmodprime(a, b, allsol, N=0, D=0): r""" Computes a rational simplification of ``a/b`` which minimizes the sum of the total degrees of the numerator and the denominator. Explanation =========== The algorithm proceeds by looking at ``a * d - b * c`` modulo the ideal generated by ``G`` for some ``c`` and ``d`` with degree less than ``a`` and ``b`` respectively. The coefficients of ``c`` and ``d`` are indeterminates and thus the coefficients of the normalform of ``a * d - b * c`` are linear polynomials in these indeterminates. If these linear polynomials, considered as system of equations, have a nontrivial solution, then `\frac{a}{b} \equiv \frac{c}{d}` modulo the ideal generated by ``G``. So, by construction, the degree of ``c`` and ``d`` is less than the degree of ``a`` and ``b``, so a simpler representation has been found. After a simpler representation has been found, the algorithm tries to reduce the degree of the numerator and denominator and returns the result afterwards. As an extension, if quick=False, we look at all possible degrees such that the total degree is less than *or equal to* the best current solution. We retain a list of all solutions of minimal degree, and try to find the best one at the end. """ c, d = a, b steps = 0 maxdeg = a.total_degree() + b.total_degree() if quick: bound = maxdeg - 1 else: bound = maxdeg while N + D <= bound: if (N, D) in tested: break tested.add((N, D)) M1 = staircase(N) M2 = staircase(D) debugf('%s / %s: %s, %s', (N, D, M1, M2)) Cs = symbols("c:%d" % len(M1), cls=Dummy) Ds = symbols("d:%d" % len(M2), cls=Dummy) ng = Cs + Ds c_hat = Poly( sum([Cs[i] * M1[i] for i in range(len(M1))]), opt.gens + ng) d_hat = Poly( sum([Ds[i] * M2[i] for i in range(len(M2))]), opt.gens + ng) r = reduced(a * d_hat - b * c_hat, G, opt.gens + ng, order=opt.order, polys=True)[1] S = Poly(r, gens=opt.gens).coeffs() sol = solve(S, Cs + Ds, particular=True, quick=True) if sol and not all(s == 0 for s in sol.values()): c = c_hat.subs(sol) d = d_hat.subs(sol) # The "free" variables occurring before as parameters # might still be in the substituted c, d, so set them # to the value chosen before: c = c.subs(dict(list(zip(Cs + Ds, [1] * (len(Cs) + len(Ds)))))) d = d.subs(dict(list(zip(Cs + Ds, [1] * (len(Cs) + len(Ds)))))) c = Poly(c, opt.gens) d = Poly(d, opt.gens) if d == 0: raise ValueError('Ideal not prime?') allsol.append((c_hat, d_hat, S, Cs + Ds)) if N + D != maxdeg: allsol = [allsol[-1]] break steps += 1 N += 1 D += 1 if steps > 0: c, d, allsol = _ratsimpmodprime(c, d, allsol, N, D - steps) c, d, allsol = _ratsimpmodprime(c, d, allsol, N - steps, D) return c, d, allsol # preprocessing. this improves performance a bit when deg(num) # and deg(denom) are large: num = reduced(num, G, opt.gens, order=opt.order)[1] denom = reduced(denom, G, opt.gens, order=opt.order)[1] if polynomial: return (num/denom).cancel() c, d, allsol = _ratsimpmodprime( Poly(num, opt.gens, domain=opt.domain), Poly(denom, opt.gens, domain=opt.domain), []) if not quick and allsol: debugf('Looking for best minimal solution. Got: %s', len(allsol)) newsol = [] for c_hat, d_hat, S, ng in allsol: sol = solve(S, ng, particular=True, quick=False) # all values of sol should be numbers; if not, solve is broken newsol.append((c_hat.subs(sol), d_hat.subs(sol))) c, d = min(newsol, key=lambda x: len(x[0].terms()) + len(x[1].terms())) if not domain.is_Field: cn, c = c.clear_denoms(convert=True) dn, d = d.clear_denoms(convert=True) r = Rational(cn, dn) else: r = Rational(1) return (c*r.q)/(d*r.p)
bb5ae80d05bab3c5a4f202ca8d0a55d08d9ec13a4f75fcacf2cfede6b5f29ad3
from sympy.core.numbers import Rational from sympy.core.singleton import S from sympy.core.relational import is_eq from sympy.functions.elementary.complexes import (conjugate, im, re, sign) from sympy.functions.elementary.exponential import (exp, log as ln) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, asin, atan2) from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.simplify.trigsimp import trigsimp from sympy.integrals.integrals import integrate from sympy.matrices.dense import MutableDenseMatrix as Matrix from sympy.core.sympify import sympify, _sympify from sympy.core.expr import Expr from sympy.core.logic import fuzzy_not, fuzzy_or from mpmath.libmp.libmpf import prec_to_dps def _check_norm(elements, norm): """validate if input norm is consistent""" if norm is not None and norm.is_number: if norm.is_positive is False: raise ValueError("Input norm must be positive.") numerical = all(i.is_number and i.is_real is True for i in elements) if numerical and is_eq(norm**2, sum(i**2 for i in elements)) is False: raise ValueError("Incompatible value for norm.") def _is_extrinsic(seq): """validate seq and return True if seq is lowercase and False if uppercase""" if type(seq) != str: raise ValueError('Expected seq to be a string.') if len(seq) != 3: raise ValueError("Expected 3 axes, got `{}`.".format(seq)) intrinsic = seq.isupper() extrinsic = seq.islower() if not (intrinsic or extrinsic): raise ValueError("seq must either be fully uppercase (for extrinsic " "rotations), or fully lowercase, for intrinsic " "rotations).") i, j, k = seq.lower() if (i == j) or (j == k): raise ValueError("Consecutive axes must be different") bad = set(seq) - set('xyzXYZ') if bad: raise ValueError("Expected axes from `seq` to be from " "['x', 'y', 'z'] or ['X', 'Y', 'Z'], " "got {}".format(''.join(bad))) return extrinsic class Quaternion(Expr): """Provides basic quaternion operations. Quaternion objects can be instantiated as Quaternion(a, b, c, d) as in (a + b*i + c*j + d*k). Parameters ========== norm : None or number Pre-defined quaternion norm. If a value is given, Quaternion.norm returns this pre-defined value instead of calculating the norm Examples ======== >>> from sympy import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q 1 + 2*i + 3*j + 4*k Quaternions over complex fields can be defined as : >>> from sympy import Quaternion >>> from sympy import symbols, I >>> x = symbols('x') >>> q1 = Quaternion(x, x**3, x, x**2, real_field = False) >>> q2 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) >>> q1 x + x**3*i + x*j + x**2*k >>> q2 (3 + 4*I) + (2 + 5*I)*i + 0*j + (7 + 8*I)*k Defining symbolic unit quaternions: >>> from sympy import Quaternion >>> from sympy.abc import w, x, y, z >>> q = Quaternion(w, x, y, z, norm=1) >>> q w + x*i + y*j + z*k >>> q.norm() 1 References ========== .. [1] http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/ .. [2] https://en.wikipedia.org/wiki/Quaternion """ _op_priority = 11.0 is_commutative = False def __new__(cls, a=0, b=0, c=0, d=0, real_field=True, norm=None): a, b, c, d = map(sympify, (a, b, c, d)) if any(i.is_commutative is False for i in [a, b, c, d]): raise ValueError("arguments have to be commutative") else: obj = Expr.__new__(cls, a, b, c, d) obj._a = a obj._b = b obj._c = c obj._d = d obj._real_field = real_field obj.set_norm(norm) return obj def set_norm(self, norm): """Sets norm of an already instantiated quaternion. Parameters ========== norm : None or number Pre-defined quaternion norm. If a value is given, Quaternion.norm returns this pre-defined value instead of calculating the norm Examples ======== >>> from sympy import Quaternion >>> from sympy.abc import a, b, c, d >>> q = Quaternion(a, b, c, d) >>> q.norm() sqrt(a**2 + b**2 + c**2 + d**2) Setting the norm: >>> q.set_norm(1) >>> q.norm() 1 Removing set norm: >>> q.set_norm(None) >>> q.norm() sqrt(a**2 + b**2 + c**2 + d**2) """ norm = sympify(norm) _check_norm(self.args, norm) self._norm = norm @property def a(self): return self._a @property def b(self): return self._b @property def c(self): return self._c @property def d(self): return self._d @property def real_field(self): return self._real_field @property def product_matrix_left(self): r"""Returns 4 x 4 Matrix equivalent to a Hamilton product from the left. This can be useful when treating quaternion elements as column vectors. Given a quaternion $q = a + bi + cj + dk$ where a, b, c and d are real numbers, the product matrix from the left is: .. math:: M = \begin{bmatrix} a &-b &-c &-d \\ b & a &-d & c \\ c & d & a &-b \\ d &-c & b & a \end{bmatrix} Examples ======== >>> from sympy import Quaternion >>> from sympy.abc import a, b, c, d >>> q1 = Quaternion(1, 0, 0, 1) >>> q2 = Quaternion(a, b, c, d) >>> q1.product_matrix_left Matrix([ [1, 0, 0, -1], [0, 1, -1, 0], [0, 1, 1, 0], [1, 0, 0, 1]]) >>> q1.product_matrix_left * q2.to_Matrix() Matrix([ [a - d], [b - c], [b + c], [a + d]]) This is equivalent to: >>> (q1 * q2).to_Matrix() Matrix([ [a - d], [b - c], [b + c], [a + d]]) """ return Matrix([ [self.a, -self.b, -self.c, -self.d], [self.b, self.a, -self.d, self.c], [self.c, self.d, self.a, -self.b], [self.d, -self.c, self.b, self.a]]) @property def product_matrix_right(self): r"""Returns 4 x 4 Matrix equivalent to a Hamilton product from the right. This can be useful when treating quaternion elements as column vectors. Given a quaternion $q = a + bi + cj + dk$ where a, b, c and d are real numbers, the product matrix from the left is: .. math:: M = \begin{bmatrix} a &-b &-c &-d \\ b & a & d &-c \\ c &-d & a & b \\ d & c &-b & a \end{bmatrix} Examples ======== >>> from sympy import Quaternion >>> from sympy.abc import a, b, c, d >>> q1 = Quaternion(a, b, c, d) >>> q2 = Quaternion(1, 0, 0, 1) >>> q2.product_matrix_right Matrix([ [1, 0, 0, -1], [0, 1, 1, 0], [0, -1, 1, 0], [1, 0, 0, 1]]) Note the switched arguments: the matrix represents the quaternion on the right, but is still considered as a matrix multiplication from the left. >>> q2.product_matrix_right * q1.to_Matrix() Matrix([ [ a - d], [ b + c], [-b + c], [ a + d]]) This is equivalent to: >>> (q1 * q2).to_Matrix() Matrix([ [ a - d], [ b + c], [-b + c], [ a + d]]) """ return Matrix([ [self.a, -self.b, -self.c, -self.d], [self.b, self.a, self.d, -self.c], [self.c, -self.d, self.a, self.b], [self.d, self.c, -self.b, self.a]]) def to_Matrix(self, vector_only=False): """Returns elements of quaternion as a column vector. By default, a Matrix of length 4 is returned, with the real part as the first element. If vector_only is True, returns only imaginary part as a Matrix of length 3. Parameters ========== vector_only : bool If True, only imaginary part is returned. Default value: False Returns ======= Matrix A column vector constructed by the elements of the quaternion. Examples ======== >>> from sympy import Quaternion >>> from sympy.abc import a, b, c, d >>> q = Quaternion(a, b, c, d) >>> q a + b*i + c*j + d*k >>> q.to_Matrix() Matrix([ [a], [b], [c], [d]]) >>> q.to_Matrix(vector_only=True) Matrix([ [b], [c], [d]]) """ if vector_only: return Matrix(self.args[1:]) else: return Matrix(self.args) @classmethod def from_Matrix(cls, elements): """Returns quaternion from elements of a column vector`. If vector_only is True, returns only imaginary part as a Matrix of length 3. Parameters ========== elements : Matrix, list or tuple of length 3 or 4. If length is 3, assume real part is zero. Default value: False Returns ======= Quaternion A quaternion created from the input elements. Examples ======== >>> from sympy import Quaternion >>> from sympy.abc import a, b, c, d >>> q = Quaternion.from_Matrix([a, b, c, d]) >>> q a + b*i + c*j + d*k >>> q = Quaternion.from_Matrix([b, c, d]) >>> q 0 + b*i + c*j + d*k """ length = len(elements) if length != 3 and length != 4: raise ValueError("Input elements must have length 3 or 4, got {} " "elements".format(length)) if length == 3: return Quaternion(0, *elements) else: return Quaternion(*elements) @classmethod def from_euler(cls, angles, seq): """Returns quaternion equivalent to rotation represented by the Euler angles, in the sequence defined by ``seq``. Parameters ========== angles : list, tuple or Matrix of 3 numbers The Euler angles (in radians). seq : string of length 3 Represents the sequence of rotations. For intrinsic rotations, seq must be all lowercase and its elements must be from the set ``{'x', 'y', 'z'}`` For extrinsic rotations, seq must be all uppercase and its elements must be from the set ``{'X', 'Y', 'Z'}`` Returns ======= Quaternion The normalized rotation quaternion calculated from the Euler angles in the given sequence. Examples ======== >>> from sympy import Quaternion >>> from sympy import pi >>> q = Quaternion.from_euler([pi/2, 0, 0], 'xyz') >>> q sqrt(2)/2 + sqrt(2)/2*i + 0*j + 0*k >>> q = Quaternion.from_euler([0, pi/2, pi] , 'zyz') >>> q 0 + (-sqrt(2)/2)*i + 0*j + sqrt(2)/2*k >>> q = Quaternion.from_euler([0, pi/2, pi] , 'ZYZ') >>> q 0 + sqrt(2)/2*i + 0*j + sqrt(2)/2*k """ if len(angles) != 3: raise ValueError("3 angles must be given.") extrinsic = _is_extrinsic(seq) i, j, k = seq.lower() # get elementary basis vectors ei = [1 if n == i else 0 for n in 'xyz'] ej = [1 if n == j else 0 for n in 'xyz'] ek = [1 if n == k else 0 for n in 'xyz'] # calculate distinct quaternions qi = cls.from_axis_angle(ei, angles[0]) qj = cls.from_axis_angle(ej, angles[1]) qk = cls.from_axis_angle(ek, angles[2]) if extrinsic: return trigsimp(qk * qj * qi) else: return trigsimp(qi * qj * qk) def to_euler(self, seq, angle_addition=True, avoid_square_root=False): r"""Returns Euler angles representing same rotation as the quaternion, in the sequence given by ``seq``. This implements the method described in [1]_. For degenerate cases (gymbal lock cases), the third angle is set to zero. Parameters ========== seq : string of length 3 Represents the sequence of rotations. For intrinsic rotations, seq must be all lowercase and its elements must be from the set ``{'x', 'y', 'z'}`` For extrinsic rotations, seq must be all uppercase and its elements must be from the set ``{'X', 'Y', 'Z'}`` angle_addition : bool When True, first and third angles are given as an addition and subtraction of two simpler ``atan2`` expressions. When False, the first and third angles are each given by a single more complicated ``atan2`` expression. This equivalent expression is given by: .. math:: \operatorname{atan_2} (b,a) \pm \operatorname{atan_2} (d,c) = \operatorname{atan_2} (bc\pm ad, ac\mp bd) Default value: True avoid_square_root : bool When True, the second angle is calculated with an expression based on ``acos``, which is slightly more complicated but avoids a square root. When False, second angle is calculated with ``atan2``, which is simpler and can be better for numerical reasons (some numerical implementations of ``acos`` have problems near zero). Default value: False Returns ======= Tuple The Euler angles calculated from the quaternion Examples ======== >>> from sympy import Quaternion >>> from sympy.abc import a, b, c, d >>> euler = Quaternion(a, b, c, d).to_euler('zyz') >>> euler (-atan2(-b, c) + atan2(d, a), 2*atan2(sqrt(b**2 + c**2), sqrt(a**2 + d**2)), atan2(-b, c) + atan2(d, a)) References ========== .. [1] https://doi.org/10.1371/journal.pone.0276302 """ if self.is_zero_quaternion(): raise ValueError('Cannot convert a quaternion with norm 0.') angles = [0, 0, 0] extrinsic = _is_extrinsic(seq) i, j, k = seq.lower() # get index corresponding to elementary basis vectors i = 'xyz'.index(i) + 1 j = 'xyz'.index(j) + 1 k = 'xyz'.index(k) + 1 if not extrinsic: i, k = k, i # check if sequence is symmetric symmetric = i == k if symmetric: k = 6 - i - j # parity of the permutation sign = (i - j) * (j - k) * (k - i) // 2 # permutate elements elements = [self.a, self.b, self.c, self.d] a = elements[0] b = elements[i] c = elements[j] d = elements[k] * sign if not symmetric: a, b, c, d = a - c, b + d, c + a, d - b if avoid_square_root: if symmetric: n2 = self.norm()**2 angles[1] = acos((a * a + b * b - c * c - d * d) / n2) else: n2 = 2 * self.norm()**2 angles[1] = asin((c * c + d * d - a * a - b * b) / n2) else: angles[1] = 2 * atan2(sqrt(c * c + d * d), sqrt(a * a + b * b)) if not symmetric: angles[1] -= S.Pi / 2 # Check for singularities in numerical cases case = 0 if is_eq(c, S.Zero) and is_eq(d, S.Zero): case = 1 if is_eq(a, S.Zero) and is_eq(b, S.Zero): case = 2 if case == 0: if angle_addition: angles[0] = atan2(b, a) + atan2(d, c) angles[2] = atan2(b, a) - atan2(d, c) else: angles[0] = atan2(b*c + a*d, a*c - b*d) angles[2] = atan2(b*c - a*d, a*c + b*d) else: # any degenerate case angles[2 * (not extrinsic)] = S.Zero if case == 1: angles[2 * extrinsic] = 2 * atan2(b, a) else: angles[2 * extrinsic] = 2 * atan2(d, c) angles[2 * extrinsic] *= (-1 if extrinsic else 1) # for Tait-Bryan angles if not symmetric: angles[0] *= sign if extrinsic: return tuple(angles[::-1]) else: return tuple(angles) @classmethod def from_axis_angle(cls, vector, angle): """Returns a rotation quaternion given the axis and the angle of rotation. Parameters ========== vector : tuple of three numbers The vector representation of the given axis. angle : number The angle by which axis is rotated (in radians). Returns ======= Quaternion The normalized rotation quaternion calculated from the given axis and the angle of rotation. Examples ======== >>> from sympy import Quaternion >>> from sympy import pi, sqrt >>> q = Quaternion.from_axis_angle((sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), 2*pi/3) >>> q 1/2 + 1/2*i + 1/2*j + 1/2*k """ (x, y, z) = vector norm = sqrt(x**2 + y**2 + z**2) (x, y, z) = (x / norm, y / norm, z / norm) s = sin(angle * S.Half) a = cos(angle * S.Half) b = x * s c = y * s d = z * s # note that this quaternion is already normalized by construction: # c^2 + (s*x)^2 + (s*y)^2 + (s*z)^2 = c^2 + s^2*(x^2 + y^2 + z^2) = c^2 + s^2 * 1 = c^2 + s^2 = 1 # so, what we return is a normalized quaternion return cls(a, b, c, d) @classmethod def from_rotation_matrix(cls, M): """Returns the equivalent quaternion of a matrix. The quaternion will be normalized only if the matrix is special orthogonal (orthogonal and det(M) = 1). Parameters ========== M : Matrix Input matrix to be converted to equivalent quaternion. M must be special orthogonal (orthogonal and det(M) = 1) for the quaternion to be normalized. Returns ======= Quaternion The quaternion equivalent to given matrix. Examples ======== >>> from sympy import Quaternion >>> from sympy import Matrix, symbols, cos, sin, trigsimp >>> x = symbols('x') >>> M = Matrix([[cos(x), -sin(x), 0], [sin(x), cos(x), 0], [0, 0, 1]]) >>> q = trigsimp(Quaternion.from_rotation_matrix(M)) >>> q sqrt(2)*sqrt(cos(x) + 1)/2 + 0*i + 0*j + sqrt(2 - 2*cos(x))*sign(sin(x))/2*k """ absQ = M.det()**Rational(1, 3) a = sqrt(absQ + M[0, 0] + M[1, 1] + M[2, 2]) / 2 b = sqrt(absQ + M[0, 0] - M[1, 1] - M[2, 2]) / 2 c = sqrt(absQ - M[0, 0] + M[1, 1] - M[2, 2]) / 2 d = sqrt(absQ - M[0, 0] - M[1, 1] + M[2, 2]) / 2 b = b * sign(M[2, 1] - M[1, 2]) c = c * sign(M[0, 2] - M[2, 0]) d = d * sign(M[1, 0] - M[0, 1]) return Quaternion(a, b, c, d) def __add__(self, other): return self.add(other) def __radd__(self, other): return self.add(other) def __sub__(self, other): return self.add(other*-1) def __mul__(self, other): return self._generic_mul(self, _sympify(other)) def __rmul__(self, other): return self._generic_mul(_sympify(other), self) def __pow__(self, p): return self.pow(p) def __neg__(self): return Quaternion(-self._a, -self._b, -self._c, -self.d) def __truediv__(self, other): return self * sympify(other)**-1 def __rtruediv__(self, other): return sympify(other) * self**-1 def _eval_Integral(self, *args): return self.integrate(*args) def diff(self, *symbols, **kwargs): kwargs.setdefault('evaluate', True) return self.func(*[a.diff(*symbols, **kwargs) for a in self.args]) def add(self, other): """Adds quaternions. Parameters ========== other : Quaternion The quaternion to add to current (self) quaternion. Returns ======= Quaternion The resultant quaternion after adding self to other Examples ======== >>> from sympy import Quaternion >>> from sympy import symbols >>> q1 = Quaternion(1, 2, 3, 4) >>> q2 = Quaternion(5, 6, 7, 8) >>> q1.add(q2) 6 + 8*i + 10*j + 12*k >>> q1 + 5 6 + 2*i + 3*j + 4*k >>> x = symbols('x', real = True) >>> q1.add(x) (x + 1) + 2*i + 3*j + 4*k Quaternions over complex fields : >>> from sympy import Quaternion >>> from sympy import I >>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) >>> q3.add(2 + 3*I) (5 + 7*I) + (2 + 5*I)*i + 0*j + (7 + 8*I)*k """ q1 = self q2 = sympify(other) # If q2 is a number or a SymPy expression instead of a quaternion if not isinstance(q2, Quaternion): if q1.real_field and q2.is_complex: return Quaternion(re(q2) + q1.a, im(q2) + q1.b, q1.c, q1.d) elif q2.is_commutative: return Quaternion(q1.a + q2, q1.b, q1.c, q1.d) else: raise ValueError("Only commutative expressions can be added with a Quaternion.") return Quaternion(q1.a + q2.a, q1.b + q2.b, q1.c + q2.c, q1.d + q2.d) def mul(self, other): """Multiplies quaternions. Parameters ========== other : Quaternion or symbol The quaternion to multiply to current (self) quaternion. Returns ======= Quaternion The resultant quaternion after multiplying self with other Examples ======== >>> from sympy import Quaternion >>> from sympy import symbols >>> q1 = Quaternion(1, 2, 3, 4) >>> q2 = Quaternion(5, 6, 7, 8) >>> q1.mul(q2) (-60) + 12*i + 30*j + 24*k >>> q1.mul(2) 2 + 4*i + 6*j + 8*k >>> x = symbols('x', real = True) >>> q1.mul(x) x + 2*x*i + 3*x*j + 4*x*k Quaternions over complex fields : >>> from sympy import Quaternion >>> from sympy import I >>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) >>> q3.mul(2 + 3*I) (2 + 3*I)*(3 + 4*I) + (2 + 3*I)*(2 + 5*I)*i + 0*j + (2 + 3*I)*(7 + 8*I)*k """ return self._generic_mul(self, _sympify(other)) @staticmethod def _generic_mul(q1, q2): """Generic multiplication. Parameters ========== q1 : Quaternion or symbol q2 : Quaternion or symbol It is important to note that if neither q1 nor q2 is a Quaternion, this function simply returns q1 * q2. Returns ======= Quaternion The resultant quaternion after multiplying q1 and q2 Examples ======== >>> from sympy import Quaternion >>> from sympy import Symbol, S >>> q1 = Quaternion(1, 2, 3, 4) >>> q2 = Quaternion(5, 6, 7, 8) >>> Quaternion._generic_mul(q1, q2) (-60) + 12*i + 30*j + 24*k >>> Quaternion._generic_mul(q1, S(2)) 2 + 4*i + 6*j + 8*k >>> x = Symbol('x', real = True) >>> Quaternion._generic_mul(q1, x) x + 2*x*i + 3*x*j + 4*x*k Quaternions over complex fields : >>> from sympy import I >>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) >>> Quaternion._generic_mul(q3, 2 + 3*I) (2 + 3*I)*(3 + 4*I) + (2 + 3*I)*(2 + 5*I)*i + 0*j + (2 + 3*I)*(7 + 8*I)*k """ # None is a Quaternion: if not isinstance(q1, Quaternion) and not isinstance(q2, Quaternion): return q1 * q2 # If q1 is a number or a SymPy expression instead of a quaternion if not isinstance(q1, Quaternion): if q2.real_field and q1.is_complex: return Quaternion(re(q1), im(q1), 0, 0) * q2 elif q1.is_commutative: return Quaternion(q1 * q2.a, q1 * q2.b, q1 * q2.c, q1 * q2.d) else: raise ValueError("Only commutative expressions can be multiplied with a Quaternion.") # If q2 is a number or a SymPy expression instead of a quaternion if not isinstance(q2, Quaternion): if q1.real_field and q2.is_complex: return q1 * Quaternion(re(q2), im(q2), 0, 0) elif q2.is_commutative: return Quaternion(q2 * q1.a, q2 * q1.b, q2 * q1.c, q2 * q1.d) else: raise ValueError("Only commutative expressions can be multiplied with a Quaternion.") # If any of the quaternions has a fixed norm, pre-compute norm if q1._norm is None and q2._norm is None: norm = None else: norm = q1.norm() * q2.norm() return Quaternion(-q1.b*q2.b - q1.c*q2.c - q1.d*q2.d + q1.a*q2.a, q1.b*q2.a + q1.c*q2.d - q1.d*q2.c + q1.a*q2.b, -q1.b*q2.d + q1.c*q2.a + q1.d*q2.b + q1.a*q2.c, q1.b*q2.c - q1.c*q2.b + q1.d*q2.a + q1.a * q2.d, norm=norm) def _eval_conjugate(self): """Returns the conjugate of the quaternion.""" q = self return Quaternion(q.a, -q.b, -q.c, -q.d, norm=q._norm) def norm(self): """Returns the norm of the quaternion.""" if self._norm is None: # check if norm is pre-defined q = self # trigsimp is used to simplify sin(x)^2 + cos(x)^2 (these terms # arise when from_axis_angle is used). self._norm = sqrt(trigsimp(q.a**2 + q.b**2 + q.c**2 + q.d**2)) return self._norm def normalize(self): """Returns the normalized form of the quaternion.""" q = self return q * (1/q.norm()) def inverse(self): """Returns the inverse of the quaternion.""" q = self if not q.norm(): raise ValueError("Cannot compute inverse for a quaternion with zero norm") return conjugate(q) * (1/q.norm()**2) def pow(self, p): """Finds the pth power of the quaternion. Parameters ========== p : int Power to be applied on quaternion. Returns ======= Quaternion Returns the p-th power of the current quaternion. Returns the inverse if p = -1. Examples ======== >>> from sympy import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q.pow(4) 668 + (-224)*i + (-336)*j + (-448)*k """ p = sympify(p) q = self if p == -1: return q.inverse() res = 1 if not p.is_Integer: return NotImplemented if p < 0: q, p = q.inverse(), -p while p > 0: if p % 2 == 1: res = q * res p = p//2 q = q * q return res def exp(self): """Returns the exponential of q (e^q). Returns ======= Quaternion Exponential of q (e^q). Examples ======== >>> from sympy import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q.exp() E*cos(sqrt(29)) + 2*sqrt(29)*E*sin(sqrt(29))/29*i + 3*sqrt(29)*E*sin(sqrt(29))/29*j + 4*sqrt(29)*E*sin(sqrt(29))/29*k """ # exp(q) = e^a(cos||v|| + v/||v||*sin||v||) q = self vector_norm = sqrt(q.b**2 + q.c**2 + q.d**2) a = exp(q.a) * cos(vector_norm) b = exp(q.a) * sin(vector_norm) * q.b / vector_norm c = exp(q.a) * sin(vector_norm) * q.c / vector_norm d = exp(q.a) * sin(vector_norm) * q.d / vector_norm return Quaternion(a, b, c, d) def _ln(self): """Returns the natural logarithm of the quaternion (_ln(q)). Examples ======== >>> from sympy import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q._ln() log(sqrt(30)) + 2*sqrt(29)*acos(sqrt(30)/30)/29*i + 3*sqrt(29)*acos(sqrt(30)/30)/29*j + 4*sqrt(29)*acos(sqrt(30)/30)/29*k """ # _ln(q) = _ln||q|| + v/||v||*arccos(a/||q||) q = self vector_norm = sqrt(q.b**2 + q.c**2 + q.d**2) q_norm = q.norm() a = ln(q_norm) b = q.b * acos(q.a / q_norm) / vector_norm c = q.c * acos(q.a / q_norm) / vector_norm d = q.d * acos(q.a / q_norm) / vector_norm return Quaternion(a, b, c, d) def _eval_subs(self, *args): elements = [i.subs(*args) for i in self.args] norm = self._norm try: norm = norm.subs(*args) except AttributeError: pass _check_norm(elements, norm) return Quaternion(*elements, norm=norm) def _eval_evalf(self, prec): """Returns the floating point approximations (decimal numbers) of the quaternion. Returns ======= Quaternion Floating point approximations of quaternion(self) Examples ======== >>> from sympy import Quaternion >>> from sympy import sqrt >>> q = Quaternion(1/sqrt(1), 1/sqrt(2), 1/sqrt(3), 1/sqrt(4)) >>> q.evalf() 1.00000000000000 + 0.707106781186547*i + 0.577350269189626*j + 0.500000000000000*k """ nprec = prec_to_dps(prec) return Quaternion(*[arg.evalf(n=nprec) for arg in self.args]) def pow_cos_sin(self, p): """Computes the pth power in the cos-sin form. Parameters ========== p : int Power to be applied on quaternion. Returns ======= Quaternion The p-th power in the cos-sin form. Examples ======== >>> from sympy import Quaternion >>> q = Quaternion(1, 2, 3, 4) >>> q.pow_cos_sin(4) 900*cos(4*acos(sqrt(30)/30)) + 1800*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*i + 2700*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*j + 3600*sqrt(29)*sin(4*acos(sqrt(30)/30))/29*k """ # q = ||q||*(cos(a) + u*sin(a)) # q^p = ||q||^p * (cos(p*a) + u*sin(p*a)) q = self (v, angle) = q.to_axis_angle() q2 = Quaternion.from_axis_angle(v, p * angle) return q2 * (q.norm()**p) def integrate(self, *args): """Computes integration of quaternion. Returns ======= Quaternion Integration of the quaternion(self) with the given variable. Examples ======== Indefinite Integral of quaternion : >>> from sympy import Quaternion >>> from sympy.abc import x >>> q = Quaternion(1, 2, 3, 4) >>> q.integrate(x) x + 2*x*i + 3*x*j + 4*x*k Definite integral of quaternion : >>> from sympy import Quaternion >>> from sympy.abc import x >>> q = Quaternion(1, 2, 3, 4) >>> q.integrate((x, 1, 5)) 4 + 8*i + 12*j + 16*k """ # TODO: is this expression correct? return Quaternion(integrate(self.a, *args), integrate(self.b, *args), integrate(self.c, *args), integrate(self.d, *args)) @staticmethod def rotate_point(pin, r): """Returns the coordinates of the point pin(a 3 tuple) after rotation. Parameters ========== pin : tuple A 3-element tuple of coordinates of a point which needs to be rotated. r : Quaternion or tuple Axis and angle of rotation. It's important to note that when r is a tuple, it must be of the form (axis, angle) Returns ======= tuple The coordinates of the point after rotation. Examples ======== >>> from sympy import Quaternion >>> from sympy import symbols, trigsimp, cos, sin >>> x = symbols('x') >>> q = Quaternion(cos(x/2), 0, 0, sin(x/2)) >>> trigsimp(Quaternion.rotate_point((1, 1, 1), q)) (sqrt(2)*cos(x + pi/4), sqrt(2)*sin(x + pi/4), 1) >>> (axis, angle) = q.to_axis_angle() >>> trigsimp(Quaternion.rotate_point((1, 1, 1), (axis, angle))) (sqrt(2)*cos(x + pi/4), sqrt(2)*sin(x + pi/4), 1) """ if isinstance(r, tuple): # if r is of the form (vector, angle) q = Quaternion.from_axis_angle(r[0], r[1]) else: # if r is a quaternion q = r.normalize() pout = q * Quaternion(0, pin[0], pin[1], pin[2]) * conjugate(q) return (pout.b, pout.c, pout.d) def to_axis_angle(self): """Returns the axis and angle of rotation of a quaternion. Returns ======= tuple Tuple of (axis, angle) Examples ======== >>> from sympy import Quaternion >>> q = Quaternion(1, 1, 1, 1) >>> (axis, angle) = q.to_axis_angle() >>> axis (sqrt(3)/3, sqrt(3)/3, sqrt(3)/3) >>> angle 2*pi/3 """ q = self if q.a.is_negative: q = q * -1 q = q.normalize() angle = trigsimp(2 * acos(q.a)) # Since quaternion is normalised, q.a is less than 1. s = sqrt(1 - q.a*q.a) x = trigsimp(q.b / s) y = trigsimp(q.c / s) z = trigsimp(q.d / s) v = (x, y, z) t = (v, angle) return t def to_rotation_matrix(self, v=None, homogeneous=True): """Returns the equivalent rotation transformation matrix of the quaternion which represents rotation about the origin if v is not passed. Parameters ========== v : tuple or None Default value: None homogeneous : bool When True, gives an expression that may be more efficient for symbolic calculations but less so for direct evaluation. Both formulas are mathematically equivalent. Default value: True Returns ======= tuple Returns the equivalent rotation transformation matrix of the quaternion which represents rotation about the origin if v is not passed. Examples ======== >>> from sympy import Quaternion >>> from sympy import symbols, trigsimp, cos, sin >>> x = symbols('x') >>> q = Quaternion(cos(x/2), 0, 0, sin(x/2)) >>> trigsimp(q.to_rotation_matrix()) Matrix([ [cos(x), -sin(x), 0], [sin(x), cos(x), 0], [ 0, 0, 1]]) Generates a 4x4 transformation matrix (used for rotation about a point other than the origin) if the point(v) is passed as an argument. """ q = self s = q.norm()**-2 # diagonal elements are different according to parameter normal if homogeneous: m00 = s*(q.a**2 + q.b**2 - q.c**2 - q.d**2) m11 = s*(q.a**2 - q.b**2 + q.c**2 - q.d**2) m22 = s*(q.a**2 - q.b**2 - q.c**2 + q.d**2) else: m00 = 1 - 2*s*(q.c**2 + q.d**2) m11 = 1 - 2*s*(q.b**2 + q.d**2) m22 = 1 - 2*s*(q.b**2 + q.c**2) m01 = 2*s*(q.b*q.c - q.d*q.a) m02 = 2*s*(q.b*q.d + q.c*q.a) m10 = 2*s*(q.b*q.c + q.d*q.a) m12 = 2*s*(q.c*q.d - q.b*q.a) m20 = 2*s*(q.b*q.d - q.c*q.a) m21 = 2*s*(q.c*q.d + q.b*q.a) if not v: return Matrix([[m00, m01, m02], [m10, m11, m12], [m20, m21, m22]]) else: (x, y, z) = v m03 = x - x*m00 - y*m01 - z*m02 m13 = y - x*m10 - y*m11 - z*m12 m23 = z - x*m20 - y*m21 - z*m22 m30 = m31 = m32 = 0 m33 = 1 return Matrix([[m00, m01, m02, m03], [m10, m11, m12, m13], [m20, m21, m22, m23], [m30, m31, m32, m33]]) def scalar_part(self): r"""Returns scalar part($\mathbf{S}(q)$) of the quaternion q. Explanation =========== Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{S}(q) = a$. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(4, 8, 13, 12) >>> q.scalar_part() 4 """ return self.a def vector_part(self): r""" Returns vector part($\mathbf{V}(q)$) of the quaternion q. Explanation =========== Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{V}(q) = bi + cj + dk$. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(1, 1, 1, 1) >>> q.vector_part() 0 + 1*i + 1*j + 1*k >>> q = Quaternion(4, 8, 13, 12) >>> q.vector_part() 0 + 8*i + 13*j + 12*k """ return Quaternion(0, self.b, self.c, self.d) def axis(self): r""" Returns the axis($\mathbf{Ax}(q)$) of the quaternion. Explanation =========== Given a quaternion $q = a + bi + cj + dk$, returns $\mathbf{Ax}(q)$ i.e., the versor of the vector part of that quaternion equal to $\mathbf{U}[\mathbf{V}(q)]$. The axis is always an imaginary unit with square equal to $-1 + 0i + 0j + 0k$. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(1, 1, 1, 1) >>> q.axis() 0 + sqrt(3)/3*i + sqrt(3)/3*j + sqrt(3)/3*k See Also ======== vector_part """ axis = self.vector_part().normalize() return Quaternion(0, axis.b, axis.c, axis.d) def is_pure(self): """ Returns true if the quaternion is pure, false if the quaternion is not pure or returns none if it is unknown. Explanation =========== A pure quaternion (also a vector quaternion) is a quaternion with scalar part equal to 0. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(0, 8, 13, 12) >>> q.is_pure() True See Also ======== scalar_part """ return self.a.is_zero def is_zero_quaternion(self): """ Returns true if the quaternion is a zero quaternion or false if it is not a zero quaternion and None if the value is unknown. Explanation =========== A zero quaternion is a quaternion with both scalar part and vector part equal to 0. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(1, 0, 0, 0) >>> q.is_zero_quaternion() False >>> q = Quaternion(0, 0, 0, 0) >>> q.is_zero_quaternion() True See Also ======== scalar_part vector_part """ return self.norm().is_zero def angle(self): r""" Returns the angle of the quaternion measured in the real-axis plane. Explanation =========== Given a quaternion $q = a + bi + cj + dk$ where a, b, c and d are real numbers, returns the angle of the quaternion given by .. math:: angle := atan2(\sqrt{b^2 + c^2 + d^2}, {a}) Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(1, 4, 4, 4) >>> q.angle() atan(4*sqrt(3)) """ return atan2(self.vector_part().norm(), self.scalar_part()) def arc_coplanar(self, other): """ Returns True if the transformation arcs represented by the input quaternions happen in the same plane. Explanation =========== Two quaternions are said to be coplanar (in this arc sense) when their axes are parallel. The plane of a quaternion is the one normal to its axis. Parameters ========== other : a Quaternion Returns ======= True : if the planes of the two quaternions are the same, apart from its orientation/sign. False : if the planes of the two quaternions are not the same, apart from its orientation/sign. None : if plane of either of the quaternion is unknown. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q1 = Quaternion(1, 4, 4, 4) >>> q2 = Quaternion(3, 8, 8, 8) >>> Quaternion.arc_coplanar(q1, q2) True >>> q1 = Quaternion(2, 8, 13, 12) >>> Quaternion.arc_coplanar(q1, q2) False See Also ======== vector_coplanar is_pure """ if (self.is_zero_quaternion()) or (other.is_zero_quaternion()): raise ValueError('Neither of the given quaternions can be 0') return fuzzy_or([(self.axis() - other.axis()).is_zero_quaternion(), (self.axis() + other.axis()).is_zero_quaternion()]) @classmethod def vector_coplanar(cls, q1, q2, q3): r""" Returns True if the axis of the pure quaternions seen as 3D vectors q1, q2, and q3 are coplanar. Explanation =========== Three pure quaternions are vector coplanar if the quaternions seen as 3D vectors are coplanar. Parameters ========== q1 A pure Quaternion. q2 A pure Quaternion. q3 A pure Quaternion. Returns ======= True : if the axis of the pure quaternions seen as 3D vectors q1, q2, and q3 are coplanar. False : if the axis of the pure quaternions seen as 3D vectors q1, q2, and q3 are not coplanar. None : if the axis of the pure quaternions seen as 3D vectors q1, q2, and q3 are coplanar is unknown. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q1 = Quaternion(0, 4, 4, 4) >>> q2 = Quaternion(0, 8, 8, 8) >>> q3 = Quaternion(0, 24, 24, 24) >>> Quaternion.vector_coplanar(q1, q2, q3) True >>> q1 = Quaternion(0, 8, 16, 8) >>> q2 = Quaternion(0, 8, 3, 12) >>> Quaternion.vector_coplanar(q1, q2, q3) False See Also ======== axis is_pure """ if fuzzy_not(q1.is_pure()) or fuzzy_not(q2.is_pure()) or fuzzy_not(q3.is_pure()): raise ValueError('The given quaternions must be pure') M = Matrix([[q1.b, q1.c, q1.d], [q2.b, q2.c, q2.d], [q3.b, q3.c, q3.d]]).det() return M.is_zero def parallel(self, other): """ Returns True if the two pure quaternions seen as 3D vectors are parallel. Explanation =========== Two pure quaternions are called parallel when their vector product is commutative which implies that the quaternions seen as 3D vectors have same direction. Parameters ========== other : a Quaternion Returns ======= True : if the two pure quaternions seen as 3D vectors are parallel. False : if the two pure quaternions seen as 3D vectors are not parallel. None : if the two pure quaternions seen as 3D vectors are parallel is unknown. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(0, 4, 4, 4) >>> q1 = Quaternion(0, 8, 8, 8) >>> q.parallel(q1) True >>> q1 = Quaternion(0, 8, 13, 12) >>> q.parallel(q1) False """ if fuzzy_not(self.is_pure()) or fuzzy_not(other.is_pure()): raise ValueError('The provided quaternions must be pure') return (self*other - other*self).is_zero_quaternion() def orthogonal(self, other): """ Returns the orthogonality of two quaternions. Explanation =========== Two pure quaternions are called orthogonal when their product is anti-commutative. Parameters ========== other : a Quaternion Returns ======= True : if the two pure quaternions seen as 3D vectors are orthogonal. False : if the two pure quaternions seen as 3D vectors are not orthogonal. None : if the two pure quaternions seen as 3D vectors are orthogonal is unknown. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(0, 4, 4, 4) >>> q1 = Quaternion(0, 8, 8, 8) >>> q.orthogonal(q1) False >>> q1 = Quaternion(0, 2, 2, 0) >>> q = Quaternion(0, 2, -2, 0) >>> q.orthogonal(q1) True """ if fuzzy_not(self.is_pure()) or fuzzy_not(other.is_pure()): raise ValueError('The given quaternions must be pure') return (self*other + other*self).is_zero_quaternion() def index_vector(self): r""" Returns the index vector of the quaternion. Explanation =========== Index vector is given by $\mathbf{T}(q)$ multiplied by $\mathbf{Ax}(q)$ where $\mathbf{Ax}(q)$ is the axis of the quaternion q, and mod(q) is the $\mathbf{T}(q)$ (magnitude) of the quaternion. Returns ======= Quaternion: representing index vector of the provided quaternion. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(2, 4, 2, 4) >>> q.index_vector() 0 + 4*sqrt(10)/3*i + 2*sqrt(10)/3*j + 4*sqrt(10)/3*k See Also ======== axis norm """ return self.norm() * self.axis() def mensor(self): """ Returns the natural logarithm of the norm(magnitude) of the quaternion. Examples ======== >>> from sympy.algebras.quaternion import Quaternion >>> q = Quaternion(2, 4, 2, 4) >>> q.mensor() log(2*sqrt(10)) >>> q.norm() 2*sqrt(10) See Also ======== norm """ return ln(self.norm())
75c083dcac759c0f8cd7c4f1dd9d2f99caebdd70601a4a03f2e9d0774cef0a62
""" Types used to represent a full function/module as an Abstract Syntax Tree. Most types are small, and are merely used as tokens in the AST. A tree diagram has been included below to illustrate the relationships between the AST types. AST Type Tree ------------- :: *Basic* | | CodegenAST | |--->AssignmentBase | |--->Assignment | |--->AugmentedAssignment | |--->AddAugmentedAssignment | |--->SubAugmentedAssignment | |--->MulAugmentedAssignment | |--->DivAugmentedAssignment | |--->ModAugmentedAssignment | |--->CodeBlock | | |--->Token |--->Attribute |--->For |--->String | |--->QuotedString | |--->Comment |--->Type | |--->IntBaseType | | |--->_SizedIntType | | |--->SignedIntType | | |--->UnsignedIntType | |--->FloatBaseType | |--->FloatType | |--->ComplexBaseType | |--->ComplexType |--->Node | |--->Variable | | |---> Pointer | |--->FunctionPrototype | |--->FunctionDefinition |--->Element |--->Declaration |--->While |--->Scope |--->Stream |--->Print |--->FunctionCall |--->BreakToken |--->ContinueToken |--->NoneToken |--->Return Predefined types ---------------- A number of ``Type`` instances are provided in the ``sympy.codegen.ast`` module for convenience. Perhaps the two most common ones for code-generation (of numeric codes) are ``float32`` and ``float64`` (known as single and double precision respectively). There are also precision generic versions of Types (for which the codeprinters selects the underlying data type at time of printing): ``real``, ``integer``, ``complex_``, ``bool_``. The other ``Type`` instances defined are: - ``intc``: Integer type used by C's "int". - ``intp``: Integer type used by C's "unsigned". - ``int8``, ``int16``, ``int32``, ``int64``: n-bit integers. - ``uint8``, ``uint16``, ``uint32``, ``uint64``: n-bit unsigned integers. - ``float80``: known as "extended precision" on modern x86/amd64 hardware. - ``complex64``: Complex number represented by two ``float32`` numbers - ``complex128``: Complex number represented by two ``float64`` numbers Using the nodes --------------- It is possible to construct simple algorithms using the AST nodes. Let's construct a loop applying Newton's method:: >>> from sympy import symbols, cos >>> from sympy.codegen.ast import While, Assignment, aug_assign, Print >>> t, dx, x = symbols('tol delta val') >>> expr = cos(x) - x**3 >>> whl = While(abs(dx) > t, [ ... Assignment(dx, -expr/expr.diff(x)), ... aug_assign(x, '+', dx), ... Print([x]) ... ]) >>> from sympy import pycode >>> py_str = pycode(whl) >>> print(py_str) while (abs(delta) > tol): delta = (val**3 - math.cos(val))/(-3*val**2 - math.sin(val)) val += delta print(val) >>> import math >>> tol, val, delta = 1e-5, 0.5, float('inf') >>> exec(py_str) 1.1121416371 0.909672693737 0.867263818209 0.865477135298 0.865474033111 >>> print('%3.1g' % (math.cos(val) - val**3)) -3e-11 If we want to generate Fortran code for the same while loop we simple call ``fcode``:: >>> from sympy import fcode >>> print(fcode(whl, standard=2003, source_format='free')) do while (abs(delta) > tol) delta = (val**3 - cos(val))/(-3*val**2 - sin(val)) val = val + delta print *, val end do There is a function constructing a loop (or a complete function) like this in :mod:`sympy.codegen.algorithms`. """ from __future__ import annotations from typing import Any from collections import defaultdict from sympy.core.relational import (Ge, Gt, Le, Lt) from sympy.core import Symbol, Tuple, Dummy from sympy.core.basic import Basic from sympy.core.expr import Expr, Atom from sympy.core.numbers import Float, Integer, oo from sympy.core.sympify import _sympify, sympify, SympifyError from sympy.utilities.iterables import (iterable, topological_sort, numbered_symbols, filter_symbols) def _mk_Tuple(args): """ Create a SymPy Tuple object from an iterable, converting Python strings to AST strings. Parameters ========== args: iterable Arguments to :class:`sympy.Tuple`. Returns ======= sympy.Tuple """ args = [String(arg) if isinstance(arg, str) else arg for arg in args] return Tuple(*args) class CodegenAST(Basic): __slots__ = () class Token(CodegenAST): """ Base class for the AST types. Explanation =========== Defining fields are set in ``_fields``. Attributes (defined in _fields) are only allowed to contain instances of Basic (unless atomic, see ``String``). The arguments to ``__new__()`` correspond to the attributes in the order defined in ``_fields`. The ``defaults`` class attribute is a dictionary mapping attribute names to their default values. Subclasses should not need to override the ``__new__()`` method. They may define a class or static method named ``_construct_<attr>`` for each attribute to process the value passed to ``__new__()``. Attributes listed in the class attribute ``not_in_args`` are not passed to :class:`~.Basic`. """ __slots__: tuple[str, ...] = () _fields = __slots__ defaults: dict[str, Any] = {} not_in_args: list[str] = [] indented_args = ['body'] @property def is_Atom(self): return len(self._fields) == 0 @classmethod def _get_constructor(cls, attr): """ Get the constructor function for an attribute by name. """ return getattr(cls, '_construct_%s' % attr, lambda x: x) @classmethod def _construct(cls, attr, arg): """ Construct an attribute value from argument passed to ``__new__()``. """ # arg may be ``NoneToken()``, so comparison is done using == instead of ``is`` operator if arg == None: return cls.defaults.get(attr, none) else: if isinstance(arg, Dummy): # SymPy's replace uses Dummy instances return arg else: return cls._get_constructor(attr)(arg) def __new__(cls, *args, **kwargs): # Pass through existing instances when given as sole argument if len(args) == 1 and not kwargs and isinstance(args[0], cls): return args[0] if len(args) > len(cls._fields): raise ValueError("Too many arguments (%d), expected at most %d" % (len(args), len(cls._fields))) attrvals = [] # Process positional arguments for attrname, argval in zip(cls._fields, args): if attrname in kwargs: raise TypeError('Got multiple values for attribute %r' % attrname) attrvals.append(cls._construct(attrname, argval)) # Process keyword arguments for attrname in cls._fields[len(args):]: if attrname in kwargs: argval = kwargs.pop(attrname) elif attrname in cls.defaults: argval = cls.defaults[attrname] else: raise TypeError('No value for %r given and attribute has no default' % attrname) attrvals.append(cls._construct(attrname, argval)) if kwargs: raise ValueError("Unknown keyword arguments: %s" % ' '.join(kwargs)) # Parent constructor basic_args = [ val for attr, val in zip(cls._fields, attrvals) if attr not in cls.not_in_args ] obj = CodegenAST.__new__(cls, *basic_args) # Set attributes for attr, arg in zip(cls._fields, attrvals): setattr(obj, attr, arg) return obj def __eq__(self, other): if not isinstance(other, self.__class__): return False for attr in self._fields: if getattr(self, attr) != getattr(other, attr): return False return True def _hashable_content(self): return tuple([getattr(self, attr) for attr in self._fields]) def __hash__(self): return super().__hash__() def _joiner(self, k, indent_level): return (',\n' + ' '*indent_level) if k in self.indented_args else ', ' def _indented(self, printer, k, v, *args, **kwargs): il = printer._context['indent_level'] def _print(arg): if isinstance(arg, Token): return printer._print(arg, *args, joiner=self._joiner(k, il), **kwargs) else: return printer._print(arg, *args, **kwargs) if isinstance(v, Tuple): joined = self._joiner(k, il).join([_print(arg) for arg in v.args]) if k in self.indented_args: return '(\n' + ' '*il + joined + ',\n' + ' '*(il - 4) + ')' else: return ('({0},)' if len(v.args) == 1 else '({0})').format(joined) else: return _print(v) def _sympyrepr(self, printer, *args, joiner=', ', **kwargs): from sympy.printing.printer import printer_context exclude = kwargs.get('exclude', ()) values = [getattr(self, k) for k in self._fields] indent_level = printer._context.get('indent_level', 0) arg_reprs = [] for i, (attr, value) in enumerate(zip(self._fields, values)): if attr in exclude: continue # Skip attributes which have the default value if attr in self.defaults and value == self.defaults[attr]: continue ilvl = indent_level + 4 if attr in self.indented_args else 0 with printer_context(printer, indent_level=ilvl): indented = self._indented(printer, attr, value, *args, **kwargs) arg_reprs.append(('{1}' if i == 0 else '{0}={1}').format(attr, indented.lstrip())) return "{}({})".format(self.__class__.__name__, joiner.join(arg_reprs)) _sympystr = _sympyrepr def __repr__(self): # sympy.core.Basic.__repr__ uses sstr from sympy.printing import srepr return srepr(self) def kwargs(self, exclude=(), apply=None): """ Get instance's attributes as dict of keyword arguments. Parameters ========== exclude : collection of str Collection of keywords to exclude. apply : callable, optional Function to apply to all values. """ kwargs = {k: getattr(self, k) for k in self._fields if k not in exclude} if apply is not None: return {k: apply(v) for k, v in kwargs.items()} else: return kwargs class BreakToken(Token): """ Represents 'break' in C/Python ('exit' in Fortran). Use the premade instance ``break_`` or instantiate manually. Examples ======== >>> from sympy import ccode, fcode >>> from sympy.codegen.ast import break_ >>> ccode(break_) 'break' >>> fcode(break_, source_format='free') 'exit' """ break_ = BreakToken() class ContinueToken(Token): """ Represents 'continue' in C/Python ('cycle' in Fortran) Use the premade instance ``continue_`` or instantiate manually. Examples ======== >>> from sympy import ccode, fcode >>> from sympy.codegen.ast import continue_ >>> ccode(continue_) 'continue' >>> fcode(continue_, source_format='free') 'cycle' """ continue_ = ContinueToken() class NoneToken(Token): """ The AST equivalence of Python's NoneType The corresponding instance of Python's ``None`` is ``none``. Examples ======== >>> from sympy.codegen.ast import none, Variable >>> from sympy import pycode >>> print(pycode(Variable('x').as_Declaration(value=none))) x = None """ def __eq__(self, other): return other is None or isinstance(other, NoneToken) def _hashable_content(self): return () def __hash__(self): return super().__hash__() none = NoneToken() class AssignmentBase(CodegenAST): """ Abstract base class for Assignment and AugmentedAssignment. Attributes: =========== op : str Symbol for assignment operator, e.g. "=", "+=", etc. """ def __new__(cls, lhs, rhs): lhs = _sympify(lhs) rhs = _sympify(rhs) cls._check_args(lhs, rhs) return super().__new__(cls, lhs, rhs) @property def lhs(self): return self.args[0] @property def rhs(self): return self.args[1] @classmethod def _check_args(cls, lhs, rhs): """ Check arguments to __new__ and raise exception if any problems found. Derived classes may wish to override this. """ from sympy.matrices.expressions.matexpr import ( MatrixElement, MatrixSymbol) from sympy.tensor.indexed import Indexed from sympy.tensor.array.expressions import ArrayElement # Tuple of things that can be on the lhs of an assignment assignable = (Symbol, MatrixSymbol, MatrixElement, Indexed, Element, Variable, ArrayElement) if not isinstance(lhs, assignable): raise TypeError("Cannot assign to lhs of type %s." % type(lhs)) # Indexed types implement shape, but don't define it until later. This # causes issues in assignment validation. For now, matrices are defined # as anything with a shape that is not an Indexed lhs_is_mat = hasattr(lhs, 'shape') and not isinstance(lhs, Indexed) rhs_is_mat = hasattr(rhs, 'shape') and not isinstance(rhs, Indexed) # If lhs and rhs have same structure, then this assignment is ok if lhs_is_mat: if not rhs_is_mat: raise ValueError("Cannot assign a scalar to a matrix.") elif lhs.shape != rhs.shape: raise ValueError("Dimensions of lhs and rhs do not align.") elif rhs_is_mat and not lhs_is_mat: raise ValueError("Cannot assign a matrix to a scalar.") class Assignment(AssignmentBase): """ Represents variable assignment for code generation. Parameters ========== lhs : Expr SymPy object representing the lhs of the expression. These should be singular objects, such as one would use in writing code. Notable types include Symbol, MatrixSymbol, MatrixElement, and Indexed. Types that subclass these types are also supported. rhs : Expr SymPy object representing the rhs of the expression. This can be any type, provided its shape corresponds to that of the lhs. For example, a Matrix type can be assigned to MatrixSymbol, but not to Symbol, as the dimensions will not align. Examples ======== >>> from sympy import symbols, MatrixSymbol, Matrix >>> from sympy.codegen.ast import Assignment >>> x, y, z = symbols('x, y, z') >>> Assignment(x, y) Assignment(x, y) >>> Assignment(x, 0) Assignment(x, 0) >>> A = MatrixSymbol('A', 1, 3) >>> mat = Matrix([x, y, z]).T >>> Assignment(A, mat) Assignment(A, Matrix([[x, y, z]])) >>> Assignment(A[0, 1], x) Assignment(A[0, 1], x) """ op = ':=' class AugmentedAssignment(AssignmentBase): """ Base class for augmented assignments. Attributes: =========== binop : str Symbol for binary operation being applied in the assignment, such as "+", "*", etc. """ binop = None # type: str @property def op(self): return self.binop + '=' class AddAugmentedAssignment(AugmentedAssignment): binop = '+' class SubAugmentedAssignment(AugmentedAssignment): binop = '-' class MulAugmentedAssignment(AugmentedAssignment): binop = '*' class DivAugmentedAssignment(AugmentedAssignment): binop = '/' class ModAugmentedAssignment(AugmentedAssignment): binop = '%' # Mapping from binary op strings to AugmentedAssignment subclasses augassign_classes = { cls.binop: cls for cls in [ AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssignment, DivAugmentedAssignment, ModAugmentedAssignment ] } def aug_assign(lhs, op, rhs): """ Create 'lhs op= rhs'. Explanation =========== Represents augmented variable assignment for code generation. This is a convenience function. You can also use the AugmentedAssignment classes directly, like AddAugmentedAssignment(x, y). Parameters ========== lhs : Expr SymPy object representing the lhs of the expression. These should be singular objects, such as one would use in writing code. Notable types include Symbol, MatrixSymbol, MatrixElement, and Indexed. Types that subclass these types are also supported. op : str Operator (+, -, /, \\*, %). rhs : Expr SymPy object representing the rhs of the expression. This can be any type, provided its shape corresponds to that of the lhs. For example, a Matrix type can be assigned to MatrixSymbol, but not to Symbol, as the dimensions will not align. Examples ======== >>> from sympy import symbols >>> from sympy.codegen.ast import aug_assign >>> x, y = symbols('x, y') >>> aug_assign(x, '+', y) AddAugmentedAssignment(x, y) """ if op not in augassign_classes: raise ValueError("Unrecognized operator %s" % op) return augassign_classes[op](lhs, rhs) class CodeBlock(CodegenAST): """ Represents a block of code. Explanation =========== For now only assignments are supported. This restriction will be lifted in the future. Useful attributes on this object are: ``left_hand_sides``: Tuple of left-hand sides of assignments, in order. ``left_hand_sides``: Tuple of right-hand sides of assignments, in order. ``free_symbols``: Free symbols of the expressions in the right-hand sides which do not appear in the left-hand side of an assignment. Useful methods on this object are: ``topological_sort``: Class method. Return a CodeBlock with assignments sorted so that variables are assigned before they are used. ``cse``: Return a new CodeBlock with common subexpressions eliminated and pulled out as assignments. Examples ======== >>> from sympy import symbols, ccode >>> from sympy.codegen.ast import CodeBlock, Assignment >>> x, y = symbols('x y') >>> c = CodeBlock(Assignment(x, 1), Assignment(y, x + 1)) >>> print(ccode(c)) x = 1; y = x + 1; """ def __new__(cls, *args): left_hand_sides = [] right_hand_sides = [] for i in args: if isinstance(i, Assignment): lhs, rhs = i.args left_hand_sides.append(lhs) right_hand_sides.append(rhs) obj = CodegenAST.__new__(cls, *args) obj.left_hand_sides = Tuple(*left_hand_sides) obj.right_hand_sides = Tuple(*right_hand_sides) return obj def __iter__(self): return iter(self.args) def _sympyrepr(self, printer, *args, **kwargs): il = printer._context.get('indent_level', 0) joiner = ',\n' + ' '*il joined = joiner.join(map(printer._print, self.args)) return ('{}(\n'.format(' '*(il-4) + self.__class__.__name__,) + ' '*il + joined + '\n' + ' '*(il - 4) + ')') _sympystr = _sympyrepr @property def free_symbols(self): return super().free_symbols - set(self.left_hand_sides) @classmethod def topological_sort(cls, assignments): """ Return a CodeBlock with topologically sorted assignments so that variables are assigned before they are used. Examples ======== The existing order of assignments is preserved as much as possible. This function assumes that variables are assigned to only once. This is a class constructor so that the default constructor for CodeBlock can error when variables are used before they are assigned. >>> from sympy import symbols >>> from sympy.codegen.ast import CodeBlock, Assignment >>> x, y, z = symbols('x y z') >>> assignments = [ ... Assignment(x, y + z), ... Assignment(y, z + 1), ... Assignment(z, 2), ... ] >>> CodeBlock.topological_sort(assignments) CodeBlock( Assignment(z, 2), Assignment(y, z + 1), Assignment(x, y + z) ) """ if not all(isinstance(i, Assignment) for i in assignments): # Will support more things later raise NotImplementedError("CodeBlock.topological_sort only supports Assignments") if any(isinstance(i, AugmentedAssignment) for i in assignments): raise NotImplementedError("CodeBlock.topological_sort does not yet work with AugmentedAssignments") # Create a graph where the nodes are assignments and there is a directed edge # between nodes that use a variable and nodes that assign that # variable, like # [(x := 1, y := x + 1), (x := 1, z := y + z), (y := x + 1, z := y + z)] # If we then topologically sort these nodes, they will be in # assignment order, like # x := 1 # y := x + 1 # z := y + z # A = The nodes # # enumerate keeps nodes in the same order they are already in if # possible. It will also allow us to handle duplicate assignments to # the same variable when those are implemented. A = list(enumerate(assignments)) # var_map = {variable: [nodes for which this variable is assigned to]} # like {x: [(1, x := y + z), (4, x := 2 * w)], ...} var_map = defaultdict(list) for node in A: i, a = node var_map[a.lhs].append(node) # E = Edges in the graph E = [] for dst_node in A: i, a = dst_node for s in a.rhs.free_symbols: for src_node in var_map[s]: E.append((src_node, dst_node)) ordered_assignments = topological_sort([A, E]) # De-enumerate the result return cls(*[a for i, a in ordered_assignments]) def cse(self, symbols=None, optimizations=None, postprocess=None, order='canonical'): """ Return a new code block with common subexpressions eliminated. Explanation =========== See the docstring of :func:`sympy.simplify.cse_main.cse` for more information. Examples ======== >>> from sympy import symbols, sin >>> from sympy.codegen.ast import CodeBlock, Assignment >>> x, y, z = symbols('x y z') >>> c = CodeBlock( ... Assignment(x, 1), ... Assignment(y, sin(x) + 1), ... Assignment(z, sin(x) - 1), ... ) ... >>> c.cse() CodeBlock( Assignment(x, 1), Assignment(x0, sin(x)), Assignment(y, x0 + 1), Assignment(z, x0 - 1) ) """ from sympy.simplify.cse_main import cse # Check that the CodeBlock only contains assignments to unique variables if not all(isinstance(i, Assignment) for i in self.args): # Will support more things later raise NotImplementedError("CodeBlock.cse only supports Assignments") if any(isinstance(i, AugmentedAssignment) for i in self.args): raise NotImplementedError("CodeBlock.cse does not yet work with AugmentedAssignments") for i, lhs in enumerate(self.left_hand_sides): if lhs in self.left_hand_sides[:i]: raise NotImplementedError("Duplicate assignments to the same " "variable are not yet supported (%s)" % lhs) # Ensure new symbols for subexpressions do not conflict with existing existing_symbols = self.atoms(Symbol) if symbols is None: symbols = numbered_symbols() symbols = filter_symbols(symbols, existing_symbols) replacements, reduced_exprs = cse(list(self.right_hand_sides), symbols=symbols, optimizations=optimizations, postprocess=postprocess, order=order) new_block = [Assignment(var, expr) for var, expr in zip(self.left_hand_sides, reduced_exprs)] new_assignments = [Assignment(var, expr) for var, expr in replacements] return self.topological_sort(new_assignments + new_block) class For(Token): """Represents a 'for-loop' in the code. Expressions are of the form: "for target in iter: body..." Parameters ========== target : symbol iter : iterable body : CodeBlock or iterable ! When passed an iterable it is used to instantiate a CodeBlock. Examples ======== >>> from sympy import symbols, Range >>> from sympy.codegen.ast import aug_assign, For >>> x, i, j, k = symbols('x i j k') >>> for_i = For(i, Range(10), [aug_assign(x, '+', i*j*k)]) >>> for_i # doctest: -NORMALIZE_WHITESPACE For(i, iterable=Range(0, 10, 1), body=CodeBlock( AddAugmentedAssignment(x, i*j*k) )) >>> for_ji = For(j, Range(7), [for_i]) >>> for_ji # doctest: -NORMALIZE_WHITESPACE For(j, iterable=Range(0, 7, 1), body=CodeBlock( For(i, iterable=Range(0, 10, 1), body=CodeBlock( AddAugmentedAssignment(x, i*j*k) )) )) >>> for_kji =For(k, Range(5), [for_ji]) >>> for_kji # doctest: -NORMALIZE_WHITESPACE For(k, iterable=Range(0, 5, 1), body=CodeBlock( For(j, iterable=Range(0, 7, 1), body=CodeBlock( For(i, iterable=Range(0, 10, 1), body=CodeBlock( AddAugmentedAssignment(x, i*j*k) )) )) )) """ __slots__ = _fields = ('target', 'iterable', 'body') _construct_target = staticmethod(_sympify) @classmethod def _construct_body(cls, itr): if isinstance(itr, CodeBlock): return itr else: return CodeBlock(*itr) @classmethod def _construct_iterable(cls, itr): if not iterable(itr): raise TypeError("iterable must be an iterable") if isinstance(itr, list): # _sympify errors on lists because they are mutable itr = tuple(itr) return _sympify(itr) class String(Atom, Token): """ SymPy object representing a string. Atomic object which is not an expression (as opposed to Symbol). Parameters ========== text : str Examples ======== >>> from sympy.codegen.ast import String >>> f = String('foo') >>> f foo >>> str(f) 'foo' >>> f.text 'foo' >>> print(repr(f)) String('foo') """ __slots__ = _fields = ('text',) not_in_args = ['text'] is_Atom = True @classmethod def _construct_text(cls, text): if not isinstance(text, str): raise TypeError("Argument text is not a string type.") return text def _sympystr(self, printer, *args, **kwargs): return self.text def kwargs(self, exclude = (), apply = None): return {} #to be removed when Atom is given a suitable func @property def func(self): return lambda: self def _latex(self, printer): from sympy.printing.latex import latex_escape return r'\texttt{{"{}"}}'.format(latex_escape(self.text)) class QuotedString(String): """ Represents a string which should be printed with quotes. """ class Comment(String): """ Represents a comment. """ class Node(Token): """ Subclass of Token, carrying the attribute 'attrs' (Tuple) Examples ======== >>> from sympy.codegen.ast import Node, value_const, pointer_const >>> n1 = Node([value_const]) >>> n1.attr_params('value_const') # get the parameters of attribute (by name) () >>> from sympy.codegen.fnodes import dimension >>> n2 = Node([value_const, dimension(5, 3)]) >>> n2.attr_params(value_const) # get the parameters of attribute (by Attribute instance) () >>> n2.attr_params('dimension') # get the parameters of attribute (by name) (5, 3) >>> n2.attr_params(pointer_const) is None True """ __slots__: tuple[str, ...] = ('attrs',) _fields = __slots__ defaults: dict[str, Any] = {'attrs': Tuple()} _construct_attrs = staticmethod(_mk_Tuple) def attr_params(self, looking_for): """ Returns the parameters of the Attribute with name ``looking_for`` in self.attrs """ for attr in self.attrs: if str(attr.name) == str(looking_for): return attr.parameters class Type(Token): """ Represents a type. Explanation =========== The naming is a super-set of NumPy naming. Type has a classmethod ``from_expr`` which offer type deduction. It also has a method ``cast_check`` which casts the argument to its type, possibly raising an exception if rounding error is not within tolerances, or if the value is not representable by the underlying data type (e.g. unsigned integers). Parameters ========== name : str Name of the type, e.g. ``object``, ``int16``, ``float16`` (where the latter two would use the ``Type`` sub-classes ``IntType`` and ``FloatType`` respectively). If a ``Type`` instance is given, the said instance is returned. Examples ======== >>> from sympy.codegen.ast import Type >>> t = Type.from_expr(42) >>> t integer >>> print(repr(t)) IntBaseType(String('integer')) >>> from sympy.codegen.ast import uint8 >>> uint8.cast_check(-1) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: Minimum value for data type bigger than new value. >>> from sympy.codegen.ast import float32 >>> v6 = 0.123456 >>> float32.cast_check(v6) 0.123456 >>> v10 = 12345.67894 >>> float32.cast_check(v10) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: Casting gives a significantly different value. >>> boost_mp50 = Type('boost::multiprecision::cpp_dec_float_50') >>> from sympy import cxxcode >>> from sympy.codegen.ast import Declaration, Variable >>> cxxcode(Declaration(Variable('x', type=boost_mp50))) 'boost::multiprecision::cpp_dec_float_50 x' References ========== .. [1] https://docs.scipy.org/doc/numpy/user/basics.types.html """ __slots__: tuple[str, ...] = ('name',) _fields = __slots__ _construct_name = String def _sympystr(self, printer, *args, **kwargs): return str(self.name) @classmethod def from_expr(cls, expr): """ Deduces type from an expression or a ``Symbol``. Parameters ========== expr : number or SymPy object The type will be deduced from type or properties. Examples ======== >>> from sympy.codegen.ast import Type, integer, complex_ >>> Type.from_expr(2) == integer True >>> from sympy import Symbol >>> Type.from_expr(Symbol('z', complex=True)) == complex_ True >>> Type.from_expr(sum) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: Could not deduce type from expr. Raises ====== ValueError when type deduction fails. """ if isinstance(expr, (float, Float)): return real if isinstance(expr, (int, Integer)) or getattr(expr, 'is_integer', False): return integer if getattr(expr, 'is_real', False): return real if isinstance(expr, complex) or getattr(expr, 'is_complex', False): return complex_ if isinstance(expr, bool) or getattr(expr, 'is_Relational', False): return bool_ else: raise ValueError("Could not deduce type from expr.") def _check(self, value): pass def cast_check(self, value, rtol=None, atol=0, precision_targets=None): """ Casts a value to the data type of the instance. Parameters ========== value : number rtol : floating point number Relative tolerance. (will be deduced if not given). atol : floating point number Absolute tolerance (in addition to ``rtol``). type_aliases : dict Maps substitutions for Type, e.g. {integer: int64, real: float32} Examples ======== >>> from sympy.codegen.ast import integer, float32, int8 >>> integer.cast_check(3.0) == 3 True >>> float32.cast_check(1e-40) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: Minimum value for data type bigger than new value. >>> int8.cast_check(256) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: Maximum value for data type smaller than new value. >>> v10 = 12345.67894 >>> float32.cast_check(v10) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: Casting gives a significantly different value. >>> from sympy.codegen.ast import float64 >>> float64.cast_check(v10) 12345.67894 >>> from sympy import Float >>> v18 = Float('0.123456789012345646') >>> float64.cast_check(v18) Traceback (most recent call last): ... ValueError: Casting gives a significantly different value. >>> from sympy.codegen.ast import float80 >>> float80.cast_check(v18) 0.123456789012345649 """ val = sympify(value) ten = Integer(10) exp10 = getattr(self, 'decimal_dig', None) if rtol is None: rtol = 1e-15 if exp10 is None else 2.0*ten**(-exp10) def tol(num): return atol + rtol*abs(num) new_val = self.cast_nocheck(value) self._check(new_val) delta = new_val - val if abs(delta) > tol(val): # rounding, e.g. int(3.5) != 3.5 raise ValueError("Casting gives a significantly different value.") return new_val def _latex(self, printer): from sympy.printing.latex import latex_escape type_name = latex_escape(self.__class__.__name__) name = latex_escape(self.name.text) return r"\text{{{}}}\left(\texttt{{{}}}\right)".format(type_name, name) class IntBaseType(Type): """ Integer base type, contains no size information. """ __slots__ = () cast_nocheck = lambda self, i: Integer(int(i)) class _SizedIntType(IntBaseType): __slots__ = ('nbits',) _fields = Type._fields + __slots__ _construct_nbits = Integer def _check(self, value): if value < self.min: raise ValueError("Value is too small: %d < %d" % (value, self.min)) if value > self.max: raise ValueError("Value is too big: %d > %d" % (value, self.max)) class SignedIntType(_SizedIntType): """ Represents a signed integer type. """ __slots__ = () @property def min(self): return -2**(self.nbits-1) @property def max(self): return 2**(self.nbits-1) - 1 class UnsignedIntType(_SizedIntType): """ Represents an unsigned integer type. """ __slots__ = () @property def min(self): return 0 @property def max(self): return 2**self.nbits - 1 two = Integer(2) class FloatBaseType(Type): """ Represents a floating point number type. """ __slots__ = () cast_nocheck = Float class FloatType(FloatBaseType): """ Represents a floating point type with fixed bit width. Base 2 & one sign bit is assumed. Parameters ========== name : str Name of the type. nbits : integer Number of bits used (storage). nmant : integer Number of bits used to represent the mantissa. nexp : integer Number of bits used to represent the mantissa. Examples ======== >>> from sympy import S >>> from sympy.codegen.ast import FloatType >>> half_precision = FloatType('f16', nbits=16, nmant=10, nexp=5) >>> half_precision.max 65504 >>> half_precision.tiny == S(2)**-14 True >>> half_precision.eps == S(2)**-10 True >>> half_precision.dig == 3 True >>> half_precision.decimal_dig == 5 True >>> half_precision.cast_check(1.0) 1.0 >>> half_precision.cast_check(1e5) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: Maximum value for data type smaller than new value. """ __slots__ = ('nbits', 'nmant', 'nexp',) _fields = Type._fields + __slots__ _construct_nbits = _construct_nmant = _construct_nexp = Integer @property def max_exponent(self): """ The largest positive number n, such that 2**(n - 1) is a representable finite value. """ # cf. C++'s ``std::numeric_limits::max_exponent`` return two**(self.nexp - 1) @property def min_exponent(self): """ The lowest negative number n, such that 2**(n - 1) is a valid normalized number. """ # cf. C++'s ``std::numeric_limits::min_exponent`` return 3 - self.max_exponent @property def max(self): """ Maximum value representable. """ return (1 - two**-(self.nmant+1))*two**self.max_exponent @property def tiny(self): """ The minimum positive normalized value. """ # See C macros: FLT_MIN, DBL_MIN, LDBL_MIN # or C++'s ``std::numeric_limits::min`` # or numpy.finfo(dtype).tiny return two**(self.min_exponent - 1) @property def eps(self): """ Difference between 1.0 and the next representable value. """ return two**(-self.nmant) @property def dig(self): """ Number of decimal digits that are guaranteed to be preserved in text. When converting text -> float -> text, you are guaranteed that at least ``dig`` number of digits are preserved with respect to rounding or overflow. """ from sympy.functions import floor, log return floor(self.nmant * log(2)/log(10)) @property def decimal_dig(self): """ Number of digits needed to store & load without loss. Explanation =========== Number of decimal digits needed to guarantee that two consecutive conversions (float -> text -> float) to be idempotent. This is useful when one do not want to loose precision due to rounding errors when storing a floating point value as text. """ from sympy.functions import ceiling, log return ceiling((self.nmant + 1) * log(2)/log(10) + 1) def cast_nocheck(self, value): """ Casts without checking if out of bounds or subnormal. """ if value == oo: # float(oo) or oo return float(oo) elif value == -oo: # float(-oo) or -oo return float(-oo) return Float(str(sympify(value).evalf(self.decimal_dig)), self.decimal_dig) def _check(self, value): if value < -self.max: raise ValueError("Value is too small: %d < %d" % (value, -self.max)) if value > self.max: raise ValueError("Value is too big: %d > %d" % (value, self.max)) if abs(value) < self.tiny: raise ValueError("Smallest (absolute) value for data type bigger than new value.") class ComplexBaseType(FloatBaseType): __slots__ = () def cast_nocheck(self, value): """ Casts without checking if out of bounds or subnormal. """ from sympy.functions import re, im return ( super().cast_nocheck(re(value)) + super().cast_nocheck(im(value))*1j ) def _check(self, value): from sympy.functions import re, im super()._check(re(value)) super()._check(im(value)) class ComplexType(ComplexBaseType, FloatType): """ Represents a complex floating point number. """ __slots__ = () # NumPy types: intc = IntBaseType('intc') intp = IntBaseType('intp') int8 = SignedIntType('int8', 8) int16 = SignedIntType('int16', 16) int32 = SignedIntType('int32', 32) int64 = SignedIntType('int64', 64) uint8 = UnsignedIntType('uint8', 8) uint16 = UnsignedIntType('uint16', 16) uint32 = UnsignedIntType('uint32', 32) uint64 = UnsignedIntType('uint64', 64) float16 = FloatType('float16', 16, nexp=5, nmant=10) # IEEE 754 binary16, Half precision float32 = FloatType('float32', 32, nexp=8, nmant=23) # IEEE 754 binary32, Single precision float64 = FloatType('float64', 64, nexp=11, nmant=52) # IEEE 754 binary64, Double precision float80 = FloatType('float80', 80, nexp=15, nmant=63) # x86 extended precision (1 integer part bit), "long double" float128 = FloatType('float128', 128, nexp=15, nmant=112) # IEEE 754 binary128, Quadruple precision float256 = FloatType('float256', 256, nexp=19, nmant=236) # IEEE 754 binary256, Octuple precision complex64 = ComplexType('complex64', nbits=64, **float32.kwargs(exclude=('name', 'nbits'))) complex128 = ComplexType('complex128', nbits=128, **float64.kwargs(exclude=('name', 'nbits'))) # Generic types (precision may be chosen by code printers): untyped = Type('untyped') real = FloatBaseType('real') integer = IntBaseType('integer') complex_ = ComplexBaseType('complex') bool_ = Type('bool') class Attribute(Token): """ Attribute (possibly parametrized) For use with :class:`sympy.codegen.ast.Node` (which takes instances of ``Attribute`` as ``attrs``). Parameters ========== name : str parameters : Tuple Examples ======== >>> from sympy.codegen.ast import Attribute >>> volatile = Attribute('volatile') >>> volatile volatile >>> print(repr(volatile)) Attribute(String('volatile')) >>> a = Attribute('foo', [1, 2, 3]) >>> a foo(1, 2, 3) >>> a.parameters == (1, 2, 3) True """ __slots__ = _fields = ('name', 'parameters') defaults = {'parameters': Tuple()} _construct_name = String _construct_parameters = staticmethod(_mk_Tuple) def _sympystr(self, printer, *args, **kwargs): result = str(self.name) if self.parameters: result += '(%s)' % ', '.join(map(lambda arg: printer._print( arg, *args, **kwargs), self.parameters)) return result value_const = Attribute('value_const') pointer_const = Attribute('pointer_const') class Variable(Node): """ Represents a variable. Parameters ========== symbol : Symbol type : Type (optional) Type of the variable. attrs : iterable of Attribute instances Will be stored as a Tuple. Examples ======== >>> from sympy import Symbol >>> from sympy.codegen.ast import Variable, float32, integer >>> x = Symbol('x') >>> v = Variable(x, type=float32) >>> v.attrs () >>> v == Variable('x') False >>> v == Variable('x', type=float32) True >>> v Variable(x, type=float32) One may also construct a ``Variable`` instance with the type deduced from assumptions about the symbol using the ``deduced`` classmethod: >>> i = Symbol('i', integer=True) >>> v = Variable.deduced(i) >>> v.type == integer True >>> v == Variable('i') False >>> from sympy.codegen.ast import value_const >>> value_const in v.attrs False >>> w = Variable('w', attrs=[value_const]) >>> w Variable(w, attrs=(value_const,)) >>> value_const in w.attrs True >>> w.as_Declaration(value=42) Declaration(Variable(w, value=42, attrs=(value_const,))) """ __slots__ = ('symbol', 'type', 'value') _fields = __slots__ + Node._fields defaults = Node.defaults.copy() defaults.update({'type': untyped, 'value': none}) _construct_symbol = staticmethod(sympify) _construct_value = staticmethod(sympify) @classmethod def deduced(cls, symbol, value=None, attrs=Tuple(), cast_check=True): """ Alt. constructor with type deduction from ``Type.from_expr``. Deduces type primarily from ``symbol``, secondarily from ``value``. Parameters ========== symbol : Symbol value : expr (optional) value of the variable. attrs : iterable of Attribute instances cast_check : bool Whether to apply ``Type.cast_check`` on ``value``. Examples ======== >>> from sympy import Symbol >>> from sympy.codegen.ast import Variable, complex_ >>> n = Symbol('n', integer=True) >>> str(Variable.deduced(n).type) 'integer' >>> x = Symbol('x', real=True) >>> v = Variable.deduced(x) >>> v.type real >>> z = Symbol('z', complex=True) >>> Variable.deduced(z).type == complex_ True """ if isinstance(symbol, Variable): return symbol try: type_ = Type.from_expr(symbol) except ValueError: type_ = Type.from_expr(value) if value is not None and cast_check: value = type_.cast_check(value) return cls(symbol, type=type_, value=value, attrs=attrs) def as_Declaration(self, **kwargs): """ Convenience method for creating a Declaration instance. Explanation =========== If the variable of the Declaration need to wrap a modified variable keyword arguments may be passed (overriding e.g. the ``value`` of the Variable instance). Examples ======== >>> from sympy.codegen.ast import Variable, NoneToken >>> x = Variable('x') >>> decl1 = x.as_Declaration() >>> # value is special NoneToken() which must be tested with == operator >>> decl1.variable.value is None # won't work False >>> decl1.variable.value == None # not PEP-8 compliant True >>> decl1.variable.value == NoneToken() # OK True >>> decl2 = x.as_Declaration(value=42.0) >>> decl2.variable.value == 42.0 True """ kw = self.kwargs() kw.update(kwargs) return Declaration(self.func(**kw)) def _relation(self, rhs, op): try: rhs = _sympify(rhs) except SympifyError: raise TypeError("Invalid comparison %s < %s" % (self, rhs)) return op(self, rhs, evaluate=False) __lt__ = lambda self, other: self._relation(other, Lt) __le__ = lambda self, other: self._relation(other, Le) __ge__ = lambda self, other: self._relation(other, Ge) __gt__ = lambda self, other: self._relation(other, Gt) class Pointer(Variable): """ Represents a pointer. See ``Variable``. Examples ======== Can create instances of ``Element``: >>> from sympy import Symbol >>> from sympy.codegen.ast import Pointer >>> i = Symbol('i', integer=True) >>> p = Pointer('x') >>> p[i+1] Element(x, indices=(i + 1,)) """ __slots__ = () def __getitem__(self, key): try: return Element(self.symbol, key) except TypeError: return Element(self.symbol, (key,)) class Element(Token): """ Element in (a possibly N-dimensional) array. Examples ======== >>> from sympy.codegen.ast import Element >>> elem = Element('x', 'ijk') >>> elem.symbol.name == 'x' True >>> elem.indices (i, j, k) >>> from sympy import ccode >>> ccode(elem) 'x[i][j][k]' >>> ccode(Element('x', 'ijk', strides='lmn', offset='o')) 'x[i*l + j*m + k*n + o]' """ __slots__ = _fields = ('symbol', 'indices', 'strides', 'offset') defaults = {'strides': none, 'offset': none} _construct_symbol = staticmethod(sympify) _construct_indices = staticmethod(lambda arg: Tuple(*arg)) _construct_strides = staticmethod(lambda arg: Tuple(*arg)) _construct_offset = staticmethod(sympify) class Declaration(Token): """ Represents a variable declaration Parameters ========== variable : Variable Examples ======== >>> from sympy.codegen.ast import Declaration, NoneToken, untyped >>> z = Declaration('z') >>> z.variable.type == untyped True >>> # value is special NoneToken() which must be tested with == operator >>> z.variable.value is None # won't work False >>> z.variable.value == None # not PEP-8 compliant True >>> z.variable.value == NoneToken() # OK True """ __slots__ = _fields = ('variable',) _construct_variable = Variable class While(Token): """ Represents a 'for-loop' in the code. Expressions are of the form: "while condition: body..." Parameters ========== condition : expression convertible to Boolean body : CodeBlock or iterable When passed an iterable it is used to instantiate a CodeBlock. Examples ======== >>> from sympy import symbols, Gt, Abs >>> from sympy.codegen import aug_assign, Assignment, While >>> x, dx = symbols('x dx') >>> expr = 1 - x**2 >>> whl = While(Gt(Abs(dx), 1e-9), [ ... Assignment(dx, -expr/expr.diff(x)), ... aug_assign(x, '+', dx) ... ]) """ __slots__ = _fields = ('condition', 'body') _construct_condition = staticmethod(lambda cond: _sympify(cond)) @classmethod def _construct_body(cls, itr): if isinstance(itr, CodeBlock): return itr else: return CodeBlock(*itr) class Scope(Token): """ Represents a scope in the code. Parameters ========== body : CodeBlock or iterable When passed an iterable it is used to instantiate a CodeBlock. """ __slots__ = _fields = ('body',) @classmethod def _construct_body(cls, itr): if isinstance(itr, CodeBlock): return itr else: return CodeBlock(*itr) class Stream(Token): """ Represents a stream. There are two predefined Stream instances ``stdout`` & ``stderr``. Parameters ========== name : str Examples ======== >>> from sympy import pycode, Symbol >>> from sympy.codegen.ast import Print, stderr, QuotedString >>> print(pycode(Print(['x'], file=stderr))) print(x, file=sys.stderr) >>> x = Symbol('x') >>> print(pycode(Print([QuotedString('x')], file=stderr))) # print literally "x" print("x", file=sys.stderr) """ __slots__ = _fields = ('name',) _construct_name = String stdout = Stream('stdout') stderr = Stream('stderr') class Print(Token): """ Represents print command in the code. Parameters ========== formatstring : str *args : Basic instances (or convertible to such through sympify) Examples ======== >>> from sympy.codegen.ast import Print >>> from sympy import pycode >>> print(pycode(Print('x y'.split(), "coordinate: %12.5g %12.5g"))) print("coordinate: %12.5g %12.5g" % (x, y)) """ __slots__ = _fields = ('print_args', 'format_string', 'file') defaults = {'format_string': none, 'file': none} _construct_print_args = staticmethod(_mk_Tuple) _construct_format_string = QuotedString _construct_file = Stream class FunctionPrototype(Node): """ Represents a function prototype Allows the user to generate forward declaration in e.g. C/C++. Parameters ========== return_type : Type name : str parameters: iterable of Variable instances attrs : iterable of Attribute instances Examples ======== >>> from sympy import ccode, symbols >>> from sympy.codegen.ast import real, FunctionPrototype >>> x, y = symbols('x y', real=True) >>> fp = FunctionPrototype(real, 'foo', [x, y]) >>> ccode(fp) 'double foo(double x, double y)' """ __slots__ = ('return_type', 'name', 'parameters') _fields: tuple[str, ...] = __slots__ + Node._fields _construct_return_type = Type _construct_name = String @staticmethod def _construct_parameters(args): def _var(arg): if isinstance(arg, Declaration): return arg.variable elif isinstance(arg, Variable): return arg else: return Variable.deduced(arg) return Tuple(*map(_var, args)) @classmethod def from_FunctionDefinition(cls, func_def): if not isinstance(func_def, FunctionDefinition): raise TypeError("func_def is not an instance of FunctionDefinition") return cls(**func_def.kwargs(exclude=('body',))) class FunctionDefinition(FunctionPrototype): """ Represents a function definition in the code. Parameters ========== return_type : Type name : str parameters: iterable of Variable instances body : CodeBlock or iterable attrs : iterable of Attribute instances Examples ======== >>> from sympy import ccode, symbols >>> from sympy.codegen.ast import real, FunctionPrototype >>> x, y = symbols('x y', real=True) >>> fp = FunctionPrototype(real, 'foo', [x, y]) >>> ccode(fp) 'double foo(double x, double y)' >>> from sympy.codegen.ast import FunctionDefinition, Return >>> body = [Return(x*y)] >>> fd = FunctionDefinition.from_FunctionPrototype(fp, body) >>> print(ccode(fd)) double foo(double x, double y){ return x*y; } """ __slots__ = ('body', ) _fields = FunctionPrototype._fields[:-1] + __slots__ + Node._fields @classmethod def _construct_body(cls, itr): if isinstance(itr, CodeBlock): return itr else: return CodeBlock(*itr) @classmethod def from_FunctionPrototype(cls, func_proto, body): if not isinstance(func_proto, FunctionPrototype): raise TypeError("func_proto is not an instance of FunctionPrototype") return cls(body=body, **func_proto.kwargs()) class Return(Token): """ Represents a return command in the code. Parameters ========== return : Basic Examples ======== >>> from sympy.codegen.ast import Return >>> from sympy.printing.pycode import pycode >>> from sympy import Symbol >>> x = Symbol('x') >>> print(pycode(Return(x))) return x """ __slots__ = _fields = ('return',) _construct_return=staticmethod(_sympify) class FunctionCall(Token, Expr): """ Represents a call to a function in the code. Parameters ========== name : str function_args : Tuple Examples ======== >>> from sympy.codegen.ast import FunctionCall >>> from sympy import pycode >>> fcall = FunctionCall('foo', 'bar baz'.split()) >>> print(pycode(fcall)) foo(bar, baz) """ __slots__ = _fields = ('name', 'function_args') _construct_name = String _construct_function_args = staticmethod(lambda args: Tuple(*args))
4862cf20c80613da3d4616938538157269c508a6f1359bee92aa77bafaafd15c
""" This module contains SymPy functions mathcin corresponding to special math functions in the C standard library (since C99, also available in C++11). The functions defined in this module allows the user to express functions such as ``expm1`` as a SymPy function for symbolic manipulation. """ from sympy.core.function import ArgumentIndexError, Function from sympy.core.numbers import Rational from sympy.core.power import Pow from sympy.core.singleton import S from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.miscellaneous import sqrt def _expm1(x): return exp(x) - S.One class expm1(Function): """ Represents the exponential function minus one. Explanation =========== The benefit of using ``expm1(x)`` over ``exp(x) - 1`` is that the latter is prone to cancellation under finite precision arithmetic when x is close to zero. Examples ======== >>> from sympy.abc import x >>> from sympy.codegen.cfunctions import expm1 >>> '%.0e' % expm1(1e-99).evalf() '1e-99' >>> from math import exp >>> exp(1e-99) - 1 0.0 >>> expm1(x).diff(x) exp(x) See Also ======== log1p """ nargs = 1 def fdiff(self, argindex=1): """ Returns the first derivative of this function. """ if argindex == 1: return exp(*self.args) else: raise ArgumentIndexError(self, argindex) def _eval_expand_func(self, **hints): return _expm1(*self.args) def _eval_rewrite_as_exp(self, arg, **kwargs): return exp(arg) - S.One _eval_rewrite_as_tractable = _eval_rewrite_as_exp @classmethod def eval(cls, arg): exp_arg = exp.eval(arg) if exp_arg is not None: return exp_arg - S.One def _eval_is_real(self): return self.args[0].is_real def _eval_is_finite(self): return self.args[0].is_finite def _log1p(x): return log(x + S.One) class log1p(Function): """ Represents the natural logarithm of a number plus one. Explanation =========== The benefit of using ``log1p(x)`` over ``log(x + 1)`` is that the latter is prone to cancellation under finite precision arithmetic when x is close to zero. Examples ======== >>> from sympy.abc import x >>> from sympy.codegen.cfunctions import log1p >>> from sympy import expand_log >>> '%.0e' % expand_log(log1p(1e-99)).evalf() '1e-99' >>> from math import log >>> log(1 + 1e-99) 0.0 >>> log1p(x).diff(x) 1/(x + 1) See Also ======== expm1 """ nargs = 1 def fdiff(self, argindex=1): """ Returns the first derivative of this function. """ if argindex == 1: return S.One/(self.args[0] + S.One) else: raise ArgumentIndexError(self, argindex) def _eval_expand_func(self, **hints): return _log1p(*self.args) def _eval_rewrite_as_log(self, arg, **kwargs): return _log1p(arg) _eval_rewrite_as_tractable = _eval_rewrite_as_log @classmethod def eval(cls, arg): if arg.is_Rational: return log(arg + S.One) elif not arg.is_Float: # not safe to add 1 to Float return log.eval(arg + S.One) elif arg.is_number: return log(Rational(arg) + S.One) def _eval_is_real(self): return (self.args[0] + S.One).is_nonnegative def _eval_is_finite(self): if (self.args[0] + S.One).is_zero: return False return self.args[0].is_finite def _eval_is_positive(self): return self.args[0].is_positive def _eval_is_zero(self): return self.args[0].is_zero def _eval_is_nonnegative(self): return self.args[0].is_nonnegative _Two = S(2) def _exp2(x): return Pow(_Two, x) class exp2(Function): """ Represents the exponential function with base two. Explanation =========== The benefit of using ``exp2(x)`` over ``2**x`` is that the latter is not as efficient under finite precision arithmetic. Examples ======== >>> from sympy.abc import x >>> from sympy.codegen.cfunctions import exp2 >>> exp2(2).evalf() == 4.0 True >>> exp2(x).diff(x) log(2)*exp2(x) See Also ======== log2 """ nargs = 1 def fdiff(self, argindex=1): """ Returns the first derivative of this function. """ if argindex == 1: return self*log(_Two) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_Pow(self, arg, **kwargs): return _exp2(arg) _eval_rewrite_as_tractable = _eval_rewrite_as_Pow def _eval_expand_func(self, **hints): return _exp2(*self.args) @classmethod def eval(cls, arg): if arg.is_number: return _exp2(arg) def _log2(x): return log(x)/log(_Two) class log2(Function): """ Represents the logarithm function with base two. Explanation =========== The benefit of using ``log2(x)`` over ``log(x)/log(2)`` is that the latter is not as efficient under finite precision arithmetic. Examples ======== >>> from sympy.abc import x >>> from sympy.codegen.cfunctions import log2 >>> log2(4).evalf() == 2.0 True >>> log2(x).diff(x) 1/(x*log(2)) See Also ======== exp2 log10 """ nargs = 1 def fdiff(self, argindex=1): """ Returns the first derivative of this function. """ if argindex == 1: return S.One/(log(_Two)*self.args[0]) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): if arg.is_number: result = log.eval(arg, base=_Two) if result.is_Atom: return result elif arg.is_Pow and arg.base == _Two: return arg.exp def _eval_evalf(self, *args, **kwargs): return self.rewrite(log).evalf(*args, **kwargs) def _eval_expand_func(self, **hints): return _log2(*self.args) def _eval_rewrite_as_log(self, arg, **kwargs): return _log2(arg) _eval_rewrite_as_tractable = _eval_rewrite_as_log def _fma(x, y, z): return x*y + z class fma(Function): """ Represents "fused multiply add". Explanation =========== The benefit of using ``fma(x, y, z)`` over ``x*y + z`` is that, under finite precision arithmetic, the former is supported by special instructions on some CPUs. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.codegen.cfunctions import fma >>> fma(x, y, z).diff(x) y """ nargs = 3 def fdiff(self, argindex=1): """ Returns the first derivative of this function. """ if argindex in (1, 2): return self.args[2 - argindex] elif argindex == 3: return S.One else: raise ArgumentIndexError(self, argindex) def _eval_expand_func(self, **hints): return _fma(*self.args) def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs): return _fma(arg) _Ten = S(10) def _log10(x): return log(x)/log(_Ten) class log10(Function): """ Represents the logarithm function with base ten. Examples ======== >>> from sympy.abc import x >>> from sympy.codegen.cfunctions import log10 >>> log10(100).evalf() == 2.0 True >>> log10(x).diff(x) 1/(x*log(10)) See Also ======== log2 """ nargs = 1 def fdiff(self, argindex=1): """ Returns the first derivative of this function. """ if argindex == 1: return S.One/(log(_Ten)*self.args[0]) else: raise ArgumentIndexError(self, argindex) @classmethod def eval(cls, arg): if arg.is_number: result = log.eval(arg, base=_Ten) if result.is_Atom: return result elif arg.is_Pow and arg.base == _Ten: return arg.exp def _eval_expand_func(self, **hints): return _log10(*self.args) def _eval_rewrite_as_log(self, arg, **kwargs): return _log10(arg) _eval_rewrite_as_tractable = _eval_rewrite_as_log def _Sqrt(x): return Pow(x, S.Half) class Sqrt(Function): # 'sqrt' already defined in sympy.functions.elementary.miscellaneous """ Represents the square root function. Explanation =========== The reason why one would use ``Sqrt(x)`` over ``sqrt(x)`` is that the latter is internally represented as ``Pow(x, S.Half)`` which may not be what one wants when doing code-generation. Examples ======== >>> from sympy.abc import x >>> from sympy.codegen.cfunctions import Sqrt >>> Sqrt(x) Sqrt(x) >>> Sqrt(x).diff(x) 1/(2*sqrt(x)) See Also ======== Cbrt """ nargs = 1 def fdiff(self, argindex=1): """ Returns the first derivative of this function. """ if argindex == 1: return Pow(self.args[0], Rational(-1, 2))/_Two else: raise ArgumentIndexError(self, argindex) def _eval_expand_func(self, **hints): return _Sqrt(*self.args) def _eval_rewrite_as_Pow(self, arg, **kwargs): return _Sqrt(arg) _eval_rewrite_as_tractable = _eval_rewrite_as_Pow def _Cbrt(x): return Pow(x, Rational(1, 3)) class Cbrt(Function): # 'cbrt' already defined in sympy.functions.elementary.miscellaneous """ Represents the cube root function. Explanation =========== The reason why one would use ``Cbrt(x)`` over ``cbrt(x)`` is that the latter is internally represented as ``Pow(x, Rational(1, 3))`` which may not be what one wants when doing code-generation. Examples ======== >>> from sympy.abc import x >>> from sympy.codegen.cfunctions import Cbrt >>> Cbrt(x) Cbrt(x) >>> Cbrt(x).diff(x) 1/(3*x**(2/3)) See Also ======== Sqrt """ nargs = 1 def fdiff(self, argindex=1): """ Returns the first derivative of this function. """ if argindex == 1: return Pow(self.args[0], Rational(-_Two/3))/3 else: raise ArgumentIndexError(self, argindex) def _eval_expand_func(self, **hints): return _Cbrt(*self.args) def _eval_rewrite_as_Pow(self, arg, **kwargs): return _Cbrt(arg) _eval_rewrite_as_tractable = _eval_rewrite_as_Pow def _hypot(x, y): return sqrt(Pow(x, 2) + Pow(y, 2)) class hypot(Function): """ Represents the hypotenuse function. Explanation =========== The hypotenuse function is provided by e.g. the math library in the C99 standard, hence one may want to represent the function symbolically when doing code-generation. Examples ======== >>> from sympy.abc import x, y >>> from sympy.codegen.cfunctions import hypot >>> hypot(3, 4).evalf() == 5.0 True >>> hypot(x, y) hypot(x, y) >>> hypot(x, y).diff(x) x/hypot(x, y) """ nargs = 2 def fdiff(self, argindex=1): """ Returns the first derivative of this function. """ if argindex in (1, 2): return 2*self.args[argindex-1]/(_Two*self.func(*self.args)) else: raise ArgumentIndexError(self, argindex) def _eval_expand_func(self, **hints): return _hypot(*self.args) def _eval_rewrite_as_Pow(self, arg, **kwargs): return _hypot(arg) _eval_rewrite_as_tractable = _eval_rewrite_as_Pow
310660dc989512f699bb33253947978cf2ee0109616f9f9034353c330e663672
"""Module for querying SymPy objects about assumptions.""" from sympy.assumptions.assume import (global_assumptions, Predicate, AppliedPredicate) from sympy.assumptions.cnf import CNF, EncodedCNF, Literal from sympy.core import sympify from sympy.core.kind import BooleanKind from sympy.core.relational import Eq, Ne, Gt, Lt, Ge, Le from sympy.logic.inference import satisfiable from sympy.utilities.decorator import memoize_property from sympy.utilities.exceptions import (sympy_deprecation_warning, SymPyDeprecationWarning, ignore_warnings) # Memoization is necessary for the properties of AssumptionKeys to # ensure that only one object of Predicate objects are created. # This is because assumption handlers are registered on those objects. class AssumptionKeys: """ This class contains all the supported keys by ``ask``. It should be accessed via the instance ``sympy.Q``. """ # DO NOT add methods or properties other than predicate keys. # SAT solver checks the properties of Q and use them to compute the # fact system. Non-predicate attributes will break this. @memoize_property def hermitian(self): from .handlers.sets import HermitianPredicate return HermitianPredicate() @memoize_property def antihermitian(self): from .handlers.sets import AntihermitianPredicate return AntihermitianPredicate() @memoize_property def real(self): from .handlers.sets import RealPredicate return RealPredicate() @memoize_property def extended_real(self): from .handlers.sets import ExtendedRealPredicate return ExtendedRealPredicate() @memoize_property def imaginary(self): from .handlers.sets import ImaginaryPredicate return ImaginaryPredicate() @memoize_property def complex(self): from .handlers.sets import ComplexPredicate return ComplexPredicate() @memoize_property def algebraic(self): from .handlers.sets import AlgebraicPredicate return AlgebraicPredicate() @memoize_property def transcendental(self): from .predicates.sets import TranscendentalPredicate return TranscendentalPredicate() @memoize_property def integer(self): from .handlers.sets import IntegerPredicate return IntegerPredicate() @memoize_property def rational(self): from .handlers.sets import RationalPredicate return RationalPredicate() @memoize_property def irrational(self): from .handlers.sets import IrrationalPredicate return IrrationalPredicate() @memoize_property def finite(self): from .handlers.calculus import FinitePredicate return FinitePredicate() @memoize_property def infinite(self): from .handlers.calculus import InfinitePredicate return InfinitePredicate() @memoize_property def positive_infinite(self): from .handlers.calculus import PositiveInfinitePredicate return PositiveInfinitePredicate() @memoize_property def negative_infinite(self): from .handlers.calculus import NegativeInfinitePredicate return NegativeInfinitePredicate() @memoize_property def positive(self): from .handlers.order import PositivePredicate return PositivePredicate() @memoize_property def negative(self): from .handlers.order import NegativePredicate return NegativePredicate() @memoize_property def zero(self): from .handlers.order import ZeroPredicate return ZeroPredicate() @memoize_property def extended_positive(self): from .handlers.order import ExtendedPositivePredicate return ExtendedPositivePredicate() @memoize_property def extended_negative(self): from .handlers.order import ExtendedNegativePredicate return ExtendedNegativePredicate() @memoize_property def nonzero(self): from .handlers.order import NonZeroPredicate return NonZeroPredicate() @memoize_property def nonpositive(self): from .handlers.order import NonPositivePredicate return NonPositivePredicate() @memoize_property def nonnegative(self): from .handlers.order import NonNegativePredicate return NonNegativePredicate() @memoize_property def extended_nonzero(self): from .handlers.order import ExtendedNonZeroPredicate return ExtendedNonZeroPredicate() @memoize_property def extended_nonpositive(self): from .handlers.order import ExtendedNonPositivePredicate return ExtendedNonPositivePredicate() @memoize_property def extended_nonnegative(self): from .handlers.order import ExtendedNonNegativePredicate return ExtendedNonNegativePredicate() @memoize_property def even(self): from .handlers.ntheory import EvenPredicate return EvenPredicate() @memoize_property def odd(self): from .handlers.ntheory import OddPredicate return OddPredicate() @memoize_property def prime(self): from .handlers.ntheory import PrimePredicate return PrimePredicate() @memoize_property def composite(self): from .handlers.ntheory import CompositePredicate return CompositePredicate() @memoize_property def commutative(self): from .handlers.common import CommutativePredicate return CommutativePredicate() @memoize_property def is_true(self): from .handlers.common import IsTruePredicate return IsTruePredicate() @memoize_property def symmetric(self): from .handlers.matrices import SymmetricPredicate return SymmetricPredicate() @memoize_property def invertible(self): from .handlers.matrices import InvertiblePredicate return InvertiblePredicate() @memoize_property def orthogonal(self): from .handlers.matrices import OrthogonalPredicate return OrthogonalPredicate() @memoize_property def unitary(self): from .handlers.matrices import UnitaryPredicate return UnitaryPredicate() @memoize_property def positive_definite(self): from .handlers.matrices import PositiveDefinitePredicate return PositiveDefinitePredicate() @memoize_property def upper_triangular(self): from .handlers.matrices import UpperTriangularPredicate return UpperTriangularPredicate() @memoize_property def lower_triangular(self): from .handlers.matrices import LowerTriangularPredicate return LowerTriangularPredicate() @memoize_property def diagonal(self): from .handlers.matrices import DiagonalPredicate return DiagonalPredicate() @memoize_property def fullrank(self): from .handlers.matrices import FullRankPredicate return FullRankPredicate() @memoize_property def square(self): from .handlers.matrices import SquarePredicate return SquarePredicate() @memoize_property def integer_elements(self): from .handlers.matrices import IntegerElementsPredicate return IntegerElementsPredicate() @memoize_property def real_elements(self): from .handlers.matrices import RealElementsPredicate return RealElementsPredicate() @memoize_property def complex_elements(self): from .handlers.matrices import ComplexElementsPredicate return ComplexElementsPredicate() @memoize_property def singular(self): from .predicates.matrices import SingularPredicate return SingularPredicate() @memoize_property def normal(self): from .predicates.matrices import NormalPredicate return NormalPredicate() @memoize_property def triangular(self): from .predicates.matrices import TriangularPredicate return TriangularPredicate() @memoize_property def unit_triangular(self): from .predicates.matrices import UnitTriangularPredicate return UnitTriangularPredicate() @memoize_property def eq(self): from .relation.equality import EqualityPredicate return EqualityPredicate() @memoize_property def ne(self): from .relation.equality import UnequalityPredicate return UnequalityPredicate() @memoize_property def gt(self): from .relation.equality import StrictGreaterThanPredicate return StrictGreaterThanPredicate() @memoize_property def ge(self): from .relation.equality import GreaterThanPredicate return GreaterThanPredicate() @memoize_property def lt(self): from .relation.equality import StrictLessThanPredicate return StrictLessThanPredicate() @memoize_property def le(self): from .relation.equality import LessThanPredicate return LessThanPredicate() Q = AssumptionKeys() def _extract_all_facts(assump, exprs): """ Extract all relevant assumptions from *assump* with respect to given *exprs*. Parameters ========== assump : sympy.assumptions.cnf.CNF exprs : tuple of expressions Returns ======= sympy.assumptions.cnf.CNF Examples ======== >>> from sympy import Q >>> from sympy.assumptions.cnf import CNF >>> from sympy.assumptions.ask import _extract_all_facts >>> from sympy.abc import x, y >>> assump = CNF.from_prop(Q.positive(x) & Q.integer(y)) >>> exprs = (x,) >>> cnf = _extract_all_facts(assump, exprs) >>> cnf.clauses {frozenset({Literal(Q.positive, False)})} """ facts = set() for clause in assump.clauses: args = [] for literal in clause: if isinstance(literal.lit, AppliedPredicate) and len(literal.lit.arguments) == 1: if literal.lit.arg in exprs: # Add literal if it has matching in it args.append(Literal(literal.lit.function, literal.is_Not)) else: # If any of the literals doesn't have matching expr don't add the whole clause. break else: if args: facts.add(frozenset(args)) return CNF(facts) def ask(proposition, assumptions=True, context=global_assumptions): """ Function to evaluate the proposition with assumptions. Explanation =========== This function evaluates the proposition to ``True`` or ``False`` if the truth value can be determined. If not, it returns ``None``. It should be discerned from :func:`~.refine()` which, when applied to a proposition, simplifies the argument to symbolic ``Boolean`` instead of Python built-in ``True``, ``False`` or ``None``. **Syntax** * ask(proposition) Evaluate the *proposition* in global assumption context. * ask(proposition, assumptions) Evaluate the *proposition* with respect to *assumptions* in global assumption context. Parameters ========== proposition : Boolean Proposition which will be evaluated to boolean value. If this is not ``AppliedPredicate``, it will be wrapped by ``Q.is_true``. assumptions : Boolean, optional Local assumptions to evaluate the *proposition*. context : AssumptionsContext, optional Default assumptions to evaluate the *proposition*. By default, this is ``sympy.assumptions.global_assumptions`` variable. Returns ======= ``True``, ``False``, or ``None`` Raises ====== TypeError : *proposition* or *assumptions* is not valid logical expression. ValueError : assumptions are inconsistent. Examples ======== >>> from sympy import ask, Q, pi >>> from sympy.abc import x, y >>> ask(Q.rational(pi)) False >>> ask(Q.even(x*y), Q.even(x) & Q.integer(y)) True >>> ask(Q.prime(4*x), Q.integer(x)) False If the truth value cannot be determined, ``None`` will be returned. >>> print(ask(Q.odd(3*x))) # cannot determine unless we know x None ``ValueError`` is raised if assumptions are inconsistent. >>> ask(Q.integer(x), Q.even(x) & Q.odd(x)) Traceback (most recent call last): ... ValueError: inconsistent assumptions Q.even(x) & Q.odd(x) Notes ===== Relations in assumptions are not implemented (yet), so the following will not give a meaningful result. >>> ask(Q.positive(x), x > 0) It is however a work in progress. See Also ======== sympy.assumptions.refine.refine : Simplification using assumptions. Proposition is not reduced to ``None`` if the truth value cannot be determined. """ from sympy.assumptions.satask import satask proposition = sympify(proposition) assumptions = sympify(assumptions) if isinstance(proposition, Predicate) or proposition.kind is not BooleanKind: raise TypeError("proposition must be a valid logical expression") if isinstance(assumptions, Predicate) or assumptions.kind is not BooleanKind: raise TypeError("assumptions must be a valid logical expression") binrelpreds = {Eq: Q.eq, Ne: Q.ne, Gt: Q.gt, Lt: Q.lt, Ge: Q.ge, Le: Q.le} if isinstance(proposition, AppliedPredicate): key, args = proposition.function, proposition.arguments elif proposition.func in binrelpreds: key, args = binrelpreds[type(proposition)], proposition.args else: key, args = Q.is_true, (proposition,) # convert local and global assumptions to CNF assump_cnf = CNF.from_prop(assumptions) assump_cnf.extend(context) # extract the relevant facts from assumptions with respect to args local_facts = _extract_all_facts(assump_cnf, args) # convert default facts and assumed facts to encoded CNF known_facts_cnf = get_all_known_facts() enc_cnf = EncodedCNF() enc_cnf.from_cnf(CNF(known_facts_cnf)) enc_cnf.add_from_cnf(local_facts) # check the satisfiability of given assumptions if local_facts.clauses and satisfiable(enc_cnf) is False: raise ValueError("inconsistent assumptions %s" % assumptions) # quick computation for single fact res = _ask_single_fact(key, local_facts) if res is not None: return res # direct resolution method, no logic res = key(*args)._eval_ask(assumptions) if res is not None: return bool(res) # using satask (still costly) res = satask(proposition, assumptions=assumptions, context=context) return res def _ask_single_fact(key, local_facts): """ Compute the truth value of single predicate using assumptions. Parameters ========== key : sympy.assumptions.assume.Predicate Proposition predicate. local_facts : sympy.assumptions.cnf.CNF Local assumption in CNF form. Returns ======= ``True``, ``False`` or ``None`` Examples ======== >>> from sympy import Q >>> from sympy.assumptions.cnf import CNF >>> from sympy.assumptions.ask import _ask_single_fact If prerequisite of proposition is rejected by the assumption, return ``False``. >>> key, assump = Q.zero, ~Q.zero >>> local_facts = CNF.from_prop(assump) >>> _ask_single_fact(key, local_facts) False >>> key, assump = Q.zero, ~Q.even >>> local_facts = CNF.from_prop(assump) >>> _ask_single_fact(key, local_facts) False If assumption implies the proposition, return ``True``. >>> key, assump = Q.even, Q.zero >>> local_facts = CNF.from_prop(assump) >>> _ask_single_fact(key, local_facts) True If proposition rejects the assumption, return ``False``. >>> key, assump = Q.even, Q.odd >>> local_facts = CNF.from_prop(assump) >>> _ask_single_fact(key, local_facts) False """ if local_facts.clauses: known_facts_dict = get_known_facts_dict() if len(local_facts.clauses) == 1: cl, = local_facts.clauses if len(cl) == 1: f, = cl prop_facts = known_facts_dict.get(key, None) prop_req = prop_facts[0] if prop_facts is not None else set() if f.is_Not and f.arg in prop_req: # the prerequisite of proposition is rejected return False for clause in local_facts.clauses: if len(clause) == 1: f, = clause prop_facts = known_facts_dict.get(f.arg, None) if not f.is_Not else None if prop_facts is None: continue prop_req, prop_rej = prop_facts if key in prop_req: # assumption implies the proposition return True elif key in prop_rej: # proposition rejects the assumption return False return None def register_handler(key, handler): """ Register a handler in the ask system. key must be a string and handler a class inheriting from AskHandler. .. deprecated:: 1.8. Use multipledispatch handler instead. See :obj:`~.Predicate`. """ sympy_deprecation_warning( """ The AskHandler system is deprecated. The register_handler() function should be replaced with the multipledispatch handler of Predicate. """, deprecated_since_version="1.8", active_deprecations_target='deprecated-askhandler', ) if isinstance(key, Predicate): key = key.name.name Qkey = getattr(Q, key, None) if Qkey is not None: Qkey.add_handler(handler) else: setattr(Q, key, Predicate(key, handlers=[handler])) def remove_handler(key, handler): """ Removes a handler from the ask system. .. deprecated:: 1.8. Use multipledispatch handler instead. See :obj:`~.Predicate`. """ sympy_deprecation_warning( """ The AskHandler system is deprecated. The remove_handler() function should be replaced with the multipledispatch handler of Predicate. """, deprecated_since_version="1.8", active_deprecations_target='deprecated-askhandler', ) if isinstance(key, Predicate): key = key.name.name # Don't show the same warning again recursively with ignore_warnings(SymPyDeprecationWarning): getattr(Q, key).remove_handler(handler) from sympy.assumptions.ask_generated import (get_all_known_facts, get_known_facts_dict)
8119ff8a73b57271c489887c4f75d1ccf949daac7ff75436cf201dc00530bc27
""" 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, Basic) from sympy.core.containers import Tuple from sympy.core.function import (Lambda, expand_complex, AppliedUndef, expand_log, _mexpand, expand_trig, nfloat) from sympy.core.mod import Mod from sympy.core.numbers import igcd, I, Number, Rational, oo, ilcm from sympy.core.power import integer_log from sympy.core.relational import Eq, Ne, Relational from sympy.core.sorting import default_sort_key, ordered from sympy.core.symbol import Symbol, _uniquely_named_symbol from sympy.core.sympify import _sympify from sympy.polys.matrices.linsolve import _linear_eq_to_dict from sympy.polys.polyroots import UnsolvableFactorError from sympy.simplify.simplify import simplify, fraction, trigsimp, nsimplify from sympy.simplify import powdenest, logcombine from sympy.functions import (log, tan, cot, sin, cos, sec, csc, exp, acos, asin, acsc, asec, piecewise_fold, Piecewise) from sympy.functions.elementary.complexes import Abs, arg, re, im from sympy.functions.elementary.hyperbolic import HyperbolicFunction from sympy.functions.elementary.miscellaneous import real_root from sympy.functions.elementary.trigonometric import TrigonometricFunction from sympy.logic.boolalg import And, BooleanTrue from sympy.sets import (FiniteSet, imageset, Interval, Intersection, Union, ConditionSet, ImageSet, Complement, Contains) from sympy.sets.sets import Set, ProductSet from sympy.matrices import zeros, 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, groebner, poly from sympy.polys.solvers import (sympy_eqs_to_ring, solve_lin_sys, PolyNonlinearError) from sympy.polys.matrices.linsolve import _linsolve from sympy.solvers.solvers import (checksol, denoms, unrad, _simple_dens, recast_to_symbols) from sympy.solvers.polysys import solve_poly_system from sympy.utilities import filldedent from sympy.utilities.iterables import (numbered_symbols, has_dups, is_sequence, iterable) from sympy.calculus.util import periodicity, continuous_domain, function_range from types import GeneratorType class NonlinearError(ValueError): """Raised when unexpectedly encountering nonlinear equations""" pass _rc = Dummy("R", real=True), Dummy("C", complex=True) def _masked(f, *atoms): """Return ``f``, with all objects given by ``atoms`` replaced with Dummy symbols, ``d``, and the list of replacements, ``(d, e)``, where ``e`` is an object of type given by ``atoms`` in which any other instances of atoms have been recursively replaced with Dummy symbols, too. The tuples are ordered so that if they are applied in sequence, the origin ``f`` will be restored. Examples ======== >>> from sympy import cos >>> from sympy.abc import x >>> from sympy.solvers.solveset import _masked >>> f = cos(cos(x) + 1) >>> f, reps = _masked(cos(1 + cos(x)), cos) >>> f _a1 >>> reps [(_a1, cos(_a0 + 1)), (_a0, cos(x))] >>> for d, e in reps: ... f = f.xreplace({d: e}) >>> f cos(cos(x) + 1) """ sym = numbered_symbols('a', cls=Dummy, real=True) mask = [] for a in ordered(f.atoms(*atoms)): for i in mask: a = a.replace(*i) mask.append((a, next(sym))) for i, (o, n) in enumerate(mask): f = f.replace(o, n) mask[i] = (n, o) mask = list(reversed(mask)) return f, mask def _invert(f_x, y, x, domain=S.Complexes): r""" Reduce the complex valued equation $f(x) = y$ to a set of equations $$\left\{g(x) = h_1(y),\ g(x) = h_2(y),\ \dots,\ g(x) = h_n(y) \right\}$$ where $g(x)$ is a simpler function than $f(x)$. The return value is a tuple $(g(x), \mathrm{set}_h)$, where $g(x)$ is a function of $x$ and $\mathrm{set}_h$ is the set of function $\left\{h_1(y), h_2(y), \dots, h_n(y)\right\}$. Here, $y$ is not necessarily a symbol. $\mathrm{set}_h$ contains the functions, along with the information about the domain in which they are valid, through set operations. For instance, if :math:`y = |x| - n` is inverted in the real domain, then $\mathrm{set}_h$ is not simply $\{-n, n\}$ as the nature of `n` is unknown; rather, it is: $$ \left(\left[0, \infty\right) \cap \left\{n\right\}\right) \cup \left(\left(-\infty, 0\right] \cap \left\{- n\right\}\right)$$ By default, the complex domain is used which means that inverting even seemingly simple functions like $\exp(x)$ will give very different results from those obtained in the real domain. (In the case of $\exp(x)$, the inversion via $\log$ is multi-valued in the complex domain, having infinitely many branches.) If you are working with real values only (or you are not sure which function to use) you should probably set the domain to ``S.Reals`` (or use ``invert_real`` which does that automatically). Examples ======== >>> from sympy.solvers.solveset import invert_complex, invert_real >>> from sympy.abc import x, y >>> from sympy import exp When does exp(x) == y? >>> invert_complex(exp(x), y, x) (x, ImageSet(Lambda(_n, I*(2*_n*pi + arg(y)) + log(Abs(y))), Integers)) >>> invert_real(exp(x), y, x) (x, Intersection({log(y)}, Reals)) When does exp(x) == 1? >>> invert_complex(exp(x), 1, x) (x, ImageSet(Lambda(_n, 2*_n*I*pi), Integers)) >>> invert_real(exp(x), 1, x) (x, {0}) See Also ======== invert_real, invert_complex """ x = sympify(x) if not x.is_Symbol: raise ValueError("x must be a symbol") f_x = sympify(f_x) if x not in f_x.free_symbols: raise ValueError("Inverse of constant function doesn't exist") y = sympify(y) if x in y.free_symbols: raise ValueError("y should be independent of x ") if domain.is_subset(S.Reals): x1, s = _invert_real(f_x, FiniteSet(y), x) else: x1, s = _invert_complex(f_x, FiniteSet(y), x) if not isinstance(s, FiniteSet) or x1 != x: return x1, s # Avoid adding gratuitous intersections with S.Complexes. Actual # conditions should be handled by the respective inverters. if domain is S.Complexes: return x1, s else: return x1, s.intersection(domain) invert_complex = _invert def invert_real(f_x, y, x): """ Inverts a real-valued function. Same as :func:`invert_complex`, but sets the domain to ``S.Reals`` before inverting. """ return _invert(f_x, y, x, S.Reals) def _invert_real(f, g_ys, symbol): """Helper function for _invert.""" if f == symbol or g_ys is S.EmptySet: return (f, g_ys) n = Dummy('n', real=True) if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1): return _invert_real(f.exp, imageset(Lambda(n, log(n)), g_ys), symbol) if hasattr(f, 'inverse') and f.inverse() is not None and not isinstance(f, ( TrigonometricFunction, HyperbolicFunction, )): if len(f.args) > 1: raise ValueError("Only functions with one argument are supported.") return _invert_real(f.args[0], imageset(Lambda(n, f.inverse()(n)), g_ys), symbol) if isinstance(f, Abs): return _invert_abs(f.args[0], g_ys, symbol) if f.is_Add: # f = g + h g, h = f.as_independent(symbol) if g is not S.Zero: return _invert_real(h, imageset(Lambda(n, n - g), g_ys), symbol) if f.is_Mul: # f = g*h g, h = f.as_independent(symbol) if g is not S.One: return _invert_real(h, imageset(Lambda(n, n/g), g_ys), symbol) if f.is_Pow: base, expo = f.args base_has_sym = base.has(symbol) expo_has_sym = expo.has(symbol) if not expo_has_sym: if expo.is_rational: num, den = expo.as_numer_denom() if den % 2 == 0 and num % 2 == 1 and den.is_zero is False: # Here we have f(x)**(num/den) = y # where den is nonzero and even and y is an element # of the set g_ys. # den is even, so we are only interested in the cases # where both f(x) and y are positive. # Restricting y to be positive (using the set g_ys_pos) # means that y**(den/num) is always positive. # Therefore it isn't necessary to also constrain f(x) # to be positive because we are only going to # find solutions of f(x) = y**(d/n) # where the rhs is already required to be positive. root = Lambda(n, real_root(n, expo)) g_ys_pos = g_ys & Interval(0, oo) res = imageset(root, g_ys_pos) _inv, _set = _invert_real(base, res, symbol) return (_inv, _set) if den % 2 == 1: root = Lambda(n, real_root(n, expo)) res = imageset(root, g_ys) if num % 2 == 0: neg_res = imageset(Lambda(n, -n), res) return _invert_real(base, res + neg_res, symbol) if num % 2 == 1: return _invert_real(base, res, symbol) elif expo.is_irrational: root = Lambda(n, real_root(n, expo)) g_ys_pos = g_ys & Interval(0, oo) res = imageset(root, g_ys_pos) return _invert_real(base, res, symbol) else: # indeterminate exponent, e.g. Float or parity of # num, den of rational could not be determined pass # use default return if not base_has_sym: rhs = g_ys.args[0] if base.is_positive: return _invert_real(expo, imageset(Lambda(n, log(n, base, evaluate=False)), g_ys), symbol) elif base.is_negative: s, b = integer_log(rhs, base) if b: return _invert_real(expo, FiniteSet(s), symbol) else: return (expo, S.EmptySet) elif base.is_zero: one = Eq(rhs, 1) if one == S.true: # special case: 0**x - 1 return _invert_real(expo, FiniteSet(0), symbol) elif one == S.false: return (expo, S.EmptySet) if isinstance(f, TrigonometricFunction): if isinstance(g_ys, FiniteSet): def inv(trig): if isinstance(trig, (sin, csc)): F = asin if isinstance(trig, sin) else acsc return (lambda a: n*pi + S.NegativeOne**n*F(a),) if isinstance(trig, (cos, sec)): F = acos if isinstance(trig, cos) else asec return ( lambda a: 2*n*pi + F(a), lambda a: 2*n*pi - F(a),) if isinstance(trig, (tan, cot)): return (lambda a: n*pi + trig.inverse()(a),) n = Dummy('n', integer=True) invs = S.EmptySet for L in inv(f): invs += Union(*[imageset(Lambda(n, L(g)), S.Integers) for g in g_ys]) return _invert_real(f.args[0], invs, symbol) return (f, g_ys) def _invert_complex(f, g_ys, symbol): """Helper function for _invert.""" if f == symbol or g_ys is S.EmptySet: return (f, g_ys) n = Dummy('n') if f.is_Add: # f = g + h g, h = f.as_independent(symbol) if g is not S.Zero: return _invert_complex(h, imageset(Lambda(n, n - g), g_ys), symbol) if f.is_Mul: # f = g*h g, h = f.as_independent(symbol) if g is not S.One: if g in {S.NegativeInfinity, S.ComplexInfinity, S.Infinity}: return (h, S.EmptySet) return _invert_complex(h, imageset(Lambda(n, n/g), g_ys), symbol) if f.is_Pow: base, expo = f.args # special case: g**r = 0 # Could be improved like `_invert_real` to handle more general cases. if expo.is_Rational and g_ys == FiniteSet(0): if expo.is_positive: return _invert_complex(base, g_ys, symbol) if hasattr(f, 'inverse') and f.inverse() is not None and \ not isinstance(f, TrigonometricFunction) and \ not isinstance(f, HyperbolicFunction) and \ not isinstance(f, exp): if len(f.args) > 1: raise ValueError("Only functions with one argument are supported.") return _invert_complex(f.args[0], imageset(Lambda(n, f.inverse()(n)), g_ys), symbol) if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1): if isinstance(g_ys, ImageSet): # can solve upto `(d*exp(exp(...(exp(a*x + b))...) + c)` format. # Further can be improved to `(d*exp(exp(...(exp(a*x**n + b*x**(n-1) + ... + f))...) + c)`. g_ys_expr = g_ys.lamda.expr g_ys_vars = g_ys.lamda.variables k = Dummy('k{}'.format(len(g_ys_vars))) g_ys_vars_1 = (k,) + g_ys_vars exp_invs = Union(*[imageset(Lambda((g_ys_vars_1,), (I*(2*k*pi + arg(g_ys_expr)) + log(Abs(g_ys_expr)))), S.Integers**(len(g_ys_vars_1)))]) return _invert_complex(f.exp, exp_invs, symbol) elif isinstance(g_ys, FiniteSet): exp_invs = Union(*[imageset(Lambda(n, I*(2*n*pi + arg(g_y)) + log(Abs(g_y))), S.Integers) for g_y in g_ys if g_y != 0]) return _invert_complex(f.exp, exp_invs, symbol) return (f, g_ys) def _invert_abs(f, g_ys, symbol): """Helper function for inverting absolute value functions. Returns the complete result of inverting an absolute value function along with the conditions which must also be satisfied. If it is certain that all these conditions are met, a :class:`~.FiniteSet` of all possible solutions is returned. If any condition cannot be satisfied, an :class:`~.EmptySet` is returned. Otherwise, a :class:`~.ConditionSet` of the solutions, with all the required conditions specified, is returned. """ if not g_ys.is_FiniteSet: # this could be used for FiniteSet, but the # results are more compact if they aren't, e.g. # ConditionSet(x, Contains(n, Interval(0, oo)), {-n, n}) vs # Union(Intersection(Interval(0, oo), {n}), Intersection(Interval(-oo, 0), {-n})) # for the solution of abs(x) - n pos = Intersection(g_ys, Interval(0, S.Infinity)) parg = _invert_real(f, pos, symbol) narg = _invert_real(-f, pos, symbol) if parg[0] != narg[0]: raise NotImplementedError return parg[0], Union(narg[1], parg[1]) # check conditions: all these must be true. If any are unknown # then return them as conditions which must be satisfied unknown = [] for a in g_ys.args: ok = a.is_nonnegative if a.is_Number else a.is_positive if ok is None: unknown.append(a) elif not ok: return symbol, S.EmptySet if unknown: conditions = And(*[Contains(i, Interval(0, oo)) for i in unknown]) else: conditions = True n = Dummy('n', real=True) # this is slightly different than above: instead of solving # +/-f on positive values, here we solve for f on +/- g_ys g_x, values = _invert_real(f, Union( imageset(Lambda(n, n), g_ys), imageset(Lambda(n, -n), g_ys)), symbol) return g_x, ConditionSet(g_x, conditions, values) def domain_check(f, symbol, p): """Returns False if point p is infinite or any subexpression of f is infinite or becomes so after replacing symbol with p. If none of these conditions is met then True will be returned. Examples ======== >>> from sympy import Mul, oo >>> from sympy.abc import x >>> from sympy.solvers.solveset import domain_check >>> g = 1/(1 + (1/(x + 1))**2) >>> domain_check(g, x, -1) False >>> domain_check(x**2, x, 0) True >>> domain_check(1/x, x, oo) False * The function relies on the assumption that the original form of the equation has not been changed by automatic simplification. >>> domain_check(x/x, x, 0) # x/x is automatically simplified to 1 True * To deal with automatic evaluations use evaluate=False: >>> domain_check(Mul(x, 1/x, evaluate=False), x, 0) False """ f, p = sympify(f), sympify(p) if p.is_infinite: return False return _domain_check(f, symbol, p) def _domain_check(f, symbol, p): # helper for domain check if f.is_Atom and f.is_finite: return True elif f.subs(symbol, p).is_infinite: return False elif isinstance(f, Piecewise): # Check the cases of the Piecewise in turn. There might be invalid # expressions in later cases that don't apply e.g. # solveset(Piecewise((0, Eq(x, 0)), (1/x, True)), x) for expr, cond in f.args: condsubs = cond.subs(symbol, p) if condsubs is S.false: continue elif condsubs is S.true: return _domain_check(expr, symbol, p) else: # We don't know which case of the Piecewise holds. On this # basis we cannot decide whether any solution is in or out of # the domain. Ideally this function would allow returning a # symbolic condition for the validity of the solution that # could be handled in the calling code. In the mean time we'll # give this particular solution the benefit of the doubt and # let it pass. return True else: # TODO : We should not blindly recurse through all args of arbitrary expressions like this return all(_domain_check(g, symbol, p) for g in f.args) def _is_finite_with_finite_vars(f, domain=S.Complexes): """ Return True if the given expression is finite. For symbols that do not assign a value for `complex` and/or `real`, the domain will be used to assign a value; symbols that do not assign a value for `finite` will be made finite. All other assumptions are left unmodified. """ def assumptions(s): A = s.assumptions0 A.setdefault('finite', A.get('finite', True)) if domain.is_subset(S.Reals): # if this gets set it will make complex=True, too A.setdefault('real', True) else: # don't change 'real' because being complex implies # nothing about being real A.setdefault('complex', True) return A reps = {s: Dummy(**assumptions(s)) for s in f.free_symbols} return f.xreplace(reps).is_finite def _is_function_class_equation(func_class, f, symbol): """ Tests whether the equation is an equation of the given function class. The given equation belongs to the given function class if it is comprised of functions of the function class which are multiplied by or added to expressions independent of the symbol. In addition, the arguments of all such functions must be linear in the symbol as well. Examples ======== >>> from sympy.solvers.solveset import _is_function_class_equation >>> from sympy import tan, sin, tanh, sinh, exp >>> from sympy.abc import x >>> from sympy.functions.elementary.trigonometric import TrigonometricFunction >>> from sympy.functions.elementary.hyperbolic import HyperbolicFunction >>> _is_function_class_equation(TrigonometricFunction, exp(x) + tan(x), x) False >>> _is_function_class_equation(TrigonometricFunction, tan(x) + sin(x), x) True >>> _is_function_class_equation(TrigonometricFunction, tan(x**2), x) False >>> _is_function_class_equation(TrigonometricFunction, tan(x + 2), x) True >>> _is_function_class_equation(HyperbolicFunction, tanh(x) + sinh(x), x) True """ if f.is_Mul or f.is_Add: return all(_is_function_class_equation(func_class, arg, symbol) for arg in f.args) if f.is_Pow: if not f.exp.has(symbol): return _is_function_class_equation(func_class, f.base, symbol) else: return False if not f.has(symbol): return True if isinstance(f, func_class): try: g = Poly(f.args[0], symbol) return g.degree() <= 1 except PolynomialError: return False else: return False def _solve_as_rational(f, symbol, domain): """ solve rational functions""" f = together(_mexpand(f, recursive=True), deep=True) g, h = fraction(f) if not h.has(symbol): try: return _solve_as_poly(g, symbol, domain) except NotImplementedError: # The polynomial formed from g could end up having # coefficients in a ring over which finding roots # isn't implemented yet, e.g. ZZ[a] for some symbol a return ConditionSet(symbol, Eq(f, 0), domain) except CoercionFailed: # contained oo, zoo or nan return S.EmptySet else: valid_solns = _solveset(g, symbol, domain) invalid_solns = _solveset(h, symbol, domain) return valid_solns - invalid_solns class _SolveTrig1Error(Exception): """Raised when _solve_trig1 heuristics do not apply""" def _solve_trig(f, symbol, domain): """Function to call other helpers to solve trigonometric equations """ sol = None try: sol = _solve_trig1(f, symbol, domain) except _SolveTrig1Error: try: sol = _solve_trig2(f, symbol, domain) except ValueError: raise NotImplementedError(filldedent(''' Solution to this kind of trigonometric equations is yet to be implemented''')) return sol def _solve_trig1(f, symbol, domain): """Primary solver for trigonometric and hyperbolic equations Returns either the solution set as a ConditionSet (auto-evaluated to a union of ImageSets if no variables besides 'symbol' are involved) or raises _SolveTrig1Error if f == 0 cannot be solved. Notes ===== Algorithm: 1. Do a change of variable x -> mu*x in arguments to trigonometric and hyperbolic functions, in order to reduce them to small integers. (This step is crucial to keep the degrees of the polynomials of step 4 low.) 2. Rewrite trigonometric/hyperbolic functions as exponentials. 3. Proceed to a 2nd change of variable, replacing exp(I*x) or exp(x) by y. 4. Solve the resulting rational equation. 5. Use invert_complex or invert_real to return to the original variable. 6. If the coefficients of 'symbol' were symbolic in nature, add the necessary consistency conditions in a ConditionSet. """ # Prepare change of variable x = Dummy('x') if _is_function_class_equation(HyperbolicFunction, f, symbol): cov = exp(x) inverter = invert_real if domain.is_subset(S.Reals) else invert_complex else: cov = exp(I*x) inverter = invert_complex f = trigsimp(f) f_original = f trig_functions = f.atoms(TrigonometricFunction, HyperbolicFunction) trig_arguments = [e.args[0] for e in trig_functions] # trigsimp may have reduced the equation to an expression # that is independent of 'symbol' (e.g. cos**2+sin**2) if not any(a.has(symbol) for a in trig_arguments): return solveset(f_original, symbol, domain) denominators = [] numerators = [] for ar in trig_arguments: try: poly_ar = Poly(ar, symbol) except PolynomialError: raise _SolveTrig1Error("trig argument is not a polynomial") if poly_ar.degree() > 1: # degree >1 still bad raise _SolveTrig1Error("degree of variable must not exceed one") if poly_ar.degree() == 0: # degree 0, don't care continue c = poly_ar.all_coeffs()[0] # got the coefficient of 'symbol' numerators.append(fraction(c)[0]) denominators.append(fraction(c)[1]) mu = lcm(denominators)/gcd(numerators) f = f.subs(symbol, mu*x) f = f.rewrite(exp) f = together(f) g, h = fraction(f) y = Dummy('y') g, h = g.expand(), h.expand() g, h = g.subs(cov, y), h.subs(cov, y) if g.has(x) or h.has(x): raise _SolveTrig1Error("change of variable not possible") solns = solveset_complex(g, y) - solveset_complex(h, y) if isinstance(solns, ConditionSet): raise _SolveTrig1Error("polynomial has ConditionSet solution") if isinstance(solns, FiniteSet): if any(isinstance(s, RootOf) for s in solns): raise _SolveTrig1Error("polynomial results in RootOf object") # revert the change of variable cov = cov.subs(x, symbol/mu) result = Union(*[inverter(cov, s, symbol)[1] for s in solns]) # In case of symbolic coefficients, the solution set is only valid # if numerator and denominator of mu are non-zero. if mu.has(Symbol): syms = (mu).atoms(Symbol) munum, muden = fraction(mu) condnum = munum.as_independent(*syms, as_Add=False)[1] condden = muden.as_independent(*syms, as_Add=False)[1] cond = And(Ne(condnum, 0), Ne(condden, 0)) else: cond = True # Actual conditions are returned as part of the ConditionSet. Adding an # intersection with C would only complicate some solution sets due to # current limitations of intersection code. (e.g. #19154) if domain is S.Complexes: # This is a slight abuse of ConditionSet. Ideally this should # be some kind of "PiecewiseSet". (See #19507 discussion) return ConditionSet(symbol, cond, result) else: return ConditionSet(symbol, cond, Intersection(result, domain)) elif solns is S.EmptySet: return S.EmptySet else: raise _SolveTrig1Error("polynomial solutions must form FiniteSet") def _solve_trig2(f, symbol, domain): """Secondary helper to solve trigonometric equations, called when first helper fails """ f = trigsimp(f) f_original = f trig_functions = f.atoms(sin, cos, tan, sec, cot, csc) trig_arguments = [e.args[0] for e in trig_functions] denominators = [] numerators = [] # todo: This solver can be extended to hyperbolics if the # analogous change of variable to tanh (instead of tan) # is used. if not trig_functions: return ConditionSet(symbol, Eq(f_original, 0), domain) # todo: The pre-processing below (extraction of numerators, denominators, # gcd, lcm, mu, etc.) should be updated to the enhanced version in # _solve_trig1. (See #19507) for ar in trig_arguments: try: poly_ar = Poly(ar, symbol) except PolynomialError: raise ValueError("give up, we cannot solve if this is not a polynomial in x") if poly_ar.degree() > 1: # degree >1 still bad raise ValueError("degree of variable inside polynomial should not exceed one") if poly_ar.degree() == 0: # degree 0, don't care continue c = poly_ar.all_coeffs()[0] # got the coefficient of 'symbol' try: numerators.append(Rational(c).p) denominators.append(Rational(c).q) except TypeError: return ConditionSet(symbol, Eq(f_original, 0), domain) x = Dummy('x') # ilcm() and igcd() require more than one argument if len(numerators) > 1: mu = Rational(2)*ilcm(*denominators)/igcd(*numerators) else: assert len(numerators) == 1 mu = Rational(2)*denominators[0]/numerators[0] f = f.subs(symbol, mu*x) f = f.rewrite(tan) f = expand_trig(f) f = together(f) g, h = fraction(f) y = Dummy('y') g, h = g.expand(), h.expand() g, h = g.subs(tan(x), y), h.subs(tan(x), y) if g.has(x) or h.has(x): return ConditionSet(symbol, Eq(f_original, 0), domain) solns = solveset(g, y, S.Reals) - solveset(h, y, S.Reals) if isinstance(solns, FiniteSet): result = Union(*[invert_real(tan(symbol/mu), s, symbol)[1] for s in solns]) dsol = invert_real(tan(symbol/mu), oo, symbol)[1] if degree(h) > degree(g): # If degree(denom)>degree(num) then there result = Union(result, dsol) # would be another sol at Lim(denom-->oo) return Intersection(result, domain) elif solns is S.EmptySet: return S.EmptySet else: return ConditionSet(symbol, Eq(f_original, 0), S.Reals) def _solve_as_poly(f, symbol, domain=S.Complexes): """ Solve the equation using polynomial techniques if it already is a polynomial equation or, with a change of variables, can be made so. """ result = None if f.is_polynomial(symbol): solns = roots(f, symbol, cubics=True, quartics=True, quintics=True, domain='EX') num_roots = sum(solns.values()) if degree(f, symbol) <= num_roots: result = FiniteSet(*solns.keys()) else: poly = Poly(f, symbol) solns = poly.all_roots() if poly.degree() <= len(solns): result = FiniteSet(*solns) else: result = ConditionSet(symbol, Eq(f, 0), domain) else: poly = Poly(f) if poly is None: result = ConditionSet(symbol, Eq(f, 0), domain) gens = [g for g in poly.gens if g.has(symbol)] if len(gens) == 1: poly = Poly(poly, gens[0]) gen = poly.gen deg = poly.degree() poly = Poly(poly.as_expr(), poly.gen, composite=True) poly_solns = FiniteSet(*roots(poly, cubics=True, quartics=True, quintics=True).keys()) if len(poly_solns) < deg: result = ConditionSet(symbol, Eq(f, 0), domain) if gen != symbol: y = Dummy('y') inverter = invert_real if domain.is_subset(S.Reals) else invert_complex lhs, rhs_s = inverter(gen, y, symbol) if lhs == symbol: result = Union(*[rhs_s.subs(y, s) for s in poly_solns]) if isinstance(result, FiniteSet) and isinstance(gen, Pow ) and gen.base.is_Rational: result = FiniteSet(*[expand_log(i) for i in result]) else: result = ConditionSet(symbol, Eq(f, 0), domain) else: result = ConditionSet(symbol, Eq(f, 0), domain) if result is not None: if isinstance(result, FiniteSet): # this is to simplify solutions like -sqrt(-I) to sqrt(2)/2 # - sqrt(2)*I/2. We are not expanding for solution with symbols # or undefined functions because that makes the solution more complicated. # For example, expand_complex(a) returns re(a) + I*im(a) if all(s.atoms(Symbol, AppliedUndef) == set() and not isinstance(s, RootOf) for s in result): s = Dummy('s') result = imageset(Lambda(s, expand_complex(s)), result) if isinstance(result, FiniteSet) and domain != S.Complexes: # Avoid adding gratuitous intersections with S.Complexes. Actual # conditions should be handled elsewhere. result = result.intersection(domain) return result else: return ConditionSet(symbol, Eq(f, 0), domain) def _solve_radical(f, unradf, symbol, solveset_solver): """ Helper function to solve equations with radicals """ res = unradf eq, cov = res if res else (f, []) if not cov: result = solveset_solver(eq, symbol) - \ Union(*[solveset_solver(g, symbol) for g in denoms(f, symbol)]) else: y, yeq = cov if not solveset_solver(y - I, y): yreal = Dummy('yreal', real=True) yeq = yeq.xreplace({y: yreal}) eq = eq.xreplace({y: yreal}) y = yreal g_y_s = solveset_solver(yeq, symbol) f_y_sols = solveset_solver(eq, y) result = Union(*[imageset(Lambda(y, g_y), f_y_sols) for g_y in g_y_s]) if not isinstance(result, FiniteSet): solution_set = result else: f_set = [] # solutions for FiniteSet c_set = [] # solutions for ConditionSet for s in result: if checksol(f, symbol, s): f_set.append(s) else: c_set.append(s) solution_set = FiniteSet(*f_set) + ConditionSet(symbol, Eq(f, 0), FiniteSet(*c_set)) return solution_set def _solve_abs(f, symbol, domain): """ Helper function to solve equation involving absolute value function """ if not domain.is_subset(S.Reals): raise ValueError(filldedent(''' Absolute values cannot be inverted in the complex domain.''')) p, q, r = Wild('p'), Wild('q'), Wild('r') pattern_match = f.match(p*Abs(q) + r) or {} f_p, f_q, f_r = [pattern_match.get(i, S.Zero) for i in (p, q, r)] if not (f_p.is_zero or f_q.is_zero): domain = continuous_domain(f_q, symbol, domain) from .inequalities import solve_univariate_inequality q_pos_cond = solve_univariate_inequality(f_q >= 0, symbol, relational=False, domain=domain, continuous=True) q_neg_cond = q_pos_cond.complement(domain) sols_q_pos = solveset_real(f_p*f_q + f_r, symbol).intersect(q_pos_cond) sols_q_neg = solveset_real(f_p*(-f_q) + f_r, symbol).intersect(q_neg_cond) return Union(sols_q_pos, sols_q_neg) else: return ConditionSet(symbol, Eq(f, 0), domain) def solve_decomposition(f, symbol, domain): """ Function to solve equations via the principle of "Decomposition and Rewriting". Examples ======== >>> from sympy import exp, sin, Symbol, pprint, S >>> from sympy.solvers.solveset import solve_decomposition as sd >>> x = Symbol('x') >>> f1 = exp(2*x) - 3*exp(x) + 2 >>> sd(f1, x, S.Reals) {0, log(2)} >>> f2 = sin(x)**2 + 2*sin(x) + 1 >>> pprint(sd(f2, x, S.Reals), use_unicode=False) 3*pi {2*n*pi + ---- | n in Integers} 2 >>> f3 = sin(x + 2) >>> pprint(sd(f3, x, S.Reals), use_unicode=False) {2*n*pi - 2 | n in Integers} U {2*n*pi - 2 + pi | n in Integers} """ from sympy.solvers.decompogen import decompogen # decompose the given function g_s = decompogen(f, symbol) # `y_s` represents the set of values for which the function `g` is to be # solved. # `solutions` represent the solutions of the equations `g = y_s` or # `g = 0` depending on the type of `y_s`. # As we are interested in solving the equation: f = 0 y_s = FiniteSet(0) for g in g_s: frange = function_range(g, symbol, domain) y_s = Intersection(frange, y_s) result = S.EmptySet if isinstance(y_s, FiniteSet): for y in y_s: solutions = solveset(Eq(g, y), symbol, domain) if not isinstance(solutions, ConditionSet): result += solutions else: if isinstance(y_s, ImageSet): iter_iset = (y_s,) elif isinstance(y_s, Union): iter_iset = y_s.args elif y_s is S.EmptySet: # y_s is not in the range of g in g_s, so no solution exists #in the given domain return S.EmptySet for iset in iter_iset: new_solutions = solveset(Eq(iset.lamda.expr, g), symbol, domain) dummy_var = tuple(iset.lamda.expr.free_symbols)[0] (base_set,) = iset.base_sets if isinstance(new_solutions, FiniteSet): new_exprs = new_solutions elif isinstance(new_solutions, Intersection): if isinstance(new_solutions.args[1], FiniteSet): new_exprs = new_solutions.args[1] for new_expr in new_exprs: result += ImageSet(Lambda(dummy_var, new_expr), base_set) if result is S.EmptySet: return ConditionSet(symbol, Eq(f, 0), domain) y_s = result return y_s def _solveset(f, symbol, domain, _check=False): """Helper for solveset to return a result from an expression that has already been sympify'ed and is known to contain the given symbol.""" # _check controls whether the answer is checked or not from sympy.simplify.simplify import signsimp if isinstance(f, BooleanTrue): return domain orig_f = f if f.is_Mul: coeff, f = f.as_independent(symbol, as_Add=False) if coeff in {S.ComplexInfinity, S.NegativeInfinity, S.Infinity}: f = together(orig_f) elif f.is_Add: a, h = f.as_independent(symbol) m, h = h.as_independent(symbol, as_Add=False) if m not in {S.ComplexInfinity, S.Zero, S.Infinity, S.NegativeInfinity}: f = a/m + h # XXX condition `m != 0` should be added to soln # assign the solvers to use solver = lambda f, x, domain=domain: _solveset(f, x, domain) inverter = lambda f, rhs, symbol: _invert(f, rhs, symbol, domain) result = S.EmptySet if f.expand().is_zero: return domain elif not f.has(symbol): return S.EmptySet elif f.is_Mul and all(_is_finite_with_finite_vars(m, domain) for m in f.args): # if f(x) and g(x) are both finite we can say that the solution of # f(x)*g(x) == 0 is same as Union(f(x) == 0, g(x) == 0) is not true in # general. g(x) can grow to infinitely large for the values where # f(x) == 0. To be sure that we are not silently allowing any # wrong solutions we are using this technique only if both f and g are # finite for a finite input. result = Union(*[solver(m, symbol) for m in f.args]) elif _is_function_class_equation(TrigonometricFunction, f, symbol) or \ _is_function_class_equation(HyperbolicFunction, f, symbol): result = _solve_trig(f, symbol, domain) elif isinstance(f, arg): a = f.args[0] result = Intersection(_solveset(re(a) > 0, symbol, domain), _solveset(im(a), symbol, domain)) elif f.is_Piecewise: expr_set_pairs = f.as_expr_set_pairs(domain) for (expr, in_set) in expr_set_pairs: if in_set.is_Relational: in_set = in_set.as_set() solns = solver(expr, symbol, in_set) result += solns elif isinstance(f, Eq): result = solver(Add(f.lhs, - f.rhs, evaluate=False), symbol, domain) elif f.is_Relational: from .inequalities import solve_univariate_inequality try: result = solve_univariate_inequality( f, symbol, domain=domain, relational=False) except NotImplementedError: result = ConditionSet(symbol, f, domain) return result elif _is_modular(f, symbol): result = _solve_modular(f, symbol, domain) else: lhs, rhs_s = inverter(f, 0, symbol) if lhs == symbol: # do some very minimal simplification since # repeated inversion may have left the result # in a state that other solvers (e.g. poly) # would have simplified; this is done here # rather than in the inverter since here it # is only done once whereas there it would # be repeated for each step of the inversion if isinstance(rhs_s, FiniteSet): rhs_s = FiniteSet(*[Mul(* signsimp(i).as_content_primitive()) for i in rhs_s]) result = rhs_s elif isinstance(rhs_s, FiniteSet): for equation in [lhs - rhs for rhs in rhs_s]: if equation == f: u = unrad(f, symbol) if u: result += _solve_radical(equation, u, symbol, solver) elif equation.has(Abs): result += _solve_abs(f, symbol, domain) else: result_rational = _solve_as_rational(equation, symbol, domain) if not isinstance(result_rational, ConditionSet): result += result_rational else: # may be a transcendental type equation t_result = _transolve(equation, symbol, domain) if isinstance(t_result, ConditionSet): # might need factoring; this is expensive so we # have delayed until now. To avoid recursion # errors look for a non-trivial factoring into # a product of symbol dependent terms; I think # that something that factors as a Pow would # have already been recognized by now. factored = equation.factor() if factored.is_Mul and equation != factored: _, dep = factored.as_independent(symbol) if not dep.is_Add: # non-trivial factoring of equation # but use form with constants # in case they need special handling t_results = [] for fac in Mul.make_args(factored): if fac.has(symbol): t_results.append(solver(fac, symbol)) t_result = Union(*t_results) result += t_result else: result += solver(equation, symbol) elif rhs_s is not S.EmptySet: result = ConditionSet(symbol, Eq(f, 0), domain) if isinstance(result, ConditionSet): if isinstance(f, Expr): num, den = f.as_numer_denom() if den.has(symbol): _result = _solveset(num, symbol, domain) if not isinstance(_result, ConditionSet): singularities = _solveset(den, symbol, domain) result = _result - singularities if _check: if isinstance(result, ConditionSet): # it wasn't solved or has enumerated all conditions # -- leave it alone return result # whittle away all but the symbol-containing core # to use this for testing if isinstance(orig_f, Expr): fx = orig_f.as_independent(symbol, as_Add=True)[1] fx = fx.as_independent(symbol, as_Add=False)[1] else: fx = orig_f if isinstance(result, FiniteSet): # check the result for invalid solutions result = FiniteSet(*[s for s in result if isinstance(s, RootOf) or domain_check(fx, symbol, s)]) return result def _is_modular(f, symbol): """ Helper function to check below mentioned types of modular equations. ``A - Mod(B, C) = 0`` A -> This can or cannot be a function of symbol. B -> This is surely a function of symbol. C -> It is an integer. Parameters ========== f : Expr The equation to be checked. symbol : Symbol The concerned variable for which the equation is to be checked. Examples ======== >>> from sympy import symbols, exp, Mod >>> from sympy.solvers.solveset import _is_modular as check >>> x, y = symbols('x y') >>> check(Mod(x, 3) - 1, x) True >>> check(Mod(x, 3) - 1, y) False >>> check(Mod(x, 3)**2 - 5, x) False >>> check(Mod(x, 3)**2 - y, x) False >>> check(exp(Mod(x, 3)) - 1, x) False >>> check(Mod(3, y) - 1, y) False """ if not f.has(Mod): return False # extract modterms from f. modterms = list(f.atoms(Mod)) return (len(modterms) == 1 and # only one Mod should be present modterms[0].args[0].has(symbol) and # B-> function of symbol modterms[0].args[1].is_integer and # C-> to be an integer. any(isinstance(term, Mod) for term in list(_term_factors(f))) # free from other funcs ) def _invert_modular(modterm, rhs, n, symbol): """ Helper function to invert modular equation. ``Mod(a, m) - rhs = 0`` Generally it is inverted as (a, ImageSet(Lambda(n, m*n + rhs), S.Integers)). More simplified form will be returned if possible. If it is not invertible then (modterm, rhs) is returned. The following cases arise while inverting equation ``Mod(a, m) - rhs = 0``: 1. If a is symbol then m*n + rhs is the required solution. 2. If a is an instance of ``Add`` then we try to find two symbol independent parts of a and the symbol independent part gets transferred to the other side and again the ``_invert_modular`` is called on the symbol dependent part. 3. If a is an instance of ``Mul`` then same as we done in ``Add`` we separate out the symbol dependent and symbol independent parts and transfer the symbol independent part to the rhs with the help of invert and again the ``_invert_modular`` is called on the symbol dependent part. 4. If a is an instance of ``Pow`` then two cases arise as following: - If a is of type (symbol_indep)**(symbol_dep) then the remainder is evaluated with the help of discrete_log function and then the least period is being found out with the help of totient function. period*n + remainder is the required solution in this case. For reference: (https://en.wikipedia.org/wiki/Euler's_theorem) - If a is of type (symbol_dep)**(symbol_indep) then we try to find all primitive solutions list with the help of nthroot_mod function. m*n + rem is the general solution where rem belongs to solutions list from nthroot_mod function. Parameters ========== modterm, rhs : Expr The modular equation to be inverted, ``modterm - rhs = 0`` symbol : Symbol The variable in the equation to be inverted. n : Dummy Dummy variable for output g_n. Returns ======= A tuple (f_x, g_n) is being returned where f_x is modular independent function of symbol and g_n being set of values f_x can have. Examples ======== >>> from sympy import symbols, exp, Mod, Dummy, S >>> from sympy.solvers.solveset import _invert_modular as invert_modular >>> x, y = symbols('x y') >>> n = Dummy('n') >>> invert_modular(Mod(exp(x), 7), S(5), n, x) (Mod(exp(x), 7), 5) >>> invert_modular(Mod(x, 7), S(5), n, x) (x, ImageSet(Lambda(_n, 7*_n + 5), Integers)) >>> invert_modular(Mod(3*x + 8, 7), S(5), n, x) (x, ImageSet(Lambda(_n, 7*_n + 6), Integers)) >>> invert_modular(Mod(x**4, 7), S(5), n, x) (x, EmptySet) >>> invert_modular(Mod(2**(x**2 + x + 1), 7), S(2), n, x) (x**2 + x + 1, ImageSet(Lambda(_n, 3*_n + 1), Naturals0)) """ a, m = modterm.args if rhs.is_real is False or any(term.is_real is False for term in list(_term_factors(a))): # Check for complex arguments return modterm, rhs if abs(rhs) >= abs(m): # if rhs has value greater than value of m. return symbol, S.EmptySet if a == symbol: return symbol, ImageSet(Lambda(n, m*n + rhs), S.Integers) if a.is_Add: # g + h = a g, h = a.as_independent(symbol) if g is not S.Zero: x_indep_term = rhs - Mod(g, m) return _invert_modular(Mod(h, m), Mod(x_indep_term, m), n, symbol) if a.is_Mul: # g*h = a g, h = a.as_independent(symbol) if g is not S.One: x_indep_term = rhs*invert(g, m) return _invert_modular(Mod(h, m), Mod(x_indep_term, m), n, symbol) if a.is_Pow: # base**expo = a base, expo = a.args if expo.has(symbol) and not base.has(symbol): # remainder -> solution independent of n of equation. # m, rhs are made coprime by dividing igcd(m, rhs) try: remainder = discrete_log(m / igcd(m, rhs), rhs, a.base) except ValueError: # log does not exist return modterm, rhs # period -> coefficient of n in the solution and also referred as # the least period of expo in which it is repeats itself. # (a**(totient(m)) - 1) divides m. Here is link of theorem: # (https://en.wikipedia.org/wiki/Euler's_theorem) period = totient(m) for p in divisors(period): # there might a lesser period exist than totient(m). if pow(a.base, p, m / igcd(m, a.base)) == 1: period = p break # recursion is not applied here since _invert_modular is currently # not smart enough to handle infinite rhs as here expo has infinite # rhs = ImageSet(Lambda(n, period*n + remainder), S.Naturals0). return expo, ImageSet(Lambda(n, period*n + remainder), S.Naturals0) elif base.has(symbol) and not expo.has(symbol): try: remainder_list = nthroot_mod(rhs, expo, m, all_roots=True) if remainder_list == []: return symbol, S.EmptySet except (ValueError, NotImplementedError): return modterm, rhs g_n = S.EmptySet for rem in remainder_list: g_n += ImageSet(Lambda(n, m*n + rem), S.Integers) return base, g_n return modterm, rhs def _solve_modular(f, symbol, domain): r""" Helper function for solving modular equations of type ``A - Mod(B, C) = 0``, where A can or cannot be a function of symbol, B is surely a function of symbol and C is an integer. Currently ``_solve_modular`` is only able to solve cases where A is not a function of symbol. Parameters ========== f : Expr The modular equation to be solved, ``f = 0`` symbol : Symbol The variable in the equation to be solved. domain : Set A set over which the equation is solved. It has to be a subset of Integers. Returns ======= A set of integer solutions satisfying the given modular equation. A ``ConditionSet`` if the equation is unsolvable. Examples ======== >>> from sympy.solvers.solveset import _solve_modular as solve_modulo >>> from sympy import S, Symbol, sin, Intersection, Interval, Mod >>> x = Symbol('x') >>> solve_modulo(Mod(5*x - 8, 7) - 3, x, S.Integers) ImageSet(Lambda(_n, 7*_n + 5), Integers) >>> solve_modulo(Mod(5*x - 8, 7) - 3, x, S.Reals) # domain should be subset of integers. ConditionSet(x, Eq(Mod(5*x + 6, 7) - 3, 0), Reals) >>> solve_modulo(-7 + Mod(x, 5), x, S.Integers) EmptySet >>> solve_modulo(Mod(12**x, 21) - 18, x, S.Integers) ImageSet(Lambda(_n, 6*_n + 2), Naturals0) >>> solve_modulo(Mod(sin(x), 7) - 3, x, S.Integers) # not solvable ConditionSet(x, Eq(Mod(sin(x), 7) - 3, 0), Integers) >>> solve_modulo(3 - Mod(x, 5), x, Intersection(S.Integers, Interval(0, 100))) Intersection(ImageSet(Lambda(_n, 5*_n + 3), Integers), Range(0, 101, 1)) """ # extract modterm and g_y from f unsolved_result = ConditionSet(symbol, Eq(f, 0), domain) modterm = list(f.atoms(Mod))[0] rhs = -S.One*(f.subs(modterm, S.Zero)) if f.as_coefficients_dict()[modterm].is_negative: # checks if coefficient of modterm is negative in main equation. rhs *= -S.One if not domain.is_subset(S.Integers): return unsolved_result if rhs.has(symbol): # TODO Case: A-> function of symbol, can be extended here # in future. return unsolved_result n = Dummy('n', integer=True) f_x, g_n = _invert_modular(modterm, rhs, n, symbol) if f_x == modterm and g_n == rhs: return unsolved_result if f_x == symbol: if domain is not S.Integers: return domain.intersect(g_n) return g_n if isinstance(g_n, ImageSet): lamda_expr = g_n.lamda.expr lamda_vars = g_n.lamda.variables base_sets = g_n.base_sets sol_set = _solveset(f_x - lamda_expr, symbol, S.Integers) if isinstance(sol_set, FiniteSet): tmp_sol = S.EmptySet for sol in sol_set: tmp_sol += ImageSet(Lambda(lamda_vars, sol), *base_sets) sol_set = tmp_sol else: sol_set = ImageSet(Lambda(lamda_vars, sol_set), *base_sets) return domain.intersect(sol_set) return unsolved_result def _term_factors(f): """ Iterator to get the factors of all terms present in the given equation. Parameters ========== f : Expr Equation that needs to be addressed Returns ======= Factors of all terms present in the equation. Examples ======== >>> from sympy import symbols >>> from sympy.solvers.solveset import _term_factors >>> x = symbols('x') >>> list(_term_factors(-2 - x**2 + x*(x + 1))) [-2, -1, x**2, x, x + 1] """ for add_arg in Add.make_args(f): yield from Mul.make_args(add_arg) def _solve_exponential(lhs, rhs, symbol, domain): r""" Helper function for solving (supported) exponential equations. Exponential equations are the sum of (currently) at most two terms with one or both of them having a power with a symbol-dependent exponent. For example .. math:: 5^{2x + 3} - 5^{3x - 1} .. math:: 4^{5 - 9x} - e^{2 - x} Parameters ========== lhs, rhs : Expr The exponential equation to be solved, `lhs = rhs` symbol : Symbol The variable in which the equation is solved domain : Set A set over which the equation is solved. Returns ======= A set of solutions satisfying the given equation. A ``ConditionSet`` if the equation is unsolvable or if the assumptions are not properly defined, in that case a different style of ``ConditionSet`` is returned having the solution(s) of the equation with the desired assumptions. Examples ======== >>> from sympy.solvers.solveset import _solve_exponential as solve_expo >>> from sympy import symbols, S >>> x = symbols('x', real=True) >>> a, b = symbols('a b') >>> solve_expo(2**x + 3**x - 5**x, 0, x, S.Reals) # not solvable ConditionSet(x, Eq(2**x + 3**x - 5**x, 0), Reals) >>> solve_expo(a**x - b**x, 0, x, S.Reals) # solvable but incorrect assumptions ConditionSet(x, (a > 0) & (b > 0), {0}) >>> solve_expo(3**(2*x) - 2**(x + 3), 0, x, S.Reals) {-3*log(2)/(-2*log(3) + log(2))} >>> solve_expo(2**x - 4**x, 0, x, S.Reals) {0} * Proof of correctness of the method The logarithm function is the inverse of the exponential function. The defining relation between exponentiation and logarithm is: .. math:: {\log_b x} = y \enspace if \enspace b^y = x Therefore if we are given an equation with exponent terms, we can convert every term to its corresponding logarithmic form. This is achieved by taking logarithms and expanding the equation using logarithmic identities so that it can easily be handled by ``solveset``. For example: .. math:: 3^{2x} = 2^{x + 3} Taking log both sides will reduce the equation to .. math:: (2x)\log(3) = (x + 3)\log(2) This form can be easily handed by ``solveset``. """ unsolved_result = ConditionSet(symbol, Eq(lhs - rhs, 0), domain) newlhs = powdenest(lhs) if lhs != newlhs: # it may also be advantageous to factor the new expr neweq = factor(newlhs - rhs) if neweq != (lhs - rhs): return _solveset(neweq, symbol, domain) # try again with _solveset if not (isinstance(lhs, Add) and len(lhs.args) == 2): # solving for the sum of more than two powers is possible # but not yet implemented return unsolved_result if rhs != 0: return unsolved_result a, b = list(ordered(lhs.args)) a_term = a.as_independent(symbol)[1] b_term = b.as_independent(symbol)[1] a_base, a_exp = a_term.as_base_exp() b_base, b_exp = b_term.as_base_exp() if domain.is_subset(S.Reals): conditions = And( a_base > 0, b_base > 0, Eq(im(a_exp), 0), Eq(im(b_exp), 0)) else: conditions = And( Ne(a_base, 0), Ne(b_base, 0)) L, R = map(lambda i: expand_log(log(i), force=True), (a, -b)) solutions = _solveset(L - R, symbol, domain) return ConditionSet(symbol, conditions, solutions) def _is_exponential(f, symbol): r""" Return ``True`` if one or more terms contain ``symbol`` only in exponents, else ``False``. Parameters ========== f : Expr The equation to be checked symbol : Symbol The variable in which the equation is checked Examples ======== >>> from sympy import symbols, cos, exp >>> from sympy.solvers.solveset import _is_exponential as check >>> x, y = symbols('x y') >>> check(y, y) False >>> check(x**y - 1, y) True >>> check(x**y*2**y - 1, y) True >>> check(exp(x + 3) + 3**x, x) True >>> check(cos(2**x), x) False * Philosophy behind the helper The function extracts each term of the equation and checks if it is of exponential form w.r.t ``symbol``. """ rv = False for expr_arg in _term_factors(f): if symbol not in expr_arg.free_symbols: continue if (isinstance(expr_arg, Pow) and symbol not in expr_arg.base.free_symbols or isinstance(expr_arg, exp)): rv = True # symbol in exponent else: return False # dependent on symbol in non-exponential way return rv def _solve_logarithm(lhs, rhs, symbol, domain): r""" Helper to solve logarithmic equations which are reducible to a single instance of `\log`. Logarithmic equations are (currently) the equations that contains `\log` terms which can be reduced to a single `\log` term or a constant using various logarithmic identities. For example: .. math:: \log(x) + \log(x - 4) can be reduced to: .. math:: \log(x(x - 4)) Parameters ========== lhs, rhs : Expr The logarithmic equation to be solved, `lhs = rhs` symbol : Symbol The variable in which the equation is solved domain : Set A set over which the equation is solved. Returns ======= A set of solutions satisfying the given equation. A ``ConditionSet`` if the equation is unsolvable. Examples ======== >>> from sympy import symbols, log, S >>> from sympy.solvers.solveset import _solve_logarithm as solve_log >>> x = symbols('x') >>> f = log(x - 3) + log(x + 3) >>> solve_log(f, 0, x, S.Reals) {-sqrt(10), sqrt(10)} * Proof of correctness A logarithm is another way to write exponent and is defined by .. math:: {\log_b x} = y \enspace if \enspace b^y = x When one side of the equation contains a single logarithm, the equation can be solved by rewriting the equation as an equivalent exponential equation as defined above. But if one side contains more than one logarithm, we need to use the properties of logarithm to condense it into a single logarithm. Take for example .. math:: \log(2x) - 15 = 0 contains single logarithm, therefore we can directly rewrite it to exponential form as .. math:: x = \frac{e^{15}}{2} But if the equation has more than one logarithm as .. math:: \log(x - 3) + \log(x + 3) = 0 we use logarithmic identities to convert it into a reduced form Using, .. math:: \log(a) + \log(b) = \log(ab) the equation becomes, .. math:: \log((x - 3)(x + 3)) This equation contains one logarithm and can be solved by rewriting to exponents. """ new_lhs = logcombine(lhs, force=True) new_f = new_lhs - rhs return _solveset(new_f, symbol, domain) def _is_logarithmic(f, symbol): r""" Return ``True`` if the equation is in the form `a\log(f(x)) + b\log(g(x)) + ... + c` else ``False``. Parameters ========== f : Expr The equation to be checked symbol : Symbol The variable in which the equation is checked Returns ======= ``True`` if the equation is logarithmic otherwise ``False``. Examples ======== >>> from sympy import symbols, tan, log >>> from sympy.solvers.solveset import _is_logarithmic as check >>> x, y = symbols('x y') >>> check(log(x + 2) - log(x + 3), x) True >>> check(tan(log(2*x)), x) False >>> check(x*log(x), x) False >>> check(x + log(x), x) False >>> check(y + log(x), x) True * Philosophy behind the helper The function extracts each term and checks whether it is logarithmic w.r.t ``symbol``. """ rv = False for term in Add.make_args(f): saw_log = False for term_arg in Mul.make_args(term): if symbol not in term_arg.free_symbols: continue if isinstance(term_arg, log): if saw_log: return False # more than one log in term saw_log = True else: return False # dependent on symbol in non-log way if saw_log: rv = True return rv def _is_lambert(f, symbol): r""" If this returns ``False`` then the Lambert solver (``_solve_lambert``) will not be called. Explanation =========== Quick check for cases that the Lambert solver might be able to handle. 1. Equations containing more than two operands and `symbol`s involving any of `Pow`, `exp`, `HyperbolicFunction`,`TrigonometricFunction`, `log` terms. 2. In `Pow`, `exp` the exponent should have `symbol` whereas for `HyperbolicFunction`,`TrigonometricFunction`, `log` should contain `symbol`. 3. For `HyperbolicFunction`,`TrigonometricFunction` the number of trigonometric functions in equation should be less than number of symbols. (since `A*cos(x) + B*sin(x) - c` is not the Lambert type). Some forms of lambert equations are: 1. X**X = C 2. X*(B*log(X) + D)**A = C 3. A*log(B*X + A) + d*X = C 4. (B*X + A)*exp(d*X + g) = C 5. g*exp(B*X + h) - B*X = C 6. A*D**(E*X + g) - B*X = C 7. A*cos(X) + B*sin(X) - D*X = C 8. A*cosh(X) + B*sinh(X) - D*X = C Where X is any variable, A, B, C, D, E are any constants, g, h are linear functions or log terms. Parameters ========== f : Expr The equation to be checked symbol : Symbol The variable in which the equation is checked Returns ======= If this returns ``False`` then the Lambert solver (``_solve_lambert``) will not be called. Examples ======== >>> from sympy.solvers.solveset import _is_lambert >>> from sympy import symbols, cosh, sinh, log >>> x = symbols('x') >>> _is_lambert(3*log(x) - x*log(3), x) True >>> _is_lambert(log(log(x - 3)) + log(x-3), x) True >>> _is_lambert(cosh(x) - sinh(x), x) False >>> _is_lambert((x**2 - 2*x + 1).subs(x, (log(x) + 3*x)**2 - 1), x) True See Also ======== _solve_lambert """ term_factors = list(_term_factors(f.expand())) # total number of symbols in equation no_of_symbols = len([arg for arg in term_factors if arg.has(symbol)]) # total number of trigonometric terms in equation no_of_trig = len([arg for arg in term_factors \ if arg.has(HyperbolicFunction, TrigonometricFunction)]) if f.is_Add and no_of_symbols >= 2: # `log`, `HyperbolicFunction`, `TrigonometricFunction` should have symbols # and no_of_trig < no_of_symbols lambert_funcs = (log, HyperbolicFunction, TrigonometricFunction) if any(isinstance(arg, lambert_funcs)\ for arg in term_factors if arg.has(symbol)): if no_of_trig < no_of_symbols: return True # here, `Pow`, `exp` exponent should have symbols elif any(isinstance(arg, (Pow, exp)) \ for arg in term_factors if (arg.as_base_exp()[1]).has(symbol)): return True return False def _transolve(f, symbol, domain): r""" Function to solve transcendental equations. It is a helper to ``solveset`` and should be used internally. ``_transolve`` currently supports the following class of equations: - Exponential equations - Logarithmic equations Parameters ========== f : Any transcendental equation that needs to be solved. This needs to be an expression, which is assumed to be equal to ``0``. symbol : The variable for which the equation is solved. This needs to be of class ``Symbol``. domain : A set over which the equation is solved. This needs to be of class ``Set``. Returns ======= Set A set of values for ``symbol`` for which ``f`` is equal to zero. An ``EmptySet`` is returned if ``f`` does not have solutions in respective domain. A ``ConditionSet`` is returned as unsolved object if algorithms to evaluate complete solution are not yet implemented. How to use ``_transolve`` ========================= ``_transolve`` should not be used as an independent function, because it assumes that the equation (``f``) and the ``symbol`` comes from ``solveset`` and might have undergone a few modification(s). To use ``_transolve`` as an independent function the equation (``f``) and the ``symbol`` should be passed as they would have been by ``solveset``. Examples ======== >>> from sympy.solvers.solveset import _transolve as transolve >>> from sympy.solvers.solvers import _tsolve as tsolve >>> from sympy import symbols, S, pprint >>> x = symbols('x', real=True) # assumption added >>> transolve(5**(x - 3) - 3**(2*x + 1), x, S.Reals) {-(log(3) + 3*log(5))/(-log(5) + 2*log(3))} How ``_transolve`` works ======================== ``_transolve`` uses two types of helper functions to solve equations of a particular class: Identifying helpers: To determine whether a given equation belongs to a certain class of equation or not. Returns either ``True`` or ``False``. Solving helpers: Once an equation is identified, a corresponding helper either solves the equation or returns a form of the equation that ``solveset`` might better be able to handle. * Philosophy behind the module The purpose of ``_transolve`` is to take equations which are not already polynomial in their generator(s) and to either recast them as such through a valid transformation or to solve them outright. A pair of helper functions for each class of supported transcendental functions are employed for this purpose. One identifies the transcendental form of an equation and the other either solves it or recasts it into a tractable form that can be solved by ``solveset``. For example, an equation in the form `ab^{f(x)} - cd^{g(x)} = 0` can be transformed to `\log(a) + f(x)\log(b) - \log(c) - g(x)\log(d) = 0` (under certain assumptions) and this can be solved with ``solveset`` if `f(x)` and `g(x)` are in polynomial form. How ``_transolve`` is better than ``_tsolve`` ============================================= 1) Better output ``_transolve`` provides expressions in a more simplified form. Consider a simple exponential equation >>> f = 3**(2*x) - 2**(x + 3) >>> pprint(transolve(f, x, S.Reals), use_unicode=False) -3*log(2) {------------------} -2*log(3) + log(2) >>> pprint(tsolve(f, x), use_unicode=False) / 3 \ | --------| | log(2/9)| [-log\2 /] 2) Extensible The API of ``_transolve`` is designed such that it is easily extensible, i.e. the code that solves a given class of equations is encapsulated in a helper and not mixed in with the code of ``_transolve`` itself. 3) Modular ``_transolve`` is designed to be modular i.e, for every class of equation a separate helper for identification and solving is implemented. This makes it easy to change or modify any of the method implemented directly in the helpers without interfering with the actual structure of the API. 4) Faster Computation Solving equation via ``_transolve`` is much faster as compared to ``_tsolve``. In ``solve``, attempts are made computing every possibility to get the solutions. This series of attempts makes solving a bit slow. In ``_transolve``, computation begins only after a particular type of equation is identified. How to add new class of equations ================================= Adding a new class of equation solver is a three-step procedure: - Identify the type of the equations Determine the type of the class of equations to which they belong: it could be of ``Add``, ``Pow``, etc. types. Separate internal functions are used for each type. Write identification and solving helpers and use them from within the routine for the given type of equation (after adding it, if necessary). Something like: .. code-block:: python def add_type(lhs, rhs, x): .... if _is_exponential(lhs, x): new_eq = _solve_exponential(lhs, rhs, x) .... rhs, lhs = eq.as_independent(x) if lhs.is_Add: result = add_type(lhs, rhs, x) - Define the identification helper. - Define the solving helper. Apart from this, a few other things needs to be taken care while adding an equation solver: - Naming conventions: Name of the identification helper should be as ``_is_class`` where class will be the name or abbreviation of the class of equation. The solving helper will be named as ``_solve_class``. For example: for exponential equations it becomes ``_is_exponential`` and ``_solve_expo``. - The identifying helpers should take two input parameters, the equation to be checked and the variable for which a solution is being sought, while solving helpers would require an additional domain parameter. - Be sure to consider corner cases. - Add tests for each helper. - Add a docstring to your helper that describes the method implemented. The documentation of the helpers should identify: - the purpose of the helper, - the method used to identify and solve the equation, - a proof of correctness - the return values of the helpers """ def add_type(lhs, rhs, symbol, domain): """ Helper for ``_transolve`` to handle equations of ``Add`` type, i.e. equations taking the form as ``a*f(x) + b*g(x) + .... = c``. For example: 4**x + 8**x = 0 """ result = ConditionSet(symbol, Eq(lhs - rhs, 0), domain) # check if it is exponential type equation if _is_exponential(lhs, symbol): result = _solve_exponential(lhs, rhs, symbol, domain) # check if it is logarithmic type equation elif _is_logarithmic(lhs, symbol): result = _solve_logarithm(lhs, rhs, symbol, domain) return result result = ConditionSet(symbol, Eq(f, 0), domain) # invert_complex handles the call to the desired inverter based # on the domain specified. lhs, rhs_s = invert_complex(f, 0, symbol, domain) if isinstance(rhs_s, FiniteSet): assert (len(rhs_s.args)) == 1 rhs = rhs_s.args[0] if lhs.is_Add: result = add_type(lhs, rhs, symbol, domain) else: result = rhs_s return result def solveset(f, symbol=None, domain=S.Complexes): r"""Solves a given inequality or equation with set as output Parameters ========== f : Expr or a relational. The target equation or inequality symbol : Symbol The variable for which the equation is solved domain : Set The domain over which the equation is solved Returns ======= Set A set of values for `symbol` for which `f` is True or is equal to zero. An :class:`~.EmptySet` is returned if `f` is False or nonzero. A :class:`~.ConditionSet` is returned as unsolved object if algorithms to evaluate complete solution are not yet implemented. ``solveset`` claims to be complete in the solution set that it returns. Raises ====== NotImplementedError The algorithms to solve inequalities in complex domain are not yet implemented. ValueError The input is not valid. RuntimeError It is a bug, please report to the github issue tracker. Notes ===== Python interprets 0 and 1 as False and True, respectively, but in this function they refer to solutions of an expression. So 0 and 1 return the domain and EmptySet, respectively, while True and False return the opposite (as they are assumed to be solutions of relational expressions). See Also ======== solveset_real: solver for real domain solveset_complex: solver for complex domain Examples ======== >>> from sympy import exp, sin, Symbol, pprint, S, Eq >>> from sympy.solvers.solveset import solveset, solveset_real * The default domain is complex. Not specifying a domain will lead to the solving of the equation in the complex domain (and this is not affected by the assumptions on the symbol): >>> x = Symbol('x') >>> pprint(solveset(exp(x) - 1, x), use_unicode=False) {2*n*I*pi | n in Integers} >>> x = Symbol('x', real=True) >>> pprint(solveset(exp(x) - 1, x), use_unicode=False) {2*n*I*pi | n in Integers} * If you want to use ``solveset`` to solve the equation in the real domain, provide a real domain. (Using ``solveset_real`` does this automatically.) >>> R = S.Reals >>> x = Symbol('x') >>> solveset(exp(x) - 1, x, R) {0} >>> solveset_real(exp(x) - 1, x) {0} The solution is unaffected by assumptions on the symbol: >>> p = Symbol('p', positive=True) >>> pprint(solveset(p**2 - 4)) {-2, 2} When a :class:`~.ConditionSet` is returned, symbols with assumptions that would alter the set are replaced with more generic symbols: >>> i = Symbol('i', imaginary=True) >>> solveset(Eq(i**2 + i*sin(i), 1), i, domain=S.Reals) ConditionSet(_R, Eq(_R**2 + _R*sin(_R) - 1, 0), Reals) * Inequalities can be solved over the real domain only. Use of a complex domain leads to a NotImplementedError. >>> solveset(exp(x) > 1, x, R) Interval.open(0, oo) """ f = sympify(f) symbol = sympify(symbol) if f is S.true: return domain if f is S.false: return S.EmptySet if not isinstance(f, (Expr, Relational, Number)): raise ValueError("%s is not a valid SymPy expression" % f) if not isinstance(symbol, (Expr, Relational)) and symbol is not None: raise ValueError("%s is not a valid SymPy symbol" % (symbol,)) if not isinstance(domain, Set): raise ValueError("%s is not a valid domain" %(domain)) free_symbols = f.free_symbols if f.has(Piecewise): f = piecewise_fold(f) if symbol is None and not free_symbols: b = Eq(f, 0) if b is S.true: return domain elif b is S.false: return S.EmptySet else: raise NotImplementedError(filldedent(''' relationship between value and 0 is unknown: %s''' % b)) if symbol is None: if len(free_symbols) == 1: symbol = free_symbols.pop() elif free_symbols: raise ValueError(filldedent(''' The independent variable must be specified for a multivariate equation.''')) elif not isinstance(symbol, Symbol): f, s, swap = recast_to_symbols([f], [symbol]) # the xreplace will be needed if a ConditionSet is returned return solveset(f[0], s[0], domain).xreplace(swap) # solveset should ignore assumptions on symbols if symbol not in _rc: x = _rc[0] if domain.is_subset(S.Reals) else _rc[1] rv = solveset(f.xreplace({symbol: x}), x, domain) # try to use the original symbol if possible try: _rv = rv.xreplace({x: symbol}) except TypeError: _rv = rv if rv.dummy_eq(_rv): rv = _rv return rv # Abs has its own handling method which avoids the # rewriting property that the first piece of abs(x) # is for x >= 0 and the 2nd piece for x < 0 -- solutions # can look better if the 2nd condition is x <= 0. Since # the solution is a set, duplication of results is not # an issue, e.g. {y, -y} when y is 0 will be {0} f, mask = _masked(f, Abs) f = f.rewrite(Piecewise) # everything that's not an Abs for d, e in mask: # everything *in* an Abs e = e.func(e.args[0].rewrite(Piecewise)) f = f.xreplace({d: e}) f = piecewise_fold(f) return _solveset(f, symbol, domain, _check=True) def solveset_real(f, symbol): return solveset(f, symbol, S.Reals) def solveset_complex(f, symbol): return solveset(f, symbol, S.Complexes) def _solveset_multi(eqs, syms, domains): '''Basic implementation of a multivariate solveset. For internal use (not ready for public consumption)''' rep = {} for sym, dom in zip(syms, domains): if dom is S.Reals: rep[sym] = Symbol(sym.name, real=True) eqs = [eq.subs(rep) for eq in eqs] syms = [sym.subs(rep) for sym in syms] syms = tuple(syms) if len(eqs) == 0: return ProductSet(*domains) if len(syms) == 1: sym = syms[0] domain = domains[0] solsets = [solveset(eq, sym, domain) for eq in eqs] solset = Intersection(*solsets) return ImageSet(Lambda((sym,), (sym,)), solset).doit() eqs = sorted(eqs, key=lambda eq: len(eq.free_symbols & set(syms))) for n, eq in enumerate(eqs): sols = [] all_handled = True for sym in syms: if sym not in eq.free_symbols: continue sol = solveset(eq, sym, domains[syms.index(sym)]) if isinstance(sol, FiniteSet): i = syms.index(sym) symsp = syms[:i] + syms[i+1:] domainsp = domains[:i] + domains[i+1:] eqsp = eqs[:n] + eqs[n+1:] for s in sol: eqsp_sub = [eq.subs(sym, s) for eq in eqsp] sol_others = _solveset_multi(eqsp_sub, symsp, domainsp) fun = Lambda((symsp,), symsp[:i] + (s,) + symsp[i:]) sols.append(ImageSet(fun, sol_others).doit()) else: all_handled = False if all_handled: return Union(*sols) def solvify(f, symbol, domain): """Solves an equation using solveset and returns the solution in accordance with the `solve` output API. Returns ======= We classify the output based on the type of solution returned by `solveset`. Solution | Output ---------------------------------------- FiniteSet | list ImageSet, | list (if `f` is periodic) Union | Union | list (with FiniteSet) EmptySet | empty list Others | None Raises ====== NotImplementedError A ConditionSet is the input. Examples ======== >>> from sympy.solvers.solveset import solvify >>> from sympy.abc import x >>> from sympy import S, tan, sin, exp >>> solvify(x**2 - 9, x, S.Reals) [-3, 3] >>> solvify(sin(x) - 1, x, S.Reals) [pi/2] >>> solvify(tan(x), x, S.Reals) [0] >>> solvify(exp(x) - 1, x, S.Complexes) >>> solvify(exp(x) - 1, x, S.Reals) [0] """ solution_set = solveset(f, symbol, domain) result = None if solution_set is S.EmptySet: result = [] elif isinstance(solution_set, ConditionSet): raise NotImplementedError('solveset is unable to solve this equation.') elif isinstance(solution_set, FiniteSet): result = list(solution_set) else: period = periodicity(f, symbol) if period is not None: solutions = S.EmptySet iter_solutions = () if isinstance(solution_set, ImageSet): iter_solutions = (solution_set,) elif isinstance(solution_set, Union): if all(isinstance(i, ImageSet) for i in solution_set.args): iter_solutions = solution_set.args for solution in iter_solutions: solutions += solution.intersect(Interval(0, period, False, True)) if isinstance(solutions, FiniteSet): result = list(solutions) else: solution = solution_set.intersect(domain) if isinstance(solution, Union): # concerned about only FiniteSet with Union but not about ImageSet # if required could be extend if any(isinstance(i, FiniteSet) for i in solution.args): result = [sol for soln in solution.args \ for sol in soln.args if isinstance(soln,FiniteSet)] else: return None elif isinstance(solution, FiniteSet): result += solution return result ############################################################################### ################################ LINSOLVE ##################################### ############################################################################### def linear_coeffs(eq, *syms, dict=False): """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 ValueError duplicate or unordered symbols are passed Parameters ========== dict - (default False) when True, return coefficients as a dictionary with coefficients keyed to syms that were present; key 1 gives the constant 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)] When nonlinear is detected, an error will be raised: * even if they would cancel after expansion (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 in given generators * when there are cross terms >>> linear_coeffs(x*(y + 1), x, y) Traceback (most recent call last): ... NonlinearError: symbol-dependent cross-terms encountered * when there are terms that contain an expression dependent on the symbols that is not linear >>> linear_coeffs(x**2, x) Traceback (most recent call last): ... NonlinearError: nonlinear in given generators """ eq = _sympify(eq) if len(syms) == 1 and iterable(syms[0]) and not isinstance(syms[0], Basic): raise ValueError('expecting unpacked symbols, *syms') symset = set(syms) if len(symset) != len(syms): raise ValueError('duplicate symbols given') try: d, c = _linear_eq_to_dict([eq], symset) d = d[0] c = c[0] except PolyNonlinearError as err: raise NonlinearError(str(err)) if dict: if c: d[S.One] = c return d rv = [S.Zero]*(len(syms) + 1) rv[-1] = c for i, k in enumerate(syms): if k not in d: continue rv[i] = d[k] return rv def linear_eq_to_matrix(equations, *symbols): r""" Converts a given System of Equations into Matrix form. Here `equations` must be a linear system of equations in `symbols`. Element ``M[i, j]`` corresponds to the coefficient of the jth symbol in the ith equation. The Matrix form corresponds to the augmented matrix form. For example: .. math:: 4x + 2y + 3z = 1 .. math:: 3x + y + z = -6 .. math:: 2x + 4y + 9z = 2 This system will return $A$ and $b$ as: $$ A = \left[\begin{array}{ccc} 4 & 2 & 3 \\ 3 & 1 & 1 \\ 2 & 4 & 9 \end{array}\right] \ \ b = \left[\begin{array}{c} 1 \\ -6 \\ 2 \end{array}\right] $$ The only simplification performed is to convert ``Eq(a, b)`` $\Rightarrow a - b$. Raises ====== NonlinearError The equations contain a nonlinear term. ValueError The symbols are not given or are not unique. Examples ======== >>> from sympy import linear_eq_to_matrix, symbols >>> c, x, y, z = symbols('c, x, y, z') The coefficients (numerical or symbolic) of the symbols will be returned as matrices: >>> eqns = [c*x + z - 1 - c, y + z, x - y] >>> A, b = linear_eq_to_matrix(eqns, [x, y, z]) >>> A Matrix([ [c, 0, 1], [0, 1, 1], [1, -1, 0]]) >>> b Matrix([ [c + 1], [ 0], [ 0]]) This routine does not simplify expressions and will raise an error if nonlinearity is encountered: >>> eqns = [ ... (x**2 - 3*x)/(x - 3) - 3, ... y**2 - 3*y - y*(y - 4) + x - 4] >>> linear_eq_to_matrix(eqns, [x, y]) Traceback (most recent call last): ... NonlinearError: symbol-dependent term can be ignored using `strict=False` Simplifying these equations will discard the removable singularity in the first and 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] 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. ''')) # construct the dictionaries try: eq, c = _linear_eq_to_dict(equations, symbols) except PolyNonlinearError as err: raise NonlinearError(str(err)) # prepare output matrices n, m = shape = len(eq), len(symbols) ix = dict(zip(symbols, range(m))) A = zeros(*shape) for row, d in enumerate(eq): for k in d: col = ix[k] A[row, col] = d[k] b = Matrix(n, 1, [-i for i in c]) return A, b def linsolve(system, *symbols): r""" Solve system of $N$ linear equations with $M$ variables; both underdetermined and overdetermined systems are supported. The possible number of solutions is zero, one or infinite. Zero solutions throws a ValueError, whereas infinite solutions are represented parametrically in terms of the given symbols. For unique solution a :class:`~.FiniteSet` of ordered tuples is returned. All standard input formats are supported: For the given set of equations, the respective input types are given below: .. math:: 3x + 2y - z = 1 .. math:: 2x - 2y + 4z = -2 .. math:: 2x - y + 2z = 0 * Augmented matrix form, ``system`` given below: $$ \text{system} = \left[{array}{cccc} 3 & 2 & -1 & 1\\ 2 & -2 & 4 & -2\\ 2 & -1 & 2 & 0 \end{array}\right] $$ :: system = Matrix([[3, 2, -1, 1], [2, -2, 4, -2], [2, -1, 2, 0]]) * List of equations form :: system = [3x + 2y - z - 1, 2x - 2y + 4z + 2, 2x - y + 2z] * Input $A$ and $b$ in matrix form (from $Ax = b$) are given as: $$ A = \left[\begin{array}{ccc} 3 & 2 & -1 \\ 2 & -2 & 4 \\ 2 & -1 & 2 \end{array}\right] \ \ b = \left[\begin{array}{c} 1 \\ -2 \\ 0 \end{array}\right] $$ :: A = Matrix([[3, 2, -1], [2, -2, 4], [2, -1, 2]]) b = Matrix([[1], [-2], [0]]) system = (A, b) Symbols can always be passed but are actually only needed when 1) a system of equations is being passed and 2) the system is passed as an underdetermined matrix and one wants to control the name of the free variables in the result. An error is raised if no symbols are used for case 1, but if no symbols are provided for case 2, internally generated symbols will be provided. When providing symbols for case 2, there should be at least as many symbols are there are columns in matrix A. The algorithm used here is Gauss-Jordan elimination, which results, after elimination, in a row echelon form matrix. Returns ======= A FiniteSet containing an ordered tuple of values for the unknowns for which the `system` has a solution. (Wrapping the tuple in FiniteSet is used to maintain a consistent output format throughout solveset.) Returns EmptySet, if the linear system is inconsistent. Raises ====== ValueError The input is not valid. The symbols are not given. Examples ======== >>> from sympy import Matrix, linsolve, symbols >>> x, y, z = symbols("x, y, z") >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]]) >>> b = Matrix([3, 6, 9]) >>> A Matrix([ [1, 2, 3], [4, 5, 6], [7, 8, 10]]) >>> b Matrix([ [3], [6], [9]]) >>> linsolve((A, b), [x, y, z]) {(-1, 2, 0)} * Parametric Solution: In case the system is underdetermined, the function will return a parametric solution in terms of the given symbols. Those that are free will be returned unchanged. e.g. in the system below, `z` is returned as the solution for variable z; it can take on any value. >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> b = Matrix([3, 6, 9]) >>> linsolve((A, b), x, y, z) {(z - 1, 2 - 2*z, z)} If no symbols are given, internally generated symbols will be used. The ``tau0`` in the third position indicates (as before) that the third variable -- whatever it is named -- can take on any value: >>> linsolve((A, b)) {(tau0 - 1, 2 - 2*tau0, tau0)} * List of equations as input >>> Eqns = [3*x + 2*y - z - 1, 2*x - 2*y + 4*z + 2, - x + y/2 - z] >>> linsolve(Eqns, x, y, z) {(1, -2, -2)} * Augmented matrix as input >>> aug = Matrix([[2, 1, 3, 1], [2, 6, 8, 3], [6, 8, 18, 5]]) >>> aug Matrix([ [2, 1, 3, 1], [2, 6, 8, 3], [6, 8, 18, 5]]) >>> linsolve(aug, x, y, z) {(3/10, 2/5, 0)} * Solve for symbolic coefficients >>> a, b, c, d, e, f = symbols('a, b, c, d, e, f') >>> eqns = [a*x + b*y - c, d*x + e*y - f] >>> linsolve(eqns, x, y) {((-b*f + c*e)/(a*e - b*d), (a*f - c*d)/(a*e - b*d))} * A degenerate system returns solution as set of given symbols. >>> system = Matrix(([0, 0, 0], [0, 0, 0], [0, 0, 0])) >>> linsolve(system, x, y) {(x, y)} * For an empty system linsolve returns empty set >>> linsolve([], x) EmptySet * An error is raised if any nonlinearity is detected, even if it could be removed with expansion >>> linsolve([x*(1/x - 1)], x) Traceback (most recent call last): ... NonlinearError: nonlinear term: 1/x >>> linsolve([x*(y + 1)], x, y) Traceback (most recent call last): ... NonlinearError: nonlinear cross-term: x*(y + 1) >>> linsolve([x**2 - 1], x) Traceback (most recent call last): ... NonlinearError: nonlinear term: 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) dup_msg = 'duplicate symbols given' b = None # if we don't get b the input was bad # unpack system if hasattr(system, '__iter__'): # 1). (A, b) if len(system) == 2 and isinstance(system[0], MatrixBase): A, b = system # 2). (eq1, eq2, ...) if not isinstance(system[0], MatrixBase): if sym_gen or not symbols: raise ValueError(filldedent(''' When passing a system of equations, the explicit symbols for which a solution is being sought must be given as a sequence, too. ''')) if len(set(symbols)) != len(symbols): raise ValueError(dup_msg) # # Pass to the sparse solver implemented in polys. It is important # that we do not attempt to convert the equations to a matrix # because that would be very inefficient for large sparse systems # of equations. # eqs = system eqs = [sympify(eq) for eq in eqs] try: sol = _linsolve(eqs, symbols) except PolyNonlinearError as exc: # e.g. cos(x) contains an element of the set of generators raise NonlinearError(str(exc)) if sol is None: return S.EmptySet sol = FiniteSet(Tuple(*(sol.get(sym, sym) for sym in symbols))) return sol elif isinstance(system, MatrixBase) and not ( symbols and not isinstance(symbols, GeneratorType) and isinstance(symbols[0], MatrixBase)): # 3). A augmented with b A, b = system[:, :-1], system[:, -1:] if b is None: raise ValueError("Invalid arguments") if sym_gen: symbols = [next(symbols) for i in range(A.cols)] symset = set(symbols) if any(symset & (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'))) elif len(symset) != len(symbols): raise ValueError(dup_msg) if not symbols: symbols = [Dummy() for _ in range(A.cols)] name = _uniquely_named_symbol('tau', (A, b), compare=lambda i: str(i).rstrip('1234567890')).name gen = numbered_symbols(name) else: gen = None # This is just a wrapper for solve_lin_sys eqs = [] rows = A.tolist() for rowi, bi in zip(rows, b): terms = [elem * sym for elem, sym in zip(rowi, symbols) if elem] terms.append(-bi) eqs.append(Add(*terms)) eqs, ring = sympy_eqs_to_ring(eqs, symbols) sol = solve_lin_sys(eqs, ring, _raw=False) if sol is None: return S.EmptySet #sol = {sym:val for sym, val in sol.items() if sym != val} sol = FiniteSet(Tuple(*(sol.get(sym, sym) for sym in symbols))) if gen is not None: solsym = sol.free_symbols rep = {sym: next(gen) for sym in symbols if sym in solsym} sol = sol.subs(rep) return sol ############################################################################## # ------------------------------nonlinsolve ---------------------------------# ############################################################################## def _return_conditionset(eqs, symbols): # return conditionset eqs = (Eq(lhs, 0) for lhs in eqs) condition_set = ConditionSet( Tuple(*symbols), And(*eqs), S.Complexes**len(symbols)) return condition_set def substitution(system, symbols, result=[{}], known_symbols=[], exclude=[], all_symbols=None): r""" Solves the `system` using substitution method. It is used in :func:`~.nonlinsolve`. This will be called from :func:`~.nonlinsolve` when any equation(s) is non polynomial equation. Parameters ========== system : list of equations The target system of equations symbols : list of symbols to be solved. The variable(s) for which the system is solved known_symbols : list of solved symbols Values are known for these variable(s) result : An empty list or list of dict If No symbol values is known then empty list otherwise symbol as keys and corresponding value in dict. exclude : Set of expression. Mostly denominator expression(s) of the equations of the system. Final solution should not satisfy these expressions. all_symbols : known_symbols + symbols(unsolved). Returns ======= A FiniteSet of ordered tuple of values of `all_symbols` for which the `system` has solution. Order of values in the tuple is same as symbols present in the parameter `all_symbols`. If parameter `all_symbols` is None then same as symbols present in the parameter `symbols`. Please note that general FiniteSet is unordered, the solution returned here is not simply a FiniteSet of solutions, rather it is a FiniteSet of ordered tuple, i.e. the first & only argument to FiniteSet is a tuple of solutions, which is ordered, & hence the returned solution is ordered. Also note that solution could also have been returned as an ordered tuple, FiniteSet is just a wrapper `{}` around the tuple. It has no other significance except for the fact it is just used to maintain a consistent output format throughout the solveset. Raises ====== ValueError The input is not valid. The symbols are not given. AttributeError The input symbols are not :class:`~.Symbol` type. Examples ======== >>> from sympy import symbols, substitution >>> x, y = symbols('x, y', real=True) >>> substitution([x + y], [x], [{y: 1}], [y], set([]), [x, y]) {(-1, 1)} * When you want a soln not satisfying $x + 1 = 0$ >>> substitution([x + y], [x], [{y: 1}], [y], set([x + 1]), [y, x]) EmptySet >>> substitution([x + y], [x], [{y: 1}], [y], set([x - 1]), [y, x]) {(1, -1)} >>> substitution([x + y - 1, y - x**2 + 5], [x, y]) {(-3, 4), (2, -1)} * Returns both real and complex solution >>> x, y, z = symbols('x, y, z') >>> from sympy import exp, sin >>> substitution([exp(x) - sin(y), y**2 - 4], [x, y]) {(ImageSet(Lambda(_n, I*(2*_n*pi + pi) + log(sin(2))), Integers), -2), (ImageSet(Lambda(_n, 2*_n*I*pi + log(sin(2))), Integers), 2)} >>> eqs = [z**2 + exp(2*x) - sin(y), -3 + exp(-y)] >>> substitution(eqs, [y, z]) {(-log(3), -sqrt(-exp(2*x) - sin(log(3)))), (-log(3), sqrt(-exp(2*x) - sin(log(3)))), (ImageSet(Lambda(_n, 2*_n*I*pi - log(3)), Integers), ImageSet(Lambda(_n, -sqrt(-exp(2*x) + sin(2*_n*I*pi - log(3)))), Integers)), (ImageSet(Lambda(_n, 2*_n*I*pi - log(3)), Integers), ImageSet(Lambda(_n, sqrt(-exp(2*x) + sin(2*_n*I*pi - log(3)))), Integers))} """ if not system: return S.EmptySet if not symbols: msg = ('Symbols must be given, for which solution of the ' 'system is to be found.') raise ValueError(filldedent(msg)) if not is_sequence(symbols): msg = ('symbols should be given as a sequence, e.g. a list.' 'Not type %s: %s') raise TypeError(filldedent(msg % (type(symbols), symbols))) if not getattr(symbols[0], 'is_Symbol', False): msg = ('Iterable of symbols must be given as ' 'second argument, not type %s: %s') raise ValueError(filldedent(msg % (type(symbols[0]), symbols[0]))) # By default `all_symbols` will be same as `symbols` if all_symbols is None: all_symbols = symbols old_result = result # storing complements and intersection for particular symbol complements = {} intersections = {} # when total_solveset_call equals total_conditionset # it means that solveset failed to solve all eqs. total_conditionset = -1 total_solveset_call = -1 def _unsolved_syms(eq, sort=False): """Returns the unsolved symbol present in the equation `eq`. """ free = eq.free_symbols unsolved = (free - set(known_symbols)) & set(all_symbols) if sort: unsolved = list(unsolved) unsolved.sort(key=default_sort_key) return unsolved # end of _unsolved_syms() # sort such that equation with the fewest potential symbols is first. # means eq with less number of variable first in the list. eqs_in_better_order = list( ordered(system, lambda _: len(_unsolved_syms(_)))) def add_intersection_complement(result, intersection_dict, complement_dict): # If solveset has returned some intersection/complement # for any symbol, it will be added in the final solution. final_result = [] for res in result: res_copy = res for key_res, value_res in res.items(): intersect_set, complement_set = None, None for key_sym, value_sym in intersection_dict.items(): if key_sym == key_res: intersect_set = value_sym for key_sym, value_sym in complement_dict.items(): if key_sym == key_res: complement_set = value_sym if intersect_set or complement_set: new_value = FiniteSet(value_res) if intersect_set and intersect_set != S.Complexes: new_value = Intersection(new_value, intersect_set) if complement_set: new_value = Complement(new_value, complement_set) if new_value is S.EmptySet: res_copy = None break elif new_value.is_FiniteSet and len(new_value) == 1: res_copy[key_res] = set(new_value).pop() else: res_copy[key_res] = new_value if res_copy is not None: final_result.append(res_copy) return final_result # end of def add_intersection_complement() def _extract_main_soln(sym, sol, soln_imageset): """Separate the Complements, Intersections, ImageSet lambda expr and its base_set. This function returns the unmasks sol from different classes of sets and also returns the appended ImageSet elements in a soln_imageset (dict: where key as unmasked element and value as ImageSet). """ # if there is union, then need to check # Complement, Intersection, Imageset. # Order should not be changed. if isinstance(sol, ConditionSet): # extracts any solution in ConditionSet sol = sol.base_set if isinstance(sol, Complement): # extract solution and complement complements[sym] = sol.args[1] sol = sol.args[0] # complement will be added at the end # using `add_intersection_complement` method # if there is union of Imageset or other in soln. # no testcase is written for this if block if isinstance(sol, Union): sol_args = sol.args sol = S.EmptySet # We need in sequence so append finteset elements # and then imageset or other. for sol_arg2 in sol_args: if isinstance(sol_arg2, FiniteSet): sol += sol_arg2 else: # ImageSet, Intersection, complement then # append them directly sol += FiniteSet(sol_arg2) if isinstance(sol, Intersection): # Interval/Set will be at 0th index always if sol.args[0] not in (S.Reals, S.Complexes): # Sometimes solveset returns soln with intersection # S.Reals or S.Complexes. We don't consider that # intersection. intersections[sym] = sol.args[0] sol = sol.args[1] # after intersection and complement Imageset should # be checked. if isinstance(sol, ImageSet): soln_imagest = sol expr2 = sol.lamda.expr sol = FiniteSet(expr2) soln_imageset[expr2] = soln_imagest if not isinstance(sol, FiniteSet): sol = FiniteSet(sol) return sol, soln_imageset # end of def _extract_main_soln() # helper function for _append_new_soln def _check_exclude(rnew, imgset_yes): rnew_ = rnew if imgset_yes: # replace all dummy variables (Imageset lambda variables) # with zero before `checksol`. Considering fundamental soln # for `checksol`. rnew_copy = rnew.copy() dummy_n = imgset_yes[0] for key_res, value_res in rnew_copy.items(): rnew_copy[key_res] = value_res.subs(dummy_n, 0) rnew_ = rnew_copy # satisfy_exclude == true if it satisfies the expr of `exclude` list. try: # something like : `Mod(-log(3), 2*I*pi)` can't be # simplified right now, so `checksol` returns `TypeError`. # when this issue is fixed this try block should be # removed. Mod(-log(3), 2*I*pi) == -log(3) satisfy_exclude = any( checksol(d, rnew_) for d in exclude) except TypeError: satisfy_exclude = None return satisfy_exclude # end of def _check_exclude() # helper function for _append_new_soln def _restore_imgset(rnew, original_imageset, newresult): restore_sym = set(rnew.keys()) & \ set(original_imageset.keys()) for key_sym in restore_sym: img = original_imageset[key_sym] rnew[key_sym] = img if rnew not in newresult: newresult.append(rnew) # end of def _restore_imgset() def _append_eq(eq, result, res, delete_soln, n=None): u = Dummy('u') if n: eq = eq.subs(n, 0) satisfy = eq if eq in (True, False) else checksol(u, u, eq, minimal=True) if satisfy is False: delete_soln = True res = {} else: result.append(res) return result, res, delete_soln def _append_new_soln(rnew, sym, sol, imgset_yes, soln_imageset, original_imageset, newresult, eq=None): """If `rnew` (A dict <symbol: soln>) contains valid soln append it to `newresult` list. `imgset_yes` is (base, dummy_var) if there was imageset in previously calculated result(otherwise empty tuple). `original_imageset` is dict of imageset expr and imageset from this result. `soln_imageset` dict of imageset expr and imageset of new soln. """ satisfy_exclude = _check_exclude(rnew, imgset_yes) delete_soln = False # soln should not satisfy expr present in `exclude` list. if not satisfy_exclude: local_n = None # if it is imageset if imgset_yes: local_n = imgset_yes[0] base = imgset_yes[1] if sym and sol: # when `sym` and `sol` is `None` means no new # soln. In that case we will append rnew directly after # substituting original imagesets in rnew values if present # (second last line of this function using _restore_imgset) dummy_list = list(sol.atoms(Dummy)) # use one dummy `n` which is in # previous imageset local_n_list = [ local_n for i in range( 0, len(dummy_list))] dummy_zip = zip(dummy_list, local_n_list) lam = Lambda(local_n, sol.subs(dummy_zip)) rnew[sym] = ImageSet(lam, base) if eq is not None: newresult, rnew, delete_soln = _append_eq( eq, newresult, rnew, delete_soln, local_n) elif eq is not None: newresult, rnew, delete_soln = _append_eq( eq, newresult, rnew, delete_soln) elif sol in soln_imageset.keys(): rnew[sym] = soln_imageset[sol] # restore original imageset _restore_imgset(rnew, original_imageset, newresult) else: newresult.append(rnew) elif satisfy_exclude: delete_soln = True rnew = {} _restore_imgset(rnew, original_imageset, newresult) return newresult, delete_soln # end of def _append_new_soln() def _new_order_result(result, eq): # separate first, second priority. `res` that makes `eq` value equals # to zero, should be used first then other result(second priority). # If it is not done then we may miss some soln. first_priority = [] second_priority = [] for res in result: if not any(isinstance(val, ImageSet) for val in res.values()): if eq.subs(res) == 0: first_priority.append(res) else: second_priority.append(res) if first_priority or second_priority: return first_priority + second_priority return result def _solve_using_known_values(result, solver): """Solves the system using already known solution (result contains the dict <symbol: value>). solver is :func:`~.solveset_complex` or :func:`~.solveset_real`. """ # stores imageset <expr: imageset(Lambda(n, expr), base)>. soln_imageset = {} total_solvest_call = 0 total_conditionst = 0 # sort such that equation with the fewest potential symbols is first. # means eq with less variable first for index, eq in enumerate(eqs_in_better_order): newresult = [] original_imageset = {} # if imageset expr is used to solve other symbol imgset_yes = False result = _new_order_result(result, eq) for res in result: got_symbol = set() # symbols solved in one iteration # find the imageset and use its expr. for key_res, value_res in res.items(): if isinstance(value_res, ImageSet): res[key_res] = value_res.lamda.expr original_imageset[key_res] = value_res dummy_n = value_res.lamda.expr.atoms(Dummy).pop() (base,) = value_res.base_sets imgset_yes = (dummy_n, base) # update eq with everything that is known so far eq2 = eq.subs(res).expand() unsolved_syms = _unsolved_syms(eq2, sort=True) if not unsolved_syms: if res: newresult, delete_res = _append_new_soln( res, None, None, imgset_yes, soln_imageset, original_imageset, newresult, eq2) if delete_res: # `delete_res` is true, means substituting `res` in # eq2 doesn't return `zero` or deleting the `res` # (a soln) since it staisfies expr of `exclude` # list. result.remove(res) continue # skip as it's independent of desired symbols depen1, depen2 = (eq2.rewrite(Add)).as_independent(*unsolved_syms) if (depen1.has(Abs) or depen2.has(Abs)) and solver == solveset_complex: # Absolute values cannot be inverted in the # complex domain continue soln_imageset = {} for sym in unsolved_syms: not_solvable = False try: soln = solver(eq2, sym) total_solvest_call += 1 soln_new = S.EmptySet if isinstance(soln, Complement): # separate solution and complement complements[sym] = soln.args[1] soln = soln.args[0] # complement will be added at the end if isinstance(soln, Intersection): # Interval will be at 0th index always if soln.args[0] != Interval(-oo, oo): # sometimes solveset returns soln # with intersection S.Reals, to confirm that # soln is in domain=S.Reals intersections[sym] = soln.args[0] soln_new += soln.args[1] soln = soln_new if soln_new else soln if index > 0 and solver == solveset_real: # one symbol's real soln, another symbol may have # corresponding complex soln. if not isinstance(soln, (ImageSet, ConditionSet)): soln += solveset_complex(eq2, sym) # might give ValueError with Abs except (NotImplementedError, ValueError): # If solveset is not able to solve equation `eq2`. Next # time we may get soln using next equation `eq2` continue if isinstance(soln, ConditionSet): if soln.base_set in (S.Reals, S.Complexes): soln = S.EmptySet # don't do `continue` we may get soln # in terms of other symbol(s) not_solvable = True total_conditionst += 1 else: soln = soln.base_set if soln is not S.EmptySet: soln, soln_imageset = _extract_main_soln( sym, soln, soln_imageset) for sol in soln: # sol is not a `Union` since we checked it # before this loop sol, soln_imageset = _extract_main_soln( sym, sol, soln_imageset) sol = set(sol).pop() free = sol.free_symbols if got_symbol and any( ss in free for ss in got_symbol ): # sol depends on previously solved symbols # then continue continue rnew = res.copy() # put each solution in res and append the new result # in the new result list (solution for symbol `s`) # along with old results. for k, v in res.items(): if isinstance(v, Expr) and isinstance(sol, Expr): # if any unsolved symbol is present # Then subs known value rnew[k] = v.subs(sym, sol) # and add this new solution if sol in soln_imageset.keys(): # replace all lambda variables with 0. imgst = soln_imageset[sol] rnew[sym] = imgst.lamda( *[0 for i in range(0, len( imgst.lamda.variables))]) else: rnew[sym] = sol newresult, delete_res = _append_new_soln( rnew, sym, sol, imgset_yes, soln_imageset, original_imageset, newresult) if delete_res: # deleting the `res` (a soln) since it staisfies # eq of `exclude` list result.remove(res) # solution got for sym if not not_solvable: got_symbol.add(sym) # next time use this new soln if newresult: result = newresult return result, total_solvest_call, total_conditionst # end def _solve_using_know_values() new_result_real, solve_call1, cnd_call1 = _solve_using_known_values( old_result, solveset_real) new_result_complex, solve_call2, cnd_call2 = _solve_using_known_values( old_result, solveset_complex) # If total_solveset_call is equal to total_conditionset # then solveset failed to solve all of the equations. # In this case we return a ConditionSet here. total_conditionset += (cnd_call1 + cnd_call2) total_solveset_call += (solve_call1 + solve_call2) if total_conditionset == total_solveset_call and total_solveset_call != -1: return _return_conditionset(eqs_in_better_order, all_symbols) # don't keep duplicate solutions filtered_complex = [] for i in list(new_result_complex): for j in list(new_result_real): if i.keys() != j.keys(): continue if all(a.dummy_eq(b) for a, b in zip(i.values(), j.values()) \ if not (isinstance(a, int) and isinstance(b, int))): break else: filtered_complex.append(i) # overall result result = new_result_real + filtered_complex result_all_variables = [] result_infinite = [] for res in result: if not res: # means {None : None} continue # If length < len(all_symbols) means infinite soln. # Some or all the soln is dependent on 1 symbol. # eg. {x: y+2} then final soln {x: y+2, y: y} if len(res) < len(all_symbols): solved_symbols = res.keys() unsolved = list(filter( lambda x: x not in solved_symbols, all_symbols)) for unsolved_sym in unsolved: res[unsolved_sym] = unsolved_sym result_infinite.append(res) if res not in result_all_variables: result_all_variables.append(res) if result_infinite: # we have general soln # eg : [{x: -1, y : 1}, {x : -y, y: y}] then # return [{x : -y, y : y}] result_all_variables = result_infinite if intersections or complements: result_all_variables = add_intersection_complement( result_all_variables, intersections, complements) # convert to ordered tuple result = S.EmptySet for r in result_all_variables: temp = [r[symb] for symb in all_symbols] result += FiniteSet(tuple(temp)) return result # end of def substitution() def _solveset_work(system, symbols): soln = solveset(system[0], symbols[0]) if isinstance(soln, FiniteSet): _soln = FiniteSet(*[tuple((s,)) for s in soln]) return _soln else: return FiniteSet(tuple(FiniteSet(soln))) def _handle_positive_dimensional(polys, symbols, denominators): from sympy.polys.polytools import groebner # substitution method where new system is groebner basis of the system _symbols = list(symbols) _symbols.sort(key=default_sort_key) basis = groebner(polys, _symbols, polys=True) new_system = [] for poly_eq in basis: new_system.append(poly_eq.as_expr()) result = [{}] result = substitution( new_system, symbols, result, [], denominators) return result # end of def _handle_positive_dimensional() def _handle_zero_dimensional(polys, symbols, system): # solve 0 dimensional poly system using `solve_poly_system` result = solve_poly_system(polys, *symbols) # May be some extra soln is added because # we used `unrad` in `_separate_poly_nonpoly`, so # need to check and remove if it is not a soln. result_update = S.EmptySet for res in result: dict_sym_value = dict(list(zip(symbols, res))) if all(checksol(eq, dict_sym_value) for eq in system): result_update += FiniteSet(res) return result_update # end of def _handle_zero_dimensional() def _separate_poly_nonpoly(system, symbols): polys = [] polys_expr = [] nonpolys = [] # unrad_changed stores a list of expressions containing # radicals that were processed using unrad # this is useful if solutions need to be checked later. unrad_changed = [] denominators = set() poly = None for eq in system: # Store denom expressions that contain symbols denominators.update(_simple_dens(eq, symbols)) # Convert equality to expression if isinstance(eq, Equality): eq = eq.rewrite(Add) # try to remove sqrt and rational power without_radicals = unrad(simplify(eq), *symbols) if without_radicals: unrad_changed.append(eq) 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, unrad_changed # end of def _separate_poly_nonpoly() def _handle_poly(polys, symbols): # _handle_poly(polys, symbols) -> (poly_sol, poly_eqs) # # We will return possible solution information to nonlinsolve as well as a # new system of polynomial equations to be solved if we cannot solve # everything directly here. The new system of polynomial equations will be # a lex-order Groebner basis for the original system. The lex basis # hopefully separate some of the variables and equations and give something # easier for substitution to work with. # The format for representing solution sets in nonlinsolve and substitution # is a list of dicts. These are the special cases: no_information = [{}] # No equations solved yet no_solutions = [] # The system is inconsistent and has no solutions. # If there is no need to attempt further solution of these equations then # we return no equations: no_equations = [] inexact = any(not p.domain.is_Exact for p in polys) if inexact: # The use of Groebner over RR is likely to result incorrectly in an # inconsistent Groebner basis. So, convert any float coefficients to # Rational before computing the Groebner basis. polys = [poly(nsimplify(p, rational=True)) for p in polys] # Compute a Groebner basis in grevlex order wrt the ordering given. We will # try to convert this to lex order later. Usually it seems to be more # efficient to compute a lex order basis by computing a grevlex basis and # converting to lex with fglm. basis = groebner(polys, symbols, order='grevlex', polys=False) # # No solutions (inconsistent equations)? # if 1 in basis: # No solutions: poly_sol = no_solutions poly_eqs = no_equations # # Finite number of solutions (zero-dimensional case) # elif basis.is_zero_dimensional: # Convert Groebner basis to lex ordering basis = basis.fglm('lex') # Convert polynomial coefficients back to float before calling # solve_poly_system if inexact: basis = [nfloat(p) for p in basis] # Solve the zero-dimensional case using solve_poly_system if possible. # If some polynomials have factors that cannot be solved in radicals # then this will fail. Using solve_poly_system(..., strict=True) # ensures that we either get a complete solution set in radicals or # UnsolvableFactorError will be raised. try: result = solve_poly_system(basis, *symbols, strict=True) except UnsolvableFactorError: # Failure... not fully solvable in radicals. Return the lex-order # basis for substitution to handle. poly_sol = no_information poly_eqs = list(basis) else: # Success! We have a finite solution set and solve_poly_system has # succeeded in finding all solutions. Return the solutions and also # an empty list of remaining equations to be solved. poly_sol = [dict(zip(symbols, res)) for res in result] poly_eqs = no_equations # # Infinite families of solutions (positive-dimensional case) # else: # In this case the grevlex basis cannot be converted to lex using the # fglm method and also solve_poly_system cannot solve the equations. We # would like to return a lex basis but since we can't use fglm we # compute the lex basis directly here. The time required to recompute # the basis is generally significantly less than the time required by # substitution to solve the new system. poly_sol = no_information poly_eqs = list(groebner(polys, symbols, order='lex', polys=False)) if inexact: poly_eqs = [nfloat(p) for p in poly_eqs] return poly_sol, poly_eqs def nonlinsolve(system, *symbols): r""" Solve system of $N$ nonlinear equations with $M$ variables, which means both under and overdetermined systems are supported. Positive dimensional system is also supported (A system with infinitely many solutions is said to be positive-dimensional). In a positive dimensional system the solution will be dependent on at least one symbol. Returns both real solution and complex solution (if they exist). Parameters ========== system : list of equations The target system of equations symbols : list of Symbols symbols should be given as a sequence eg. list Returns ======= A :class:`~.FiniteSet` of ordered tuple of values of `symbols` for which the `system` has solution. Order of values in the tuple is same as symbols present in the parameter `symbols`. Please note that general :class:`~.FiniteSet` is unordered, the solution returned here is not simply a :class:`~.FiniteSet` of solutions, rather it is a :class:`~.FiniteSet` of ordered tuple, i.e. the first and only argument to :class:`~.FiniteSet` is a tuple of solutions, which is ordered, and, hence ,the returned solution is ordered. Also note that solution could also have been returned as an ordered tuple, FiniteSet is just a wrapper ``{}`` around the tuple. It has no other significance except for the fact it is just used to maintain a consistent output format throughout the solveset. For the given set of equations, the respective input types are given below: .. math:: xy - 1 = 0 .. math:: 4x^2 + y^2 - 5 = 0 :: system = [x*y - 1, 4*x**2 + y**2 - 5] symbols = [x, y] Raises ====== ValueError The input is not valid. The symbols are not given. AttributeError The input symbols are not `Symbol` type. Examples ======== >>> from sympy import symbols, nonlinsolve >>> x, y, z = symbols('x, y, z', real=True) >>> nonlinsolve([x*y - 1, 4*x**2 + y**2 - 5], [x, y]) {(-1, -1), (-1/2, -2), (1/2, 2), (1, 1)} 1. Positive dimensional system and complements: >>> from sympy import pprint >>> from sympy.polys.polytools import is_zero_dimensional >>> a, b, c, d = symbols('a, b, c, d', extended_real=True) >>> eq1 = a + b + c + d >>> eq2 = a*b + b*c + c*d + d*a >>> eq3 = a*b*c + b*c*d + c*d*a + d*a*b >>> eq4 = a*b*c*d - 1 >>> system = [eq1, eq2, eq3, eq4] >>> is_zero_dimensional(system) False >>> pprint(nonlinsolve(system, [a, b, c, d]), use_unicode=False) -1 1 1 -1 {(---, -d, -, {d} \ {0}), (-, -d, ---, {d} \ {0})} d d d d >>> nonlinsolve([(x+y)**2 - 4, x + y - 2], [x, y]) {(2 - y, y)} 2. If some of the equations are non-polynomial then `nonlinsolve` will call the ``substitution`` function and return real and complex solutions, if present. >>> from sympy import exp, sin >>> nonlinsolve([exp(x) - sin(y), y**2 - 4], [x, y]) {(ImageSet(Lambda(_n, I*(2*_n*pi + pi) + log(sin(2))), Integers), -2), (ImageSet(Lambda(_n, 2*_n*I*pi + log(sin(2))), Integers), 2)} 3. If system is non-linear polynomial and zero-dimensional then it returns both solution (real and complex solutions, if present) using :func:`~.solve_poly_system`: >>> from sympy import sqrt >>> nonlinsolve([x**2 - 2*y**2 -2, x*y - 2], [x, y]) {(-2, -1), (2, 1), (-sqrt(2)*I, sqrt(2)*I), (sqrt(2)*I, -sqrt(2)*I)} 4. ``nonlinsolve`` can solve some linear (zero or positive dimensional) system (because it uses the :func:`sympy.polys.polytools.groebner` function to get the groebner basis and then uses the ``substitution`` function basis as the new `system`). But it is not recommended to solve linear system using ``nonlinsolve``, because :func:`~.linsolve` is better for general linear systems. >>> nonlinsolve([x + 2*y -z - 3, x - y - 4*z + 9, y + z - 4], [x, y, z]) {(3*z - 5, 4 - z, z)} 5. System having polynomial equations and only real solution is solved using :func:`~.solve_poly_system`: >>> e1 = sqrt(x**2 + y**2) - 10 >>> e2 = sqrt(y**2 + (-x + 10)**2) - 3 >>> nonlinsolve((e1, e2), (x, y)) {(191/20, -3*sqrt(391)/20), (191/20, 3*sqrt(391)/20)} >>> nonlinsolve([x**2 + 2/y - 2, x + y - 3], [x, y]) {(1, 2), (1 - sqrt(5), 2 + sqrt(5)), (1 + sqrt(5), 2 - sqrt(5))} >>> nonlinsolve([x**2 + 2/y - 2, x + y - 3], [y, x]) {(2, 1), (2 - sqrt(5), 1 + sqrt(5)), (2 + sqrt(5), 1 - sqrt(5))} 6. It is better to use symbols instead of trigonometric functions or :class:`~.Function`. For example, replace $\sin(x)$ with a symbol, replace $f(x)$ with a symbol and so on. Get a solution from ``nonlinsolve`` and then use :func:`~.solveset` to get the value of $x$. How nonlinsolve is better than old solver ``_solve_system`` : ============================================================= 1. A positive dimensional system solver: nonlinsolve can return solution for positive dimensional system. It finds the Groebner Basis of the positive dimensional system(calling it as basis) then we can start solving equation(having least number of variable first in the basis) using solveset and substituting that solved solutions into other equation(of basis) to get solution in terms of minimum variables. Here the important thing is how we are substituting the known values and in which equations. 2. Real and complex solutions: nonlinsolve returns both real and complex solution. If all the equations in the system are polynomial then using :func:`~.solve_poly_system` both real and complex solution is returned. If all the equations in the system are not polynomial equation then goes to ``substitution`` method with this polynomial and non polynomial equation(s), to solve for unsolved variables. Here to solve for particular variable solveset_real and solveset_complex is used. For both real and complex solution ``_solve_using_known_values`` is used inside ``substitution`` (``substitution`` will be called when any non-polynomial equation is present). If a solution is valid its general solution is added to the final result. 3. :class:`~.Complement` and :class:`~.Intersection` will be added: nonlinsolve maintains dict for complements and intersections. If solveset find complements or/and intersections with any interval or set during the execution of ``substitution`` function, then complement or/and intersection for that variable is added before returning final solution. """ 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)) symbols = list(map(_sympify, symbols)) 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, unrad_changed = \ _separate_poly_nonpoly(system, symbols) poly_eqs = [] poly_sol = [{}] if polys: poly_sol, poly_eqs = _handle_poly(polys, symbols) if poly_sol and poly_sol[0]: poly_syms = set().union(*(eq.free_symbols for eq in polys)) unrad_syms = set().union(*(eq.free_symbols for eq in unrad_changed)) if unrad_syms == poly_syms and unrad_changed: # if all the symbols have been solved by _handle_poly # and unrad has been used then check solutions poly_sol = [sol for sol in poly_sol if checksol(unrad_changed, sol)] # Collect together the unsolved polynomials with the non-polynomial # equations. remaining = poly_eqs + nonpolys # to_tuple converts a solution dictionary to a tuple containing the # value for each symbol to_tuple = lambda sol: tuple(sol[s] for s in symbols) if not remaining: # If there is nothing left to solve then return the solution from # solve_poly_system directly. return FiniteSet(*map(to_tuple, poly_sol)) else: # Here we handle: # # 1. The Groebner basis if solve_poly_system failed. # 2. The Groebner basis in the positive-dimensional case. # 3. Any non-polynomial equations # # If solve_poly_system did succeed then we pass those solutions in as # preliminary results. subs_res = substitution(remaining, symbols, result=poly_sol, exclude=denominators) if not isinstance(subs_res, FiniteSet): return subs_res # check solutions produced by substitution. Currently, checking is done for # only those solutions which have non-Set variable values. if unrad_changed: result = [dict(zip(symbols, sol)) for sol in subs_res.args] correct_sols = [sol for sol in result if any(isinstance(v, Set) for v in sol) or checksol(unrad_changed, sol) != False] return FiniteSet(*map(to_tuple, correct_sols)) else: return subs_res
490c3e5bc77954705f17cd4461515b71249552bb081c6f5af58cdb91468a22a7
"""Solvers of systems of polynomial equations. """ import itertools from sympy.core import S from sympy.core.sorting import default_sort_key from sympy.polys import Poly, groebner, roots from sympy.polys.polytools import parallel_poly_from_expr from sympy.polys.polyerrors import (ComputationFailed, PolificationFailed, CoercionFailed) from sympy.simplify import rcollect from sympy.utilities import postfixes from sympy.utilities.misc import filldedent class SolveFailed(Exception): """Raised when solver's conditions were not met. """ def solve_poly_system(seq, *gens, strict=False, **args): """ Return a list of solutions for the system of polynomial equations or else None. Parameters ========== seq: a list/tuple/set Listing all the equations that are needed to be solved gens: generators generators of the equations in seq for which we want the solutions strict: a boolean (default is False) if strict is True, NotImplementedError will be raised if the solution is known to be incomplete (which can occur if not all solutions are expressible in radicals) args: Keyword arguments Special options for solving the equations. Returns ======= List[Tuple] a list of tuples with elements being solutions for the symbols in the order they were passed as gens None None is returned when the computed basis contains only the ground. Examples ======== >>> from sympy import solve_poly_system >>> from sympy.abc import x, y >>> solve_poly_system([x*y - 2*y, 2*y**2 - x**2], x, y) [(0, 0), (2, -sqrt(2)), (2, sqrt(2))] >>> solve_poly_system([x**5 - x + y**3, y**2 - 1], x, y, strict=True) Traceback (most recent call last): ... UnsolvableFactorError """ try: polys, opt = parallel_poly_from_expr(seq, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('solve_poly_system', len(seq), exc) if len(polys) == len(opt.gens) == 2: f, g = polys if all(i <= 2 for i in f.degree_list() + g.degree_list()): try: return solve_biquadratic(f, g, opt) except SolveFailed: pass return solve_generic(polys, opt, strict=strict) def solve_biquadratic(f, g, opt): """Solve a system of two bivariate quadratic polynomial equations. Parameters ========== f: a single Expr or Poly First equation g: a single Expr or Poly Second Equation opt: an Options object For specifying keyword arguments and generators Returns ======= List[Tuple] a list of tuples with elements being solutions for the symbols in the order they were passed as gens None None is returned when the computed basis contains only the ground. Examples ======== >>> from sympy import Options, Poly >>> from sympy.abc import x, y >>> from sympy.solvers.polysys import solve_biquadratic >>> NewOption = Options((x, y), {'domain': 'ZZ'}) >>> a = Poly(y**2 - 4 + x, y, x, domain='ZZ') >>> b = Poly(y*2 + 3*x - 7, y, x, domain='ZZ') >>> solve_biquadratic(a, b, NewOption) [(1/3, 3), (41/27, 11/9)] >>> a = Poly(y + x**2 - 3, y, x, domain='ZZ') >>> b = Poly(-y + x - 4, y, x, domain='ZZ') >>> solve_biquadratic(a, b, NewOption) [(7/2 - sqrt(29)/2, -sqrt(29)/2 - 1/2), (sqrt(29)/2 + 7/2, -1/2 + \ sqrt(29)/2)] """ G = groebner([f, g]) if len(G) == 1 and G[0].is_ground: return None if len(G) != 2: raise SolveFailed x, y = opt.gens p, q = G if not p.gcd(q).is_ground: # not 0-dimensional raise SolveFailed p = Poly(p, x, expand=False) p_roots = [rcollect(expr, y) for expr in roots(p).keys()] q = q.ltrim(-1) q_roots = list(roots(q).keys()) solutions = [(p_root.subs(y, q_root), q_root) for q_root, p_root in itertools.product(q_roots, p_roots)] return sorted(solutions, key=default_sort_key) def solve_generic(polys, opt, strict=False): """ Solve a generic system of polynomial equations. Returns all possible solutions over C[x_1, x_2, ..., x_m] of a set F = { f_1, f_2, ..., f_n } of polynomial equations, using Groebner basis approach. For now only zero-dimensional systems are supported, which means F can have at most a finite number of solutions. If the basis contains only the ground, None is returned. The algorithm works by the fact that, supposing G is the basis of F with respect to an elimination order (here lexicographic order is used), G and F generate the same ideal, they have the same set of solutions. By the elimination property, if G is a reduced, zero-dimensional Groebner basis, then there exists an univariate polynomial in G (in its last variable). This can be solved by computing its roots. Substituting all computed roots for the last (eliminated) variable in other elements of G, new polynomial system is generated. Applying the above procedure recursively, a finite number of solutions can be found. The ability of finding all solutions by this procedure depends on the root finding algorithms. If no solutions were found, it means only that roots() failed, but the system is solvable. To overcome this difficulty use numerical algorithms instead. Parameters ========== polys: a list/tuple/set Listing all the polynomial equations that are needed to be solved opt: an Options object For specifying keyword arguments and generators strict: a boolean If strict is True, NotImplementedError will be raised if the solution is known to be incomplete Returns ======= List[Tuple] a list of tuples with elements being solutions for the symbols in the order they were passed as gens None None is returned when the computed basis contains only the ground. References ========== .. [Buchberger01] B. Buchberger, Groebner Bases: A Short Introduction for Systems Theorists, In: R. Moreno-Diaz, B. Buchberger, J.L. Freire, Proceedings of EUROCAST'01, February, 2001 .. [Cox97] D. Cox, J. Little, D. O'Shea, Ideals, Varieties and Algorithms, Springer, Second Edition, 1997, pp. 112 Raises ======== NotImplementedError If the system is not zero-dimensional (does not have a finite number of solutions) UnsolvableFactorError If ``strict`` is True and not all solution components are expressible in radicals Examples ======== >>> from sympy import Poly, Options >>> from sympy.solvers.polysys import solve_generic >>> from sympy.abc import x, y >>> NewOption = Options((x, y), {'domain': 'ZZ'}) >>> a = Poly(x - y + 5, x, y, domain='ZZ') >>> b = Poly(x + y - 3, x, y, domain='ZZ') >>> solve_generic([a, b], NewOption) [(-1, 4)] >>> a = Poly(x - 2*y + 5, x, y, domain='ZZ') >>> b = Poly(2*x - y - 3, x, y, domain='ZZ') >>> solve_generic([a, b], NewOption) [(11/3, 13/3)] >>> a = Poly(x**2 + y, x, y, domain='ZZ') >>> b = Poly(x + y*4, x, y, domain='ZZ') >>> solve_generic([a, b], NewOption) [(0, 0), (1/4, -1/16)] >>> a = Poly(x**5 - x + y**3, x, y, domain='ZZ') >>> b = Poly(y**2 - 1, x, y, domain='ZZ') >>> solve_generic([a, b], NewOption, strict=True) Traceback (most recent call last): ... UnsolvableFactorError """ def _is_univariate(f): """Returns True if 'f' is univariate in its last variable. """ for monom in f.monoms(): if any(monom[:-1]): return False return True def _subs_root(f, gen, zero): """Replace generator with a root so that the result is nice. """ p = f.as_expr({gen: zero}) if f.degree(gen) >= 2: p = p.expand(deep=False) return p def _solve_reduced_system(system, gens, entry=False): """Recursively solves reduced polynomial systems. """ if len(system) == len(gens) == 1: # the below line will produce UnsolvableFactorError if # strict=True and the solution from `roots` is incomplete zeros = list(roots(system[0], gens[-1], strict=strict).keys()) return [(zero,) for zero in zeros] basis = groebner(system, gens, polys=True) if len(basis) == 1 and basis[0].is_ground: if not entry: return [] else: return None univariate = list(filter(_is_univariate, basis)) if len(basis) < len(gens): raise NotImplementedError(filldedent(''' only zero-dimensional systems supported (finite number of solutions) ''')) if len(univariate) == 1: f = univariate.pop() else: raise NotImplementedError(filldedent(''' only zero-dimensional systems supported (finite number of solutions) ''')) gens = f.gens gen = gens[-1] # the below line will produce UnsolvableFactorError if # strict=True and the solution from `roots` is incomplete zeros = list(roots(f.ltrim(gen), strict=strict).keys()) if not zeros: return [] if len(basis) == 1: return [(zero,) for zero in zeros] solutions = [] for zero in zeros: new_system = [] new_gens = gens[:-1] for b in basis[:-1]: eq = _subs_root(b, gen, zero) if eq is not S.Zero: new_system.append(eq) for solution in _solve_reduced_system(new_system, new_gens): solutions.append(solution + (zero,)) if solutions and len(solutions[0]) != len(gens): raise NotImplementedError(filldedent(''' only zero-dimensional systems supported (finite number of solutions) ''')) return solutions try: result = _solve_reduced_system(polys, opt.gens, entry=True) except CoercionFailed: raise NotImplementedError if result is not None: return sorted(result, key=default_sort_key) def solve_triangulated(polys, *gens, **args): """ Solve a polynomial system using Gianni-Kalkbrenner algorithm. The algorithm proceeds by computing one Groebner basis in the ground domain and then by iteratively computing polynomial factorizations in appropriately constructed algebraic extensions of the ground domain. Parameters ========== polys: a list/tuple/set Listing all the equations that are needed to be solved gens: generators generators of the equations in polys for which we want the solutions args: Keyword arguments Special options for solving the equations Returns ======= List[Tuple] A List of tuples. Solutions for symbols that satisfy the equations listed in polys Examples ======== >>> from sympy import solve_triangulated >>> from sympy.abc import x, y, z >>> F = [x**2 + y + z - 1, x + y**2 + z - 1, x + y + z**2 - 1] >>> solve_triangulated(F, x, y, z) [(0, 0, 1), (0, 1, 0), (1, 0, 0)] References ========== 1. Patrizia Gianni, Teo Mora, Algebraic Solution of System of Polynomial Equations using Groebner Bases, AAECC-5 on Applied Algebra, Algebraic Algorithms and Error-Correcting Codes, LNCS 356 247--257, 1989 """ G = groebner(polys, gens, polys=True) G = list(reversed(G)) domain = args.get('domain') if domain is not None: for i, g in enumerate(G): G[i] = g.set_domain(domain) f, G = G[0].ltrim(-1), G[1:] dom = f.get_domain() zeros = f.ground_roots() solutions = set() for zero in zeros: solutions.add(((zero,), dom)) var_seq = reversed(gens[:-1]) vars_seq = postfixes(gens[1:]) for var, vars in zip(var_seq, vars_seq): _solutions = set() for values, dom in solutions: H, mapping = [], list(zip(vars, values)) for g in G: _vars = (var,) + vars if g.has_only_gens(*_vars) and g.degree(var) != 0: h = g.ltrim(var).eval(dict(mapping)) if g.degree(var) == h.degree(): H.append(h) p = min(H, key=lambda h: h.degree()) zeros = p.ground_roots() for zero in zeros: if not zero.is_Rational: dom_zero = dom.algebraic_field(zero) else: dom_zero = dom _solutions.add(((zero,) + values, dom_zero)) solutions = _solutions solutions = list(solutions) for i, (solution, _) in enumerate(solutions): solutions[i] = solution return sorted(solutions, key=default_sort_key)
a8192736f30fc84893829a91b4a20df0fc591e53fc41c9c427515202a1c8925e
""" This module contain solvers for all kinds of equations: - algebraic or transcendental, use solve() - recurrence, use rsolve() - differential, use dsolve() - nonlinear (numerically), use nsolve() (you will need a good starting point) """ from __future__ import annotations from sympy.core import (S, Add, Symbol, Dummy, Expr, Mul) from sympy.core.assumptions import check_assumptions from sympy.core.exprtools import factor_terms from sympy.core.function import (expand_mul, expand_log, Derivative, AppliedUndef, UndefinedFunction, nfloat, Function, expand_power_exp, _mexpand, expand, expand_func) from sympy.core.logic import fuzzy_not from sympy.core.numbers import ilcm, Float, Rational, _illegal from sympy.core.power import integer_log, Pow from sympy.core.relational import Eq, Ne from sympy.core.sorting import ordered, default_sort_key from sympy.core.sympify import sympify, _sympify from sympy.core.traversal import preorder_traversal from sympy.logic.boolalg import And, BooleanAtom from sympy.functions import (log, exp, LambertW, cos, sin, tan, acos, asin, atan, Abs, re, im, arg, sqrt, atan2) from sympy.functions.combinatorial.factorials import binomial from sympy.functions.elementary.hyperbolic import HyperbolicFunction from sympy.functions.elementary.piecewise import piecewise_fold, Piecewise from sympy.functions.elementary.trigonometric import TrigonometricFunction from sympy.integrals.integrals import Integral from sympy.ntheory.factor_ import divisors from sympy.simplify import (simplify, collect, powsimp, posify, # type: ignore powdenest, nsimplify, denom, logcombine, sqrtdenest, fraction, separatevars) from sympy.simplify.sqrtdenest import sqrt_depth from sympy.simplify.fu import TR1, TR2i from sympy.matrices.common import NonInvertibleMatrixError from sympy.matrices import Matrix, zeros from sympy.polys import roots, cancel, factor, Poly from sympy.polys.polyerrors import GeneratorsNeeded, PolynomialError from sympy.polys.solvers import sympy_eqs_to_ring, solve_lin_sys from sympy.utilities.lambdify import lambdify from sympy.utilities.misc import filldedent, debugf from sympy.utilities.iterables import (connected_components, generate_bell, uniq, iterable, is_sequence, subsets, flatten) from sympy.utilities.decorator import conserve_mpmath_dps from mpmath import findroot from sympy.solvers.polysys import solve_poly_system from types import GeneratorType from collections import defaultdict from itertools import combinations, product import warnings def recast_to_symbols(eqs, symbols): """ Return (e, s, d) where e and s are versions of *eqs* and *symbols* in which any non-Symbol objects in *symbols* have been replaced with generic Dummy symbols and d is a dictionary that can be used to restore the original expressions. Examples ======== >>> from sympy.solvers.solvers import recast_to_symbols >>> from sympy import symbols, Function >>> x, y = symbols('x y') >>> fx = Function('f')(x) >>> eqs, syms = [fx + 1, x, y], [fx, y] >>> e, s, d = recast_to_symbols(eqs, syms); (e, s, d) ([_X0 + 1, x, y], [_X0, y], {_X0: f(x)}) The original equations and symbols can be restored using d: >>> assert [i.xreplace(d) for i in eqs] == eqs >>> assert [d.get(i, i) for i in s] == syms """ if not iterable(eqs) and iterable(symbols): raise ValueError('Both eqs and symbols must be iterable') orig = list(symbols) symbols = list(ordered(symbols)) swap_sym = {} i = 0 for j, s in enumerate(symbols): if not isinstance(s, Symbol) and s not in swap_sym: swap_sym[s] = Dummy('X%d' % i) i += 1 new_f = [] for i in eqs: isubs = getattr(i, 'subs', None) if isubs is not None: new_f.append(isubs(swap_sym)) else: new_f.append(i) restore = {v: k for k, v in swap_sym.items()} return new_f, [swap_sym.get(i, i) for i in orig], restore def _ispow(e): """Return True if e is a Pow or is exp.""" return isinstance(e, Expr) and (e.is_Pow or isinstance(e, exp)) def _simple_dens(f, symbols): # when checking if a denominator is zero, we can just check the # base of powers with nonzero exponents since if the base is zero # the power will be zero, too. To keep it simple and fast, we # limit simplification to exponents that are Numbers dens = set() for d in denoms(f, symbols): if d.is_Pow and d.exp.is_Number: if d.exp.is_zero: continue # foo**0 is never 0 d = d.base dens.add(d) return dens def denoms(eq, *symbols): """ Return (recursively) set of all denominators that appear in *eq* that contain any symbol in *symbols*; if *symbols* are not provided then all denominators will be returned. Examples ======== >>> from sympy.solvers.solvers import denoms >>> from sympy.abc import x, y, z >>> denoms(x/y) {y} >>> denoms(x/(y*z)) {y, z} >>> denoms(3/x + y/z) {x, z} >>> denoms(x/2 + y/z) {2, z} If *symbols* are provided then only denominators containing those symbols will be returned: >>> denoms(1/x + 1/y + 1/z, y, z) {y, z} """ pot = preorder_traversal(eq) dens = set() for p in pot: # Here p might be Tuple or Relational # Expr subtrees (e.g. lhs and rhs) will be traversed after by pot if not isinstance(p, Expr): continue den = denom(p) if den is S.One: continue for d in Mul.make_args(den): dens.add(d) if not symbols: return dens elif len(symbols) == 1: if iterable(symbols[0]): symbols = symbols[0] return {d for d in dens if any(s in d.free_symbols for s in symbols)} def checksol(f, symbol, sol=None, **flags): """ Checks whether sol is a solution of equation f == 0. Explanation =========== Input can be either a single symbol and corresponding value or a dictionary of symbols and values. When given as a dictionary and flag ``simplify=True``, the values in the dictionary will be simplified. *f* can be a single equation or an iterable of equations. A solution must satisfy all equations in *f* to be considered valid; if a solution does not satisfy any equation, False is returned; if one or more checks are inconclusive (and none are False) then None is returned. Examples ======== >>> from sympy import checksol, symbols >>> x, y = symbols('x,y') >>> checksol(x**4 - 1, x, 1) True >>> checksol(x**4 - 1, x, 0) False >>> checksol(x**2 + y**2 - 5**2, {x: 3, y: 4}) True To check if an expression is zero using ``checksol()``, pass it as *f* and send an empty dictionary for *symbol*: >>> checksol(x**2 + x - x*(x + 1), {}) True None is returned if ``checksol()`` could not conclude. flags: 'numerical=True (default)' do a fast numerical check if ``f`` has only one symbol. 'minimal=True (default is False)' a very fast, minimal testing. 'warn=True (default is False)' show a warning if checksol() could not conclude. 'simplify=True (default)' simplify solution before substituting into function and simplify the function before trying specific simplifications 'force=True (default is False)' make positive all symbols without assumptions regarding sign. """ from sympy.physics.units import Unit minimal = flags.get('minimal', False) if sol is not None: sol = {symbol: sol} elif isinstance(symbol, dict): sol = symbol else: msg = 'Expecting (sym, val) or ({sym: val}, None) but got (%s, %s)' raise ValueError(msg % (symbol, sol)) if iterable(f): if not f: raise ValueError('no functions to check') rv = True for fi in f: check = checksol(fi, sol, **flags) if check: continue if check is False: return False rv = None # don't return, wait to see if there's a False return rv f = _sympify(f) if f.is_number: return f.is_zero if isinstance(f, Poly): f = f.as_expr() elif isinstance(f, (Eq, Ne)): if f.rhs in (S.true, S.false): f = f.reversed B, E = f.args if isinstance(B, BooleanAtom): f = f.subs(sol) if not f.is_Boolean: return else: f = f.rewrite(Add, evaluate=False) if isinstance(f, BooleanAtom): return bool(f) elif not f.is_Relational and not f: return True illegal = set(_illegal) if any(sympify(v).atoms() & illegal for k, v in sol.items()): return False attempt = -1 numerical = flags.get('numerical', True) while 1: attempt += 1 if attempt == 0: val = f.subs(sol) if isinstance(val, Mul): val = val.as_independent(Unit)[0] if val.atoms() & illegal: return False elif attempt == 1: if not val.is_number: if not val.is_constant(*list(sol.keys()), simplify=not minimal): return False # there are free symbols -- simple expansion might work _, val = val.as_content_primitive() val = _mexpand(val.as_numer_denom()[0], recursive=True) elif attempt == 2: if minimal: return if flags.get('simplify', True): for k in sol: sol[k] = simplify(sol[k]) # start over without the failed expanded form, possibly # with a simplified solution val = simplify(f.subs(sol)) if flags.get('force', True): val, reps = posify(val) # expansion may work now, so try again and check exval = _mexpand(val, recursive=True) if exval.is_number: # we can decide now val = exval else: # if there are no radicals and no functions then this can't be # zero anymore -- can it? pot = preorder_traversal(expand_mul(val)) seen = set() saw_pow_func = False for p in pot: if p in seen: continue seen.add(p) if p.is_Pow and not p.exp.is_Integer: saw_pow_func = True elif p.is_Function: saw_pow_func = True elif isinstance(p, UndefinedFunction): saw_pow_func = True if saw_pow_func: break if saw_pow_func is False: return False if flags.get('force', True): # don't do a zero check with the positive assumptions in place val = val.subs(reps) nz = fuzzy_not(val.is_zero) if nz is not None: # issue 5673: nz may be True even when False # so these are just hacks to keep a false positive # from being returned # HACK 1: LambertW (issue 5673) if val.is_number and val.has(LambertW): # don't eval this to verify solution since if we got here, # numerical must be False return None # add other HACKs here if necessary, otherwise we assume # the nz value is correct return not nz break if val.is_Rational: return val == 0 if numerical and val.is_number: return (abs(val.n(18).n(12, chop=True)) < 1e-9) is S.true if flags.get('warn', False): warnings.warn("\n\tWarning: could not verify solution %s." % sol) # returns None if it can't conclude # TODO: improve solution testing def solve(f, *symbols, **flags): r""" Algebraically solves equations and systems of equations. Explanation =========== Currently supported: - polynomial - transcendental - piecewise combinations of the above - systems of linear and polynomial equations - systems containing relational expressions - systems implied by undetermined coefficients Examples ======== The default output varies according to the input and might be a list (possibly empty), a dictionary, a list of dictionaries or tuples, or an expression involving relationals. For specifics regarding different forms of output that may appear, see :ref:`solve_output`. Let it suffice here to say that to obtain a uniform output from `solve` use ``dict=True`` or ``set=True`` (see below). >>> from sympy import solve, Poly, Eq, Matrix, Symbol >>> from sympy.abc import x, y, z, a, b The expressions that are passed can be Expr, Equality, or Poly classes (or lists of the same); a Matrix is considered to be a list of all the elements of the matrix: >>> solve(x - 3, x) [3] >>> solve(Eq(x, 3), x) [3] >>> solve(Poly(x - 3), x) [3] >>> solve(Matrix([[x, x + y]]), x, y) == solve([x, x + y], x, y) True If no symbols are indicated to be of interest and the equation is univariate, a list of values is returned; otherwise, the keys in a dictionary will indicate which (of all the variables used in the expression(s)) variables and solutions were found: >>> solve(x**2 - 4) [-2, 2] >>> solve((x - a)*(y - b)) [{a: x}, {b: y}] >>> solve([x - 3, y - 1]) {x: 3, y: 1} >>> solve([x - 3, y**2 - 1]) [{x: 3, y: -1}, {x: 3, y: 1}] If you pass symbols for which solutions are sought, the output will vary depending on the number of symbols you passed, whether you are passing a list of expressions or not, and whether a linear system was solved. Uniform output is attained by using ``dict=True`` or ``set=True``. >>> #### *** feel free to skip to the stars below *** #### >>> from sympy import TableForm >>> h = [None, ';|;'.join(['e', 's', 'solve(e, s)', 'solve(e, s, dict=True)', ... 'solve(e, s, set=True)']).split(';')] >>> t = [] >>> for e, s in [ ... (x - y, y), ... (x - y, [x, y]), ... (x**2 - y, [x, y]), ... ([x - 3, y -1], [x, y]), ... ]: ... how = [{}, dict(dict=True), dict(set=True)] ... res = [solve(e, s, **f) for f in how] ... t.append([e, '|', s, '|'] + [res[0], '|', res[1], '|', res[2]]) ... >>> # ******************************************************* # >>> TableForm(t, headings=h, alignments="<") e | s | solve(e, s) | solve(e, s, dict=True) | solve(e, s, set=True) --------------------------------------------------------------------------------------- x - y | y | [x] | [{y: x}] | ([y], {(x,)}) x - y | [x, y] | [(y, y)] | [{x: y}] | ([x, y], {(y, y)}) x**2 - y | [x, y] | [(x, x**2)] | [{y: x**2}] | ([x, y], {(x, x**2)}) [x - 3, y - 1] | [x, y] | {x: 3, y: 1} | [{x: 3, y: 1}] | ([x, y], {(3, 1)}) * If any equation does not depend on the symbol(s) given, it will be eliminated from the equation set and an answer may be given implicitly in terms of variables that were not of interest: >>> solve([x - y, y - 3], x) {x: y} When you pass all but one of the free symbols, an attempt is made to find a single solution based on the method of undetermined coefficients. If it succeeds, a dictionary of values is returned. If you want an algebraic solutions for one or more of the symbols, pass the expression to be solved in a list: >>> e = a*x + b - 2*x - 3 >>> solve(e, [a, b]) {a: 2, b: 3} >>> solve([e], [a, b]) {a: -b/x + (2*x + 3)/x} When there is no solution for any given symbol which will make all expressions zero, the empty list is returned (or an empty set in the tuple when ``set=True``): >>> from sympy import sqrt >>> solve(3, x) [] >>> solve(x - 3, y) [] >>> solve(sqrt(x) + 1, x, set=True) ([x], set()) When an object other than a Symbol is given as a symbol, it is isolated algebraically and an implicit solution may be obtained. This is mostly provided as a convenience to save you from replacing the object with a Symbol and solving for that Symbol. It will only work if the specified object can be replaced with a Symbol using the subs method: >>> from sympy import exp, Function >>> f = Function('f') >>> solve(f(x) - x, f(x)) [x] >>> solve(f(x).diff(x) - f(x) - x, f(x).diff(x)) [x + f(x)] >>> solve(f(x).diff(x) - f(x) - x, f(x)) [-x + Derivative(f(x), x)] >>> solve(x + exp(x)**2, exp(x), set=True) ([exp(x)], {(-sqrt(-x),), (sqrt(-x),)}) >>> from sympy import Indexed, IndexedBase, Tuple >>> A = IndexedBase('A') >>> eqs = Tuple(A[1] + A[2] - 3, A[1] - A[2] + 1) >>> solve(eqs, eqs.atoms(Indexed)) {A[1]: 1, A[2]: 2} * To solve for a function within a derivative, use :func:`~.dsolve`. To solve for a symbol implicitly, use implicit=True: >>> solve(x + exp(x), x) [-LambertW(1)] >>> solve(x + exp(x), x, implicit=True) [-exp(x)] It is possible to solve for anything in an expression that can be replaced with a symbol using :obj:`~sympy.core.basic.Basic.subs`: >>> solve(x + 2 + sqrt(3), x + 2) [-sqrt(3)] >>> solve((x + 2 + sqrt(3), x + 4 + y), y, x + 2) {y: -2 + sqrt(3), x + 2: -sqrt(3)} * Nothing heroic is done in this implicit solving so you may end up with a symbol still in the solution: >>> eqs = (x*y + 3*y + sqrt(3), x + 4 + y) >>> solve(eqs, y, x + 2) {y: -sqrt(3)/(x + 3), x + 2: -2*x/(x + 3) - 6/(x + 3) + sqrt(3)/(x + 3)} >>> solve(eqs, y*x, x) {x: -y - 4, x*y: -3*y - sqrt(3)} * If you attempt to solve for a number, remember that the number you have obtained does not necessarily mean that the value is equivalent to the expression obtained: >>> solve(sqrt(2) - 1, 1) [sqrt(2)] >>> solve(x - y + 1, 1) # /!\ -1 is targeted, too [x/(y - 1)] >>> [_.subs(z, -1) for _ in solve((x - y + 1).subs(-1, z), 1)] [-x + y] **Additional Examples** ``solve()`` with check=True (default) will run through the symbol tags to eliminate unwanted solutions. If no assumptions are included, all possible solutions will be returned: >>> x = Symbol("x") >>> solve(x**2 - 1) [-1, 1] By setting the ``positive`` flag, only one solution will be returned: >>> pos = Symbol("pos", positive=True) >>> solve(pos**2 - 1) [1] When the solutions are checked, those that make any denominator zero are automatically excluded. If you do not want to exclude such solutions, then use the check=False option: >>> from sympy import sin, limit >>> solve(sin(x)/x) # 0 is excluded [pi] If ``check=False``, then a solution to the numerator being zero is found but the value of $x = 0$ is a spurious solution since $\sin(x)/x$ has the well known limit (without discontinuity) of 1 at $x = 0$: >>> solve(sin(x)/x, check=False) [0, pi] In the following case, however, the limit exists and is equal to the value of $x = 0$ that is excluded when check=True: >>> eq = x**2*(1/x - z**2/x) >>> solve(eq, x) [] >>> solve(eq, x, check=False) [0] >>> limit(eq, x, 0, '-') 0 >>> limit(eq, x, 0, '+') 0 **Solving Relationships** When one or more expressions passed to ``solve`` is a relational, a relational result is returned (and the ``dict`` and ``set`` flags are ignored): >>> solve(x < 3) (-oo < x) & (x < 3) >>> solve([x < 3, x**2 > 4], x) ((-oo < x) & (x < -2)) | ((2 < x) & (x < 3)) >>> solve([x + y - 3, x > 3], x) (3 < x) & (x < oo) & Eq(x, 3 - y) Although checking of assumptions on symbols in relationals is not done, setting assumptions will affect how certain relationals might automatically simplify: >>> solve(x**2 > 4) ((-oo < x) & (x < -2)) | ((2 < x) & (x < oo)) >>> r = Symbol('r', real=True) >>> solve(r**2 > 4) (2 < r) | (r < -2) There is currently no algorithm in SymPy that allows you to use relationships to resolve more than one variable. So the following does not determine that ``q < 0`` (and trying to solve for ``r`` and ``q`` will raise an error): >>> from sympy import symbols >>> r, q = symbols('r, q', real=True) >>> solve([r + q - 3, r > 3], r) (3 < r) & Eq(r, 3 - q) You can directly call the routine that ``solve`` calls when it encounters a relational: :func:`~.reduce_inequalities`. It treats Expr like Equality. >>> from sympy import reduce_inequalities >>> reduce_inequalities([x**2 - 4]) Eq(x, -2) | Eq(x, 2) If each relationship contains only one symbol of interest, the expressions can be processed for multiple symbols: >>> reduce_inequalities([0 <= x - 1, y < 3], [x, y]) (-oo < y) & (1 <= x) & (x < oo) & (y < 3) But an error is raised if any relationship has more than one symbol of interest: >>> reduce_inequalities([0 <= x*y - 1, y < 3], [x, y]) Traceback (most recent call last): ... NotImplementedError: inequality has more than one symbol of interest. **Disabling High-Order Explicit Solutions** When solving polynomial expressions, you might not want explicit solutions (which can be quite long). If the expression is univariate, ``CRootOf`` instances will be returned instead: >>> solve(x**3 - x + 1) [-1/((-1/2 - sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)) - (-1/2 - sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3, -(-1/2 + sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)/3 - 1/((-1/2 + sqrt(3)*I/2)*(3*sqrt(69)/2 + 27/2)**(1/3)), -(3*sqrt(69)/2 + 27/2)**(1/3)/3 - 1/(3*sqrt(69)/2 + 27/2)**(1/3)] >>> solve(x**3 - x + 1, cubics=False) [CRootOf(x**3 - x + 1, 0), CRootOf(x**3 - x + 1, 1), CRootOf(x**3 - x + 1, 2)] If the expression is multivariate, no solution might be returned: >>> solve(x**3 - x + a, x, cubics=False) [] Sometimes solutions will be obtained even when a flag is False because the expression could be factored. In the following example, the equation can be factored as the product of a linear and a quadratic factor so explicit solutions (which did not require solving a cubic expression) are obtained: >>> eq = x**3 + 3*x**2 + x - 1 >>> solve(eq, cubics=False) [-1, -1 + sqrt(2), -sqrt(2) - 1] **Solving Equations Involving Radicals** Because of SymPy's use of the principle root, some solutions to radical equations will be missed unless check=False: >>> from sympy import root >>> eq = root(x**3 - 3*x**2, 3) + 1 - x >>> solve(eq) [] >>> solve(eq, check=False) [1/3] In the above example, there is only a single solution to the equation. Other expressions will yield spurious roots which must be checked manually; roots which give a negative argument to odd-powered radicals will also need special checking: >>> from sympy import real_root, S >>> eq = root(x, 3) - root(x, 5) + S(1)/7 >>> solve(eq) # this gives 2 solutions but misses a 3rd [CRootOf(7*x**5 - 7*x**3 + 1, 1)**15, CRootOf(7*x**5 - 7*x**3 + 1, 2)**15] >>> sol = solve(eq, check=False) >>> [abs(eq.subs(x,i).n(2)) for i in sol] [0.48, 0.e-110, 0.e-110, 0.052, 0.052] The first solution is negative so ``real_root`` must be used to see that it satisfies the expression: >>> abs(real_root(eq.subs(x, sol[0])).n(2)) 0.e-110 If the roots of the equation are not real then more care will be necessary to find the roots, especially for higher order equations. Consider the following expression: >>> expr = root(x, 3) - root(x, 5) We will construct a known value for this expression at x = 3 by selecting the 1-th root for each radical: >>> expr1 = root(x, 3, 1) - root(x, 5, 1) >>> v = expr1.subs(x, -3) The ``solve`` function is unable to find any exact roots to this equation: >>> eq = Eq(expr, v); eq1 = Eq(expr1, v) >>> solve(eq, check=False), solve(eq1, check=False) ([], []) The function ``unrad``, however, can be used to get a form of the equation for which numerical roots can be found: >>> from sympy.solvers.solvers import unrad >>> from sympy import nroots >>> e, (p, cov) = unrad(eq) >>> pvals = nroots(e) >>> inversion = solve(cov, x)[0] >>> xvals = [inversion.subs(p, i) for i in pvals] Although ``eq`` or ``eq1`` could have been used to find ``xvals``, the solution can only be verified with ``expr1``: >>> z = expr - v >>> [xi.n(chop=1e-9) for xi in xvals if abs(z.subs(x, xi).n()) < 1e-9] [] >>> z1 = expr1 - v >>> [xi.n(chop=1e-9) for xi in xvals if abs(z1.subs(x, xi).n()) < 1e-9] [-3.0] Parameters ========== f : - a single Expr or Poly that must be zero - an Equality - a Relational expression - a Boolean - iterable of one or more of the above symbols : (object(s) to solve for) specified as - none given (other non-numeric objects will be used) - single symbol - denested list of symbols (e.g., ``solve(f, x, y)``) - ordered iterable of symbols (e.g., ``solve(f, [x, y])``) flags : dict=True (default is False) Return list (perhaps empty) of solution mappings. set=True (default is False) Return list of symbols and set of tuple(s) of solution(s). exclude=[] (default) Do not try to solve for any of the free symbols in exclude; if expressions are given, the free symbols in them will be extracted automatically. check=True (default) If False, do not do any testing of solutions. This can be useful if you want to include solutions that make any denominator zero. numerical=True (default) Do a fast numerical check if *f* has only one symbol. minimal=True (default is False) A very fast, minimal testing. warn=True (default is False) Show a warning if ``checksol()`` could not conclude. simplify=True (default) Simplify all but polynomials of order 3 or greater before returning them and (if check is not False) use the general simplify function on the solutions and the expression obtained when they are substituted into the function which should be zero. force=True (default is False) Make positive all symbols without assumptions regarding sign. rational=True (default) Recast Floats as Rational; if this option is not used, the system containing Floats may fail to solve because of issues with polys. If rational=None, Floats will be recast as rationals but the answer will be recast as Floats. If the flag is False then nothing will be done to the Floats. manual=True (default is False) Do not use the polys/matrix method to solve a system of equations, solve them one at a time as you might "manually." implicit=True (default is False) Allows ``solve`` to return a solution for a pattern in terms of other functions that contain that pattern; this is only needed if the pattern is inside of some invertible function like cos, exp, ect. particular=True (default is False) Instructs ``solve`` to try to find a particular solution to a linear system with as many zeros as possible; this is very expensive. quick=True (default is False; ``particular`` must be True) Selects a fast heuristic to find a solution with many zeros whereas a value of False uses the very slow method guaranteed to find the largest number of zeros possible. cubics=True (default) Return explicit solutions when cubic expressions are encountered. When False, quartics and quintics are disabled, too. quartics=True (default) Return explicit solutions when quartic expressions are encountered. When False, quintics are disabled, too. quintics=True (default) Return explicit solutions (if possible) when quintic expressions are encountered. See Also ======== rsolve: For solving recurrence relationships dsolve: For solving differential equations """ from .inequalities import reduce_inequalities # checking/recording flags ########################################################################### # set solver types explicitly; as soon as one is False # all the rest will be False hints = ('cubics', 'quartics', 'quintics') default = True for k in hints: default = flags.setdefault(k, bool(flags.get(k, default))) # allow solution to contain symbol if True: implicit = flags.get('implicit', False) # record desire to see warnings warn = flags.get('warn', False) # this flag will be needed for quick exits below, so record # now -- but don't record `dict` yet since it might change as_set = flags.get('set', False) # keeping track of how f was passed bare_f = not iterable(f) # check flag usage for particular/quick which should only be used # with systems of equations if flags.get('quick', None) is not None: if not flags.get('particular', None): raise ValueError('when using `quick`, `particular` should be True') if flags.get('particular', False) and bare_f: raise ValueError(filldedent(""" The 'particular/quick' flag is usually used with systems of equations. Either pass your equation in a list or consider using a solver like `diophantine` if you are looking for a solution in integers.""")) # sympify everything, creating list of expressions and list of symbols ########################################################################### def _sympified_list(w): return list(map(sympify, w if iterable(w) else [w])) f, symbols = (_sympified_list(w) for w in [f, symbols]) # preprocess symbol(s) ########################################################################### ordered_symbols = None # were the symbols in a well defined order? if not symbols: # get symbols from equations symbols = set().union(*[fi.free_symbols for fi in f]) if len(symbols) < len(f): for fi in f: pot = preorder_traversal(fi) for p in pot: if isinstance(p, AppliedUndef): if not as_set: flags['dict'] = True # better show symbols symbols.add(p) pot.skip() # don't go any deeper ordered_symbols = False symbols = list(ordered(symbols)) # to make it canonical else: if len(symbols) == 1 and iterable(symbols[0]): symbols = symbols[0] ordered_symbols = symbols and is_sequence(symbols, include=GeneratorType) _symbols = list(uniq(symbols)) if len(_symbols) != len(symbols): ordered_symbols = False symbols = list(ordered(symbols)) else: symbols = _symbols # check for duplicates if len(symbols) != len(set(symbols)): raise ValueError('duplicate symbols given') # remove those not of interest exclude = flags.pop('exclude', set()) if exclude: if isinstance(exclude, Expr): exclude = [exclude] exclude = set().union(*[e.free_symbols for e in sympify(exclude)]) symbols = [s for s in symbols if s not in exclude] # preprocess equation(s) ########################################################################### # automatically ignore True values if isinstance(f, list): f = [s for s in f if s is not S.true] # handle canonicalization of equation types for i, fi in enumerate(f): if isinstance(fi, (Eq, Ne)): if 'ImmutableDenseMatrix' in [type(a).__name__ for a in fi.args]: fi = fi.lhs - fi.rhs else: L, R = fi.args if isinstance(R, BooleanAtom): L, R = R, L if isinstance(L, BooleanAtom): if isinstance(fi, Ne): L = ~L if R.is_Relational: fi = ~R if L is S.false else R elif R.is_Symbol: return L elif R.is_Boolean and (~R).is_Symbol: return ~L else: raise NotImplementedError(filldedent(''' Unanticipated argument of Eq when other arg is True or False. ''')) else: fi = fi.rewrite(Add, evaluate=False) f[i] = fi # *** dispatch and handle as a system of relationals # ************************************************** if fi.is_Relational: if len(symbols) != 1: raise ValueError("can only solve for one symbol at a time") if warn and symbols[0].assumptions0: warnings.warn(filldedent(""" \tWarning: assumptions about variable '%s' are not handled currently.""" % symbols[0])) return reduce_inequalities(f, symbols=symbols) # convert Poly to expression if isinstance(fi, Poly): f[i] = fi.as_expr() # rewrite hyperbolics in terms of exp if they have symbols of # interest f[i] = f[i].replace(lambda w: isinstance(w, HyperbolicFunction) and \ w.has_free(*symbols), lambda w: w.rewrite(exp)) # if we have a Matrix, we need to iterate over its elements again if f[i].is_Matrix: bare_f = False f.extend(list(f[i])) f[i] = S.Zero # if we can split it into real and imaginary parts then do so freei = f[i].free_symbols if freei and all(s.is_extended_real or s.is_imaginary for s in freei): fr, fi = f[i].as_real_imag() # accept as long as new re, im, arg or atan2 are not introduced had = f[i].atoms(re, im, arg, atan2) if fr and fi and fr != fi and not any( i.atoms(re, im, arg, atan2) - had for i in (fr, fi)): if bare_f: bare_f = False f[i: i + 1] = [fr, fi] # real/imag handling ----------------------------- if any(isinstance(fi, (bool, BooleanAtom)) for fi in f): if as_set: return [], set() return [] for i, fi in enumerate(f): # Abs while True: was = fi fi = fi.replace(Abs, lambda arg: separatevars(Abs(arg)).rewrite(Piecewise) if arg.has(*symbols) else Abs(arg)) if was == fi: break for e in fi.find(Abs): if e.has(*symbols): raise NotImplementedError('solving %s when the argument ' 'is not real or imaginary.' % e) # arg fi = fi.replace(arg, lambda a: arg(a).rewrite(atan2).rewrite(atan)) # save changes f[i] = fi # see if re(s) or im(s) appear freim = [fi for fi in f if fi.has(re, im)] if freim: irf = [] for s in symbols: if s.is_real or s.is_imaginary: continue # neither re(x) nor im(x) will appear # if re(s) or im(s) appear, the auxiliary equation must be present if any(fi.has(re(s), im(s)) for fi in freim): irf.append((s, re(s) + S.ImaginaryUnit*im(s))) if irf: for s, rhs in irf: f = [fi.xreplace({s: rhs}) for fi in f] + [s - rhs] symbols.extend([re(s), im(s)]) if bare_f: bare_f = False flags['dict'] = True # end of real/imag handling ----------------------------- # we can solve for non-symbol entities by replacing them with Dummy symbols f, symbols, swap_sym = recast_to_symbols(f, symbols) # this set of symbols (perhaps recast) is needed below symset = set(symbols) # get rid of equations that have no symbols of interest; we don't # try to solve them because the user didn't ask and they might be # hard to solve; this means that solutions may be given in terms # of the eliminated equations e.g. solve((x-y, y-3), x) -> {x: y} newf = [] for fi in f: # let the solver handle equations that.. # - have no symbols but are expressions # - have symbols of interest # - have no symbols of interest but are constant # but when an expression is not constant and has no symbols of # interest, it can't change what we obtain for a solution from # the remaining equations so we don't include it; and if it's # zero it can be removed and if it's not zero, there is no # solution for the equation set as a whole # # The reason for doing this filtering is to allow an answer # to be obtained to queries like solve((x - y, y), x); without # this mod the return value is [] ok = False if fi.free_symbols & symset: ok = True else: if fi.is_number: if fi.is_Number: if fi.is_zero: continue return [] ok = True else: if fi.is_constant(): ok = True if ok: newf.append(fi) if not newf: if as_set: return symbols, set() return [] f = newf del newf # mask off any Object that we aren't going to invert: Derivative, # Integral, etc... so that solving for anything that they contain will # give an implicit solution seen = set() non_inverts = set() for fi in f: pot = preorder_traversal(fi) for p in pot: if not isinstance(p, Expr) or isinstance(p, Piecewise): pass elif (isinstance(p, bool) or not p.args or p in symset or p.is_Add or p.is_Mul or p.is_Pow and not implicit or p.is_Function and not implicit) and p.func not in (re, im): continue elif p not in seen: seen.add(p) if p.free_symbols & symset: non_inverts.add(p) else: continue pot.skip() del seen non_inverts = dict(list(zip(non_inverts, [Dummy() for _ in non_inverts]))) f = [fi.subs(non_inverts) for fi in f] # Both xreplace and subs are needed below: xreplace to force substitution # inside Derivative, subs to handle non-straightforward substitutions non_inverts = [(v, k.xreplace(swap_sym).subs(swap_sym)) for k, v in non_inverts.items()] # rationalize Floats floats = False if flags.get('rational', True) is not False: for i, fi in enumerate(f): if fi.has(Float): floats = True f[i] = nsimplify(fi, rational=True) # capture any denominators before rewriting since # they may disappear after the rewrite, e.g. issue 14779 flags['_denominators'] = _simple_dens(f[0], symbols) # Any embedded piecewise functions need to be brought out to the # top level so that the appropriate strategy gets selected. # However, this is necessary only if one of the piecewise # functions depends on one of the symbols we are solving for. def _has_piecewise(e): if e.is_Piecewise: return e.has(*symbols) return any(_has_piecewise(a) for a in e.args) for i, fi in enumerate(f): if _has_piecewise(fi): f[i] = piecewise_fold(fi) # # try to get a solution ########################################################################### if bare_f: solution = None if len(symbols) != 1: solution = _solve_undetermined(f[0], symbols, flags) if not solution: solution = _solve(f[0], *symbols, **flags) else: linear, solution = _solve_system(f, symbols, **flags) assert type(solution) is list assert not solution or type(solution[0]) is dict, solution # # postprocessing ########################################################################### # capture as_dict flag now (as_set already captured) as_dict = flags.get('dict', False) # define how solution will get unpacked tuple_format = lambda s: [tuple([i.get(x, x) for x in symbols]) for i in s] if as_dict or as_set: unpack = None elif bare_f: if len(symbols) == 1: unpack = lambda s: [i[symbols[0]] for i in s] elif len(solution) == 1 and len(solution[0]) == len(symbols): # undetermined linear coeffs solution unpack = lambda s: s[0] elif ordered_symbols: unpack = tuple_format else: unpack = lambda s: s else: if solution: if linear and len(solution) == 1: # if you want the tuple solution for the linear # case, use `set=True` unpack = lambda s: s[0] elif ordered_symbols: unpack = tuple_format else: unpack = lambda s: s else: unpack = None # Restore masked-off objects if non_inverts and type(solution) is list: solution = [{k: v.subs(non_inverts) for k, v in s.items()} for s in solution] # Restore original "symbols" if a dictionary is returned. # This is not necessary for # - the single univariate equation case # since the symbol will have been removed from the solution; # - the nonlinear poly_system since that only supports zero-dimensional # systems and those results come back as a list # # ** unless there were Derivatives with the symbols, but those were handled # above. if swap_sym: symbols = [swap_sym.get(k, k) for k in symbols] for i, sol in enumerate(solution): solution[i] = {swap_sym.get(k, k): v.subs(swap_sym) for k, v in sol.items()} # Get assumptions about symbols, to filter solutions. # Note that if assumptions about a solution can't be verified, it is still # returned. check = flags.get('check', True) # restore floats if floats and solution and flags.get('rational', None) is None: solution = nfloat(solution, exponent=False) # nfloat might reveal more duplicates solution = _remove_duplicate_solutions(solution) if check and solution: # assumption checking warn = flags.get('warn', False) got_None = [] # solutions for which one or more symbols gave None no_False = [] # solutions for which no symbols gave False for sol in solution: a_None = False for symb, val in sol.items(): test = check_assumptions(val, **symb.assumptions0) if test: continue if test is False: break a_None = True else: no_False.append(sol) if a_None: got_None.append(sol) solution = no_False if warn and got_None: warnings.warn(filldedent(""" \tWarning: assumptions concerning following solution(s) cannot be checked:""" + '\n\t' + ', '.join(str(s) for s in got_None))) # # done ########################################################################### if not solution: if as_set: return symbols, set() return [] # make orderings canonical for list of dictionaries if not as_set: # for set, no point in ordering solution = [{k: s[k] for k in ordered(s)} for s in solution] solution.sort(key=default_sort_key) if not (as_set or as_dict): return unpack(solution) if as_dict: return solution # set output: (symbols, {t1, t2, ...}) from list of dictionaries; # include all symbols for those that like a verbose solution # and to resolve any differences in dictionary keys. # # The set results can easily be used to make a verbose dict as # k, v = solve(eqs, syms, set=True) # sol = [dict(zip(k,i)) for i in v] # if ordered_symbols: k = symbols # keep preferred order else: # just unify the symbols for which solutions were found k = list(ordered(set(flatten(tuple(i.keys()) for i in solution)))) return k, {tuple([s.get(ki, ki) for ki in k]) for s in solution} def _solve_undetermined(g, symbols, flags): """solve helper to return a list with one dict (solution) else None A direct call to solve_undetermined_coeffs is more flexible and can return both multiple solutions and handle more than one independent variable. Here, we have to be more cautious to keep from solving something that does not look like an undetermined coeffs system -- to minimize the surprise factor since singularities that cancel are not prohibited in solve_undetermined_coeffs. """ if g.free_symbols - set(symbols): sol = solve_undetermined_coeffs(g, symbols, **dict(flags, dict=True, set=None)) if len(sol) == 1: return sol def _solve(f, *symbols, **flags): """Return a checked solution for *f* in terms of one or more of the symbols in the form of a list of dictionaries. If no method is implemented to solve the equation, a NotImplementedError will be raised. In the case that conversion of an expression to a Poly gives None a ValueError will be raised. """ not_impl_msg = "No algorithms are implemented to solve equation %s" if len(symbols) != 1: # look for solutions for desired symbols that are independent # of symbols already solved for, e.g. if we solve for x = y # then no symbol having x in its solution will be returned. # First solve for linear symbols (since that is easier and limits # solution size) and then proceed with symbols appearing # in a non-linear fashion. Ideally, if one is solving a single # expression for several symbols, they would have to be # appear in factors of an expression, but we do not here # attempt factorization. XXX perhaps handling a Mul # should come first in this routine whether there is # one or several symbols. nonlin_s = [] got_s = set() rhs_s = set() result = [] for s in symbols: xi, v = solve_linear(f, symbols=[s]) if xi == s: # no need to check but we should simplify if desired if flags.get('simplify', True): v = simplify(v) vfree = v.free_symbols if vfree & got_s: # was linear, but has redundant relationship # e.g. x - y = 0 has y == x is redundant for x == y # so ignore continue rhs_s |= vfree got_s.add(xi) result.append({xi: v}) elif xi: # there might be a non-linear solution if xi is not 0 nonlin_s.append(s) if not nonlin_s: return result for s in nonlin_s: try: soln = _solve(f, s, **flags) for sol in soln: if sol[s].free_symbols & got_s: # depends on previously solved symbols: ignore continue got_s.add(s) result.append(sol) except NotImplementedError: continue if got_s: return result else: raise NotImplementedError(not_impl_msg % f) # solve f for a single variable symbol = symbols[0] # expand binomials only if it has the unknown symbol f = f.replace(lambda e: isinstance(e, binomial) and e.has(symbol), lambda e: expand_func(e)) # checking will be done unless it is turned off before making a # recursive call; the variables `checkdens` and `check` are # captured here (for reference below) in case flag value changes flags['check'] = checkdens = check = flags.pop('check', True) # build up solutions if f is a Mul if f.is_Mul: result = set() for m in f.args: if m in {S.NegativeInfinity, S.ComplexInfinity, S.Infinity}: result = set() break soln = _vsolve(m, symbol, **flags) result.update(set(soln)) result = [{symbol: v} for v in result] if check: # all solutions have been checked but now we must # check that the solutions do not set denominators # in any factor to zero dens = flags.get('_denominators', _simple_dens(f, symbols)) result = [s for s in result if not any(checksol(den, s, **flags) for den in dens)] # set flags for quick exit at end; solutions for each # factor were already checked and simplified check = False flags['simplify'] = False elif f.is_Piecewise: result = set() for i, (expr, cond) in enumerate(f.args): if expr.is_zero: raise NotImplementedError( 'solve cannot represent interval solutions') candidates = _vsolve(expr, symbol, **flags) # the explicit condition for this expr is the current cond # and none of the previous conditions args = [~c for _, c in f.args[:i]] + [cond] cond = And(*args) for candidate in candidates: if candidate in result: # an unconditional value was already there continue try: v = cond.subs(symbol, candidate) _eval_simplify = getattr(v, '_eval_simplify', None) if _eval_simplify is not None: # unconditionally take the simplification of v v = _eval_simplify(ratio=2, measure=lambda x: 1) except TypeError: # incompatible type with condition(s) continue if v == False: continue if v == True: result.add(candidate) else: result.add(Piecewise( (candidate, v), (S.NaN, True))) # solutions already checked and simplified # **************************************** return [{symbol: r} for r in result] else: # first see if it really depends on symbol and whether there # is only a linear solution f_num, sol = solve_linear(f, symbols=symbols) if f_num.is_zero or sol is S.NaN: return [] elif f_num.is_Symbol: # no need to check but simplify if desired if flags.get('simplify', True): sol = simplify(sol) return [{f_num: sol}] poly = None # check for a single Add generator if not f_num.is_Add: add_args = [i for i in f_num.atoms(Add) if symbol in i.free_symbols] if len(add_args) == 1: gen = add_args[0] spart = gen.as_independent(symbol)[1].as_base_exp()[0] if spart == symbol: try: poly = Poly(f_num, spart) except PolynomialError: pass result = False # no solution was obtained msg = '' # there is no failure message # Poly is generally robust enough to convert anything to # a polynomial and tell us the different generators that it # contains, so we will inspect the generators identified by # polys to figure out what to do. # try to identify a single generator that will allow us to solve this # as a polynomial, followed (perhaps) by a change of variables if the # generator is not a symbol try: if poly is None: poly = Poly(f_num) if poly is None: raise ValueError('could not convert %s to Poly' % f_num) except GeneratorsNeeded: simplified_f = simplify(f_num) if simplified_f != f_num: return _solve(simplified_f, symbol, **flags) raise ValueError('expression appears to be a constant') gens = [g for g in poly.gens if g.has(symbol)] def _as_base_q(x): """Return (b**e, q) for x = b**(p*e/q) where p/q is the leading Rational of the exponent of x, e.g. exp(-2*x/3) -> (exp(x), 3) """ b, e = x.as_base_exp() if e.is_Rational: return b, e.q if not e.is_Mul: return x, 1 c, ee = e.as_coeff_Mul() if c.is_Rational and c is not S.One: # c could be a Float return b**ee, c.q return x, 1 if len(gens) > 1: # If there is more than one generator, it could be that the # generators have the same base but different powers, e.g. # >>> Poly(exp(x) + 1/exp(x)) # Poly(exp(-x) + exp(x), exp(-x), exp(x), domain='ZZ') # # If unrad was not disabled then there should be no rational # exponents appearing as in # >>> Poly(sqrt(x) + sqrt(sqrt(x))) # Poly(sqrt(x) + x**(1/4), sqrt(x), x**(1/4), domain='ZZ') bases, qs = list(zip(*[_as_base_q(g) for g in gens])) bases = set(bases) if len(bases) > 1 or not all(q == 1 for q in qs): funcs = {b for b in bases if b.is_Function} trig = {_ for _ in funcs if isinstance(_, TrigonometricFunction)} other = funcs - trig if not other and len(funcs.intersection(trig)) > 1: newf = None if f_num.is_Add and len(f_num.args) == 2: # check for sin(x)**p = cos(x)**p _args = f_num.args t = a, b = [i.atoms(Function).intersection( trig) for i in _args] if all(len(i) == 1 for i in t): a, b = [i.pop() for i in t] if isinstance(a, cos): a, b = b, a _args = _args[::-1] if isinstance(a, sin) and isinstance(b, cos ) and a.args[0] == b.args[0]: # sin(x) + cos(x) = 0 -> tan(x) + 1 = 0 newf, _d = (TR2i(_args[0]/_args[1]) + 1 ).as_numer_denom() if not _d.is_Number: newf = None if newf is None: newf = TR1(f_num).rewrite(tan) if newf != f_num: # don't check the rewritten form --check # solutions in the un-rewritten form below flags['check'] = False result = _solve(newf, symbol, **flags) flags['check'] = check # just a simple case - see if replacement of single function # clears all symbol-dependent functions, e.g. # log(x) - log(log(x) - 1) - 3 can be solved even though it has # two generators. if result is False and funcs: funcs = list(ordered(funcs)) # put shallowest function first f1 = funcs[0] t = Dummy('t') # perform the substitution ftry = f_num.subs(f1, t) # if no Functions left, we can proceed with usual solve if not ftry.has(symbol): cv_sols = _solve(ftry, t, **flags) cv_inv = list(ordered(_vsolve(t - f1, symbol, **flags)))[0] result = [{symbol: cv_inv.subs(sol)} for sol in cv_sols] if result is False: msg = 'multiple generators %s' % gens else: # e.g. case where gens are exp(x), exp(-x) u = bases.pop() t = Dummy('t') inv = _vsolve(u - t, symbol, **flags) if isinstance(u, (Pow, exp)): # this will be resolved by factor in _tsolve but we might # as well try a simple expansion here to get things in # order so something like the following will work now without # having to factor: # # >>> eq = (exp(I*(-x-2))+exp(I*(x+2))) # >>> eq.subs(exp(x),y) # fails # exp(I*(-x - 2)) + exp(I*(x + 2)) # >>> eq.expand().subs(exp(x),y) # works # y**I*exp(2*I) + y**(-I)*exp(-2*I) def _expand(p): b, e = p.as_base_exp() e = expand_mul(e) return expand_power_exp(b**e) ftry = f_num.replace( lambda w: w.is_Pow or isinstance(w, exp), _expand).subs(u, t) if not ftry.has(symbol): soln = _solve(ftry, t, **flags) result = [{symbol: i.subs(s)} for i in inv for s in soln] elif len(gens) == 1: # There is only one generator that we are interested in, but # there may have been more than one generator identified by # polys (e.g. for symbols other than the one we are interested # in) so recast the poly in terms of our generator of interest. # Also use composite=True with f_num since Poly won't update # poly as documented in issue 8810. poly = Poly(f_num, gens[0], composite=True) # if we aren't on the tsolve-pass, use roots if not flags.pop('tsolve', False): soln = None deg = poly.degree() flags['tsolve'] = True hints = ('cubics', 'quartics', 'quintics') solvers = {h: flags.get(h) for h in hints} soln = roots(poly, **solvers) if sum(soln.values()) < deg: # e.g. roots(32*x**5 + 400*x**4 + 2032*x**3 + # 5000*x**2 + 6250*x + 3189) -> {} # so all_roots is used and RootOf instances are # returned *unless* the system is multivariate # or high-order EX domain. try: soln = poly.all_roots() except NotImplementedError: if not flags.get('incomplete', True): raise NotImplementedError( filldedent(''' Neither high-order multivariate polynomials nor sorting of EX-domain polynomials is supported. If you want to see any results, pass keyword incomplete=True to solve; to see numerical values of roots for univariate expressions, use nroots. ''')) else: pass else: soln = list(soln.keys()) if soln is not None: u = poly.gen if u != symbol: try: t = Dummy('t') inv = _vsolve(u - t, symbol, **flags) soln = {i.subs(t, s) for i in inv for s in soln} except NotImplementedError: # perhaps _tsolve can handle f_num soln = None else: check = False # only dens need to be checked if soln is not None: if len(soln) > 2: # if the flag wasn't set then unset it since high-order # results are quite long. Perhaps one could base this # decision on a certain critical length of the # roots. In addition, wester test M2 has an expression # whose roots can be shown to be real with the # unsimplified form of the solution whereas only one of # the simplified forms appears to be real. flags['simplify'] = flags.get('simplify', False) if soln is not None: result = [{symbol: v} for v in soln] # fallback if above fails # ----------------------- if result is False: # try unrad if flags.pop('_unrad', True): try: u = unrad(f_num, symbol) except (ValueError, NotImplementedError): u = False if u: eq, cov = u if cov: isym, ieq = cov inv = _vsolve(ieq, symbol, **flags)[0] rv = {inv.subs(xi) for xi in _solve(eq, isym, **flags)} else: try: rv = set(_vsolve(eq, symbol, **flags)) except NotImplementedError: rv = None if rv is not None: result = [{symbol: v} for v in rv] # if the flag wasn't set then unset it since unrad results # can be quite long or of very high order flags['simplify'] = flags.get('simplify', False) else: pass # for coverage # try _tsolve if result is False: flags.pop('tsolve', None) # allow tsolve to be used on next pass try: soln = _tsolve(f_num, symbol, **flags) if soln is not None: result = [{symbol: v} for v in soln] except PolynomialError: pass # ----------- end of fallback ---------------------------- if result is False: raise NotImplementedError('\n'.join([msg, not_impl_msg % f])) result = _remove_duplicate_solutions(result) if flags.get('simplify', True): result = [{k: d[k].simplify() for k in d} for d in result] # Simplification might reveal more duplicates result = _remove_duplicate_solutions(result) # we just simplified the solution so we now set the flag to # False so the simplification doesn't happen again in checksol() flags['simplify'] = False if checkdens: # reject any result that makes any denom. affirmatively 0; # if in doubt, keep it dens = _simple_dens(f, symbols) result = [r for r in result if not any(checksol(d, r, **flags) for d in dens)] if check: # keep only results if the check is not False result = [r for r in result if checksol(f_num, r, **flags) is not False] return result def _remove_duplicate_solutions(solutions: list[dict[Expr, Expr]] ) -> list[dict[Expr, Expr]]: """Remove duplicates from a list of dicts""" solutions_set = set() solutions_new = [] for sol in solutions: solset = frozenset(sol.items()) if solset not in solutions_set: solutions_new.append(sol) solutions_set.add(solset) return solutions_new def _solve_system(exprs, symbols, **flags): """return ``(linear, solution)`` where ``linear`` is True if the system was linear, else False; ``solution`` is a list of dictionaries giving solutions for the symbols """ if not exprs: return False, [] if flags.pop('_split', True): # Split the system into connected components V = exprs symsset = set(symbols) exprsyms = {e: e.free_symbols & symsset for e in exprs} E = [] sym_indices = {sym: i for i, sym in enumerate(symbols)} for n, e1 in enumerate(exprs): for e2 in exprs[:n]: # Equations are connected if they share a symbol if exprsyms[e1] & exprsyms[e2]: E.append((e1, e2)) G = V, E subexprs = connected_components(G) if len(subexprs) > 1: subsols = [] linear = True for subexpr in subexprs: subsyms = set() for e in subexpr: subsyms |= exprsyms[e] subsyms = list(sorted(subsyms, key = lambda x: sym_indices[x])) flags['_split'] = False # skip split step _linear, subsol = _solve_system(subexpr, subsyms, **flags) if linear: linear = linear and _linear if not isinstance(subsol, list): subsol = [subsol] subsols.append(subsol) # Full solution is cartesion product of subsystems sols = [] for soldicts in product(*subsols): sols.append(dict(item for sd in soldicts for item in sd.items())) return linear, sols polys = [] dens = set() failed = [] result = [] solved_syms = [] linear = True manual = flags.get('manual', False) checkdens = check = flags.get('check', True) for j, g in enumerate(exprs): dens.update(_simple_dens(g, symbols)) i, d = _invert(g, *symbols) if d in symbols: if linear: linear = solve_linear(g, 0, [d])[0] == d g = d - i g = g.as_numer_denom()[0] if manual: failed.append(g) continue poly = g.as_poly(*symbols, extension=True) if poly is not None: polys.append(poly) else: failed.append(g) if polys: if all(p.is_linear for p in polys): n, m = len(polys), len(symbols) matrix = zeros(n, m + 1) for i, poly in enumerate(polys): for monom, coeff in poly.terms(): try: j = monom.index(1) matrix[i, j] = coeff except ValueError: matrix[i, m] = -coeff # returns a dictionary ({symbols: values}) or None if flags.pop('particular', False): result = minsolve_linear_system(matrix, *symbols, **flags) else: result = solve_linear_system(matrix, *symbols, **flags) result = [result] if result else [] if failed: if result: solved_syms = list(result[0].keys()) # there is only one result dict else: solved_syms = [] # linear doesn't change else: linear = False if len(symbols) > len(polys): free = set().union(*[p.free_symbols for p in polys]) free = list(ordered(free.intersection(symbols))) got_s = set() result = [] for syms in subsets(free, len(polys)): try: # returns [], None or list of tuples res = solve_poly_system(polys, *syms) if res: for r in set(res): skip = False for r1 in r: if got_s and any(ss in r1.free_symbols for ss in got_s): # sol depends on previously # solved symbols: discard it skip = True if not skip: got_s.update(syms) result.append(dict(list(zip(syms, r)))) except NotImplementedError: pass if got_s: solved_syms = list(got_s) else: raise NotImplementedError('no valid subset found') else: try: result = solve_poly_system(polys, *symbols) if result: solved_syms = symbols result = [dict(list(zip(solved_syms, r))) for r in set(result)] except NotImplementedError: failed.extend([g.as_expr() for g in polys]) solved_syms = [] # convert None or [] to [{}] result = result or [{}] if failed: linear = False # For each failed equation, see if we can solve for one of the # remaining symbols from that equation. If so, we update the # solution set and continue with the next failed equation, # repeating until we are done or we get an equation that can't # be solved. def _ok_syms(e, sort=False): rv = e.free_symbols & legal # Solve first for symbols that have lower degree in the equation. # Ideally we want to solve firstly for symbols that appear linearly # with rational coefficients e.g. if e = x*y + z then we should # solve for z first. def key(sym): ep = e.as_poly(sym) if ep is None: complexity = (S.Infinity, S.Infinity, S.Infinity) else: coeff_syms = ep.LC().free_symbols complexity = (ep.degree(), len(coeff_syms & rv), len(coeff_syms)) return complexity + (default_sort_key(sym),) if sort: rv = sorted(rv, key=key) return rv legal = set(symbols) # what we are interested in # sort so equation with the fewest potential symbols is first u = Dummy() # used in solution checking for eq in ordered(failed, lambda _: len(_ok_syms(_))): newresult = [] bad_results = [] hit = False for r in result: got_s = set() # update eq with everything that is known so far eq2 = eq.subs(r) # if check is True then we see if it satisfies this # equation, otherwise we just accept it if check and r: b = checksol(u, u, eq2, minimal=True) if b is not None: # this solution is sufficient to know whether # it is valid or not so we either accept or # reject it, then continue if b: newresult.append(r) else: bad_results.append(r) continue # search for a symbol amongst those available that # can be solved for ok_syms = _ok_syms(eq2, sort=True) if not ok_syms: if r: newresult.append(r) break # skip as it's independent of desired symbols for s in ok_syms: try: soln = _vsolve(eq2, s, **flags) except NotImplementedError: continue # put each solution in r and append the now-expanded # result in the new result list; use copy since the # solution for s is being added in-place for sol in soln: if got_s and any(ss in sol.free_symbols for ss in got_s): # sol depends on previously solved symbols: discard it continue rnew = r.copy() for k, v in r.items(): rnew[k] = v.subs(s, sol) # and add this new solution rnew[s] = sol # check that it is independent of previous solutions iset = set(rnew.items()) for i in newresult: if len(i) < len(iset) and not set(i.items()) - iset: # this is a superset of a known solution that # is smaller break else: # keep it newresult.append(rnew) hit = True got_s.add(s) if not hit: raise NotImplementedError('could not solve %s' % eq2) else: result = newresult for b in bad_results: if b in result: result.remove(b) if not result: return False, [] # rely on linear/polynomial system solvers to simplify # XXX the following tests show that the expressions # returned are not the same as they would be if simplify # were applied to this: # sympy/solvers/ode/tests/test_systems/test__classify_linear_system # sympy/solvers/tests/test_solvers/test_issue_4886 # so the docs should be updated to reflect that or else # the following should be `bool(failed) or not linear` default_simplify = bool(failed) if flags.get('simplify', default_simplify): for r in result: for k in r: r[k] = simplify(r[k]) flags['simplify'] = False # don't need to do so in checksol now if checkdens: result = [r for r in result if not any(checksol(d, r, **flags) for d in dens)] if check and not linear: result = [r for r in result if not any(checksol(e, r, **flags) is False for e in exprs)] result = [r for r in result if r] return linear, result def solve_linear(lhs, rhs=0, symbols=[], exclude=[]): r""" Return a tuple derived from ``f = lhs - rhs`` that is one of the following: ``(0, 1)``, ``(0, 0)``, ``(symbol, solution)``, ``(n, d)``. Explanation =========== ``(0, 1)`` meaning that ``f`` is independent of the symbols in *symbols* that are not in *exclude*. ``(0, 0)`` meaning that there is no solution to the equation amongst the symbols given. If the first element of the tuple is not zero, then the function is guaranteed to be dependent on a symbol in *symbols*. ``(symbol, solution)`` where symbol appears linearly in the numerator of ``f``, is in *symbols* (if given), and is not in *exclude* (if given). No simplification is done to ``f`` other than a ``mul=True`` expansion, so the solution will correspond strictly to a unique solution. ``(n, d)`` where ``n`` and ``d`` are the numerator and denominator of ``f`` when the numerator was not linear in any symbol of interest; ``n`` will never be a symbol unless a solution for that symbol was found (in which case the second element is the solution, not the denominator). Examples ======== >>> from sympy import cancel, Pow ``f`` is independent of the symbols in *symbols* that are not in *exclude*: >>> from sympy import cos, sin, solve_linear >>> from sympy.abc import x, y, z >>> eq = y*cos(x)**2 + y*sin(x)**2 - y # = y*(1 - 1) = 0 >>> solve_linear(eq) (0, 1) >>> eq = cos(x)**2 + sin(x)**2 # = 1 >>> solve_linear(eq) (0, 1) >>> solve_linear(x, exclude=[x]) (0, 1) The variable ``x`` appears as a linear variable in each of the following: >>> solve_linear(x + y**2) (x, -y**2) >>> solve_linear(1/x - y**2) (x, y**(-2)) When not linear in ``x`` or ``y`` then the numerator and denominator are returned: >>> solve_linear(x**2/y**2 - 3) (x**2 - 3*y**2, y**2) If the numerator of the expression is a symbol, then ``(0, 0)`` is returned if the solution for that symbol would have set any denominator to 0: >>> eq = 1/(1/x - 2) >>> eq.as_numer_denom() (x, 1 - 2*x) >>> solve_linear(eq) (0, 0) But automatic rewriting may cause a symbol in the denominator to appear in the numerator so a solution will be returned: >>> (1/x)**-1 x >>> solve_linear((1/x)**-1) (x, 0) Use an unevaluated expression to avoid this: >>> solve_linear(Pow(1/x, -1, evaluate=False)) (0, 0) If ``x`` is allowed to cancel in the following expression, then it appears to be linear in ``x``, but this sort of cancellation is not done by ``solve_linear`` so the solution will always satisfy the original expression without causing a division by zero error. >>> eq = x**2*(1/x - z**2/x) >>> solve_linear(cancel(eq)) (x, 0) >>> solve_linear(eq) (x**2*(1 - z**2), x) A list of symbols for which a solution is desired may be given: >>> solve_linear(x + y + z, symbols=[y]) (y, -x - z) A list of symbols to ignore may also be given: >>> solve_linear(x + y + z, exclude=[x]) (y, -x - z) (A solution for ``y`` is obtained because it is the first variable from the canonically sorted list of symbols that had a linear solution.) """ if isinstance(lhs, Eq): if rhs: raise ValueError(filldedent(''' If lhs is an Equality, rhs must be 0 but was %s''' % rhs)) rhs = lhs.rhs lhs = lhs.lhs dens = None eq = lhs - rhs n, d = eq.as_numer_denom() if not n: return S.Zero, S.One free = n.free_symbols if not symbols: symbols = free else: bad = [s for s in symbols if not s.is_Symbol] if bad: if len(bad) == 1: bad = bad[0] if len(symbols) == 1: eg = 'solve(%s, %s)' % (eq, symbols[0]) else: eg = 'solve(%s, *%s)' % (eq, list(symbols)) raise ValueError(filldedent(''' solve_linear only handles symbols, not %s. To isolate non-symbols use solve, e.g. >>> %s <<<. ''' % (bad, eg))) symbols = free.intersection(symbols) symbols = symbols.difference(exclude) if not symbols: return S.Zero, S.One # derivatives are easy to do but tricky to analyze to see if they # are going to disallow a linear solution, so for simplicity we # just evaluate the ones that have the symbols of interest derivs = defaultdict(list) for der in n.atoms(Derivative): csym = der.free_symbols & symbols for c in csym: derivs[c].append(der) all_zero = True for xi in sorted(symbols, key=default_sort_key): # canonical order # if there are derivatives in this var, calculate them now if isinstance(derivs[xi], list): derivs[xi] = {der: der.doit() for der in derivs[xi]} newn = n.subs(derivs[xi]) dnewn_dxi = newn.diff(xi) # dnewn_dxi can be nonzero if it survives differentation by any # of its free symbols free = dnewn_dxi.free_symbols if dnewn_dxi and (not free or any(dnewn_dxi.diff(s) for s in free) or free == symbols): all_zero = False if dnewn_dxi is S.NaN: break if xi not in dnewn_dxi.free_symbols: vi = -1/dnewn_dxi*(newn.subs(xi, 0)) if dens is None: dens = _simple_dens(eq, symbols) if not any(checksol(di, {xi: vi}, minimal=True) is True for di in dens): # simplify any trivial integral irep = [(i, i.doit()) for i in vi.atoms(Integral) if i.function.is_number] # do a slight bit of simplification vi = expand_mul(vi.subs(irep)) return xi, vi if all_zero: return S.Zero, S.One if n.is_Symbol: # no solution for this symbol was found return S.Zero, S.Zero return n, d def minsolve_linear_system(system, *symbols, **flags): r""" Find a particular solution to a linear system. Explanation =========== In particular, try to find a solution with the minimal possible number of non-zero variables using a naive algorithm with exponential complexity. If ``quick=True``, a heuristic is used. """ quick = flags.get('quick', False) # Check if there are any non-zero solutions at all s0 = solve_linear_system(system, *symbols, **flags) if not s0 or all(v == 0 for v in s0.values()): return s0 if quick: # We just solve the system and try to heuristically find a nice # solution. s = solve_linear_system(system, *symbols) def update(determined, solution): delete = [] for k, v in solution.items(): solution[k] = v.subs(determined) if not solution[k].free_symbols: delete.append(k) determined[k] = solution[k] for k in delete: del solution[k] determined = {} update(determined, s) while s: # NOTE sort by default_sort_key to get deterministic result k = max((k for k in s.values()), key=lambda x: (len(x.free_symbols), default_sort_key(x))) kfree = k.free_symbols x = next(reversed(list(ordered(kfree)))) if len(kfree) != 1: determined[x] = S.Zero else: val = _vsolve(k, x, check=False)[0] if not val and not any(v.subs(x, val) for v in s.values()): determined[x] = S.One else: determined[x] = val update(determined, s) return determined else: # We try to select n variables which we want to be non-zero. # All others will be assumed zero. We try to solve the modified system. # If there is a non-trivial solution, just set the free variables to # one. If we do this for increasing n, trying all combinations of # variables, we will find an optimal solution. # We speed up slightly by starting at one less than the number of # variables the quick method manages. N = len(symbols) bestsol = minsolve_linear_system(system, *symbols, quick=True) n0 = len([x for x in bestsol.values() if x != 0]) for n in range(n0 - 1, 1, -1): debugf('minsolve: %s', n) thissol = None for nonzeros in combinations(range(N), n): subm = Matrix([system.col(i).T for i in nonzeros] + [system.col(-1).T]).T s = solve_linear_system(subm, *[symbols[i] for i in nonzeros]) if s and not all(v == 0 for v in s.values()): subs = [(symbols[v], S.One) for v in nonzeros] for k, v in s.items(): s[k] = v.subs(subs) for sym in symbols: if sym not in s: if symbols.index(sym) in nonzeros: s[sym] = S.One else: s[sym] = S.Zero thissol = s break if thissol is None: break bestsol = thissol return bestsol def solve_linear_system(system, *symbols, **flags): r""" Solve system of $N$ linear equations with $M$ variables, which means both under- and overdetermined systems are supported. Explanation =========== The possible number of solutions is zero, one, or infinite. Respectively, this procedure will return None or a dictionary with solutions. In the case of underdetermined systems, all arbitrary parameters are skipped. This may cause a situation in which an empty dictionary is returned. In that case, all symbols can be assigned arbitrary values. Input to this function is a $N\times M + 1$ matrix, which means it has to be in augmented form. If you prefer to enter $N$ equations and $M$ unknowns then use ``solve(Neqs, *Msymbols)`` instead. Note: a local copy of the matrix is made by this routine so the matrix that is passed will not be modified. The algorithm used here is fraction-free Gaussian elimination, which results, after elimination, in an upper-triangular matrix. Then solutions are found using back-substitution. This approach is more efficient and compact than the Gauss-Jordan method. Examples ======== >>> from sympy import Matrix, solve_linear_system >>> from sympy.abc import x, y Solve the following system:: x + 4 y == 2 -2 x + y == 14 >>> system = Matrix(( (1, 4, 2), (-2, 1, 14))) >>> solve_linear_system(system, x, y) {x: -6, y: 2} A degenerate system returns an empty dictionary: >>> system = Matrix(( (0,0,0), (0,0,0) )) >>> solve_linear_system(system, x, y) {} """ assert system.shape[1] == len(symbols) + 1 # This is just a wrapper for solve_lin_sys eqs = list(system * Matrix(symbols + (-1,))) eqs, ring = sympy_eqs_to_ring(eqs, symbols) sol = solve_lin_sys(eqs, ring, _raw=False) if sol is not None: sol = {sym:val for sym, val in sol.items() if sym != val} return sol def solve_undetermined_coeffs(equ, coeffs, *syms, **flags): r""" Solve a system of equations in $k$ parameters that is formed by matching coefficients in variables ``coeffs`` that are on factors dependent on the remaining variables (or those given explicitly by ``syms``. Explanation =========== The result of this function is a dictionary with symbolic values of those parameters with respect to coefficients in $q$ -- empty if there is no solution or coefficients do not appear in the equation -- else None (if the system was not recognized). If there is more than one solution, the solutions are passed as a list. The output can be modified using the same semantics as for `solve` since the flags that are passed are sent directly to `solve` so, for example the flag ``dict=True`` will always return a list of solutions as dictionaries. This function accepts both Equality and Expr class instances. The solving process is most efficient when symbols are specified in addition to parameters to be determined, but an attempt to determine them (if absent) will be made. If an expected solution is not obtained (and symbols were not specified) try specifying them. Examples ======== >>> from sympy import Eq, solve_undetermined_coeffs >>> from sympy.abc import a, b, c, h, p, k, x, y >>> solve_undetermined_coeffs(Eq(a*x + a + b, x/2), [a, b], x) {a: 1/2, b: -1/2} >>> solve_undetermined_coeffs(a - 2, [a]) {a: 2} The equation can be nonlinear in the symbols: >>> X, Y, Z = y, x**y, y*x**y >>> eq = a*X + b*Y + c*Z - X - 2*Y - 3*Z >>> coeffs = a, b, c >>> syms = x, y >>> solve_undetermined_coeffs(eq, coeffs, syms) {a: 1, b: 2, c: 3} And the system can be nonlinear in coefficients, too, but if there is only a single solution, it will be returned as a dictionary: >>> eq = a*x**2 + b*x + c - ((x - h)**2 + 4*p*k)/4/p >>> solve_undetermined_coeffs(eq, (h, p, k), x) {h: -b/(2*a), k: (4*a*c - b**2)/(4*a), p: 1/(4*a)} Multiple solutions are always returned in a list: >>> solve_undetermined_coeffs(a**2*x + b - x, [a, b], x) [{a: -1, b: 0}, {a: 1, b: 0}] Using flag ``dict=True`` (in keeping with semantics in :func:`~.solve`) will force the result to always be a list with any solutions as elements in that list. >>> solve_undetermined_coeffs(a*x - 2*x, [a], dict=True) [{a: 2}] """ if not (coeffs and all(i.is_Symbol for i in coeffs)): raise ValueError('must provide symbols for coeffs') if isinstance(equ, Eq): eq = equ.lhs - equ.rhs else: eq = equ ceq = cancel(eq) xeq = _mexpand(ceq.as_numer_denom()[0], recursive=True) free = xeq.free_symbols coeffs = free & set(coeffs) if not coeffs: return ([], {}) if flags.get('set', None) else [] # solve(0, x) -> [] if not syms: # e.g. A*exp(x) + B - (exp(x) + y) separated into parts that # don't/do depend on coeffs gives # -(exp(x) + y), A*exp(x) + B # then see what symbols are common to both # {x} = {x, A, B} - {x, y} ind, dep = xeq.as_independent(*coeffs, as_Add=True) dfree = dep.free_symbols syms = dfree & ind.free_symbols if not syms: # but if the system looks like (a + b)*x + b - c # then {} = {a, b, x} - c # so calculate {x} = {a, b, x} - {a, b} syms = dfree - set(coeffs) if not syms: syms = [Dummy()] else: if len(syms) == 1 and iterable(syms[0]): syms = syms[0] e, s, _ = recast_to_symbols([xeq], syms) xeq = e[0] syms = s # find the functional forms in which symbols appear gens = set(xeq.as_coefficients_dict(*syms).keys()) - {1} cset = set(coeffs) if any(g.has_xfree(cset) for g in gens): return # a generator contained a coefficient symbol # make sure we are working with symbols for generators e, gens, _ = recast_to_symbols([xeq], list(gens)) xeq = e[0] # collect coefficients in front of generators system = list(collect(xeq, gens, evaluate=False).values()) # get a solution soln = solve(system, coeffs, **flags) # unpack unless told otherwise if length is 1 settings = flags.get('dict', None) or flags.get('set', None) if type(soln) is dict or settings or len(soln) != 1: return soln return soln[0] def solve_linear_system_LU(matrix, syms): """ Solves the augmented matrix system using ``LUsolve`` and returns a dictionary in which solutions are keyed to the symbols of *syms* as ordered. Explanation =========== The matrix must be invertible. Examples ======== >>> from sympy import Matrix, solve_linear_system_LU >>> from sympy.abc import x, y, z >>> solve_linear_system_LU(Matrix([ ... [1, 2, 0, 1], ... [3, 2, 2, 1], ... [2, 0, 0, 1]]), [x, y, z]) {x: 1/2, y: 1/4, z: -1/2} See Also ======== LUsolve """ if matrix.rows != matrix.cols - 1: raise ValueError("Rows should be equal to columns - 1") A = matrix[:matrix.rows, :matrix.rows] b = matrix[:, matrix.cols - 1:] soln = A.LUsolve(b) solutions = {} for i in range(soln.rows): solutions[syms[i]] = soln[i, 0] return solutions def det_perm(M): """ Return the determinant of *M* by using permutations to select factors. Explanation =========== For sizes larger than 8 the number of permutations becomes prohibitively large, or if there are no symbols in the matrix, it is better to use the standard determinant routines (e.g., ``M.det()``.) See Also ======== det_minor det_quick """ args = [] s = True n = M.rows list_ = M.flat() for perm in generate_bell(n): fac = [] idx = 0 for j in perm: fac.append(list_[idx + j]) idx += n term = Mul(*fac) # disaster with unevaluated Mul -- takes forever for n=7 args.append(term if s else -term) s = not s return Add(*args) def det_minor(M): """ Return the ``det(M)`` computed from minors without introducing new nesting in products. See Also ======== det_perm det_quick """ n = M.rows if n == 2: return M[0, 0]*M[1, 1] - M[1, 0]*M[0, 1] else: return sum([(1, -1)[i % 2]*Add(*[M[0, i]*d for d in Add.make_args(det_minor(M.minor_submatrix(0, i)))]) if M[0, i] else S.Zero for i in range(n)]) def det_quick(M, method=None): """ Return ``det(M)`` assuming that either there are lots of zeros or the size of the matrix is small. If this assumption is not met, then the normal Matrix.det function will be used with method = ``method``. See Also ======== det_minor det_perm """ if any(i.has(Symbol) for i in M): if M.rows < 8 and all(i.has(Symbol) for i in M): return det_perm(M) return det_minor(M) else: return M.det(method=method) if method else M.det() def inv_quick(M): """Return the inverse of ``M``, assuming that either there are lots of zeros or the size of the matrix is small. """ if not all(i.is_Number for i in M): if not any(i.is_Number for i in M): det = lambda _: det_perm(_) else: det = lambda _: det_minor(_) else: return M.inv() n = M.rows d = det(M) if d == S.Zero: raise NonInvertibleMatrixError("Matrix det == 0; not invertible") ret = zeros(n) s1 = -1 for i in range(n): s = s1 = -s1 for j in range(n): di = det(M.minor_submatrix(i, j)) ret[j, i] = s*di/d s = -s return ret # these are functions that have multiple inverse values per period multi_inverses = { sin: lambda x: (asin(x), S.Pi - asin(x)), cos: lambda x: (acos(x), 2*S.Pi - acos(x)), } def _vsolve(e, s, **flags): """return list of scalar values for the solution of e for symbol s""" return [i[s] for i in _solve(e, s, **flags)] def _tsolve(eq, sym, **flags): """ Helper for ``_solve`` that solves a transcendental equation with respect to the given symbol. Various equations containing powers and logarithms, can be solved. There is currently no guarantee that all solutions will be returned or that a real solution will be favored over a complex one. Either a list of potential solutions will be returned or None will be returned (in the case that no method was known to get a solution for the equation). All other errors (like the inability to cast an expression as a Poly) are unhandled. Examples ======== >>> from sympy import log, ordered >>> from sympy.solvers.solvers import _tsolve as tsolve >>> from sympy.abc import x >>> list(ordered(tsolve(3**(2*x + 5) - 4, x))) [-5/2 + log(2)/log(3), (-5*log(3)/2 + log(2) + I*pi)/log(3)] >>> tsolve(log(x) + 2*x, x) [LambertW(2)/2] """ if 'tsolve_saw' not in flags: flags['tsolve_saw'] = [] if eq in flags['tsolve_saw']: return None else: flags['tsolve_saw'].append(eq) rhs, lhs = _invert(eq, sym) if lhs == sym: return [rhs] try: if lhs.is_Add: # it's time to try factoring; powdenest is used # to try get powers in standard form for better factoring f = factor(powdenest(lhs - rhs)) if f.is_Mul: return _vsolve(f, sym, **flags) if rhs: f = logcombine(lhs, force=flags.get('force', True)) if f.count(log) != lhs.count(log): if isinstance(f, log): return _vsolve(f.args[0] - exp(rhs), sym, **flags) return _tsolve(f - rhs, sym, **flags) elif lhs.is_Pow: if lhs.exp.is_Integer: if lhs - rhs != eq: return _vsolve(lhs - rhs, sym, **flags) if sym not in lhs.exp.free_symbols: return _vsolve(lhs.base - rhs**(1/lhs.exp), sym, **flags) # _tsolve calls this with Dummy before passing the actual number in. if any(t.is_Dummy for t in rhs.free_symbols): raise NotImplementedError # _tsolve will call here again... # a ** g(x) == 0 if not rhs: # f(x)**g(x) only has solutions where f(x) == 0 and g(x) != 0 at # the same place sol_base = _vsolve(lhs.base, sym, **flags) return [s for s in sol_base if lhs.exp.subs(sym, s) != 0] # XXX use checksol here? # a ** g(x) == b if not lhs.base.has(sym): if lhs.base == 0: return _vsolve(lhs.exp, sym, **flags) if rhs != 0 else [] # Gets most solutions... if lhs.base == rhs.as_base_exp()[0]: # handles case when bases are equal sol = _vsolve(lhs.exp - rhs.as_base_exp()[1], sym, **flags) else: # handles cases when bases are not equal and exp # may or may not be equal f = exp(log(lhs.base)*lhs.exp) - exp(log(rhs)) sol = _vsolve(f, sym, **flags) # Check for duplicate solutions def equal(expr1, expr2): _ = Dummy() eq = checksol(expr1 - _, _, expr2) if eq is None: if nsimplify(expr1) != nsimplify(expr2): return False # they might be coincidentally the same # so check more rigorously eq = expr1.equals(expr2) # XXX expensive but necessary? return eq # Guess a rational exponent e_rat = nsimplify(log(abs(rhs))/log(abs(lhs.base))) e_rat = simplify(posify(e_rat)[0]) n, d = fraction(e_rat) if expand(lhs.base**n - rhs**d) == 0: sol = [s for s in sol if not equal(lhs.exp.subs(sym, s), e_rat)] sol.extend(_vsolve(lhs.exp - e_rat, sym, **flags)) return list(set(sol)) # f(x) ** g(x) == c else: sol = [] logform = lhs.exp*log(lhs.base) - log(rhs) if logform != lhs - rhs: try: sol.extend(_vsolve(logform, sym, **flags)) except NotImplementedError: pass # Collect possible solutions and check with substitution later. check = [] if rhs == 1: # f(x) ** g(x) = 1 -- g(x)=0 or f(x)=+-1 check.extend(_vsolve(lhs.exp, sym, **flags)) check.extend(_vsolve(lhs.base - 1, sym, **flags)) check.extend(_vsolve(lhs.base + 1, sym, **flags)) elif rhs.is_Rational: for d in (i for i in divisors(abs(rhs.p)) if i != 1): e, t = integer_log(rhs.p, d) if not t: continue # rhs.p != d**b for s in divisors(abs(rhs.q)): if s**e== rhs.q: r = Rational(d, s) check.extend(_vsolve(lhs.base - r, sym, **flags)) check.extend(_vsolve(lhs.base + r, sym, **flags)) check.extend(_vsolve(lhs.exp - e, sym, **flags)) elif rhs.is_irrational: b_l, e_l = lhs.base.as_base_exp() n, d = (e_l*lhs.exp).as_numer_denom() b, e = sqrtdenest(rhs).as_base_exp() check = [sqrtdenest(i) for i in (_vsolve(lhs.base - b, sym, **flags))] check.extend([sqrtdenest(i) for i in (_vsolve(lhs.exp - e, sym, **flags))]) if e_l*d != 1: check.extend(_vsolve(b_l**n - rhs**(e_l*d), sym, **flags)) for s in check: ok = checksol(eq, sym, s) if ok is None: ok = eq.subs(sym, s).equals(0) if ok: sol.append(s) return list(set(sol)) elif lhs.is_Function and len(lhs.args) == 1: if lhs.func in multi_inverses: # sin(x) = 1/3 -> x - asin(1/3) & x - (pi - asin(1/3)) soln = [] for i in multi_inverses[type(lhs)](rhs): soln.extend(_vsolve(lhs.args[0] - i, sym, **flags)) return list(set(soln)) elif lhs.func == LambertW: return _vsolve(lhs.args[0] - rhs*exp(rhs), sym, **flags) rewrite = lhs.rewrite(exp) if rewrite != lhs: return _vsolve(rewrite - rhs, sym, **flags) except NotImplementedError: pass # maybe it is a lambert pattern if flags.pop('bivariate', True): # lambert forms may need some help being recognized, e.g. changing # 2**(3*x) + x**3*log(2)**3 + 3*x**2*log(2)**2 + 3*x*log(2) + 1 # to 2**(3*x) + (x*log(2) + 1)**3 # make generator in log have exponent of 1 logs = eq.atoms(log) spow = min( {i.exp for j in logs for i in j.atoms(Pow) if i.base == sym} or {1}) if spow != 1: p = sym**spow u = Dummy('bivariate-cov') ueq = eq.subs(p, u) if not ueq.has_free(sym): sol = _vsolve(ueq, u, **flags) inv = _vsolve(p - u, sym) return [i.subs(u, s) for i in inv for s in sol] g = _filtered_gens(eq.as_poly(), sym) up_or_log = set() for gi in g: if isinstance(gi, (exp, log)) or (gi.is_Pow and gi.base == S.Exp1): up_or_log.add(gi) elif gi.is_Pow: gisimp = powdenest(expand_power_exp(gi)) if gisimp.is_Pow and sym in gisimp.exp.free_symbols: up_or_log.add(gi) eq_down = expand_log(expand_power_exp(eq)).subs( dict(list(zip(up_or_log, [0]*len(up_or_log))))) eq = expand_power_exp(factor(eq_down, deep=True) + (eq - eq_down)) rhs, lhs = _invert(eq, sym) if lhs.has(sym): try: poly = lhs.as_poly() g = _filtered_gens(poly, sym) _eq = lhs - rhs sols = _solve_lambert(_eq, sym, g) # use a simplified form if it satisfies eq # and has fewer operations for n, s in enumerate(sols): ns = nsimplify(s) if ns != s and ns.count_ops() <= s.count_ops(): ok = checksol(_eq, sym, ns) if ok is None: ok = _eq.subs(sym, ns).equals(0) if ok: sols[n] = ns return sols except NotImplementedError: # maybe it's a convoluted function if len(g) == 2: try: gpu = bivariate_type(lhs - rhs, *g) if gpu is None: raise NotImplementedError g, p, u = gpu flags['bivariate'] = False inversion = _tsolve(g - u, sym, **flags) if inversion: sol = _vsolve(p, u, **flags) return list({i.subs(u, s) for i in inversion for s in sol}) except NotImplementedError: pass else: pass if flags.pop('force', True): flags['force'] = False pos, reps = posify(lhs - rhs) if rhs == S.ComplexInfinity: return [] for u, s in reps.items(): if s == sym: break else: u = sym if pos.has(u): try: soln = _vsolve(pos, u, **flags) return [s.subs(reps) for s in soln] except NotImplementedError: pass else: pass # here for coverage return # here for coverage # TODO: option for calculating J numerically @conserve_mpmath_dps def nsolve(*args, dict=False, **kwargs): r""" Solve a nonlinear equation system numerically: ``nsolve(f, [args,] x0, modules=['mpmath'], **kwargs)``. Explanation =========== ``f`` is a vector function of symbolic expressions representing the system. *args* are the variables. If there is only one variable, this argument can be omitted. ``x0`` is a starting vector close to a solution. Use the modules keyword to specify which modules should be used to evaluate the function and the Jacobian matrix. Make sure to use a module that supports matrices. For more information on the syntax, please see the docstring of ``lambdify``. If the keyword arguments contain ``dict=True`` (default is False) ``nsolve`` will return a list (perhaps empty) of solution mappings. This might be especially useful if you want to use ``nsolve`` as a fallback to solve since using the dict argument for both methods produces return values of consistent type structure. Please note: to keep this consistent with ``solve``, the solution will be returned in a list even though ``nsolve`` (currently at least) only finds one solution at a time. Overdetermined systems are supported. Examples ======== >>> from sympy import Symbol, nsolve >>> import mpmath >>> mpmath.mp.dps = 15 >>> x1 = Symbol('x1') >>> x2 = Symbol('x2') >>> f1 = 3 * x1**2 - 2 * x2**2 - 1 >>> f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8 >>> print(nsolve((f1, f2), (x1, x2), (-1, 1))) Matrix([[-1.19287309935246], [1.27844411169911]]) For one-dimensional functions the syntax is simplified: >>> from sympy import sin, nsolve >>> from sympy.abc import x >>> nsolve(sin(x), x, 2) 3.14159265358979 >>> nsolve(sin(x), 2) 3.14159265358979 To solve with higher precision than the default, use the prec argument: >>> from sympy import cos >>> nsolve(cos(x) - x, 1) 0.739085133215161 >>> nsolve(cos(x) - x, 1, prec=50) 0.73908513321516064165531208767387340401341175890076 >>> cos(_) 0.73908513321516064165531208767387340401341175890076 To solve for complex roots of real functions, a nonreal initial point must be specified: >>> from sympy import I >>> nsolve(x**2 + 2, I) 1.4142135623731*I ``mpmath.findroot`` is used and you can find their more extensive documentation, especially concerning keyword parameters and available solvers. Note, however, that functions which are very steep near the root, the verification of the solution may fail. In this case you should use the flag ``verify=False`` and independently verify the solution. >>> from sympy import cos, cosh >>> f = cos(x)*cosh(x) - 1 >>> nsolve(f, 3.14*100) Traceback (most recent call last): ... ValueError: Could not find root within given tolerance. (1.39267e+230 > 2.1684e-19) >>> ans = nsolve(f, 3.14*100, verify=False); ans 312.588469032184 >>> f.subs(x, ans).n(2) 2.1e+121 >>> (f/f.diff(x)).subs(x, ans).n(2) 7.4e-15 One might safely skip the verification if bounds of the root are known and a bisection method is used: >>> bounds = lambda i: (3.14*i, 3.14*(i + 1)) >>> nsolve(f, bounds(100), solver='bisect', verify=False) 315.730061685774 Alternatively, a function may be better behaved when the denominator is ignored. Since this is not always the case, however, the decision of what function to use is left to the discretion of the user. >>> eq = x**2/(1 - x)/(1 - 2*x)**2 - 100 >>> nsolve(eq, 0.46) Traceback (most recent call last): ... ValueError: Could not find root within given tolerance. (10000 > 2.1684e-19) Try another starting point or tweak arguments. >>> nsolve(eq.as_numer_denom()[0], 0.46) 0.46792545969349058 """ # there are several other SymPy functions that use method= so # guard against that here if 'method' in kwargs: raise ValueError(filldedent(''' Keyword "method" should not be used in this context. When using some mpmath solvers directly, the keyword "method" is used, but when using nsolve (and findroot) the keyword to use is "solver".''')) if 'prec' in kwargs: import mpmath mpmath.mp.dps = kwargs.pop('prec') # keyword argument to return result as a dictionary as_dict = dict from builtins import dict # to unhide the builtin # interpret arguments if len(args) == 3: f = args[0] fargs = args[1] x0 = args[2] if iterable(fargs) and iterable(x0): if len(x0) != len(fargs): raise TypeError('nsolve expected exactly %i guess vectors, got %i' % (len(fargs), len(x0))) elif len(args) == 2: f = args[0] fargs = None x0 = args[1] if iterable(f): raise TypeError('nsolve expected 3 arguments, got 2') elif len(args) < 2: raise TypeError('nsolve expected at least 2 arguments, got %i' % len(args)) else: raise TypeError('nsolve expected at most 3 arguments, got %i' % len(args)) modules = kwargs.get('modules', ['mpmath']) if iterable(f): f = list(f) for i, fi in enumerate(f): if isinstance(fi, Eq): f[i] = fi.lhs - fi.rhs f = Matrix(f).T if iterable(x0): x0 = list(x0) if not isinstance(f, Matrix): # assume it's a SymPy expression if isinstance(f, Eq): f = f.lhs - f.rhs syms = f.free_symbols if fargs is None: fargs = syms.copy().pop() if not (len(syms) == 1 and (fargs in syms or fargs[0] in syms)): raise ValueError(filldedent(''' expected a one-dimensional and numerical function''')) # the function is much better behaved if there is no denominator # but sending the numerator is left to the user since sometimes # the function is better behaved when the denominator is present # e.g., issue 11768 f = lambdify(fargs, f, modules) x = sympify(findroot(f, x0, **kwargs)) if as_dict: return [{fargs: x}] return x if len(fargs) > f.cols: raise NotImplementedError(filldedent(''' need at least as many equations as variables''')) verbose = kwargs.get('verbose', False) if verbose: print('f(x):') print(f) # derive Jacobian J = f.jacobian(fargs) if verbose: print('J(x):') print(J) # create functions f = lambdify(fargs, f.T, modules) J = lambdify(fargs, J, modules) # solve the system numerically x = findroot(f, x0, J=J, **kwargs) if as_dict: return [dict(zip(fargs, [sympify(xi) for xi in x]))] return Matrix(x) def _invert(eq, *symbols, **kwargs): """ Return tuple (i, d) where ``i`` is independent of *symbols* and ``d`` contains symbols. Explanation =========== ``i`` and ``d`` are obtained after recursively using algebraic inversion until an uninvertible ``d`` remains. If there are no free symbols then ``d`` will be zero. Some (but not necessarily all) solutions to the expression ``i - d`` will be related to the solutions of the original expression. Examples ======== >>> from sympy.solvers.solvers import _invert as invert >>> from sympy import sqrt, cos >>> from sympy.abc import x, y >>> invert(x - 3) (3, x) >>> invert(3) (3, 0) >>> invert(2*cos(x) - 1) (1/2, cos(x)) >>> invert(sqrt(x) - 3) (3, sqrt(x)) >>> invert(sqrt(x) + y, x) (-y, sqrt(x)) >>> invert(sqrt(x) + y, y) (-sqrt(x), y) >>> invert(sqrt(x) + y, x, y) (0, sqrt(x) + y) If there is more than one symbol in a power's base and the exponent is not an Integer, then the principal root will be used for the inversion: >>> invert(sqrt(x + y) - 2) (4, x + y) >>> invert(sqrt(x + y) - 2) (4, x + y) If the exponent is an Integer, setting ``integer_power`` to True will force the principal root to be selected: >>> invert(x**2 - 4, integer_power=True) (2, x) """ eq = sympify(eq) if eq.args: # make sure we are working with flat eq eq = eq.func(*eq.args) free = eq.free_symbols if not symbols: symbols = free if not free & set(symbols): return eq, S.Zero dointpow = bool(kwargs.get('integer_power', False)) lhs = eq rhs = S.Zero while True: was = lhs while True: indep, dep = lhs.as_independent(*symbols) # dep + indep == rhs if lhs.is_Add: # this indicates we have done it all if indep.is_zero: break lhs = dep rhs -= indep # dep * indep == rhs else: # this indicates we have done it all if indep is S.One: break lhs = dep rhs /= indep # collect like-terms in symbols if lhs.is_Add: terms = {} for a in lhs.args: i, d = a.as_independent(*symbols) terms.setdefault(d, []).append(i) if any(len(v) > 1 for v in terms.values()): args = [] for d, i in terms.items(): if len(i) > 1: args.append(Add(*i)*d) else: args.append(i[0]*d) lhs = Add(*args) # if it's a two-term Add with rhs = 0 and two powers we can get the # dependent terms together, e.g. 3*f(x) + 2*g(x) -> f(x)/g(x) = -2/3 if lhs.is_Add and not rhs and len(lhs.args) == 2 and \ not lhs.is_polynomial(*symbols): a, b = ordered(lhs.args) ai, ad = a.as_independent(*symbols) bi, bd = b.as_independent(*symbols) if any(_ispow(i) for i in (ad, bd)): a_base, a_exp = ad.as_base_exp() b_base, b_exp = bd.as_base_exp() if a_base == b_base: # a = -b lhs = powsimp(powdenest(ad/bd)) rhs = -bi/ai else: rat = ad/bd _lhs = powsimp(ad/bd) if _lhs != rat: lhs = _lhs rhs = -bi/ai elif ai == -bi: if isinstance(ad, Function) and ad.func == bd.func: if len(ad.args) == len(bd.args) == 1: lhs = ad.args[0] - bd.args[0] elif len(ad.args) == len(bd.args): # should be able to solve # f(x, y) - f(2 - x, 0) == 0 -> x == 1 raise NotImplementedError( 'equal function with more than 1 argument') else: raise ValueError( 'function with different numbers of args') elif lhs.is_Mul and any(_ispow(a) for a in lhs.args): lhs = powsimp(powdenest(lhs)) if lhs.is_Function: if hasattr(lhs, 'inverse') and lhs.inverse() is not None and len(lhs.args) == 1: # -1 # f(x) = g -> x = f (g) # # /!\ inverse should not be defined if there are multiple values # for the function -- these are handled in _tsolve # rhs = lhs.inverse()(rhs) lhs = lhs.args[0] elif isinstance(lhs, atan2): y, x = lhs.args lhs = 2*atan(y/(sqrt(x**2 + y**2) + x)) elif lhs.func == rhs.func: if len(lhs.args) == len(rhs.args) == 1: lhs = lhs.args[0] rhs = rhs.args[0] elif len(lhs.args) == len(rhs.args): # should be able to solve # f(x, y) == f(2, 3) -> x == 2 # f(x, x + y) == f(2, 3) -> x == 2 raise NotImplementedError( 'equal function with more than 1 argument') else: raise ValueError( 'function with different numbers of args') if rhs and lhs.is_Pow and lhs.exp.is_Integer and lhs.exp < 0: lhs = 1/lhs rhs = 1/rhs # base**a = b -> base = b**(1/a) if # a is an Integer and dointpow=True (this gives real branch of root) # a is not an Integer and the equation is multivariate and the # base has more than 1 symbol in it # The rationale for this is that right now the multi-system solvers # doesn't try to resolve generators to see, for example, if the whole # system is written in terms of sqrt(x + y) so it will just fail, so we # do that step here. if lhs.is_Pow and ( lhs.exp.is_Integer and dointpow or not lhs.exp.is_Integer and len(symbols) > 1 and len(lhs.base.free_symbols & set(symbols)) > 1): rhs = rhs**(1/lhs.exp) lhs = lhs.base if lhs == was: break return rhs, lhs def unrad(eq, *syms, **flags): """ Remove radicals with symbolic arguments and return (eq, cov), None, or raise an error. Explanation =========== None is returned if there are no radicals to remove. NotImplementedError is raised if there are radicals and they cannot be removed or if the relationship between the original symbols and the change of variable needed to rewrite the system as a polynomial cannot be solved. Otherwise the tuple, ``(eq, cov)``, is returned where: *eq*, ``cov`` *eq* is an equation without radicals (in the symbol(s) of interest) whose solutions are a superset of the solutions to the original expression. *eq* might be rewritten in terms of a new variable; the relationship to the original variables is given by ``cov`` which is a list containing ``v`` and ``v**p - b`` where ``p`` is the power needed to clear the radical and ``b`` is the radical now expressed as a polynomial in the symbols of interest. For example, for sqrt(2 - x) the tuple would be ``(c, c**2 - 2 + x)``. The solutions of *eq* will contain solutions to the original equation (if there are any). *syms* An iterable of symbols which, if provided, will limit the focus of radical removal: only radicals with one or more of the symbols of interest will be cleared. All free symbols are used if *syms* is not set. *flags* are used internally for communication during recursive calls. Two options are also recognized: ``take``, when defined, is interpreted as a single-argument function that returns True if a given Pow should be handled. Radicals can be removed from an expression if: * All bases of the radicals are the same; a change of variables is done in this case. * If all radicals appear in one term of the expression. * There are only four terms with sqrt() factors or there are less than four terms having sqrt() factors. * There are only two terms with radicals. Examples ======== >>> from sympy.solvers.solvers import unrad >>> from sympy.abc import x >>> from sympy import sqrt, Rational, root >>> unrad(sqrt(x)*x**Rational(1, 3) + 2) (x**5 - 64, []) >>> unrad(sqrt(x) + root(x + 1, 3)) (-x**3 + x**2 + 2*x + 1, []) >>> eq = sqrt(x) + root(x, 3) - 2 >>> unrad(eq) (_p**3 + _p**2 - 2, [_p, _p**6 - x]) """ uflags = dict(check=False, simplify=False) def _cov(p, e): if cov: # XXX - uncovered oldp, olde = cov if Poly(e, p).degree(p) in (1, 2): cov[:] = [p, olde.subs(oldp, _vsolve(e, p, **uflags)[0])] else: raise NotImplementedError else: cov[:] = [p, e] def _canonical(eq, cov): if cov: # change symbol to vanilla so no solutions are eliminated p, e = cov rep = {p: Dummy(p.name)} eq = eq.xreplace(rep) cov = [p.xreplace(rep), e.xreplace(rep)] # remove constants and powers of factors since these don't change # the location of the root; XXX should factor or factor_terms be used? eq = factor_terms(_mexpand(eq.as_numer_denom()[0], recursive=True), clear=True) if eq.is_Mul: args = [] for f in eq.args: if f.is_number: continue if f.is_Pow: args.append(f.base) else: args.append(f) eq = Mul(*args) # leave as Mul for more efficient solving # make the sign canonical margs = list(Mul.make_args(eq)) changed = False for i, m in enumerate(margs): if m.could_extract_minus_sign(): margs[i] = -m changed = True if changed: eq = Mul(*margs, evaluate=False) return eq, cov def _Q(pow): # return leading Rational of denominator of Pow's exponent c = pow.as_base_exp()[1].as_coeff_Mul()[0] if not c.is_Rational: return S.One return c.q # define the _take method that will determine whether a term is of interest def _take(d): # return True if coefficient of any factor's exponent's den is not 1 for pow in Mul.make_args(d): if not pow.is_Pow: continue if _Q(pow) == 1: continue if pow.free_symbols & syms: return True return False _take = flags.setdefault('_take', _take) if isinstance(eq, Eq): eq = eq.lhs - eq.rhs # XXX legacy Eq as Eqn support elif not isinstance(eq, Expr): return cov, nwas, rpt = [flags.setdefault(k, v) for k, v in sorted(dict(cov=[], n=None, rpt=0).items())] # preconditioning eq = powdenest(factor_terms(eq, radical=True, clear=True)) eq = eq.as_numer_denom()[0] eq = _mexpand(eq, recursive=True) if eq.is_number: return # see if there are radicals in symbols of interest syms = set(syms) or eq.free_symbols # _take uses this poly = eq.as_poly() gens = [g for g in poly.gens if _take(g)] if not gens: return # recast poly in terms of eigen-gens poly = eq.as_poly(*gens) # not a polynomial e.g. 1 + sqrt(x)*exp(sqrt(x)) with gen sqrt(x) if poly is None: return # - an exponent has a symbol of interest (don't handle) if any(g.exp.has(*syms) for g in gens): return def _rads_bases_lcm(poly): # if all the bases are the same or all the radicals are in one # term, `lcm` will be the lcm of the denominators of the # exponents of the radicals lcm = 1 rads = set() bases = set() for g in poly.gens: q = _Q(g) if q != 1: rads.add(g) lcm = ilcm(lcm, q) bases.add(g.base) return rads, bases, lcm rads, bases, lcm = _rads_bases_lcm(poly) covsym = Dummy('p', nonnegative=True) # only keep in syms symbols that actually appear in radicals; # and update gens newsyms = set() for r in rads: newsyms.update(syms & r.free_symbols) if newsyms != syms: syms = newsyms # get terms together that have common generators drad = dict(zip(rads, range(len(rads)))) rterms = {(): []} args = Add.make_args(poly.as_expr()) for t in args: if _take(t): common = set(t.as_poly().gens).intersection(rads) key = tuple(sorted([drad[i] for i in common])) else: key = () rterms.setdefault(key, []).append(t) others = Add(*rterms.pop(())) rterms = [Add(*rterms[k]) for k in rterms.keys()] # the output will depend on the order terms are processed, so # make it canonical quickly rterms = list(reversed(list(ordered(rterms)))) ok = False # we don't have a solution yet depth = sqrt_depth(eq) if len(rterms) == 1 and not (rterms[0].is_Add and lcm > 2): eq = rterms[0]**lcm - ((-others)**lcm) ok = True else: if len(rterms) == 1 and rterms[0].is_Add: rterms = list(rterms[0].args) if len(bases) == 1: b = bases.pop() if len(syms) > 1: x = b.free_symbols else: x = syms x = list(ordered(x))[0] try: inv = _vsolve(covsym**lcm - b, x, **uflags) if not inv: raise NotImplementedError eq = poly.as_expr().subs(b, covsym**lcm).subs(x, inv[0]) _cov(covsym, covsym**lcm - b) return _canonical(eq, cov) except NotImplementedError: pass if len(rterms) == 2: if not others: eq = rterms[0]**lcm - (-rterms[1])**lcm ok = True elif not log(lcm, 2).is_Integer: # the lcm-is-power-of-two case is handled below r0, r1 = rterms if flags.get('_reverse', False): r1, r0 = r0, r1 i0 = _rads0, _bases0, lcm0 = _rads_bases_lcm(r0.as_poly()) i1 = _rads1, _bases1, lcm1 = _rads_bases_lcm(r1.as_poly()) for reverse in range(2): if reverse: i0, i1 = i1, i0 r0, r1 = r1, r0 _rads1, _, lcm1 = i1 _rads1 = Mul(*_rads1) t1 = _rads1**lcm1 c = covsym**lcm1 - t1 for x in syms: try: sol = _vsolve(c, x, **uflags) if not sol: raise NotImplementedError neweq = r0.subs(x, sol[0]) + covsym*r1/_rads1 + \ others tmp = unrad(neweq, covsym) if tmp: eq, newcov = tmp if newcov: newp, newc = newcov _cov(newp, c.subs(covsym, _vsolve(newc, covsym, **uflags)[0])) else: _cov(covsym, c) else: eq = neweq _cov(covsym, c) ok = True break except NotImplementedError: if reverse: raise NotImplementedError( 'no successful change of variable found') else: pass if ok: break elif len(rterms) == 3: # two cube roots and another with order less than 5 # (so an analytical solution can be found) or a base # that matches one of the cube root bases info = [_rads_bases_lcm(i.as_poly()) for i in rterms] RAD = 0 BASES = 1 LCM = 2 if info[0][LCM] != 3: info.append(info.pop(0)) rterms.append(rterms.pop(0)) elif info[1][LCM] != 3: info.append(info.pop(1)) rterms.append(rterms.pop(1)) if info[0][LCM] == info[1][LCM] == 3: if info[1][BASES] != info[2][BASES]: info[0], info[1] = info[1], info[0] rterms[0], rterms[1] = rterms[1], rterms[0] if info[1][BASES] == info[2][BASES]: eq = rterms[0]**3 + (rterms[1] + rterms[2] + others)**3 ok = True elif info[2][LCM] < 5: # a*root(A, 3) + b*root(B, 3) + others = c a, b, c, d, A, B = [Dummy(i) for i in 'abcdAB'] # zz represents the unraded expression into which the # specifics for this case are substituted zz = (c - d)*(A**3*a**9 + 3*A**2*B*a**6*b**3 - 3*A**2*a**6*c**3 + 9*A**2*a**6*c**2*d - 9*A**2*a**6*c*d**2 + 3*A**2*a**6*d**3 + 3*A*B**2*a**3*b**6 + 21*A*B*a**3*b**3*c**3 - 63*A*B*a**3*b**3*c**2*d + 63*A*B*a**3*b**3*c*d**2 - 21*A*B*a**3*b**3*d**3 + 3*A*a**3*c**6 - 18*A*a**3*c**5*d + 45*A*a**3*c**4*d**2 - 60*A*a**3*c**3*d**3 + 45*A*a**3*c**2*d**4 - 18*A*a**3*c*d**5 + 3*A*a**3*d**6 + B**3*b**9 - 3*B**2*b**6*c**3 + 9*B**2*b**6*c**2*d - 9*B**2*b**6*c*d**2 + 3*B**2*b**6*d**3 + 3*B*b**3*c**6 - 18*B*b**3*c**5*d + 45*B*b**3*c**4*d**2 - 60*B*b**3*c**3*d**3 + 45*B*b**3*c**2*d**4 - 18*B*b**3*c*d**5 + 3*B*b**3*d**6 - c**9 + 9*c**8*d - 36*c**7*d**2 + 84*c**6*d**3 - 126*c**5*d**4 + 126*c**4*d**5 - 84*c**3*d**6 + 36*c**2*d**7 - 9*c*d**8 + d**9) def _t(i): b = Mul(*info[i][RAD]) return cancel(rterms[i]/b), Mul(*info[i][BASES]) aa, AA = _t(0) bb, BB = _t(1) cc = -rterms[2] dd = others eq = zz.xreplace(dict(zip( (a, A, b, B, c, d), (aa, AA, bb, BB, cc, dd)))) ok = True # handle power-of-2 cases if not ok: if log(lcm, 2).is_Integer and (not others and len(rterms) == 4 or len(rterms) < 4): def _norm2(a, b): return a**2 + b**2 + 2*a*b if len(rterms) == 4: # (r0+r1)**2 - (r2+r3)**2 r0, r1, r2, r3 = rterms eq = _norm2(r0, r1) - _norm2(r2, r3) ok = True elif len(rterms) == 3: # (r1+r2)**2 - (r0+others)**2 r0, r1, r2 = rterms eq = _norm2(r1, r2) - _norm2(r0, others) ok = True elif len(rterms) == 2: # r0**2 - (r1+others)**2 r0, r1 = rterms eq = r0**2 - _norm2(r1, others) ok = True new_depth = sqrt_depth(eq) if ok else depth rpt += 1 # XXX how many repeats with others unchanging is enough? if not ok or ( nwas is not None and len(rterms) == nwas and new_depth is not None and new_depth == depth and rpt > 3): raise NotImplementedError('Cannot remove all radicals') flags.update(dict(cov=cov, n=len(rterms), rpt=rpt)) neq = unrad(eq, *syms, **flags) if neq: eq, cov = neq eq, cov = _canonical(eq, cov) return eq, cov # delayed imports from sympy.solvers.bivariate import ( bivariate_type, _solve_lambert, _filtered_gens)
f62e4fd56c63f1d4ffe8c09bd00d7320207566316320e5d82a9b4fed49afcd0b
from sympy.core import Add, Mul, Pow, S from sympy.core.basic import Basic from sympy.core.expr import Expr from sympy.core.numbers import _sympifyit, oo, zoo from sympy.core.relational import is_le, is_lt, is_ge, is_gt from sympy.core.sympify import _sympify from sympy.functions.elementary.miscellaneous import Min, Max from sympy.logic.boolalg import And from sympy.multipledispatch import dispatch from sympy.series.order import Order from sympy.sets.sets import FiniteSet class AccumulationBounds(Expr): r"""An accumulation bounds. # Note AccumulationBounds has an alias: AccumBounds AccumulationBounds represent an interval `[a, b]`, which is always closed at the ends. Here `a` and `b` can be any value from extended real numbers. The intended meaning of AccummulationBounds is to give an approximate location of the accumulation points of a real function at a limit point. Let `a` and `b` be reals such that `a \le b`. `\left\langle a, b\right\rangle = \{x \in \mathbb{R} \mid a \le x \le b\}` `\left\langle -\infty, b\right\rangle = \{x \in \mathbb{R} \mid x \le b\} \cup \{-\infty, \infty\}` `\left\langle a, \infty \right\rangle = \{x \in \mathbb{R} \mid a \le x\} \cup \{-\infty, \infty\}` `\left\langle -\infty, \infty \right\rangle = \mathbb{R} \cup \{-\infty, \infty\}` ``oo`` and ``-oo`` are added to the second and third definition respectively, since if either ``-oo`` or ``oo`` is an argument, then the other one should be included (though not as an end point). This is forced, since we have, for example, ``1/AccumBounds(0, 1) = AccumBounds(1, oo)``, and the limit at `0` is not one-sided. As `x` tends to `0-`, then `1/x \rightarrow -\infty`, so `-\infty` should be interpreted as belonging to ``AccumBounds(1, oo)`` though it need not appear explicitly. In many cases it suffices to know that the limit set is bounded. However, in some other cases more exact information could be useful. For example, all accumulation values of `\cos(x) + 1` are non-negative. (``AccumBounds(-1, 1) + 1 = AccumBounds(0, 2)``) A AccumulationBounds object is defined to be real AccumulationBounds, if its end points are finite reals. Let `X`, `Y` be real AccumulationBounds, then their sum, difference, product are defined to be the following sets: `X + Y = \{ x+y \mid x \in X \cap y \in Y\}` `X - Y = \{ x-y \mid x \in X \cap y \in Y\}` `X \times Y = \{ x \times y \mid x \in X \cap y \in Y\}` When an AccumBounds is raised to a negative power, if 0 is contained between the bounds then an infinite range is returned, otherwise if an endpoint is 0 then a semi-infinite range with consistent sign will be returned. AccumBounds in expressions behave a lot like Intervals but the semantics are not necessarily the same. Division (or exponentiation to a negative integer power) could be handled with *intervals* by returning a union of the results obtained after splitting the bounds between negatives and positives, but that is not done with AccumBounds. In addition, bounds are assumed to be independent of each other; if the same bound is used in more than one place in an expression, the result may not be the supremum or infimum of the expression (see below). Finally, when a boundary is ``1``, exponentiation to the power of ``oo`` yields ``oo``, neither ``1`` nor ``nan``. Examples ======== >>> from sympy import AccumBounds, sin, exp, log, pi, E, S, oo >>> from sympy.abc import x >>> AccumBounds(0, 1) + AccumBounds(1, 2) AccumBounds(1, 3) >>> AccumBounds(0, 1) - AccumBounds(0, 2) AccumBounds(-2, 1) >>> AccumBounds(-2, 3)*AccumBounds(-1, 1) AccumBounds(-3, 3) >>> AccumBounds(1, 2)*AccumBounds(3, 5) AccumBounds(3, 10) The exponentiation of AccumulationBounds is defined as follows: If 0 does not belong to `X` or `n > 0` then `X^n = \{ x^n \mid x \in X\}` >>> AccumBounds(1, 4)**(S(1)/2) AccumBounds(1, 2) otherwise, an infinite or semi-infinite result is obtained: >>> 1/AccumBounds(-1, 1) AccumBounds(-oo, oo) >>> 1/AccumBounds(0, 2) AccumBounds(1/2, oo) >>> 1/AccumBounds(-oo, 0) AccumBounds(-oo, 0) A boundary of 1 will always generate all nonnegatives: >>> AccumBounds(1, 2)**oo AccumBounds(0, oo) >>> AccumBounds(0, 1)**oo AccumBounds(0, oo) If the exponent is itself an AccumulationBounds or is not an integer then unevaluated results will be returned unless the base values are positive: >>> AccumBounds(2, 3)**AccumBounds(-1, 2) AccumBounds(1/3, 9) >>> AccumBounds(-2, 3)**AccumBounds(-1, 2) AccumBounds(-2, 3)**AccumBounds(-1, 2) >>> AccumBounds(-2, -1)**(S(1)/2) sqrt(AccumBounds(-2, -1)) Note: `\left\langle a, b\right\rangle^2` is not same as `\left\langle a, b\right\rangle \times \left\langle a, b\right\rangle` >>> AccumBounds(-1, 1)**2 AccumBounds(0, 1) >>> AccumBounds(1, 3) < 4 True >>> AccumBounds(1, 3) < -1 False Some elementary functions can also take AccumulationBounds as input. A function `f` evaluated for some real AccumulationBounds `\left\langle a, b \right\rangle` is defined as `f(\left\langle a, b\right\rangle) = \{ f(x) \mid a \le x \le b \}` >>> sin(AccumBounds(pi/6, pi/3)) AccumBounds(1/2, sqrt(3)/2) >>> exp(AccumBounds(0, 1)) AccumBounds(1, E) >>> log(AccumBounds(1, E)) AccumBounds(0, 1) Some symbol in an expression can be substituted for a AccumulationBounds object. But it does not necessarily evaluate the AccumulationBounds for that expression. The same expression can be evaluated to different values depending upon the form it is used for substitution since each instance of an AccumulationBounds is considered independent. For example: >>> (x**2 + 2*x + 1).subs(x, AccumBounds(-1, 1)) AccumBounds(-1, 4) >>> ((x + 1)**2).subs(x, AccumBounds(-1, 1)) AccumBounds(0, 4) References ========== .. [1] https://en.wikipedia.org/wiki/Interval_arithmetic .. [2] http://fab.cba.mit.edu/classes/S62.12/docs/Hickey_interval.pdf Notes ===== Do not use ``AccumulationBounds`` for floating point interval arithmetic calculations, use ``mpmath.iv`` instead. """ is_extended_real = True is_number = False def __new__(cls, min, max): min = _sympify(min) max = _sympify(max) # Only allow real intervals (use symbols with 'is_extended_real=True'). if not min.is_extended_real or not max.is_extended_real: raise ValueError("Only real AccumulationBounds are supported") if max == min: return max # Make sure that the created AccumBounds object will be valid. if max.is_number and min.is_number: bad = max.is_comparable and min.is_comparable and max < min else: bad = (max - min).is_extended_negative if bad: raise ValueError( "Lower limit should be smaller than upper limit") return Basic.__new__(cls, min, max) # setting the operation priority _op_priority = 11.0 def _eval_is_real(self): if self.min.is_real and self.max.is_real: return True @property def min(self): """ Returns the minimum possible value attained by AccumulationBounds object. Examples ======== >>> from sympy import AccumBounds >>> AccumBounds(1, 3).min 1 """ return self.args[0] @property def max(self): """ Returns the maximum possible value attained by AccumulationBounds object. Examples ======== >>> from sympy import AccumBounds >>> AccumBounds(1, 3).max 3 """ return self.args[1] @property def delta(self): """ Returns the difference of maximum possible value attained by AccumulationBounds object and minimum possible value attained by AccumulationBounds object. Examples ======== >>> from sympy import AccumBounds >>> AccumBounds(1, 3).delta 2 """ return self.max - self.min @property def mid(self): """ Returns the mean of maximum possible value attained by AccumulationBounds object and minimum possible value attained by AccumulationBounds object. Examples ======== >>> from sympy import AccumBounds >>> AccumBounds(1, 3).mid 2 """ return (self.min + self.max) / 2 @_sympifyit('other', NotImplemented) def _eval_power(self, other): return self.__pow__(other) @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Expr): if isinstance(other, AccumBounds): return AccumBounds( Add(self.min, other.min), Add(self.max, other.max)) if other is S.Infinity and self.min is S.NegativeInfinity or \ other is S.NegativeInfinity and self.max is S.Infinity: return AccumBounds(-oo, oo) elif other.is_extended_real: if self.min is S.NegativeInfinity and self.max is S.Infinity: return AccumBounds(-oo, oo) elif self.min is S.NegativeInfinity: return AccumBounds(-oo, self.max + other) elif self.max is S.Infinity: return AccumBounds(self.min + other, oo) else: return AccumBounds(Add(self.min, other), Add(self.max, other)) return Add(self, other, evaluate=False) return NotImplemented __radd__ = __add__ def __neg__(self): return AccumBounds(-self.max, -self.min) @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Expr): if isinstance(other, AccumBounds): return AccumBounds( Add(self.min, -other.max), Add(self.max, -other.min)) if other is S.NegativeInfinity and self.min is S.NegativeInfinity or \ other is S.Infinity and self.max is S.Infinity: return AccumBounds(-oo, oo) elif other.is_extended_real: if self.min is S.NegativeInfinity and self.max is S.Infinity: return AccumBounds(-oo, oo) elif self.min is S.NegativeInfinity: return AccumBounds(-oo, self.max - other) elif self.max is S.Infinity: return AccumBounds(self.min - other, oo) else: return AccumBounds( Add(self.min, -other), Add(self.max, -other)) return Add(self, -other, evaluate=False) return NotImplemented @_sympifyit('other', NotImplemented) def __rsub__(self, other): return self.__neg__() + other @_sympifyit('other', NotImplemented) def __mul__(self, other): if self.args == (-oo, oo): return self if isinstance(other, Expr): if isinstance(other, AccumBounds): if other.args == (-oo, oo): return other v = set() for a in self.args: vi = other*a for i in vi.args or (vi,): v.add(i) return AccumBounds(Min(*v), Max(*v)) if other is S.Infinity: if self.min.is_zero: return AccumBounds(0, oo) if self.max.is_zero: return AccumBounds(-oo, 0) if other is S.NegativeInfinity: if self.min.is_zero: return AccumBounds(-oo, 0) if self.max.is_zero: return AccumBounds(0, oo) if other.is_extended_real: if other.is_zero: if self.max is S.Infinity: return AccumBounds(0, oo) if self.min is S.NegativeInfinity: return AccumBounds(-oo, 0) return S.Zero if other.is_extended_positive: return AccumBounds( Mul(self.min, other), Mul(self.max, other)) elif other.is_extended_negative: return AccumBounds( Mul(self.max, other), Mul(self.min, other)) if isinstance(other, Order): return other return Mul(self, other, evaluate=False) return NotImplemented __rmul__ = __mul__ @_sympifyit('other', NotImplemented) def __truediv__(self, other): if isinstance(other, Expr): if isinstance(other, AccumBounds): if other.min.is_positive or other.max.is_negative: return self * AccumBounds(1/other.max, 1/other.min) if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative and other.min.is_extended_nonpositive and other.max.is_extended_nonnegative): if self.min.is_zero and other.min.is_zero: return AccumBounds(0, oo) if self.max.is_zero and other.min.is_zero: return AccumBounds(-oo, 0) return AccumBounds(-oo, oo) if self.max.is_extended_negative: if other.min.is_extended_negative: if other.max.is_zero: return AccumBounds(self.max / other.min, oo) if other.max.is_extended_positive: # if we were dealing with intervals we would return # Union(Interval(-oo, self.max/other.max), # Interval(self.max/other.min, oo)) return AccumBounds(-oo, oo) if other.min.is_zero and other.max.is_extended_positive: return AccumBounds(-oo, self.max / other.max) if self.min.is_extended_positive: if other.min.is_extended_negative: if other.max.is_zero: return AccumBounds(-oo, self.min / other.min) if other.max.is_extended_positive: # if we were dealing with intervals we would return # Union(Interval(-oo, self.min/other.min), # Interval(self.min/other.max, oo)) return AccumBounds(-oo, oo) if other.min.is_zero and other.max.is_extended_positive: return AccumBounds(self.min / other.max, oo) elif other.is_extended_real: if other in (S.Infinity, S.NegativeInfinity): if self == AccumBounds(-oo, oo): return AccumBounds(-oo, oo) if self.max is S.Infinity: return AccumBounds(Min(0, other), Max(0, other)) if self.min is S.NegativeInfinity: return AccumBounds(Min(0, -other), Max(0, -other)) if other.is_extended_positive: return AccumBounds(self.min / other, self.max / other) elif other.is_extended_negative: return AccumBounds(self.max / other, self.min / other) if (1 / other) is S.ComplexInfinity: return Mul(self, 1 / other, evaluate=False) else: return Mul(self, 1 / other) return NotImplemented @_sympifyit('other', NotImplemented) def __rtruediv__(self, other): if isinstance(other, Expr): if other.is_extended_real: if other.is_zero: return S.Zero if (self.min.is_extended_nonpositive and self.max.is_extended_nonnegative): if self.min.is_zero: if other.is_extended_positive: return AccumBounds(Mul(other, 1 / self.max), oo) if other.is_extended_negative: return AccumBounds(-oo, Mul(other, 1 / self.max)) if self.max.is_zero: if other.is_extended_positive: return AccumBounds(-oo, Mul(other, 1 / self.min)) if other.is_extended_negative: return AccumBounds(Mul(other, 1 / self.min), oo) return AccumBounds(-oo, oo) else: return AccumBounds(Min(other / self.min, other / self.max), Max(other / self.min, other / self.max)) return Mul(other, 1 / self, evaluate=False) else: return NotImplemented @_sympifyit('other', NotImplemented) def __pow__(self, other): if isinstance(other, Expr): if other is S.Infinity: if self.min.is_extended_nonnegative: if self.max < 1: return S.Zero if self.min > 1: return S.Infinity return AccumBounds(0, oo) elif self.max.is_extended_negative: if self.min > -1: return S.Zero if self.max < -1: return zoo return S.NaN else: if self.min > -1: if self.max < 1: return S.Zero return AccumBounds(0, oo) return AccumBounds(-oo, oo) if other is S.NegativeInfinity: return (1/self)**oo # generically true if (self.max - self.min).is_nonnegative: # well defined if self.min.is_nonnegative: # no 0 to worry about if other.is_nonnegative: # no infinity to worry about return self.func(self.min**other, self.max**other) if other.is_zero: return S.One # x**0 = 1 if other.is_Integer or other.is_integer: if self.min.is_extended_positive: return AccumBounds( Min(self.min**other, self.max**other), Max(self.min**other, self.max**other)) elif self.max.is_extended_negative: return AccumBounds( Min(self.max**other, self.min**other), Max(self.max**other, self.min**other)) if other % 2 == 0: if other.is_extended_negative: if self.min.is_zero: return AccumBounds(self.max**other, oo) if self.max.is_zero: return AccumBounds(self.min**other, oo) return (1/self)**(-other) return AccumBounds( S.Zero, Max(self.min**other, self.max**other)) elif other % 2 == 1: if other.is_extended_negative: if self.min.is_zero: return AccumBounds(self.max**other, oo) if self.max.is_zero: return AccumBounds(-oo, self.min**other) return (1/self)**(-other) return AccumBounds(self.min**other, self.max**other) # non-integer exponent # 0**neg or neg**frac yields complex if (other.is_number or other.is_rational) and ( self.min.is_extended_nonnegative or ( other.is_extended_nonnegative and self.min.is_extended_nonnegative)): num, den = other.as_numer_denom() if num is S.One: return AccumBounds(*[i**(1/den) for i in self.args]) elif den is not S.One: # e.g. if other is not Float return (self**num)**(1/den) # ok for non-negative base if isinstance(other, AccumBounds): if (self.min.is_extended_positive or self.min.is_extended_nonnegative and other.min.is_extended_nonnegative): p = [self**i for i in other.args] if not any(i.is_Pow for i in p): a = [j for i in p for j in i.args or (i,)] try: return self.func(min(a), max(a)) except TypeError: # can't sort pass return Pow(self, other, evaluate=False) return NotImplemented @_sympifyit('other', NotImplemented) def __rpow__(self, other): if other.is_real and other.is_extended_nonnegative and ( self.max - self.min).is_extended_positive: if other is S.One: return S.One if other.is_extended_positive: a, b = [other**i for i in self.args] if min(a, b) != a: a, b = b, a return self.func(a, b) if other.is_zero: if self.min.is_zero: return self.func(0, 1) if self.min.is_extended_positive: return S.Zero return Pow(other, self, evaluate=False) def __abs__(self): if self.max.is_extended_negative: return self.__neg__() elif self.min.is_extended_negative: return AccumBounds(S.Zero, Max(abs(self.min), self.max)) else: return self def __contains__(self, other): """ Returns ``True`` if other is contained in self, where other belongs to extended real numbers, ``False`` if not contained, otherwise TypeError is raised. Examples ======== >>> from sympy import AccumBounds, oo >>> 1 in AccumBounds(-1, 3) True -oo and oo go together as limits (in AccumulationBounds). >>> -oo in AccumBounds(1, oo) True >>> oo in AccumBounds(-oo, 0) True """ other = _sympify(other) if other in (S.Infinity, S.NegativeInfinity): if self.min is S.NegativeInfinity or self.max is S.Infinity: return True return False rv = And(self.min <= other, self.max >= other) if rv not in (True, False): raise TypeError("input failed to evaluate") return rv def intersection(self, other): """ Returns the intersection of 'self' and 'other'. Here other can be an instance of :py:class:`~.FiniteSet` or AccumulationBounds. Parameters ========== other : AccumulationBounds Another AccumulationBounds object with which the intersection has to be computed. Returns ======= AccumulationBounds Intersection of ``self`` and ``other``. Examples ======== >>> from sympy import AccumBounds, FiniteSet >>> AccumBounds(1, 3).intersection(AccumBounds(2, 4)) AccumBounds(2, 3) >>> AccumBounds(1, 3).intersection(AccumBounds(4, 6)) EmptySet >>> AccumBounds(1, 4).intersection(FiniteSet(1, 2, 5)) {1, 2} """ if not isinstance(other, (AccumBounds, FiniteSet)): raise TypeError( "Input must be AccumulationBounds or FiniteSet object") if isinstance(other, FiniteSet): fin_set = S.EmptySet for i in other: if i in self: fin_set = fin_set + FiniteSet(i) return fin_set if self.max < other.min or self.min > other.max: return S.EmptySet if self.min <= other.min: if self.max <= other.max: return AccumBounds(other.min, self.max) if self.max > other.max: return other if other.min <= self.min: if other.max < self.max: return AccumBounds(self.min, other.max) if other.max > self.max: return self def union(self, other): # TODO : Devise a better method for Union of AccumBounds # this method is not actually correct and # can be made better if not isinstance(other, AccumBounds): raise TypeError( "Input must be AccumulationBounds or FiniteSet object") if self.min <= other.min and self.max >= other.min: return AccumBounds(self.min, Max(self.max, other.max)) if other.min <= self.min and other.max >= self.min: return AccumBounds(other.min, Max(self.max, other.max)) @dispatch(AccumulationBounds, AccumulationBounds) # type: ignore # noqa:F811 def _eval_is_le(lhs, rhs): # noqa:F811 if is_le(lhs.max, rhs.min): return True if is_gt(lhs.min, rhs.max): return False @dispatch(AccumulationBounds, Basic) # type: ignore # noqa:F811 def _eval_is_le(lhs, rhs): # noqa: F811 """ Returns ``True `` if range of values attained by ``lhs`` AccumulationBounds object is greater than the range of values attained by ``rhs``, where ``rhs`` may be any value of type AccumulationBounds object or extended real number value, ``False`` if ``rhs`` satisfies the same property, else an unevaluated :py:class:`~.Relational`. Examples ======== >>> from sympy import AccumBounds, oo >>> AccumBounds(1, 3) > AccumBounds(4, oo) False >>> AccumBounds(1, 4) > AccumBounds(3, 4) AccumBounds(1, 4) > AccumBounds(3, 4) >>> AccumBounds(1, oo) > -1 True """ if not rhs.is_extended_real: raise TypeError( "Invalid comparison of %s %s" % (type(rhs), rhs)) elif rhs.is_comparable: if is_le(lhs.max, rhs): return True if is_gt(lhs.min, rhs): return False @dispatch(AccumulationBounds, AccumulationBounds) def _eval_is_ge(lhs, rhs): # noqa:F811 if is_ge(lhs.min, rhs.max): return True if is_lt(lhs.max, rhs.min): return False @dispatch(AccumulationBounds, Expr) # type:ignore def _eval_is_ge(lhs, rhs): # noqa: F811 """ Returns ``True`` if range of values attained by ``lhs`` AccumulationBounds object is less that the range of values attained by ``rhs``, where other may be any value of type AccumulationBounds object or extended real number value, ``False`` if ``rhs`` satisfies the same property, else an unevaluated :py:class:`~.Relational`. Examples ======== >>> from sympy import AccumBounds, oo >>> AccumBounds(1, 3) >= AccumBounds(4, oo) False >>> AccumBounds(1, 4) >= AccumBounds(3, 4) AccumBounds(1, 4) >= AccumBounds(3, 4) >>> AccumBounds(1, oo) >= 1 True """ if not rhs.is_extended_real: raise TypeError( "Invalid comparison of %s %s" % (type(rhs), rhs)) elif rhs.is_comparable: if is_ge(lhs.min, rhs): return True if is_lt(lhs.max, rhs): return False @dispatch(Expr, AccumulationBounds) # type:ignore def _eval_is_ge(lhs, rhs): # noqa:F811 if not lhs.is_extended_real: raise TypeError( "Invalid comparison of %s %s" % (type(lhs), lhs)) elif lhs.is_comparable: if is_le(rhs.max, lhs): return True if is_gt(rhs.min, lhs): return False @dispatch(AccumulationBounds, AccumulationBounds) # type:ignore def _eval_is_ge(lhs, rhs): # noqa:F811 if is_ge(lhs.min, rhs.max): return True if is_lt(lhs.max, rhs.min): return False # setting an alias for AccumulationBounds AccumBounds = AccumulationBounds
8fdd2e2e204c24345b5dd6b356191b1693aaa7f6bc07bb2b7728b621c799f500
from .accumulationbounds import AccumBounds, AccumulationBounds # noqa: F401 from .singularities import singularities from sympy.core import Pow, S from sympy.core.function import diff, expand_mul from sympy.core.kind import NumberKind from sympy.core.mod import Mod from sympy.core.numbers import equal_valued from sympy.core.relational import Relational from sympy.core.symbol import Symbol, Dummy from sympy.core.sympify import _sympify from sympy.functions.elementary.complexes import Abs, im, re from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import ( TrigonometricFunction, sin, cos, csc, sec) from sympy.polys.polytools import degree, lcm_list from sympy.sets.sets import (Interval, Intersection, FiniteSet, Union, Complement) from sympy.sets.fancysets import ImageSet from sympy.utilities import filldedent from sympy.utilities.iterables import iterable def continuous_domain(f, symbol, domain): """ Returns the intervals in the given domain for which the function is continuous. This method is limited by the ability to determine the various singularities and discontinuities of the given function. Parameters ========== f : :py:class:`~.Expr` The concerned function. symbol : :py:class:`~.Symbol` The variable for which the intervals are to be determined. domain : :py:class:`~.Interval` The domain over which the continuity of the symbol has to be checked. Examples ======== >>> from sympy import Interval, Symbol, S, tan, log, pi, sqrt >>> from sympy.calculus.util import continuous_domain >>> x = Symbol('x') >>> continuous_domain(1/x, x, S.Reals) Union(Interval.open(-oo, 0), Interval.open(0, oo)) >>> continuous_domain(tan(x), x, Interval(0, pi)) Union(Interval.Ropen(0, pi/2), Interval.Lopen(pi/2, pi)) >>> continuous_domain(sqrt(x - 2), x, Interval(-5, 5)) Interval(2, 5) >>> continuous_domain(log(2*x - 1), x, S.Reals) Interval.open(1/2, oo) Returns ======= :py:class:`~.Interval` Union of all intervals where the function is continuous. Raises ====== NotImplementedError If the method to determine continuity of such a function has not yet been developed. """ from sympy.solvers.inequalities import solve_univariate_inequality if domain.is_subset(S.Reals): constrained_interval = domain for atom in f.atoms(Pow): den = atom.exp.as_numer_denom()[1] if den.is_even and den.is_nonzero: constraint = solve_univariate_inequality(atom.base >= 0, symbol).as_set() constrained_interval = Intersection(constraint, constrained_interval) for atom in f.atoms(log): constraint = solve_univariate_inequality(atom.args[0] > 0, symbol).as_set() constrained_interval = Intersection(constraint, constrained_interval) return constrained_interval - singularities(f, symbol, domain) def function_range(f, symbol, domain): """ Finds the range of a function in a given domain. This method is limited by the ability to determine the singularities and determine limits. Parameters ========== f : :py:class:`~.Expr` The concerned function. symbol : :py:class:`~.Symbol` The variable for which the range of function is to be determined. domain : :py:class:`~.Interval` The domain under which the range of the function has to be found. Examples ======== >>> from sympy import Interval, Symbol, S, exp, log, pi, sqrt, sin, tan >>> from sympy.calculus.util import function_range >>> x = Symbol('x') >>> function_range(sin(x), x, Interval(0, 2*pi)) Interval(-1, 1) >>> function_range(tan(x), x, Interval(-pi/2, pi/2)) Interval(-oo, oo) >>> function_range(1/x, x, S.Reals) Union(Interval.open(-oo, 0), Interval.open(0, oo)) >>> function_range(exp(x), x, S.Reals) Interval.open(0, oo) >>> function_range(log(x), x, S.Reals) Interval(-oo, oo) >>> function_range(sqrt(x), x, Interval(-5, 9)) Interval(0, 3) Returns ======= :py:class:`~.Interval` Union of all ranges for all intervals under domain where function is continuous. Raises ====== NotImplementedError If any of the intervals, in the given domain, for which function is continuous are not finite or real, OR if the critical points of the function on the domain cannot be found. """ if domain is S.EmptySet: return S.EmptySet period = periodicity(f, symbol) if period == S.Zero: # the expression is constant wrt symbol return FiniteSet(f.expand()) from sympy.series.limits import limit from sympy.solvers.solveset import solveset if period is not None: if isinstance(domain, Interval): if (domain.inf - domain.sup).is_infinite: domain = Interval(0, period) elif isinstance(domain, Union): for sub_dom in domain.args: if isinstance(sub_dom, Interval) and \ ((sub_dom.inf - sub_dom.sup).is_infinite): domain = Interval(0, period) intervals = continuous_domain(f, symbol, domain) range_int = S.EmptySet if isinstance(intervals,(Interval, FiniteSet)): interval_iter = (intervals,) elif isinstance(intervals, Union): interval_iter = intervals.args else: raise NotImplementedError(filldedent(''' Unable to find range for the given domain. ''')) for interval in interval_iter: if isinstance(interval, FiniteSet): for singleton in interval: if singleton in domain: range_int += FiniteSet(f.subs(symbol, singleton)) elif isinstance(interval, Interval): vals = S.EmptySet critical_points = S.EmptySet critical_values = S.EmptySet bounds = ((interval.left_open, interval.inf, '+'), (interval.right_open, interval.sup, '-')) for is_open, limit_point, direction in bounds: if is_open: critical_values += FiniteSet(limit(f, symbol, limit_point, direction)) vals += critical_values else: vals += FiniteSet(f.subs(symbol, limit_point)) solution = solveset(f.diff(symbol), symbol, interval) if not iterable(solution): raise NotImplementedError( 'Unable to find critical points for {}'.format(f)) if isinstance(solution, ImageSet): raise NotImplementedError( 'Infinite number of critical points for {}'.format(f)) critical_points += solution for critical_point in critical_points: vals += FiniteSet(f.subs(symbol, critical_point)) left_open, right_open = False, False if critical_values is not S.EmptySet: if critical_values.inf == vals.inf: left_open = True if critical_values.sup == vals.sup: right_open = True range_int += Interval(vals.inf, vals.sup, left_open, right_open) else: raise NotImplementedError(filldedent(''' Unable to find range for the given domain. ''')) return range_int def not_empty_in(finset_intersection, *syms): """ Finds the domain of the functions in ``finset_intersection`` in which the ``finite_set`` is not-empty. Parameters ========== finset_intersection : Intersection of FiniteSet The unevaluated intersection of FiniteSet containing real-valued functions with Union of Sets syms : Tuple of symbols Symbol for which domain is to be found Raises ====== NotImplementedError The algorithms to find the non-emptiness of the given FiniteSet are not yet implemented. ValueError The input is not valid. RuntimeError It is a bug, please report it to the github issue tracker (https://github.com/sympy/sympy/issues). Examples ======== >>> from sympy import FiniteSet, Interval, not_empty_in, oo >>> from sympy.abc import x >>> not_empty_in(FiniteSet(x/2).intersect(Interval(0, 1)), x) Interval(0, 2) >>> not_empty_in(FiniteSet(x, x**2).intersect(Interval(1, 2)), x) Union(Interval(1, 2), Interval(-sqrt(2), -1)) >>> not_empty_in(FiniteSet(x**2/(x + 2)).intersect(Interval(1, oo)), x) Union(Interval.Lopen(-2, -1), Interval(2, oo)) """ # TODO: handle piecewise defined functions # TODO: handle transcendental functions # TODO: handle multivariate functions if len(syms) == 0: raise ValueError("One or more symbols must be given in syms.") if finset_intersection is S.EmptySet: return S.EmptySet if isinstance(finset_intersection, Union): elm_in_sets = finset_intersection.args[0] return Union(not_empty_in(finset_intersection.args[1], *syms), elm_in_sets) if isinstance(finset_intersection, FiniteSet): finite_set = finset_intersection _sets = S.Reals else: finite_set = finset_intersection.args[1] _sets = finset_intersection.args[0] if not isinstance(finite_set, FiniteSet): raise ValueError('A FiniteSet must be given, not %s: %s' % (type(finite_set), finite_set)) if len(syms) == 1: symb = syms[0] else: raise NotImplementedError('more than one variables %s not handled' % (syms,)) def elm_domain(expr, intrvl): """ Finds the domain of an expression in any given interval """ from sympy.solvers.solveset import solveset _start = intrvl.start _end = intrvl.end _singularities = solveset(expr.as_numer_denom()[1], symb, domain=S.Reals) if intrvl.right_open: if _end is S.Infinity: _domain1 = S.Reals else: _domain1 = solveset(expr < _end, symb, domain=S.Reals) else: _domain1 = solveset(expr <= _end, symb, domain=S.Reals) if intrvl.left_open: if _start is S.NegativeInfinity: _domain2 = S.Reals else: _domain2 = solveset(expr > _start, symb, domain=S.Reals) else: _domain2 = solveset(expr >= _start, symb, domain=S.Reals) # domain in the interval expr_with_sing = Intersection(_domain1, _domain2) expr_domain = Complement(expr_with_sing, _singularities) return expr_domain if isinstance(_sets, Interval): return Union(*[elm_domain(element, _sets) for element in finite_set]) if isinstance(_sets, Union): _domain = S.EmptySet for intrvl in _sets.args: _domain_element = Union(*[elm_domain(element, intrvl) for element in finite_set]) _domain = Union(_domain, _domain_element) return _domain def periodicity(f, symbol, check=False): """ Tests the given function for periodicity in the given symbol. Parameters ========== f : :py:class:`~.Expr` The concerned function. symbol : :py:class:`~.Symbol` The variable for which the period is to be determined. check : bool, optional The flag to verify whether the value being returned is a period or not. Returns ======= period The period of the function is returned. ``None`` is returned when the function is aperiodic or has a complex period. The value of $0$ is returned as the period of a constant function. Raises ====== NotImplementedError The value of the period computed cannot be verified. Notes ===== Currently, we do not support functions with a complex period. The period of functions having complex periodic values such as ``exp``, ``sinh`` is evaluated to ``None``. The value returned might not be the "fundamental" period of the given function i.e. it may not be the smallest periodic value of the function. The verification of the period through the ``check`` flag is not reliable due to internal simplification of the given expression. Hence, it is set to ``False`` by default. Examples ======== >>> from sympy import periodicity, Symbol, sin, cos, tan, exp >>> x = Symbol('x') >>> f = sin(x) + sin(2*x) + sin(3*x) >>> periodicity(f, x) 2*pi >>> periodicity(sin(x)*cos(x), x) pi >>> periodicity(exp(tan(2*x) - 1), x) pi/2 >>> periodicity(sin(4*x)**cos(2*x), x) pi >>> periodicity(exp(x), x) """ if symbol.kind is not NumberKind: raise NotImplementedError("Cannot use symbol of kind %s" % symbol.kind) temp = Dummy('x', real=True) f = f.subs(symbol, temp) symbol = temp def _check(orig_f, period): '''Return the checked period or raise an error.''' new_f = orig_f.subs(symbol, symbol + period) if new_f.equals(orig_f): return period else: raise NotImplementedError(filldedent(''' The period of the given function cannot be verified. When `%s` was replaced with `%s + %s` in `%s`, the result was `%s` which was not recognized as being the same as the original function. So either the period was wrong or the two forms were not recognized as being equal. Set check=False to obtain the value.''' % (symbol, symbol, period, orig_f, new_f))) orig_f = f period = None if isinstance(f, Relational): f = f.lhs - f.rhs f = f.simplify() if symbol not in f.free_symbols: return S.Zero if isinstance(f, TrigonometricFunction): try: period = f.period(symbol) except NotImplementedError: pass if isinstance(f, Abs): arg = f.args[0] if isinstance(arg, (sec, csc, cos)): # all but tan and cot might have a # a period that is half as large # so recast as sin arg = sin(arg.args[0]) period = periodicity(arg, symbol) if period is not None and isinstance(arg, sin): # the argument of Abs was a trigonometric other than # cot or tan; test to see if the half-period # is valid. Abs(arg) has behaviour equivalent to # orig_f, so use that for test: orig_f = Abs(arg) try: return _check(orig_f, period/2) except NotImplementedError as err: if check: raise NotImplementedError(err) # else let new orig_f and period be # checked below if isinstance(f, exp) or (f.is_Pow and f.base == S.Exp1): f = Pow(S.Exp1, expand_mul(f.exp)) if im(f) != 0: period_real = periodicity(re(f), symbol) period_imag = periodicity(im(f), symbol) if period_real is not None and period_imag is not None: period = lcim([period_real, period_imag]) if f.is_Pow and f.base != S.Exp1: base, expo = f.args base_has_sym = base.has(symbol) expo_has_sym = expo.has(symbol) if base_has_sym and not expo_has_sym: period = periodicity(base, symbol) elif expo_has_sym and not base_has_sym: period = periodicity(expo, symbol) else: period = _periodicity(f.args, symbol) elif f.is_Mul: coeff, g = f.as_independent(symbol, as_Add=False) if isinstance(g, TrigonometricFunction) or not equal_valued(coeff, 1): period = periodicity(g, symbol) else: period = _periodicity(g.args, symbol) elif f.is_Add: k, g = f.as_independent(symbol) if k is not S.Zero: return periodicity(g, symbol) period = _periodicity(g.args, symbol) elif isinstance(f, Mod): a, n = f.args if a == symbol: period = n elif isinstance(a, TrigonometricFunction): period = periodicity(a, symbol) #check if 'f' is linear in 'symbol' elif (a.is_polynomial(symbol) and degree(a, symbol) == 1 and symbol not in n.free_symbols): period = Abs(n / a.diff(symbol)) elif isinstance(f, Piecewise): pass # not handling Piecewise yet as the return type is not favorable elif period is None: from sympy.solvers.decompogen import compogen, decompogen g_s = decompogen(f, symbol) num_of_gs = len(g_s) if num_of_gs > 1: for index, g in enumerate(reversed(g_s)): start_index = num_of_gs - 1 - index g = compogen(g_s[start_index:], symbol) if g not in (orig_f, f): # Fix for issue 12620 period = periodicity(g, symbol) if period is not None: break if period is not None: if check: return _check(orig_f, period) return period return None def _periodicity(args, symbol): """ Helper for `periodicity` to find the period of a list of simpler functions. It uses the `lcim` method to find the least common period of all the functions. Parameters ========== args : Tuple of :py:class:`~.Symbol` All the symbols present in a function. symbol : :py:class:`~.Symbol` The symbol over which the function is to be evaluated. Returns ======= period The least common period of the function for all the symbols of the function. ``None`` if for at least one of the symbols the function is aperiodic. """ periods = [] for f in args: period = periodicity(f, symbol) if period is None: return None if period is not S.Zero: periods.append(period) if len(periods) > 1: return lcim(periods) if periods: return periods[0] def lcim(numbers): """Returns the least common integral multiple of a list of numbers. The numbers can be rational or irrational or a mixture of both. `None` is returned for incommensurable numbers. Parameters ========== numbers : list Numbers (rational and/or irrational) for which lcim is to be found. Returns ======= number lcim if it exists, otherwise ``None`` for incommensurable numbers. Examples ======== >>> from sympy.calculus.util import lcim >>> from sympy import S, pi >>> lcim([S(1)/2, S(3)/4, S(5)/6]) 15/2 >>> lcim([2*pi, 3*pi, pi, pi/2]) 6*pi >>> lcim([S(1), 2*pi]) """ result = None if all(num.is_irrational for num in numbers): factorized_nums = list(map(lambda num: num.factor(), numbers)) factors_num = list( map(lambda num: num.as_coeff_Mul(), factorized_nums)) term = factors_num[0][1] if all(factor == term for coeff, factor in factors_num): common_term = term coeffs = [coeff for coeff, factor in factors_num] result = lcm_list(coeffs) * common_term elif all(num.is_rational for num in numbers): result = lcm_list(numbers) else: pass return result def is_convex(f, *syms, domain=S.Reals): r"""Determines the convexity of the function passed in the argument. Parameters ========== f : :py:class:`~.Expr` The concerned function. syms : Tuple of :py:class:`~.Symbol` The variables with respect to which the convexity is to be determined. domain : :py:class:`~.Interval`, optional The domain over which the convexity of the function has to be checked. If unspecified, S.Reals will be the default domain. Returns ======= bool The method returns ``True`` if the function is convex otherwise it returns ``False``. Raises ====== NotImplementedError The check for the convexity of multivariate functions is not implemented yet. Notes ===== To determine concavity of a function pass `-f` as the concerned function. To determine logarithmic convexity of a function pass `\log(f)` as concerned function. To determine logarithmic concavity of a function pass `-\log(f)` as concerned function. Currently, convexity check of multivariate functions is not handled. Examples ======== >>> from sympy import is_convex, symbols, exp, oo, Interval >>> x = symbols('x') >>> is_convex(exp(x), x) True >>> is_convex(x**3, x, domain = Interval(-1, oo)) False >>> is_convex(1/x**2, x, domain=Interval.open(0, oo)) True References ========== .. [1] https://en.wikipedia.org/wiki/Convex_function .. [2] http://www.ifp.illinois.edu/~angelia/L3_convfunc.pdf .. [3] https://en.wikipedia.org/wiki/Logarithmically_convex_function .. [4] https://en.wikipedia.org/wiki/Logarithmically_concave_function .. [5] https://en.wikipedia.org/wiki/Concave_function """ if len(syms) > 1: raise NotImplementedError( "The check for the convexity of multivariate functions is not implemented yet.") from sympy.solvers.inequalities import solve_univariate_inequality f = _sympify(f) var = syms[0] if any(s in domain for s in singularities(f, var)): return False condition = f.diff(var, 2) < 0 if solve_univariate_inequality(condition, var, False, domain): return False return True def stationary_points(f, symbol, domain=S.Reals): """ Returns the stationary points of a function (where derivative of the function is 0) in the given domain. Parameters ========== f : :py:class:`~.Expr` The concerned function. symbol : :py:class:`~.Symbol` The variable for which the stationary points are to be determined. domain : :py:class:`~.Interval` The domain over which the stationary points have to be checked. If unspecified, ``S.Reals`` will be the default domain. Returns ======= Set A set of stationary points for the function. If there are no stationary point, an :py:class:`~.EmptySet` is returned. Examples ======== >>> from sympy import Interval, Symbol, S, sin, pi, pprint, stationary_points >>> x = Symbol('x') >>> stationary_points(1/x, x, S.Reals) EmptySet >>> pprint(stationary_points(sin(x), x), use_unicode=False) pi 3*pi {2*n*pi + -- | n in Integers} U {2*n*pi + ---- | n in Integers} 2 2 >>> stationary_points(sin(x),x, Interval(0, 4*pi)) {pi/2, 3*pi/2, 5*pi/2, 7*pi/2} """ from sympy.solvers.solveset import solveset if domain is S.EmptySet: return S.EmptySet domain = continuous_domain(f, symbol, domain) set = solveset(diff(f, symbol), symbol, domain) return set def maximum(f, symbol, domain=S.Reals): """ Returns the maximum value of a function in the given domain. Parameters ========== f : :py:class:`~.Expr` The concerned function. symbol : :py:class:`~.Symbol` The variable for maximum value needs to be determined. domain : :py:class:`~.Interval` The domain over which the maximum have to be checked. If unspecified, then the global maximum is returned. Returns ======= number Maximum value of the function in given domain. Examples ======== >>> from sympy import Interval, Symbol, S, sin, cos, pi, maximum >>> x = Symbol('x') >>> f = -x**2 + 2*x + 5 >>> maximum(f, x, S.Reals) 6 >>> maximum(sin(x), x, Interval(-pi, pi/4)) sqrt(2)/2 >>> maximum(sin(x)*cos(x), x) 1/2 """ if isinstance(symbol, Symbol): if domain is S.EmptySet: raise ValueError("Maximum value not defined for empty domain.") return function_range(f, symbol, domain).sup else: raise ValueError("%s is not a valid symbol." % symbol) def minimum(f, symbol, domain=S.Reals): """ Returns the minimum value of a function in the given domain. Parameters ========== f : :py:class:`~.Expr` The concerned function. symbol : :py:class:`~.Symbol` The variable for minimum value needs to be determined. domain : :py:class:`~.Interval` The domain over which the minimum have to be checked. If unspecified, then the global minimum is returned. Returns ======= number Minimum value of the function in the given domain. Examples ======== >>> from sympy import Interval, Symbol, S, sin, cos, minimum >>> x = Symbol('x') >>> f = x**2 + 2*x + 5 >>> minimum(f, x, S.Reals) 4 >>> minimum(sin(x), x, Interval(2, 3)) sin(3) >>> minimum(sin(x)*cos(x), x) -1/2 """ if isinstance(symbol, Symbol): if domain is S.EmptySet: raise ValueError("Minimum value not defined for empty domain.") return function_range(f, symbol, domain).inf else: raise ValueError("%s is not a valid symbol." % symbol)
c48bf9975690ecaf3ff3dd32d456529f3ba12e4aa7c3130e9e5dfdb0ea233b78
""" This module provides convenient functions to transform SymPy expressions to lambda functions which can be used to calculate numerical values very fast. """ from __future__ import annotations from typing import Any import builtins import inspect import keyword import textwrap import linecache # Required despite static analysis claiming it is not used from sympy.external import import_module # noqa:F401 from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.decorator import doctest_depends_on from sympy.utilities.iterables import (is_sequence, iterable, NotIterable, flatten) from sympy.utilities.misc import filldedent __doctest_requires__ = {('lambdify',): ['numpy', 'tensorflow']} # Default namespaces, letting us define translations that can't be defined # by simple variable maps, like I => 1j MATH_DEFAULT: dict[str, Any] = {} MPMATH_DEFAULT: dict[str, Any] = {} NUMPY_DEFAULT: dict[str, Any] = {"I": 1j} SCIPY_DEFAULT: dict[str, Any] = {"I": 1j} CUPY_DEFAULT: dict[str, Any] = {"I": 1j} JAX_DEFAULT: dict[str, Any] = {"I": 1j} TENSORFLOW_DEFAULT: dict[str, Any] = {} SYMPY_DEFAULT: dict[str, Any] = {} NUMEXPR_DEFAULT: dict[str, Any] = {} # These are the namespaces the lambda functions will use. # These are separate from the names above because they are modified # throughout this file, whereas the defaults should remain unmodified. MATH = MATH_DEFAULT.copy() MPMATH = MPMATH_DEFAULT.copy() NUMPY = NUMPY_DEFAULT.copy() SCIPY = SCIPY_DEFAULT.copy() CUPY = CUPY_DEFAULT.copy() JAX = JAX_DEFAULT.copy() TENSORFLOW = TENSORFLOW_DEFAULT.copy() SYMPY = SYMPY_DEFAULT.copy() NUMEXPR = NUMEXPR_DEFAULT.copy() # Mappings between SymPy and other modules function names. MATH_TRANSLATIONS = { "ceiling": "ceil", "E": "e", "ln": "log", } # NOTE: This dictionary is reused in Function._eval_evalf to allow subclasses # of Function to automatically evalf. MPMATH_TRANSLATIONS = { "Abs": "fabs", "elliptic_k": "ellipk", "elliptic_f": "ellipf", "elliptic_e": "ellipe", "elliptic_pi": "ellippi", "ceiling": "ceil", "chebyshevt": "chebyt", "chebyshevu": "chebyu", "E": "e", "I": "j", "ln": "log", #"lowergamma":"lower_gamma", "oo": "inf", #"uppergamma":"upper_gamma", "LambertW": "lambertw", "MutableDenseMatrix": "matrix", "ImmutableDenseMatrix": "matrix", "conjugate": "conj", "dirichlet_eta": "altzeta", "Ei": "ei", "Shi": "shi", "Chi": "chi", "Si": "si", "Ci": "ci", "RisingFactorial": "rf", "FallingFactorial": "ff", "betainc_regularized": "betainc", } NUMPY_TRANSLATIONS: dict[str, str] = { "Heaviside": "heaviside", } SCIPY_TRANSLATIONS: dict[str, str] = {} CUPY_TRANSLATIONS: dict[str, str] = {} JAX_TRANSLATIONS: dict[str, str] = {} TENSORFLOW_TRANSLATIONS: dict[str, str] = {} NUMEXPR_TRANSLATIONS: dict[str, str] = {} # Available modules: MODULES = { "math": (MATH, MATH_DEFAULT, MATH_TRANSLATIONS, ("from math import *",)), "mpmath": (MPMATH, MPMATH_DEFAULT, MPMATH_TRANSLATIONS, ("from mpmath import *",)), "numpy": (NUMPY, NUMPY_DEFAULT, NUMPY_TRANSLATIONS, ("import numpy; from numpy import *; from numpy.linalg import *",)), "scipy": (SCIPY, SCIPY_DEFAULT, SCIPY_TRANSLATIONS, ("import scipy; import numpy; from scipy.special import *",)), "cupy": (CUPY, CUPY_DEFAULT, CUPY_TRANSLATIONS, ("import cupy",)), "jax": (JAX, JAX_DEFAULT, JAX_TRANSLATIONS, ("import jax",)), "tensorflow": (TENSORFLOW, TENSORFLOW_DEFAULT, TENSORFLOW_TRANSLATIONS, ("import tensorflow",)), "sympy": (SYMPY, SYMPY_DEFAULT, {}, ( "from sympy.functions import *", "from sympy.matrices import *", "from sympy import Integral, pi, oo, nan, zoo, E, I",)), "numexpr" : (NUMEXPR, NUMEXPR_DEFAULT, NUMEXPR_TRANSLATIONS, ("import_module('numexpr')", )), } def _import(module, reload=False): """ Creates a global translation dictionary for module. The argument module has to be one of the following strings: "math", "mpmath", "numpy", "sympy", "tensorflow", "jax". These dictionaries map names of Python functions to their equivalent in other modules. """ try: namespace, namespace_default, translations, import_commands = MODULES[ module] except KeyError: raise NameError( "'%s' module cannot be used for lambdification" % module) # Clear namespace or exit if namespace != namespace_default: # The namespace was already generated, don't do it again if not forced. if reload: namespace.clear() namespace.update(namespace_default) else: return for import_command in import_commands: if import_command.startswith('import_module'): module = eval(import_command) if module is not None: namespace.update(module.__dict__) continue else: try: exec(import_command, {}, namespace) continue except ImportError: pass raise ImportError( "Cannot import '%s' with '%s' command" % (module, import_command)) # Add translated names to namespace for sympyname, translation in translations.items(): namespace[sympyname] = namespace[translation] # For computing the modulus of a SymPy expression we use the builtin abs # function, instead of the previously used fabs function for all # translation modules. This is because the fabs function in the math # module does not accept complex valued arguments. (see issue 9474). The # only exception, where we don't use the builtin abs function is the # mpmath translation module, because mpmath.fabs returns mpf objects in # contrast to abs(). if 'Abs' not in namespace: namespace['Abs'] = abs # Used for dynamically generated filenames that are inserted into the # linecache. _lambdify_generated_counter = 1 @doctest_depends_on(modules=('numpy', 'scipy', 'tensorflow',), python_version=(3,)) def lambdify(args, expr, modules=None, printer=None, use_imps=True, dummify=False, cse=False): """Convert a SymPy expression into a function that allows for fast numeric evaluation. .. warning:: This function uses ``exec``, and thus should not be used on unsanitized input. .. deprecated:: 1.7 Passing a set for the *args* parameter is deprecated as sets are unordered. Use an ordered iterable such as a list or tuple. Explanation =========== For example, to convert the SymPy expression ``sin(x) + cos(x)`` to an equivalent NumPy function that numerically evaluates it: >>> from sympy import sin, cos, symbols, lambdify >>> import numpy as np >>> x = symbols('x') >>> expr = sin(x) + cos(x) >>> expr sin(x) + cos(x) >>> f = lambdify(x, expr, 'numpy') >>> a = np.array([1, 2]) >>> f(a) [1.38177329 0.49315059] The primary purpose of this function is to provide a bridge from SymPy expressions to numerical libraries such as NumPy, SciPy, NumExpr, mpmath, and tensorflow. In general, SymPy functions do not work with objects from other libraries, such as NumPy arrays, and functions from numeric libraries like NumPy or mpmath do not work on SymPy expressions. ``lambdify`` bridges the two by converting a SymPy expression to an equivalent numeric function. The basic workflow with ``lambdify`` is to first create a SymPy expression representing whatever mathematical function you wish to evaluate. This should be done using only SymPy functions and expressions. Then, use ``lambdify`` to convert this to an equivalent function for numerical evaluation. For instance, above we created ``expr`` using the SymPy symbol ``x`` and SymPy functions ``sin`` and ``cos``, then converted it to an equivalent NumPy function ``f``, and called it on a NumPy array ``a``. Parameters ========== args : List[Symbol] A variable or a list of variables whose nesting represents the nesting of the arguments that will be passed to the function. Variables can be symbols, undefined functions, or matrix symbols. >>> from sympy import Eq >>> from sympy.abc import x, y, z The list of variables should match the structure of how the arguments will be passed to the function. Simply enclose the parameters as they will be passed in a list. To call a function like ``f(x)`` then ``[x]`` should be the first argument to ``lambdify``; for this case a single ``x`` can also be used: >>> f = lambdify(x, x + 1) >>> f(1) 2 >>> f = lambdify([x], x + 1) >>> f(1) 2 To call a function like ``f(x, y)`` then ``[x, y]`` will be the first argument of the ``lambdify``: >>> f = lambdify([x, y], x + y) >>> f(1, 1) 2 To call a function with a single 3-element tuple like ``f((x, y, z))`` then ``[(x, y, z)]`` will be the first argument of the ``lambdify``: >>> f = lambdify([(x, y, z)], Eq(z**2, x**2 + y**2)) >>> f((3, 4, 5)) True If two args will be passed and the first is a scalar but the second is a tuple with two arguments then the items in the list should match that structure: >>> f = lambdify([x, (y, z)], x + y + z) >>> f(1, (2, 3)) 6 expr : Expr An expression, list of expressions, or matrix to be evaluated. Lists may be nested. If the expression is a list, the output will also be a list. >>> f = lambdify(x, [x, [x + 1, x + 2]]) >>> f(1) [1, [2, 3]] If it is a matrix, an array will be returned (for the NumPy module). >>> from sympy import Matrix >>> f = lambdify(x, Matrix([x, x + 1])) >>> f(1) [[1] [2]] Note that the argument order here (variables then expression) is used to emulate the Python ``lambda`` keyword. ``lambdify(x, expr)`` works (roughly) like ``lambda x: expr`` (see :ref:`lambdify-how-it-works` below). modules : str, optional Specifies the numeric library to use. If not specified, *modules* defaults to: - ``["scipy", "numpy"]`` if SciPy is installed - ``["numpy"]`` if only NumPy is installed - ``["math", "mpmath", "sympy"]`` if neither is installed. That is, SymPy functions are replaced as far as possible by either ``scipy`` or ``numpy`` functions if available, and Python's standard library ``math``, or ``mpmath`` functions otherwise. *modules* can be one of the following types: - The strings ``"math"``, ``"mpmath"``, ``"numpy"``, ``"numexpr"``, ``"scipy"``, ``"sympy"``, or ``"tensorflow"`` or ``"jax"``. This uses the corresponding printer and namespace mapping for that module. - A module (e.g., ``math``). This uses the global namespace of the module. If the module is one of the above known modules, it will also use the corresponding printer and namespace mapping (i.e., ``modules=numpy`` is equivalent to ``modules="numpy"``). - A dictionary that maps names of SymPy functions to arbitrary functions (e.g., ``{'sin': custom_sin}``). - A list that contains a mix of the arguments above, with higher priority given to entries appearing first (e.g., to use the NumPy module but override the ``sin`` function with a custom version, you can use ``[{'sin': custom_sin}, 'numpy']``). dummify : bool, optional Whether or not the variables in the provided expression that are not valid Python identifiers are substituted with dummy symbols. This allows for undefined functions like ``Function('f')(t)`` to be supplied as arguments. By default, the variables are only dummified if they are not valid Python identifiers. Set ``dummify=True`` to replace all arguments with dummy symbols (if ``args`` is not a string) - for example, to ensure that the arguments do not redefine any built-in names. cse : bool, or callable, optional Large expressions can be computed more efficiently when common subexpressions are identified and precomputed before being used multiple time. Finding the subexpressions will make creation of the 'lambdify' function slower, however. When ``True``, ``sympy.simplify.cse`` is used, otherwise (the default) the user may pass a function matching the ``cse`` signature. Examples ======== >>> from sympy.utilities.lambdify import implemented_function >>> from sympy import sqrt, sin, Matrix >>> from sympy import Function >>> from sympy.abc import w, x, y, z >>> f = lambdify(x, x**2) >>> f(2) 4 >>> f = lambdify((x, y, z), [z, y, x]) >>> f(1,2,3) [3, 2, 1] >>> f = lambdify(x, sqrt(x)) >>> f(4) 2.0 >>> f = lambdify((x, y), sin(x*y)**2) >>> f(0, 5) 0.0 >>> row = lambdify((x, y), Matrix((x, x + y)).T, modules='sympy') >>> row(1, 2) Matrix([[1, 3]]) ``lambdify`` can be used to translate SymPy expressions into mpmath functions. This may be preferable to using ``evalf`` (which uses mpmath on the backend) in some cases. >>> f = lambdify(x, sin(x), 'mpmath') >>> f(1) 0.8414709848078965 Tuple arguments are handled and the lambdified function should be called with the same type of arguments as were used to create the function: >>> f = lambdify((x, (y, z)), x + y) >>> f(1, (2, 4)) 3 The ``flatten`` function can be used to always work with flattened arguments: >>> from sympy.utilities.iterables import flatten >>> args = w, (x, (y, z)) >>> vals = 1, (2, (3, 4)) >>> f = lambdify(flatten(args), w + x + y + z) >>> f(*flatten(vals)) 10 Functions present in ``expr`` can also carry their own numerical implementations, in a callable attached to the ``_imp_`` attribute. This can be used with undefined functions using the ``implemented_function`` factory: >>> f = implemented_function(Function('f'), lambda x: x+1) >>> func = lambdify(x, f(x)) >>> func(4) 5 ``lambdify`` always prefers ``_imp_`` implementations to implementations in other namespaces, unless the ``use_imps`` input parameter is False. Usage with Tensorflow: >>> import tensorflow as tf >>> from sympy import Max, sin, lambdify >>> from sympy.abc import x >>> f = Max(x, sin(x)) >>> func = lambdify(x, f, 'tensorflow') After tensorflow v2, eager execution is enabled by default. If you want to get the compatible result across tensorflow v1 and v2 as same as this tutorial, run this line. >>> tf.compat.v1.enable_eager_execution() If you have eager execution enabled, you can get the result out immediately as you can use numpy. If you pass tensorflow objects, you may get an ``EagerTensor`` object instead of value. >>> result = func(tf.constant(1.0)) >>> print(result) tf.Tensor(1.0, shape=(), dtype=float32) >>> print(result.__class__) <class 'tensorflow.python.framework.ops.EagerTensor'> You can use ``.numpy()`` to get the numpy value of the tensor. >>> result.numpy() 1.0 >>> var = tf.Variable(2.0) >>> result = func(var) # also works for tf.Variable and tf.Placeholder >>> result.numpy() 2.0 And it works with any shape array. >>> tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]]) >>> result = func(tensor) >>> result.numpy() [[1. 2.] [3. 4.]] Notes ===== - For functions involving large array calculations, numexpr can provide a significant speedup over numpy. Please note that the available functions for numexpr are more limited than numpy but can be expanded with ``implemented_function`` and user defined subclasses of Function. If specified, numexpr may be the only option in modules. The official list of numexpr functions can be found at: https://numexpr.readthedocs.io/en/latest/user_guide.html#supported-functions - In the above examples, the generated functions can accept scalar values or numpy arrays as arguments. However, in some cases the generated function relies on the input being a numpy array: >>> import numpy >>> from sympy import Piecewise >>> from sympy.testing.pytest import ignore_warnings >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "numpy") >>> with ignore_warnings(RuntimeWarning): ... f(numpy.array([-1, 0, 1, 2])) [-1. 0. 1. 0.5] >>> f(0) Traceback (most recent call last): ... ZeroDivisionError: division by zero In such cases, the input should be wrapped in a numpy array: >>> with ignore_warnings(RuntimeWarning): ... float(f(numpy.array([0]))) 0.0 Or if numpy functionality is not required another module can be used: >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "math") >>> f(0) 0 .. _lambdify-how-it-works: How it works ============ When using this function, it helps a great deal to have an idea of what it is doing. At its core, lambdify is nothing more than a namespace translation, on top of a special printer that makes some corner cases work properly. To understand lambdify, first we must properly understand how Python namespaces work. Say we had two files. One called ``sin_cos_sympy.py``, with .. code:: python # sin_cos_sympy.py from sympy.functions.elementary.trigonometric import (cos, sin) def sin_cos(x): return sin(x) + cos(x) and one called ``sin_cos_numpy.py`` with .. code:: python # sin_cos_numpy.py from numpy import sin, cos def sin_cos(x): return sin(x) + cos(x) The two files define an identical function ``sin_cos``. However, in the first file, ``sin`` and ``cos`` are defined as the SymPy ``sin`` and ``cos``. In the second, they are defined as the NumPy versions. If we were to import the first file and use the ``sin_cos`` function, we would get something like >>> from sin_cos_sympy import sin_cos # doctest: +SKIP >>> sin_cos(1) # doctest: +SKIP cos(1) + sin(1) On the other hand, if we imported ``sin_cos`` from the second file, we would get >>> from sin_cos_numpy import sin_cos # doctest: +SKIP >>> sin_cos(1) # doctest: +SKIP 1.38177329068 In the first case we got a symbolic output, because it used the symbolic ``sin`` and ``cos`` functions from SymPy. In the second, we got a numeric result, because ``sin_cos`` used the numeric ``sin`` and ``cos`` functions from NumPy. But notice that the versions of ``sin`` and ``cos`` that were used was not inherent to the ``sin_cos`` function definition. Both ``sin_cos`` definitions are exactly the same. Rather, it was based on the names defined at the module where the ``sin_cos`` function was defined. The key point here is that when function in Python references a name that is not defined in the function, that name is looked up in the "global" namespace of the module where that function is defined. Now, in Python, we can emulate this behavior without actually writing a file to disk using the ``exec`` function. ``exec`` takes a string containing a block of Python code, and a dictionary that should contain the global variables of the module. It then executes the code "in" that dictionary, as if it were the module globals. The following is equivalent to the ``sin_cos`` defined in ``sin_cos_sympy.py``: >>> import sympy >>> module_dictionary = {'sin': sympy.sin, 'cos': sympy.cos} >>> exec(''' ... def sin_cos(x): ... return sin(x) + cos(x) ... ''', module_dictionary) >>> sin_cos = module_dictionary['sin_cos'] >>> sin_cos(1) cos(1) + sin(1) and similarly with ``sin_cos_numpy``: >>> import numpy >>> module_dictionary = {'sin': numpy.sin, 'cos': numpy.cos} >>> exec(''' ... def sin_cos(x): ... return sin(x) + cos(x) ... ''', module_dictionary) >>> sin_cos = module_dictionary['sin_cos'] >>> sin_cos(1) 1.38177329068 So now we can get an idea of how ``lambdify`` works. The name "lambdify" comes from the fact that we can think of something like ``lambdify(x, sin(x) + cos(x), 'numpy')`` as ``lambda x: sin(x) + cos(x)``, where ``sin`` and ``cos`` come from the ``numpy`` namespace. This is also why the symbols argument is first in ``lambdify``, as opposed to most SymPy functions where it comes after the expression: to better mimic the ``lambda`` keyword. ``lambdify`` takes the input expression (like ``sin(x) + cos(x)``) and 1. Converts it to a string 2. Creates a module globals dictionary based on the modules that are passed in (by default, it uses the NumPy module) 3. Creates the string ``"def func({vars}): return {expr}"``, where ``{vars}`` is the list of variables separated by commas, and ``{expr}`` is the string created in step 1., then ``exec``s that string with the module globals namespace and returns ``func``. In fact, functions returned by ``lambdify`` support inspection. So you can see exactly how they are defined by using ``inspect.getsource``, or ``??`` if you are using IPython or the Jupyter notebook. >>> f = lambdify(x, sin(x) + cos(x)) >>> import inspect >>> print(inspect.getsource(f)) def _lambdifygenerated(x): return sin(x) + cos(x) This shows us the source code of the function, but not the namespace it was defined in. We can inspect that by looking at the ``__globals__`` attribute of ``f``: >>> f.__globals__['sin'] <ufunc 'sin'> >>> f.__globals__['cos'] <ufunc 'cos'> >>> f.__globals__['sin'] is numpy.sin True This shows us that ``sin`` and ``cos`` in the namespace of ``f`` will be ``numpy.sin`` and ``numpy.cos``. Note that there are some convenience layers in each of these steps, but at the core, this is how ``lambdify`` works. Step 1 is done using the ``LambdaPrinter`` printers defined in the printing module (see :mod:`sympy.printing.lambdarepr`). This allows different SymPy expressions to define how they should be converted to a string for different modules. You can change which printer ``lambdify`` uses by passing a custom printer in to the ``printer`` argument. Step 2 is augmented by certain translations. There are default translations for each module, but you can provide your own by passing a list to the ``modules`` argument. For instance, >>> def mysin(x): ... print('taking the sin of', x) ... return numpy.sin(x) ... >>> f = lambdify(x, sin(x), [{'sin': mysin}, 'numpy']) >>> f(1) taking the sin of 1 0.8414709848078965 The globals dictionary is generated from the list by merging the dictionary ``{'sin': mysin}`` and the module dictionary for NumPy. The merging is done so that earlier items take precedence, which is why ``mysin`` is used above instead of ``numpy.sin``. If you want to modify the way ``lambdify`` works for a given function, it is usually easiest to do so by modifying the globals dictionary as such. In more complicated cases, it may be necessary to create and pass in a custom printer. Finally, step 3 is augmented with certain convenience operations, such as the addition of a docstring. Understanding how ``lambdify`` works can make it easier to avoid certain gotchas when using it. For instance, a common mistake is to create a lambdified function for one module (say, NumPy), and pass it objects from another (say, a SymPy expression). For instance, say we create >>> from sympy.abc import x >>> f = lambdify(x, x + 1, 'numpy') Now if we pass in a NumPy array, we get that array plus 1 >>> import numpy >>> a = numpy.array([1, 2]) >>> f(a) [2 3] But what happens if you make the mistake of passing in a SymPy expression instead of a NumPy array: >>> f(x + 1) x + 2 This worked, but it was only by accident. Now take a different lambdified function: >>> from sympy import sin >>> g = lambdify(x, x + sin(x), 'numpy') This works as expected on NumPy arrays: >>> g(a) [1.84147098 2.90929743] But if we try to pass in a SymPy expression, it fails >>> try: ... g(x + 1) ... # NumPy release after 1.17 raises TypeError instead of ... # AttributeError ... except (AttributeError, TypeError): ... raise AttributeError() # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... AttributeError: Now, let's look at what happened. The reason this fails is that ``g`` calls ``numpy.sin`` on the input expression, and ``numpy.sin`` does not know how to operate on a SymPy object. **As a general rule, NumPy functions do not know how to operate on SymPy expressions, and SymPy functions do not know how to operate on NumPy arrays. This is why lambdify exists: to provide a bridge between SymPy and NumPy.** However, why is it that ``f`` did work? That's because ``f`` does not call any functions, it only adds 1. So the resulting function that is created, ``def _lambdifygenerated(x): return x + 1`` does not depend on the globals namespace it is defined in. Thus it works, but only by accident. A future version of ``lambdify`` may remove this behavior. Be aware that certain implementation details described here may change in future versions of SymPy. The API of passing in custom modules and printers will not change, but the details of how a lambda function is created may change. However, the basic idea will remain the same, and understanding it will be helpful to understanding the behavior of lambdify. **In general: you should create lambdified functions for one module (say, NumPy), and only pass it input types that are compatible with that module (say, NumPy arrays).** Remember that by default, if the ``module`` argument is not provided, ``lambdify`` creates functions using the NumPy and SciPy namespaces. """ from sympy.core.symbol import Symbol from sympy.core.expr import Expr # If the user hasn't specified any modules, use what is available. if modules is None: try: _import("scipy") except ImportError: try: _import("numpy") except ImportError: # Use either numpy (if available) or python.math where possible. # XXX: This leads to different behaviour on different systems and # might be the reason for irreproducible errors. modules = ["math", "mpmath", "sympy"] else: modules = ["numpy"] else: modules = ["numpy", "scipy"] # Get the needed namespaces. namespaces = [] # First find any function implementations if use_imps: namespaces.append(_imp_namespace(expr)) # Check for dict before iterating if isinstance(modules, (dict, str)) or not hasattr(modules, '__iter__'): namespaces.append(modules) else: # consistency check if _module_present('numexpr', modules) and len(modules) > 1: raise TypeError("numexpr must be the only item in 'modules'") namespaces += list(modules) # fill namespace with first having highest priority namespace = {} for m in namespaces[::-1]: buf = _get_namespace(m) namespace.update(buf) if hasattr(expr, "atoms"): #Try if you can extract symbols from the expression. #Move on if expr.atoms in not implemented. syms = expr.atoms(Symbol) for term in syms: namespace.update({str(term): term}) if printer is None: if _module_present('mpmath', namespaces): from sympy.printing.pycode import MpmathPrinter as Printer # type: ignore elif _module_present('scipy', namespaces): from sympy.printing.numpy import SciPyPrinter as Printer # type: ignore elif _module_present('numpy', namespaces): from sympy.printing.numpy import NumPyPrinter as Printer # type: ignore elif _module_present('cupy', namespaces): from sympy.printing.numpy import CuPyPrinter as Printer # type: ignore elif _module_present('jax', namespaces): from sympy.printing.numpy import JaxPrinter as Printer # type: ignore elif _module_present('numexpr', namespaces): from sympy.printing.lambdarepr import NumExprPrinter as Printer # type: ignore elif _module_present('tensorflow', namespaces): from sympy.printing.tensorflow import TensorflowPrinter as Printer # type: ignore elif _module_present('sympy', namespaces): from sympy.printing.pycode import SymPyPrinter as Printer # type: ignore else: from sympy.printing.pycode import PythonCodePrinter as Printer # type: ignore user_functions = {} for m in namespaces[::-1]: if isinstance(m, dict): for k in m: user_functions[k] = k printer = Printer({'fully_qualified_modules': False, 'inline': True, 'allow_unknown_functions': True, 'user_functions': user_functions}) if isinstance(args, set): sympy_deprecation_warning( """ Passing the function arguments to lambdify() as a set is deprecated. This leads to unpredictable results since sets are unordered. Instead, use a list or tuple for the function arguments. """, deprecated_since_version="1.6.3", active_deprecations_target="deprecated-lambdify-arguments-set", ) # Get the names of the args, for creating a docstring iterable_args = (args,) if isinstance(args, Expr) else args names = [] # Grab the callers frame, for getting the names by inspection (if needed) callers_local_vars = inspect.currentframe().f_back.f_locals.items() # type: ignore for n, var in enumerate(iterable_args): if hasattr(var, 'name'): names.append(var.name) else: # It's an iterable. Try to get name by inspection of calling frame. name_list = [var_name for var_name, var_val in callers_local_vars if var_val is var] if len(name_list) == 1: names.append(name_list[0]) else: # Cannot infer name with certainty. arg_# will have to do. names.append('arg_' + str(n)) # Create the function definition code and execute it funcname = '_lambdifygenerated' if _module_present('tensorflow', namespaces): funcprinter = _TensorflowEvaluatorPrinter(printer, dummify) else: funcprinter = _EvaluatorPrinter(printer, dummify) if cse == True: from sympy.simplify.cse_main import cse as _cse cses, _expr = _cse(expr, list=False) elif callable(cse): cses, _expr = cse(expr) else: cses, _expr = (), expr funcstr = funcprinter.doprint(funcname, iterable_args, _expr, cses=cses) # Collect the module imports from the code printers. imp_mod_lines = [] for mod, keys in (getattr(printer, 'module_imports', None) or {}).items(): for k in keys: if k not in namespace: ln = "from %s import %s" % (mod, k) try: exec(ln, {}, namespace) except ImportError: # Tensorflow 2.0 has issues with importing a specific # function from its submodule. # https://github.com/tensorflow/tensorflow/issues/33022 ln = "%s = %s.%s" % (k, mod, k) exec(ln, {}, namespace) imp_mod_lines.append(ln) # Provide lambda expression with builtins, and compatible implementation of range namespace.update({'builtins':builtins, 'range':range}) funclocals = {} global _lambdify_generated_counter filename = '<lambdifygenerated-%s>' % _lambdify_generated_counter _lambdify_generated_counter += 1 c = compile(funcstr, filename, 'exec') exec(c, namespace, funclocals) # mtime has to be None or else linecache.checkcache will remove it linecache.cache[filename] = (len(funcstr), None, funcstr.splitlines(True), filename) # type: ignore func = funclocals[funcname] # Apply the docstring sig = "func({})".format(", ".join(str(i) for i in names)) sig = textwrap.fill(sig, subsequent_indent=' '*8) expr_str = str(expr) if len(expr_str) > 78: expr_str = textwrap.wrap(expr_str, 75)[0] + '...' func.__doc__ = ( "Created with lambdify. Signature:\n\n" "{sig}\n\n" "Expression:\n\n" "{expr}\n\n" "Source code:\n\n" "{src}\n\n" "Imported modules:\n\n" "{imp_mods}" ).format(sig=sig, expr=expr_str, src=funcstr, imp_mods='\n'.join(imp_mod_lines)) return func def _module_present(modname, modlist): if modname in modlist: return True for m in modlist: if hasattr(m, '__name__') and m.__name__ == modname: return True return False def _get_namespace(m): """ This is used by _lambdify to parse its arguments. """ if isinstance(m, str): _import(m) return MODULES[m][0] elif isinstance(m, dict): return m elif hasattr(m, "__dict__"): return m.__dict__ else: raise TypeError("Argument must be either a string, dict or module but it is: %s" % m) def _recursive_to_string(doprint, arg): """Functions in lambdify accept both SymPy types and non-SymPy types such as python lists and tuples. This method ensures that we only call the doprint method of the printer with SymPy types (so that the printer safely can use SymPy-methods).""" from sympy.matrices.common import MatrixOperations from sympy.core.basic import Basic if isinstance(arg, (Basic, MatrixOperations)): return doprint(arg) elif iterable(arg): if isinstance(arg, list): left, right = "[", "]" elif isinstance(arg, tuple): left, right = "(", ",)" else: raise NotImplementedError("unhandled type: %s, %s" % (type(arg), arg)) return left +', '.join(_recursive_to_string(doprint, e) for e in arg) + right elif isinstance(arg, str): return arg else: return doprint(arg) def lambdastr(args, expr, printer=None, dummify=None): """ Returns a string that can be evaluated to a lambda function. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.utilities.lambdify import lambdastr >>> lambdastr(x, x**2) 'lambda x: (x**2)' >>> lambdastr((x,y,z), [z,y,x]) 'lambda x,y,z: ([z, y, x])' Although tuples may not appear as arguments to lambda in Python 3, lambdastr will create a lambda function that will unpack the original arguments so that nested arguments can be handled: >>> lambdastr((x, (y, z)), x + y) 'lambda _0,_1: (lambda x,y,z: (x + y))(_0,_1[0],_1[1])' """ # Transforming everything to strings. from sympy.matrices import DeferredVector from sympy.core.basic import Basic from sympy.core.function import (Derivative, Function) from sympy.core.symbol import (Dummy, Symbol) from sympy.core.sympify import sympify if printer is not None: if inspect.isfunction(printer): lambdarepr = printer else: if inspect.isclass(printer): lambdarepr = lambda expr: printer().doprint(expr) else: lambdarepr = lambda expr: printer.doprint(expr) else: #XXX: This has to be done here because of circular imports from sympy.printing.lambdarepr import lambdarepr def sub_args(args, dummies_dict): if isinstance(args, str): return args elif isinstance(args, DeferredVector): return str(args) elif iterable(args): dummies = flatten([sub_args(a, dummies_dict) for a in args]) return ",".join(str(a) for a in dummies) else: # replace these with Dummy symbols if isinstance(args, (Function, Symbol, Derivative)): dummies = Dummy() dummies_dict.update({args : dummies}) return str(dummies) else: return str(args) def sub_expr(expr, dummies_dict): expr = sympify(expr) # dict/tuple are sympified to Basic if isinstance(expr, Basic): expr = expr.xreplace(dummies_dict) # list is not sympified to Basic elif isinstance(expr, list): expr = [sub_expr(a, dummies_dict) for a in expr] return expr # Transform args def isiter(l): return iterable(l, exclude=(str, DeferredVector, NotIterable)) def flat_indexes(iterable): n = 0 for el in iterable: if isiter(el): for ndeep in flat_indexes(el): yield (n,) + ndeep else: yield (n,) n += 1 if dummify is None: dummify = any(isinstance(a, Basic) and a.atoms(Function, Derivative) for a in ( args if isiter(args) else [args])) if isiter(args) and any(isiter(i) for i in args): dum_args = [str(Dummy(str(i))) for i in range(len(args))] indexed_args = ','.join([ dum_args[ind[0]] + ''.join(["[%s]" % k for k in ind[1:]]) for ind in flat_indexes(args)]) lstr = lambdastr(flatten(args), expr, printer=printer, dummify=dummify) return 'lambda %s: (%s)(%s)' % (','.join(dum_args), lstr, indexed_args) dummies_dict = {} if dummify: args = sub_args(args, dummies_dict) else: if isinstance(args, str): pass elif iterable(args, exclude=DeferredVector): args = ",".join(str(a) for a in args) # Transform expr if dummify: if isinstance(expr, str): pass else: expr = sub_expr(expr, dummies_dict) expr = _recursive_to_string(lambdarepr, expr) return "lambda %s: (%s)" % (args, expr) class _EvaluatorPrinter: def __init__(self, printer=None, dummify=False): self._dummify = dummify #XXX: This has to be done here because of circular imports from sympy.printing.lambdarepr import LambdaPrinter if printer is None: printer = LambdaPrinter() if inspect.isfunction(printer): self._exprrepr = printer else: if inspect.isclass(printer): printer = printer() self._exprrepr = printer.doprint #if hasattr(printer, '_print_Symbol'): # symbolrepr = printer._print_Symbol #if hasattr(printer, '_print_Dummy'): # dummyrepr = printer._print_Dummy # Used to print the generated function arguments in a standard way self._argrepr = LambdaPrinter().doprint def doprint(self, funcname, args, expr, *, cses=()): """ Returns the function definition code as a string. """ from sympy.core.symbol import Dummy funcbody = [] if not iterable(args): args = [args] if cses: subvars, subexprs = zip(*cses) exprs = [expr] + list(subexprs) argstrs, exprs = self._preprocess(args, exprs) expr, subexprs = exprs[0], exprs[1:] cses = zip(subvars, subexprs) else: argstrs, expr = self._preprocess(args, expr) # Generate argument unpacking and final argument list funcargs = [] unpackings = [] for argstr in argstrs: if iterable(argstr): funcargs.append(self._argrepr(Dummy())) unpackings.extend(self._print_unpacking(argstr, funcargs[-1])) else: funcargs.append(argstr) funcsig = 'def {}({}):'.format(funcname, ', '.join(funcargs)) # Wrap input arguments before unpacking funcbody.extend(self._print_funcargwrapping(funcargs)) funcbody.extend(unpackings) for s, e in cses: if e is None: funcbody.append('del {}'.format(s)) else: funcbody.append('{} = {}'.format(s, self._exprrepr(e))) str_expr = _recursive_to_string(self._exprrepr, expr) if '\n' in str_expr: str_expr = '({})'.format(str_expr) funcbody.append('return {}'.format(str_expr)) funclines = [funcsig] funclines.extend([' ' + line for line in funcbody]) return '\n'.join(funclines) + '\n' @classmethod def _is_safe_ident(cls, ident): return isinstance(ident, str) and ident.isidentifier() \ and not keyword.iskeyword(ident) def _preprocess(self, args, expr): """Preprocess args, expr to replace arguments that do not map to valid Python identifiers. Returns string form of args, and updated expr. """ from sympy.core.basic import Basic from sympy.core.sorting import ordered from sympy.core.function import (Derivative, Function) from sympy.core.symbol import Dummy, uniquely_named_symbol from sympy.matrices import DeferredVector from sympy.core.expr import Expr # Args of type Dummy can cause name collisions with args # of type Symbol. Force dummify of everything in this # situation. dummify = self._dummify or any( isinstance(arg, Dummy) for arg in flatten(args)) argstrs = [None]*len(args) for arg, i in reversed(list(ordered(zip(args, range(len(args)))))): if iterable(arg): s, expr = self._preprocess(arg, expr) elif isinstance(arg, DeferredVector): s = str(arg) elif isinstance(arg, Basic) and arg.is_symbol: s = self._argrepr(arg) if dummify or not self._is_safe_ident(s): dummy = Dummy() if isinstance(expr, Expr): dummy = uniquely_named_symbol( dummy.name, expr, modify=lambda s: '_' + s) s = self._argrepr(dummy) expr = self._subexpr(expr, {arg: dummy}) elif dummify or isinstance(arg, (Function, Derivative)): dummy = Dummy() s = self._argrepr(dummy) expr = self._subexpr(expr, {arg: dummy}) else: s = str(arg) argstrs[i] = s return argstrs, expr def _subexpr(self, expr, dummies_dict): from sympy.matrices import DeferredVector from sympy.core.sympify import sympify expr = sympify(expr) xreplace = getattr(expr, 'xreplace', None) if xreplace is not None: expr = xreplace(dummies_dict) else: if isinstance(expr, DeferredVector): pass elif isinstance(expr, dict): k = [self._subexpr(sympify(a), dummies_dict) for a in expr.keys()] v = [self._subexpr(sympify(a), dummies_dict) for a in expr.values()] expr = dict(zip(k, v)) elif isinstance(expr, tuple): expr = tuple(self._subexpr(sympify(a), dummies_dict) for a in expr) elif isinstance(expr, list): expr = [self._subexpr(sympify(a), dummies_dict) for a in expr] return expr def _print_funcargwrapping(self, args): """Generate argument wrapping code. args is the argument list of the generated function (strings). Return value is a list of lines of code that will be inserted at the beginning of the function definition. """ return [] def _print_unpacking(self, unpackto, arg): """Generate argument unpacking code. arg is the function argument to be unpacked (a string), and unpackto is a list or nested lists of the variable names (strings) to unpack to. """ def unpack_lhs(lvalues): return '[{}]'.format(', '.join( unpack_lhs(val) if iterable(val) else val for val in lvalues)) return ['{} = {}'.format(unpack_lhs(unpackto), arg)] class _TensorflowEvaluatorPrinter(_EvaluatorPrinter): def _print_unpacking(self, lvalues, rvalue): """Generate argument unpacking code. This method is used when the input value is not interable, but can be indexed (see issue #14655). """ def flat_indexes(elems): n = 0 for el in elems: if iterable(el): for ndeep in flat_indexes(el): yield (n,) + ndeep else: yield (n,) n += 1 indexed = ', '.join('{}[{}]'.format(rvalue, ']['.join(map(str, ind))) for ind in flat_indexes(lvalues)) return ['[{}] = [{}]'.format(', '.join(flatten(lvalues)), indexed)] def _imp_namespace(expr, namespace=None): """ Return namespace dict with function implementations We need to search for functions in anything that can be thrown at us - that is - anything that could be passed as ``expr``. Examples include SymPy expressions, as well as tuples, lists and dicts that may contain SymPy expressions. Parameters ---------- expr : object Something passed to lambdify, that will generate valid code from ``str(expr)``. namespace : None or mapping Namespace to fill. None results in new empty dict Returns ------- namespace : dict dict with keys of implemented function names within ``expr`` and corresponding values being the numerical implementation of function Examples ======== >>> from sympy.abc import x >>> from sympy.utilities.lambdify import implemented_function, _imp_namespace >>> from sympy import Function >>> f = implemented_function(Function('f'), lambda x: x+1) >>> g = implemented_function(Function('g'), lambda x: x*10) >>> namespace = _imp_namespace(f(g(x))) >>> sorted(namespace.keys()) ['f', 'g'] """ # Delayed import to avoid circular imports from sympy.core.function import FunctionClass if namespace is None: namespace = {} # tuples, lists, dicts are valid expressions if is_sequence(expr): for arg in expr: _imp_namespace(arg, namespace) return namespace elif isinstance(expr, dict): for key, val in expr.items(): # functions can be in dictionary keys _imp_namespace(key, namespace) _imp_namespace(val, namespace) return namespace # SymPy expressions may be Functions themselves func = getattr(expr, 'func', None) if isinstance(func, FunctionClass): imp = getattr(func, '_imp_', None) if imp is not None: name = expr.func.__name__ if name in namespace and namespace[name] != imp: raise ValueError('We found more than one ' 'implementation with name ' '"%s"' % name) namespace[name] = imp # and / or they may take Functions as arguments if hasattr(expr, 'args'): for arg in expr.args: _imp_namespace(arg, namespace) return namespace def implemented_function(symfunc, implementation): """ Add numerical ``implementation`` to function ``symfunc``. ``symfunc`` can be an ``UndefinedFunction`` instance, or a name string. In the latter case we create an ``UndefinedFunction`` instance with that name. Be aware that this is a quick workaround, not a general method to create special symbolic functions. If you want to create a symbolic function to be used by all the machinery of SymPy you should subclass the ``Function`` class. Parameters ---------- symfunc : ``str`` or ``UndefinedFunction`` instance If ``str``, then create new ``UndefinedFunction`` with this as name. If ``symfunc`` is an Undefined function, create a new function with the same name and the implemented function attached. implementation : callable numerical implementation to be called by ``evalf()`` or ``lambdify`` Returns ------- afunc : sympy.FunctionClass instance function with attached implementation Examples ======== >>> from sympy.abc import x >>> from sympy.utilities.lambdify import implemented_function >>> from sympy import lambdify >>> f = implemented_function('f', lambda x: x+1) >>> lam_f = lambdify(x, f(x)) >>> lam_f(4) 5 """ # Delayed import to avoid circular imports from sympy.core.function import UndefinedFunction # if name, create function to hold implementation kwargs = {} if isinstance(symfunc, UndefinedFunction): kwargs = symfunc._kwargs symfunc = symfunc.__name__ if isinstance(symfunc, str): # Keyword arguments to UndefinedFunction are added as attributes to # the created class. symfunc = UndefinedFunction( symfunc, _imp_=staticmethod(implementation), **kwargs) elif not isinstance(symfunc, UndefinedFunction): raise ValueError(filldedent(''' symfunc should be either a string or an UndefinedFunction instance.''')) return symfunc
a58a6dcb660382f1792c1ae68805728aaa62aa17c57984df41f4bbb1340c364b
""" Algorithms and classes to support enumerative combinatorics. Currently just multiset partitions, but more could be added. Terminology (following Knuth, algorithm 7.1.2.5M TAOCP) *multiset* aaabbcccc has a *partition* aaabc | bccc The submultisets, aaabc and bccc of the partition are called *parts*, or sometimes *vectors*. (Knuth notes that multiset partitions can be thought of as partitions of vectors of integers, where the ith element of the vector gives the multiplicity of element i.) The values a, b and c are *components* of the multiset. These correspond to elements of a set, but in a multiset can be present with a multiplicity greater than 1. The algorithm deserves some explanation. Think of the part aaabc from the multiset above. If we impose an ordering on the components of the multiset, we can represent a part with a vector, in which the value of the first element of the vector corresponds to the multiplicity of the first component in that part. Thus, aaabc can be represented by the vector [3, 1, 1]. We can also define an ordering on parts, based on the lexicographic ordering of the vector (leftmost vector element, i.e., the element with the smallest component number, is the most significant), so that [3, 1, 1] > [3, 1, 0] and [3, 1, 1] > [2, 1, 4]. The ordering on parts can be extended to an ordering on partitions: First, sort the parts in each partition, left-to-right in decreasing order. Then partition A is greater than partition B if A's leftmost/greatest part is greater than B's leftmost part. If the leftmost parts are equal, compare the second parts, and so on. In this ordering, the greatest partition of a given multiset has only one part. The least partition is the one in which the components are spread out, one per part. The enumeration algorithms in this file yield the partitions of the argument multiset in decreasing order. The main data structure is a stack of parts, corresponding to the current partition. An important invariant is that the parts on the stack are themselves in decreasing order. This data structure is decremented to find the next smaller partition. Most often, decrementing the partition will only involve adjustments to the smallest parts at the top of the stack, much as adjacent integers *usually* differ only in their last few digits. Knuth's algorithm uses two main operations on parts: Decrement - change the part so that it is smaller in the (vector) lexicographic order, but reduced by the smallest amount possible. For example, if the multiset has vector [5, 3, 1], and the bottom/greatest part is [4, 2, 1], this part would decrement to [4, 2, 0], while [4, 0, 0] would decrement to [3, 3, 1]. A singleton part is never decremented -- [1, 0, 0] is not decremented to [0, 3, 1]. Instead, the decrement operator needs to fail for this case. In Knuth's pseudocode, the decrement operator is step m5. Spread unallocated multiplicity - Once a part has been decremented, it cannot be the rightmost part in the partition. There is some multiplicity that has not been allocated, and new parts must be created above it in the stack to use up this multiplicity. To maintain the invariant that the parts on the stack are in decreasing order, these new parts must be less than or equal to the decremented part. For example, if the multiset is [5, 3, 1], and its most significant part has just been decremented to [5, 3, 0], the spread operation will add a new part so that the stack becomes [[5, 3, 0], [0, 0, 1]]. If the most significant part (for the same multiset) has been decremented to [2, 0, 0] the stack becomes [[2, 0, 0], [2, 0, 0], [1, 3, 1]]. In the pseudocode, the spread operation for one part is step m2. The complete spread operation is a loop of steps m2 and m3. In order to facilitate the spread operation, Knuth stores, for each component of each part, not just the multiplicity of that component in the part, but also the total multiplicity available for this component in this part or any lesser part above it on the stack. One added twist is that Knuth does not represent the part vectors as arrays. Instead, he uses a sparse representation, in which a component of a part is represented as a component number (c), plus the multiplicity of the component in that part (v) as well as the total multiplicity available for that component (u). This saves time that would be spent skipping over zeros. """ class PartComponent: """Internal class used in support of the multiset partitions enumerators and the associated visitor functions. Represents one component of one part of the current partition. A stack of these, plus an auxiliary frame array, f, represents a partition of the multiset. Knuth's pseudocode makes c, u, and v separate arrays. """ __slots__ = ('c', 'u', 'v') def __init__(self): self.c = 0 # Component number self.u = 0 # The as yet unpartitioned amount in component c # *before* it is allocated by this triple self.v = 0 # Amount of c component in the current part # (v<=u). An invariant of the representation is # that the next higher triple for this component # (if there is one) will have a value of u-v in # its u attribute. def __repr__(self): "for debug/algorithm animation purposes" return 'c:%d u:%d v:%d' % (self.c, self.u, self.v) def __eq__(self, other): """Define value oriented equality, which is useful for testers""" return (isinstance(other, self.__class__) and self.c == other.c and self.u == other.u and self.v == other.v) def __ne__(self, other): """Defined for consistency with __eq__""" return not self == other # This function tries to be a faithful implementation of algorithm # 7.1.2.5M in Volume 4A, Combinatoral Algorithms, Part 1, of The Art # of Computer Programming, by Donald Knuth. This includes using # (mostly) the same variable names, etc. This makes for rather # low-level Python. # Changes from Knuth's pseudocode include # - use PartComponent struct/object instead of 3 arrays # - make the function a generator # - map (with some difficulty) the GOTOs to Python control structures. # - Knuth uses 1-based numbering for components, this code is 0-based # - renamed variable l to lpart. # - flag variable x takes on values True/False instead of 1/0 # def multiset_partitions_taocp(multiplicities): """Enumerates partitions of a multiset. Parameters ========== multiplicities list of integer multiplicities of the components of the multiset. Yields ====== state Internal data structure which encodes a particular partition. This output is then usually processed by a visitor function which combines the information from this data structure with the components themselves to produce an actual partition. Unless they wish to create their own visitor function, users will have little need to look inside this data structure. But, for reference, it is a 3-element list with components: f is a frame array, which is used to divide pstack into parts. lpart points to the base of the topmost part. pstack is an array of PartComponent objects. The ``state`` output offers a peek into the internal data structures of the enumeration function. The client should treat this as read-only; any modification of the data structure will cause unpredictable (and almost certainly incorrect) results. Also, the components of ``state`` are modified in place at each iteration. Hence, the visitor must be called at each loop iteration. Accumulating the ``state`` instances and processing them later will not work. Examples ======== >>> from sympy.utilities.enumerative import list_visitor >>> from sympy.utilities.enumerative import multiset_partitions_taocp >>> # variables components and multiplicities represent the multiset 'abb' >>> components = 'ab' >>> multiplicities = [1, 2] >>> states = multiset_partitions_taocp(multiplicities) >>> list(list_visitor(state, components) for state in states) [[['a', 'b', 'b']], [['a', 'b'], ['b']], [['a'], ['b', 'b']], [['a'], ['b'], ['b']]] See Also ======== sympy.utilities.iterables.multiset_partitions: Takes a multiset as input and directly yields multiset partitions. It dispatches to a number of functions, including this one, for implementation. Most users will find it more convenient to use than multiset_partitions_taocp. """ # Important variables. # m is the number of components, i.e., number of distinct elements m = len(multiplicities) # n is the cardinality, total number of elements whether or not distinct n = sum(multiplicities) # The main data structure, f segments pstack into parts. See # list_visitor() for example code indicating how this internal # state corresponds to a partition. # Note: allocation of space for stack is conservative. Knuth's # exercise 7.2.1.5.68 gives some indication of how to tighten this # bound, but this is not implemented. pstack = [PartComponent() for i in range(n * m + 1)] f = [0] * (n + 1) # Step M1 in Knuth (Initialize) # Initial state - entire multiset in one part. for j in range(m): ps = pstack[j] ps.c = j ps.u = multiplicities[j] ps.v = multiplicities[j] # Other variables f[0] = 0 a = 0 lpart = 0 f[1] = m b = m # in general, current stack frame is from a to b - 1 while True: while True: # Step M2 (Subtract v from u) j = a k = b x = False while j < b: pstack[k].u = pstack[j].u - pstack[j].v if pstack[k].u == 0: x = True elif not x: pstack[k].c = pstack[j].c pstack[k].v = min(pstack[j].v, pstack[k].u) x = pstack[k].u < pstack[j].v k = k + 1 else: # x is True pstack[k].c = pstack[j].c pstack[k].v = pstack[k].u k = k + 1 j = j + 1 # Note: x is True iff v has changed # Step M3 (Push if nonzero.) if k > b: a = b b = k lpart = lpart + 1 f[lpart + 1] = b # Return to M2 else: break # Continue to M4 # M4 Visit a partition state = [f, lpart, pstack] yield state # M5 (Decrease v) while True: j = b-1 while (pstack[j].v == 0): j = j - 1 if j == a and pstack[j].v == 1: # M6 (Backtrack) if lpart == 0: return lpart = lpart - 1 b = a a = f[lpart] # Return to M5 else: pstack[j].v = pstack[j].v - 1 for k in range(j + 1, b): pstack[k].v = pstack[k].u break # GOTO M2 # --------------- Visitor functions for multiset partitions --------------- # A visitor takes the partition state generated by # multiset_partitions_taocp or other enumerator, and produces useful # output (such as the actual partition). def factoring_visitor(state, primes): """Use with multiset_partitions_taocp to enumerate the ways a number can be expressed as a product of factors. For this usage, the exponents of the prime factors of a number are arguments to the partition enumerator, while the corresponding prime factors are input here. Examples ======== To enumerate the factorings of a number we can think of the elements of the partition as being the prime factors and the multiplicities as being their exponents. >>> from sympy.utilities.enumerative import factoring_visitor >>> from sympy.utilities.enumerative import multiset_partitions_taocp >>> from sympy import factorint >>> primes, multiplicities = zip(*factorint(24).items()) >>> primes (2, 3) >>> multiplicities (3, 1) >>> states = multiset_partitions_taocp(multiplicities) >>> list(factoring_visitor(state, primes) for state in states) [[24], [8, 3], [12, 2], [4, 6], [4, 2, 3], [6, 2, 2], [2, 2, 2, 3]] """ f, lpart, pstack = state factoring = [] for i in range(lpart + 1): factor = 1 for ps in pstack[f[i]: f[i + 1]]: if ps.v > 0: factor *= primes[ps.c] ** ps.v factoring.append(factor) return factoring def list_visitor(state, components): """Return a list of lists to represent the partition. Examples ======== >>> from sympy.utilities.enumerative import list_visitor >>> from sympy.utilities.enumerative import multiset_partitions_taocp >>> states = multiset_partitions_taocp([1, 2, 1]) >>> s = next(states) >>> list_visitor(s, 'abc') # for multiset 'a b b c' [['a', 'b', 'b', 'c']] >>> s = next(states) >>> list_visitor(s, [1, 2, 3]) # for multiset '1 2 2 3 [[1, 2, 2], [3]] """ f, lpart, pstack = state partition = [] for i in range(lpart+1): part = [] for ps in pstack[f[i]:f[i+1]]: if ps.v > 0: part.extend([components[ps.c]] * ps.v) partition.append(part) return partition class MultisetPartitionTraverser(): """ Has methods to ``enumerate`` and ``count`` the partitions of a multiset. This implements a refactored and extended version of Knuth's algorithm 7.1.2.5M [AOCP]_." The enumeration methods of this class are generators and return data structures which can be interpreted by the same visitor functions used for the output of ``multiset_partitions_taocp``. Examples ======== >>> from sympy.utilities.enumerative import MultisetPartitionTraverser >>> m = MultisetPartitionTraverser() >>> m.count_partitions([4,4,4,2]) 127750 >>> m.count_partitions([3,3,3]) 686 See Also ======== multiset_partitions_taocp sympy.utilities.iterables.multiset_partitions References ========== .. [AOCP] Algorithm 7.1.2.5M in Volume 4A, Combinatoral Algorithms, Part 1, of The Art of Computer Programming, by Donald Knuth. .. [Factorisatio] On a Problem of Oppenheim concerning "Factorisatio Numerorum" E. R. Canfield, Paul Erdos, Carl Pomerance, JOURNAL OF NUMBER THEORY, Vol. 17, No. 1. August 1983. See section 7 for a description of an algorithm similar to Knuth's. .. [Yorgey] Generating Multiset Partitions, Brent Yorgey, The Monad.Reader, Issue 8, September 2007. """ def __init__(self): self.debug = False # TRACING variables. These are useful for gathering # statistics on the algorithm itself, but have no particular # benefit to a user of the code. self.k1 = 0 self.k2 = 0 self.p1 = 0 self.pstack = None self.f = None self.lpart = 0 self.discarded = 0 # dp_stack is list of lists of (part_key, start_count) pairs self.dp_stack = [] # dp_map is map part_key-> count, where count represents the # number of multiset which are descendants of a part with this # key, **or any of its decrements** # Thus, when we find a part in the map, we add its count # value to the running total, cut off the enumeration, and # backtrack if not hasattr(self, 'dp_map'): self.dp_map = {} def db_trace(self, msg): """Useful for understanding/debugging the algorithms. Not generally activated in end-user code.""" if self.debug: # XXX: animation_visitor is undefined... Clearly this does not # work and was not tested. Previous code in comments below. raise RuntimeError #letters = 'abcdefghijklmnopqrstuvwxyz' #state = [self.f, self.lpart, self.pstack] #print("DBG:", msg, # ["".join(part) for part in list_visitor(state, letters)], # animation_visitor(state)) # # Helper methods for enumeration # def _initialize_enumeration(self, multiplicities): """Allocates and initializes the partition stack. This is called from the enumeration/counting routines, so there is no need to call it separately.""" num_components = len(multiplicities) # cardinality is the total number of elements, whether or not distinct cardinality = sum(multiplicities) # pstack is the partition stack, which is segmented by # f into parts. self.pstack = [PartComponent() for i in range(num_components * cardinality + 1)] self.f = [0] * (cardinality + 1) # Initial state - entire multiset in one part. for j in range(num_components): ps = self.pstack[j] ps.c = j ps.u = multiplicities[j] ps.v = multiplicities[j] self.f[0] = 0 self.f[1] = num_components self.lpart = 0 # The decrement_part() method corresponds to step M5 in Knuth's # algorithm. This is the base version for enum_all(). Modified # versions of this method are needed if we want to restrict # sizes of the partitions produced. def decrement_part(self, part): """Decrements part (a subrange of pstack), if possible, returning True iff the part was successfully decremented. If you think of the v values in the part as a multi-digit integer (least significant digit on the right) this is basically decrementing that integer, but with the extra constraint that the leftmost digit cannot be decremented to 0. Parameters ========== part The part, represented as a list of PartComponent objects, which is to be decremented. """ plen = len(part) for j in range(plen - 1, -1, -1): if j == 0 and part[j].v > 1 or j > 0 and part[j].v > 0: # found val to decrement part[j].v -= 1 # Reset trailing parts back to maximum for k in range(j + 1, plen): part[k].v = part[k].u return True return False # Version to allow number of parts to be bounded from above. # Corresponds to (a modified) step M5. def decrement_part_small(self, part, ub): """Decrements part (a subrange of pstack), if possible, returning True iff the part was successfully decremented. Parameters ========== part part to be decremented (topmost part on the stack) ub the maximum number of parts allowed in a partition returned by the calling traversal. Notes ===== The goal of this modification of the ordinary decrement method is to fail (meaning that the subtree rooted at this part is to be skipped) when it can be proved that this part can only have child partitions which are larger than allowed by ``ub``. If a decision is made to fail, it must be accurate, otherwise the enumeration will miss some partitions. But, it is OK not to capture all the possible failures -- if a part is passed that should not be, the resulting too-large partitions are filtered by the enumeration one level up. However, as is usual in constrained enumerations, failing early is advantageous. The tests used by this method catch the most common cases, although this implementation is by no means the last word on this problem. The tests include: 1) ``lpart`` must be less than ``ub`` by at least 2. This is because once a part has been decremented, the partition will gain at least one child in the spread step. 2) If the leading component of the part is about to be decremented, check for how many parts will be added in order to use up the unallocated multiplicity in that leading component, and fail if this number is greater than allowed by ``ub``. (See code for the exact expression.) This test is given in the answer to Knuth's problem 7.2.1.5.69. 3) If there is *exactly* enough room to expand the leading component by the above test, check the next component (if it exists) once decrementing has finished. If this has ``v == 0``, this next component will push the expansion over the limit by 1, so fail. """ if self.lpart >= ub - 1: self.p1 += 1 # increment to keep track of usefulness of tests return False plen = len(part) for j in range(plen - 1, -1, -1): # Knuth's mod, (answer to problem 7.2.1.5.69) if j == 0 and (part[0].v - 1)*(ub - self.lpart) < part[0].u: self.k1 += 1 return False if j == 0 and part[j].v > 1 or j > 0 and part[j].v > 0: # found val to decrement part[j].v -= 1 # Reset trailing parts back to maximum for k in range(j + 1, plen): part[k].v = part[k].u # Have now decremented part, but are we doomed to # failure when it is expanded? Check one oddball case # that turns out to be surprisingly common - exactly # enough room to expand the leading component, but no # room for the second component, which has v=0. if (plen > 1 and part[1].v == 0 and (part[0].u - part[0].v) == ((ub - self.lpart - 1) * part[0].v)): self.k2 += 1 self.db_trace("Decrement fails test 3") return False return True return False def decrement_part_large(self, part, amt, lb): """Decrements part, while respecting size constraint. A part can have no children which are of sufficient size (as indicated by ``lb``) unless that part has sufficient unallocated multiplicity. When enforcing the size constraint, this method will decrement the part (if necessary) by an amount needed to ensure sufficient unallocated multiplicity. Returns True iff the part was successfully decremented. Parameters ========== part part to be decremented (topmost part on the stack) amt Can only take values 0 or 1. A value of 1 means that the part must be decremented, and then the size constraint is enforced. A value of 0 means just to enforce the ``lb`` size constraint. lb The partitions produced by the calling enumeration must have more parts than this value. """ if amt == 1: # In this case we always need to increment, *before* # enforcing the "sufficient unallocated multiplicity" # constraint. Easiest for this is just to call the # regular decrement method. if not self.decrement_part(part): return False # Next, perform any needed additional decrementing to respect # "sufficient unallocated multiplicity" (or fail if this is # not possible). min_unalloc = lb - self.lpart if min_unalloc <= 0: return True total_mult = sum(pc.u for pc in part) total_alloc = sum(pc.v for pc in part) if total_mult <= min_unalloc: return False deficit = min_unalloc - (total_mult - total_alloc) if deficit <= 0: return True for i in range(len(part) - 1, -1, -1): if i == 0: if part[0].v > deficit: part[0].v -= deficit return True else: return False # This shouldn't happen, due to above check else: if part[i].v >= deficit: part[i].v -= deficit return True else: deficit -= part[i].v part[i].v = 0 def decrement_part_range(self, part, lb, ub): """Decrements part (a subrange of pstack), if possible, returning True iff the part was successfully decremented. Parameters ========== part part to be decremented (topmost part on the stack) ub the maximum number of parts allowed in a partition returned by the calling traversal. lb The partitions produced by the calling enumeration must have more parts than this value. Notes ===== Combines the constraints of _small and _large decrement methods. If returns success, part has been decremented at least once, but perhaps by quite a bit more if needed to meet the lb constraint. """ # Constraint in the range case is just enforcing both the # constraints from _small and _large cases. Note the 0 as the # second argument to the _large call -- this is the signal to # decrement only as needed to for constraint enforcement. The # short circuiting and left-to-right order of the 'and' # operator is important for this to work correctly. return self.decrement_part_small(part, ub) and \ self.decrement_part_large(part, 0, lb) def spread_part_multiplicity(self): """Returns True if a new part has been created, and adjusts pstack, f and lpart as needed. Notes ===== Spreads unallocated multiplicity from the current top part into a new part created above the current on the stack. This new part is constrained to be less than or equal to the old in terms of the part ordering. This call does nothing (and returns False) if the current top part has no unallocated multiplicity. """ j = self.f[self.lpart] # base of current top part k = self.f[self.lpart + 1] # ub of current; potential base of next base = k # save for later comparison changed = False # Set to true when the new part (so far) is # strictly less than (as opposed to less than # or equal) to the old. for j in range(self.f[self.lpart], self.f[self.lpart + 1]): self.pstack[k].u = self.pstack[j].u - self.pstack[j].v if self.pstack[k].u == 0: changed = True else: self.pstack[k].c = self.pstack[j].c if changed: # Put all available multiplicity in this part self.pstack[k].v = self.pstack[k].u else: # Still maintaining ordering constraint if self.pstack[k].u < self.pstack[j].v: self.pstack[k].v = self.pstack[k].u changed = True else: self.pstack[k].v = self.pstack[j].v k = k + 1 if k > base: # Adjust for the new part on stack self.lpart = self.lpart + 1 self.f[self.lpart + 1] = k return True return False def top_part(self): """Return current top part on the stack, as a slice of pstack. """ return self.pstack[self.f[self.lpart]:self.f[self.lpart + 1]] # Same interface and functionality as multiset_partitions_taocp(), # but some might find this refactored version easier to follow. def enum_all(self, multiplicities): """Enumerate the partitions of a multiset. Examples ======== >>> from sympy.utilities.enumerative import list_visitor >>> from sympy.utilities.enumerative import MultisetPartitionTraverser >>> m = MultisetPartitionTraverser() >>> states = m.enum_all([2,2]) >>> list(list_visitor(state, 'ab') for state in states) [[['a', 'a', 'b', 'b']], [['a', 'a', 'b'], ['b']], [['a', 'a'], ['b', 'b']], [['a', 'a'], ['b'], ['b']], [['a', 'b', 'b'], ['a']], [['a', 'b'], ['a', 'b']], [['a', 'b'], ['a'], ['b']], [['a'], ['a'], ['b', 'b']], [['a'], ['a'], ['b'], ['b']]] See Also ======== multiset_partitions_taocp: which provides the same result as this method, but is about twice as fast. Hence, enum_all is primarily useful for testing. Also see the function for a discussion of states and visitors. """ self._initialize_enumeration(multiplicities) while True: while self.spread_part_multiplicity(): pass # M4 Visit a partition state = [self.f, self.lpart, self.pstack] yield state # M5 (Decrease v) while not self.decrement_part(self.top_part()): # M6 (Backtrack) if self.lpart == 0: return self.lpart -= 1 def enum_small(self, multiplicities, ub): """Enumerate multiset partitions with no more than ``ub`` parts. Equivalent to enum_range(multiplicities, 0, ub) Parameters ========== multiplicities list of multiplicities of the components of the multiset. ub Maximum number of parts Examples ======== >>> from sympy.utilities.enumerative import list_visitor >>> from sympy.utilities.enumerative import MultisetPartitionTraverser >>> m = MultisetPartitionTraverser() >>> states = m.enum_small([2,2], 2) >>> list(list_visitor(state, 'ab') for state in states) [[['a', 'a', 'b', 'b']], [['a', 'a', 'b'], ['b']], [['a', 'a'], ['b', 'b']], [['a', 'b', 'b'], ['a']], [['a', 'b'], ['a', 'b']]] The implementation is based, in part, on the answer given to exercise 69, in Knuth [AOCP]_. See Also ======== enum_all, enum_large, enum_range """ # Keep track of iterations which do not yield a partition. # Clearly, we would like to keep this number small. self.discarded = 0 if ub <= 0: return self._initialize_enumeration(multiplicities) while True: while self.spread_part_multiplicity(): self.db_trace('spread 1') if self.lpart >= ub: self.discarded += 1 self.db_trace(' Discarding') self.lpart = ub - 2 break else: # M4 Visit a partition state = [self.f, self.lpart, self.pstack] yield state # M5 (Decrease v) while not self.decrement_part_small(self.top_part(), ub): self.db_trace("Failed decrement, going to backtrack") # M6 (Backtrack) if self.lpart == 0: return self.lpart -= 1 self.db_trace("Backtracked to") self.db_trace("decrement ok, about to expand") def enum_large(self, multiplicities, lb): """Enumerate the partitions of a multiset with lb < num(parts) Equivalent to enum_range(multiplicities, lb, sum(multiplicities)) Parameters ========== multiplicities list of multiplicities of the components of the multiset. lb Number of parts in the partition must be greater than this lower bound. Examples ======== >>> from sympy.utilities.enumerative import list_visitor >>> from sympy.utilities.enumerative import MultisetPartitionTraverser >>> m = MultisetPartitionTraverser() >>> states = m.enum_large([2,2], 2) >>> list(list_visitor(state, 'ab') for state in states) [[['a', 'a'], ['b'], ['b']], [['a', 'b'], ['a'], ['b']], [['a'], ['a'], ['b', 'b']], [['a'], ['a'], ['b'], ['b']]] See Also ======== enum_all, enum_small, enum_range """ self.discarded = 0 if lb >= sum(multiplicities): return self._initialize_enumeration(multiplicities) self.decrement_part_large(self.top_part(), 0, lb) while True: good_partition = True while self.spread_part_multiplicity(): if not self.decrement_part_large(self.top_part(), 0, lb): # Failure here should be rare/impossible self.discarded += 1 good_partition = False break # M4 Visit a partition if good_partition: state = [self.f, self.lpart, self.pstack] yield state # M5 (Decrease v) while not self.decrement_part_large(self.top_part(), 1, lb): # M6 (Backtrack) if self.lpart == 0: return self.lpart -= 1 def enum_range(self, multiplicities, lb, ub): """Enumerate the partitions of a multiset with ``lb < num(parts) <= ub``. In particular, if partitions with exactly ``k`` parts are desired, call with ``(multiplicities, k - 1, k)``. This method generalizes enum_all, enum_small, and enum_large. Examples ======== >>> from sympy.utilities.enumerative import list_visitor >>> from sympy.utilities.enumerative import MultisetPartitionTraverser >>> m = MultisetPartitionTraverser() >>> states = m.enum_range([2,2], 1, 2) >>> list(list_visitor(state, 'ab') for state in states) [[['a', 'a', 'b'], ['b']], [['a', 'a'], ['b', 'b']], [['a', 'b', 'b'], ['a']], [['a', 'b'], ['a', 'b']]] """ # combine the constraints of the _large and _small # enumerations. self.discarded = 0 if ub <= 0 or lb >= sum(multiplicities): return self._initialize_enumeration(multiplicities) self.decrement_part_large(self.top_part(), 0, lb) while True: good_partition = True while self.spread_part_multiplicity(): self.db_trace("spread 1") if not self.decrement_part_large(self.top_part(), 0, lb): # Failure here - possible in range case? self.db_trace(" Discarding (large cons)") self.discarded += 1 good_partition = False break elif self.lpart >= ub: self.discarded += 1 good_partition = False self.db_trace(" Discarding small cons") self.lpart = ub - 2 break # M4 Visit a partition if good_partition: state = [self.f, self.lpart, self.pstack] yield state # M5 (Decrease v) while not self.decrement_part_range(self.top_part(), lb, ub): self.db_trace("Failed decrement, going to backtrack") # M6 (Backtrack) if self.lpart == 0: return self.lpart -= 1 self.db_trace("Backtracked to") self.db_trace("decrement ok, about to expand") def count_partitions_slow(self, multiplicities): """Returns the number of partitions of a multiset whose elements have the multiplicities given in ``multiplicities``. Primarily for comparison purposes. It follows the same path as enumerate, and counts, rather than generates, the partitions. See Also ======== count_partitions Has the same calling interface, but is much faster. """ # number of partitions so far in the enumeration self.pcount = 0 self._initialize_enumeration(multiplicities) while True: while self.spread_part_multiplicity(): pass # M4 Visit (count) a partition self.pcount += 1 # M5 (Decrease v) while not self.decrement_part(self.top_part()): # M6 (Backtrack) if self.lpart == 0: return self.pcount self.lpart -= 1 def count_partitions(self, multiplicities): """Returns the number of partitions of a multiset whose components have the multiplicities given in ``multiplicities``. For larger counts, this method is much faster than calling one of the enumerators and counting the result. Uses dynamic programming to cut down on the number of nodes actually explored. The dictionary used in order to accelerate the counting process is stored in the ``MultisetPartitionTraverser`` object and persists across calls. If the user does not expect to call ``count_partitions`` for any additional multisets, the object should be cleared to save memory. On the other hand, the cache built up from one count run can significantly speed up subsequent calls to ``count_partitions``, so it may be advantageous not to clear the object. Examples ======== >>> from sympy.utilities.enumerative import MultisetPartitionTraverser >>> m = MultisetPartitionTraverser() >>> m.count_partitions([9,8,2]) 288716 >>> m.count_partitions([2,2]) 9 >>> del m Notes ===== If one looks at the workings of Knuth's algorithm M [AOCP]_, it can be viewed as a traversal of a binary tree of parts. A part has (up to) two children, the left child resulting from the spread operation, and the right child from the decrement operation. The ordinary enumeration of multiset partitions is an in-order traversal of this tree, and with the partitions corresponding to paths from the root to the leaves. The mapping from paths to partitions is a little complicated, since the partition would contain only those parts which are leaves or the parents of a spread link, not those which are parents of a decrement link. For counting purposes, it is sufficient to count leaves, and this can be done with a recursive in-order traversal. The number of leaves of a subtree rooted at a particular part is a function only of that part itself, so memoizing has the potential to speed up the counting dramatically. This method follows a computational approach which is similar to the hypothetical memoized recursive function, but with two differences: 1) This method is iterative, borrowing its structure from the other enumerations and maintaining an explicit stack of parts which are in the process of being counted. (There may be multisets which can be counted reasonably quickly by this implementation, but which would overflow the default Python recursion limit with a recursive implementation.) 2) Instead of using the part data structure directly, a more compact key is constructed. This saves space, but more importantly coalesces some parts which would remain separate with physical keys. Unlike the enumeration functions, there is currently no _range version of count_partitions. If someone wants to stretch their brain, it should be possible to construct one by memoizing with a histogram of counts rather than a single count, and combining the histograms. """ # number of partitions so far in the enumeration self.pcount = 0 # dp_stack is list of lists of (part_key, start_count) pairs self.dp_stack = [] self._initialize_enumeration(multiplicities) pkey = part_key(self.top_part()) self.dp_stack.append([(pkey, 0), ]) while True: while self.spread_part_multiplicity(): pkey = part_key(self.top_part()) if pkey in self.dp_map: # Already have a cached value for the count of the # subtree rooted at this part. Add it to the # running counter, and break out of the spread # loop. The -1 below is to compensate for the # leaf that this code path would otherwise find, # and which gets incremented for below. self.pcount += (self.dp_map[pkey] - 1) self.lpart -= 1 break else: self.dp_stack.append([(pkey, self.pcount), ]) # M4 count a leaf partition self.pcount += 1 # M5 (Decrease v) while not self.decrement_part(self.top_part()): # M6 (Backtrack) for key, oldcount in self.dp_stack.pop(): self.dp_map[key] = self.pcount - oldcount if self.lpart == 0: return self.pcount self.lpart -= 1 # At this point have successfully decremented the part on # the stack and it does not appear in the cache. It needs # to be added to the list at the top of dp_stack pkey = part_key(self.top_part()) self.dp_stack[-1].append((pkey, self.pcount),) def part_key(part): """Helper for MultisetPartitionTraverser.count_partitions that creates a key for ``part``, that only includes information which can affect the count for that part. (Any irrelevant information just reduces the effectiveness of dynamic programming.) Notes ===== This member function is a candidate for future exploration. There are likely symmetries that can be exploited to coalesce some ``part_key`` values, and thereby save space and improve performance. """ # The component number is irrelevant for counting partitions, so # leave it out of the memo key. rval = [] for ps in part: rval.append(ps.u) rval.append(ps.v) return tuple(rval)
4a60186ba54174787c4b3f9fa47290d5901c6f98b0ff74b3c088e6ed5b597b85
from collections import defaultdict, OrderedDict from itertools import ( chain, combinations, combinations_with_replacement, cycle, islice, permutations, product ) # For backwards compatibility from itertools import product as cartes # noqa: F401 from operator import gt # this is the logical location of these functions from sympy.utilities.enumerative import ( multiset_partitions_taocp, list_visitor, MultisetPartitionTraverser) from sympy.utilities.misc import as_int from sympy.utilities.decorator import deprecated def is_palindromic(s, i=0, j=None): """ Return True if the sequence is the same from left to right as it is from right to left in the whole sequence (default) or in the Python slice ``s[i: j]``; else False. Examples ======== >>> from sympy.utilities.iterables import is_palindromic >>> is_palindromic([1, 0, 1]) True >>> is_palindromic('abcbb') False >>> is_palindromic('abcbb', 1) False Normal Python slicing is performed in place so there is no need to create a slice of the sequence for testing: >>> is_palindromic('abcbb', 1, -1) True >>> is_palindromic('abcbb', -4, -1) True See Also ======== sympy.ntheory.digits.is_palindromic: tests integers """ i, j, _ = slice(i, j).indices(len(s)) m = (j - i)//2 # if length is odd, middle element will be ignored return all(s[i + k] == s[j - 1 - k] for k in range(m)) def flatten(iterable, levels=None, cls=None): # noqa: F811 """ Recursively denest iterable containers. >>> from sympy import flatten >>> flatten([1, 2, 3]) [1, 2, 3] >>> flatten([1, 2, [3]]) [1, 2, 3] >>> flatten([1, [2, 3], [4, 5]]) [1, 2, 3, 4, 5] >>> flatten([1.0, 2, (1, None)]) [1.0, 2, 1, None] If you want to denest only a specified number of levels of nested containers, then set ``levels`` flag to the desired number of levels:: >>> ls = [[(-2, -1), (1, 2)], [(0, 0)]] >>> flatten(ls, levels=1) [(-2, -1), (1, 2), (0, 0)] If cls argument is specified, it will only flatten instances of that class, for example: >>> from sympy import Basic, S >>> class MyOp(Basic): ... pass ... >>> flatten([MyOp(S(1), MyOp(S(2), S(3)))], cls=MyOp) [1, 2, 3] adapted from https://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks """ from sympy.tensor.array import NDimArray if levels is not None: if not levels: return iterable elif levels > 0: levels -= 1 else: raise ValueError( "expected non-negative number of levels, got %s" % levels) if cls is None: reducible = lambda x: is_sequence(x, set) else: reducible = lambda x: isinstance(x, cls) result = [] for el in iterable: if reducible(el): if hasattr(el, 'args') and not isinstance(el, NDimArray): el = el.args result.extend(flatten(el, levels=levels, cls=cls)) else: result.append(el) return result def unflatten(iter, n=2): """Group ``iter`` into tuples of length ``n``. Raise an error if the length of ``iter`` is not a multiple of ``n``. """ if n < 1 or len(iter) % n: raise ValueError('iter length is not a multiple of %i' % n) return list(zip(*(iter[i::n] for i in range(n)))) def reshape(seq, how): """Reshape the sequence according to the template in ``how``. Examples ======== >>> from sympy.utilities import reshape >>> seq = list(range(1, 9)) >>> reshape(seq, [4]) # lists of 4 [[1, 2, 3, 4], [5, 6, 7, 8]] >>> reshape(seq, (4,)) # tuples of 4 [(1, 2, 3, 4), (5, 6, 7, 8)] >>> reshape(seq, (2, 2)) # tuples of 4 [(1, 2, 3, 4), (5, 6, 7, 8)] >>> reshape(seq, (2, [2])) # (i, i, [i, i]) [(1, 2, [3, 4]), (5, 6, [7, 8])] >>> reshape(seq, ((2,), [2])) # etc.... [((1, 2), [3, 4]), ((5, 6), [7, 8])] >>> reshape(seq, (1, [2], 1)) [(1, [2, 3], 4), (5, [6, 7], 8)] >>> reshape(tuple(seq), ([[1], 1, (2,)],)) (([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],)) >>> reshape(tuple(seq), ([1], 1, (2,))) (([1], 2, (3, 4)), ([5], 6, (7, 8))) >>> reshape(list(range(12)), [2, [3], {2}, (1, (3,), 1)]) [[0, 1, [2, 3, 4], {5, 6}, (7, (8, 9, 10), 11)]] """ m = sum(flatten(how)) n, rem = divmod(len(seq), m) if m < 0 or rem: raise ValueError('template must sum to positive number ' 'that divides the length of the sequence') i = 0 container = type(how) rv = [None]*n for k in range(len(rv)): _rv = [] for hi in how: if isinstance(hi, int): _rv.extend(seq[i: i + hi]) i += hi else: n = sum(flatten(hi)) hi_type = type(hi) _rv.append(hi_type(reshape(seq[i: i + n], hi)[0])) i += n rv[k] = container(_rv) return type(seq)(rv) def group(seq, multiple=True): """ Splits a sequence into a list of lists of equal, adjacent elements. Examples ======== >>> from sympy import group >>> group([1, 1, 1, 2, 2, 3]) [[1, 1, 1], [2, 2], [3]] >>> group([1, 1, 1, 2, 2, 3], multiple=False) [(1, 3), (2, 2), (3, 1)] >>> group([1, 1, 3, 2, 2, 1], multiple=False) [(1, 2), (3, 1), (2, 2), (1, 1)] See Also ======== multiset """ if not seq: return [] current, groups = [seq[0]], [] for elem in seq[1:]: if elem == current[-1]: current.append(elem) else: groups.append(current) current = [elem] groups.append(current) if multiple: return groups for i, current in enumerate(groups): groups[i] = (current[0], len(current)) return groups def _iproduct2(iterable1, iterable2): '''Cartesian product of two possibly infinite iterables''' it1 = iter(iterable1) it2 = iter(iterable2) elems1 = [] elems2 = [] sentinel = object() def append(it, elems): e = next(it, sentinel) if e is not sentinel: elems.append(e) n = 0 append(it1, elems1) append(it2, elems2) while n <= len(elems1) + len(elems2): for m in range(n-len(elems1)+1, len(elems2)): yield (elems1[n-m], elems2[m]) n += 1 append(it1, elems1) append(it2, elems2) def iproduct(*iterables): ''' Cartesian product of iterables. Generator of the Cartesian product of iterables. This is analogous to itertools.product except that it works with infinite iterables and will yield any item from the infinite product eventually. Examples ======== >>> from sympy.utilities.iterables import iproduct >>> sorted(iproduct([1,2], [3,4])) [(1, 3), (1, 4), (2, 3), (2, 4)] With an infinite iterator: >>> from sympy import S >>> (3,) in iproduct(S.Integers) True >>> (3, 4) in iproduct(S.Integers, S.Integers) True .. seealso:: `itertools.product <https://docs.python.org/3/library/itertools.html#itertools.product>`_ ''' if len(iterables) == 0: yield () return elif len(iterables) == 1: for e in iterables[0]: yield (e,) elif len(iterables) == 2: yield from _iproduct2(*iterables) else: first, others = iterables[0], iterables[1:] for ef, eo in _iproduct2(first, iproduct(*others)): yield (ef,) + eo def multiset(seq): """Return the hashable sequence in multiset form with values being the multiplicity of the item in the sequence. Examples ======== >>> from sympy.utilities.iterables import multiset >>> multiset('mississippi') {'i': 4, 'm': 1, 'p': 2, 's': 4} See Also ======== group """ rv = defaultdict(int) for s in seq: rv[s] += 1 return dict(rv) def ibin(n, bits=None, str=False): """Return a list of length ``bits`` corresponding to the binary value of ``n`` with small bits to the right (last). If bits is omitted, the length will be the number required to represent ``n``. If the bits are desired in reversed order, use the ``[::-1]`` slice of the returned list. If a sequence of all bits-length lists starting from ``[0, 0,..., 0]`` through ``[1, 1, ..., 1]`` are desired, pass a non-integer for bits, e.g. ``'all'``. If the bit *string* is desired pass ``str=True``. Examples ======== >>> from sympy.utilities.iterables import ibin >>> ibin(2) [1, 0] >>> ibin(2, 4) [0, 0, 1, 0] If all lists corresponding to 0 to 2**n - 1, pass a non-integer for bits: >>> bits = 2 >>> for i in ibin(2, 'all'): ... print(i) (0, 0) (0, 1) (1, 0) (1, 1) If a bit string is desired of a given length, use str=True: >>> n = 123 >>> bits = 10 >>> ibin(n, bits, str=True) '0001111011' >>> ibin(n, bits, str=True)[::-1] # small bits left '1101111000' >>> list(ibin(3, 'all', str=True)) ['000', '001', '010', '011', '100', '101', '110', '111'] """ if n < 0: raise ValueError("negative numbers are not allowed") n = as_int(n) if bits is None: bits = 0 else: try: bits = as_int(bits) except ValueError: bits = -1 else: if n.bit_length() > bits: raise ValueError( "`bits` must be >= {}".format(n.bit_length())) if not str: if bits >= 0: return [1 if i == "1" else 0 for i in bin(n)[2:].rjust(bits, "0")] else: return variations(range(2), n, repetition=True) else: if bits >= 0: return bin(n)[2:].rjust(bits, "0") else: return (bin(i)[2:].rjust(n, "0") for i in range(2**n)) def variations(seq, n, repetition=False): r"""Returns an iterator over the n-sized variations of ``seq`` (size N). ``repetition`` controls whether items in ``seq`` can appear more than once; Examples ======== ``variations(seq, n)`` will return `\frac{N!}{(N - n)!}` permutations without repetition of ``seq``'s elements: >>> from sympy import variations >>> list(variations([1, 2], 2)) [(1, 2), (2, 1)] ``variations(seq, n, True)`` will return the `N^n` permutations obtained by allowing repetition of elements: >>> list(variations([1, 2], 2, repetition=True)) [(1, 1), (1, 2), (2, 1), (2, 2)] If you ask for more items than are in the set you get the empty set unless you allow repetitions: >>> list(variations([0, 1], 3, repetition=False)) [] >>> list(variations([0, 1], 3, repetition=True))[:4] [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1)] .. seealso:: `itertools.permutations <https://docs.python.org/3/library/itertools.html#itertools.permutations>`_, `itertools.product <https://docs.python.org/3/library/itertools.html#itertools.product>`_ """ if not repetition: seq = tuple(seq) if len(seq) < n: return iter(()) # 0 length iterator return permutations(seq, n) else: if n == 0: return iter(((),)) # yields 1 empty tuple else: return product(seq, repeat=n) def subsets(seq, k=None, repetition=False): r"""Generates all `k`-subsets (combinations) from an `n`-element set, ``seq``. A `k`-subset of an `n`-element set is any subset of length exactly `k`. The number of `k`-subsets of an `n`-element set is given by ``binomial(n, k)``, whereas there are `2^n` subsets all together. If `k` is ``None`` then all `2^n` subsets will be returned from shortest to longest. Examples ======== >>> from sympy import subsets ``subsets(seq, k)`` will return the `\frac{n!}{k!(n - k)!}` `k`-subsets (combinations) without repetition, i.e. once an item has been removed, it can no longer be "taken": >>> list(subsets([1, 2], 2)) [(1, 2)] >>> list(subsets([1, 2])) [(), (1,), (2,), (1, 2)] >>> list(subsets([1, 2, 3], 2)) [(1, 2), (1, 3), (2, 3)] ``subsets(seq, k, repetition=True)`` will return the `\frac{(n - 1 + k)!}{k!(n - 1)!}` combinations *with* repetition: >>> list(subsets([1, 2], 2, repetition=True)) [(1, 1), (1, 2), (2, 2)] If you ask for more items than are in the set you get the empty set unless you allow repetitions: >>> list(subsets([0, 1], 3, repetition=False)) [] >>> list(subsets([0, 1], 3, repetition=True)) [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)] """ if k is None: if not repetition: return chain.from_iterable((combinations(seq, k) for k in range(len(seq) + 1))) else: return chain.from_iterable((combinations_with_replacement(seq, k) for k in range(len(seq) + 1))) else: if not repetition: return combinations(seq, k) else: return combinations_with_replacement(seq, k) def filter_symbols(iterator, exclude): """ Only yield elements from `iterator` that do not occur in `exclude`. Parameters ========== iterator : iterable iterator to take elements from exclude : iterable elements to exclude Returns ======= iterator : iterator filtered iterator """ exclude = set(exclude) for s in iterator: if s not in exclude: yield s def numbered_symbols(prefix='x', cls=None, start=0, exclude=(), *args, **assumptions): """ Generate an infinite stream of Symbols consisting of a prefix and increasing subscripts provided that they do not occur in ``exclude``. Parameters ========== prefix : str, optional The prefix to use. By default, this function will generate symbols of the form "x0", "x1", etc. cls : class, optional The class to use. By default, it uses ``Symbol``, but you can also use ``Wild`` or ``Dummy``. start : int, optional The start number. By default, it is 0. Returns ======= sym : Symbol The subscripted symbols. """ exclude = set(exclude or []) if cls is None: # We can't just make the default cls=Symbol because it isn't # imported yet. from sympy.core import Symbol cls = Symbol while True: name = '%s%s' % (prefix, start) s = cls(name, *args, **assumptions) if s not in exclude: yield s start += 1 def capture(func): """Return the printed output of func(). ``func`` should be a function without arguments that produces output with print statements. >>> from sympy.utilities.iterables import capture >>> from sympy import pprint >>> from sympy.abc import x >>> def foo(): ... print('hello world!') ... >>> 'hello' in capture(foo) # foo, not foo() True >>> capture(lambda: pprint(2/x)) '2\\n-\\nx\\n' """ from io import StringIO import sys stdout = sys.stdout sys.stdout = file = StringIO() try: func() finally: sys.stdout = stdout return file.getvalue() def sift(seq, keyfunc, binary=False): """ Sift the sequence, ``seq`` according to ``keyfunc``. Returns ======= When ``binary`` is ``False`` (default), the output is a dictionary where elements of ``seq`` are stored in a list keyed to the value of keyfunc for that element. If ``binary`` is True then a tuple with lists ``T`` and ``F`` are returned where ``T`` is a list containing elements of seq for which ``keyfunc`` was ``True`` and ``F`` containing those elements for which ``keyfunc`` was ``False``; a ValueError is raised if the ``keyfunc`` is not binary. Examples ======== >>> from sympy.utilities import sift >>> from sympy.abc import x, y >>> from sympy import sqrt, exp, pi, Tuple >>> sift(range(5), lambda x: x % 2) {0: [0, 2, 4], 1: [1, 3]} sift() returns a defaultdict() object, so any key that has no matches will give []. >>> sift([x], lambda x: x.is_commutative) {True: [x]} >>> _[False] [] Sometimes you will not know how many keys you will get: >>> sift([sqrt(x), exp(x), (y**x)**2], ... lambda x: x.as_base_exp()[0]) {E: [exp(x)], x: [sqrt(x)], y: [y**(2*x)]} Sometimes you expect the results to be binary; the results can be unpacked by setting ``binary`` to True: >>> sift(range(4), lambda x: x % 2, binary=True) ([1, 3], [0, 2]) >>> sift(Tuple(1, pi), lambda x: x.is_rational, binary=True) ([1], [pi]) A ValueError is raised if the predicate was not actually binary (which is a good test for the logic where sifting is used and binary results were expected): >>> unknown = exp(1) - pi # the rationality of this is unknown >>> args = Tuple(1, pi, unknown) >>> sift(args, lambda x: x.is_rational, binary=True) Traceback (most recent call last): ... ValueError: keyfunc gave non-binary output The non-binary sifting shows that there were 3 keys generated: >>> set(sift(args, lambda x: x.is_rational).keys()) {None, False, True} If you need to sort the sifted items it might be better to use ``ordered`` which can economically apply multiple sort keys to a sequence while sorting. See Also ======== ordered """ if not binary: m = defaultdict(list) for i in seq: m[keyfunc(i)].append(i) return m sift = F, T = [], [] for i in seq: try: sift[keyfunc(i)].append(i) except (IndexError, TypeError): raise ValueError('keyfunc gave non-binary output') return T, F def take(iter, n): """Return ``n`` items from ``iter`` iterator. """ return [ value for _, value in zip(range(n), iter) ] def dict_merge(*dicts): """Merge dictionaries into a single dictionary. """ merged = {} for dict in dicts: merged.update(dict) return merged def common_prefix(*seqs): """Return the subsequence that is a common start of sequences in ``seqs``. >>> from sympy.utilities.iterables import common_prefix >>> common_prefix(list(range(3))) [0, 1, 2] >>> common_prefix(list(range(3)), list(range(4))) [0, 1, 2] >>> common_prefix([1, 2, 3], [1, 2, 5]) [1, 2] >>> common_prefix([1, 2, 3], [1, 3, 5]) [1] """ if not all(seqs): return [] elif len(seqs) == 1: return seqs[0] i = 0 for i in range(min(len(s) for s in seqs)): if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))): break else: i += 1 return seqs[0][:i] def common_suffix(*seqs): """Return the subsequence that is a common ending of sequences in ``seqs``. >>> from sympy.utilities.iterables import common_suffix >>> common_suffix(list(range(3))) [0, 1, 2] >>> common_suffix(list(range(3)), list(range(4))) [] >>> common_suffix([1, 2, 3], [9, 2, 3]) [2, 3] >>> common_suffix([1, 2, 3], [9, 7, 3]) [3] """ if not all(seqs): return [] elif len(seqs) == 1: return seqs[0] i = 0 for i in range(-1, -min(len(s) for s in seqs) - 1, -1): if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))): break else: i -= 1 if i == -1: return [] else: return seqs[0][i + 1:] def prefixes(seq): """ Generate all prefixes of a sequence. Examples ======== >>> from sympy.utilities.iterables import prefixes >>> list(prefixes([1,2,3,4])) [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]] """ n = len(seq) for i in range(n): yield seq[:i + 1] def postfixes(seq): """ Generate all postfixes of a sequence. Examples ======== >>> from sympy.utilities.iterables import postfixes >>> list(postfixes([1,2,3,4])) [[4], [3, 4], [2, 3, 4], [1, 2, 3, 4]] """ n = len(seq) for i in range(n): yield seq[n - i - 1:] def topological_sort(graph, key=None): r""" Topological sort of graph's vertices. Parameters ========== graph : tuple[list, list[tuple[T, T]] A tuple consisting of a list of vertices and a list of edges of a graph to be sorted topologically. key : callable[T] (optional) Ordering key for vertices on the same level. By default the natural (e.g. lexicographic) ordering is used (in this case the base type must implement ordering relations). Examples ======== Consider a graph:: +---+ +---+ +---+ | 7 |\ | 5 | | 3 | +---+ \ +---+ +---+ | _\___/ ____ _/ | | / \___/ \ / | V V V V | +----+ +---+ | | 11 | | 8 | | +----+ +---+ | | | \____ ___/ _ | | \ \ / / \ | V \ V V / V V +---+ \ +---+ | +----+ | 2 | | | 9 | | | 10 | +---+ | +---+ | +----+ \________/ where vertices are integers. This graph can be encoded using elementary Python's data structures as follows:: >>> V = [2, 3, 5, 7, 8, 9, 10, 11] >>> E = [(7, 11), (7, 8), (5, 11), (3, 8), (3, 10), ... (11, 2), (11, 9), (11, 10), (8, 9)] To compute a topological sort for graph ``(V, E)`` issue:: >>> from sympy.utilities.iterables import topological_sort >>> topological_sort((V, E)) [3, 5, 7, 8, 11, 2, 9, 10] If specific tie breaking approach is needed, use ``key`` parameter:: >>> topological_sort((V, E), key=lambda v: -v) [7, 5, 11, 3, 10, 8, 9, 2] Only acyclic graphs can be sorted. If the input graph has a cycle, then ``ValueError`` will be raised:: >>> topological_sort((V, E + [(10, 7)])) Traceback (most recent call last): ... ValueError: cycle detected References ========== .. [1] https://en.wikipedia.org/wiki/Topological_sorting """ V, E = graph L = [] S = set(V) E = list(E) for v, u in E: S.discard(u) if key is None: key = lambda value: value S = sorted(S, key=key, reverse=True) while S: node = S.pop() L.append(node) for u, v in list(E): if u == node: E.remove((u, v)) for _u, _v in E: if v == _v: break else: kv = key(v) for i, s in enumerate(S): ks = key(s) if kv > ks: S.insert(i, v) break else: S.append(v) if E: raise ValueError("cycle detected") else: return L def strongly_connected_components(G): r""" Strongly connected components of a directed graph in reverse topological order. Parameters ========== graph : tuple[list, list[tuple[T, T]] A tuple consisting of a list of vertices and a list of edges of a graph whose strongly connected components are to be found. Examples ======== Consider a directed graph (in dot notation):: digraph { A -> B A -> C B -> C C -> B B -> D } .. graphviz:: digraph { A -> B A -> C B -> C C -> B B -> D } where vertices are the letters A, B, C and D. This graph can be encoded using Python's elementary data structures as follows:: >>> V = ['A', 'B', 'C', 'D'] >>> E = [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'B'), ('B', 'D')] The strongly connected components of this graph can be computed as >>> from sympy.utilities.iterables import strongly_connected_components >>> strongly_connected_components((V, E)) [['D'], ['B', 'C'], ['A']] This also gives the components in reverse topological order. Since the subgraph containing B and C has a cycle they must be together in a strongly connected component. A and D are connected to the rest of the graph but not in a cyclic manner so they appear as their own strongly connected components. Notes ===== The vertices of the graph must be hashable for the data structures used. If the vertices are unhashable replace them with integer indices. This function uses Tarjan's algorithm to compute the strongly connected components in `O(|V|+|E|)` (linear) time. References ========== .. [1] https://en.wikipedia.org/wiki/Strongly_connected_component .. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm See Also ======== sympy.utilities.iterables.connected_components """ # Map from a vertex to its neighbours V, E = G Gmap = {vi: [] for vi in V} for v1, v2 in E: Gmap[v1].append(v2) return _strongly_connected_components(V, Gmap) def _strongly_connected_components(V, Gmap): """More efficient internal routine for strongly_connected_components""" # # Here V is an iterable of vertices and Gmap is a dict mapping each vertex # to a list of neighbours e.g.: # # V = [0, 1, 2, 3] # Gmap = {0: [2, 3], 1: [0]} # # For a large graph these data structures can often be created more # efficiently then those expected by strongly_connected_components() which # in this case would be # # V = [0, 1, 2, 3] # Gmap = [(0, 2), (0, 3), (1, 0)] # # XXX: Maybe this should be the recommended function to use instead... # # Non-recursive Tarjan's algorithm: lowlink = {} indices = {} stack = OrderedDict() callstack = [] components = [] nomore = object() def start(v): index = len(stack) indices[v] = lowlink[v] = index stack[v] = None callstack.append((v, iter(Gmap[v]))) def finish(v1): # Finished a component? if lowlink[v1] == indices[v1]: component = [stack.popitem()[0]] while component[-1] is not v1: component.append(stack.popitem()[0]) components.append(component[::-1]) v2, _ = callstack.pop() if callstack: v1, _ = callstack[-1] lowlink[v1] = min(lowlink[v1], lowlink[v2]) for v in V: if v in indices: continue start(v) while callstack: v1, it1 = callstack[-1] v2 = next(it1, nomore) # Finished children of v1? if v2 is nomore: finish(v1) # Recurse on v2 elif v2 not in indices: start(v2) elif v2 in stack: lowlink[v1] = min(lowlink[v1], indices[v2]) # Reverse topological sort order: return components def connected_components(G): r""" Connected components of an undirected graph or weakly connected components of a directed graph. Parameters ========== graph : tuple[list, list[tuple[T, T]] A tuple consisting of a list of vertices and a list of edges of a graph whose connected components are to be found. Examples ======== Given an undirected graph:: graph { A -- B C -- D } .. graphviz:: graph { A -- B C -- D } We can find the connected components using this function if we include each edge in both directions:: >>> from sympy.utilities.iterables import connected_components >>> V = ['A', 'B', 'C', 'D'] >>> E = [('A', 'B'), ('B', 'A'), ('C', 'D'), ('D', 'C')] >>> connected_components((V, E)) [['A', 'B'], ['C', 'D']] The weakly connected components of a directed graph can found the same way. Notes ===== The vertices of the graph must be hashable for the data structures used. If the vertices are unhashable replace them with integer indices. This function uses Tarjan's algorithm to compute the connected components in `O(|V|+|E|)` (linear) time. References ========== .. [1] https://en.wikipedia.org/wiki/Component_(graph_theory) .. [2] https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm See Also ======== sympy.utilities.iterables.strongly_connected_components """ # Duplicate edges both ways so that the graph is effectively undirected # and return the strongly connected components: V, E = G E_undirected = [] for v1, v2 in E: E_undirected.extend([(v1, v2), (v2, v1)]) return strongly_connected_components((V, E_undirected)) def rotate_left(x, y): """ Left rotates a list x by the number of steps specified in y. Examples ======== >>> from sympy.utilities.iterables import rotate_left >>> a = [0, 1, 2] >>> rotate_left(a, 1) [1, 2, 0] """ if len(x) == 0: return [] y = y % len(x) return x[y:] + x[:y] def rotate_right(x, y): """ Right rotates a list x by the number of steps specified in y. Examples ======== >>> from sympy.utilities.iterables import rotate_right >>> a = [0, 1, 2] >>> rotate_right(a, 1) [2, 0, 1] """ if len(x) == 0: return [] y = len(x) - y % len(x) return x[y:] + x[:y] def least_rotation(x, key=None): ''' Returns the number of steps of left rotation required to obtain lexicographically minimal string/list/tuple, etc. Examples ======== >>> from sympy.utilities.iterables import least_rotation, rotate_left >>> a = [3, 1, 5, 1, 2] >>> least_rotation(a) 3 >>> rotate_left(a, _) [1, 2, 3, 1, 5] References ========== .. [1] https://en.wikipedia.org/wiki/Lexicographically_minimal_string_rotation ''' from sympy.functions.elementary.miscellaneous import Id if key is None: key = Id S = x + x # Concatenate string to it self to avoid modular arithmetic f = [-1] * len(S) # Failure function k = 0 # Least rotation of string found so far for j in range(1,len(S)): sj = S[j] i = f[j-k-1] while i != -1 and sj != S[k+i+1]: if key(sj) < key(S[k+i+1]): k = j-i-1 i = f[i] if sj != S[k+i+1]: if key(sj) < key(S[k]): k = j f[j-k] = -1 else: f[j-k] = i+1 return k def multiset_combinations(m, n, g=None): """ Return the unique combinations of size ``n`` from multiset ``m``. Examples ======== >>> from sympy.utilities.iterables import multiset_combinations >>> from itertools import combinations >>> [''.join(i) for i in multiset_combinations('baby', 3)] ['abb', 'aby', 'bby'] >>> def count(f, s): return len(list(f(s, 3))) The number of combinations depends on the number of letters; the number of unique combinations depends on how the letters are repeated. >>> s1 = 'abracadabra' >>> s2 = 'banana tree' >>> count(combinations, s1), count(multiset_combinations, s1) (165, 23) >>> count(combinations, s2), count(multiset_combinations, s2) (165, 54) """ from sympy.core.sorting import ordered if g is None: if isinstance(m, dict): if any(as_int(v) < 0 for v in m.values()): raise ValueError('counts cannot be negative') N = sum(m.values()) if n > N: return g = [[k, m[k]] for k in ordered(m)] else: m = list(m) N = len(m) if n > N: return try: m = multiset(m) g = [(k, m[k]) for k in ordered(m)] except TypeError: m = list(ordered(m)) g = [list(i) for i in group(m, multiple=False)] del m else: # not checking counts since g is intended for internal use N = sum(v for k, v in g) if n > N or not n: yield [] else: for i, (k, v) in enumerate(g): if v >= n: yield [k]*n v = n - 1 for v in range(min(n, v), 0, -1): for j in multiset_combinations(None, n - v, g[i + 1:]): rv = [k]*v + j if len(rv) == n: yield rv def multiset_permutations(m, size=None, g=None): """ Return the unique permutations of multiset ``m``. Examples ======== >>> from sympy.utilities.iterables import multiset_permutations >>> from sympy import factorial >>> [''.join(i) for i in multiset_permutations('aab')] ['aab', 'aba', 'baa'] >>> factorial(len('banana')) 720 >>> len(list(multiset_permutations('banana'))) 60 """ from sympy.core.sorting import ordered if g is None: if isinstance(m, dict): if any(as_int(v) < 0 for v in m.values()): raise ValueError('counts cannot be negative') g = [[k, m[k]] for k in ordered(m)] else: m = list(ordered(m)) g = [list(i) for i in group(m, multiple=False)] del m do = [gi for gi in g if gi[1] > 0] SUM = sum([gi[1] for gi in do]) if not do or size is not None and (size > SUM or size < 1): if not do and size is None or size == 0: yield [] return elif size == 1: for k, v in do: yield [k] elif len(do) == 1: k, v = do[0] v = v if size is None else (size if size <= v else 0) yield [k for i in range(v)] elif all(v == 1 for k, v in do): for p in permutations([k for k, v in do], size): yield list(p) else: size = size if size is not None else SUM for i, (k, v) in enumerate(do): do[i][1] -= 1 for j in multiset_permutations(None, size - 1, do): if j: yield [k] + j do[i][1] += 1 def _partition(seq, vector, m=None): """ Return the partition of seq as specified by the partition vector. Examples ======== >>> from sympy.utilities.iterables import _partition >>> _partition('abcde', [1, 0, 1, 2, 0]) [['b', 'e'], ['a', 'c'], ['d']] Specifying the number of bins in the partition is optional: >>> _partition('abcde', [1, 0, 1, 2, 0], 3) [['b', 'e'], ['a', 'c'], ['d']] The output of _set_partitions can be passed as follows: >>> output = (3, [1, 0, 1, 2, 0]) >>> _partition('abcde', *output) [['b', 'e'], ['a', 'c'], ['d']] See Also ======== combinatorics.partitions.Partition.from_rgs """ if m is None: m = max(vector) + 1 elif isinstance(vector, int): # entered as m, vector vector, m = m, vector p = [[] for i in range(m)] for i, v in enumerate(vector): p[v].append(seq[i]) return p def _set_partitions(n): """Cycle through all partitions of n elements, yielding the current number of partitions, ``m``, and a mutable list, ``q`` such that ``element[i]`` is in part ``q[i]`` of the partition. NOTE: ``q`` is modified in place and generally should not be changed between function calls. Examples ======== >>> from sympy.utilities.iterables import _set_partitions, _partition >>> for m, q in _set_partitions(3): ... print('%s %s %s' % (m, q, _partition('abc', q, m))) 1 [0, 0, 0] [['a', 'b', 'c']] 2 [0, 0, 1] [['a', 'b'], ['c']] 2 [0, 1, 0] [['a', 'c'], ['b']] 2 [0, 1, 1] [['a'], ['b', 'c']] 3 [0, 1, 2] [['a'], ['b'], ['c']] Notes ===== This algorithm is similar to, and solves the same problem as, Algorithm 7.2.1.5H, from volume 4A of Knuth's The Art of Computer Programming. Knuth uses the term "restricted growth string" where this code refers to a "partition vector". In each case, the meaning is the same: the value in the ith element of the vector specifies to which part the ith set element is to be assigned. At the lowest level, this code implements an n-digit big-endian counter (stored in the array q) which is incremented (with carries) to get the next partition in the sequence. A special twist is that a digit is constrained to be at most one greater than the maximum of all the digits to the left of it. The array p maintains this maximum, so that the code can efficiently decide when a digit can be incremented in place or whether it needs to be reset to 0 and trigger a carry to the next digit. The enumeration starts with all the digits 0 (which corresponds to all the set elements being assigned to the same 0th part), and ends with 0123...n, which corresponds to each set element being assigned to a different, singleton, part. This routine was rewritten to use 0-based lists while trying to preserve the beauty and efficiency of the original algorithm. References ========== .. [1] Nijenhuis, Albert and Wilf, Herbert. (1978) Combinatorial Algorithms, 2nd Ed, p 91, algorithm "nexequ". Available online from https://www.math.upenn.edu/~wilf/website/CombAlgDownld.html (viewed November 17, 2012). """ p = [0]*n q = [0]*n nc = 1 yield nc, q while nc != n: m = n while 1: m -= 1 i = q[m] if p[i] != 1: break q[m] = 0 i += 1 q[m] = i m += 1 nc += m - n p[0] += n - m if i == nc: p[nc] = 0 nc += 1 p[i - 1] -= 1 p[i] += 1 yield nc, q def multiset_partitions(multiset, m=None): """ Return unique partitions of the given multiset (in list form). If ``m`` is None, all multisets will be returned, otherwise only partitions with ``m`` parts will be returned. If ``multiset`` is an integer, a range [0, 1, ..., multiset - 1] will be supplied. Examples ======== >>> from sympy.utilities.iterables import multiset_partitions >>> list(multiset_partitions([1, 2, 3, 4], 2)) [[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]], [[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]], [[1], [2, 3, 4]]] >>> list(multiset_partitions([1, 2, 3, 4], 1)) [[[1, 2, 3, 4]]] Only unique partitions are returned and these will be returned in a canonical order regardless of the order of the input: >>> a = [1, 2, 2, 1] >>> ans = list(multiset_partitions(a, 2)) >>> a.sort() >>> list(multiset_partitions(a, 2)) == ans True >>> a = range(3, 1, -1) >>> (list(multiset_partitions(a)) == ... list(multiset_partitions(sorted(a)))) True If m is omitted then all partitions will be returned: >>> list(multiset_partitions([1, 1, 2])) [[[1, 1, 2]], [[1, 1], [2]], [[1, 2], [1]], [[1], [1], [2]]] >>> list(multiset_partitions([1]*3)) [[[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]] Counting ======== The number of partitions of a set is given by the bell number: >>> from sympy import bell >>> len(list(multiset_partitions(5))) == bell(5) == 52 True The number of partitions of length k from a set of size n is given by the Stirling Number of the 2nd kind: >>> from sympy.functions.combinatorial.numbers import stirling >>> stirling(5, 2) == len(list(multiset_partitions(5, 2))) == 15 True These comments on counting apply to *sets*, not multisets. Notes ===== When all the elements are the same in the multiset, the order of the returned partitions is determined by the ``partitions`` routine. If one is counting partitions then it is better to use the ``nT`` function. See Also ======== partitions sympy.combinatorics.partitions.Partition sympy.combinatorics.partitions.IntegerPartition sympy.functions.combinatorial.numbers.nT """ # This function looks at the supplied input and dispatches to # several special-case routines as they apply. if isinstance(multiset, int): n = multiset if m and m > n: return multiset = list(range(n)) if m == 1: yield [multiset[:]] return # If m is not None, it can sometimes be faster to use # MultisetPartitionTraverser.enum_range() even for inputs # which are sets. Since the _set_partitions code is quite # fast, this is only advantageous when the overall set # partitions outnumber those with the desired number of parts # by a large factor. (At least 60.) Such a switch is not # currently implemented. for nc, q in _set_partitions(n): if m is None or nc == m: rv = [[] for i in range(nc)] for i in range(n): rv[q[i]].append(multiset[i]) yield rv return if len(multiset) == 1 and isinstance(multiset, str): multiset = [multiset] if not has_variety(multiset): # Only one component, repeated n times. The resulting # partitions correspond to partitions of integer n. n = len(multiset) if m and m > n: return if m == 1: yield [multiset[:]] return x = multiset[:1] for size, p in partitions(n, m, size=True): if m is None or size == m: rv = [] for k in sorted(p): rv.extend([x*k]*p[k]) yield rv else: from sympy.core.sorting import ordered multiset = list(ordered(multiset)) n = len(multiset) if m and m > n: return if m == 1: yield [multiset[:]] return # Split the information of the multiset into two lists - # one of the elements themselves, and one (of the same length) # giving the number of repeats for the corresponding element. elements, multiplicities = zip(*group(multiset, False)) if len(elements) < len(multiset): # General case - multiset with more than one distinct element # and at least one element repeated more than once. if m: mpt = MultisetPartitionTraverser() for state in mpt.enum_range(multiplicities, m-1, m): yield list_visitor(state, elements) else: for state in multiset_partitions_taocp(multiplicities): yield list_visitor(state, elements) else: # Set partitions case - no repeated elements. Pretty much # same as int argument case above, with same possible, but # currently unimplemented optimization for some cases when # m is not None for nc, q in _set_partitions(n): if m is None or nc == m: rv = [[] for i in range(nc)] for i in range(n): rv[q[i]].append(i) yield [[multiset[j] for j in i] for i in rv] def partitions(n, m=None, k=None, size=False): """Generate all partitions of positive integer, n. Parameters ========== m : integer (default gives partitions of all sizes) limits number of parts in partition (mnemonic: m, maximum parts) k : integer (default gives partitions number from 1 through n) limits the numbers that are kept in the partition (mnemonic: k, keys) size : bool (default False, only partition is returned) when ``True`` then (M, P) is returned where M is the sum of the multiplicities and P is the generated partition. Each partition is represented as a dictionary, mapping an integer to the number of copies of that integer in the partition. For example, the first partition of 4 returned is {4: 1}, "4: one of them". Examples ======== >>> from sympy.utilities.iterables import partitions The numbers appearing in the partition (the key of the returned dict) are limited with k: >>> for p in partitions(6, k=2): # doctest: +SKIP ... print(p) {2: 3} {1: 2, 2: 2} {1: 4, 2: 1} {1: 6} The maximum number of parts in the partition (the sum of the values in the returned dict) are limited with m (default value, None, gives partitions from 1 through n): >>> for p in partitions(6, m=2): # doctest: +SKIP ... print(p) ... {6: 1} {1: 1, 5: 1} {2: 1, 4: 1} {3: 2} References ========== .. [1] modified from Tim Peter's version to allow for k and m values: http://code.activestate.com/recipes/218332-generator-for-integer-partitions/ See Also ======== sympy.combinatorics.partitions.Partition sympy.combinatorics.partitions.IntegerPartition """ if (n <= 0 or m is not None and m < 1 or k is not None and k < 1 or m and k and m*k < n): # the empty set is the only way to handle these inputs # and returning {} to represent it is consistent with # the counting convention, e.g. nT(0) == 1. if size: yield 0, {} else: yield {} return if m is None: m = n else: m = min(m, n) k = min(k or n, n) n, m, k = as_int(n), as_int(m), as_int(k) q, r = divmod(n, k) ms = {k: q} keys = [k] # ms.keys(), from largest to smallest if r: ms[r] = 1 keys.append(r) room = m - q - bool(r) if size: yield sum(ms.values()), ms.copy() else: yield ms.copy() while keys != [1]: # Reuse any 1's. if keys[-1] == 1: del keys[-1] reuse = ms.pop(1) room += reuse else: reuse = 0 while 1: # Let i be the smallest key larger than 1. Reuse one # instance of i. i = keys[-1] newcount = ms[i] = ms[i] - 1 reuse += i if newcount == 0: del keys[-1], ms[i] room += 1 # Break the remainder into pieces of size i-1. i -= 1 q, r = divmod(reuse, i) need = q + bool(r) if need > room: if not keys: return continue ms[i] = q keys.append(i) if r: ms[r] = 1 keys.append(r) break room -= need if size: yield sum(ms.values()), ms.copy() else: yield ms.copy() def ordered_partitions(n, m=None, sort=True): """Generates ordered partitions of integer ``n``. Parameters ========== m : integer (default None) The default value gives partitions of all sizes else only those with size m. In addition, if ``m`` is not None then partitions are generated *in place* (see examples). sort : bool (default True) Controls whether partitions are returned in sorted order when ``m`` is not None; when False, the partitions are returned as fast as possible with elements sorted, but when m|n the partitions will not be in ascending lexicographical order. Examples ======== >>> from sympy.utilities.iterables import ordered_partitions All partitions of 5 in ascending lexicographical: >>> for p in ordered_partitions(5): ... print(p) [1, 1, 1, 1, 1] [1, 1, 1, 2] [1, 1, 3] [1, 2, 2] [1, 4] [2, 3] [5] Only partitions of 5 with two parts: >>> for p in ordered_partitions(5, 2): ... print(p) [1, 4] [2, 3] When ``m`` is given, a given list objects will be used more than once for speed reasons so you will not see the correct partitions unless you make a copy of each as it is generated: >>> [p for p in ordered_partitions(7, 3)] [[1, 1, 1], [1, 1, 1], [1, 1, 1], [2, 2, 2]] >>> [list(p) for p in ordered_partitions(7, 3)] [[1, 1, 5], [1, 2, 4], [1, 3, 3], [2, 2, 3]] When ``n`` is a multiple of ``m``, the elements are still sorted but the partitions themselves will be *unordered* if sort is False; the default is to return them in ascending lexicographical order. >>> for p in ordered_partitions(6, 2): ... print(p) [1, 5] [2, 4] [3, 3] But if speed is more important than ordering, sort can be set to False: >>> for p in ordered_partitions(6, 2, sort=False): ... print(p) [1, 5] [3, 3] [2, 4] References ========== .. [1] Generating Integer Partitions, [online], Available: https://jeromekelleher.net/generating-integer-partitions.html .. [2] Jerome Kelleher and Barry O'Sullivan, "Generating All Partitions: A Comparison Of Two Encodings", [online], Available: https://arxiv.org/pdf/0909.2331v2.pdf """ if n < 1 or m is not None and m < 1: # the empty set is the only way to handle these inputs # and returning {} to represent it is consistent with # the counting convention, e.g. nT(0) == 1. yield [] return if m is None: # The list `a`'s leading elements contain the partition in which # y is the biggest element and x is either the same as y or the # 2nd largest element; v and w are adjacent element indices # to which x and y are being assigned, respectively. a = [1]*n y = -1 v = n while v > 0: v -= 1 x = a[v] + 1 while y >= 2 * x: a[v] = x y -= x v += 1 w = v + 1 while x <= y: a[v] = x a[w] = y yield a[:w + 1] x += 1 y -= 1 a[v] = x + y y = a[v] - 1 yield a[:w] elif m == 1: yield [n] elif n == m: yield [1]*n else: # recursively generate partitions of size m for b in range(1, n//m + 1): a = [b]*m x = n - b*m if not x: if sort: yield a elif not sort and x <= m: for ax in ordered_partitions(x, sort=False): mi = len(ax) a[-mi:] = [i + b for i in ax] yield a a[-mi:] = [b]*mi else: for mi in range(1, m): for ax in ordered_partitions(x, mi, sort=True): a[-mi:] = [i + b for i in ax] yield a a[-mi:] = [b]*mi def binary_partitions(n): """ Generates the binary partition of n. A binary partition consists only of numbers that are powers of two. Each step reduces a `2^{k+1}` to `2^k` and `2^k`. Thus 16 is converted to 8 and 8. Examples ======== >>> from sympy.utilities.iterables import binary_partitions >>> for i in binary_partitions(5): ... print(i) ... [4, 1] [2, 2, 1] [2, 1, 1, 1] [1, 1, 1, 1, 1] References ========== .. [1] TAOCP 4, section 7.2.1.5, problem 64 """ from math import ceil, log power = int(2**(ceil(log(n, 2)))) acc = 0 partition = [] while power: if acc + power <= n: partition.append(power) acc += power power >>= 1 last_num = len(partition) - 1 - (n & 1) while last_num >= 0: yield partition if partition[last_num] == 2: partition[last_num] = 1 partition.append(1) last_num -= 1 continue partition.append(1) partition[last_num] >>= 1 x = partition[last_num + 1] = partition[last_num] last_num += 1 while x > 1: if x <= len(partition) - last_num - 1: del partition[-x + 1:] last_num += 1 partition[last_num] = x else: x >>= 1 yield [1]*n def has_dups(seq): """Return True if there are any duplicate elements in ``seq``. Examples ======== >>> from sympy import has_dups, Dict, Set >>> has_dups((1, 2, 1)) True >>> has_dups(range(3)) False >>> all(has_dups(c) is False for c in (set(), Set(), dict(), Dict())) True """ from sympy.core.containers import Dict from sympy.sets.sets import Set if isinstance(seq, (dict, set, Dict, Set)): return False unique = set() try: return any(True for s in seq if s in unique or unique.add(s)) except TypeError: return len(seq) != len(list(uniq(seq))) def has_variety(seq): """Return True if there are any different elements in ``seq``. Examples ======== >>> from sympy import has_variety >>> has_variety((1, 2, 1)) True >>> has_variety((1, 1, 1)) False """ for i, s in enumerate(seq): if i == 0: sentinel = s else: if s != sentinel: return True return False def uniq(seq, result=None): """ Yield unique elements from ``seq`` as an iterator. The second parameter ``result`` is used internally; it is not necessary to pass anything for this. Note: changing the sequence during iteration will raise a RuntimeError if the size of the sequence is known; if you pass an iterator and advance the iterator you will change the output of this routine but there will be no warning. Examples ======== >>> from sympy.utilities.iterables import uniq >>> dat = [1, 4, 1, 5, 4, 2, 1, 2] >>> type(uniq(dat)) in (list, tuple) False >>> list(uniq(dat)) [1, 4, 5, 2] >>> list(uniq(x for x in dat)) [1, 4, 5, 2] >>> list(uniq([[1], [2, 1], [1]])) [[1], [2, 1]] """ try: n = len(seq) except TypeError: n = None def check(): # check that size of seq did not change during iteration; # if n == None the object won't support size changing, e.g. # an iterator can't be changed if n is not None and len(seq) != n: raise RuntimeError('sequence changed size during iteration') try: seen = set() result = result or [] for i, s in enumerate(seq): if not (s in seen or seen.add(s)): yield s check() except TypeError: if s not in result: yield s check() result.append(s) if hasattr(seq, '__getitem__'): yield from uniq(seq[i + 1:], result) else: yield from uniq(seq, result) def generate_bell(n): """Return permutations of [0, 1, ..., n - 1] such that each permutation differs from the last by the exchange of a single pair of neighbors. The ``n!`` permutations are returned as an iterator. In order to obtain the next permutation from a random starting permutation, use the ``next_trotterjohnson`` method of the Permutation class (which generates the same sequence in a different manner). Examples ======== >>> from itertools import permutations >>> from sympy.utilities.iterables import generate_bell >>> from sympy import zeros, Matrix This is the sort of permutation used in the ringing of physical bells, and does not produce permutations in lexicographical order. Rather, the permutations differ from each other by exactly one inversion, and the position at which the swapping occurs varies periodically in a simple fashion. Consider the first few permutations of 4 elements generated by ``permutations`` and ``generate_bell``: >>> list(permutations(range(4)))[:5] [(0, 1, 2, 3), (0, 1, 3, 2), (0, 2, 1, 3), (0, 2, 3, 1), (0, 3, 1, 2)] >>> list(generate_bell(4))[:5] [(0, 1, 2, 3), (0, 1, 3, 2), (0, 3, 1, 2), (3, 0, 1, 2), (3, 0, 2, 1)] Notice how the 2nd and 3rd lexicographical permutations have 3 elements out of place whereas each "bell" permutation always has only two elements out of place relative to the previous permutation (and so the signature (+/-1) of a permutation is opposite of the signature of the previous permutation). How the position of inversion varies across the elements can be seen by tracing out where the largest number appears in the permutations: >>> m = zeros(4, 24) >>> for i, p in enumerate(generate_bell(4)): ... m[:, i] = Matrix([j - 3 for j in list(p)]) # make largest zero >>> m.print_nonzero('X') [XXX XXXXXX XXXXXX XXX] [XX XX XXXX XX XXXX XX XX] [X XXXX XX XXXX XX XXXX X] [ XXXXXX XXXXXX XXXXXX ] See Also ======== sympy.combinatorics.permutations.Permutation.next_trotterjohnson References ========== .. [1] https://en.wikipedia.org/wiki/Method_ringing .. [2] https://stackoverflow.com/questions/4856615/recursive-permutation/4857018 .. [3] http://programminggeeks.com/bell-algorithm-for-permutation/ .. [4] https://en.wikipedia.org/wiki/Steinhaus%E2%80%93Johnson%E2%80%93Trotter_algorithm .. [5] Generating involutions, derangements, and relatives by ECO Vincent Vajnovszki, DMTCS vol 1 issue 12, 2010 """ n = as_int(n) if n < 1: raise ValueError('n must be a positive integer') if n == 1: yield (0,) elif n == 2: yield (0, 1) yield (1, 0) elif n == 3: yield from [(0, 1, 2), (0, 2, 1), (2, 0, 1), (2, 1, 0), (1, 2, 0), (1, 0, 2)] else: m = n - 1 op = [0] + [-1]*m l = list(range(n)) while True: yield tuple(l) # find biggest element with op big = None, -1 # idx, value for i in range(n): if op[i] and l[i] > big[1]: big = i, l[i] i, _ = big if i is None: break # there are no ops left # swap it with neighbor in the indicated direction j = i + op[i] l[i], l[j] = l[j], l[i] op[i], op[j] = op[j], op[i] # if it landed at the end or if the neighbor in the same # direction is bigger then turn off op if j == 0 or j == m or l[j + op[j]] > l[j]: op[j] = 0 # any element bigger to the left gets +1 op for i in range(j): if l[i] > l[j]: op[i] = 1 # any element bigger to the right gets -1 op for i in range(j + 1, n): if l[i] > l[j]: op[i] = -1 def generate_involutions(n): """ Generates involutions. An involution is a permutation that when multiplied by itself equals the identity permutation. In this implementation the involutions are generated using Fixed Points. Alternatively, an involution can be considered as a permutation that does not contain any cycles with a length that is greater than two. Examples ======== >>> from sympy.utilities.iterables import generate_involutions >>> list(generate_involutions(3)) [(0, 1, 2), (0, 2, 1), (1, 0, 2), (2, 1, 0)] >>> len(list(generate_involutions(4))) 10 References ========== .. [1] http://mathworld.wolfram.com/PermutationInvolution.html """ idx = list(range(n)) for p in permutations(idx): for i in idx: if p[p[i]] != i: break else: yield p def multiset_derangements(s): """Generate derangements of the elements of s *in place*. Examples ======== >>> from sympy.utilities.iterables import multiset_derangements, uniq Because the derangements of multisets (not sets) are generated in place, copies of the return value must be made if a collection of derangements is desired or else all values will be the same: >>> list(uniq([i for i in multiset_derangements('1233')])) [[None, None, None, None]] >>> [i.copy() for i in multiset_derangements('1233')] [['3', '3', '1', '2'], ['3', '3', '2', '1']] >>> [''.join(i) for i in multiset_derangements('1233')] ['3312', '3321'] """ from sympy.core.sorting import ordered # create multiset dictionary of hashable elements or else # remap elements to integers try: ms = multiset(s) except TypeError: # give each element a canonical integer value key = dict(enumerate(ordered(uniq(s)))) h = [] for si in s: for k in key: if key[k] == si: h.append(k) break for i in multiset_derangements(h): yield [key[j] for j in i] return mx = max(ms.values()) # max repetition of any element n = len(s) # the number of elements ## special cases # 1) one element has more than half the total cardinality of s: no # derangements are possible. if mx*2 > n: return # 2) all elements appear once: singletons if len(ms) == n: yield from _set_derangements(s) return # find the first element that is repeated the most to place # in the following two special cases where the selection # is unambiguous: either there are two elements with multiplicity # of mx or else there is only one with multiplicity mx for M in ms: if ms[M] == mx: break inonM = [i for i in range(n) if s[i] != M] # location of non-M iM = [i for i in range(n) if s[i] == M] # locations of M rv = [None]*n # 3) half are the same if 2*mx == n: # M goes into non-M locations for i in inonM: rv[i] = M # permutations of non-M go to M locations for p in multiset_permutations([s[i] for i in inonM]): for i, pi in zip(iM, p): rv[i] = pi yield rv # clean-up (and encourages proper use of routine) rv[:] = [None]*n return # 4) single repeat covers all but 1 of the non-repeats: # if there is one repeat then the multiset of the values # of ms would be {mx: 1, 1: n - mx}, i.e. there would # be n - mx + 1 values with the condition that n - 2*mx = 1 if n - 2*mx == 1 and len(ms.values()) == n - mx + 1: for i, i1 in enumerate(inonM): ifill = inonM[:i] + inonM[i+1:] for j in ifill: rv[j] = M for p in permutations([s[j] for j in ifill]): rv[i1] = s[i1] for j, pi in zip(iM, p): rv[j] = pi k = i1 for j in iM: rv[j], rv[k] = rv[k], rv[j] yield rv k = j # clean-up (and encourages proper use of routine) rv[:] = [None]*n return ## general case is handled with 3 helpers: # 1) `finish_derangements` will place the last two elements # which have arbitrary multiplicities, e.g. for multiset # {c: 3, a: 2, b: 2}, the last two elements are a and b # 2) `iopen` will tell where a given element can be placed # 3) `do` will recursively place elements into subsets of # valid locations def finish_derangements(): """Place the last two elements into the partially completed derangement, and yield the results. """ a = take[1][0] # penultimate element a_ct = take[1][1] b = take[0][0] # last element to be placed b_ct = take[0][1] # split the indexes of the not-already-assigned elements of rv into # three categories forced_a = [] # positions which must have an a forced_b = [] # positions which must have a b open_free = [] # positions which could take either for i in range(len(s)): if rv[i] is None: if s[i] == a: forced_b.append(i) elif s[i] == b: forced_a.append(i) else: open_free.append(i) if len(forced_a) > a_ct or len(forced_b) > b_ct: # No derangement possible return for i in forced_a: rv[i] = a for i in forced_b: rv[i] = b for a_place in combinations(open_free, a_ct - len(forced_a)): for a_pos in a_place: rv[a_pos] = a for i in open_free: if rv[i] is None: # anything not in the subset is set to b rv[i] = b yield rv # Clean up/undo the final placements for i in open_free: rv[i] = None # additional cleanup - clear forced_a, forced_b for i in forced_a: rv[i] = None for i in forced_b: rv[i] = None def iopen(v): # return indices at which element v can be placed in rv: # locations which are not already occupied if that location # does not already contain v in the same location of s return [i for i in range(n) if rv[i] is None and s[i] != v] def do(j): if j == 1: # handle the last two elements (regardless of multiplicity) # with a special method yield from finish_derangements() else: # place the mx elements of M into a subset of places # into which it can be replaced M, mx = take[j] for i in combinations(iopen(M), mx): # place M for ii in i: rv[ii] = M # recursively place the next element yield from do(j - 1) # mark positions where M was placed as once again # open for placement of other elements for ii in i: rv[ii] = None # process elements in order of canonically decreasing multiplicity take = sorted(ms.items(), key=lambda x:(x[1], x[0])) yield from do(len(take) - 1) rv[:] = [None]*n def random_derangement(t, choice=None, strict=True): """Return a list of elements in which none are in the same positions as they were originally. If an element fills more than half of the positions then an error will be raised since no derangement is possible. To obtain a derangement of as many items as possible--with some of the most numerous remaining in their original positions--pass `strict=False`. To produce a pseudorandom derangment, pass a pseudorandom selector like `choice` (see below). Examples ======== >>> from sympy.utilities.iterables import random_derangement >>> t = 'SymPy: a CAS in pure Python' >>> d = random_derangement(t) >>> all(i != j for i, j in zip(d, t)) True A predictable result can be obtained by using a pseudorandom generator for the choice: >>> from sympy.core.random import seed, choice as c >>> seed(1) >>> d = [''.join(random_derangement(t, c)) for i in range(5)] >>> assert len(set(d)) != 1 # we got different values By reseeding, the same sequence can be obtained: >>> seed(1) >>> d2 = [''.join(random_derangement(t, c)) for i in range(5)] >>> assert d == d2 """ if choice is None: import secrets choice = secrets.choice def shuffle(rv): '''Knuth shuffle''' for i in range(len(rv) - 1, 0, -1): x = choice(rv[:i + 1]) j = rv.index(x) rv[i], rv[j] = rv[j], rv[i] def pick(rv, n): '''shuffle rv and return the first n values ''' shuffle(rv) return rv[:n] ms = multiset(t) tot = len(t) ms = sorted(ms.items(), key=lambda x: x[1]) # if there are not enough spaces for the most # plentiful element to move to then some of them # will have to stay in place M, mx = ms[-1] n = len(t) xs = 2*mx - tot if xs > 0: if strict: raise ValueError('no derangement possible') opts = [i for (i, c) in enumerate(t) if c == ms[-1][0]] pick(opts, xs) stay = sorted(opts[:xs]) rv = list(t) for i in reversed(stay): rv.pop(i) rv = random_derangement(rv, choice) for i in stay: rv.insert(i, ms[-1][0]) return ''.join(rv) if type(t) is str else rv # the normal derangement calculated from here if n == len(ms): # approx 1/3 will succeed rv = list(t) while True: shuffle(rv) if all(i != j for i,j in zip(rv, t)): break else: # general case rv = [None]*n while True: j = 0 while j > -len(ms): # do most numerous first j -= 1 e, c = ms[j] opts = [i for i in range(n) if rv[i] is None and t[i] != e] if len(opts) < c: for i in range(n): rv[i] = None break # try again pick(opts, c) for i in range(c): rv[opts[i]] = e else: return rv return rv def _set_derangements(s): """ yield derangements of items in ``s`` which are assumed to contain no repeated elements """ if len(s) < 2: return if len(s) == 2: yield [s[1], s[0]] return if len(s) == 3: yield [s[1], s[2], s[0]] yield [s[2], s[0], s[1]] return for p in permutations(s): if not any(i == j for i, j in zip(p, s)): yield list(p) def generate_derangements(s): """ Return unique derangements of the elements of iterable ``s``. Examples ======== >>> from sympy.utilities.iterables import generate_derangements >>> list(generate_derangements([0, 1, 2])) [[1, 2, 0], [2, 0, 1]] >>> list(generate_derangements([0, 1, 2, 2])) [[2, 2, 0, 1], [2, 2, 1, 0]] >>> list(generate_derangements([0, 1, 1])) [] See Also ======== sympy.functions.combinatorial.factorials.subfactorial """ if not has_dups(s): yield from _set_derangements(s) else: for p in multiset_derangements(s): yield list(p) def necklaces(n, k, free=False): """ A routine to generate necklaces that may (free=True) or may not (free=False) be turned over to be viewed. The "necklaces" returned are comprised of ``n`` integers (beads) with ``k`` different values (colors). Only unique necklaces are returned. Examples ======== >>> from sympy.utilities.iterables import necklaces, bracelets >>> def show(s, i): ... return ''.join(s[j] for j in i) The "unrestricted necklace" is sometimes also referred to as a "bracelet" (an object that can be turned over, a sequence that can be reversed) and the term "necklace" is used to imply a sequence that cannot be reversed. So ACB == ABC for a bracelet (rotate and reverse) while the two are different for a necklace since rotation alone cannot make the two sequences the same. (mnemonic: Bracelets can be viewed Backwards, but Not Necklaces.) >>> B = [show('ABC', i) for i in bracelets(3, 3)] >>> N = [show('ABC', i) for i in necklaces(3, 3)] >>> set(N) - set(B) {'ACB'} >>> list(necklaces(4, 2)) [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 1), (0, 1, 0, 1), (0, 1, 1, 1), (1, 1, 1, 1)] >>> [show('.o', i) for i in bracelets(4, 2)] ['....', '...o', '..oo', '.o.o', '.ooo', 'oooo'] References ========== .. [1] http://mathworld.wolfram.com/Necklace.html .. [2] Frank Ruskey, Carla Savage, and Terry Min Yih Wang, Generating necklaces, Journal of Algorithms 13 (1992), 414-430; https://doi.org/10.1016/0196-6774(92)90047-G """ # The FKM algorithm if k == 0 and n > 0: return a = [0]*n yield tuple(a) if n == 0: return while True: i = n - 1 while a[i] == k - 1: i -= 1 if i == -1: return a[i] += 1 for j in range(n - i - 1): a[j + i + 1] = a[j] if n % (i + 1) == 0 and (not free or all(a <= a[j::-1] + a[-1:j:-1] for j in range(n - 1))): # No need to test j = n - 1. yield tuple(a) def bracelets(n, k): """Wrapper to necklaces to return a free (unrestricted) necklace.""" return necklaces(n, k, free=True) def generate_oriented_forest(n): """ This algorithm generates oriented forests. An oriented graph is a directed graph having no symmetric pair of directed edges. A forest is an acyclic graph, i.e., it has no cycles. A forest can also be described as a disjoint union of trees, which are graphs in which any two vertices are connected by exactly one simple path. Examples ======== >>> from sympy.utilities.iterables import generate_oriented_forest >>> list(generate_oriented_forest(4)) [[0, 1, 2, 3], [0, 1, 2, 2], [0, 1, 2, 1], [0, 1, 2, 0], \ [0, 1, 1, 1], [0, 1, 1, 0], [0, 1, 0, 1], [0, 1, 0, 0], [0, 0, 0, 0]] References ========== .. [1] T. Beyer and S.M. Hedetniemi: constant time generation of rooted trees, SIAM J. Computing Vol. 9, No. 4, November 1980 .. [2] https://stackoverflow.com/questions/1633833/oriented-forest-taocp-algorithm-in-python """ P = list(range(-1, n)) while True: yield P[1:] if P[n] > 0: P[n] = P[P[n]] else: for p in range(n - 1, 0, -1): if P[p] != 0: target = P[p] - 1 for q in range(p - 1, 0, -1): if P[q] == target: break offset = p - q for i in range(p, n + 1): P[i] = P[i - offset] break else: break def minlex(seq, directed=True, key=None): r""" Return the rotation of the sequence in which the lexically smallest elements appear first, e.g. `cba \rightarrow acb`. The sequence returned is a tuple, unless the input sequence is a string in which case a string is returned. If ``directed`` is False then the smaller of the sequence and the reversed sequence is returned, e.g. `cba \rightarrow abc`. If ``key`` is not None then it is used to extract a comparison key from each element in iterable. Examples ======== >>> from sympy.combinatorics.polyhedron import minlex >>> minlex((1, 2, 0)) (0, 1, 2) >>> minlex((1, 0, 2)) (0, 2, 1) >>> minlex((1, 0, 2), directed=False) (0, 1, 2) >>> minlex('11010011000', directed=True) '00011010011' >>> minlex('11010011000', directed=False) '00011001011' >>> minlex(('bb', 'aaa', 'c', 'a')) ('a', 'bb', 'aaa', 'c') >>> minlex(('bb', 'aaa', 'c', 'a'), key=len) ('c', 'a', 'bb', 'aaa') """ from sympy.functions.elementary.miscellaneous import Id if key is None: key = Id best = rotate_left(seq, least_rotation(seq, key=key)) if not directed: rseq = seq[::-1] rbest = rotate_left(rseq, least_rotation(rseq, key=key)) best = min(best, rbest, key=key) # Convert to tuple, unless we started with a string. return tuple(best) if not isinstance(seq, str) else best def runs(seq, op=gt): """Group the sequence into lists in which successive elements all compare the same with the comparison operator, ``op``: op(seq[i + 1], seq[i]) is True from all elements in a run. Examples ======== >>> from sympy.utilities.iterables import runs >>> from operator import ge >>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2]) [[0, 1, 2], [2], [1, 4], [3], [2], [2]] >>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2], op=ge) [[0, 1, 2, 2], [1, 4], [3], [2, 2]] """ cycles = [] seq = iter(seq) try: run = [next(seq)] except StopIteration: return [] while True: try: ei = next(seq) except StopIteration: break if op(ei, run[-1]): run.append(ei) continue else: cycles.append(run) run = [ei] if run: cycles.append(run) return cycles def sequence_partitions(l, n, /): r"""Returns the partition of sequence $l$ into $n$ bins Explanation =========== Given the sequence $l_1 \cdots l_m \in V^+$ where $V^+$ is the Kleene plus of $V$ The set of $n$ partitions of $l$ is defined as: .. math:: \{(s_1, \cdots, s_n) | s_1 \in V^+, \cdots, s_n \in V^+, s_1 \cdots s_n = l_1 \cdots l_m\} Parameters ========== l : Sequence[T] A nonempty sequence of any Python objects n : int A positive integer Yields ====== out : list[Sequence[T]] A list of sequences with concatenation equals $l$. This should conform with the type of $l$. Examples ======== >>> from sympy.utilities.iterables import sequence_partitions >>> for out in sequence_partitions([1, 2, 3, 4], 2): ... print(out) [[1], [2, 3, 4]] [[1, 2], [3, 4]] [[1, 2, 3], [4]] Notes ===== This is modified version of EnricoGiampieri's partition generator from https://stackoverflow.com/questions/13131491/ See Also ======== sequence_partitions_empty """ # Asserting l is nonempty is done only for sanity check if n == 1 and l: yield [l] return for i in range(1, len(l)): for part in sequence_partitions(l[i:], n - 1): yield [l[:i]] + part def sequence_partitions_empty(l, n, /): r"""Returns the partition of sequence $l$ into $n$ bins with empty sequence Explanation =========== Given the sequence $l_1 \cdots l_m \in V^*$ where $V^*$ is the Kleene star of $V$ The set of $n$ partitions of $l$ is defined as: .. math:: \{(s_1, \cdots, s_n) | s_1 \in V^*, \cdots, s_n \in V^*, s_1 \cdots s_n = l_1 \cdots l_m\} There are more combinations than :func:`sequence_partitions` because empty sequence can fill everywhere, so we try to provide different utility for this. Parameters ========== l : Sequence[T] A sequence of any Python objects (can be possibly empty) n : int A positive integer Yields ====== out : list[Sequence[T]] A list of sequences with concatenation equals $l$. This should conform with the type of $l$. Examples ======== >>> from sympy.utilities.iterables import sequence_partitions_empty >>> for out in sequence_partitions_empty([1, 2, 3, 4], 2): ... print(out) [[], [1, 2, 3, 4]] [[1], [2, 3, 4]] [[1, 2], [3, 4]] [[1, 2, 3], [4]] [[1, 2, 3, 4], []] See Also ======== sequence_partitions """ if n < 1: return if n == 1: yield [l] return for i in range(0, len(l) + 1): for part in sequence_partitions_empty(l[i:], n - 1): yield [l[:i]] + part def kbins(l, k, ordered=None): """ Return sequence ``l`` partitioned into ``k`` bins. Examples ======== The default is to give the items in the same order, but grouped into k partitions without any reordering: >>> from sympy.utilities.iterables import kbins >>> for p in kbins(list(range(5)), 2): ... print(p) ... [[0], [1, 2, 3, 4]] [[0, 1], [2, 3, 4]] [[0, 1, 2], [3, 4]] [[0, 1, 2, 3], [4]] The ``ordered`` flag is either None (to give the simple partition of the elements) or is a 2 digit integer indicating whether the order of the bins and the order of the items in the bins matters. Given:: A = [[0], [1, 2]] B = [[1, 2], [0]] C = [[2, 1], [0]] D = [[0], [2, 1]] the following values for ``ordered`` have the shown meanings:: 00 means A == B == C == D 01 means A == B 10 means A == D 11 means A == A >>> for ordered_flag in [None, 0, 1, 10, 11]: ... print('ordered = %s' % ordered_flag) ... for p in kbins(list(range(3)), 2, ordered=ordered_flag): ... print(' %s' % p) ... ordered = None [[0], [1, 2]] [[0, 1], [2]] ordered = 0 [[0, 1], [2]] [[0, 2], [1]] [[0], [1, 2]] ordered = 1 [[0], [1, 2]] [[0], [2, 1]] [[1], [0, 2]] [[1], [2, 0]] [[2], [0, 1]] [[2], [1, 0]] ordered = 10 [[0, 1], [2]] [[2], [0, 1]] [[0, 2], [1]] [[1], [0, 2]] [[0], [1, 2]] [[1, 2], [0]] ordered = 11 [[0], [1, 2]] [[0, 1], [2]] [[0], [2, 1]] [[0, 2], [1]] [[1], [0, 2]] [[1, 0], [2]] [[1], [2, 0]] [[1, 2], [0]] [[2], [0, 1]] [[2, 0], [1]] [[2], [1, 0]] [[2, 1], [0]] See Also ======== partitions, multiset_partitions """ if ordered is None: yield from sequence_partitions(l, k) elif ordered == 11: for pl in multiset_permutations(l): pl = list(pl) yield from sequence_partitions(pl, k) elif ordered == 00: yield from multiset_partitions(l, k) elif ordered == 10: for p in multiset_partitions(l, k): for perm in permutations(p): yield list(perm) elif ordered == 1: for kgot, p in partitions(len(l), k, size=True): if kgot != k: continue for li in multiset_permutations(l): rv = [] i = j = 0 li = list(li) for size, multiplicity in sorted(p.items()): for m in range(multiplicity): j = i + size rv.append(li[i: j]) i = j yield rv else: raise ValueError( 'ordered must be one of 00, 01, 10 or 11, not %s' % ordered) def permute_signs(t): """Return iterator in which the signs of non-zero elements of t are permuted. Examples ======== >>> from sympy.utilities.iterables import permute_signs >>> list(permute_signs((0, 1, 2))) [(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2)] """ for signs in product(*[(1, -1)]*(len(t) - t.count(0))): signs = list(signs) yield type(t)([i*signs.pop() if i else i for i in t]) def signed_permutations(t): """Return iterator in which the signs of non-zero elements of t and the order of the elements are permuted. Examples ======== >>> from sympy.utilities.iterables import signed_permutations >>> list(signed_permutations((0, 1, 2))) [(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2), (0, 2, 1), (0, -2, 1), (0, 2, -1), (0, -2, -1), (1, 0, 2), (-1, 0, 2), (1, 0, -2), (-1, 0, -2), (1, 2, 0), (-1, 2, 0), (1, -2, 0), (-1, -2, 0), (2, 0, 1), (-2, 0, 1), (2, 0, -1), (-2, 0, -1), (2, 1, 0), (-2, 1, 0), (2, -1, 0), (-2, -1, 0)] """ return (type(t)(i) for j in permutations(t) for i in permute_signs(j)) def rotations(s, dir=1): """Return a generator giving the items in s as list where each subsequent list has the items rotated to the left (default) or right (``dir=-1``) relative to the previous list. Examples ======== >>> from sympy import rotations >>> list(rotations([1,2,3])) [[1, 2, 3], [2, 3, 1], [3, 1, 2]] >>> list(rotations([1,2,3], -1)) [[1, 2, 3], [3, 1, 2], [2, 3, 1]] """ seq = list(s) for i in range(len(seq)): yield seq seq = rotate_left(seq, dir) def roundrobin(*iterables): """roundrobin recipe taken from itertools documentation: https://docs.python.org/3/library/itertools.html#itertools-recipes roundrobin('ABC', 'D', 'EF') --> A D E B F C Recipe credited to George Sakkis """ nexts = cycle(iter(it).__next__ for it in iterables) pending = len(iterables) while pending: try: for nxt in nexts: yield nxt() except StopIteration: pending -= 1 nexts = cycle(islice(nexts, pending)) class NotIterable: """ Use this as mixin when creating a class which is not supposed to return true when iterable() is called on its instances because calling list() on the instance, for example, would result in an infinite loop. """ pass def iterable(i, exclude=(str, dict, NotIterable)): """ Return a boolean indicating whether ``i`` is SymPy iterable. True also indicates that the iterator is finite, e.g. you can call list(...) on the instance. When SymPy is working with iterables, it is almost always assuming that the iterable is not a string or a mapping, so those are excluded by default. If you want a pure Python definition, make exclude=None. To exclude multiple items, pass them as a tuple. You can also set the _iterable attribute to True or False on your class, which will override the checks here, including the exclude test. As a rule of thumb, some SymPy functions use this to check if they should recursively map over an object. If an object is technically iterable in the Python sense but does not desire this behavior (e.g., because its iteration is not finite, or because iteration might induce an unwanted computation), it should disable it by setting the _iterable attribute to False. See also: is_sequence Examples ======== >>> from sympy.utilities.iterables import iterable >>> from sympy import Tuple >>> things = [[1], (1,), set([1]), Tuple(1), (j for j in [1, 2]), {1:2}, '1', 1] >>> for i in things: ... print('%s %s' % (iterable(i), type(i))) True <... 'list'> True <... 'tuple'> True <... 'set'> True <class 'sympy.core.containers.Tuple'> True <... 'generator'> False <... 'dict'> False <... 'str'> False <... 'int'> >>> iterable({}, exclude=None) True >>> iterable({}, exclude=str) True >>> iterable("no", exclude=str) False """ if hasattr(i, '_iterable'): return i._iterable try: iter(i) except TypeError: return False if exclude: return not isinstance(i, exclude) return True def is_sequence(i, include=None): """ Return a boolean indicating whether ``i`` is a sequence in the SymPy sense. If anything that fails the test below should be included as being a sequence for your application, set 'include' to that object's type; multiple types should be passed as a tuple of types. Note: although generators can generate a sequence, they often need special handling to make sure their elements are captured before the generator is exhausted, so these are not included by default in the definition of a sequence. See also: iterable Examples ======== >>> from sympy.utilities.iterables import is_sequence >>> from types import GeneratorType >>> is_sequence([]) True >>> is_sequence(set()) False >>> is_sequence('abc') False >>> is_sequence('abc', include=str) True >>> generator = (c for c in 'abc') >>> is_sequence(generator) False >>> is_sequence(generator, include=(str, GeneratorType)) True """ return (hasattr(i, '__getitem__') and iterable(i) or bool(include) and isinstance(i, include)) @deprecated( """ Using postorder_traversal from the sympy.utilities.iterables submodule is deprecated. Instead, use postorder_traversal from the top-level sympy namespace, like sympy.postorder_traversal """, deprecated_since_version="1.10", active_deprecations_target="deprecated-traversal-functions-moved") def postorder_traversal(node, keys=None): from sympy.core.traversal import postorder_traversal as _postorder_traversal return _postorder_traversal(node, keys=keys) @deprecated( """ Using interactive_traversal from the sympy.utilities.iterables submodule is deprecated. Instead, use interactive_traversal from the top-level sympy namespace, like sympy.interactive_traversal """, deprecated_since_version="1.10", active_deprecations_target="deprecated-traversal-functions-moved") def interactive_traversal(expr): from sympy.interactive.traversal import interactive_traversal as _interactive_traversal return _interactive_traversal(expr) @deprecated( """ Importing default_sort_key from sympy.utilities.iterables is deprecated. Use from sympy import default_sort_key instead. """, deprecated_since_version="1.10", active_deprecations_target="deprecated-sympy-core-compatibility", ) def default_sort_key(*args, **kwargs): from sympy import default_sort_key as _default_sort_key return _default_sort_key(*args, **kwargs) @deprecated( """ Importing default_sort_key from sympy.utilities.iterables is deprecated. Use from sympy import default_sort_key instead. """, deprecated_since_version="1.10", active_deprecations_target="deprecated-sympy-core-compatibility", ) def ordered(*args, **kwargs): from sympy import ordered as _ordered return _ordered(*args, **kwargs)
c0db3f92d7d8c484a2cdbb4974300435e9f3154f0c631d48f24b8d97af96d9b1
"""Miscellaneous stuff that does not really fit anywhere else.""" from __future__ import annotations import operator import sys import os import re as _re import struct from textwrap import fill, dedent class Undecidable(ValueError): # an error to be raised when a decision cannot be made definitively # where a definitive answer is needed pass def filldedent(s, w=70, **kwargs): """ Strips leading and trailing empty lines from a copy of ``s``, then dedents, fills and returns it. Empty line stripping serves to deal with docstrings like this one that start with a newline after the initial triple quote, inserting an empty line at the beginning of the string. Additional keyword arguments will be passed to ``textwrap.fill()``. See Also ======== strlines, rawlines """ return '\n' + fill(dedent(str(s)).strip('\n'), width=w, **kwargs) def strlines(s, c=64, short=False): """Return a cut-and-pastable string that, when printed, is equivalent to the input. The lines will be surrounded by parentheses and no line will be longer than c (default 64) characters. If the line contains newlines characters, the `rawlines` result will be returned. If ``short`` is True (default is False) then if there is one line it will be returned without bounding parentheses. Examples ======== >>> from sympy.utilities.misc import strlines >>> q = 'this is a long string that should be broken into shorter lines' >>> print(strlines(q, 40)) ( 'this is a long string that should be b' 'roken into shorter lines' ) >>> q == ( ... 'this is a long string that should be b' ... 'roken into shorter lines' ... ) True See Also ======== filldedent, rawlines """ if not isinstance(s, str): raise ValueError('expecting string input') if '\n' in s: return rawlines(s) q = '"' if repr(s).startswith('"') else "'" q = (q,)*2 if '\\' in s: # use r-string m = '(\nr%s%%s%s\n)' % q j = '%s\nr%s' % q c -= 3 else: m = '(\n%s%%s%s\n)' % q j = '%s\n%s' % q c -= 2 out = [] while s: out.append(s[:c]) s=s[c:] if short and len(out) == 1: return (m % out[0]).splitlines()[1] # strip bounding (\n...\n) return m % j.join(out) def rawlines(s): """Return a cut-and-pastable string that, when printed, is equivalent to the input. Use this when there is more than one line in the string. The string returned is formatted so it can be indented nicely within tests; in some cases it is wrapped in the dedent function which has to be imported from textwrap. Examples ======== Note: because there are characters in the examples below that need to be escaped because they are themselves within a triple quoted docstring, expressions below look more complicated than they would be if they were printed in an interpreter window. >>> from sympy.utilities.misc import rawlines >>> from sympy import TableForm >>> s = str(TableForm([[1, 10]], headings=(None, ['a', 'bee']))) >>> print(rawlines(s)) ( 'a bee\\n' '-----\\n' '1 10 ' ) >>> print(rawlines('''this ... that''')) dedent('''\\ this that''') >>> print(rawlines('''this ... that ... ''')) dedent('''\\ this that ''') >>> s = \"\"\"this ... is a triple ''' ... \"\"\" >>> print(rawlines(s)) dedent(\"\"\"\\ this is a triple ''' \"\"\") >>> print(rawlines('''this ... that ... ''')) ( 'this\\n' 'that\\n' ' ' ) See Also ======== filldedent, strlines """ lines = s.split('\n') if len(lines) == 1: return repr(lines[0]) triple = ["'''" in s, '"""' in s] if any(li.endswith(' ') for li in lines) or '\\' in s or all(triple): rv = [] # add on the newlines trailing = s.endswith('\n') last = len(lines) - 1 for i, li in enumerate(lines): if i != last or trailing: rv.append(repr(li + '\n')) else: rv.append(repr(li)) return '(\n %s\n)' % '\n '.join(rv) else: rv = '\n '.join(lines) if triple[0]: return 'dedent("""\\\n %s""")' % rv else: return "dedent('''\\\n %s''')" % rv ARCH = str(struct.calcsize('P') * 8) + "-bit" # XXX: PyPy does not support hash randomization HASH_RANDOMIZATION = getattr(sys.flags, 'hash_randomization', False) _debug_tmp: list[str] = [] _debug_iter = 0 def debug_decorator(func): """If SYMPY_DEBUG is True, it will print a nice execution tree with arguments and results of all decorated functions, else do nothing. """ from sympy import SYMPY_DEBUG if not SYMPY_DEBUG: return func def maketree(f, *args, **kw): global _debug_tmp global _debug_iter oldtmp = _debug_tmp _debug_tmp = [] _debug_iter += 1 def tree(subtrees): def indent(s, variant=1): x = s.split("\n") r = "+-%s\n" % x[0] for a in x[1:]: if a == "": continue if variant == 1: r += "| %s\n" % a else: r += " %s\n" % a return r if len(subtrees) == 0: return "" f = [] for a in subtrees[:-1]: f.append(indent(a)) f.append(indent(subtrees[-1], 2)) return ''.join(f) # If there is a bug and the algorithm enters an infinite loop, enable the # following lines. It will print the names and parameters of all major functions # that are called, *before* they are called #from functools import reduce #print("%s%s %s%s" % (_debug_iter, reduce(lambda x, y: x + y, \ # map(lambda x: '-', range(1, 2 + _debug_iter))), f.__name__, args)) r = f(*args, **kw) _debug_iter -= 1 s = "%s%s = %s\n" % (f.__name__, args, r) if _debug_tmp != []: s += tree(_debug_tmp) _debug_tmp = oldtmp _debug_tmp.append(s) if _debug_iter == 0: print(_debug_tmp[0]) _debug_tmp = [] return r def decorated(*args, **kwargs): return maketree(func, *args, **kwargs) return decorated def debug(*args): """ Print ``*args`` if SYMPY_DEBUG is True, else do nothing. """ from sympy import SYMPY_DEBUG if SYMPY_DEBUG: print(*args, file=sys.stderr) def debugf(string, args): """ Print ``string%args`` if SYMPY_DEBUG is True, else do nothing. This is intended for debug messages using formatted strings. """ from sympy import SYMPY_DEBUG if SYMPY_DEBUG: print(string%args, file=sys.stderr) def find_executable(executable, path=None): """Try to find 'executable' in the directories listed in 'path' (a string listing directories separated by 'os.pathsep'; defaults to os.environ['PATH']). Returns the complete filename or None if not found """ from .exceptions import sympy_deprecation_warning sympy_deprecation_warning( """ sympy.utilities.misc.find_executable() is deprecated. Use the standard library shutil.which() function instead. """, deprecated_since_version="1.7", active_deprecations_target="deprecated-find-executable", ) if path is None: path = os.environ['PATH'] paths = path.split(os.pathsep) extlist = [''] if os.name == 'os2': (base, ext) = os.path.splitext(executable) # executable files on OS/2 can have an arbitrary extension, but # .exe is automatically appended if no dot is present in the name if not ext: executable = executable + ".exe" elif sys.platform == 'win32': pathext = os.environ['PATHEXT'].lower().split(os.pathsep) (base, ext) = os.path.splitext(executable) if ext.lower() not in pathext: extlist = pathext for ext in extlist: execname = executable + ext if os.path.isfile(execname): return execname else: for p in paths: f = os.path.join(p, execname) if os.path.isfile(f): return f return None def func_name(x, short=False): """Return function name of `x` (if defined) else the `type(x)`. If short is True and there is a shorter alias for the result, return the alias. Examples ======== >>> from sympy.utilities.misc import func_name >>> from sympy import Matrix >>> from sympy.abc import x >>> func_name(Matrix.eye(3)) 'MutableDenseMatrix' >>> func_name(x < 1) 'StrictLessThan' >>> func_name(x < 1, short=True) 'Lt' """ alias = { 'GreaterThan': 'Ge', 'StrictGreaterThan': 'Gt', 'LessThan': 'Le', 'StrictLessThan': 'Lt', 'Equality': 'Eq', 'Unequality': 'Ne', } typ = type(x) if str(typ).startswith("<type '"): typ = str(typ).split("'")[1].split("'")[0] elif str(typ).startswith("<class '"): typ = str(typ).split("'")[1].split("'")[0] rv = getattr(getattr(x, 'func', x), '__name__', typ) if '.' in rv: rv = rv.split('.')[-1] if short: rv = alias.get(rv, rv) return rv def _replace(reps): """Return a function that can make the replacements, given in ``reps``, on a string. The replacements should be given as mapping. Examples ======== >>> from sympy.utilities.misc import _replace >>> f = _replace(dict(foo='bar', d='t')) >>> f('food') 'bart' >>> f = _replace({}) >>> f('food') 'food' """ if not reps: return lambda x: x D = lambda match: reps[match.group(0)] pattern = _re.compile("|".join( [_re.escape(k) for k, v in reps.items()]), _re.M) return lambda string: pattern.sub(D, string) def replace(string, *reps): """Return ``string`` with all keys in ``reps`` replaced with their corresponding values, longer strings first, irrespective of the order they are given. ``reps`` may be passed as tuples or a single mapping. Examples ======== >>> from sympy.utilities.misc import replace >>> replace('foo', {'oo': 'ar', 'f': 'b'}) 'bar' >>> replace("spamham sha", ("spam", "eggs"), ("sha","md5")) 'eggsham md5' There is no guarantee that a unique answer will be obtained if keys in a mapping overlap (i.e. are the same length and have some identical sequence at the beginning/end): >>> reps = [ ... ('ab', 'x'), ... ('bc', 'y')] >>> replace('abc', *reps) in ('xc', 'ay') True References ========== .. [1] https://stackoverflow.com/questions/6116978/python-replace-multiple-strings """ if len(reps) == 1: kv = reps[0] if isinstance(kv, dict): reps = kv else: return string.replace(*kv) else: reps = dict(reps) return _replace(reps)(string) def translate(s, a, b=None, c=None): """Return ``s`` where characters have been replaced or deleted. SYNTAX ====== translate(s, None, deletechars): all characters in ``deletechars`` are deleted translate(s, map [,deletechars]): all characters in ``deletechars`` (if provided) are deleted then the replacements defined by map are made; if the keys of map are strings then the longer ones are handled first. Multicharacter deletions should have a value of ''. translate(s, oldchars, newchars, deletechars) all characters in ``deletechars`` are deleted then each character in ``oldchars`` is replaced with the corresponding character in ``newchars`` Examples ======== >>> from sympy.utilities.misc import translate >>> abc = 'abc' >>> translate(abc, None, 'a') 'bc' >>> translate(abc, {'a': 'x'}, 'c') 'xb' >>> translate(abc, {'abc': 'x', 'a': 'y'}) 'x' >>> translate('abcd', 'ac', 'AC', 'd') 'AbC' There is no guarantee that a unique answer will be obtained if keys in a mapping overlap are the same length and have some identical sequences at the beginning/end: >>> translate(abc, {'ab': 'x', 'bc': 'y'}) in ('xc', 'ay') True """ mr = {} if a is None: if c is not None: raise ValueError('c should be None when a=None is passed, instead got %s' % c) if b is None: return s c = b a = b = '' else: if isinstance(a, dict): short = {} for k in list(a.keys()): if len(k) == 1 and len(a[k]) == 1: short[k] = a.pop(k) mr = a c = b if short: a, b = [''.join(i) for i in list(zip(*short.items()))] else: a = b = '' elif len(a) != len(b): raise ValueError('oldchars and newchars have different lengths') if c: val = str.maketrans('', '', c) s = s.translate(val) s = replace(s, mr) n = str.maketrans(a, b) return s.translate(n) def ordinal(num): """Return ordinal number string of num, e.g. 1 becomes 1st. """ # modified from https://codereview.stackexchange.com/questions/41298/producing-ordinal-numbers n = as_int(num) k = abs(n) % 100 if 11 <= k <= 13: suffix = 'th' elif k % 10 == 1: suffix = 'st' elif k % 10 == 2: suffix = 'nd' elif k % 10 == 3: suffix = 'rd' else: suffix = 'th' return str(n) + suffix def as_int(n, strict=True): """ Convert the argument to a builtin integer. The return value is guaranteed to be equal to the input. ValueError is raised if the input has a non-integral value. When ``strict`` is True, this uses `__index__ <https://docs.python.org/3/reference/datamodel.html#object.__index__>`_ and when it is False it uses ``int``. Examples ======== >>> from sympy.utilities.misc import as_int >>> from sympy import sqrt, S The function is primarily concerned with sanitizing input for functions that need to work with builtin integers, so anything that is unambiguously an integer should be returned as an int: >>> as_int(S(3)) 3 Floats, being of limited precision, are not assumed to be exact and will raise an error unless the ``strict`` flag is False. This precision issue becomes apparent for large floating point numbers: >>> big = 1e23 >>> type(big) is float True >>> big == int(big) True >>> as_int(big) Traceback (most recent call last): ... ValueError: ... is not an integer >>> as_int(big, strict=False) 99999999999999991611392 Input that might be a complex representation of an integer value is also rejected by default: >>> one = sqrt(3 + 2*sqrt(2)) - sqrt(2) >>> int(one) == 1 True >>> as_int(one) Traceback (most recent call last): ... ValueError: ... is not an integer """ if strict: try: if isinstance(n, bool): raise TypeError return operator.index(n) except TypeError: raise ValueError('%s is not an integer' % (n,)) else: try: result = int(n) except TypeError: raise ValueError('%s is not an integer' % (n,)) if n != result: raise ValueError('%s is not an integer' % (n,)) return result
0470e702998c15bdcf5b7afdf02a32e1940b20d2ce8a735e1c4666818c49e6c7
from sympy.core import S from sympy.core.function import Lambda from sympy.core.power import Pow from .pycode import PythonCodePrinter, _known_functions_math, _print_known_const, _print_known_func, _unpack_integral_limits, ArrayPrinter from .codeprinter import CodePrinter _not_in_numpy = 'erf erfc factorial gamma loggamma'.split() _in_numpy = [(k, v) for k, v in _known_functions_math.items() if k not in _not_in_numpy] _known_functions_numpy = dict(_in_numpy, **{ 'acos': 'arccos', 'acosh': 'arccosh', 'asin': 'arcsin', 'asinh': 'arcsinh', 'atan': 'arctan', 'atan2': 'arctan2', 'atanh': 'arctanh', 'exp2': 'exp2', 'sign': 'sign', 'logaddexp': 'logaddexp', 'logaddexp2': 'logaddexp2', }) _known_constants_numpy = { 'Exp1': 'e', 'Pi': 'pi', 'EulerGamma': 'euler_gamma', 'NaN': 'nan', 'Infinity': 'PINF', 'NegativeInfinity': 'NINF' } _numpy_known_functions = {k: 'numpy.' + v for k, v in _known_functions_numpy.items()} _numpy_known_constants = {k: 'numpy.' + v for k, v in _known_constants_numpy.items()} class NumPyPrinter(ArrayPrinter, PythonCodePrinter): """ Numpy printer which handles vectorized piecewise functions, logical operators, etc. """ _module = 'numpy' _kf = _numpy_known_functions _kc = _numpy_known_constants def __init__(self, settings=None): """ `settings` is passed to CodePrinter.__init__() `module` specifies the array module to use, currently 'NumPy', 'CuPy' or 'JAX'. """ self.language = "Python with {}".format(self._module) self.printmethod = "_{}code".format(self._module) self._kf = {**PythonCodePrinter._kf, **self._kf} super().__init__(settings=settings) def _print_seq(self, seq): "General sequence printer: converts to tuple" # Print tuples here instead of lists because numba supports # tuples in nopython mode. delimiter=', ' return '({},)'.format(delimiter.join(self._print(item) for item in seq)) def _print_MatMul(self, expr): "Matrix multiplication printer" if expr.as_coeff_matrices()[0] is not S.One: expr_list = expr.as_coeff_matrices()[1]+[(expr.as_coeff_matrices()[0])] return '({})'.format(').dot('.join(self._print(i) for i in expr_list)) return '({})'.format(').dot('.join(self._print(i) for i in expr.args)) def _print_MatPow(self, expr): "Matrix power printer" return '{}({}, {})'.format(self._module_format(self._module + '.linalg.matrix_power'), self._print(expr.args[0]), self._print(expr.args[1])) def _print_Inverse(self, expr): "Matrix inverse printer" return '{}({})'.format(self._module_format(self._module + '.linalg.inv'), self._print(expr.args[0])) def _print_DotProduct(self, expr): # DotProduct allows any shape order, but numpy.dot does matrix # multiplication, so we have to make sure it gets 1 x n by n x 1. arg1, arg2 = expr.args if arg1.shape[0] != 1: arg1 = arg1.T if arg2.shape[1] != 1: arg2 = arg2.T return "%s(%s, %s)" % (self._module_format(self._module + '.dot'), self._print(arg1), self._print(arg2)) def _print_MatrixSolve(self, expr): return "%s(%s, %s)" % (self._module_format(self._module + '.linalg.solve'), self._print(expr.matrix), self._print(expr.vector)) def _print_ZeroMatrix(self, expr): return '{}({})'.format(self._module_format(self._module + '.zeros'), self._print(expr.shape)) def _print_OneMatrix(self, expr): return '{}({})'.format(self._module_format(self._module + '.ones'), self._print(expr.shape)) def _print_FunctionMatrix(self, expr): from sympy.abc import i, j lamda = expr.lamda if not isinstance(lamda, Lambda): lamda = Lambda((i, j), lamda(i, j)) return '{}(lambda {}: {}, {})'.format(self._module_format(self._module + '.fromfunction'), ', '.join(self._print(arg) for arg in lamda.args[0]), self._print(lamda.args[1]), self._print(expr.shape)) def _print_HadamardProduct(self, expr): func = self._module_format(self._module + '.multiply') return ''.join('{}({}, '.format(func, self._print(arg)) \ for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]), ')' * (len(expr.args) - 1)) def _print_KroneckerProduct(self, expr): func = self._module_format(self._module + '.kron') return ''.join('{}({}, '.format(func, self._print(arg)) \ for arg in expr.args[:-1]) + "{}{}".format(self._print(expr.args[-1]), ')' * (len(expr.args) - 1)) def _print_Adjoint(self, expr): return '{}({}({}))'.format( self._module_format(self._module + '.conjugate'), self._module_format(self._module + '.transpose'), self._print(expr.args[0])) def _print_DiagonalOf(self, expr): vect = '{}({})'.format( self._module_format(self._module + '.diag'), self._print(expr.arg)) return '{}({}, (-1, 1))'.format( self._module_format(self._module + '.reshape'), vect) def _print_DiagMatrix(self, expr): return '{}({})'.format(self._module_format(self._module + '.diagflat'), self._print(expr.args[0])) def _print_DiagonalMatrix(self, expr): return '{}({}, {}({}, {}))'.format(self._module_format(self._module + '.multiply'), self._print(expr.arg), self._module_format(self._module + '.eye'), self._print(expr.shape[0]), self._print(expr.shape[1])) def _print_Piecewise(self, expr): "Piecewise function printer" from sympy.logic.boolalg import ITE, simplify_logic def print_cond(cond): """ Problem having an ITE in the cond. """ if cond.has(ITE): return self._print(simplify_logic(cond)) else: return self._print(cond) exprs = '[{}]'.format(','.join(self._print(arg.expr) for arg in expr.args)) conds = '[{}]'.format(','.join(print_cond(arg.cond) for arg in expr.args)) # If [default_value, True] is a (expr, cond) sequence in a Piecewise object # it will behave the same as passing the 'default' kwarg to select() # *as long as* it is the last element in expr.args. # If this is not the case, it may be triggered prematurely. return '{}({}, {}, default={})'.format( self._module_format(self._module + '.select'), conds, exprs, self._print(S.NaN)) def _print_Relational(self, expr): "Relational printer for Equality and Unequality" op = { '==' :'equal', '!=' :'not_equal', '<' :'less', '<=' :'less_equal', '>' :'greater', '>=' :'greater_equal', } if expr.rel_op in op: lhs = self._print(expr.lhs) rhs = self._print(expr.rhs) return '{op}({lhs}, {rhs})'.format(op=self._module_format(self._module + '.'+op[expr.rel_op]), lhs=lhs, rhs=rhs) return super()._print_Relational(expr) def _print_And(self, expr): "Logical And printer" # We have to override LambdaPrinter because it uses Python 'and' keyword. # If LambdaPrinter didn't define it, we could use StrPrinter's # version of the function and add 'logical_and' to NUMPY_TRANSLATIONS. return '{}.reduce(({}))'.format(self._module_format(self._module + '.logical_and'), ','.join(self._print(i) for i in expr.args)) def _print_Or(self, expr): "Logical Or printer" # We have to override LambdaPrinter because it uses Python 'or' keyword. # If LambdaPrinter didn't define it, we could use StrPrinter's # version of the function and add 'logical_or' to NUMPY_TRANSLATIONS. return '{}.reduce(({}))'.format(self._module_format(self._module + '.logical_or'), ','.join(self._print(i) for i in expr.args)) def _print_Not(self, expr): "Logical Not printer" # We have to override LambdaPrinter because it uses Python 'not' keyword. # If LambdaPrinter didn't define it, we would still have to define our # own because StrPrinter doesn't define it. return '{}({})'.format(self._module_format(self._module + '.logical_not'), ','.join(self._print(i) for i in expr.args)) def _print_Pow(self, expr, rational=False): # XXX Workaround for negative integer power error if expr.exp.is_integer and expr.exp.is_negative: expr = Pow(expr.base, expr.exp.evalf(), evaluate=False) return self._hprint_Pow(expr, rational=rational, sqrt=self._module + '.sqrt') def _print_Min(self, expr): return '{}(({}), axis=0)'.format(self._module_format(self._module + '.amin'), ','.join(self._print(i) for i in expr.args)) def _print_Max(self, expr): return '{}(({}), axis=0)'.format(self._module_format(self._module + '.amax'), ','.join(self._print(i) for i in expr.args)) def _print_arg(self, expr): return "%s(%s)" % (self._module_format(self._module + '.angle'), self._print(expr.args[0])) def _print_im(self, expr): return "%s(%s)" % (self._module_format(self._module + '.imag'), self._print(expr.args[0])) def _print_Mod(self, expr): return "%s(%s)" % (self._module_format(self._module + '.mod'), ', '.join( map(lambda arg: self._print(arg), expr.args))) def _print_re(self, expr): return "%s(%s)" % (self._module_format(self._module + '.real'), self._print(expr.args[0])) def _print_sinc(self, expr): return "%s(%s)" % (self._module_format(self._module + '.sinc'), self._print(expr.args[0]/S.Pi)) def _print_MatrixBase(self, expr): func = self.known_functions.get(expr.__class__.__name__, None) if func is None: func = self._module_format(self._module + '.array') return "%s(%s)" % (func, self._print(expr.tolist())) def _print_Identity(self, expr): shape = expr.shape if all(dim.is_Integer for dim in shape): return "%s(%s)" % (self._module_format(self._module + '.eye'), self._print(expr.shape[0])) else: raise NotImplementedError("Symbolic matrix dimensions are not yet supported for identity matrices") def _print_BlockMatrix(self, expr): return '{}({})'.format(self._module_format(self._module + '.block'), self._print(expr.args[0].tolist())) def _print_NDimArray(self, expr): if len(expr.shape) == 1: return self._module + '.array(' + self._print(expr.args[0]) + ')' if len(expr.shape) == 2: return self._print(expr.tomatrix()) # Should be possible to extend to more dimensions return CodePrinter._print_not_supported(self, expr) _add = "add" _einsum = "einsum" _transpose = "transpose" _ones = "ones" _zeros = "zeros" _print_lowergamma = CodePrinter._print_not_supported _print_uppergamma = CodePrinter._print_not_supported _print_fresnelc = CodePrinter._print_not_supported _print_fresnels = CodePrinter._print_not_supported for func in _numpy_known_functions: setattr(NumPyPrinter, f'_print_{func}', _print_known_func) for const in _numpy_known_constants: setattr(NumPyPrinter, f'_print_{const}', _print_known_const) _known_functions_scipy_special = { 'Ei': 'expi', 'erf': 'erf', 'erfc': 'erfc', 'besselj': 'jv', 'bessely': 'yv', 'besseli': 'iv', 'besselk': 'kv', 'cosm1': 'cosm1', 'powm1': 'powm1', 'factorial': 'factorial', 'gamma': 'gamma', 'loggamma': 'gammaln', 'digamma': 'psi', 'polygamma': 'polygamma', 'RisingFactorial': 'poch', 'jacobi': 'eval_jacobi', 'gegenbauer': 'eval_gegenbauer', 'chebyshevt': 'eval_chebyt', 'chebyshevu': 'eval_chebyu', 'legendre': 'eval_legendre', 'hermite': 'eval_hermite', 'laguerre': 'eval_laguerre', 'assoc_laguerre': 'eval_genlaguerre', 'beta': 'beta', 'LambertW' : 'lambertw', } _known_constants_scipy_constants = { 'GoldenRatio': 'golden_ratio', 'Pi': 'pi', } _scipy_known_functions = {k : "scipy.special." + v for k, v in _known_functions_scipy_special.items()} _scipy_known_constants = {k : "scipy.constants." + v for k, v in _known_constants_scipy_constants.items()} class SciPyPrinter(NumPyPrinter): _kf = {**NumPyPrinter._kf, **_scipy_known_functions} _kc = {**NumPyPrinter._kc, **_scipy_known_constants} def __init__(self, settings=None): super().__init__(settings=settings) self.language = "Python with SciPy and NumPy" def _print_SparseRepMatrix(self, expr): i, j, data = [], [], [] for (r, c), v in expr.todok().items(): i.append(r) j.append(c) data.append(v) return "{name}(({data}, ({i}, {j})), shape={shape})".format( name=self._module_format('scipy.sparse.coo_matrix'), data=data, i=i, j=j, shape=expr.shape ) _print_ImmutableSparseMatrix = _print_SparseRepMatrix # SciPy's lpmv has a different order of arguments from assoc_legendre def _print_assoc_legendre(self, expr): return "{0}({2}, {1}, {3})".format( self._module_format('scipy.special.lpmv'), self._print(expr.args[0]), self._print(expr.args[1]), self._print(expr.args[2])) def _print_lowergamma(self, expr): return "{0}({2})*{1}({2}, {3})".format( self._module_format('scipy.special.gamma'), self._module_format('scipy.special.gammainc'), self._print(expr.args[0]), self._print(expr.args[1])) def _print_uppergamma(self, expr): return "{0}({2})*{1}({2}, {3})".format( self._module_format('scipy.special.gamma'), self._module_format('scipy.special.gammaincc'), self._print(expr.args[0]), self._print(expr.args[1])) def _print_betainc(self, expr): betainc = self._module_format('scipy.special.betainc') beta = self._module_format('scipy.special.beta') args = [self._print(arg) for arg in expr.args] return f"({betainc}({args[0]}, {args[1]}, {args[3]}) - {betainc}({args[0]}, {args[1]}, {args[2]})) \ * {beta}({args[0]}, {args[1]})" def _print_betainc_regularized(self, expr): return "{0}({1}, {2}, {4}) - {0}({1}, {2}, {3})".format( self._module_format('scipy.special.betainc'), self._print(expr.args[0]), self._print(expr.args[1]), self._print(expr.args[2]), self._print(expr.args[3])) def _print_fresnels(self, expr): return "{}({})[0]".format( self._module_format("scipy.special.fresnel"), self._print(expr.args[0])) def _print_fresnelc(self, expr): return "{}({})[1]".format( self._module_format("scipy.special.fresnel"), self._print(expr.args[0])) def _print_airyai(self, expr): return "{}({})[0]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_airyaiprime(self, expr): return "{}({})[1]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_airybi(self, expr): return "{}({})[2]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_airybiprime(self, expr): return "{}({})[3]".format( self._module_format("scipy.special.airy"), self._print(expr.args[0])) def _print_bernoulli(self, expr): # scipy's bernoulli is inconsistent with SymPy's so rewrite return self._print(expr._eval_rewrite_as_zeta(*expr.args)) def _print_harmonic(self, expr): return self._print(expr._eval_rewrite_as_zeta(*expr.args)) def _print_Integral(self, e): integration_vars, limits = _unpack_integral_limits(e) if len(limits) == 1: # nicer (but not necessary) to prefer quad over nquad for 1D case module_str = self._module_format("scipy.integrate.quad") limit_str = "%s, %s" % tuple(map(self._print, limits[0])) else: module_str = self._module_format("scipy.integrate.nquad") limit_str = "({})".format(", ".join( "(%s, %s)" % tuple(map(self._print, l)) for l in limits)) return "{}(lambda {}: {}, {})[0]".format( module_str, ", ".join(map(self._print, integration_vars)), self._print(e.args[0]), limit_str) def _print_Si(self, expr): return "{}({})[0]".format( self._module_format("scipy.special.sici"), self._print(expr.args[0])) def _print_Ci(self, expr): return "{}({})[1]".format( self._module_format("scipy.special.sici"), self._print(expr.args[0])) for func in _scipy_known_functions: setattr(SciPyPrinter, f'_print_{func}', _print_known_func) for const in _scipy_known_constants: setattr(SciPyPrinter, f'_print_{const}', _print_known_const) _cupy_known_functions = {k : "cupy." + v for k, v in _known_functions_numpy.items()} _cupy_known_constants = {k : "cupy." + v for k, v in _known_constants_numpy.items()} class CuPyPrinter(NumPyPrinter): """ CuPy printer which handles vectorized piecewise functions, logical operators, etc. """ _module = 'cupy' _kf = _cupy_known_functions _kc = _cupy_known_constants def __init__(self, settings=None): super().__init__(settings=settings) for func in _cupy_known_functions: setattr(CuPyPrinter, f'_print_{func}', _print_known_func) for const in _cupy_known_constants: setattr(CuPyPrinter, f'_print_{const}', _print_known_const) _jax_known_functions = {k: 'jax.numpy.' + v for k, v in _known_functions_numpy.items()} _jax_known_constants = {k: 'jax.numpy.' + v for k, v in _known_constants_numpy.items()} class JaxPrinter(NumPyPrinter): """ JAX printer which handles vectorized piecewise functions, logical operators, etc. """ _module = "jax.numpy" _kf = _jax_known_functions _kc = _jax_known_constants def __init__(self, settings=None): super().__init__(settings=settings) # These need specific override to allow for the lack of "jax.numpy.reduce" def _print_And(self, expr): "Logical And printer" return "{}({}.asarray([{}]), axis=0)".format( self._module_format(self._module + ".all"), self._module_format(self._module), ",".join(self._print(i) for i in expr.args), ) def _print_Or(self, expr): "Logical Or printer" return "{}({}.asarray([{}]), axis=0)".format( self._module_format(self._module + ".any"), self._module_format(self._module), ",".join(self._print(i) for i in expr.args), ) for func in _jax_known_functions: setattr(JaxPrinter, f'_print_{func}', _print_known_func) for const in _jax_known_constants: setattr(JaxPrinter, f'_print_{const}', _print_known_const)
383f71601a1393ec91861b5b09ac7271e83596c9c2694725a7f3565b8b9a3586
""" Rust code printer The `RustCodePrinter` converts SymPy expressions into Rust expressions. A complete code generator, which uses `rust_code` extensively, can be found in `sympy.utilities.codegen`. The `codegen` module can be used to generate complete source code files. """ # Possible Improvement # # * make sure we follow Rust Style Guidelines_ # * make use of pattern matching # * better support for reference # * generate generic code and use trait to make sure they have specific methods # * use crates_ to get more math support # - num_ # + BigInt_, BigUint_ # + Complex_ # + Rational64_, Rational32_, BigRational_ # # .. _crates: https://crates.io/ # .. _Guidelines: https://github.com/rust-lang/rust/tree/master/src/doc/style # .. _num: http://rust-num.github.io/num/num/ # .. _BigInt: http://rust-num.github.io/num/num/bigint/struct.BigInt.html # .. _BigUint: http://rust-num.github.io/num/num/bigint/struct.BigUint.html # .. _Complex: http://rust-num.github.io/num/num/complex/struct.Complex.html # .. _Rational32: http://rust-num.github.io/num/num/rational/type.Rational32.html # .. _Rational64: http://rust-num.github.io/num/num/rational/type.Rational64.html # .. _BigRational: http://rust-num.github.io/num/num/rational/type.BigRational.html from __future__ import annotations from typing import Any from sympy.core import S, Rational, Float, Lambda from sympy.core.numbers import equal_valued from sympy.printing.codeprinter import CodePrinter # Rust's methods for integer and float can be found at here : # # * `Rust - Primitive Type f64 <https://doc.rust-lang.org/std/primitive.f64.html>`_ # * `Rust - Primitive Type i64 <https://doc.rust-lang.org/std/primitive.i64.html>`_ # # Function Style : # # 1. args[0].func(args[1:]), method with arguments # 2. args[0].func(), method without arguments # 3. args[1].func(), method without arguments (e.g. (e, x) => x.exp()) # 4. func(args), function with arguments # dictionary mapping SymPy function to (argument_conditions, Rust_function). # Used in RustCodePrinter._print_Function(self) # f64 method in Rust known_functions = { # "": "is_nan", # "": "is_infinite", # "": "is_finite", # "": "is_normal", # "": "classify", "floor": "floor", "ceiling": "ceil", # "": "round", # "": "trunc", # "": "fract", "Abs": "abs", "sign": "signum", # "": "is_sign_positive", # "": "is_sign_negative", # "": "mul_add", "Pow": [(lambda base, exp: equal_valued(exp, -1), "recip", 2), # 1.0/x (lambda base, exp: equal_valued(exp, 0.5), "sqrt", 2), # x ** 0.5 (lambda base, exp: equal_valued(exp, -0.5), "sqrt().recip", 2), # 1/(x ** 0.5) (lambda base, exp: exp == Rational(1, 3), "cbrt", 2), # x ** (1/3) (lambda base, exp: equal_valued(base, 2), "exp2", 3), # 2 ** x (lambda base, exp: exp.is_integer, "powi", 1), # x ** y, for i32 (lambda base, exp: not exp.is_integer, "powf", 1)], # x ** y, for f64 "exp": [(lambda exp: True, "exp", 2)], # e ** x "log": "ln", # "": "log", # number.log(base) # "": "log2", # "": "log10", # "": "to_degrees", # "": "to_radians", "Max": "max", "Min": "min", # "": "hypot", # (x**2 + y**2) ** 0.5 "sin": "sin", "cos": "cos", "tan": "tan", "asin": "asin", "acos": "acos", "atan": "atan", "atan2": "atan2", # "": "sin_cos", # "": "exp_m1", # e ** x - 1 # "": "ln_1p", # ln(1 + x) "sinh": "sinh", "cosh": "cosh", "tanh": "tanh", "asinh": "asinh", "acosh": "acosh", "atanh": "atanh", "sqrt": "sqrt", # To enable automatic rewrites } # i64 method in Rust # known_functions_i64 = { # "": "min_value", # "": "max_value", # "": "from_str_radix", # "": "count_ones", # "": "count_zeros", # "": "leading_zeros", # "": "trainling_zeros", # "": "rotate_left", # "": "rotate_right", # "": "swap_bytes", # "": "from_be", # "": "from_le", # "": "to_be", # to big endian # "": "to_le", # to little endian # "": "checked_add", # "": "checked_sub", # "": "checked_mul", # "": "checked_div", # "": "checked_rem", # "": "checked_neg", # "": "checked_shl", # "": "checked_shr", # "": "checked_abs", # "": "saturating_add", # "": "saturating_sub", # "": "saturating_mul", # "": "wrapping_add", # "": "wrapping_sub", # "": "wrapping_mul", # "": "wrapping_div", # "": "wrapping_rem", # "": "wrapping_neg", # "": "wrapping_shl", # "": "wrapping_shr", # "": "wrapping_abs", # "": "overflowing_add", # "": "overflowing_sub", # "": "overflowing_mul", # "": "overflowing_div", # "": "overflowing_rem", # "": "overflowing_neg", # "": "overflowing_shl", # "": "overflowing_shr", # "": "overflowing_abs", # "Pow": "pow", # "Abs": "abs", # "sign": "signum", # "": "is_positive", # "": "is_negnative", # } # These are the core reserved words in the Rust language. Taken from: # http://doc.rust-lang.org/grammar.html#keywords reserved_words = ['abstract', 'alignof', 'as', 'become', 'box', 'break', 'const', 'continue', 'crate', 'do', 'else', 'enum', 'extern', 'false', 'final', 'fn', 'for', 'if', 'impl', 'in', 'let', 'loop', 'macro', 'match', 'mod', 'move', 'mut', 'offsetof', 'override', 'priv', 'proc', 'pub', 'pure', 'ref', 'return', 'Self', 'self', 'sizeof', 'static', 'struct', 'super', 'trait', 'true', 'type', 'typeof', 'unsafe', 'unsized', 'use', 'virtual', 'where', 'while', 'yield'] class RustCodePrinter(CodePrinter): """A printer to convert SymPy expressions to strings of Rust code""" printmethod = "_rust_code" language = "Rust" _default_settings: dict[str, Any] = { 'order': None, 'full_prec': 'auto', 'precision': 17, 'user_functions': {}, 'human': True, 'contract': True, 'dereference': set(), 'error_on_reserved': False, 'reserved_word_suffix': '_', 'inline': False, } def __init__(self, settings={}): CodePrinter.__init__(self, settings) self.known_functions = dict(known_functions) userfuncs = settings.get('user_functions', {}) self.known_functions.update(userfuncs) self._dereference = set(settings.get('dereference', [])) self.reserved_words = set(reserved_words) def _rate_index_position(self, p): return p*5 def _get_statement(self, codestring): return "%s;" % codestring def _get_comment(self, text): return "// %s" % text def _declare_number_const(self, name, value): return "const %s: f64 = %s;" % (name, value) def _format_code(self, lines): return self.indent_code(lines) def _traverse_matrix_indices(self, mat): rows, cols = mat.shape return ((i, j) for i in range(rows) for j in range(cols)) def _get_loop_opening_ending(self, indices): open_lines = [] close_lines = [] loopstart = "for %(var)s in %(start)s..%(end)s {" for i in indices: # Rust arrays start at 0 and end at dimension-1 open_lines.append(loopstart % { 'var': self._print(i), 'start': self._print(i.lower), 'end': self._print(i.upper + 1)}) close_lines.append("}") return open_lines, close_lines def _print_caller_var(self, expr): if len(expr.args) > 1: # for something like `sin(x + y + z)`, # make sure we can get '(x + y + z).sin()' # instead of 'x + y + z.sin()' return '(' + self._print(expr) + ')' elif expr.is_number: return self._print(expr, _type=True) else: return self._print(expr) def _print_Function(self, expr): """ basic function for printing `Function` Function Style : 1. args[0].func(args[1:]), method with arguments 2. args[0].func(), method without arguments 3. args[1].func(), method without arguments (e.g. (e, x) => x.exp()) 4. func(args), function with arguments """ if expr.func.__name__ in self.known_functions: cond_func = self.known_functions[expr.func.__name__] func = None style = 1 if isinstance(cond_func, str): func = cond_func else: for cond, func, style in cond_func: if cond(*expr.args): break if func is not None: if style == 1: ret = "%(var)s.%(method)s(%(args)s)" % { 'var': self._print_caller_var(expr.args[0]), 'method': func, 'args': self.stringify(expr.args[1:], ", ") if len(expr.args) > 1 else '' } elif style == 2: ret = "%(var)s.%(method)s()" % { 'var': self._print_caller_var(expr.args[0]), 'method': func, } elif style == 3: ret = "%(var)s.%(method)s()" % { 'var': self._print_caller_var(expr.args[1]), 'method': func, } else: ret = "%(func)s(%(args)s)" % { 'func': func, 'args': self.stringify(expr.args, ", "), } return ret elif hasattr(expr, '_imp_') and isinstance(expr._imp_, Lambda): # inlined function return self._print(expr._imp_(*expr.args)) elif expr.func.__name__ in self._rewriteable_functions: # Simple rewrite to supported function possible target_f, required_fs = self._rewriteable_functions[expr.func.__name__] if self._can_print(target_f) and all(self._can_print(f) for f in required_fs): return self._print(expr.rewrite(target_f)) else: return self._print_not_supported(expr) def _print_Pow(self, expr): if expr.base.is_integer and not expr.exp.is_integer: expr = type(expr)(Float(expr.base), expr.exp) return self._print(expr) return self._print_Function(expr) def _print_Float(self, expr, _type=False): ret = super()._print_Float(expr) if _type: return ret + '_f64' else: return ret def _print_Integer(self, expr, _type=False): ret = super()._print_Integer(expr) if _type: return ret + '_i32' else: return ret def _print_Rational(self, expr): p, q = int(expr.p), int(expr.q) return '%d_f64/%d.0' % (p, q) def _print_Relational(self, expr): lhs_code = self._print(expr.lhs) rhs_code = self._print(expr.rhs) op = expr.rel_op return "{} {} {}".format(lhs_code, op, rhs_code) def _print_Indexed(self, expr): # calculate index for 1d array dims = expr.shape elem = S.Zero offset = S.One for i in reversed(range(expr.rank)): elem += expr.indices[i]*offset offset *= dims[i] return "%s[%s]" % (self._print(expr.base.label), self._print(elem)) def _print_Idx(self, expr): return expr.label.name def _print_Dummy(self, expr): return expr.name def _print_Exp1(self, expr, _type=False): return "E" def _print_Pi(self, expr, _type=False): return 'PI' def _print_Infinity(self, expr, _type=False): return 'INFINITY' def _print_NegativeInfinity(self, expr, _type=False): return 'NEG_INFINITY' def _print_BooleanTrue(self, expr, _type=False): return "true" def _print_BooleanFalse(self, expr, _type=False): return "false" def _print_bool(self, expr, _type=False): return str(expr).lower() def _print_NaN(self, expr, _type=False): return "NAN" def _print_Piecewise(self, expr): if expr.args[-1].cond != True: # We need the last conditional to be a True, otherwise the resulting # function may not return a result. raise ValueError("All Piecewise expressions must contain an " "(expr, True) statement to be used as a default " "condition. Without one, the generated " "expression may not evaluate to anything under " "some condition.") lines = [] for i, (e, c) in enumerate(expr.args): if i == 0: lines.append("if (%s) {" % self._print(c)) elif i == len(expr.args) - 1 and c == True: lines[-1] += " else {" else: lines[-1] += " else if (%s) {" % self._print(c) code0 = self._print(e) lines.append(code0) lines.append("}") if self._settings['inline']: return " ".join(lines) else: return "\n".join(lines) def _print_ITE(self, expr): from sympy.functions import Piecewise return self._print(expr.rewrite(Piecewise, deep=False)) def _print_MatrixBase(self, A): if A.cols == 1: return "[%s]" % ", ".join(self._print(a) for a in A) else: raise ValueError("Full Matrix Support in Rust need Crates (https://crates.io/keywords/matrix).") def _print_SparseRepMatrix(self, mat): # do not allow sparse matrices to be made dense return self._print_not_supported(mat) def _print_MatrixElement(self, expr): return "%s[%s]" % (expr.parent, expr.j + expr.i*expr.parent.shape[1]) def _print_Symbol(self, expr): name = super()._print_Symbol(expr) if expr in self._dereference: return '(*%s)' % name else: return name def _print_Assignment(self, expr): from sympy.tensor.indexed import IndexedBase lhs = expr.lhs rhs = expr.rhs if self._settings["contract"] and (lhs.has(IndexedBase) or rhs.has(IndexedBase)): # Here we check if there is looping to be done, and if so # print the required loops. return self._doprint_loops(rhs, lhs) else: lhs_code = self._print(lhs) rhs_code = self._print(rhs) return self._get_statement("%s = %s" % (lhs_code, rhs_code)) def indent_code(self, code): """Accepts a string of code or a list of code lines""" if isinstance(code, str): code_lines = self.indent_code(code.splitlines(True)) return ''.join(code_lines) tab = " " inc_token = ('{', '(', '{\n', '(\n') dec_token = ('}', ')') code = [ line.lstrip(' \t') for line in code ] increase = [ int(any(map(line.endswith, inc_token))) for line in code ] decrease = [ int(any(map(line.startswith, dec_token))) for line in code ] pretty = [] level = 0 for n, line in enumerate(code): if line in ('', '\n'): pretty.append(line) continue level -= decrease[n] pretty.append("%s%s" % (tab*level, line)) level += increase[n] return pretty def rust_code(expr, assign_to=None, **settings): """Converts an expr to a string of Rust code Parameters ========== expr : Expr A SymPy expression to be converted. assign_to : optional When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, ``Symbol``, ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of line-wrapping, or for expressions that generate multi-line statements. precision : integer, optional The precision for numbers such as pi [default=15]. user_functions : dict, optional A dictionary where the keys are string representations of either ``FunctionClass`` or ``UndefinedFunction`` instances and the values are their desired C string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples. dereference : iterable, optional An iterable of symbols that should be dereferenced in the printed code expression. These would be values passed by address to the function. For example, if ``dereference=[a]``, the resulting code would print ``(*a)`` instead of ``a``. human : bool, optional If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True]. contract: bool, optional If True, ``Indexed`` instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True]. Examples ======== >>> from sympy import rust_code, symbols, Rational, sin, ceiling, Abs, Function >>> x, tau = symbols("x, tau") >>> rust_code((2*tau)**Rational(7, 2)) '8*1.4142135623731*tau.powf(7_f64/2.0)' >>> rust_code(sin(x), assign_to="s") 's = x.sin();' Simple custom printing can be defined for certain types by passing a dictionary of {"type" : "function"} to the ``user_functions`` kwarg. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. >>> custom_functions = { ... "ceiling": "CEIL", ... "Abs": [(lambda x: not x.is_integer, "fabs", 4), ... (lambda x: x.is_integer, "ABS", 4)], ... "func": "f" ... } >>> func = Function('func') >>> rust_code(func(Abs(x) + ceiling(x)), user_functions=custom_functions) '(fabs(x) + x.CEIL()).f()' ``Piecewise`` expressions are converted into conditionals. If an ``assign_to`` variable is provided an if statement is created, otherwise the ternary operator is used. Note that if the ``Piecewise`` lacks a default term, represented by ``(expr, True)`` then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything. >>> from sympy import Piecewise >>> expr = Piecewise((x + 1, x > 0), (x, True)) >>> print(rust_code(expr, tau)) tau = if (x > 0) { x + 1 } else { x }; Support for loops is provided through ``Indexed`` types. With ``contract=True`` these expressions will be turned into loops, whereas ``contract=False`` will just print the assignment expression that should be looped over: >>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', 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])/(t[i+1]-t[i])) >>> rust_code(e.rhs, assign_to=e.lhs, contract=False) 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);' Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions must be provided to ``assign_to``. Note that any expression that can be generated normally can also exist inside a Matrix: >>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) >>> A = MatrixSymbol('A', 3, 1) >>> print(rust_code(mat, A)) A = [x.powi(2), if (x > 0) { x + 1 } else { x }, x.sin()]; """ return RustCodePrinter(settings).doprint(expr, assign_to) def print_rust_code(expr, **settings): """Prints Rust representation of the given expression.""" print(rust_code(expr, **settings))
751e8474602cc9458a44a8405828968799a3c9ea0c1cfb46c9e0f6d96d55feec
"""Printing subsystem driver SymPy's printing system works the following way: Any expression can be passed to a designated Printer who then is responsible to return an adequate representation of that expression. **The basic concept is the following:** 1. Let the object print itself if it knows how. 2. Take the best fitting method defined in the printer. 3. As fall-back use the emptyPrinter method for the printer. Which Method is Responsible for Printing? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The whole printing process is started by calling ``.doprint(expr)`` on the printer which you want to use. This method looks for an appropriate method which can print the given expression in the given style that the printer defines. While looking for the method, it follows these steps: 1. **Let the object print itself if it knows how.** The printer looks for a specific method in every object. The name of that method depends on the specific printer and is defined under ``Printer.printmethod``. For example, StrPrinter calls ``_sympystr`` and LatexPrinter calls ``_latex``. Look at the documentation of the printer that you want to use. The name of the method is specified there. This was the original way of doing printing in sympy. Every class had its own latex, mathml, str and repr methods, but it turned out that it is hard to produce a high quality printer, if all the methods are spread out that far. Therefore all printing code was combined into the different printers, which works great for built-in SymPy objects, but not that good for user defined classes where it is inconvenient to patch the printers. 2. **Take the best fitting method defined in the printer.** The printer loops through expr classes (class + its bases), and tries to dispatch the work to ``_print_<EXPR_CLASS>`` e.g., suppose we have the following class hierarchy:: Basic | Atom | Number | Rational then, for ``expr=Rational(...)``, the Printer will try to call printer methods in the order as shown in the figure below:: p._print(expr) | |-- p._print_Rational(expr) | |-- p._print_Number(expr) | |-- p._print_Atom(expr) | `-- p._print_Basic(expr) if ``._print_Rational`` method exists in the printer, then it is called, and the result is returned back. Otherwise, the printer tries to call ``._print_Number`` and so on. 3. **As a fall-back use the emptyPrinter method for the printer.** As fall-back ``self.emptyPrinter`` will be called with the expression. If not defined in the Printer subclass this will be the same as ``str(expr)``. .. _printer_example: Example of Custom Printer ^^^^^^^^^^^^^^^^^^^^^^^^^ In the example below, we have a printer which prints the derivative of a function in a shorter form. .. code-block:: python from sympy.core.symbol import Symbol from sympy.printing.latex import LatexPrinter, print_latex from sympy.core.function import UndefinedFunction, Function class MyLatexPrinter(LatexPrinter): \"\"\"Print derivative of a function of symbols in a shorter form. \"\"\" def _print_Derivative(self, expr): function, *vars = expr.args if not isinstance(type(function), UndefinedFunction) or \\ not all(isinstance(i, Symbol) for i in vars): return super()._print_Derivative(expr) # If you want the printer to work correctly for nested # expressions then use self._print() instead of str() or latex(). # See the example of nested modulo below in the custom printing # method section. return "{}_{{{}}}".format( self._print(Symbol(function.func.__name__)), ''.join(self._print(i) for i in vars)) def print_my_latex(expr): \"\"\" Most of the printers define their own wrappers for print(). These wrappers usually take printer settings. Our printer does not have any settings. \"\"\" print(MyLatexPrinter().doprint(expr)) y = Symbol("y") x = Symbol("x") f = Function("f") expr = f(x, y).diff(x, y) # Print the expression using the normal latex printer and our custom # printer. print_latex(expr) print_my_latex(expr) The output of the code above is:: \\frac{\\partial^{2}}{\\partial x\\partial y} f{\\left(x,y \\right)} f_{xy} .. _printer_method_example: Example of Custom Printing Method ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ In the example below, the latex printing of the modulo operator is modified. This is done by overriding the method ``_latex`` of ``Mod``. >>> from sympy import Symbol, Mod, Integer, print_latex >>> # Always use printer._print() >>> class ModOp(Mod): ... def _latex(self, printer): ... a, b = [printer._print(i) for i in self.args] ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b) Comparing the output of our custom operator to the builtin one: >>> x = Symbol('x') >>> m = Symbol('m') >>> print_latex(Mod(x, m)) x \\bmod m >>> print_latex(ModOp(x, m)) \\operatorname{Mod}{\\left(x, m\\right)} Common mistakes ~~~~~~~~~~~~~~~ It's important to always use ``self._print(obj)`` to print subcomponents of an expression when customizing a printer. Mistakes include: 1. Using ``self.doprint(obj)`` instead: >>> # This example does not work properly, as only the outermost call may use >>> # doprint. >>> class ModOpModeWrong(Mod): ... def _latex(self, printer): ... a, b = [printer.doprint(i) for i in self.args] ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b) This fails when the ``mode`` argument is passed to the printer: >>> print_latex(ModOp(x, m), mode='inline') # ok $\\operatorname{Mod}{\\left(x, m\\right)}$ >>> print_latex(ModOpModeWrong(x, m), mode='inline') # bad $\\operatorname{Mod}{\\left($x$, $m$\\right)}$ 2. Using ``str(obj)`` instead: >>> class ModOpNestedWrong(Mod): ... def _latex(self, printer): ... a, b = [str(i) for i in self.args] ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b) This fails on nested objects: >>> # Nested modulo. >>> print_latex(ModOp(ModOp(x, m), Integer(7))) # ok \\operatorname{Mod}{\\left(\\operatorname{Mod}{\\left(x, m\\right)}, 7\\right)} >>> print_latex(ModOpNestedWrong(ModOpNestedWrong(x, m), Integer(7))) # bad \\operatorname{Mod}{\\left(ModOpNestedWrong(x, m), 7\\right)} 3. Using ``LatexPrinter()._print(obj)`` instead. >>> from sympy.printing.latex import LatexPrinter >>> class ModOpSettingsWrong(Mod): ... def _latex(self, printer): ... a, b = [LatexPrinter()._print(i) for i in self.args] ... return r"\\operatorname{Mod}{\\left(%s, %s\\right)}" % (a, b) This causes all the settings to be discarded in the subobjects. As an example, the ``full_prec`` setting which shows floats to full precision is ignored: >>> from sympy import Float >>> print_latex(ModOp(Float(1) * x, m), full_prec=True) # ok \\operatorname{Mod}{\\left(1.00000000000000 x, m\\right)} >>> print_latex(ModOpSettingsWrong(Float(1) * x, m), full_prec=True) # bad \\operatorname{Mod}{\\left(1.0 x, m\\right)} """ from __future__ import annotations import sys from typing import Any, Type import inspect from contextlib import contextmanager from functools import cmp_to_key, update_wrapper from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.function import AppliedUndef, UndefinedFunction, Function @contextmanager def printer_context(printer, **kwargs): original = printer._context.copy() try: printer._context.update(kwargs) yield finally: printer._context = original class Printer: """ Generic printer Its job is to provide infrastructure for implementing new printers easily. If you want to define your custom Printer or your custom printing method for your custom class then see the example above: printer_example_ . """ _global_settings: dict[str, Any] = {} _default_settings: 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 = {} # 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) -> str: """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): if not (isinstance(expr, type) and issubclass(expr, Basic)): return getattr(expr, self.printmethod)(self, **kwargs) # See if the class of expr is known, or if one of its super # classes is known, and use that print function # Exception: ignore the subclasses of Undefined, so that, e.g., # Function('gamma') does not get dispatched to _print_gamma classes = type(expr).__mro__ if AppliedUndef in classes: classes = classes[classes.index(AppliedUndef):] if UndefinedFunction in classes: classes = classes[classes.index(UndefinedFunction):] # Another exception: if someone subclasses a known function, e.g., # gamma, and changes the name, then ignore _print_gamma if Function in classes: i = classes.index(Function) classes = tuple(c for c in classes[:i] if \ c.__name__ == classes[0].__name__ or \ c.__name__.endswith("Base")) + classes[i:] for cls in classes: printmethodname = '_print_' + cls.__name__ printmethod = getattr(self, printmethodname, None) if printmethod is not None: return printmethod(expr, **kwargs) # Unknown object, fall back to the emptyPrinter. return self.emptyPrinter(expr) finally: self._print_level -= 1 def emptyPrinter(self, expr): return str(expr) def _as_ordered_terms(self, expr, order=None): """A compatibility function for ordering terms in Add. """ order = order or self.order if order == 'old': return sorted(Add.make_args(expr), key=cmp_to_key(Basic._compare_pretty)) elif order == 'none': return list(expr.args) else: return expr.as_ordered_terms(order=order) class _PrintFunction: """ Function wrapper to replace ``**settings`` in the signature with printer defaults """ def __init__(self, f, print_cls: Type[Printer]): # find all the non-setting arguments params = list(inspect.signature(f).parameters.values()) assert params.pop(-1).kind == inspect.Parameter.VAR_KEYWORD self.__other_params = params self.__print_cls = print_cls update_wrapper(self, f) def __reduce__(self): # Since this is used as a decorator, it replaces the original function. # The default pickling will try to pickle self.__wrapped__ and fail # because the wrapped function can't be retrieved by name. return self.__wrapped__.__qualname__ def __call__(self, *args, **kwargs): return self.__wrapped__(*args, **kwargs) @property def __signature__(self) -> inspect.Signature: settings = self.__print_cls._get_initial_settings() return inspect.Signature( parameters=self.__other_params + [ inspect.Parameter(k, inspect.Parameter.KEYWORD_ONLY, default=v) for k, v in settings.items() ], return_annotation=self.__wrapped__.__annotations__.get('return', inspect.Signature.empty) # type:ignore ) def print_function(print_cls): """ A decorator to replace kwargs with the printer settings in __signature__ """ def decorator(f): if sys.version_info < (3, 9): # We have to create a subclass so that `help` actually shows the docstring in older Python versions. # IPython and Sphinx do not need this, only a raw Python console. cls = type(f'{f.__qualname__}_PrintFunction', (_PrintFunction,), dict(__doc__=f.__doc__)) else: cls = _PrintFunction return cls(f, print_cls) return decorator
bcc0052da0d614767602ea09e7bc41f9aaefbf26aa7ec0c380f255cf94bff499
""" C code printer The C89CodePrinter & C99CodePrinter converts single SymPy expressions into single C expressions, using the functions defined in math.h where possible. A complete code generator, which uses ccode extensively, can be found in sympy.utilities.codegen. The codegen module can be used to generate complete source code files that are compilable without further modifications. """ from __future__ import annotations from typing import Any from functools import wraps from itertools import chain from sympy.core import S from sympy.core.numbers import equal_valued from sympy.codegen.ast import ( Assignment, Pointer, Variable, Declaration, Type, real, complex_, integer, bool_, float32, float64, float80, complex64, complex128, intc, value_const, pointer_const, int8, int16, int32, int64, uint8, uint16, uint32, uint64, untyped, none ) from sympy.printing.codeprinter import CodePrinter, requires from sympy.printing.precedence import precedence, PRECEDENCE from sympy.sets.fancysets import Range # These are defined in the other file so we can avoid importing sympy.codegen # from the top-level 'import sympy'. Export them here as well. from sympy.printing.codeprinter import ccode, print_ccode # noqa:F401 # dictionary mapping SymPy function to (argument_conditions, C_function). # Used in C89CodePrinter._print_Function(self) known_functions_C89 = { "Abs": [(lambda x: not x.is_integer, "fabs"), (lambda x: x.is_integer, "abs")], "sin": "sin", "cos": "cos", "tan": "tan", "asin": "asin", "acos": "acos", "atan": "atan", "atan2": "atan2", "exp": "exp", "log": "log", "sinh": "sinh", "cosh": "cosh", "tanh": "tanh", "floor": "floor", "ceiling": "ceil", "sqrt": "sqrt", # To enable automatic rewrites } known_functions_C99 = dict(known_functions_C89, **{ 'exp2': 'exp2', 'expm1': 'expm1', 'log10': 'log10', 'log2': 'log2', 'log1p': 'log1p', 'Cbrt': 'cbrt', 'hypot': 'hypot', 'fma': 'fma', 'loggamma': 'lgamma', 'erfc': 'erfc', 'Max': 'fmax', 'Min': 'fmin', "asinh": "asinh", "acosh": "acosh", "atanh": "atanh", "erf": "erf", "gamma": "tgamma", }) # These are the core reserved words in the C language. Taken from: # http://en.cppreference.com/w/c/keyword reserved_words = [ 'auto', 'break', 'case', 'char', 'const', 'continue', 'default', 'do', 'double', 'else', 'enum', 'extern', 'float', 'for', 'goto', 'if', 'int', 'long', 'register', 'return', 'short', 'signed', 'sizeof', 'static', 'struct', 'entry', # never standardized, we'll leave it here anyway 'switch', 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while' ] reserved_words_c99 = ['inline', 'restrict'] def get_math_macros(): """ Returns a dictionary with math-related macros from math.h/cmath Note that these macros are not strictly required by the C/C++-standard. For MSVC they are enabled by defining "_USE_MATH_DEFINES" (preferably via a compilation flag). Returns ======= Dictionary mapping SymPy expressions to strings (macro names) """ from sympy.codegen.cfunctions import log2, Sqrt from sympy.functions.elementary.exponential import log from sympy.functions.elementary.miscellaneous import sqrt return { S.Exp1: 'M_E', log2(S.Exp1): 'M_LOG2E', 1/log(2): 'M_LOG2E', log(2): 'M_LN2', log(10): 'M_LN10', S.Pi: 'M_PI', S.Pi/2: 'M_PI_2', S.Pi/4: 'M_PI_4', 1/S.Pi: 'M_1_PI', 2/S.Pi: 'M_2_PI', 2/sqrt(S.Pi): 'M_2_SQRTPI', 2/Sqrt(S.Pi): 'M_2_SQRTPI', sqrt(2): 'M_SQRT2', Sqrt(2): 'M_SQRT2', 1/sqrt(2): 'M_SQRT1_2', 1/Sqrt(2): 'M_SQRT1_2' } def _as_macro_if_defined(meth): """ Decorator for printer methods When a Printer's method is decorated using this decorator the expressions printed will first be looked for in the attribute ``math_macros``, and if present it will print the macro name in ``math_macros`` followed by a type suffix for the type ``real``. e.g. printing ``sympy.pi`` would print ``M_PIl`` if real is mapped to float80. """ @wraps(meth) def _meth_wrapper(self, expr, **kwargs): if expr in self.math_macros: return '%s%s' % (self.math_macros[expr], self._get_math_macro_suffix(real)) else: return meth(self, expr, **kwargs) return _meth_wrapper class C89CodePrinter(CodePrinter): """A printer to convert Python expressions to strings of C code""" printmethod = "_ccode" language = "C" standard = "C89" reserved_words = set(reserved_words) _default_settings: dict[str, Any] = { 'order': None, 'full_prec': 'auto', 'precision': 17, 'user_functions': {}, 'human': True, 'allow_unknown_functions': False, 'contract': True, 'dereference': set(), 'error_on_reserved': False, 'reserved_word_suffix': '_', } type_aliases = { real: float64, complex_: complex128, integer: intc } type_mappings: dict[Type, Any] = { real: 'double', intc: 'int', float32: 'float', float64: 'double', integer: 'int', bool_: 'bool', int8: 'int8_t', int16: 'int16_t', int32: 'int32_t', int64: 'int64_t', uint8: 'int8_t', uint16: 'int16_t', uint32: 'int32_t', uint64: 'int64_t', } type_headers = { bool_: {'stdbool.h'}, int8: {'stdint.h'}, int16: {'stdint.h'}, int32: {'stdint.h'}, int64: {'stdint.h'}, uint8: {'stdint.h'}, uint16: {'stdint.h'}, uint32: {'stdint.h'}, uint64: {'stdint.h'}, } # Macros needed to be defined when using a Type type_macros: dict[Type, tuple[str, ...]] = {} type_func_suffixes = { float32: 'f', float64: '', float80: 'l' } type_literal_suffixes = { float32: 'F', float64: '', float80: 'L' } type_math_macro_suffixes = { float80: 'l' } math_macros = None _ns = '' # namespace, C++ uses 'std::' # known_functions-dict to copy _kf: dict[str, Any] = known_functions_C89 def __init__(self, settings=None): settings = settings or {} if self.math_macros is None: self.math_macros = settings.pop('math_macros', get_math_macros()) self.type_aliases = dict(chain(self.type_aliases.items(), settings.pop('type_aliases', {}).items())) self.type_mappings = dict(chain(self.type_mappings.items(), settings.pop('type_mappings', {}).items())) self.type_headers = dict(chain(self.type_headers.items(), settings.pop('type_headers', {}).items())) self.type_macros = dict(chain(self.type_macros.items(), settings.pop('type_macros', {}).items())) self.type_func_suffixes = dict(chain(self.type_func_suffixes.items(), settings.pop('type_func_suffixes', {}).items())) self.type_literal_suffixes = dict(chain(self.type_literal_suffixes.items(), settings.pop('type_literal_suffixes', {}).items())) self.type_math_macro_suffixes = dict(chain(self.type_math_macro_suffixes.items(), settings.pop('type_math_macro_suffixes', {}).items())) super().__init__(settings) self.known_functions = dict(self._kf, **settings.get('user_functions', {})) self._dereference = set(settings.get('dereference', [])) self.headers = set() self.libraries = set() self.macros = set() def _rate_index_position(self, p): return p*5 def _get_statement(self, codestring): """ Get code string as a statement - i.e. ending with a semicolon. """ return codestring if codestring.endswith(';') else codestring + ';' def _get_comment(self, text): return "/* {} */".format(text) def _declare_number_const(self, name, value): type_ = self.type_aliases[real] var = Variable(name, type=type_, value=value.evalf(type_.decimal_dig), attrs={value_const}) decl = Declaration(var) return self._get_statement(self._print(decl)) def _format_code(self, lines): return self.indent_code(lines) def _traverse_matrix_indices(self, mat): rows, cols = mat.shape return ((i, j) for i in range(rows) for j in range(cols)) @_as_macro_if_defined def _print_Mul(self, expr, **kwargs): return super()._print_Mul(expr, **kwargs) @_as_macro_if_defined def _print_Pow(self, expr): if "Pow" in self.known_functions: return self._print_Function(expr) PREC = precedence(expr) suffix = self._get_func_suffix(real) if equal_valued(expr.exp, -1): literal_suffix = self._get_literal_suffix(real) return '1.0%s/%s' % (literal_suffix, self.parenthesize(expr.base, PREC)) elif equal_valued(expr.exp, 0.5): return '%ssqrt%s(%s)' % (self._ns, suffix, self._print(expr.base)) elif expr.exp == S.One/3 and self.standard != 'C89': return '%scbrt%s(%s)' % (self._ns, suffix, self._print(expr.base)) else: return '%spow%s(%s, %s)' % (self._ns, suffix, self._print(expr.base), self._print(expr.exp)) def _print_Mod(self, expr): num, den = expr.args if num.is_integer and den.is_integer: PREC = precedence(expr) snum, sden = [self.parenthesize(arg, PREC) for arg in expr.args] # % is remainder (same sign as numerator), not modulo (same sign as # denominator), in C. Hence, % only works as modulo if both numbers # have the same sign if (num.is_nonnegative and den.is_nonnegative or num.is_nonpositive and den.is_nonpositive): return f"{snum} % {sden}" return f"(({snum} % {sden}) + {sden}) % {sden}" # Not guaranteed integer return self._print_math_func(expr, known='fmod') def _print_Rational(self, expr): p, q = int(expr.p), int(expr.q) suffix = self._get_literal_suffix(real) return '%d.0%s/%d.0%s' % (p, suffix, q, suffix) def _print_Indexed(self, expr): # calculate index for 1d array offset = getattr(expr.base, 'offset', S.Zero) strides = getattr(expr.base, 'strides', None) indices = expr.indices if strides is None or isinstance(strides, str): dims = expr.shape shift = S.One temp = tuple() if strides == 'C' or strides is None: traversal = reversed(range(expr.rank)) indices = indices[::-1] elif strides == 'F': traversal = range(expr.rank) for i in traversal: temp += (shift,) shift *= dims[i] strides = temp flat_index = sum([x[0]*x[1] for x in zip(indices, strides)]) + offset return "%s[%s]" % (self._print(expr.base.label), self._print(flat_index)) def _print_Idx(self, expr): return self._print(expr.label) @_as_macro_if_defined def _print_NumberSymbol(self, expr): return super()._print_NumberSymbol(expr) def _print_Infinity(self, expr): return 'HUGE_VAL' def _print_NegativeInfinity(self, expr): return '-HUGE_VAL' def _print_Piecewise(self, expr): if expr.args[-1].cond != True: # We need the last conditional to be a True, otherwise the resulting # function may not return a result. raise ValueError("All Piecewise expressions must contain an " "(expr, True) statement to be used as a default " "condition. Without one, the generated " "expression may not evaluate to anything under " "some condition.") lines = [] if expr.has(Assignment): for i, (e, c) in enumerate(expr.args): if i == 0: lines.append("if (%s) {" % self._print(c)) elif i == len(expr.args) - 1 and c == True: lines.append("else {") else: lines.append("else if (%s) {" % self._print(c)) code0 = self._print(e) lines.append(code0) lines.append("}") return "\n".join(lines) else: # The piecewise was used in an expression, need to do inline # operators. This has the downside that inline operators will # not work for statements that span multiple lines (Matrix or # Indexed expressions). ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c), self._print(e)) for e, c in expr.args[:-1]] last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr) return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)]) def _print_ITE(self, expr): from sympy.functions import Piecewise return self._print(expr.rewrite(Piecewise, deep=False)) def _print_MatrixElement(self, expr): return "{}[{}]".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True), expr.j + expr.i*expr.parent.shape[1]) def _print_Symbol(self, expr): name = super()._print_Symbol(expr) if expr in self._settings['dereference']: return '(*{})'.format(name) else: return name def _print_Relational(self, expr): lhs_code = self._print(expr.lhs) rhs_code = self._print(expr.rhs) op = expr.rel_op return "{} {} {}".format(lhs_code, op, rhs_code) def _print_For(self, expr): target = self._print(expr.target) if isinstance(expr.iterable, Range): start, stop, step = expr.iterable.args else: raise NotImplementedError("Only iterable currently supported is Range") body = self._print(expr.body) return ('for ({target} = {start}; {target} < {stop}; {target} += ' '{step}) {{\n{body}\n}}').format(target=target, start=start, stop=stop, step=step, body=body) def _print_sign(self, func): return '((({0}) > 0) - (({0}) < 0))'.format(self._print(func.args[0])) def _print_Max(self, expr): if "Max" in self.known_functions: return self._print_Function(expr) def inner_print_max(args): # The more natural abstraction of creating if len(args) == 1: # and printing smaller Max objects is slow return self._print(args[0]) # when there are many arguments. half = len(args) // 2 return "((%(a)s > %(b)s) ? %(a)s : %(b)s)" % { 'a': inner_print_max(args[:half]), 'b': inner_print_max(args[half:]) } return inner_print_max(expr.args) def _print_Min(self, expr): if "Min" in self.known_functions: return self._print_Function(expr) def inner_print_min(args): # The more natural abstraction of creating if len(args) == 1: # and printing smaller Min objects is slow return self._print(args[0]) # when there are many arguments. half = len(args) // 2 return "((%(a)s < %(b)s) ? %(a)s : %(b)s)" % { 'a': inner_print_min(args[:half]), 'b': inner_print_min(args[half:]) } return inner_print_min(expr.args) def indent_code(self, code): """Accepts a string of code or a list of code lines""" if isinstance(code, str): code_lines = self.indent_code(code.splitlines(True)) return ''.join(code_lines) tab = " " inc_token = ('{', '(', '{\n', '(\n') dec_token = ('}', ')') code = [line.lstrip(' \t') for line in code] increase = [int(any(map(line.endswith, inc_token))) for line in code] decrease = [int(any(map(line.startswith, dec_token))) for line in code] pretty = [] level = 0 for n, line in enumerate(code): if line in ('', '\n'): pretty.append(line) continue level -= decrease[n] pretty.append("%s%s" % (tab*level, line)) level += increase[n] return pretty def _get_func_suffix(self, type_): return self.type_func_suffixes[self.type_aliases.get(type_, type_)] def _get_literal_suffix(self, type_): return self.type_literal_suffixes[self.type_aliases.get(type_, type_)] def _get_math_macro_suffix(self, type_): alias = self.type_aliases.get(type_, type_) dflt = self.type_math_macro_suffixes.get(alias, '') return self.type_math_macro_suffixes.get(type_, dflt) def _print_Tuple(self, expr): return '{'+', '.join(self._print(e) for e in expr)+'}' _print_List = _print_Tuple def _print_Type(self, type_): self.headers.update(self.type_headers.get(type_, set())) self.macros.update(self.type_macros.get(type_, set())) return self._print(self.type_mappings.get(type_, type_.name)) def _print_Declaration(self, decl): from sympy.codegen.cnodes import restrict var = decl.variable val = var.value if var.type == untyped: raise ValueError("C does not support untyped variables") if isinstance(var, Pointer): result = '{vc}{t} *{pc} {r}{s}'.format( vc='const ' if value_const in var.attrs else '', t=self._print(var.type), pc=' const' if pointer_const in var.attrs else '', r='restrict ' if restrict in var.attrs else '', s=self._print(var.symbol) ) elif isinstance(var, Variable): result = '{vc}{t} {s}'.format( vc='const ' if value_const in var.attrs else '', t=self._print(var.type), s=self._print(var.symbol) ) else: raise NotImplementedError("Unknown type of var: %s" % type(var)) if val != None: # Must be "!= None", cannot be "is not None" result += ' = %s' % self._print(val) return result def _print_Float(self, flt): type_ = self.type_aliases.get(real, real) self.macros.update(self.type_macros.get(type_, set())) suffix = self._get_literal_suffix(type_) num = str(flt.evalf(type_.decimal_dig)) if 'e' not in num and '.' not in num: num += '.0' num_parts = num.split('e') num_parts[0] = num_parts[0].rstrip('0') if num_parts[0].endswith('.'): num_parts[0] += '0' return 'e'.join(num_parts) + suffix @requires(headers={'stdbool.h'}) def _print_BooleanTrue(self, expr): return 'true' @requires(headers={'stdbool.h'}) def _print_BooleanFalse(self, expr): return 'false' def _print_Element(self, elem): if elem.strides == None: # Must be "== None", cannot be "is None" if elem.offset != None: # Must be "!= None", cannot be "is not None" raise ValueError("Expected strides when offset is given") idxs = ']['.join(map(lambda arg: self._print(arg), elem.indices)) else: global_idx = sum([i*s for i, s in zip(elem.indices, elem.strides)]) if elem.offset != None: # Must be "!= None", cannot be "is not None" global_idx += elem.offset idxs = self._print(global_idx) return "{symb}[{idxs}]".format( symb=self._print(elem.symbol), idxs=idxs ) def _print_CodeBlock(self, expr): """ Elements of code blocks printed as statements. """ return '\n'.join([self._get_statement(self._print(i)) for i in expr.args]) def _print_While(self, expr): return 'while ({condition}) {{\n{body}\n}}'.format(**expr.kwargs( apply=lambda arg: self._print(arg))) def _print_Scope(self, expr): return '{\n%s\n}' % self._print_CodeBlock(expr.body) @requires(headers={'stdio.h'}) def _print_Print(self, expr): return 'printf({fmt}, {pargs})'.format( fmt=self._print(expr.format_string), pargs=', '.join(map(lambda arg: self._print(arg), expr.print_args)) ) def _print_FunctionPrototype(self, expr): pars = ', '.join(map(lambda arg: self._print(Declaration(arg)), expr.parameters)) return "%s %s(%s)" % ( tuple(map(lambda arg: self._print(arg), (expr.return_type, expr.name))) + (pars,) ) def _print_FunctionDefinition(self, expr): return "%s%s" % (self._print_FunctionPrototype(expr), self._print_Scope(expr)) def _print_Return(self, expr): arg, = expr.args return 'return %s' % self._print(arg) def _print_CommaOperator(self, expr): return '(%s)' % ', '.join(map(lambda arg: self._print(arg), expr.args)) def _print_Label(self, expr): if expr.body == none: return '%s:' % str(expr.name) if len(expr.body.args) == 1: return '%s:\n%s' % (str(expr.name), self._print_CodeBlock(expr.body)) return '%s:\n{\n%s\n}' % (str(expr.name), self._print_CodeBlock(expr.body)) def _print_goto(self, expr): return 'goto %s' % expr.label.name def _print_PreIncrement(self, expr): arg, = expr.args return '++(%s)' % self._print(arg) def _print_PostIncrement(self, expr): arg, = expr.args return '(%s)++' % self._print(arg) def _print_PreDecrement(self, expr): arg, = expr.args return '--(%s)' % self._print(arg) def _print_PostDecrement(self, expr): arg, = expr.args return '(%s)--' % self._print(arg) def _print_struct(self, expr): return "%(keyword)s %(name)s {\n%(lines)s}" % dict( keyword=expr.__class__.__name__, name=expr.name, lines=';\n'.join( [self._print(decl) for decl in expr.declarations] + ['']) ) def _print_BreakToken(self, _): return 'break' def _print_ContinueToken(self, _): return 'continue' _print_union = _print_struct class C99CodePrinter(C89CodePrinter): standard = 'C99' reserved_words = set(reserved_words + reserved_words_c99) type_mappings=dict(chain(C89CodePrinter.type_mappings.items(), { complex64: 'float complex', complex128: 'double complex', }.items())) type_headers = dict(chain(C89CodePrinter.type_headers.items(), { complex64: {'complex.h'}, complex128: {'complex.h'} }.items())) # known_functions-dict to copy _kf: dict[str, Any] = known_functions_C99 # functions with versions with 'f' and 'l' suffixes: _prec_funcs = ('fabs fmod remainder remquo fma fmax fmin fdim nan exp exp2' ' expm1 log log10 log2 log1p pow sqrt cbrt hypot sin cos tan' ' asin acos atan atan2 sinh cosh tanh asinh acosh atanh erf' ' erfc tgamma lgamma ceil floor trunc round nearbyint rint' ' frexp ldexp modf scalbn ilogb logb nextafter copysign').split() def _print_Infinity(self, expr): return 'INFINITY' def _print_NegativeInfinity(self, expr): return '-INFINITY' def _print_NaN(self, expr): return 'NAN' # tgamma was already covered by 'known_functions' dict @requires(headers={'math.h'}, libraries={'m'}) @_as_macro_if_defined def _print_math_func(self, expr, nest=False, known=None): if known is None: known = self.known_functions[expr.__class__.__name__] if not isinstance(known, str): for cb, name in known: if cb(*expr.args): known = name break else: raise ValueError("No matching printer") try: return known(self, *expr.args) except TypeError: suffix = self._get_func_suffix(real) if self._ns + known in self._prec_funcs else '' if nest: args = self._print(expr.args[0]) if len(expr.args) > 1: paren_pile = '' for curr_arg in expr.args[1:-1]: paren_pile += ')' args += ', {ns}{name}{suffix}({next}'.format( ns=self._ns, name=known, suffix=suffix, next = self._print(curr_arg) ) args += ', %s%s' % ( self._print(expr.func(expr.args[-1])), paren_pile ) else: args = ', '.join(map(lambda arg: self._print(arg), expr.args)) return '{ns}{name}{suffix}({args})'.format( ns=self._ns, name=known, suffix=suffix, args=args ) def _print_Max(self, expr): return self._print_math_func(expr, nest=True) def _print_Min(self, expr): return self._print_math_func(expr, nest=True) def _get_loop_opening_ending(self, indices): open_lines = [] close_lines = [] loopstart = "for (int %(var)s=%(start)s; %(var)s<%(end)s; %(var)s++){" # C99 for i in indices: # C arrays start at 0 and end at dimension-1 open_lines.append(loopstart % { 'var': self._print(i.label), 'start': self._print(i.lower), 'end': self._print(i.upper + 1)}) close_lines.append("}") return open_lines, close_lines for k in ('Abs Sqrt exp exp2 expm1 log log10 log2 log1p Cbrt hypot fma' ' loggamma sin cos tan asin acos atan atan2 sinh cosh tanh asinh acosh ' 'atanh erf erfc loggamma gamma ceiling floor').split(): setattr(C99CodePrinter, '_print_%s' % k, C99CodePrinter._print_math_func) class C11CodePrinter(C99CodePrinter): @requires(headers={'stdalign.h'}) def _print_alignof(self, expr): arg, = expr.args return 'alignof(%s)' % self._print(arg) c_code_printers = { 'c89': C89CodePrinter, 'c99': C99CodePrinter, 'c11': C11CodePrinter }
c8590e7776befc850b21646454539af05b1fc75e908b06bbc67fde614d30840d
""" Fortran code printer The FCodePrinter converts single SymPy expressions into single Fortran expressions, using the functions defined in the Fortran 77 standard where possible. Some useful pointers to Fortran can be found on wikipedia: https://en.wikipedia.org/wiki/Fortran Most of the code below is based on the "Professional Programmer\'s Guide to Fortran77" by Clive G. Page: http://www.star.le.ac.uk/~cgp/prof77.html Fortran is a case-insensitive language. This might cause trouble because SymPy is case sensitive. So, fcode adds underscores to variable names when it is necessary to make them different for Fortran. """ from __future__ import annotations from typing import Any from collections import defaultdict from itertools import chain import string from sympy.codegen.ast import ( Assignment, Declaration, Pointer, value_const, float32, float64, float80, complex64, complex128, int8, int16, int32, int64, intc, real, integer, bool_, complex_ ) from sympy.codegen.fnodes import ( allocatable, isign, dsign, cmplx, merge, literal_dp, elemental, pure, intent_in, intent_out, intent_inout ) from sympy.core import S, Add, N, Float, Symbol from sympy.core.function import Function from sympy.core.numbers import equal_valued from sympy.core.relational import Eq from sympy.sets import Range from sympy.printing.codeprinter import CodePrinter from sympy.printing.precedence import precedence, PRECEDENCE from sympy.printing.printer import printer_context # These are defined in the other file so we can avoid importing sympy.codegen # from the top-level 'import sympy'. Export them here as well. from sympy.printing.codeprinter import fcode, print_fcode # noqa:F401 known_functions = { "sin": "sin", "cos": "cos", "tan": "tan", "asin": "asin", "acos": "acos", "atan": "atan", "atan2": "atan2", "sinh": "sinh", "cosh": "cosh", "tanh": "tanh", "log": "log", "exp": "exp", "erf": "erf", "Abs": "abs", "conjugate": "conjg", "Max": "max", "Min": "min", } class FCodePrinter(CodePrinter): """A printer to convert SymPy expressions to strings of Fortran code""" printmethod = "_fcode" language = "Fortran" type_aliases = { integer: int32, real: float64, complex_: complex128, } type_mappings = { intc: 'integer(c_int)', float32: 'real*4', # real(kind(0.e0)) float64: 'real*8', # real(kind(0.d0)) float80: 'real*10', # real(kind(????)) complex64: 'complex*8', complex128: 'complex*16', int8: 'integer*1', int16: 'integer*2', int32: 'integer*4', int64: 'integer*8', bool_: 'logical' } type_modules = { intc: {'iso_c_binding': 'c_int'} } _default_settings: dict[str, Any] = { 'order': None, 'full_prec': 'auto', 'precision': 17, 'user_functions': {}, 'human': True, 'allow_unknown_functions': False, 'source_format': 'fixed', 'contract': True, 'standard': 77, 'name_mangling': True, } _operators = { 'and': '.and.', 'or': '.or.', 'xor': '.neqv.', 'equivalent': '.eqv.', 'not': '.not. ', } _relationals = { '!=': '/=', } def __init__(self, settings=None): if not settings: settings = {} self.mangled_symbols = {} # Dict showing mapping of all words self.used_name = [] self.type_aliases = dict(chain(self.type_aliases.items(), settings.pop('type_aliases', {}).items())) self.type_mappings = dict(chain(self.type_mappings.items(), settings.pop('type_mappings', {}).items())) super().__init__(settings) self.known_functions = dict(known_functions) userfuncs = settings.get('user_functions', {}) self.known_functions.update(userfuncs) # leading columns depend on fixed or free format standards = {66, 77, 90, 95, 2003, 2008} if self._settings['standard'] not in standards: raise ValueError("Unknown Fortran standard: %s" % self._settings[ 'standard']) self.module_uses = defaultdict(set) # e.g.: use iso_c_binding, only: c_int @property def _lead(self): if self._settings['source_format'] == 'fixed': return {'code': " ", 'cont': " @ ", 'comment': "C "} elif self._settings['source_format'] == 'free': return {'code': "", 'cont': " ", 'comment': "! "} else: raise ValueError("Unknown source format: %s" % self._settings['source_format']) def _print_Symbol(self, expr): if self._settings['name_mangling'] == True: if expr not in self.mangled_symbols: name = expr.name while name.lower() in self.used_name: name += '_' self.used_name.append(name.lower()) if name == expr.name: self.mangled_symbols[expr] = expr else: self.mangled_symbols[expr] = Symbol(name) expr = expr.xreplace(self.mangled_symbols) name = super()._print_Symbol(expr) return name def _rate_index_position(self, p): return -p*5 def _get_statement(self, codestring): return codestring def _get_comment(self, text): return "! {}".format(text) def _declare_number_const(self, name, value): return "parameter ({} = {})".format(name, self._print(value)) def _print_NumberSymbol(self, expr): # A Number symbol that is not implemented here or with _printmethod # is registered and evaluated self._number_symbols.add((expr, Float(expr.evalf(self._settings['precision'])))) return str(expr) def _format_code(self, lines): return self._wrap_fortran(self.indent_code(lines)) def _traverse_matrix_indices(self, mat): rows, cols = mat.shape return ((i, j) for j in range(cols) for i in range(rows)) def _get_loop_opening_ending(self, indices): open_lines = [] close_lines = [] for i in indices: # fortran arrays start at 1 and end at dimension var, start, stop = map(self._print, [i.label, i.lower + 1, i.upper + 1]) open_lines.append("do %s = %s, %s" % (var, start, stop)) close_lines.append("end do") return open_lines, close_lines def _print_sign(self, expr): from sympy.functions.elementary.complexes import Abs arg, = expr.args if arg.is_integer: new_expr = merge(0, isign(1, arg), Eq(arg, 0)) elif (arg.is_complex or arg.is_infinite): new_expr = merge(cmplx(literal_dp(0), literal_dp(0)), arg/Abs(arg), Eq(Abs(arg), literal_dp(0))) else: new_expr = merge(literal_dp(0), dsign(literal_dp(1), arg), Eq(arg, literal_dp(0))) return self._print(new_expr) def _print_Piecewise(self, expr): if expr.args[-1].cond != True: # We need the last conditional to be a True, otherwise the resulting # function may not return a result. raise ValueError("All Piecewise expressions must contain an " "(expr, True) statement to be used as a default " "condition. Without one, the generated " "expression may not evaluate to anything under " "some condition.") lines = [] if expr.has(Assignment): for i, (e, c) in enumerate(expr.args): if i == 0: lines.append("if (%s) then" % self._print(c)) elif i == len(expr.args) - 1 and c == True: lines.append("else") else: lines.append("else if (%s) then" % self._print(c)) lines.append(self._print(e)) lines.append("end if") return "\n".join(lines) elif self._settings["standard"] >= 95: # Only supported in F95 and newer: # The piecewise was used in an expression, need to do inline # operators. This has the downside that inline operators will # not work for statements that span multiple lines (Matrix or # Indexed expressions). pattern = "merge({T}, {F}, {COND})" code = self._print(expr.args[-1].expr) terms = list(expr.args[:-1]) while terms: e, c = terms.pop() expr = self._print(e) cond = self._print(c) code = pattern.format(T=expr, F=code, COND=cond) return code else: # `merge` is not supported prior to F95 raise NotImplementedError("Using Piecewise as an expression using " "inline operators is not supported in " "standards earlier than Fortran95.") def _print_MatrixElement(self, expr): return "{}({}, {})".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True), expr.i + 1, expr.j + 1) def _print_Add(self, expr): # purpose: print complex numbers nicely in Fortran. # collect the purely real and purely imaginary parts: pure_real = [] pure_imaginary = [] mixed = [] for arg in expr.args: if arg.is_number and arg.is_real: pure_real.append(arg) elif arg.is_number and arg.is_imaginary: pure_imaginary.append(arg) else: mixed.append(arg) if pure_imaginary: if mixed: PREC = precedence(expr) term = Add(*mixed) t = self._print(term) if t.startswith('-'): sign = "-" t = t[1:] else: sign = "+" if precedence(term) < PREC: t = "(%s)" % t return "cmplx(%s,%s) %s %s" % ( self._print(Add(*pure_real)), self._print(-S.ImaginaryUnit*Add(*pure_imaginary)), sign, t, ) else: return "cmplx(%s,%s)" % ( self._print(Add(*pure_real)), self._print(-S.ImaginaryUnit*Add(*pure_imaginary)), ) else: return CodePrinter._print_Add(self, expr) def _print_Function(self, expr): # All constant function args are evaluated as floats prec = self._settings['precision'] args = [N(a, prec) for a in expr.args] eval_expr = expr.func(*args) if not isinstance(eval_expr, Function): return self._print(eval_expr) else: return CodePrinter._print_Function(self, expr.func(*args)) def _print_Mod(self, expr): # NOTE : Fortran has the functions mod() and modulo(). modulo() behaves # the same wrt to the sign of the arguments as Python and SymPy's # modulus computations (% and Mod()) but is not available in Fortran 66 # or Fortran 77, thus we raise an error. if self._settings['standard'] in [66, 77]: msg = ("Python % operator and SymPy's Mod() function are not " "supported by Fortran 66 or 77 standards.") raise NotImplementedError(msg) else: x, y = expr.args return " modulo({}, {})".format(self._print(x), self._print(y)) def _print_ImaginaryUnit(self, expr): # purpose: print complex numbers nicely in Fortran. return "cmplx(0,1)" def _print_int(self, expr): return str(expr) def _print_Mul(self, expr): # purpose: print complex numbers nicely in Fortran. if expr.is_number and expr.is_imaginary: return "cmplx(0,%s)" % ( self._print(-S.ImaginaryUnit*expr) ) else: return CodePrinter._print_Mul(self, expr) def _print_Pow(self, expr): PREC = precedence(expr) if equal_valued(expr.exp, -1): return '%s/%s' % ( self._print(literal_dp(1)), self.parenthesize(expr.base, PREC) ) elif equal_valued(expr.exp, 0.5): if expr.base.is_integer: # Fortran intrinsic sqrt() does not accept integer argument if expr.base.is_Number: return 'sqrt(%s.0d0)' % self._print(expr.base) else: return 'sqrt(dble(%s))' % self._print(expr.base) else: return 'sqrt(%s)' % self._print(expr.base) else: return CodePrinter._print_Pow(self, expr) def _print_Rational(self, expr): p, q = int(expr.p), int(expr.q) return "%d.0d0/%d.0d0" % (p, q) def _print_Float(self, expr): printed = CodePrinter._print_Float(self, expr) e = printed.find('e') if e > -1: return "%sd%s" % (printed[:e], printed[e + 1:]) return "%sd0" % printed def _print_Relational(self, expr): lhs_code = self._print(expr.lhs) rhs_code = self._print(expr.rhs) op = expr.rel_op op = op if op not in self._relationals else self._relationals[op] return "{} {} {}".format(lhs_code, op, rhs_code) def _print_Indexed(self, expr): inds = [ self._print(i) for i in expr.indices ] return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds)) def _print_Idx(self, expr): return self._print(expr.label) def _print_AugmentedAssignment(self, expr): lhs_code = self._print(expr.lhs) rhs_code = self._print(expr.rhs) return self._get_statement("{0} = {0} {1} {2}".format( *map(lambda arg: self._print(arg), [lhs_code, expr.binop, rhs_code]))) def _print_sum_(self, sm): params = self._print(sm.array) if sm.dim != None: # Must use '!= None', cannot use 'is not None' params += ', ' + self._print(sm.dim) if sm.mask != None: # Must use '!= None', cannot use 'is not None' params += ', mask=' + self._print(sm.mask) return '%s(%s)' % (sm.__class__.__name__.rstrip('_'), params) def _print_product_(self, prod): return self._print_sum_(prod) def _print_Do(self, do): excl = ['concurrent'] if do.step == 1: excl.append('step') step = '' else: step = ', {step}' return ( 'do {concurrent}{counter} = {first}, {last}'+step+'\n' '{body}\n' 'end do\n' ).format( concurrent='concurrent ' if do.concurrent else '', **do.kwargs(apply=lambda arg: self._print(arg), exclude=excl) ) def _print_ImpliedDoLoop(self, idl): step = '' if idl.step == 1 else ', {step}' return ('({expr}, {counter} = {first}, {last}'+step+')').format( **idl.kwargs(apply=lambda arg: self._print(arg)) ) def _print_For(self, expr): target = self._print(expr.target) if isinstance(expr.iterable, Range): start, stop, step = expr.iterable.args else: raise NotImplementedError("Only iterable currently supported is Range") body = self._print(expr.body) return ('do {target} = {start}, {stop}, {step}\n' '{body}\n' 'end do').format(target=target, start=start, stop=stop - 1, step=step, body=body) def _print_Type(self, type_): type_ = self.type_aliases.get(type_, type_) type_str = self.type_mappings.get(type_, type_.name) module_uses = self.type_modules.get(type_) if module_uses: for k, v in module_uses: self.module_uses[k].add(v) return type_str def _print_Element(self, elem): return '{symbol}({idxs})'.format( symbol=self._print(elem.symbol), idxs=', '.join(map(lambda arg: self._print(arg), elem.indices)) ) def _print_Extent(self, ext): return str(ext) def _print_Declaration(self, expr): var = expr.variable val = var.value dim = var.attr_params('dimension') intents = [intent in var.attrs for intent in (intent_in, intent_out, intent_inout)] if intents.count(True) == 0: intent = '' elif intents.count(True) == 1: intent = ', intent(%s)' % ['in', 'out', 'inout'][intents.index(True)] else: raise ValueError("Multiple intents specified for %s" % self) if isinstance(var, Pointer): raise NotImplementedError("Pointers are not available by default in Fortran.") if self._settings["standard"] >= 90: result = '{t}{vc}{dim}{intent}{alloc} :: {s}'.format( t=self._print(var.type), vc=', parameter' if value_const in var.attrs else '', dim=', dimension(%s)' % ', '.join(map(lambda arg: self._print(arg), dim)) if dim else '', intent=intent, alloc=', allocatable' if allocatable in var.attrs else '', s=self._print(var.symbol) ) if val != None: # Must be "!= None", cannot be "is not None" result += ' = %s' % self._print(val) else: if value_const in var.attrs or val: raise NotImplementedError("F77 init./parameter statem. req. multiple lines.") result = ' '.join(map(lambda arg: self._print(arg), [var.type, var.symbol])) return result def _print_Infinity(self, expr): return '(huge(%s) + 1)' % self._print(literal_dp(0)) def _print_While(self, expr): return 'do while ({condition})\n{body}\nend do'.format(**expr.kwargs( apply=lambda arg: self._print(arg))) def _print_BooleanTrue(self, expr): return '.true.' def _print_BooleanFalse(self, expr): return '.false.' def _pad_leading_columns(self, lines): result = [] for line in lines: if line.startswith('!'): result.append(self._lead['comment'] + line[1:].lstrip()) else: result.append(self._lead['code'] + line) return result def _wrap_fortran(self, lines): """Wrap long Fortran lines Argument: lines -- a list of lines (without \\n character) A comment line is split at white space. Code lines are split with a more complex rule to give nice results. """ # routine to find split point in a code line my_alnum = set("_+-." + string.digits + string.ascii_letters) my_white = set(" \t()") def split_pos_code(line, endpos): if len(line) <= endpos: return len(line) pos = endpos split = lambda pos: \ (line[pos] in my_alnum and line[pos - 1] not in my_alnum) or \ (line[pos] not in my_alnum and line[pos - 1] in my_alnum) or \ (line[pos] in my_white and line[pos - 1] not in my_white) or \ (line[pos] not in my_white and line[pos - 1] in my_white) while not split(pos): pos -= 1 if pos == 0: return endpos return pos # split line by line and add the split lines to result result = [] if self._settings['source_format'] == 'free': trailing = ' &' else: trailing = '' for line in lines: if line.startswith(self._lead['comment']): # comment line if len(line) > 72: pos = line.rfind(" ", 6, 72) if pos == -1: pos = 72 hunk = line[:pos] line = line[pos:].lstrip() result.append(hunk) while line: pos = line.rfind(" ", 0, 66) if pos == -1 or len(line) < 66: pos = 66 hunk = line[:pos] line = line[pos:].lstrip() result.append("%s%s" % (self._lead['comment'], hunk)) else: result.append(line) elif line.startswith(self._lead['code']): # code line pos = split_pos_code(line, 72) hunk = line[:pos].rstrip() line = line[pos:].lstrip() if line: hunk += trailing result.append(hunk) while line: pos = split_pos_code(line, 65) hunk = line[:pos].rstrip() line = line[pos:].lstrip() if line: hunk += trailing result.append("%s%s" % (self._lead['cont'], hunk)) else: result.append(line) return result def indent_code(self, code): """Accepts a string of code or a list of code lines""" if isinstance(code, str): code_lines = self.indent_code(code.splitlines(True)) return ''.join(code_lines) free = self._settings['source_format'] == 'free' code = [ line.lstrip(' \t') for line in code ] inc_keyword = ('do ', 'if(', 'if ', 'do\n', 'else', 'program', 'interface') dec_keyword = ('end do', 'enddo', 'end if', 'endif', 'else', 'end program', 'end interface') increase = [ int(any(map(line.startswith, inc_keyword))) for line in code ] decrease = [ int(any(map(line.startswith, dec_keyword))) for line in code ] continuation = [ int(any(map(line.endswith, ['&', '&\n']))) for line in code ] level = 0 cont_padding = 0 tabwidth = 3 new_code = [] for i, line in enumerate(code): if line in ('', '\n'): new_code.append(line) continue level -= decrease[i] if free: padding = " "*(level*tabwidth + cont_padding) else: padding = " "*level*tabwidth line = "%s%s" % (padding, line) if not free: line = self._pad_leading_columns([line])[0] new_code.append(line) if continuation[i]: cont_padding = 2*tabwidth else: cont_padding = 0 level += increase[i] if not free: return self._wrap_fortran(new_code) return new_code def _print_GoTo(self, goto): if goto.expr: # computed goto return "go to ({labels}), {expr}".format( labels=', '.join(map(lambda arg: self._print(arg), goto.labels)), expr=self._print(goto.expr) ) else: lbl, = goto.labels return "go to %s" % self._print(lbl) def _print_Program(self, prog): return ( "program {name}\n" "{body}\n" "end program\n" ).format(**prog.kwargs(apply=lambda arg: self._print(arg))) def _print_Module(self, mod): return ( "module {name}\n" "{declarations}\n" "\ncontains\n\n" "{definitions}\n" "end module\n" ).format(**mod.kwargs(apply=lambda arg: self._print(arg))) def _print_Stream(self, strm): if strm.name == 'stdout' and self._settings["standard"] >= 2003: self.module_uses['iso_c_binding'].add('stdint=>input_unit') return 'input_unit' elif strm.name == 'stderr' and self._settings["standard"] >= 2003: self.module_uses['iso_c_binding'].add('stdint=>error_unit') return 'error_unit' else: if strm.name == 'stdout': return '*' else: return strm.name def _print_Print(self, ps): if ps.format_string != None: # Must be '!= None', cannot be 'is not None' fmt = self._print(ps.format_string) else: fmt = "*" return "print {fmt}, {iolist}".format(fmt=fmt, iolist=', '.join( map(lambda arg: self._print(arg), ps.print_args))) def _print_Return(self, rs): arg, = rs.args return "{result_name} = {arg}".format( result_name=self._context.get('result_name', 'sympy_result'), arg=self._print(arg) ) def _print_FortranReturn(self, frs): arg, = frs.args if arg: return 'return %s' % self._print(arg) else: return 'return' def _head(self, entity, fp, **kwargs): bind_C_params = fp.attr_params('bind_C') if bind_C_params is None: bind = '' else: bind = ' bind(C, name="%s")' % bind_C_params[0] if bind_C_params else ' bind(C)' result_name = self._settings.get('result_name', None) return ( "{entity}{name}({arg_names}){result}{bind}\n" "{arg_declarations}" ).format( entity=entity, name=self._print(fp.name), arg_names=', '.join([self._print(arg.symbol) for arg in fp.parameters]), result=(' result(%s)' % result_name) if result_name else '', bind=bind, arg_declarations='\n'.join(map(lambda arg: self._print(Declaration(arg)), fp.parameters)) ) def _print_FunctionPrototype(self, fp): entity = "{} function ".format(self._print(fp.return_type)) return ( "interface\n" "{function_head}\n" "end function\n" "end interface" ).format(function_head=self._head(entity, fp)) def _print_FunctionDefinition(self, fd): if elemental in fd.attrs: prefix = 'elemental ' elif pure in fd.attrs: prefix = 'pure ' else: prefix = '' entity = "{} function ".format(self._print(fd.return_type)) with printer_context(self, result_name=fd.name): return ( "{prefix}{function_head}\n" "{body}\n" "end function\n" ).format( prefix=prefix, function_head=self._head(entity, fd), body=self._print(fd.body) ) def _print_Subroutine(self, sub): return ( '{subroutine_head}\n' '{body}\n' 'end subroutine\n' ).format( subroutine_head=self._head('subroutine ', sub), body=self._print(sub.body) ) def _print_SubroutineCall(self, scall): return 'call {name}({args})'.format( name=self._print(scall.name), args=', '.join(map(lambda arg: self._print(arg), scall.subroutine_args)) ) def _print_use_rename(self, rnm): return "%s => %s" % tuple(map(lambda arg: self._print(arg), rnm.args)) def _print_use(self, use): result = 'use %s' % self._print(use.namespace) if use.rename != None: # Must be '!= None', cannot be 'is not None' result += ', ' + ', '.join([self._print(rnm) for rnm in use.rename]) if use.only != None: # Must be '!= None', cannot be 'is not None' result += ', only: ' + ', '.join([self._print(nly) for nly in use.only]) return result def _print_BreakToken(self, _): return 'exit' def _print_ContinueToken(self, _): return 'cycle' def _print_ArrayConstructor(self, ac): fmtstr = "[%s]" if self._settings["standard"] >= 2003 else '(/%s/)' return fmtstr % ', '.join(map(lambda arg: self._print(arg), ac.elements)) def _print_ArrayElement(self, elem): return '{symbol}({idxs})'.format( symbol=self._print(elem.name), idxs=', '.join(map(lambda arg: self._print(arg), elem.indices)) )
9a059861a72a90b8816e557ad02447d46e850bd1646742ce7c062cd4d8313870
""" R code printer The RCodePrinter converts single SymPy expressions into single R expressions, using the functions defined in math.h where possible. """ from __future__ import annotations from typing import Any from sympy.core.numbers import equal_valued from sympy.printing.codeprinter import CodePrinter from sympy.printing.precedence import precedence, PRECEDENCE from sympy.sets.fancysets import Range # dictionary mapping SymPy function to (argument_conditions, C_function). # Used in RCodePrinter._print_Function(self) known_functions = { #"Abs": [(lambda x: not x.is_integer, "fabs")], "Abs": "abs", "sin": "sin", "cos": "cos", "tan": "tan", "asin": "asin", "acos": "acos", "atan": "atan", "atan2": "atan2", "exp": "exp", "log": "log", "erf": "erf", "sinh": "sinh", "cosh": "cosh", "tanh": "tanh", "asinh": "asinh", "acosh": "acosh", "atanh": "atanh", "floor": "floor", "ceiling": "ceiling", "sign": "sign", "Max": "max", "Min": "min", "factorial": "factorial", "gamma": "gamma", "digamma": "digamma", "trigamma": "trigamma", "beta": "beta", "sqrt": "sqrt", # To enable automatic rewrite } # These are the core reserved words in the R language. Taken from: # https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Reserved-words reserved_words = ['if', 'else', 'repeat', 'while', 'function', 'for', 'in', 'next', 'break', 'TRUE', 'FALSE', 'NULL', 'Inf', 'NaN', 'NA', 'NA_integer_', 'NA_real_', 'NA_complex_', 'NA_character_', 'volatile'] class RCodePrinter(CodePrinter): """A printer to convert SymPy expressions to strings of R code""" printmethod = "_rcode" language = "R" _default_settings: dict[str, Any] = { 'order': None, 'full_prec': 'auto', 'precision': 15, 'user_functions': {}, 'human': True, 'contract': True, 'dereference': set(), 'error_on_reserved': False, 'reserved_word_suffix': '_', } _operators = { 'and': '&', 'or': '|', 'not': '!', } _relationals: dict[str, str] = {} def __init__(self, settings={}): CodePrinter.__init__(self, settings) self.known_functions = dict(known_functions) userfuncs = settings.get('user_functions', {}) self.known_functions.update(userfuncs) self._dereference = set(settings.get('dereference', [])) self.reserved_words = set(reserved_words) def _rate_index_position(self, p): return p*5 def _get_statement(self, codestring): return "%s;" % codestring def _get_comment(self, text): return "// {}".format(text) def _declare_number_const(self, name, value): return "{} = {};".format(name, value) def _format_code(self, lines): return self.indent_code(lines) def _traverse_matrix_indices(self, mat): rows, cols = mat.shape return ((i, j) for i in range(rows) for j in range(cols)) def _get_loop_opening_ending(self, indices): """Returns a tuple (open_lines, close_lines) containing lists of codelines """ open_lines = [] close_lines = [] loopstart = "for (%(var)s in %(start)s:%(end)s){" for i in indices: # R arrays start at 1 and end at dimension open_lines.append(loopstart % { 'var': self._print(i.label), 'start': self._print(i.lower+1), 'end': self._print(i.upper + 1)}) close_lines.append("}") return open_lines, close_lines def _print_Pow(self, expr): if "Pow" in self.known_functions: return self._print_Function(expr) PREC = precedence(expr) if equal_valued(expr.exp, -1): return '1.0/%s' % (self.parenthesize(expr.base, PREC)) elif equal_valued(expr.exp, 0.5): return 'sqrt(%s)' % self._print(expr.base) else: return '%s^%s' % (self.parenthesize(expr.base, PREC), self.parenthesize(expr.exp, PREC)) def _print_Rational(self, expr): p, q = int(expr.p), int(expr.q) return '%d.0/%d.0' % (p, q) def _print_Indexed(self, expr): inds = [ self._print(i) for i in expr.indices ] return "%s[%s]" % (self._print(expr.base.label), ", ".join(inds)) def _print_Idx(self, expr): return self._print(expr.label) def _print_Exp1(self, expr): return "exp(1)" def _print_Pi(self, expr): return 'pi' def _print_Infinity(self, expr): return 'Inf' def _print_NegativeInfinity(self, expr): return '-Inf' def _print_Assignment(self, expr): from sympy.codegen.ast import Assignment from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.tensor.indexed import IndexedBase lhs = expr.lhs rhs = expr.rhs # We special case assignments that take multiple lines #if isinstance(expr.rhs, Piecewise): # from sympy.functions.elementary.piecewise import Piecewise # # Here we modify Piecewise so each expression is now # # an Assignment, and then continue on the print. # expressions = [] # conditions = [] # for (e, c) in rhs.args: # expressions.append(Assignment(lhs, e)) # conditions.append(c) # temp = Piecewise(*zip(expressions, conditions)) # return self._print(temp) #elif isinstance(lhs, MatrixSymbol): if isinstance(lhs, MatrixSymbol): # Here we form an Assignment for each element in the array, # printing each one. lines = [] for (i, j) in self._traverse_matrix_indices(lhs): temp = Assignment(lhs[i, j], rhs[i, j]) code0 = self._print(temp) lines.append(code0) return "\n".join(lines) elif self._settings["contract"] and (lhs.has(IndexedBase) or rhs.has(IndexedBase)): # Here we check if there is looping to be done, and if so # print the required loops. return self._doprint_loops(rhs, lhs) else: lhs_code = self._print(lhs) rhs_code = self._print(rhs) return self._get_statement("%s = %s" % (lhs_code, rhs_code)) def _print_Piecewise(self, expr): # This method is called only for inline if constructs # Top level piecewise is handled in doprint() if expr.args[-1].cond == True: last_line = "%s" % self._print(expr.args[-1].expr) else: last_line = "ifelse(%s,%s,NA)" % (self._print(expr.args[-1].cond), self._print(expr.args[-1].expr)) code=last_line for e, c in reversed(expr.args[:-1]): code= "ifelse(%s,%s," % (self._print(c), self._print(e))+code+")" return(code) def _print_ITE(self, expr): from sympy.functions import Piecewise return self._print(expr.rewrite(Piecewise)) def _print_MatrixElement(self, expr): return "{}[{}]".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True), expr.j + expr.i*expr.parent.shape[1]) def _print_Symbol(self, expr): name = super()._print_Symbol(expr) if expr in self._dereference: return '(*{})'.format(name) else: return name def _print_Relational(self, expr): lhs_code = self._print(expr.lhs) rhs_code = self._print(expr.rhs) op = expr.rel_op return "{} {} {}".format(lhs_code, op, rhs_code) def _print_AugmentedAssignment(self, expr): lhs_code = self._print(expr.lhs) op = expr.op rhs_code = self._print(expr.rhs) return "{} {} {};".format(lhs_code, op, rhs_code) def _print_For(self, expr): target = self._print(expr.target) if isinstance(expr.iterable, Range): start, stop, step = expr.iterable.args else: raise NotImplementedError("Only iterable currently supported is Range") body = self._print(expr.body) return 'for({target} in seq(from={start}, to={stop}, by={step}){{\n{body}\n}}'.format(target=target, start=start, stop=stop-1, step=step, body=body) def indent_code(self, code): """Accepts a string of code or a list of code lines""" if isinstance(code, str): code_lines = self.indent_code(code.splitlines(True)) return ''.join(code_lines) tab = " " inc_token = ('{', '(', '{\n', '(\n') dec_token = ('}', ')') code = [ line.lstrip(' \t') for line in code ] increase = [ int(any(map(line.endswith, inc_token))) for line in code ] decrease = [ int(any(map(line.startswith, dec_token))) for line in code ] pretty = [] level = 0 for n, line in enumerate(code): if line in ('', '\n'): pretty.append(line) continue level -= decrease[n] pretty.append("%s%s" % (tab*level, line)) level += increase[n] return pretty def rcode(expr, assign_to=None, **settings): """Converts an expr to a string of r code Parameters ========== expr : Expr A SymPy expression to be converted. assign_to : optional When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, ``Symbol``, ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of line-wrapping, or for expressions that generate multi-line statements. precision : integer, optional The precision for numbers such as pi [default=15]. user_functions : dict, optional A dictionary where the keys are string representations of either ``FunctionClass`` or ``UndefinedFunction`` instances and the values are their desired R string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, rfunction_string)] or [(argument_test, rfunction_formater)]. See below for examples. human : bool, optional If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True]. contract: bool, optional If True, ``Indexed`` instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True]. Examples ======== >>> from sympy import rcode, symbols, Rational, sin, ceiling, Abs, Function >>> x, tau = symbols("x, tau") >>> rcode((2*tau)**Rational(7, 2)) '8*sqrt(2)*tau^(7.0/2.0)' >>> rcode(sin(x), assign_to="s") 's = sin(x);' Simple custom printing can be defined for certain types by passing a dictionary of {"type" : "function"} to the ``user_functions`` kwarg. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. >>> custom_functions = { ... "ceiling": "CEIL", ... "Abs": [(lambda x: not x.is_integer, "fabs"), ... (lambda x: x.is_integer, "ABS")], ... "func": "f" ... } >>> func = Function('func') >>> rcode(func(Abs(x) + ceiling(x)), user_functions=custom_functions) 'f(fabs(x) + CEIL(x))' or if the R-function takes a subset of the original arguments: >>> rcode(2**x + 3**x, user_functions={'Pow': [ ... (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e), ... (lambda b, e: b != 2, 'pow')]}) 'exp2(x) + pow(3, x)' ``Piecewise`` expressions are converted into conditionals. If an ``assign_to`` variable is provided an if statement is created, otherwise the ternary operator is used. Note that if the ``Piecewise`` lacks a default term, represented by ``(expr, True)`` then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything. >>> from sympy import Piecewise >>> expr = Piecewise((x + 1, x > 0), (x, True)) >>> print(rcode(expr, assign_to=tau)) tau = ifelse(x > 0,x + 1,x); Support for loops is provided through ``Indexed`` types. With ``contract=True`` these expressions will be turned into loops, whereas ``contract=False`` will just print the assignment expression that should be looped over: >>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', 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])/(t[i+1]-t[i])) >>> rcode(e.rhs, assign_to=e.lhs, contract=False) 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);' Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions must be provided to ``assign_to``. Note that any expression that can be generated normally can also exist inside a Matrix: >>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) >>> A = MatrixSymbol('A', 3, 1) >>> print(rcode(mat, A)) A[0] = x^2; A[1] = ifelse(x > 0,x + 1,x); A[2] = sin(x); """ return RCodePrinter(settings).doprint(expr, assign_to) def print_rcode(expr, **settings): """Prints R representation of the given expression.""" print(rcode(expr, **settings))
df50669c253e082aa5940a4e049a7910f40244eee18d4ee1bd84ea6317ab3d88
""" Octave (and Matlab) code printer The `OctaveCodePrinter` converts SymPy expressions into Octave expressions. It uses a subset of the Octave language for Matlab compatibility. A complete code generator, which uses `octave_code` extensively, can be found in `sympy.utilities.codegen`. The `codegen` module can be used to generate complete source code files. """ from __future__ import annotations from typing import Any from sympy.core import Mul, Pow, S, Rational from sympy.core.mul import _keep_coeff from sympy.core.numbers import equal_valued from sympy.printing.codeprinter import CodePrinter from sympy.printing.precedence import precedence, PRECEDENCE from re import search # List of known functions. First, those that have the same name in # SymPy and Octave. This is almost certainly incomplete! known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc", "asin", "acos", "acot", "atan", "atan2", "asec", "acsc", "sinh", "cosh", "tanh", "coth", "csch", "sech", "asinh", "acosh", "atanh", "acoth", "asech", "acsch", "erfc", "erfi", "erf", "erfinv", "erfcinv", "besseli", "besselj", "besselk", "bessely", "bernoulli", "beta", "euler", "exp", "factorial", "floor", "fresnelc", "fresnels", "gamma", "harmonic", "log", "polylog", "sign", "zeta", "legendre"] # These functions have different names ("SymPy": "Octave"), more # generally a mapping to (argument_conditions, octave_function). known_fcns_src2 = { "Abs": "abs", "arg": "angle", # arg/angle ok in Octave but only angle in Matlab "binomial": "bincoeff", "ceiling": "ceil", "chebyshevu": "chebyshevU", "chebyshevt": "chebyshevT", "Chi": "coshint", "Ci": "cosint", "conjugate": "conj", "DiracDelta": "dirac", "Heaviside": "heaviside", "im": "imag", "laguerre": "laguerreL", "LambertW": "lambertw", "li": "logint", "loggamma": "gammaln", "Max": "max", "Min": "min", "Mod": "mod", "polygamma": "psi", "re": "real", "RisingFactorial": "pochhammer", "Shi": "sinhint", "Si": "sinint", } class OctaveCodePrinter(CodePrinter): """ A printer to convert expressions to strings of Octave/Matlab code. """ printmethod = "_octave" language = "Octave" _operators = { 'and': '&', 'or': '|', 'not': '~', } _default_settings: dict[str, Any] = { 'order': None, 'full_prec': 'auto', 'precision': 17, 'user_functions': {}, 'human': True, 'allow_unknown_functions': False, 'contract': True, 'inline': True, } # Note: contract is for expressing tensors as loops (if True), or just # assignment (if False). FIXME: this should be looked a more carefully # for Octave. def __init__(self, settings={}): super().__init__(settings) self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1)) self.known_functions.update(dict(known_fcns_src2)) userfuncs = settings.get('user_functions', {}) self.known_functions.update(userfuncs) def _rate_index_position(self, p): return p*5 def _get_statement(self, codestring): return "%s;" % codestring def _get_comment(self, text): return "% {}".format(text) def _declare_number_const(self, name, value): return "{} = {};".format(name, value) def _format_code(self, lines): return self.indent_code(lines) def _traverse_matrix_indices(self, mat): # Octave uses Fortran order (column-major) rows, cols = mat.shape return ((i, j) for j in range(cols) for i in range(rows)) def _get_loop_opening_ending(self, indices): open_lines = [] close_lines = [] for i in indices: # Octave arrays start at 1 and end at dimension var, start, stop = map(self._print, [i.label, i.lower + 1, i.upper + 1]) open_lines.append("for %s = %s:%s" % (var, start, stop)) close_lines.append("end") return open_lines, close_lines def _print_Mul(self, expr): # print complex numbers nicely in Octave if (expr.is_number and expr.is_imaginary and (S.ImaginaryUnit*expr).is_Integer): return "%si" % self._print(-S.ImaginaryUnit*expr) # cribbed from str.py prec = precedence(expr) 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) for x in a] b_str = [self.parenthesize(x, prec) 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)] # from here it differs from str.py to deal with "*" and ".*" def multjoin(a, a_str): # here we probably are assuming the constants will come first r = a_str[0] for i in range(1, len(a)): mulsym = '*' if a[i-1].is_number else '.*' r = r + mulsym + a_str[i] return r if not b: return sign + multjoin(a, a_str) elif len(b) == 1: divsym = '/' if b[0].is_number else './' return sign + multjoin(a, a_str) + divsym + b_str[0] else: divsym = '/' if all(bi.is_number for bi in b) else './' return (sign + multjoin(a, a_str) + divsym + "(%s)" % multjoin(b, b_str)) def _print_Relational(self, expr): lhs_code = self._print(expr.lhs) rhs_code = self._print(expr.rhs) op = expr.rel_op return "{} {} {}".format(lhs_code, op, rhs_code) def _print_Pow(self, expr): powsymbol = '^' if all(x.is_number for x in expr.args) else '.^' PREC = precedence(expr) if equal_valued(expr.exp, 0.5): return "sqrt(%s)" % self._print(expr.base) if expr.is_commutative: if equal_valued(expr.exp, -0.5): sym = '/' if expr.base.is_number else './' return "1" + sym + "sqrt(%s)" % self._print(expr.base) if equal_valued(expr.exp, -1): sym = '/' if expr.base.is_number else './' return "1" + sym + "%s" % self.parenthesize(expr.base, PREC) return '%s%s%s' % (self.parenthesize(expr.base, PREC), powsymbol, self.parenthesize(expr.exp, PREC)) def _print_MatPow(self, expr): PREC = precedence(expr) return '%s^%s' % (self.parenthesize(expr.base, PREC), self.parenthesize(expr.exp, PREC)) def _print_MatrixSolve(self, expr): PREC = precedence(expr) return "%s \\ %s" % (self.parenthesize(expr.matrix, PREC), self.parenthesize(expr.vector, PREC)) def _print_Pi(self, expr): return 'pi' def _print_ImaginaryUnit(self, expr): return "1i" def _print_Exp1(self, expr): return "exp(1)" def _print_GoldenRatio(self, expr): # FIXME: how to do better, e.g., for octave_code(2*GoldenRatio)? #return self._print((1+sqrt(S(5)))/2) return "(1+sqrt(5))/2" def _print_Assignment(self, expr): from sympy.codegen.ast import Assignment from sympy.functions.elementary.piecewise import Piecewise from sympy.tensor.indexed import IndexedBase # Copied from codeprinter, but remove special MatrixSymbol treatment lhs = expr.lhs rhs = expr.rhs # We special case assignments that take multiple lines if not self._settings["inline"] and isinstance(expr.rhs, Piecewise): # Here we modify Piecewise so each expression is now # an Assignment, and then continue on the print. expressions = [] conditions = [] for (e, c) in rhs.args: expressions.append(Assignment(lhs, e)) conditions.append(c) temp = Piecewise(*zip(expressions, conditions)) return self._print(temp) if self._settings["contract"] and (lhs.has(IndexedBase) or rhs.has(IndexedBase)): # Here we check if there is looping to be done, and if so # print the required loops. return self._doprint_loops(rhs, lhs) else: lhs_code = self._print(lhs) rhs_code = self._print(rhs) return self._get_statement("%s = %s" % (lhs_code, rhs_code)) def _print_Infinity(self, expr): return 'inf' def _print_NegativeInfinity(self, expr): return '-inf' def _print_NaN(self, expr): return 'NaN' def _print_list(self, expr): return '{' + ', '.join(self._print(a) for a in expr) + '}' _print_tuple = _print_list _print_Tuple = _print_list _print_List = _print_list def _print_BooleanTrue(self, expr): return "true" def _print_BooleanFalse(self, expr): return "false" def _print_bool(self, expr): return str(expr).lower() # Could generate quadrature code for definite Integrals? #_print_Integral = _print_not_supported def _print_MatrixBase(self, A): # Handle zero dimensions: if (A.rows, A.cols) == (0, 0): return '[]' elif S.Zero in A.shape: return 'zeros(%s, %s)' % (A.rows, A.cols) elif (A.rows, A.cols) == (1, 1): # Octave does not distinguish between scalars and 1x1 matrices return self._print(A[0, 0]) return "[%s]" % "; ".join(" ".join([self._print(a) for a in A[r, :]]) for r in range(A.rows)) def _print_SparseRepMatrix(self, A): from sympy.matrices import Matrix L = A.col_list(); # make row vectors of the indices and entries I = Matrix([[k[0] + 1 for k in L]]) J = Matrix([[k[1] + 1 for k in L]]) AIJ = Matrix([[k[2] for k in L]]) return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J), self._print(AIJ), A.rows, A.cols) def _print_MatrixElement(self, expr): return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \ + '(%s, %s)' % (expr.i + 1, expr.j + 1) def _print_MatrixSlice(self, expr): def strslice(x, lim): l = x[0] + 1 h = x[1] step = x[2] lstr = self._print(l) hstr = 'end' if h == lim else self._print(h) if step == 1: if l == 1 and h == lim: return ':' if l == h: return lstr else: return lstr + ':' + hstr else: return ':'.join((lstr, self._print(step), hstr)) return (self._print(expr.parent) + '(' + strslice(expr.rowslice, expr.parent.shape[0]) + ', ' + strslice(expr.colslice, expr.parent.shape[1]) + ')') def _print_Indexed(self, expr): inds = [ self._print(i) for i in expr.indices ] return "%s(%s)" % (self._print(expr.base.label), ", ".join(inds)) def _print_Idx(self, expr): return self._print(expr.label) def _print_KroneckerDelta(self, expr): prec = PRECEDENCE["Pow"] return "double(%s == %s)" % tuple(self.parenthesize(x, prec) for x in expr.args) def _print_HadamardProduct(self, expr): return '.*'.join([self.parenthesize(arg, precedence(expr)) for arg in expr.args]) def _print_HadamardPower(self, expr): PREC = precedence(expr) return '.**'.join([ self.parenthesize(expr.base, PREC), self.parenthesize(expr.exp, PREC) ]) def _print_Identity(self, expr): shape = expr.shape if len(shape) == 2 and shape[0] == shape[1]: shape = [shape[0]] s = ", ".join(self._print(n) for n in shape) return "eye(" + s + ")" def _print_lowergamma(self, expr): # Octave implements regularized incomplete gamma function return "(gammainc({1}, {0}).*gamma({0}))".format( self._print(expr.args[0]), self._print(expr.args[1])) def _print_uppergamma(self, expr): return "(gammainc({1}, {0}, 'upper').*gamma({0}))".format( self._print(expr.args[0]), self._print(expr.args[1])) def _print_sinc(self, expr): #Note: Divide by pi because Octave implements normalized sinc function. return "sinc(%s)" % self._print(expr.args[0]/S.Pi) def _print_hankel1(self, expr): return "besselh(%s, 1, %s)" % (self._print(expr.order), self._print(expr.argument)) def _print_hankel2(self, expr): return "besselh(%s, 2, %s)" % (self._print(expr.order), self._print(expr.argument)) # Note: as of 2015, Octave doesn't have spherical Bessel functions def _print_jn(self, expr): from sympy.functions import sqrt, besselj x = expr.argument expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x) return self._print(expr2) def _print_yn(self, expr): from sympy.functions import sqrt, bessely x = expr.argument expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x) return self._print(expr2) def _print_airyai(self, expr): return "airy(0, %s)" % self._print(expr.args[0]) def _print_airyaiprime(self, expr): return "airy(1, %s)" % self._print(expr.args[0]) def _print_airybi(self, expr): return "airy(2, %s)" % self._print(expr.args[0]) def _print_airybiprime(self, expr): return "airy(3, %s)" % self._print(expr.args[0]) def _print_expint(self, expr): mu, x = expr.args if mu != 1: return self._print_not_supported(expr) return "expint(%s)" % self._print(x) def _one_or_two_reversed_args(self, expr): assert len(expr.args) <= 2 return '{name}({args})'.format( name=self.known_functions[expr.__class__.__name__], args=", ".join([self._print(x) for x in reversed(expr.args)]) ) _print_DiracDelta = _print_LambertW = _one_or_two_reversed_args def _nested_binary_math_func(self, expr): return '{name}({arg1}, {arg2})'.format( name=self.known_functions[expr.__class__.__name__], arg1=self._print(expr.args[0]), arg2=self._print(expr.func(*expr.args[1:])) ) _print_Max = _print_Min = _nested_binary_math_func def _print_Piecewise(self, expr): if expr.args[-1].cond != True: # We need the last conditional to be a True, otherwise the resulting # function may not return a result. raise ValueError("All Piecewise expressions must contain an " "(expr, True) statement to be used as a default " "condition. Without one, the generated " "expression may not evaluate to anything under " "some condition.") lines = [] if self._settings["inline"]: # Express each (cond, expr) pair in a nested Horner form: # (condition) .* (expr) + (not cond) .* (<others>) # Expressions that result in multiple statements won't work here. ecpairs = ["({0}).*({1}) + (~({0})).*(".format (self._print(c), self._print(e)) for e, c in expr.args[:-1]] elast = "%s" % self._print(expr.args[-1].expr) pw = " ...\n".join(ecpairs) + elast + ")"*len(ecpairs) # Note: current need these outer brackets for 2*pw. Would be # nicer to teach parenthesize() to do this for us when needed! return "(" + pw + ")" else: for i, (e, c) in enumerate(expr.args): if i == 0: lines.append("if (%s)" % self._print(c)) elif i == len(expr.args) - 1 and c == True: lines.append("else") else: lines.append("elseif (%s)" % self._print(c)) code0 = self._print(e) lines.append(code0) if i == len(expr.args) - 1: lines.append("end") return "\n".join(lines) def _print_zeta(self, expr): if len(expr.args) == 1: return "zeta(%s)" % self._print(expr.args[0]) else: # Matlab two argument zeta is not equivalent to SymPy's return self._print_not_supported(expr) def indent_code(self, code): """Accepts a string of code or a list of code lines""" # code mostly copied from ccode if isinstance(code, str): code_lines = self.indent_code(code.splitlines(True)) return ''.join(code_lines) tab = " " inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ') dec_regex = ('^end$', '^elseif ', '^else$') # pre-strip left-space from the code code = [ line.lstrip(' \t') for line in code ] increase = [ int(any(search(re, line) for re in inc_regex)) for line in code ] decrease = [ int(any(search(re, line) for re in dec_regex)) for line in code ] pretty = [] level = 0 for n, line in enumerate(code): if line in ('', '\n'): pretty.append(line) continue level -= decrease[n] pretty.append("%s%s" % (tab*level, line)) level += increase[n] return pretty def octave_code(expr, assign_to=None, **settings): r"""Converts `expr` to a string of Octave (or Matlab) code. The string uses a subset of the Octave language for Matlab compatibility. Parameters ========== expr : Expr A SymPy expression to be converted. assign_to : optional When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, ``Symbol``, ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for expressions that generate multi-line statements. precision : integer, optional The precision for numbers such as pi [default=16]. user_functions : dict, optional A dictionary where keys are ``FunctionClass`` instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples. human : bool, optional If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True]. contract: bool, optional If True, ``Indexed`` instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True]. inline: bool, optional If True, we try to create single-statement code instead of multiple statements. [default=True]. Examples ======== >>> from sympy import octave_code, symbols, sin, pi >>> x = symbols('x') >>> octave_code(sin(x).series(x).removeO()) 'x.^5/120 - x.^3/6 + x' >>> from sympy import Rational, ceiling >>> x, y, tau = symbols("x, y, tau") >>> octave_code((2*tau)**Rational(7, 2)) '8*sqrt(2)*tau.^(7/2)' Note that element-wise (Hadamard) operations are used by default between symbols. This is because its very common in Octave to write "vectorized" code. It is harmless if the values are scalars. >>> octave_code(sin(pi*x*y), assign_to="s") 's = sin(pi*x.*y);' If you need a matrix product "*" or matrix power "^", you can specify the symbol as a ``MatrixSymbol``. >>> from sympy import Symbol, MatrixSymbol >>> n = Symbol('n', integer=True, positive=True) >>> A = MatrixSymbol('A', n, n) >>> octave_code(3*pi*A**3) '(3*pi)*A^3' This class uses several rules to decide which symbol to use a product. Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*". A HadamardProduct can be used to specify componentwise multiplication ".*" of two MatrixSymbols. There is currently there is no easy way to specify scalar symbols, so sometimes the code might have some minor cosmetic issues. For example, suppose x and y are scalars and A is a Matrix, then while a human programmer might write "(x^2*y)*A^3", we generate: >>> octave_code(x**2*y*A**3) '(x.^2.*y)*A^3' Matrices are supported using Octave inline notation. When using ``assign_to`` with matrices, the name can be specified either as a string or as a ``MatrixSymbol``. The dimensions must align in the latter case. >>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([[x**2, sin(x), ceiling(x)]]) >>> octave_code(mat, assign_to='A') 'A = [x.^2 sin(x) ceil(x)];' ``Piecewise`` expressions are implemented with logical masking by default. Alternatively, you can pass "inline=False" to use if-else conditionals. Note that if the ``Piecewise`` lacks a default term, represented by ``(expr, True)`` then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything. >>> from sympy import Piecewise >>> pw = Piecewise((x + 1, x > 0), (x, True)) >>> octave_code(pw, assign_to=tau) 'tau = ((x > 0).*(x + 1) + (~(x > 0)).*(x));' Note that any expression that can be generated normally can also exist inside a Matrix: >>> mat = Matrix([[x**2, pw, sin(x)]]) >>> octave_code(mat, assign_to='A') 'A = [x.^2 ((x > 0).*(x + 1) + (~(x > 0)).*(x)) sin(x)];' Custom printing can be defined for certain types by passing a dictionary of "type" : "function" to the ``user_functions`` kwarg. Alternatively, the dictionary value can be a list of tuples i.e., [(argument_test, cfunction_string)]. This can be used to call a custom Octave function. >>> from sympy import Function >>> f = Function('f') >>> g = Function('g') >>> custom_functions = { ... "f": "existing_octave_fcn", ... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"), ... (lambda x: not x.is_Matrix, "my_fcn")] ... } >>> mat = Matrix([[1, x]]) >>> octave_code(f(x) + g(x) + g(mat), user_functions=custom_functions) 'existing_octave_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])' Support for loops is provided through ``Indexed`` types. With ``contract=True`` these expressions will be turned into loops, whereas ``contract=False`` will just print the assignment expression that should be looped over: >>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', 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])/(t[i+1]-t[i])) >>> octave_code(e.rhs, assign_to=e.lhs, contract=False) 'Dy(i) = (y(i + 1) - y(i))./(t(i + 1) - t(i));' """ return OctaveCodePrinter(settings).doprint(expr, assign_to) def print_octave_code(expr, **settings): """Prints the Octave (or Matlab) representation of the given expression. See `octave_code` for the meaning of the optional arguments. """ print(octave_code(expr, **settings))
c841a112c13f5a41b833a3e945d511c3e15bb06f9e54b2fc776f9ddc25299079
""" Maple code printer The MapleCodePrinter converts single SymPy expressions into single Maple expressions, using the functions defined in the Maple objects where possible. FIXME: This module is still under actively developed. Some functions may be not completed. """ from sympy.core import S from sympy.core.numbers import Integer, IntegerConstant, equal_valued from sympy.printing.codeprinter import CodePrinter from sympy.printing.precedence import precedence, PRECEDENCE import sympy _known_func_same_name = ( 'sin', 'cos', 'tan', 'sec', 'csc', 'cot', 'sinh', 'cosh', 'tanh', 'sech', 'csch', 'coth', 'exp', 'floor', 'factorial', 'bernoulli', 'euler', 'fibonacci', 'gcd', 'lcm', 'conjugate', 'Ci', 'Chi', 'Ei', 'Li', 'Si', 'Shi', 'erf', 'erfc', 'harmonic', 'LambertW', 'sqrt', # For automatic rewrites ) known_functions = { # SymPy -> Maple 'Abs': 'abs', 'log': 'ln', 'asin': 'arcsin', 'acos': 'arccos', 'atan': 'arctan', 'asec': 'arcsec', 'acsc': 'arccsc', 'acot': 'arccot', 'asinh': 'arcsinh', 'acosh': 'arccosh', 'atanh': 'arctanh', 'asech': 'arcsech', 'acsch': 'arccsch', 'acoth': 'arccoth', 'ceiling': 'ceil', 'Max' : 'max', 'Min' : 'min', 'factorial2': 'doublefactorial', 'RisingFactorial': 'pochhammer', 'besseli': 'BesselI', 'besselj': 'BesselJ', 'besselk': 'BesselK', 'bessely': 'BesselY', 'hankelh1': 'HankelH1', 'hankelh2': 'HankelH2', 'airyai': 'AiryAi', 'airybi': 'AiryBi', 'appellf1': 'AppellF1', 'fresnelc': 'FresnelC', 'fresnels': 'FresnelS', 'lerchphi' : 'LerchPhi', } for _func in _known_func_same_name: known_functions[_func] = _func number_symbols = { # SymPy -> Maple S.Pi: 'Pi', S.Exp1: 'exp(1)', S.Catalan: 'Catalan', S.EulerGamma: 'gamma', S.GoldenRatio: '(1/2 + (1/2)*sqrt(5))' } spec_relational_ops = { # SymPy -> Maple '==': '=', '!=': '<>' } not_supported_symbol = [ S.ComplexInfinity ] class MapleCodePrinter(CodePrinter): """ Printer which converts a SymPy expression into a maple code. """ printmethod = "_maple" language = "maple" _default_settings = { 'order': None, 'full_prec': 'auto', 'human': True, 'inline': True, 'allow_unknown_functions': True, } def __init__(self, settings=None): if settings is None: settings = {} super().__init__(settings) self.known_functions = dict(known_functions) userfuncs = settings.get('user_functions', {}) self.known_functions.update(userfuncs) def _get_statement(self, codestring): return "%s;" % codestring def _get_comment(self, text): return "# {}".format(text) def _declare_number_const(self, name, value): return "{} := {};".format(name, value.evalf(self._settings['precision'])) def _format_code(self, lines): return lines def _print_tuple(self, expr): return self._print(list(expr)) def _print_Tuple(self, expr): return self._print(list(expr)) def _print_Assignment(self, expr): lhs = self._print(expr.lhs) rhs = self._print(expr.rhs) return "{lhs} := {rhs}".format(lhs=lhs, rhs=rhs) def _print_Pow(self, expr, **kwargs): PREC = precedence(expr) if equal_valued(expr.exp, -1): return '1/%s' % (self.parenthesize(expr.base, PREC)) elif equal_valued(expr.exp, 0.5): return 'sqrt(%s)' % self._print(expr.base) elif equal_valued(expr.exp, -0.5): return '1/sqrt(%s)' % self._print(expr.base) else: return '{base}^{exp}'.format( base=self.parenthesize(expr.base, PREC), exp=self.parenthesize(expr.exp, PREC)) def _print_Piecewise(self, expr): if (expr.args[-1].cond is not True) and (expr.args[-1].cond != S.BooleanTrue): # We need the last conditional to be a True, otherwise the resulting # function may not return a result. raise ValueError("All Piecewise expressions must contain an " "(expr, True) statement to be used as a default " "condition. Without one, the generated " "expression may not evaluate to anything under " "some condition.") _coup_list = [ ("{c}, {e}".format(c=self._print(c), e=self._print(e)) if c is not True and c is not S.BooleanTrue else "{e}".format( e=self._print(e))) for e, c in expr.args] _inbrace = ', '.join(_coup_list) return 'piecewise({_inbrace})'.format(_inbrace=_inbrace) def _print_Rational(self, expr): p, q = int(expr.p), int(expr.q) return "{p}/{q}".format(p=str(p), q=str(q)) def _print_Relational(self, expr): PREC=precedence(expr) lhs_code = self.parenthesize(expr.lhs, PREC) rhs_code = self.parenthesize(expr.rhs, PREC) op = expr.rel_op if op in spec_relational_ops: op = spec_relational_ops[op] return "{lhs} {rel_op} {rhs}".format(lhs=lhs_code, rel_op=op, rhs=rhs_code) def _print_NumberSymbol(self, expr): return number_symbols[expr] def _print_NegativeInfinity(self, expr): return '-infinity' def _print_Infinity(self, expr): return 'infinity' def _print_Idx(self, expr): return self._print(expr.label) def _print_BooleanTrue(self, expr): return "true" def _print_BooleanFalse(self, expr): return "false" def _print_bool(self, expr): return 'true' if expr else 'false' def _print_NaN(self, expr): return 'undefined' def _get_matrix(self, expr, sparse=False): if S.Zero in expr.shape: _strM = 'Matrix([], storage = {storage})'.format( storage='sparse' if sparse else 'rectangular') else: _strM = 'Matrix({list}, storage = {storage})'.format( list=self._print(expr.tolist()), storage='sparse' if sparse else 'rectangular') return _strM def _print_MatrixElement(self, expr): return "{parent}[{i_maple}, {j_maple}]".format( parent=self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True), i_maple=self._print(expr.i + 1), j_maple=self._print(expr.j + 1)) def _print_MatrixBase(self, expr): return self._get_matrix(expr, sparse=False) def _print_SparseRepMatrix(self, expr): return self._get_matrix(expr, sparse=True) def _print_Identity(self, expr): if isinstance(expr.rows, (Integer, IntegerConstant)): return self._print(sympy.SparseMatrix(expr)) else: return "Matrix({var_size}, shape = identity)".format(var_size=self._print(expr.rows)) def _print_MatMul(self, expr): PREC=precedence(expr) _fact_list = list(expr.args) _const = None if not isinstance(_fact_list[0], (sympy.MatrixBase, sympy.MatrixExpr, sympy.MatrixSlice, sympy.MatrixSymbol)): _const, _fact_list = _fact_list[0], _fact_list[1:] if _const is None or _const == 1: return '.'.join(self.parenthesize(_m, PREC) for _m in _fact_list) else: return '{c}*{m}'.format(c=_const, m='.'.join(self.parenthesize(_m, PREC) for _m in _fact_list)) def _print_MatPow(self, expr): # This function requires LinearAlgebra Function in Maple return 'MatrixPower({A}, {n})'.format(A=self._print(expr.base), n=self._print(expr.exp)) def _print_HadamardProduct(self, expr): PREC = precedence(expr) _fact_list = list(expr.args) return '*'.join(self.parenthesize(_m, PREC) for _m in _fact_list) def _print_Derivative(self, expr): _f, (_var, _order) = expr.args if _order != 1: _second_arg = '{var}${order}'.format(var=self._print(_var), order=self._print(_order)) else: _second_arg = '{var}'.format(var=self._print(_var)) return 'diff({func_expr}, {sec_arg})'.format(func_expr=self._print(_f), sec_arg=_second_arg) def maple_code(expr, assign_to=None, **settings): r"""Converts ``expr`` to a string of Maple code. Parameters ========== expr : Expr A SymPy expression to be converted. assign_to : optional When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, ``Symbol``, ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for expressions that generate multi-line statements. precision : integer, optional The precision for numbers such as pi [default=16]. user_functions : dict, optional A dictionary where keys are ``FunctionClass`` instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples. human : bool, optional If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True]. contract: bool, optional If True, ``Indexed`` instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True]. inline: bool, optional If True, we try to create single-statement code instead of multiple statements. [default=True]. """ return MapleCodePrinter(settings).doprint(expr, assign_to) def print_maple_code(expr, **settings): """Prints the Maple representation of the given expression. See :func:`maple_code` for the meaning of the optional arguments. Examples ======== >>> from sympy import print_maple_code, symbols >>> x, y = symbols('x y') >>> print_maple_code(x, assign_to=y) y := x """ print(maple_code(expr, **settings))
124194a8c1f7a8101b2d56d24ae622e1943cf46e315089834f69d301fde79fd1
""" Javascript code printer The JavascriptCodePrinter converts single SymPy expressions into single Javascript expressions, using the functions defined in the Javascript Math object where possible. """ from __future__ import annotations from typing import Any from sympy.core import S from sympy.core.numbers import equal_valued from sympy.printing.codeprinter import CodePrinter from sympy.printing.precedence import precedence, PRECEDENCE # dictionary mapping SymPy function to (argument_conditions, Javascript_function). # Used in JavascriptCodePrinter._print_Function(self) known_functions = { 'Abs': 'Math.abs', 'acos': 'Math.acos', 'acosh': 'Math.acosh', 'asin': 'Math.asin', 'asinh': 'Math.asinh', 'atan': 'Math.atan', 'atan2': 'Math.atan2', 'atanh': 'Math.atanh', 'ceiling': 'Math.ceil', 'cos': 'Math.cos', 'cosh': 'Math.cosh', 'exp': 'Math.exp', 'floor': 'Math.floor', 'log': 'Math.log', 'Max': 'Math.max', 'Min': 'Math.min', 'sign': 'Math.sign', 'sin': 'Math.sin', 'sinh': 'Math.sinh', 'tan': 'Math.tan', 'tanh': 'Math.tanh', } class JavascriptCodePrinter(CodePrinter): """"A Printer to convert Python expressions to strings of JavaScript code """ printmethod = '_javascript' language = 'JavaScript' _default_settings: dict[str, Any] = { 'order': None, 'full_prec': 'auto', 'precision': 17, 'user_functions': {}, 'human': True, 'allow_unknown_functions': False, 'contract': True, } def __init__(self, settings={}): CodePrinter.__init__(self, settings) self.known_functions = dict(known_functions) userfuncs = settings.get('user_functions', {}) self.known_functions.update(userfuncs) def _rate_index_position(self, p): return p*5 def _get_statement(self, codestring): return "%s;" % codestring def _get_comment(self, text): return "// {}".format(text) def _declare_number_const(self, name, value): return "var {} = {};".format(name, value.evalf(self._settings['precision'])) def _format_code(self, lines): return self.indent_code(lines) def _traverse_matrix_indices(self, mat): rows, cols = mat.shape return ((i, j) for i in range(rows) for j in range(cols)) def _get_loop_opening_ending(self, indices): open_lines = [] close_lines = [] loopstart = "for (var %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){" for i in indices: # Javascript arrays start at 0 and end at dimension-1 open_lines.append(loopstart % { 'varble': self._print(i.label), 'start': self._print(i.lower), 'end': self._print(i.upper + 1)}) close_lines.append("}") return open_lines, close_lines def _print_Pow(self, expr): PREC = precedence(expr) if equal_valued(expr.exp, -1): return '1/%s' % (self.parenthesize(expr.base, PREC)) elif equal_valued(expr.exp, 0.5): return 'Math.sqrt(%s)' % self._print(expr.base) elif expr.exp == S.One/3: return 'Math.cbrt(%s)' % self._print(expr.base) else: return 'Math.pow(%s, %s)' % (self._print(expr.base), self._print(expr.exp)) def _print_Rational(self, expr): p, q = int(expr.p), int(expr.q) return '%d/%d' % (p, q) def _print_Mod(self, expr): num, den = expr.args PREC = precedence(expr) snum, sden = [self.parenthesize(arg, PREC) for arg in expr.args] # % is remainder (same sign as numerator), not modulo (same sign as # denominator), in js. Hence, % only works as modulo if both numbers # have the same sign if (num.is_nonnegative and den.is_nonnegative or num.is_nonpositive and den.is_nonpositive): return f"{snum} % {sden}" return f"(({snum} % {sden}) + {sden}) % {sden}" def _print_Relational(self, expr): lhs_code = self._print(expr.lhs) rhs_code = self._print(expr.rhs) op = expr.rel_op return "{} {} {}".format(lhs_code, op, rhs_code) def _print_Indexed(self, expr): # calculate index for 1d array dims = expr.shape elem = S.Zero offset = S.One for i in reversed(range(expr.rank)): elem += expr.indices[i]*offset offset *= dims[i] return "%s[%s]" % (self._print(expr.base.label), self._print(elem)) def _print_Idx(self, expr): return self._print(expr.label) def _print_Exp1(self, expr): return "Math.E" def _print_Pi(self, expr): return 'Math.PI' def _print_Infinity(self, expr): return 'Number.POSITIVE_INFINITY' def _print_NegativeInfinity(self, expr): return 'Number.NEGATIVE_INFINITY' def _print_Piecewise(self, expr): from sympy.codegen.ast import Assignment if expr.args[-1].cond != True: # We need the last conditional to be a True, otherwise the resulting # function may not return a result. raise ValueError("All Piecewise expressions must contain an " "(expr, True) statement to be used as a default " "condition. Without one, the generated " "expression may not evaluate to anything under " "some condition.") lines = [] if expr.has(Assignment): for i, (e, c) in enumerate(expr.args): if i == 0: lines.append("if (%s) {" % self._print(c)) elif i == len(expr.args) - 1 and c == True: lines.append("else {") else: lines.append("else if (%s) {" % self._print(c)) code0 = self._print(e) lines.append(code0) lines.append("}") return "\n".join(lines) else: # The piecewise was used in an expression, need to do inline # operators. This has the downside that inline operators will # not work for statements that span multiple lines (Matrix or # Indexed expressions). ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c), self._print(e)) for e, c in expr.args[:-1]] last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr) return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)]) def _print_MatrixElement(self, expr): return "{}[{}]".format(self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True), expr.j + expr.i*expr.parent.shape[1]) def indent_code(self, code): """Accepts a string of code or a list of code lines""" if isinstance(code, str): code_lines = self.indent_code(code.splitlines(True)) return ''.join(code_lines) tab = " " inc_token = ('{', '(', '{\n', '(\n') dec_token = ('}', ')') code = [ line.lstrip(' \t') for line in code ] increase = [ int(any(map(line.endswith, inc_token))) for line in code ] decrease = [ int(any(map(line.startswith, dec_token))) for line in code ] pretty = [] level = 0 for n, line in enumerate(code): if line in ('', '\n'): pretty.append(line) continue level -= decrease[n] pretty.append("%s%s" % (tab*level, line)) level += increase[n] return pretty def jscode(expr, assign_to=None, **settings): """Converts an expr to a string of javascript code Parameters ========== expr : Expr A SymPy expression to be converted. assign_to : optional When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, ``Symbol``, ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of line-wrapping, or for expressions that generate multi-line statements. precision : integer, optional The precision for numbers such as pi [default=15]. user_functions : dict, optional A dictionary where keys are ``FunctionClass`` instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, js_function_string)]. See below for examples. human : bool, optional If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True]. contract: bool, optional If True, ``Indexed`` instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True]. Examples ======== >>> from sympy import jscode, symbols, Rational, sin, ceiling, Abs >>> x, tau = symbols("x, tau") >>> jscode((2*tau)**Rational(7, 2)) '8*Math.sqrt(2)*Math.pow(tau, 7/2)' >>> jscode(sin(x), assign_to="s") 's = Math.sin(x);' Custom printing can be defined for certain types by passing a dictionary of "type" : "function" to the ``user_functions`` kwarg. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, js_function_string)]. >>> custom_functions = { ... "ceiling": "CEIL", ... "Abs": [(lambda x: not x.is_integer, "fabs"), ... (lambda x: x.is_integer, "ABS")] ... } >>> jscode(Abs(x) + ceiling(x), user_functions=custom_functions) 'fabs(x) + CEIL(x)' ``Piecewise`` expressions are converted into conditionals. If an ``assign_to`` variable is provided an if statement is created, otherwise the ternary operator is used. Note that if the ``Piecewise`` lacks a default term, represented by ``(expr, True)`` then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything. >>> from sympy import Piecewise >>> expr = Piecewise((x + 1, x > 0), (x, True)) >>> print(jscode(expr, tau)) if (x > 0) { tau = x + 1; } else { tau = x; } Support for loops is provided through ``Indexed`` types. With ``contract=True`` these expressions will be turned into loops, whereas ``contract=False`` will just print the assignment expression that should be looped over: >>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', 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])/(t[i+1]-t[i])) >>> jscode(e.rhs, assign_to=e.lhs, contract=False) 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);' Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions must be provided to ``assign_to``. Note that any expression that can be generated normally can also exist inside a Matrix: >>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) >>> A = MatrixSymbol('A', 3, 1) >>> print(jscode(mat, A)) A[0] = Math.pow(x, 2); if (x > 0) { A[1] = x + 1; } else { A[1] = x; } A[2] = Math.sin(x); """ return JavascriptCodePrinter(settings).doprint(expr, assign_to) def print_jscode(expr, **settings): """Prints the Javascript representation of the given expression. See jscode for the meaning of the optional arguments. """ print(jscode(expr, **settings))
889a8e3eb1e1a898c073a5274fff11ec0e4d15c9fa22613798e4cb4bb5f46d46
""" Julia code printer The `JuliaCodePrinter` converts SymPy expressions into Julia expressions. A complete code generator, which uses `julia_code` extensively, can be found in `sympy.utilities.codegen`. The `codegen` module can be used to generate complete source code files. """ from __future__ import annotations from typing import Any from sympy.core import Mul, Pow, S, Rational from sympy.core.mul import _keep_coeff from sympy.core.numbers import equal_valued from sympy.printing.codeprinter import CodePrinter from sympy.printing.precedence import precedence, PRECEDENCE from re import search # List of known functions. First, those that have the same name in # SymPy and Julia. This is almost certainly incomplete! known_fcns_src1 = ["sin", "cos", "tan", "cot", "sec", "csc", "asin", "acos", "atan", "acot", "asec", "acsc", "sinh", "cosh", "tanh", "coth", "sech", "csch", "asinh", "acosh", "atanh", "acoth", "asech", "acsch", "sinc", "atan2", "sign", "floor", "log", "exp", "cbrt", "sqrt", "erf", "erfc", "erfi", "factorial", "gamma", "digamma", "trigamma", "polygamma", "beta", "airyai", "airyaiprime", "airybi", "airybiprime", "besselj", "bessely", "besseli", "besselk", "erfinv", "erfcinv"] # These functions have different names ("SymPy": "Julia"), more # generally a mapping to (argument_conditions, julia_function). known_fcns_src2 = { "Abs": "abs", "ceiling": "ceil", "conjugate": "conj", "hankel1": "hankelh1", "hankel2": "hankelh2", "im": "imag", "re": "real" } class JuliaCodePrinter(CodePrinter): """ A printer to convert expressions to strings of Julia code. """ printmethod = "_julia" language = "Julia" _operators = { 'and': '&&', 'or': '||', 'not': '!', } _default_settings: dict[str, Any] = { 'order': None, 'full_prec': 'auto', 'precision': 17, 'user_functions': {}, 'human': True, 'allow_unknown_functions': False, 'contract': True, 'inline': True, } # Note: contract is for expressing tensors as loops (if True), or just # assignment (if False). FIXME: this should be looked a more carefully # for Julia. def __init__(self, settings={}): super().__init__(settings) self.known_functions = dict(zip(known_fcns_src1, known_fcns_src1)) self.known_functions.update(dict(known_fcns_src2)) userfuncs = settings.get('user_functions', {}) self.known_functions.update(userfuncs) def _rate_index_position(self, p): return p*5 def _get_statement(self, codestring): return "%s" % codestring def _get_comment(self, text): return "# {}".format(text) def _declare_number_const(self, name, value): return "const {} = {}".format(name, value) def _format_code(self, lines): return self.indent_code(lines) def _traverse_matrix_indices(self, mat): # Julia uses Fortran order (column-major) rows, cols = mat.shape return ((i, j) for j in range(cols) for i in range(rows)) def _get_loop_opening_ending(self, indices): open_lines = [] close_lines = [] for i in indices: # Julia arrays start at 1 and end at dimension var, start, stop = map(self._print, [i.label, i.lower + 1, i.upper + 1]) open_lines.append("for %s = %s:%s" % (var, start, stop)) close_lines.append("end") return open_lines, close_lines def _print_Mul(self, expr): # print complex numbers nicely in Julia if (expr.is_number and expr.is_imaginary and expr.as_coeff_Mul()[0].is_integer): return "%sim" % self._print(-S.ImaginaryUnit*expr) # cribbed from str.py prec = precedence(expr) 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 and item.p == 1: # Save the Rational type in julia Unless the numerator is 1. # For example: # julia_code(Rational(3, 7)*x) --> (3 // 7) * x # julia_code(x/3) --> x / 3 but not x * (1 // 3) b.append(Rational(item.q)) else: a.append(item) a = a or [S.One] a_str = [self.parenthesize(x, prec) for x in a] b_str = [self.parenthesize(x, prec) 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)] # from here it differs from str.py to deal with "*" and ".*" def multjoin(a, a_str): # here we probably are assuming the constants will come first r = a_str[0] for i in range(1, len(a)): mulsym = '*' if a[i-1].is_number else '.*' r = "%s %s %s" % (r, mulsym, a_str[i]) return r if not b: return sign + multjoin(a, a_str) elif len(b) == 1: divsym = '/' if b[0].is_number else './' return "%s %s %s" % (sign+multjoin(a, a_str), divsym, b_str[0]) else: divsym = '/' if all(bi.is_number for bi in b) else './' return "%s %s (%s)" % (sign + multjoin(a, a_str), divsym, multjoin(b, b_str)) def _print_Relational(self, expr): lhs_code = self._print(expr.lhs) rhs_code = self._print(expr.rhs) op = expr.rel_op return "{} {} {}".format(lhs_code, op, rhs_code) def _print_Pow(self, expr): powsymbol = '^' if all(x.is_number for x in expr.args) else '.^' PREC = precedence(expr) if equal_valued(expr.exp, 0.5): return "sqrt(%s)" % self._print(expr.base) if expr.is_commutative: if equal_valued(expr.exp, -0.5): sym = '/' if expr.base.is_number else './' return "1 %s sqrt(%s)" % (sym, self._print(expr.base)) if equal_valued(expr.exp, -1): sym = '/' if expr.base.is_number else './' return "1 %s %s" % (sym, self.parenthesize(expr.base, PREC)) return '%s %s %s' % (self.parenthesize(expr.base, PREC), powsymbol, self.parenthesize(expr.exp, PREC)) def _print_MatPow(self, expr): PREC = precedence(expr) return '%s ^ %s' % (self.parenthesize(expr.base, PREC), self.parenthesize(expr.exp, PREC)) def _print_Pi(self, expr): if self._settings["inline"]: return "pi" else: return super()._print_NumberSymbol(expr) def _print_ImaginaryUnit(self, expr): return "im" def _print_Exp1(self, expr): if self._settings["inline"]: return "e" else: return super()._print_NumberSymbol(expr) def _print_EulerGamma(self, expr): if self._settings["inline"]: return "eulergamma" else: return super()._print_NumberSymbol(expr) def _print_Catalan(self, expr): if self._settings["inline"]: return "catalan" else: return super()._print_NumberSymbol(expr) def _print_GoldenRatio(self, expr): if self._settings["inline"]: return "golden" else: return super()._print_NumberSymbol(expr) def _print_Assignment(self, expr): from sympy.codegen.ast import Assignment from sympy.functions.elementary.piecewise import Piecewise from sympy.tensor.indexed import IndexedBase # Copied from codeprinter, but remove special MatrixSymbol treatment lhs = expr.lhs rhs = expr.rhs # We special case assignments that take multiple lines if not self._settings["inline"] and isinstance(expr.rhs, Piecewise): # Here we modify Piecewise so each expression is now # an Assignment, and then continue on the print. expressions = [] conditions = [] for (e, c) in rhs.args: expressions.append(Assignment(lhs, e)) conditions.append(c) temp = Piecewise(*zip(expressions, conditions)) return self._print(temp) if self._settings["contract"] and (lhs.has(IndexedBase) or rhs.has(IndexedBase)): # Here we check if there is looping to be done, and if so # print the required loops. return self._doprint_loops(rhs, lhs) else: lhs_code = self._print(lhs) rhs_code = self._print(rhs) return self._get_statement("%s = %s" % (lhs_code, rhs_code)) def _print_Infinity(self, expr): return 'Inf' def _print_NegativeInfinity(self, expr): return '-Inf' def _print_NaN(self, expr): return 'NaN' def _print_list(self, expr): return 'Any[' + ', '.join(self._print(a) for a in expr) + ']' def _print_tuple(self, expr): if len(expr) == 1: return "(%s,)" % self._print(expr[0]) else: return "(%s)" % self.stringify(expr, ", ") _print_Tuple = _print_tuple def _print_BooleanTrue(self, expr): return "true" def _print_BooleanFalse(self, expr): return "false" def _print_bool(self, expr): return str(expr).lower() # Could generate quadrature code for definite Integrals? #_print_Integral = _print_not_supported def _print_MatrixBase(self, A): # Handle zero dimensions: if S.Zero in A.shape: return 'zeros(%s, %s)' % (A.rows, A.cols) elif (A.rows, A.cols) == (1, 1): return "[%s]" % A[0, 0] elif A.rows == 1: return "[%s]" % A.table(self, rowstart='', rowend='', colsep=' ') elif A.cols == 1: # note .table would unnecessarily equispace the rows return "[%s]" % ", ".join([self._print(a) for a in A]) return "[%s]" % A.table(self, rowstart='', rowend='', rowsep=';\n', colsep=' ') def _print_SparseRepMatrix(self, A): from sympy.matrices import Matrix L = A.col_list(); # make row vectors of the indices and entries I = Matrix([k[0] + 1 for k in L]) J = Matrix([k[1] + 1 for k in L]) AIJ = Matrix([k[2] for k in L]) return "sparse(%s, %s, %s, %s, %s)" % (self._print(I), self._print(J), self._print(AIJ), A.rows, A.cols) def _print_MatrixElement(self, expr): return self.parenthesize(expr.parent, PRECEDENCE["Atom"], strict=True) \ + '[%s,%s]' % (expr.i + 1, expr.j + 1) def _print_MatrixSlice(self, expr): def strslice(x, lim): l = x[0] + 1 h = x[1] step = x[2] lstr = self._print(l) hstr = 'end' if h == lim else self._print(h) if step == 1: if l == 1 and h == lim: return ':' if l == h: return lstr else: return lstr + ':' + hstr else: return ':'.join((lstr, self._print(step), hstr)) return (self._print(expr.parent) + '[' + strslice(expr.rowslice, expr.parent.shape[0]) + ',' + strslice(expr.colslice, expr.parent.shape[1]) + ']') def _print_Indexed(self, expr): inds = [ self._print(i) for i in expr.indices ] return "%s[%s]" % (self._print(expr.base.label), ",".join(inds)) def _print_Idx(self, expr): return self._print(expr.label) def _print_Identity(self, expr): return "eye(%s)" % self._print(expr.shape[0]) def _print_HadamardProduct(self, expr): return ' .* '.join([self.parenthesize(arg, precedence(expr)) for arg in expr.args]) def _print_HadamardPower(self, expr): PREC = precedence(expr) return '.**'.join([ self.parenthesize(expr.base, PREC), self.parenthesize(expr.exp, PREC) ]) def _print_Rational(self, expr): if expr.q == 1: return str(expr.p) return "%s // %s" % (expr.p, expr.q) # Note: as of 2022, Julia doesn't have spherical Bessel functions def _print_jn(self, expr): from sympy.functions import sqrt, besselj x = expr.argument expr2 = sqrt(S.Pi/(2*x))*besselj(expr.order + S.Half, x) return self._print(expr2) def _print_yn(self, expr): from sympy.functions import sqrt, bessely x = expr.argument expr2 = sqrt(S.Pi/(2*x))*bessely(expr.order + S.Half, x) return self._print(expr2) def _print_Piecewise(self, expr): if expr.args[-1].cond != True: # We need the last conditional to be a True, otherwise the resulting # function may not return a result. raise ValueError("All Piecewise expressions must contain an " "(expr, True) statement to be used as a default " "condition. Without one, the generated " "expression may not evaluate to anything under " "some condition.") lines = [] if self._settings["inline"]: # Express each (cond, expr) pair in a nested Horner form: # (condition) .* (expr) + (not cond) .* (<others>) # Expressions that result in multiple statements won't work here. ecpairs = ["({}) ? ({}) :".format (self._print(c), self._print(e)) for e, c in expr.args[:-1]] elast = " (%s)" % self._print(expr.args[-1].expr) pw = "\n".join(ecpairs) + elast # Note: current need these outer brackets for 2*pw. Would be # nicer to teach parenthesize() to do this for us when needed! return "(" + pw + ")" else: for i, (e, c) in enumerate(expr.args): if i == 0: lines.append("if (%s)" % self._print(c)) elif i == len(expr.args) - 1 and c == True: lines.append("else") else: lines.append("elseif (%s)" % self._print(c)) code0 = self._print(e) lines.append(code0) if i == len(expr.args) - 1: lines.append("end") return "\n".join(lines) 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 indent_code(self, code): """Accepts a string of code or a list of code lines""" # code mostly copied from ccode if isinstance(code, str): code_lines = self.indent_code(code.splitlines(True)) return ''.join(code_lines) tab = " " inc_regex = ('^function ', '^if ', '^elseif ', '^else$', '^for ') dec_regex = ('^end$', '^elseif ', '^else$') # pre-strip left-space from the code code = [ line.lstrip(' \t') for line in code ] increase = [ int(any(search(re, line) for re in inc_regex)) for line in code ] decrease = [ int(any(search(re, line) for re in dec_regex)) for line in code ] pretty = [] level = 0 for n, line in enumerate(code): if line in ('', '\n'): pretty.append(line) continue level -= decrease[n] pretty.append("%s%s" % (tab*level, line)) level += increase[n] return pretty def julia_code(expr, assign_to=None, **settings): r"""Converts `expr` to a string of Julia code. Parameters ========== expr : Expr A SymPy expression to be converted. assign_to : optional When given, the argument is used as the name of the variable to which the expression is assigned. Can be a string, ``Symbol``, ``MatrixSymbol``, or ``Indexed`` type. This can be helpful for expressions that generate multi-line statements. precision : integer, optional The precision for numbers such as pi [default=16]. user_functions : dict, optional A dictionary where keys are ``FunctionClass`` instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples. human : bool, optional If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True]. contract: bool, optional If True, ``Indexed`` instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True]. inline: bool, optional If True, we try to create single-statement code instead of multiple statements. [default=True]. Examples ======== >>> from sympy import julia_code, symbols, sin, pi >>> x = symbols('x') >>> julia_code(sin(x).series(x).removeO()) 'x .^ 5 / 120 - x .^ 3 / 6 + x' >>> from sympy import Rational, ceiling >>> x, y, tau = symbols("x, y, tau") >>> julia_code((2*tau)**Rational(7, 2)) '8 * sqrt(2) * tau .^ (7 // 2)' Note that element-wise (Hadamard) operations are used by default between symbols. This is because its possible in Julia to write "vectorized" code. It is harmless if the values are scalars. >>> julia_code(sin(pi*x*y), assign_to="s") 's = sin(pi * x .* y)' If you need a matrix product "*" or matrix power "^", you can specify the symbol as a ``MatrixSymbol``. >>> from sympy import Symbol, MatrixSymbol >>> n = Symbol('n', integer=True, positive=True) >>> A = MatrixSymbol('A', n, n) >>> julia_code(3*pi*A**3) '(3 * pi) * A ^ 3' This class uses several rules to decide which symbol to use a product. Pure numbers use "*", Symbols use ".*" and MatrixSymbols use "*". A HadamardProduct can be used to specify componentwise multiplication ".*" of two MatrixSymbols. There is currently there is no easy way to specify scalar symbols, so sometimes the code might have some minor cosmetic issues. For example, suppose x and y are scalars and A is a Matrix, then while a human programmer might write "(x^2*y)*A^3", we generate: >>> julia_code(x**2*y*A**3) '(x .^ 2 .* y) * A ^ 3' Matrices are supported using Julia inline notation. When using ``assign_to`` with matrices, the name can be specified either as a string or as a ``MatrixSymbol``. The dimensions must align in the latter case. >>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([[x**2, sin(x), ceiling(x)]]) >>> julia_code(mat, assign_to='A') 'A = [x .^ 2 sin(x) ceil(x)]' ``Piecewise`` expressions are implemented with logical masking by default. Alternatively, you can pass "inline=False" to use if-else conditionals. Note that if the ``Piecewise`` lacks a default term, represented by ``(expr, True)`` then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything. >>> from sympy import Piecewise >>> pw = Piecewise((x + 1, x > 0), (x, True)) >>> julia_code(pw, assign_to=tau) 'tau = ((x > 0) ? (x + 1) : (x))' Note that any expression that can be generated normally can also exist inside a Matrix: >>> mat = Matrix([[x**2, pw, sin(x)]]) >>> julia_code(mat, assign_to='A') 'A = [x .^ 2 ((x > 0) ? (x + 1) : (x)) sin(x)]' Custom printing can be defined for certain types by passing a dictionary of "type" : "function" to the ``user_functions`` kwarg. Alternatively, the dictionary value can be a list of tuples i.e., [(argument_test, cfunction_string)]. This can be used to call a custom Julia function. >>> from sympy import Function >>> f = Function('f') >>> g = Function('g') >>> custom_functions = { ... "f": "existing_julia_fcn", ... "g": [(lambda x: x.is_Matrix, "my_mat_fcn"), ... (lambda x: not x.is_Matrix, "my_fcn")] ... } >>> mat = Matrix([[1, x]]) >>> julia_code(f(x) + g(x) + g(mat), user_functions=custom_functions) 'existing_julia_fcn(x) + my_fcn(x) + my_mat_fcn([1 x])' Support for loops is provided through ``Indexed`` types. With ``contract=True`` these expressions will be turned into loops, whereas ``contract=False`` will just print the assignment expression that should be looped over: >>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', 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])/(t[i+1]-t[i])) >>> julia_code(e.rhs, assign_to=e.lhs, contract=False) 'Dy[i] = (y[i + 1] - y[i]) ./ (t[i + 1] - t[i])' """ return JuliaCodePrinter(settings).doprint(expr, assign_to) def print_julia_code(expr, **settings): """Prints the Julia representation of the given expression. See `julia_code` for the meaning of the optional arguments. """ print(julia_code(expr, **settings))
c8e6f03da10c7693edc72bf9572549149b630dd9b41abf313d0821e4962eb834
from __future__ import annotations from sympy.core import Basic, S from sympy.core.function import Lambda from sympy.core.numbers import equal_valued from sympy.printing.codeprinter import CodePrinter from sympy.printing.precedence import precedence from functools import reduce known_functions = { 'Abs': 'abs', 'sin': 'sin', 'cos': 'cos', 'tan': 'tan', 'acos': 'acos', 'asin': 'asin', 'atan': 'atan', 'atan2': 'atan', 'ceiling': 'ceil', 'floor': 'floor', 'sign': 'sign', 'exp': 'exp', 'log': 'log', 'add': 'add', 'sub': 'sub', 'mul': 'mul', 'pow': 'pow' } class GLSLPrinter(CodePrinter): """ Rudimentary, generic GLSL printing tools. Additional settings: 'use_operators': Boolean (should the printer use operators for +,-,*, or functions?) """ _not_supported: set[Basic] = set() printmethod = "_glsl" language = "GLSL" _default_settings = { 'use_operators': True, 'zero': 0, 'mat_nested': False, 'mat_separator': ',\n', 'mat_transpose': False, 'array_type': 'float', 'glsl_types': True, 'order': None, 'full_prec': 'auto', 'precision': 9, 'user_functions': {}, 'human': True, 'allow_unknown_functions': False, 'contract': True, 'error_on_reserved': False, 'reserved_word_suffix': '_', } def __init__(self, settings={}): CodePrinter.__init__(self, settings) self.known_functions = dict(known_functions) userfuncs = settings.get('user_functions', {}) self.known_functions.update(userfuncs) def _rate_index_position(self, p): return p*5 def _get_statement(self, codestring): return "%s;" % codestring def _get_comment(self, text): return "// {}".format(text) def _declare_number_const(self, name, value): return "float {} = {};".format(name, value) def _format_code(self, lines): return self.indent_code(lines) def indent_code(self, code): """Accepts a string of code or a list of code lines""" if isinstance(code, str): code_lines = self.indent_code(code.splitlines(True)) return ''.join(code_lines) tab = " " inc_token = ('{', '(', '{\n', '(\n') dec_token = ('}', ')') code = [line.lstrip(' \t') for line in code] increase = [int(any(map(line.endswith, inc_token))) for line in code] decrease = [int(any(map(line.startswith, dec_token))) for line in code] pretty = [] level = 0 for n, line in enumerate(code): if line in ('', '\n'): pretty.append(line) continue level -= decrease[n] pretty.append("%s%s" % (tab*level, line)) level += increase[n] return pretty def _print_MatrixBase(self, mat): mat_separator = self._settings['mat_separator'] mat_transpose = self._settings['mat_transpose'] column_vector = (mat.rows == 1) if mat_transpose else (mat.cols == 1) A = mat.transpose() if mat_transpose != column_vector else mat glsl_types = self._settings['glsl_types'] array_type = self._settings['array_type'] array_size = A.cols*A.rows array_constructor = "{}[{}]".format(array_type, array_size) if A.cols == 1: return self._print(A[0]); if A.rows <= 4 and A.cols <= 4 and glsl_types: if A.rows == 1: return "vec{}{}".format( A.cols, A.table(self,rowstart='(',rowend=')') ) elif A.rows == A.cols: return "mat{}({})".format( A.rows, A.table(self,rowsep=', ', rowstart='',rowend='') ) else: return "mat{}x{}({})".format( A.cols, A.rows, A.table(self,rowsep=', ', rowstart='',rowend='') ) elif S.One in A.shape: return "{}({})".format( array_constructor, A.table(self,rowsep=mat_separator,rowstart='',rowend='') ) elif not self._settings['mat_nested']: return "{}(\n{}\n) /* a {}x{} matrix */".format( array_constructor, A.table(self,rowsep=mat_separator,rowstart='',rowend=''), A.rows, A.cols ) elif self._settings['mat_nested']: return "{}[{}][{}](\n{}\n)".format( array_type, A.rows, A.cols, A.table(self,rowsep=mat_separator,rowstart='float[](',rowend=')') ) def _print_SparseRepMatrix(self, mat): # do not allow sparse matrices to be made dense return self._print_not_supported(mat) def _traverse_matrix_indices(self, mat): mat_transpose = self._settings['mat_transpose'] if mat_transpose: rows,cols = mat.shape else: cols,rows = mat.shape return ((i, j) for i in range(cols) for j in range(rows)) def _print_MatrixElement(self, expr): # print('begin _print_MatrixElement') nest = self._settings['mat_nested']; glsl_types = self._settings['glsl_types']; mat_transpose = self._settings['mat_transpose']; if mat_transpose: cols,rows = expr.parent.shape i,j = expr.j,expr.i else: rows,cols = expr.parent.shape i,j = expr.i,expr.j pnt = self._print(expr.parent) if glsl_types and ((rows <= 4 and cols <=4) or nest): return "{}[{}][{}]".format(pnt, i, j) else: return "{}[{}]".format(pnt, i + j*rows) def _print_list(self, expr): l = ', '.join(self._print(item) for item in expr) glsl_types = self._settings['glsl_types'] array_type = self._settings['array_type'] array_size = len(expr) array_constructor = '{}[{}]'.format(array_type, array_size) if array_size <= 4 and glsl_types: return 'vec{}({})'.format(array_size, l) else: return '{}({})'.format(array_constructor, l) _print_tuple = _print_list _print_Tuple = _print_list def _get_loop_opening_ending(self, indices): open_lines = [] close_lines = [] loopstart = "for (int %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){" for i in indices: # GLSL arrays start at 0 and end at dimension-1 open_lines.append(loopstart % { 'varble': self._print(i.label), 'start': self._print(i.lower), 'end': self._print(i.upper + 1)}) close_lines.append("}") return open_lines, close_lines def _print_Function_with_args(self, func, func_args): if func in self.known_functions: cond_func = self.known_functions[func] func = None if isinstance(cond_func, str): func = cond_func else: for cond, func in cond_func: if cond(func_args): break if func is not None: try: return func(*[self.parenthesize(item, 0) for item in func_args]) except TypeError: return '{}({})'.format(func, self.stringify(func_args, ", ")) elif isinstance(func, Lambda): # inlined function return self._print(func(*func_args)) else: return self._print_not_supported(func) def _print_Piecewise(self, expr): from sympy.codegen.ast import Assignment if expr.args[-1].cond != True: # We need the last conditional to be a True, otherwise the resulting # function may not return a result. raise ValueError("All Piecewise expressions must contain an " "(expr, True) statement to be used as a default " "condition. Without one, the generated " "expression may not evaluate to anything under " "some condition.") lines = [] if expr.has(Assignment): for i, (e, c) in enumerate(expr.args): if i == 0: lines.append("if (%s) {" % self._print(c)) elif i == len(expr.args) - 1 and c == True: lines.append("else {") else: lines.append("else if (%s) {" % self._print(c)) code0 = self._print(e) lines.append(code0) lines.append("}") return "\n".join(lines) else: # The piecewise was used in an expression, need to do inline # operators. This has the downside that inline operators will # not work for statements that span multiple lines (Matrix or # Indexed expressions). ecpairs = ["((%s) ? (\n%s\n)\n" % (self._print(c), self._print(e)) for e, c in expr.args[:-1]] last_line = ": (\n%s\n)" % self._print(expr.args[-1].expr) return ": ".join(ecpairs) + last_line + " ".join([")"*len(ecpairs)]) def _print_Idx(self, expr): return self._print(expr.label) def _print_Indexed(self, expr): # calculate index for 1d array dims = expr.shape elem = S.Zero offset = S.One for i in reversed(range(expr.rank)): elem += expr.indices[i]*offset offset *= dims[i] return "{}[{}]".format( self._print(expr.base.label), self._print(elem) ) def _print_Pow(self, expr): PREC = precedence(expr) if equal_valued(expr.exp, -1): return '1.0/%s' % (self.parenthesize(expr.base, PREC)) elif equal_valued(expr.exp, 0.5): return 'sqrt(%s)' % self._print(expr.base) else: try: e = self._print(float(expr.exp)) except TypeError: e = self._print(expr.exp) return self._print_Function_with_args('pow', ( self._print(expr.base), e )) def _print_int(self, expr): return str(float(expr)) def _print_Rational(self, expr): return "{}.0/{}.0".format(expr.p, expr.q) def _print_Relational(self, expr): lhs_code = self._print(expr.lhs) rhs_code = self._print(expr.rhs) op = expr.rel_op return "{} {} {}".format(lhs_code, op, rhs_code) def _print_Add(self, expr, order=None): if self._settings['use_operators']: return CodePrinter._print_Add(self, expr, order=order) terms = expr.as_ordered_terms() def partition(p,l): return reduce(lambda x, y: (x[0]+[y], x[1]) if p(y) else (x[0], x[1]+[y]), l, ([], [])) def add(a,b): return self._print_Function_with_args('add', (a, b)) # return self.known_functions['add']+'(%s, %s)' % (a,b) neg, pos = partition(lambda arg: arg.could_extract_minus_sign(), terms) if pos: s = pos = reduce(lambda a,b: add(a,b), map(lambda t: self._print(t),pos)) else: s = pos = self._print(self._settings['zero']) if neg: # sum the absolute values of the negative terms neg = reduce(lambda a,b: add(a,b), map(lambda n: self._print(-n),neg)) # then subtract them from the positive terms s = self._print_Function_with_args('sub', (pos,neg)) # s = self.known_functions['sub']+'(%s, %s)' % (pos,neg) return s def _print_Mul(self, expr, **kwargs): if self._settings['use_operators']: return CodePrinter._print_Mul(self, expr, **kwargs) terms = expr.as_ordered_factors() def mul(a,b): # return self.known_functions['mul']+'(%s, %s)' % (a,b) return self._print_Function_with_args('mul', (a,b)) s = reduce(lambda a,b: mul(a,b), map(lambda t: self._print(t), terms)) return s def glsl_code(expr,assign_to=None,**settings): """Converts an expr to a string of GLSL code Parameters ========== expr : Expr A SymPy expression to be converted. assign_to : optional When given, the argument is used for naming the variable or variables to which the expression is assigned. Can be a string, ``Symbol``, ``MatrixSymbol`` or ``Indexed`` type object. In cases where ``expr`` would be printed as an array, a list of string or ``Symbol`` objects can also be passed. This is helpful in case of line-wrapping, or for expressions that generate multi-line statements. It can also be used to spread an array-like expression into multiple assignments. use_operators: bool, optional If set to False, then *,/,+,- operators will be replaced with functions mul, add, and sub, which must be implemented by the user, e.g. for implementing non-standard rings or emulated quad/octal precision. [default=True] glsl_types: bool, optional Set this argument to ``False`` in order to avoid using the ``vec`` and ``mat`` types. The printer will instead use arrays (or nested arrays). [default=True] mat_nested: bool, optional GLSL version 4.3 and above support nested arrays (arrays of arrays). Set this to ``True`` to render matrices as nested arrays. [default=False] mat_separator: str, optional By default, matrices are rendered with newlines using this separator, making them easier to read, but less compact. By removing the newline this option can be used to make them more vertically compact. [default=',\n'] mat_transpose: bool, optional GLSL's matrix multiplication implementation assumes column-major indexing. By default, this printer ignores that convention. Setting this option to ``True`` transposes all matrix output. [default=False] array_type: str, optional The GLSL array constructor type. [default='float'] precision : integer, optional The precision for numbers such as pi [default=15]. user_functions : dict, optional A dictionary where keys are ``FunctionClass`` instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, js_function_string)]. See below for examples. human : bool, optional If True, the result is a single string that may contain some constant declarations for the number symbols. If False, the same information is returned in a tuple of (symbols_to_declare, not_supported_functions, code_text). [default=True]. contract: bool, optional If True, ``Indexed`` instances are assumed to obey tensor contraction rules and the corresponding nested loops over indices are generated. Setting contract=False will not generate loops, instead the user is responsible to provide values for the indices in the code. [default=True]. Examples ======== >>> from sympy import glsl_code, symbols, Rational, sin, ceiling, Abs >>> x, tau = symbols("x, tau") >>> glsl_code((2*tau)**Rational(7, 2)) '8*sqrt(2)*pow(tau, 3.5)' >>> glsl_code(sin(x), assign_to="float y") 'float y = sin(x);' Various GLSL types are supported: >>> from sympy import Matrix, glsl_code >>> glsl_code(Matrix([1,2,3])) 'vec3(1, 2, 3)' >>> glsl_code(Matrix([[1, 2],[3, 4]])) 'mat2(1, 2, 3, 4)' Pass ``mat_transpose = True`` to switch to column-major indexing: >>> glsl_code(Matrix([[1, 2],[3, 4]]), mat_transpose = True) 'mat2(1, 3, 2, 4)' By default, larger matrices get collapsed into float arrays: >>> print(glsl_code( Matrix([[1,2,3,4,5],[6,7,8,9,10]]) )) float[10]( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ) /* a 2x5 matrix */ The type of array constructor used to print GLSL arrays can be controlled via the ``array_type`` parameter: >>> glsl_code(Matrix([1,2,3,4,5]), array_type='int') 'int[5](1, 2, 3, 4, 5)' Passing a list of strings or ``symbols`` to the ``assign_to`` parameter will yield a multi-line assignment for each item in an array-like expression: >>> x_struct_members = symbols('x.a x.b x.c x.d') >>> print(glsl_code(Matrix([1,2,3,4]), assign_to=x_struct_members)) x.a = 1; x.b = 2; x.c = 3; x.d = 4; This could be useful in cases where it's desirable to modify members of a GLSL ``Struct``. It could also be used to spread items from an array-like expression into various miscellaneous assignments: >>> misc_assignments = ('x[0]', 'x[1]', 'float y', 'float z') >>> print(glsl_code(Matrix([1,2,3,4]), assign_to=misc_assignments)) x[0] = 1; x[1] = 2; float y = 3; float z = 4; Passing ``mat_nested = True`` instead prints out nested float arrays, which are supported in GLSL 4.3 and above. >>> mat = Matrix([ ... [ 0, 1, 2], ... [ 3, 4, 5], ... [ 6, 7, 8], ... [ 9, 10, 11], ... [12, 13, 14]]) >>> print(glsl_code( mat, mat_nested = True )) float[5][3]( float[]( 0, 1, 2), float[]( 3, 4, 5), float[]( 6, 7, 8), float[]( 9, 10, 11), float[](12, 13, 14) ) Custom printing can be defined for certain types by passing a dictionary of "type" : "function" to the ``user_functions`` kwarg. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, js_function_string)]. >>> custom_functions = { ... "ceiling": "CEIL", ... "Abs": [(lambda x: not x.is_integer, "fabs"), ... (lambda x: x.is_integer, "ABS")] ... } >>> glsl_code(Abs(x) + ceiling(x), user_functions=custom_functions) 'fabs(x) + CEIL(x)' If further control is needed, addition, subtraction, multiplication and division operators can be replaced with ``add``, ``sub``, and ``mul`` functions. This is done by passing ``use_operators = False``: >>> x,y,z = symbols('x,y,z') >>> glsl_code(x*(y+z), use_operators = False) 'mul(x, add(y, z))' >>> glsl_code(x*(y+z*(x-y)**z), use_operators = False) 'mul(x, add(y, mul(z, pow(sub(x, y), z))))' ``Piecewise`` expressions are converted into conditionals. If an ``assign_to`` variable is provided an if statement is created, otherwise the ternary operator is used. Note that if the ``Piecewise`` lacks a default term, represented by ``(expr, True)`` then an error will be thrown. This is to prevent generating an expression that may not evaluate to anything. >>> from sympy import Piecewise >>> expr = Piecewise((x + 1, x > 0), (x, True)) >>> print(glsl_code(expr, tau)) if (x > 0) { tau = x + 1; } else { tau = x; } Support for loops is provided through ``Indexed`` types. With ``contract=True`` these expressions will be turned into loops, whereas ``contract=False`` will just print the assignment expression that should be looped over: >>> from sympy import Eq, IndexedBase, Idx >>> len_y = 5 >>> y = IndexedBase('y', shape=(len_y,)) >>> t = IndexedBase('t', 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])/(t[i+1]-t[i])) >>> glsl_code(e.rhs, assign_to=e.lhs, contract=False) 'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);' >>> from sympy import Matrix, MatrixSymbol >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)]) >>> A = MatrixSymbol('A', 3, 1) >>> print(glsl_code(mat, A)) A[0][0] = pow(x, 2.0); if (x > 0) { A[1][0] = x + 1; } else { A[1][0] = x; } A[2][0] = sin(x); """ return GLSLPrinter(settings).doprint(expr,assign_to) def print_glsl(expr, **settings): """Prints the GLSL representation of the given expression. See GLSLPrinter init function for settings. """ print(glsl_code(expr, **settings))
547d1a6c5d49428bc9f3115dafbf4e6f6e8439d6e089600a8d40cee6fd989639
""" Integral Transforms """ from functools import reduce, wraps from itertools import repeat from sympy.core import S, pi from sympy.core.add import Add from sympy.core.function import ( AppliedUndef, count_ops, expand, expand_mul, Function) from sympy.core.mul import Mul from sympy.core.numbers import igcd, ilcm from sympy.core.sorting import default_sort_key from sympy.core.symbol import Dummy from sympy.core.traversal import postorder_traversal from sympy.functions.combinatorial.factorials import factorial, rf from sympy.functions.elementary.complexes import re, arg, Abs from sympy.functions.elementary.exponential import exp, exp_polar from sympy.functions.elementary.hyperbolic import cosh, coth, sinh, tanh from sympy.functions.elementary.integers import ceiling from sympy.functions.elementary.miscellaneous import Max, Min, sqrt from sympy.functions.elementary.piecewise import piecewise_fold from sympy.functions.elementary.trigonometric import cos, cot, sin, tan from sympy.functions.special.bessel import besselj from sympy.functions.special.delta_functions import Heaviside from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import meijerg from sympy.integrals import integrate, Integral from sympy.integrals.meijerint import _dummy from sympy.logic.boolalg import to_cnf, conjuncts, disjuncts, Or, And from sympy.polys.polyroots import roots from sympy.polys.polytools import factor, Poly from sympy.polys.rootoftools import CRootOf from sympy.utilities.iterables import iterable from sympy.utilities.misc import debug ########################################################################## # Helpers / Utilities ########################################################################## class IntegralTransformError(NotImplementedError): """ Exception raised in relation to problems computing transforms. Explanation =========== This class is mostly used internally; if integrals cannot be computed objects representing unevaluated transforms are usually returned. The hint ``needeval=True`` can be used to disable returning transform objects, and instead raise this exception if an integral cannot be computed. """ def __init__(self, transform, function, msg): super().__init__( "%s Transform could not be computed: %s." % (transform, msg)) self.function = function class IntegralTransform(Function): """ Base class for integral transforms. Explanation =========== This class represents unevaluated transforms. To implement a concrete transform, derive from this class and implement the ``_compute_transform(f, x, s, **hints)`` and ``_as_integral(f, x, s)`` functions. If the transform cannot be computed, raise :obj:`IntegralTransformError`. Also set ``cls._name``. For instance, >>> from sympy import LaplaceTransform >>> LaplaceTransform._name 'Laplace' Implement ``self._collapse_extra`` if your function returns more than just a number and possibly a convergence condition. """ @property def function(self): """ The function to be transformed. """ return self.args[0] @property def function_variable(self): """ The dependent variable of the function to be transformed. """ return self.args[1] @property def transform_variable(self): """ The independent transform variable. """ return self.args[2] @property def free_symbols(self): """ This method returns the symbols that will exist when the transform is evaluated. """ return self.function.free_symbols.union({self.transform_variable}) \ - {self.function_variable} def _compute_transform(self, f, x, s, **hints): raise NotImplementedError def _as_integral(self, f, x, s): raise NotImplementedError def _collapse_extra(self, extra): cond = And(*extra) if cond == False: raise IntegralTransformError(self.__class__.name, None, '') return cond def _try_directly(self, **hints): T = None try_directly = not any(func.has(self.function_variable) for func in self.function.atoms(AppliedUndef)) if try_directly: try: T = self._compute_transform(self.function, self.function_variable, self.transform_variable, **hints) except IntegralTransformError: debug('[IT _try ] Caught IntegralTransformError, returns None') T = None fn = self.function if not fn.is_Add: fn = expand_mul(fn) return fn, T def doit(self, **hints): """ Try to evaluate the transform in closed form. Explanation =========== This general function handles linearity, but apart from that leaves pretty much everything to _compute_transform. Standard hints are the following: - ``simplify``: whether or not to simplify the result - ``noconds``: if True, do not return convergence conditions - ``needeval``: if True, raise IntegralTransformError instead of returning IntegralTransform objects The default values of these hints depend on the concrete transform, usually the default is ``(simplify, noconds, needeval) = (True, False, False)``. """ needeval = hints.pop('needeval', False) simplify = hints.pop('simplify', True) hints['simplify'] = simplify fn, T = self._try_directly(**hints) if T is not None: return T if fn.is_Add: hints['needeval'] = needeval res = [self.__class__(*([x] + list(self.args[1:]))).doit(**hints) for x in fn.args] extra = [] ress = [] for x in res: if not isinstance(x, tuple): x = [x] ress.append(x[0]) if len(x) == 2: # only a condition extra.append(x[1]) elif len(x) > 2: # some region parameters and a condition (Mellin, Laplace) extra += [x[1:]] if simplify==True: res = Add(*ress).simplify() else: res = Add(*ress) if not extra: return res try: extra = self._collapse_extra(extra) if iterable(extra): return tuple([res]) + tuple(extra) else: return (res, extra) except IntegralTransformError: pass if needeval: raise IntegralTransformError( self.__class__._name, self.function, 'needeval') # TODO handle derivatives etc # pull out constant coefficients coeff, rest = fn.as_coeff_mul(self.function_variable) return coeff*self.__class__(*([Mul(*rest)] + list(self.args[1:]))) @property def as_integral(self): return self._as_integral(self.function, self.function_variable, self.transform_variable) def _eval_rewrite_as_Integral(self, *args, **kwargs): return self.as_integral def _simplify(expr, doit): if doit: from sympy.simplify import simplify from sympy.simplify.powsimp import powdenest return simplify(powdenest(piecewise_fold(expr), polar=True)) return expr def _noconds_(default): """ This is a decorator generator for dropping convergence conditions. Explanation =========== Suppose you define a function ``transform(*args)`` which returns a tuple of the form ``(result, cond1, cond2, ...)``. Decorating it ``@_noconds_(default)`` will add a new keyword argument ``noconds`` to it. If ``noconds=True``, the return value will be altered to be only ``result``, whereas if ``noconds=False`` the return value will not be altered. The default value of the ``noconds`` keyword will be ``default`` (i.e. the argument of this function). """ def make_wrapper(func): @wraps(func) def wrapper(*args, noconds=default, **kwargs): res = func(*args, **kwargs) if noconds: return res[0] return res return wrapper return make_wrapper _noconds = _noconds_(False) ########################################################################## # Mellin Transform ########################################################################## def _default_integrator(f, x): return integrate(f, (x, S.Zero, S.Infinity)) @_noconds def _mellin_transform(f, x, s_, integrator=_default_integrator, simplify=True): """ Backend function to compute Mellin transforms. """ # We use a fresh dummy, because assumptions on s might drop conditions on # convergence of the integral. s = _dummy('s', 'mellin-transform', f) F = integrator(x**(s - 1) * f, x) if not F.has(Integral): return _simplify(F.subs(s, s_), simplify), (S.NegativeInfinity, S.Infinity), S.true if not F.is_Piecewise: # XXX can this work if integration gives continuous result now? raise IntegralTransformError('Mellin', f, 'could not compute integral') F, cond = F.args[0] if F.has(Integral): raise IntegralTransformError( 'Mellin', f, 'integral in unexpected form') def process_conds(cond): """ Turn ``cond`` into a strip (a, b), and auxiliary conditions. """ from sympy.solvers.inequalities import _solve_inequality a = S.NegativeInfinity b = S.Infinity aux = S.true conds = conjuncts(to_cnf(cond)) t = Dummy('t', real=True) for c in conds: a_ = S.Infinity b_ = S.NegativeInfinity aux_ = [] for d in disjuncts(c): d_ = d.replace( re, lambda x: x.as_real_imag()[0]).subs(re(s), t) if not d.is_Relational or \ d.rel_op in ('==', '!=') \ or d_.has(s) or not d_.has(t): aux_ += [d] continue soln = _solve_inequality(d_, t) if not soln.is_Relational or \ soln.rel_op in ('==', '!='): aux_ += [d] continue if soln.lts == t: b_ = Max(soln.gts, b_) else: a_ = Min(soln.lts, a_) if a_ is not S.Infinity and a_ != b: a = Max(a_, a) elif b_ is not S.NegativeInfinity and b_ != a: b = Min(b_, b) else: aux = And(aux, Or(*aux_)) return a, b, aux conds = [process_conds(c) for c in disjuncts(cond)] conds = [x for x in conds if x[2] != False] conds.sort(key=lambda x: (x[0] - x[1], count_ops(x[2]))) if not conds: raise IntegralTransformError('Mellin', f, 'no convergence found') a, b, aux = conds[0] return _simplify(F.subs(s, s_), simplify), (a, b), aux class MellinTransform(IntegralTransform): """ Class representing unevaluated Mellin transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute Mellin transforms, see the :func:`mellin_transform` docstring. """ _name = 'Mellin' def _compute_transform(self, f, x, s, **hints): return _mellin_transform(f, x, s, **hints) def _as_integral(self, f, x, s): return Integral(f*x**(s - 1), (x, S.Zero, S.Infinity)) def _collapse_extra(self, extra): a = [] b = [] cond = [] for (sa, sb), c in extra: a += [sa] b += [sb] cond += [c] res = (Max(*a), Min(*b)), And(*cond) if (res[0][0] >= res[0][1]) == True or res[1] == False: raise IntegralTransformError( 'Mellin', None, 'no combined convergence.') return res def mellin_transform(f, x, s, **hints): r""" Compute the Mellin transform `F(s)` of `f(x)`, .. math :: F(s) = \int_0^\infty x^{s-1} f(x) \mathrm{d}x. For all "sensible" functions, this converges absolutely in a strip `a < \operatorname{Re}(s) < b`. Explanation =========== The Mellin transform is related via change of variables to the Fourier transform, and also to the (bilateral) Laplace transform. This function returns ``(F, (a, b), cond)`` where ``F`` is the Mellin transform of ``f``, ``(a, b)`` is the fundamental strip (as above), and ``cond`` are auxiliary convergence conditions. If the integral cannot be computed in closed form, this function returns an unevaluated :class:`MellinTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. If ``noconds=False``, then only `F` will be returned (i.e. not ``cond``, and also not the strip ``(a, b)``). Examples ======== >>> from sympy import mellin_transform, exp >>> from sympy.abc import x, s >>> mellin_transform(exp(-x), x, s) (gamma(s), (0, oo), True) See Also ======== inverse_mellin_transform, laplace_transform, fourier_transform hankel_transform, inverse_hankel_transform """ return MellinTransform(f, x, s).doit(**hints) def _rewrite_sin(m_n, s, a, b): """ Re-write the sine function ``sin(m*s + n)`` as gamma functions, compatible with the strip (a, b). Return ``(gamma1, gamma2, fac)`` so that ``f == fac/(gamma1 * gamma2)``. Examples ======== >>> from sympy.integrals.transforms import _rewrite_sin >>> from sympy import pi, S >>> from sympy.abc import s >>> _rewrite_sin((pi, 0), s, 0, 1) (gamma(s), gamma(1 - s), pi) >>> _rewrite_sin((pi, 0), s, 1, 0) (gamma(s - 1), gamma(2 - s), -pi) >>> _rewrite_sin((pi, 0), s, -1, 0) (gamma(s + 1), gamma(-s), -pi) >>> _rewrite_sin((pi, pi/2), s, S(1)/2, S(3)/2) (gamma(s - 1/2), gamma(3/2 - s), -pi) >>> _rewrite_sin((pi, pi), s, 0, 1) (gamma(s), gamma(1 - s), -pi) >>> _rewrite_sin((2*pi, 0), s, 0, S(1)/2) (gamma(2*s), gamma(1 - 2*s), pi) >>> _rewrite_sin((2*pi, 0), s, S(1)/2, 1) (gamma(2*s - 1), gamma(2 - 2*s), -pi) """ # (This is a separate function because it is moderately complicated, # and I want to doctest it.) # We want to use pi/sin(pi*x) = gamma(x)*gamma(1-x). # But there is one comlication: the gamma functions determine the # inegration contour in the definition of the G-function. Usually # it would not matter if this is slightly shifted, unless this way # we create an undefined function! # So we try to write this in such a way that the gammas are # eminently on the right side of the strip. m, n = m_n m = expand_mul(m/pi) n = expand_mul(n/pi) r = ceiling(-m*a - n.as_real_imag()[0]) # Don't use re(n), does not expand return gamma(m*s + n + r), gamma(1 - n - r - m*s), (-1)**r*pi class MellinTransformStripError(ValueError): """ Exception raised by _rewrite_gamma. Mainly for internal use. """ pass def _rewrite_gamma(f, s, a, b): """ Try to rewrite the product f(s) as a product of gamma functions, so that the inverse Mellin transform of f can be expressed as a meijer G function. Explanation =========== Return (an, ap), (bm, bq), arg, exp, fac such that G((an, ap), (bm, bq), arg/z**exp)*fac is the inverse Mellin transform of f(s). Raises IntegralTransformError or MellinTransformStripError on failure. It is asserted that f has no poles in the fundamental strip designated by (a, b). One of a and b is allowed to be None. The fundamental strip is important, because it determines the inversion contour. This function can handle exponentials, linear factors, trigonometric functions. This is a helper function for inverse_mellin_transform that will not attempt any transformations on f. Examples ======== >>> from sympy.integrals.transforms import _rewrite_gamma >>> from sympy.abc import s >>> from sympy import oo >>> _rewrite_gamma(s*(s+3)*(s-1), s, -oo, oo) (([], [-3, 0, 1]), ([-2, 1, 2], []), 1, 1, -1) >>> _rewrite_gamma((s-1)**2, s, -oo, oo) (([], [1, 1]), ([2, 2], []), 1, 1, 1) Importance of the fundamental strip: >>> _rewrite_gamma(1/s, s, 0, oo) (([1], []), ([], [0]), 1, 1, 1) >>> _rewrite_gamma(1/s, s, None, oo) (([1], []), ([], [0]), 1, 1, 1) >>> _rewrite_gamma(1/s, s, 0, None) (([1], []), ([], [0]), 1, 1, 1) >>> _rewrite_gamma(1/s, s, -oo, 0) (([], [1]), ([0], []), 1, 1, -1) >>> _rewrite_gamma(1/s, s, None, 0) (([], [1]), ([0], []), 1, 1, -1) >>> _rewrite_gamma(1/s, s, -oo, None) (([], [1]), ([0], []), 1, 1, -1) >>> _rewrite_gamma(2**(-s+3), s, -oo, oo) (([], []), ([], []), 1/2, 1, 8) """ # Our strategy will be as follows: # 1) Guess a constant c such that the inversion integral should be # performed wrt s'=c*s (instead of plain s). Write s for s'. # 2) Process all factors, rewrite them independently as gamma functions in # argument s, or exponentials of s. # 3) Try to transform all gamma functions s.t. they have argument # a+s or a-s. # 4) Check that the resulting G function parameters are valid. # 5) Combine all the exponentials. a_, b_ = S([a, b]) def left(c, is_numer): """ Decide whether pole at c lies to the left of the fundamental strip. """ # heuristically, this is the best chance for us to solve the inequalities c = expand(re(c)) if a_ is None and b_ is S.Infinity: return True if a_ is None: return c < b_ if b_ is None: return c <= a_ if (c >= b_) == True: return False if (c <= a_) == True: return True if is_numer: return None if a_.free_symbols or b_.free_symbols or c.free_symbols: return None # XXX #raise IntegralTransformError('Inverse Mellin', f, # 'Could not determine position of singularity %s' # ' relative to fundamental strip' % c) raise MellinTransformStripError('Pole inside critical strip?') # 1) s_multipliers = [] for g in f.atoms(gamma): if not g.has(s): continue arg = g.args[0] if arg.is_Add: arg = arg.as_independent(s)[1] coeff, _ = arg.as_coeff_mul(s) s_multipliers += [coeff] for g in f.atoms(sin, cos, tan, cot): if not g.has(s): continue arg = g.args[0] if arg.is_Add: arg = arg.as_independent(s)[1] coeff, _ = arg.as_coeff_mul(s) s_multipliers += [coeff/pi] s_multipliers = [Abs(x) if x.is_extended_real else x for x in s_multipliers] common_coefficient = S.One for x in s_multipliers: if not x.is_Rational: common_coefficient = x break s_multipliers = [x/common_coefficient for x in s_multipliers] if not (all(x.is_Rational for x in s_multipliers) and common_coefficient.is_extended_real): raise IntegralTransformError("Gamma", None, "Nonrational multiplier") s_multiplier = common_coefficient/reduce(ilcm, [S(x.q) for x in s_multipliers], S.One) if s_multiplier == common_coefficient: if len(s_multipliers) == 0: s_multiplier = common_coefficient else: s_multiplier = common_coefficient \ *reduce(igcd, [S(x.p) for x in s_multipliers]) f = f.subs(s, s/s_multiplier) fac = S.One/s_multiplier exponent = S.One/s_multiplier if a_ is not None: a_ *= s_multiplier if b_ is not None: b_ *= s_multiplier # 2) numer, denom = f.as_numer_denom() numer = Mul.make_args(numer) denom = Mul.make_args(denom) args = list(zip(numer, repeat(True))) + list(zip(denom, repeat(False))) facs = [] dfacs = [] # *_gammas will contain pairs (a, c) representing Gamma(a*s + c) numer_gammas = [] denom_gammas = [] # exponentials will contain bases for exponentials of s exponentials = [] def exception(fact): return IntegralTransformError("Inverse Mellin", f, "Unrecognised form '%s'." % fact) while args: fact, is_numer = args.pop() if is_numer: ugammas, lgammas = numer_gammas, denom_gammas ufacs = facs else: ugammas, lgammas = denom_gammas, numer_gammas ufacs = dfacs def linear_arg(arg): """ Test if arg is of form a*s+b, raise exception if not. """ if not arg.is_polynomial(s): raise exception(fact) p = Poly(arg, s) if p.degree() != 1: raise exception(fact) return p.all_coeffs() # constants if not fact.has(s): ufacs += [fact] # exponentials elif fact.is_Pow or isinstance(fact, exp): if fact.is_Pow: base = fact.base exp_ = fact.exp else: base = exp_polar(1) exp_ = fact.exp if exp_.is_Integer: cond = is_numer if exp_ < 0: cond = not cond args += [(base, cond)]*Abs(exp_) continue elif not base.has(s): a, b = linear_arg(exp_) if not is_numer: base = 1/base exponentials += [base**a] facs += [base**b] else: raise exception(fact) # linear factors elif fact.is_polynomial(s): p = Poly(fact, s) if p.degree() != 1: # We completely factor the poly. For this we need the roots. # Now roots() only works in some cases (low degree), and CRootOf # only works without parameters. So try both... coeff = p.LT()[1] rs = roots(p, s) if len(rs) != p.degree(): rs = CRootOf.all_roots(p) ufacs += [coeff] args += [(s - c, is_numer) for c in rs] continue a, c = p.all_coeffs() ufacs += [a] c /= -a # Now need to convert s - c if left(c, is_numer): ugammas += [(S.One, -c + 1)] lgammas += [(S.One, -c)] else: ufacs += [-1] ugammas += [(S.NegativeOne, c + 1)] lgammas += [(S.NegativeOne, c)] elif isinstance(fact, gamma): a, b = linear_arg(fact.args[0]) if is_numer: if (a > 0 and (left(-b/a, is_numer) == False)) or \ (a < 0 and (left(-b/a, is_numer) == True)): raise NotImplementedError( 'Gammas partially over the strip.') ugammas += [(a, b)] elif isinstance(fact, sin): # We try to re-write all trigs as gammas. This is not in # general the best strategy, since sometimes this is impossible, # but rewriting as exponentials would work. However trig functions # in inverse mellin transforms usually all come from simplifying # gamma terms, so this should work. a = fact.args[0] if is_numer: # No problem with the poles. gamma1, gamma2, fac_ = gamma(a/pi), gamma(1 - a/pi), pi else: gamma1, gamma2, fac_ = _rewrite_sin(linear_arg(a), s, a_, b_) args += [(gamma1, not is_numer), (gamma2, not is_numer)] ufacs += [fac_] elif isinstance(fact, tan): a = fact.args[0] args += [(sin(a, evaluate=False), is_numer), (sin(pi/2 - a, evaluate=False), not is_numer)] elif isinstance(fact, cos): a = fact.args[0] args += [(sin(pi/2 - a, evaluate=False), is_numer)] elif isinstance(fact, cot): a = fact.args[0] args += [(sin(pi/2 - a, evaluate=False), is_numer), (sin(a, evaluate=False), not is_numer)] else: raise exception(fact) fac *= Mul(*facs)/Mul(*dfacs) # 3) an, ap, bm, bq = [], [], [], [] for gammas, plus, minus, is_numer in [(numer_gammas, an, bm, True), (denom_gammas, bq, ap, False)]: while gammas: a, c = gammas.pop() if a != -1 and a != +1: # We use the gamma function multiplication theorem. p = Abs(S(a)) newa = a/p newc = c/p if not a.is_Integer: raise TypeError("a is not an integer") for k in range(p): gammas += [(newa, newc + k/p)] if is_numer: fac *= (2*pi)**((1 - p)/2) * p**(c - S.Half) exponentials += [p**a] else: fac /= (2*pi)**((1 - p)/2) * p**(c - S.Half) exponentials += [p**(-a)] continue if a == +1: plus.append(1 - c) else: minus.append(c) # 4) # TODO # 5) arg = Mul(*exponentials) # for testability, sort the arguments an.sort(key=default_sort_key) ap.sort(key=default_sort_key) bm.sort(key=default_sort_key) bq.sort(key=default_sort_key) return (an, ap), (bm, bq), arg, exponent, fac @_noconds_(True) def _inverse_mellin_transform(F, s, x_, strip, as_meijerg=False): """ A helper for the real inverse_mellin_transform function, this one here assumes x to be real and positive. """ x = _dummy('t', 'inverse-mellin-transform', F, positive=True) # Actually, we won't try integration at all. Instead we use the definition # of the Meijer G function as a fairly general inverse mellin transform. F = F.rewrite(gamma) for g in [factor(F), expand_mul(F), expand(F)]: if g.is_Add: # do all terms separately ress = [_inverse_mellin_transform(G, s, x, strip, as_meijerg, noconds=False) for G in g.args] conds = [p[1] for p in ress] ress = [p[0] for p in ress] res = Add(*ress) if not as_meijerg: res = factor(res, gens=res.atoms(Heaviside)) return res.subs(x, x_), And(*conds) try: a, b, C, e, fac = _rewrite_gamma(g, s, strip[0], strip[1]) except IntegralTransformError: continue try: G = meijerg(a, b, C/x**e) except ValueError: continue if as_meijerg: h = G else: try: from sympy.simplify import hyperexpand h = hyperexpand(G) except NotImplementedError: raise IntegralTransformError( 'Inverse Mellin', F, 'Could not calculate integral') if h.is_Piecewise and len(h.args) == 3: # XXX we break modularity here! h = Heaviside(x - Abs(C))*h.args[0].args[0] \ + Heaviside(Abs(C) - x)*h.args[1].args[0] # We must ensure that the integral along the line we want converges, # and return that value. # See [L], 5.2 cond = [Abs(arg(G.argument)) < G.delta*pi] # Note: we allow ">=" here, this corresponds to convergence if we let # limits go to oo symmetrically. ">" corresponds to absolute convergence. cond += [And(Or(len(G.ap) != len(G.bq), 0 >= re(G.nu) + 1), Abs(arg(G.argument)) == G.delta*pi)] cond = Or(*cond) if cond == False: raise IntegralTransformError( 'Inverse Mellin', F, 'does not converge') return (h*fac).subs(x, x_), cond raise IntegralTransformError('Inverse Mellin', F, '') _allowed = None class InverseMellinTransform(IntegralTransform): """ Class representing unevaluated inverse Mellin transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse Mellin transforms, see the :func:`inverse_mellin_transform` docstring. """ _name = 'Inverse Mellin' _none_sentinel = Dummy('None') _c = Dummy('c') def __new__(cls, F, s, x, a, b, **opts): if a is None: a = InverseMellinTransform._none_sentinel if b is None: b = InverseMellinTransform._none_sentinel return IntegralTransform.__new__(cls, F, s, x, a, b, **opts) @property def fundamental_strip(self): a, b = self.args[3], self.args[4] if a is InverseMellinTransform._none_sentinel: a = None if b is InverseMellinTransform._none_sentinel: b = None return a, b def _compute_transform(self, F, s, x, **hints): # IntegralTransform's doit will cause this hint to exist, but # InverseMellinTransform should ignore it hints.pop('simplify', True) global _allowed if _allowed is None: _allowed = { exp, gamma, sin, cos, tan, cot, cosh, sinh, tanh, coth, factorial, rf} for f in postorder_traversal(F): if f.is_Function and f.has(s) and f.func not in _allowed: raise IntegralTransformError('Inverse Mellin', F, 'Component %s not recognised.' % f) strip = self.fundamental_strip return _inverse_mellin_transform(F, s, x, strip, **hints) def _as_integral(self, F, s, x): c = self.__class__._c return Integral(F*x**(-s), (s, c - S.ImaginaryUnit*S.Infinity, c + S.ImaginaryUnit*S.Infinity))/(2*S.Pi*S.ImaginaryUnit) def inverse_mellin_transform(F, s, x, strip, **hints): r""" Compute the inverse Mellin transform of `F(s)` over the fundamental strip given by ``strip=(a, b)``. Explanation =========== This can be defined as .. math:: f(x) = \frac{1}{2\pi i} \int_{c - i\infty}^{c + i\infty} x^{-s} F(s) \mathrm{d}s, for any `c` in the fundamental strip. Under certain regularity conditions on `F` and/or `f`, this recovers `f` from its Mellin transform `F` (and vice versa), for positive real `x`. One of `a` or `b` may be passed as ``None``; a suitable `c` will be inferred. If the integral cannot be computed in closed form, this function returns an unevaluated :class:`InverseMellinTransform` object. Note that this function will assume x to be positive and real, regardless of the SymPy assumptions! For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Examples ======== >>> from sympy import inverse_mellin_transform, oo, gamma >>> from sympy.abc import x, s >>> inverse_mellin_transform(gamma(s), s, x, (0, oo)) exp(-x) The fundamental strip matters: >>> f = 1/(s**2 - 1) >>> inverse_mellin_transform(f, s, x, (-oo, -1)) x*(1 - 1/x**2)*Heaviside(x - 1)/2 >>> inverse_mellin_transform(f, s, x, (-1, 1)) -x*Heaviside(1 - x)/2 - Heaviside(x - 1)/(2*x) >>> inverse_mellin_transform(f, s, x, (1, oo)) (1/2 - x**2/2)*Heaviside(1 - x)/x See Also ======== mellin_transform hankel_transform, inverse_hankel_transform """ return InverseMellinTransform(F, s, x, strip[0], strip[1]).doit(**hints) ########################################################################## # Fourier Transform ########################################################################## @_noconds_(True) def _fourier_transform(f, x, k, a, b, name, simplify=True): r""" Compute a general Fourier-type transform .. math:: F(k) = a \int_{-\infty}^{\infty} e^{bixk} f(x)\, dx. For suitable choice of *a* and *b*, this reduces to the standard Fourier and inverse Fourier transforms. """ F = integrate(a*f*exp(b*S.ImaginaryUnit*x*k), (x, S.NegativeInfinity, S.Infinity)) if not F.has(Integral): return _simplify(F, simplify), S.true integral_f = integrate(f, (x, S.NegativeInfinity, S.Infinity)) if integral_f in (S.NegativeInfinity, S.Infinity, S.NaN) or integral_f.has(Integral): raise IntegralTransformError(name, f, 'function not integrable on real axis') if not F.is_Piecewise: raise IntegralTransformError(name, f, 'could not compute integral') F, cond = F.args[0] if F.has(Integral): raise IntegralTransformError(name, f, 'integral in unexpected form') return _simplify(F, simplify), cond class FourierTypeTransform(IntegralTransform): """ Base class for Fourier transforms.""" def a(self): raise NotImplementedError( "Class %s must implement a(self) but does not" % self.__class__) def b(self): raise NotImplementedError( "Class %s must implement b(self) but does not" % self.__class__) def _compute_transform(self, f, x, k, **hints): return _fourier_transform(f, x, k, self.a(), self.b(), self.__class__._name, **hints) def _as_integral(self, f, x, k): a = self.a() b = self.b() return Integral(a*f*exp(b*S.ImaginaryUnit*x*k), (x, S.NegativeInfinity, S.Infinity)) class FourierTransform(FourierTypeTransform): """ Class representing unevaluated Fourier transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute Fourier transforms, see the :func:`fourier_transform` docstring. """ _name = 'Fourier' def a(self): return 1 def b(self): return -2*S.Pi def fourier_transform(f, x, k, **hints): r""" Compute the unitary, ordinary-frequency Fourier transform of ``f``, defined as .. math:: F(k) = \int_{-\infty}^\infty f(x) e^{-2\pi i x k} \mathrm{d} x. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`FourierTransform` object. For other Fourier transform conventions, see the function :func:`sympy.integrals.transforms._fourier_transform`. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import fourier_transform, exp >>> from sympy.abc import x, k >>> fourier_transform(exp(-x**2), x, k) sqrt(pi)*exp(-pi**2*k**2) >>> fourier_transform(exp(-x**2), x, k, noconds=False) (sqrt(pi)*exp(-pi**2*k**2), True) See Also ======== inverse_fourier_transform sine_transform, inverse_sine_transform cosine_transform, inverse_cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return FourierTransform(f, x, k).doit(**hints) class InverseFourierTransform(FourierTypeTransform): """ Class representing unevaluated inverse Fourier transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse Fourier transforms, see the :func:`inverse_fourier_transform` docstring. """ _name = 'Inverse Fourier' def a(self): return 1 def b(self): return 2*S.Pi def inverse_fourier_transform(F, k, x, **hints): r""" Compute the unitary, ordinary-frequency inverse Fourier transform of `F`, defined as .. math:: f(x) = \int_{-\infty}^\infty F(k) e^{2\pi i x k} \mathrm{d} k. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`InverseFourierTransform` object. For other Fourier transform conventions, see the function :func:`sympy.integrals.transforms._fourier_transform`. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import inverse_fourier_transform, exp, sqrt, pi >>> from sympy.abc import x, k >>> inverse_fourier_transform(sqrt(pi)*exp(-(pi*k)**2), k, x) exp(-x**2) >>> inverse_fourier_transform(sqrt(pi)*exp(-(pi*k)**2), k, x, noconds=False) (exp(-x**2), True) See Also ======== fourier_transform sine_transform, inverse_sine_transform cosine_transform, inverse_cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return InverseFourierTransform(F, k, x).doit(**hints) ########################################################################## # Fourier Sine and Cosine Transform ########################################################################## @_noconds_(True) def _sine_cosine_transform(f, x, k, a, b, K, name, simplify=True): """ Compute a general sine or cosine-type transform F(k) = a int_0^oo b*sin(x*k) f(x) dx. F(k) = a int_0^oo b*cos(x*k) f(x) dx. For suitable choice of a and b, this reduces to the standard sine/cosine and inverse sine/cosine transforms. """ F = integrate(a*f*K(b*x*k), (x, S.Zero, S.Infinity)) if not F.has(Integral): return _simplify(F, simplify), S.true if not F.is_Piecewise: raise IntegralTransformError(name, f, 'could not compute integral') F, cond = F.args[0] if F.has(Integral): raise IntegralTransformError(name, f, 'integral in unexpected form') return _simplify(F, simplify), cond class SineCosineTypeTransform(IntegralTransform): """ Base class for sine and cosine transforms. Specify cls._kern. """ def a(self): raise NotImplementedError( "Class %s must implement a(self) but does not" % self.__class__) def b(self): raise NotImplementedError( "Class %s must implement b(self) but does not" % self.__class__) def _compute_transform(self, f, x, k, **hints): return _sine_cosine_transform(f, x, k, self.a(), self.b(), self.__class__._kern, self.__class__._name, **hints) def _as_integral(self, f, x, k): a = self.a() b = self.b() K = self.__class__._kern return Integral(a*f*K(b*x*k), (x, S.Zero, S.Infinity)) class SineTransform(SineCosineTypeTransform): """ Class representing unevaluated sine transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute sine transforms, see the :func:`sine_transform` docstring. """ _name = 'Sine' _kern = sin def a(self): return sqrt(2)/sqrt(pi) def b(self): return S.One def sine_transform(f, x, k, **hints): r""" Compute the unitary, ordinary-frequency sine transform of `f`, defined as .. math:: F(k) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty f(x) \sin(2\pi x k) \mathrm{d} x. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`SineTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import sine_transform, exp >>> from sympy.abc import x, k, a >>> sine_transform(x*exp(-a*x**2), x, k) sqrt(2)*k*exp(-k**2/(4*a))/(4*a**(3/2)) >>> sine_transform(x**(-a), x, k) 2**(1/2 - a)*k**(a - 1)*gamma(1 - a/2)/gamma(a/2 + 1/2) See Also ======== fourier_transform, inverse_fourier_transform inverse_sine_transform cosine_transform, inverse_cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return SineTransform(f, x, k).doit(**hints) class InverseSineTransform(SineCosineTypeTransform): """ Class representing unevaluated inverse sine transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse sine transforms, see the :func:`inverse_sine_transform` docstring. """ _name = 'Inverse Sine' _kern = sin def a(self): return sqrt(2)/sqrt(pi) def b(self): return S.One def inverse_sine_transform(F, k, x, **hints): r""" Compute the unitary, ordinary-frequency inverse sine transform of `F`, defined as .. math:: f(x) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty F(k) \sin(2\pi x k) \mathrm{d} k. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`InverseSineTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import inverse_sine_transform, exp, sqrt, gamma >>> from sympy.abc import x, k, a >>> inverse_sine_transform(2**((1-2*a)/2)*k**(a - 1)* ... gamma(-a/2 + 1)/gamma((a+1)/2), k, x) x**(-a) >>> inverse_sine_transform(sqrt(2)*k*exp(-k**2/(4*a))/(4*sqrt(a)**3), k, x) x*exp(-a*x**2) See Also ======== fourier_transform, inverse_fourier_transform sine_transform cosine_transform, inverse_cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return InverseSineTransform(F, k, x).doit(**hints) class CosineTransform(SineCosineTypeTransform): """ Class representing unevaluated cosine transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute cosine transforms, see the :func:`cosine_transform` docstring. """ _name = 'Cosine' _kern = cos def a(self): return sqrt(2)/sqrt(pi) def b(self): return S.One def cosine_transform(f, x, k, **hints): r""" Compute the unitary, ordinary-frequency cosine transform of `f`, defined as .. math:: F(k) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty f(x) \cos(2\pi x k) \mathrm{d} x. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`CosineTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import cosine_transform, exp, sqrt, cos >>> from sympy.abc import x, k, a >>> cosine_transform(exp(-a*x), x, k) sqrt(2)*a/(sqrt(pi)*(a**2 + k**2)) >>> cosine_transform(exp(-a*sqrt(x))*cos(a*sqrt(x)), x, k) a*exp(-a**2/(2*k))/(2*k**(3/2)) See Also ======== fourier_transform, inverse_fourier_transform, sine_transform, inverse_sine_transform inverse_cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return CosineTransform(f, x, k).doit(**hints) class InverseCosineTransform(SineCosineTypeTransform): """ Class representing unevaluated inverse cosine transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse cosine transforms, see the :func:`inverse_cosine_transform` docstring. """ _name = 'Inverse Cosine' _kern = cos def a(self): return sqrt(2)/sqrt(pi) def b(self): return S.One def inverse_cosine_transform(F, k, x, **hints): r""" Compute the unitary, ordinary-frequency inverse cosine transform of `F`, defined as .. math:: f(x) = \sqrt{\frac{2}{\pi}} \int_{0}^\infty F(k) \cos(2\pi x k) \mathrm{d} k. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`InverseCosineTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import inverse_cosine_transform, sqrt, pi >>> from sympy.abc import x, k, a >>> inverse_cosine_transform(sqrt(2)*a/(sqrt(pi)*(a**2 + k**2)), k, x) exp(-a*x) >>> inverse_cosine_transform(1/sqrt(k), k, x) 1/sqrt(x) See Also ======== fourier_transform, inverse_fourier_transform, sine_transform, inverse_sine_transform cosine_transform hankel_transform, inverse_hankel_transform mellin_transform, laplace_transform """ return InverseCosineTransform(F, k, x).doit(**hints) ########################################################################## # Hankel Transform ########################################################################## @_noconds_(True) def _hankel_transform(f, r, k, nu, name, simplify=True): r""" Compute a general Hankel transform .. math:: F_\nu(k) = \int_{0}^\infty f(r) J_\nu(k r) r \mathrm{d} r. """ F = integrate(f*besselj(nu, k*r)*r, (r, S.Zero, S.Infinity)) if not F.has(Integral): return _simplify(F, simplify), S.true if not F.is_Piecewise: raise IntegralTransformError(name, f, 'could not compute integral') F, cond = F.args[0] if F.has(Integral): raise IntegralTransformError(name, f, 'integral in unexpected form') return _simplify(F, simplify), cond class HankelTypeTransform(IntegralTransform): """ Base class for Hankel transforms. """ def doit(self, **hints): return self._compute_transform(self.function, self.function_variable, self.transform_variable, self.args[3], **hints) def _compute_transform(self, f, r, k, nu, **hints): return _hankel_transform(f, r, k, nu, self._name, **hints) def _as_integral(self, f, r, k, nu): return Integral(f*besselj(nu, k*r)*r, (r, S.Zero, S.Infinity)) @property def as_integral(self): return self._as_integral(self.function, self.function_variable, self.transform_variable, self.args[3]) class HankelTransform(HankelTypeTransform): """ Class representing unevaluated Hankel transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute Hankel transforms, see the :func:`hankel_transform` docstring. """ _name = 'Hankel' def hankel_transform(f, r, k, nu, **hints): r""" Compute the Hankel transform of `f`, defined as .. math:: F_\nu(k) = \int_{0}^\infty f(r) J_\nu(k r) r \mathrm{d} r. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`HankelTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import hankel_transform, inverse_hankel_transform >>> from sympy import exp >>> from sympy.abc import r, k, m, nu, a >>> ht = hankel_transform(1/r**m, r, k, nu) >>> ht 2*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/(2**m*gamma(m/2 + nu/2)) >>> inverse_hankel_transform(ht, k, r, nu) r**(-m) >>> ht = hankel_transform(exp(-a*r), r, k, 0) >>> ht a/(k**3*(a**2/k**2 + 1)**(3/2)) >>> inverse_hankel_transform(ht, k, r, 0) exp(-a*r) See Also ======== fourier_transform, inverse_fourier_transform sine_transform, inverse_sine_transform cosine_transform, inverse_cosine_transform inverse_hankel_transform mellin_transform, laplace_transform """ return HankelTransform(f, r, k, nu).doit(**hints) class InverseHankelTransform(HankelTypeTransform): """ Class representing unevaluated inverse Hankel transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse Hankel transforms, see the :func:`inverse_hankel_transform` docstring. """ _name = 'Inverse Hankel' def inverse_hankel_transform(F, k, r, nu, **hints): r""" Compute the inverse Hankel transform of `F` defined as .. math:: f(r) = \int_{0}^\infty F_\nu(k) J_\nu(k r) k \mathrm{d} k. Explanation =========== If the transform cannot be computed in closed form, this function returns an unevaluated :class:`InverseHankelTransform` object. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Note that for this transform, by default ``noconds=True``. Examples ======== >>> from sympy import hankel_transform, inverse_hankel_transform >>> from sympy import exp >>> from sympy.abc import r, k, m, nu, a >>> ht = hankel_transform(1/r**m, r, k, nu) >>> ht 2*k**(m - 2)*gamma(-m/2 + nu/2 + 1)/(2**m*gamma(m/2 + nu/2)) >>> inverse_hankel_transform(ht, k, r, nu) r**(-m) >>> ht = hankel_transform(exp(-a*r), r, k, 0) >>> ht a/(k**3*(a**2/k**2 + 1)**(3/2)) >>> inverse_hankel_transform(ht, k, r, 0) exp(-a*r) See Also ======== fourier_transform, inverse_fourier_transform sine_transform, inverse_sine_transform cosine_transform, inverse_cosine_transform hankel_transform mellin_transform, laplace_transform """ return InverseHankelTransform(F, k, r, nu).doit(**hints) ########################################################################## # Laplace Transform ########################################################################## # Stub classes and functions that used to be here import sympy.integrals.laplace as _laplace LaplaceTransform = _laplace.LaplaceTransform laplace_transform = _laplace.laplace_transform InverseLaplaceTransform = _laplace.InverseLaplaceTransform inverse_laplace_transform = _laplace.inverse_laplace_transform
44b7af21df6f65232c3eab873f555d972ea830a20462893e7cf25bd7a62ce69f
"""Laplace Transforms""" from sympy.core import S, pi, I from sympy.core.add import Add from sympy.core.cache import cacheit from sympy.core.function import ( AppliedUndef, Derivative, expand, expand_complex, expand_mul, expand_trig, Lambda, WildFunction, diff) from sympy.core.mul import Mul, prod from sympy.core.relational import _canonical, Ge, Gt, Lt, Unequality, Eq from sympy.core.sorting import ordered from sympy.core.symbol import Dummy, symbols, Wild from sympy.functions.elementary.complexes import ( re, im, arg, Abs, polar_lift, periodic_argument) from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.hyperbolic import cosh, coth, sinh, asinh from sympy.functions.elementary.miscellaneous import Max, Min, sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import cos, sin, atan from sympy.functions.special.bessel import besseli, besselj, besselk, bessely from sympy.functions.special.delta_functions import DiracDelta, Heaviside from sympy.functions.special.error_functions import erf, erfc, Ei from sympy.functions.special.gamma_functions import digamma, gamma, lowergamma from sympy.integrals import integrate, Integral from sympy.integrals.transforms import ( _simplify, IntegralTransform, IntegralTransformError) from sympy.logic.boolalg import to_cnf, conjuncts, disjuncts, Or, And from sympy.matrices.matrices import MatrixBase from sympy.polys.matrices.linsolve import _lin_eq2dict from sympy.polys.polyerrors import PolynomialError from sympy.polys.polyroots import roots from sympy.polys.polytools import Poly from sympy.polys.rationaltools import together from sympy.polys.rootoftools import RootSum from sympy.utilities.exceptions import ( sympy_deprecation_warning, SymPyDeprecationWarning, ignore_warnings) from sympy.utilities.misc import debug, debugf def _simplifyconds(expr, s, a): r""" Naively simplify some conditions occurring in ``expr``, given that `\operatorname{Re}(s) > a`. Examples ======== >>> from sympy.integrals.laplace import _simplifyconds >>> from sympy.abc import x >>> from sympy import sympify as S >>> _simplifyconds(abs(x**2) < 1, x, 1) False >>> _simplifyconds(abs(x**2) < 1, x, 2) False >>> _simplifyconds(abs(x**2) < 1, x, 0) Abs(x**2) < 1 >>> _simplifyconds(abs(1/x**2) < 1, x, 1) True >>> _simplifyconds(S(1) < abs(x), x, 1) True >>> _simplifyconds(S(1) < abs(1/x), x, 1) False >>> from sympy import Ne >>> _simplifyconds(Ne(1, x**3), x, 1) True >>> _simplifyconds(Ne(1, x**3), x, 2) True >>> _simplifyconds(Ne(1, x**3), x, 0) Ne(1, x**3) """ def power(ex): if ex == s: return 1 if ex.is_Pow and ex.base == s: return ex.exp return None def bigger(ex1, ex2): """ Return True only if |ex1| > |ex2|, False only if |ex1| < |ex2|. Else return None. """ if ex1.has(s) and ex2.has(s): return None if isinstance(ex1, Abs): ex1 = ex1.args[0] if isinstance(ex2, Abs): ex2 = ex2.args[0] if ex1.has(s): return bigger(1/ex2, 1/ex1) n = power(ex2) if n is None: return None try: if n > 0 and (Abs(ex1) <= Abs(a)**n) == True: return False if n < 0 and (Abs(ex1) >= Abs(a)**n) == True: return True except TypeError: pass def replie(x, y): """ simplify x < y """ if not (x.is_positive or isinstance(x, Abs)) \ or not (y.is_positive or isinstance(y, Abs)): return (x < y) r = bigger(x, y) if r is not None: return not r return (x < y) def replue(x, y): b = bigger(x, y) if b in (True, False): return True return Unequality(x, y) def repl(ex, *args): if ex in (True, False): return bool(ex) return ex.replace(*args) from sympy.simplify.radsimp import collect_abs expr = collect_abs(expr) expr = repl(expr, Lt, replie) expr = repl(expr, Gt, lambda x, y: replie(y, x)) expr = repl(expr, Unequality, replue) return S(expr) def expand_dirac_delta(expr): """ Expand an expression involving DiractDelta to get it as a linear combination of DiracDelta functions. """ return _lin_eq2dict(expr, expr.atoms(DiracDelta)) def _laplace_transform_integration(f, t, s_, simplify=True): """ The backend function for doing Laplace transforms by integration. This backend assumes that the frontend has already split sums such that `f` is to an addition anymore. """ s = Dummy('s') debugf('[LT _l_t_i ] started with (%s, %s, %s)', (f, t, s)) debugf('[LT _l_t_i ] and simplify=%s', (simplify, )) if f.has(DiracDelta): return None F = integrate(f*exp(-s*t), (t, S.Zero, S.Infinity)) debugf('[LT _l_t_i ] integrated: %s', (F, )) if not F.has(Integral): return _simplify(F.subs(s, s_), simplify), S.NegativeInfinity, S.true if not F.is_Piecewise: debug('[LT _l_t_i ] not piecewise.') return None F, cond = F.args[0] if F.has(Integral): debug('[LT _l_t_i ] integral in unexpected form.') return None def process_conds(conds): """ Turn ``conds`` into a strip and auxiliary conditions. """ from sympy.solvers.inequalities import _solve_inequality a = S.NegativeInfinity aux = S.true conds = conjuncts(to_cnf(conds)) p, q, w1, w2, w3, w4, w5 = symbols( 'p q w1 w2 w3 w4 w5', cls=Wild, exclude=[s]) patterns = ( p*Abs(arg((s + w3)*q)) < w2, p*Abs(arg((s + w3)*q)) <= w2, Abs(periodic_argument((s + w3)**p*q, w1)) < w2, Abs(periodic_argument((s + w3)**p*q, w1)) <= w2, Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) < w2, Abs(periodic_argument((polar_lift(s + w3))**p*q, w1)) <= w2) for c in conds: a_ = S.Infinity aux_ = [] for d in disjuncts(c): if d.is_Relational and s in d.rhs.free_symbols: d = d.reversed if d.is_Relational and isinstance(d, (Ge, Gt)): d = d.reversedsign for pat in patterns: m = d.match(pat) if m: break if m: if m[q].is_positive and m[w2]/m[p] == pi/2: d = -re(s + m[w3]) < 0 m = d.match(p - cos(w1*Abs(arg(s*w5))*w2)*Abs(s**w3)**w4 < 0) if not m: m = d.match( cos(p - Abs(periodic_argument(s**w1*w5, q))*w2)*Abs(s**w3)**w4 < 0) if not m: m = d.match( p - cos(Abs(periodic_argument(polar_lift(s)**w1*w5, q))*w2 )*Abs(s**w3)**w4 < 0) if m and all(m[wild].is_positive for wild in [w1, w2, w3, w4, w5]): d = re(s) > m[p] d_ = d.replace( re, lambda x: x.expand().as_real_imag()[0]).subs(re(s), t) if not d.is_Relational or \ d.rel_op in ('==', '!=') \ or d_.has(s) or not d_.has(t): aux_ += [d] continue soln = _solve_inequality(d_, t) if not soln.is_Relational or \ soln.rel_op in ('==', '!='): aux_ += [d] continue if soln.lts == t: debug('[LT _l_t_i ] convergence not in half-plane.') return None else: a_ = Min(soln.lts, a_) if a_ is not S.Infinity: a = Max(a_, a) else: aux = And(aux, Or(*aux_)) return a, aux.canonical if aux.is_Relational else aux conds = [process_conds(c) for c in disjuncts(cond)] conds2 = [x for x in conds if x[1] != False and x[0] is not S.NegativeInfinity] if not conds2: conds2 = [x for x in conds if x[1] != False] conds = list(ordered(conds2)) def cnt(expr): if expr in (True, False): return 0 return expr.count_ops() conds.sort(key=lambda x: (-x[0], cnt(x[1]))) if not conds: debug('[LT _l_t_i ] no convergence found.') return None a, aux = conds[0] # XXX is [0] always the right one? def sbs(expr): return expr.subs(s, s_) if simplify: F = _simplifyconds(F, s, a) aux = _simplifyconds(aux, s, a) return _simplify(F.subs(s, s_), simplify), sbs(a), _canonical(sbs(aux)) def _laplace_deep_collect(f, t): """ This is an internal helper function that traverses through the epression tree of `f(t)` and collects arguments. The purpose of it is that anything like `f(w*t-1*t-c)` will be written as `f((w-1)*t-c)` such that it can match `f(a*t+b)`. """ func = f.func args = list(f.args) if len(f.args) == 0: return f else: args = [_laplace_deep_collect(arg, t) for arg in args] if func.is_Add: return func(*args).collect(t) else: return func(*args) @cacheit def _laplace_build_rules(): """ This is an internal helper function that returns the table of Laplace transform rules in terms of the time variable `t` and the frequency variable `s`. It is used by ``_laplace_apply_rules``. Each entry is a tuple containing: (time domain pattern, frequency-domain replacement, condition for the rule to be applied, convergence plane, preparation function) The preparation function is a function with one argument that is applied to the expression before matching. For most rules it should be ``_laplace_deep_collect``. """ t = Dummy('t') s = Dummy('s') a = Wild('a', exclude=[t]) b = Wild('b', exclude=[t]) n = Wild('n', exclude=[t]) tau = Wild('tau', exclude=[t]) omega = Wild('omega', exclude=[t]) dco = lambda f: _laplace_deep_collect(f, t) debug('_laplace_build_rules is building rules') laplace_transform_rules = [ (a, a/s, S.true, S.Zero, dco), # 4.2.1 (DiracDelta(a*t-b), exp(-s*b/a)/Abs(a), Or(And(a>0, b>=0), And(a<0, b<=0)), S.NegativeInfinity, dco), # Not in Bateman54 (DiracDelta(a*t-b), S(0), Or(And(a<0, b>=0), And(a>0, b<=0)), S.NegativeInfinity, dco), # Not in Bateman54 (Heaviside(a*t-b), exp(-s*b/a)/s, And(a>0, b>0), S.Zero, dco), # 4.4.1 (Heaviside(a*t-b), (1-exp(-s*b/a))/s, And(a<0, b<0), S.Zero, dco), # 4.4.1 (Heaviside(a*t-b), 1/s, And(a>0, b<=0), S.Zero, dco), # 4.4.1 (Heaviside(a*t-b), 0, And(a<0, b>0), S.Zero, dco), # 4.4.1 (t, 1/s**2, S.true, S.Zero, dco), # 4.2.3 (1/(a*t+b), -exp(-b/a*s)*Ei(-b/a*s)/a, Abs(arg(b/a))<pi, S.Zero, dco), # 4.2.6 (1/sqrt(a*t+b), sqrt(a*pi/s)*exp(b/a*s)*erfc(sqrt(b/a*s))/a, Abs(arg(b/a))<pi, S.Zero, dco), # 4.2.18 ((a*t+b)**(-S(3)/2), 2*b**(-S(1)/2)-2*(pi*s/a)**(S(1)/2)*exp(b/a*s)*\ erfc(sqrt(b/a*s))/a, Abs(arg(b/a))<pi, S.Zero, dco), # 4.2.20 (sqrt(t)/(t+b), sqrt(pi/s)-pi*sqrt(b)*exp(b*s)*erfc(sqrt(b*s)), Abs(arg(b))<pi, S.Zero, dco), # 4.2.22 (1/(a*sqrt(t) + t**(3/2)), pi*a**(S(1)/2)*exp(a*s)*erfc(sqrt(a*s)), S.true, S.Zero, dco), # Not in Bateman54 (t**n, gamma(n+1)/s**(n+1), n>-1, S.Zero, dco), # 4.3.1 ((a*t+b)**n, lowergamma(n+1, b/a*s)*exp(-b/a*s)/s**(n+1)/a, And(n>-1, Abs(arg(b/a))<pi), S.Zero, dco), # 4.3.4 (t**n/(t+a), a**n*gamma(n+1)*lowergamma(-n,a*s), And(n>-1, Abs(arg(a))<pi), S.Zero, dco), # 4.3.7 (exp(a*t-tau), exp(-tau)/(s-a), S.true, a, dco), # 4.5.1 (t*exp(a*t-tau), exp(-tau)/(s-a)**2, S.true, a, dco), # 4.5.2 (t**n*exp(a*t), gamma(n+1)/(s-a)**(n+1), re(n)>-1, a, dco), # 4.5.3 (exp(-a*t**2), sqrt(pi/4/a)*exp(s**2/4/a)*erfc(s/sqrt(4*a)), re(a)>0, S.Zero, dco), # 4.5.21 (t*exp(-a*t**2), 1/(2*a)-2/sqrt(pi)/(4*a)**(S(3)/2)*s*erfc(s/sqrt(4*a)), re(a)>0, S.Zero, dco), # 4.5.22 (exp(-a/t), 2*sqrt(a/s)*besselk(1, 2*sqrt(a*s)), re(a)>=0, S.Zero, dco), # 4.5.25 (sqrt(t)*exp(-a/t), S(1)/2*sqrt(pi/s**3)*(1+2*sqrt(a*s))*exp(-2*sqrt(a*s)), re(a)>=0, S.Zero, dco), # 4.5.26 (exp(-a/t)/sqrt(t), sqrt(pi/s)*exp(-2*sqrt(a*s)), re(a)>=0, S.Zero, dco), # 4.5.27 (exp(-a/t)/(t*sqrt(t)), sqrt(pi/a)*exp(-2*sqrt(a*s)), re(a)>0, S.Zero, dco), # 4.5.28 (t**n*exp(-a/t), 2*(a/s)**((n+1)/2)*besselk(n+1, 2*sqrt(a*s)), re(a)>0, S.Zero, dco), # 4.5.29 (exp(-2*sqrt(a*t)), s**(-1)-sqrt(pi*a)*s**(-S(3)/2)*exp(a/s)*\ erfc(sqrt(a/s)), Abs(arg(a))<pi, S.Zero, dco), # 4.5.31 (exp(-2*sqrt(a*t))/sqrt(t), (pi/s)**(S(1)/2)*exp(a/s)*erfc(sqrt(a/s)), Abs(arg(a))<pi, S.Zero, dco), # 4.5.33 (log(a*t), -log(exp(S.EulerGamma)*s/a)/s, a>0, S.Zero, dco), # 4.6.1 (log(1+a*t), -exp(s/a)/s*Ei(-s/a), Abs(arg(a))<pi, S.Zero, dco), # 4.6.4 (log(a*t+b), (log(b)-exp(s/b/a)/s*a*Ei(-s/b))/s*a, And(a>0,Abs(arg(b))<pi), S.Zero, dco), # 4.6.5 (log(t)/sqrt(t), -sqrt(pi/s)*log(4*s*exp(S.EulerGamma)), S.true, S.Zero, dco), # 4.6.9 (t**n*log(t), gamma(n+1)*s**(-n-1)*(digamma(n+1)-log(s)), re(n)>-1, S.Zero, dco), # 4.6.11 (log(a*t)**2, (log(exp(S.EulerGamma)*s/a)**2+pi**2/6)/s, a>0, S.Zero, dco), # 4.6.13 (sin(omega*t), omega/(s**2+omega**2), S.true, Abs(im(omega)), dco), # 4,7,1 (Abs(sin(omega*t)), omega/(s**2+omega**2)*coth(pi*s/2/omega), omega>0, S.Zero, dco), # 4.7.2 (sin(omega*t)/t, atan(omega/s), S.true, Abs(im(omega)), dco), # 4.7.16 (sin(omega*t)**2/t, log(1+4*omega**2/s**2)/4, S.true, 2*Abs(im(omega)), dco), # 4.7.17 (sin(omega*t)**2/t**2, omega*atan(2*omega/s)-s*log(1+4*omega**2/s**2)/4, S.true, 2*Abs(im(omega)), dco), # 4.7.20 (sin(2*sqrt(a*t)), sqrt(pi*a)/s/sqrt(s)*exp(-a/s), S.true, S.Zero, dco), # 4.7.32 (sin(2*sqrt(a*t))/t, pi*erf(sqrt(a/s)), S.true, S.Zero, dco), # 4.7.34 (cos(omega*t), s/(s**2+omega**2), S.true, Abs(im(omega)), dco), # 4.7.43 (cos(omega*t)**2, (s**2+2*omega**2)/(s**2+4*omega**2)/s, S.true, 2*Abs(im(omega)), dco), # 4.7.45 (sqrt(t)*cos(2*sqrt(a*t)), sqrt(pi)/2*s**(-S(5)/2)*(s-2*a)*exp(-a/s), S.true, S.Zero, dco), # 4.7.66 (cos(2*sqrt(a*t))/sqrt(t), sqrt(pi/s)*exp(-a/s), S.true, S.Zero, dco), # 4.7.67 (sin(a*t)*sin(b*t), 2*a*b*s/(s**2+(a+b)**2)/(s**2+(a-b)**2), S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.78 (cos(a*t)*sin(b*t), b*(s**2-a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2), S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.79 (cos(a*t)*cos(b*t), s*(s**2+a**2+b**2)/(s**2+(a+b)**2)/(s**2+(a-b)**2), S.true, Abs(im(a))+Abs(im(b)), dco), # 4.7.80 (sinh(a*t), a/(s**2-a**2), S.true, Abs(re(a)), dco), # 4.9.1 (cosh(a*t), s/(s**2-a**2), S.true, Abs(re(a)), dco), # 4.9.2 (sinh(a*t)**2, 2*a**2/(s**3-4*a**2*s), S.true, 2*Abs(re(a)), dco), # 4.9.3 (cosh(a*t)**2, (s**2-2*a**2)/(s**3-4*a**2*s), S.true, 2*Abs(re(a)), dco), # 4.9.4 (sinh(a*t)/t, log((s+a)/(s-a))/2, S.true, Abs(re(a)), dco), # 4.9.12 (t**n*sinh(a*t), gamma(n+1)/2*((s-a)**(-n-1)-(s+a)**(-n-1)), n>-2, Abs(a), dco), # 4.9.18 (t**n*cosh(a*t), gamma(n+1)/2*((s-a)**(-n-1)+(s+a)**(-n-1)), n>-1, Abs(a), dco), # 4.9.19 (sinh(2*sqrt(a*t)), sqrt(pi*a)/s/sqrt(s)*exp(a/s), S.true, S.Zero, dco), # 4.9.34 (cosh(2*sqrt(a*t)), 1/s+sqrt(pi*a)/s/sqrt(s)*exp(a/s)*erf(sqrt(a/s)), S.true, S.Zero, dco), # 4.9.35 (sqrt(t)*sinh(2*sqrt(a*t)), pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a)*\ exp(a/s)*erf(sqrt(a/s))-a**(S(1)/2)*s**(-2), S.true, S.Zero, dco), # 4.9.36 (sqrt(t)*cosh(2*sqrt(a*t)), pi**(S(1)/2)*s**(-S(5)/2)*(s/2+a)*exp(a/s), S.true, S.Zero, dco), # 4.9.37 (sinh(2*sqrt(a*t))/sqrt(t), pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s)*\ erf(sqrt(a/s)), S.true, S.Zero, dco), # 4.9.38 (cosh(2*sqrt(a*t))/sqrt(t), pi**(S(1)/2)*s**(-S(1)/2)*exp(a/s), S.true, S.Zero, dco), # 4.9.39 (sinh(sqrt(a*t))**2/sqrt(t), pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)-1), S.true, S.Zero, dco), # 4.9.40 (cosh(sqrt(a*t))**2/sqrt(t), pi**(S(1)/2)/2*s**(-S(1)/2)*(exp(a/s)+1), S.true, S.Zero, dco), # 4.9.41 (erf(a*t), exp(s**2/(2*a)**2)*erfc(s/(2*a))/s, 4*Abs(arg(a))<pi, S.Zero, dco), # 4.12.2 (erf(sqrt(a*t)), sqrt(a)/sqrt(s+a)/s, S.true, Max(S.Zero, -re(a)), dco), # 4.12.4 (exp(a*t)*erf(sqrt(a*t)), sqrt(a)/sqrt(s)/(s-a), S.true, Max(S.Zero, re(a)), dco), # 4.12.5 (erf(sqrt(a/t)/2), (1-exp(-sqrt(a*s)))/s, re(a)>0, S.Zero, dco), # 4.12.6 (erfc(sqrt(a*t)), (sqrt(s+a)-sqrt(a))/sqrt(s+a)/s, S.true, -re(a), dco), # 4.12.9 (exp(a*t)*erfc(sqrt(a*t)), 1/(s+sqrt(a*s)), S.true, S.Zero, dco), # 4.12.10 (erfc(sqrt(a/t)/2), exp(-sqrt(a*s))/s, re(a)>0, S.Zero, dco), # 4.2.11 (besselj(n, a*t), a**n/(sqrt(s**2+a**2)*(s+sqrt(s**2+a**2))**n), re(n)>-1, Abs(im(a)), dco), # 4.14.1 (t**b*besselj(n, a*t), 2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2+a**2)**(-n-S.Half), And(re(n)>-S.Half, Eq(b, n)), Abs(im(a)), dco), # 4.14.7 (t**b*besselj(n, a*t), 2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2+a**2)**(-n-S(3)/2), And(re(n)>-1, Eq(b, n+1)), Abs(im(a)), dco), # 4.14.8 (besselj(0, 2*sqrt(a*t)), exp(-a/s)/s, S.true, S.Zero, dco), # 4.14.25 (t**(b)*besselj(n, 2*sqrt(a*t)), a**(n/2)*s**(-n-1)*exp(-a/s), And(re(n)>-1, Eq(b, n*S.Half)), S.Zero, dco), # 4.14.30 (besselj(0, a*sqrt(t**2+b*t)), exp(b*s-b*sqrt(s**2+a**2))/sqrt(s**2+a**2), Abs(arg(b))<pi, Abs(im(a)), dco), # 4.15.19 (besseli(n, a*t), a**n/(sqrt(s**2-a**2)*(s+sqrt(s**2-a**2))**n), re(n)>-1, Abs(re(a)), dco), # 4.16.1 (t**b*besseli(n, a*t), 2**n/sqrt(pi)*gamma(n+S.Half)*a**n*(s**2-a**2)**(-n-S.Half), And(re(n)>-S.Half, Eq(b, n)), Abs(re(a)), dco), # 4.16.6 (t**b*besseli(n, a*t), 2**(n+1)/sqrt(pi)*gamma(n+S(3)/2)*a**n*s*(s**2-a**2)**(-n-S(3)/2), And(re(n)>-1, Eq(b, n+1)), Abs(re(a)), dco), # 4.16.7 (t**(b)*besseli(n, 2*sqrt(a*t)), a**(n/2)*s**(-n-1)*exp(a/s), And(re(n)>-1, Eq(b, n*S.Half)), S.Zero, dco), # 4.16.18 (bessely(0, a*t), -2/pi*asinh(s/a)/sqrt(s**2+a**2), S.true, Abs(im(a)), dco), # 4.15.44 (besselk(0, a*t), log((s + sqrt(s**2-a**2))/a)/(sqrt(s**2-a**2)), S.true, -re(a), dco) # 4.16.23 ] return laplace_transform_rules, t, s def _laplace_rule_timescale(f, t, s): """ This function applies the time-scaling rule of the Laplace transform in a straight-forward way. For example, if it gets ``(f(a*t), t, s)``, it will compute ``LaplaceTransform(f(t)/a, t, s/a)`` if ``a>0``. """ a = Wild('a', exclude=[t]) g = WildFunction('g', nargs=1) ma1 = f.match(g) if ma1: arg = ma1[g].args[0].collect(t) ma2 = arg.match(a*t) if ma2 and ma2[a].is_positive and not ma2[a]==1: debug('_laplace_apply_prog rules match:') debugf(' f: %s _ %s, %s )', (f, ma1, ma2)) debug(' rule: time scaling (4.1.4)') r, pr, cr = _laplace_transform(1/ma2[a]*ma1[g].func(t), t, s/ma2[a], simplify=False) return (r, pr, cr) return None def _laplace_rule_heaviside(f, t, s): """ This function deals with time-shifted Heaviside step functions. If the time shift is positive, it applies the time-shift rule of the Laplace transform. For example, if it gets ``(Heaviside(t-a)*f(t), t, s)``, it will compute ``exp(-a*s)*LaplaceTransform(f(t+a), t, s)``. If the time shift is negative, the Heaviside function is simply removed as it means nothing to the Laplace transform. The function does not remove a factor ``Heaviside(t)``; this is done by the simple rules. """ a = Wild('a', exclude=[t]) y = Wild('y') g = Wild('g') ma1 = f.match(Heaviside(y)*g) if ma1: ma2 = ma1[y].match(t-a) if ma2 and ma2[a].is_positive: debug('_laplace_apply_prog_rules match:') debugf(' f: %s ( %s, %s )', (f, ma1, ma2)) debug(' rule: time shift (4.1.4)') r, pr, cr = _laplace_transform(ma1[g].subs(t, t+ma2[a]), t, s, simplify=False) return (exp(-ma2[a]*s)*r, pr, cr) if ma2 and ma2[a].is_negative: debug('_laplace_apply_prog_rules match:') debugf(' f: %s ( %s, %s )', (f, ma1, ma2)) debug(' rule: Heaviside factor with negative time shift (4.1.4)') r, pr, cr = _laplace_transform(ma1[g], t, s, simplify=False) return (r, pr, cr) return None def _laplace_rule_exp(f, t, s): """ If this function finds a factor ``exp(a*t)``, it applies the frequency-shift rule of the Laplace transform and adjusts the convergence plane accordingly. For example, if it gets ``(exp(-a*t)*f(t), t, s)``, it will compute ``LaplaceTransform(f(t), t, s+a)``. """ a = Wild('a', exclude=[t]) y = Wild('y') z = Wild('z') ma1 = f.match(exp(y)*z) if ma1: ma2 = ma1[y].collect(t).match(a*t) if ma2: debug('_laplace_apply_prog_rules match:') debugf(' f: %s ( %s, %s )', (f, ma1, ma2)) debug(' rule: multiply with exp (4.1.5)') r, pr, cr = _laplace_transform(ma1[z], t, s-ma2[a], simplify=False) return (r, pr+re(ma2[a]), cr) return None def _laplace_rule_delta(f, t, s): """ If this function finds a factor ``DiracDelta(b*t-a)``, it applies the masking property of the delta distribution. For example, if it gets ``(DiracDelta(t-a)*f(t), t, s)``, it will return ``(f(a)*exp(-a*s), -a, True)``. """ # This rule is not in Bateman54 a = Wild('a', exclude=[t]) b = Wild('b', exclude=[t]) y = Wild('y') z = Wild('z') ma1 = f.match(DiracDelta(y)*z) if ma1 and not ma1[z].has(DiracDelta): ma2 = ma1[y].collect(t).match(b*t-a) if ma2: debug('_laplace_apply_prog_rules match:') debugf(' f: %s ( %s, %s )', (f, ma1, ma2)) debug(' rule: multiply with DiracDelta') loc = ma2[a]/ma2[b] if re(loc)>=0 and im(loc)==0: r = exp(-ma2[a]/ma2[b]*s)*ma1[z].subs(t, ma2[a]/ma2[b])/ma2[b] return (r, S.NegativeInfinity, S.true) else: return (0, S.NegativeInfinity, S.true) if ma1[y].is_polynomial(t): ro = roots(ma1[y], t) if not roots is {} and set(ro.values())=={1}: slope = diff(ma1[y], t) r = Add(*[ exp(-x*s)*ma1[z].subs(t, s)/slope.subs(t, x) for x in list(ro.keys()) if im(x)==0 and re(x)>=0 ]) return (r, S.NegativeInfinity, S.true) return None def _laplace_rule_trig(f, t, s, doit=True, **hints): """ This function covers trigonometric factors. All of the rules have a similar form: ``trig(y)*z`` is matched, and then two copies of the Laplace transform of `z` are shifted in the s Domain and added with a weight. The parameters in the tuples are (fm, nu, s1, s2, sd): fm: Function to match nu: Number of the rule, for debug purposes s1: weight of the sum, 'I' for sin and '1' for all others s2: sign of the second copy of the Laplace transform of z sd: shift direction; shift along real or imaginary axis if `1` or `I` The convergence plane is changed only if a frequency shift is done along the real axis. """ # These rules follow from Bateman54, 4.1.5 and Euler's formulas a = Wild('a', exclude=[t]) y = Wild('y') z = Wild('z') trigrules = [(sinh(y), '1.6', 1, -1, 1), (cosh(y), '1.7', 1, 1, 1), (sin(y), '1.8', -I, -1, I), (cos(y), '1.9', 1, 1, I)] for trigrule in trigrules: fm, nu, s1, s2, sd = trigrule ma1 = f.match(z*fm) if ma1: ma2 = ma1[y].collect(t).match(a*t) if ma2: debug('_laplace_apply_rules match:') debugf(' f: %s ( %s, %s )', (f, ma1, ma2)) debugf(' rule: multiply with %s (%s)', (fm.func, nu)) r, pr, cr = _laplace_transform(ma1[z], t, s, simplify=False) if sd==1: cp_shift = Abs(re(ma2[a])) else: cp_shift = Abs(im(ma2[a])) return ((s1*(r.subs(s, s-sd*ma2[a])+\ s2*r.subs(s, s+sd*ma2[a])))/2, pr+cp_shift, cr) return None def _laplace_rule_diff(f, t, s, doit=True, **hints): """ This function looks for derivatives in the time domain and replaces it by factors of `s` and initial conditions in the frequency domain. For example, if it gets ``(diff(f(t), t), t, s)``, it will compute ``s*LaplaceTransform(f(t), t, s) - f(0)``. """ a = Wild('a', exclude=[t]) n = Wild('n', exclude=[t]) g = WildFunction('g') ma1 = f.match(a*Derivative(g, (t, n))) if ma1 and ma1[n].is_integer: m = [ z.has(t) for z in ma1[g].args ] if sum(m)==1: debug('_laplace_apply_rules match:') debugf(' f, n: %s, %s', (f, ma1[n])) debug(' rule: time derivative (4.1.8)') d = [] for k in range(ma1[n]): if k==0: y = ma1[g].subs(t, 0) else: y = Derivative(ma1[g], (t, k)).subs(t, 0) d.append(s**(ma1[n]-k-1)*y) r, pr, cr = _laplace_transform(ma1[g], t, s, simplify=False) return (ma1[a]*(s**ma1[n]*r - Add(*d)), pr, cr) return None def _laplace_rule_sdiff(f, t, s, doit=True, **hints): """ This function looks for multiplications with polynoimials in `t` as they correspond to differentiation in the frequency domain. For example, if it gets ``(t*f(t), t, s)``, it will compute ``-Derivative(LaplaceTransform(f(t), t, s), s)``. """ if f.is_Mul: pfac = [1] ofac = [1] for fac in Mul.make_args(f): if fac.is_polynomial(t): pfac.append(fac) else: ofac.append(fac) if len(pfac)>1: pex = prod(pfac) pc = Poly(pex, t).all_coeffs() N = len(pc) if N>1: debug('_laplace_apply_rules match:') debugf(' f, n: %s, %s', (f, pfac)) debug(' rule: frequency derivative (4.1.6)') oex = prod(ofac) r_, p_, c_ = _laplace_transform(oex, t, s, simplify=False) deri = [r_] d1 = False try: d1 = -diff(deri[-1], s) except ValueError: d1 = False if r_.has(LaplaceTransform): for k in range(N-1): deri.append((-1)**(k+1)*Derivative(r_, s, k+1)) else: if d1: deri.append(d1) for k in range(N-2): deri.append(-diff(deri[-1], s)) if d1: r = Add(*[ pc[N-n-1]*deri[n] for n in range(N) ]) return (r, p_, c_) return None def _laplace_expand(f, t, s, doit=True, **hints): """ This function tries to expand its argument with successively stronger methods: first it will expand on the top level, then it will expand any multiplications in depth, then it will try all avilable expansion methods, and finally it will try to expand trigonometric functions. If it can expand, it will then compute the Laplace transform of the expanded term. """ if f.is_Add: return None r = expand(f, deep=False) if r.is_Add: return _laplace_transform(r, t, s, simplify=False) r = expand_mul(f) if r.is_Add: return _laplace_transform(r, t, s, simplify=False) r = expand(f) if r.is_Add: return _laplace_transform(r, t, s, simplify=False) if not r==f: return _laplace_transform(r, t, s, simplify=False) r = expand(expand_trig(f)) if r.is_Add: return _laplace_transform(r, t, s, simplify=False) return None def _laplace_apply_prog_rules(f, t, s): """ This function applies all program rules and returns the result if one of them gives a result. """ prog_rules = [_laplace_rule_heaviside, _laplace_rule_delta, _laplace_rule_timescale, _laplace_rule_exp, _laplace_rule_trig, _laplace_rule_diff, _laplace_rule_sdiff] for p_rule in prog_rules: if (L := p_rule(f, t, s)) is not None: return L return None def _laplace_apply_simple_rules(f, t, s): """ This function applies all simple rules and returns the result if one of them gives a result. """ simple_rules, t_, s_ = _laplace_build_rules() prep_old = '' prep_f = '' for t_dom, s_dom, check, plane, prep in simple_rules: if not prep_old == prep: prep_f = prep(f.subs({t: t_})) prep_old = prep ma = prep_f.match(t_dom) if ma: try: c = check.xreplace(ma) except TypeError: # This may happen if the time function has imaginary # numbers in it. Then we give up. continue if c==True: debug('_laplace_apply_simple_rules match:') debugf(' f: %s', (f,)) debugf(' rule: %s o---o %s', (t_dom, s_dom)) debugf(' match: %s', (ma, )) return (s_dom.xreplace(ma).subs({s_: s}), plane.xreplace(ma), S.true) return None def _laplace_transform(fn, t_, s_, simplify=True): """ Front-end function of the Laplace transform. It tries to apply all known rules recursively, and if everything else fails, it tries to integrate. """ debugf('[LT _l_t] (%s, %s, %s)', (fn, t_, s_)) terms = Add.make_args(fn) terms_s = [] planes = [] conditions = [] for ff in terms: k, ft = ff.as_independent(t_, as_Add=False) if (r := _laplace_apply_simple_rules(ft, t_, s_)) is not None: pass elif (r := _laplace_apply_prog_rules(ft, t_, s_)) is not None: pass elif (r := _laplace_expand(ft, t_, s_)) is not None: pass elif any(undef.has(t_) for undef in ft.atoms(AppliedUndef)): # If there are undefined functions f(t) then integration is # unlikely to do anything useful so we skip it and given an # unevaluated LaplaceTransform. r = (LaplaceTransform(ft, t_, s_), S.NegativeInfinity, True) elif (r := _laplace_transform_integration(ft, t_, s_, simplify=simplify)) is not None: pass else: r = (LaplaceTransform(ft, t_, s_), S.NegativeInfinity, True) (ri_, pi_, ci_) = r terms_s.append(k*ri_) planes.append(pi_) conditions.append(ci_) result = Add(*terms_s) if simplify: result = result.simplify(doit=False) plane = Max(*planes) condition = And(*conditions) return result, plane, condition class LaplaceTransform(IntegralTransform): """ Class representing unevaluated Laplace transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute Laplace transforms, see the :func:`laplace_transform` docstring. If this is called with ``.doit()``, it returns the Laplace transform as an expression. If it is called with ``.doit(noconds=False)``, it returns a tuple containing the same expression, a convergence plane, and conditions. """ _name = 'Laplace' def _compute_transform(self, f, t, s, **hints): _simplify = hints.get('simplify', False) LT = _laplace_transform_integration(f, t, s, simplify=_simplify) return LT def _as_integral(self, f, t, s): return Integral(f*exp(-s*t), (t, S.Zero, S.Infinity)) def _collapse_extra(self, extra): conds = [] planes = [] for plane, cond in extra: conds.append(cond) planes.append(plane) cond = And(*conds) plane = Max(*planes) if cond == False: raise IntegralTransformError( 'Laplace', None, 'No combined convergence.') return plane, cond def doit(self, **hints): """ Try to evaluate the transform in closed form. Explanation =========== Standard hints are the following: - ``noconds``: if True, do not return convergence conditions. The default setting is `True`. - ``simplify``: if True, it simplifies the final result. This is the default behaviour """ _noconds = hints.get('noconds', True) _simplify = hints.get('simplify', True) debugf('[LT doit] (%s, %s, %s)', (self.function, self.function_variable, self.transform_variable)) t_ = self.function_variable s_ = self.transform_variable fn = self.function r = _laplace_transform(fn, t_, s_, simplify=_simplify) if _noconds: return r[0] else: return r def laplace_transform(f, t, s, legacy_matrix=True, **hints): r""" Compute the Laplace Transform `F(s)` of `f(t)`, .. math :: F(s) = \int_{0^{-}}^\infty e^{-st} f(t) \mathrm{d}t. Explanation =========== For all sensible functions, this converges absolutely in a half-plane .. math :: a < \operatorname{Re}(s) This function returns ``(F, a, cond)`` where ``F`` is the Laplace transform of ``f``, `a` is the half-plane of convergence, and `cond` are auxiliary convergence conditions. The implementation is rule-based, and if you are interested in which rules are applied, and whether integration is attempted, you can switch debug information on by setting ``sympy.SYMPY_DEBUG=True``. The numbers of the rules in the debug information (and the code) refer to Bateman's Tables of Integral Transforms [1]. The lower bound is `0-`, meaning that this bound should be approached from the lower side. This is only necessary if distributions are involved. At present, it is only done if `f(t)` contains ``DiracDelta``, in which case the Laplace transform is computed implicitly as .. math :: F(s) = \lim_{\tau\to 0^{-}} \int_{\tau}^\infty e^{-st} f(t) \mathrm{d}t by applying rules. If the Laplace transform cannot be fully computed in closed form, this function returns expressions containing unevaluated :class:`LaplaceTransform` objects. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. If ``noconds=True``, only `F` will be returned (i.e. not ``cond``, and also not the plane ``a``). .. deprecated:: 1.9 Legacy behavior for matrices where ``laplace_transform`` with ``noconds=False`` (the default) returns a Matrix whose elements are tuples. The behavior of ``laplace_transform`` for matrices will change in a future release of SymPy to return a tuple of the transformed Matrix and the convergence conditions for the matrix as a whole. Use ``legacy_matrix=False`` to enable the new behavior. Examples ======== >>> from sympy import DiracDelta, exp, laplace_transform >>> from sympy.abc import t, s, a >>> laplace_transform(t**4, t, s) (24/s**5, 0, True) >>> laplace_transform(t**a, t, s) (s**(-a - 1)*gamma(a + 1), 0, re(a) > -1) >>> laplace_transform(DiracDelta(t)-a*exp(-a*t), t, s) (s/(a + s), -a, True) References ========== .. [1] Erdelyi, A. (ed.), Tables of Integral Transforms, Volume 1, Bateman Manuscript Prooject, McGraw-Hill (1954), available: https://resolver.caltech.edu/CaltechAUTHORS:20140123-101456353 See Also ======== inverse_laplace_transform, mellin_transform, fourier_transform hankel_transform, inverse_hankel_transform """ _noconds = hints.get('noconds', False) _simplify = hints.get('simplify', True) if isinstance(f, MatrixBase) and hasattr(f, 'applyfunc'): conds = not hints.get('noconds', False) if conds and legacy_matrix: sympy_deprecation_warning( """ Calling laplace_transform() on a Matrix with noconds=False (the default) is deprecated. Either noconds=True or use legacy_matrix=False to get the new behavior. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-laplace-transform-matrix", ) # Temporarily disable the deprecation warning for non-Expr objects # in Matrix with ignore_warnings(SymPyDeprecationWarning): return f.applyfunc(lambda fij: laplace_transform(fij, t, s, **hints)) else: elements_trans = [laplace_transform(fij, t, s, **hints) for fij in f] if conds: elements, avals, conditions = zip(*elements_trans) f_laplace = type(f)(*f.shape, elements) return f_laplace, Max(*avals), And(*conditions) else: return type(f)(*f.shape, elements_trans) LT = LaplaceTransform(f, t, s).doit(noconds=False, simplify=_simplify) if not _noconds: return LT else: return LT[0] def _inverse_laplace_transform_integration(F, s, t_, plane, simplify=True): """ The backend function for inverse Laplace transforms. """ from sympy.integrals.meijerint import meijerint_inversion, _get_coeff_exp from sympy.integrals.transforms import inverse_mellin_transform # There are two strategies we can try: # 1) Use inverse mellin transforms - related by a simple change of variables. # 2) Use the inversion integral. t = Dummy('t', real=True) def pw_simp(*args): """ Simplify a piecewise expression from hyperexpand. """ # XXX we break modularity here! if len(args) != 3: return Piecewise(*args) arg = args[2].args[0].argument coeff, exponent = _get_coeff_exp(arg, t) e1 = args[0].args[0] e2 = args[1].args[0] return Heaviside(1/Abs(coeff) - t**exponent)*e1 \ + Heaviside(t**exponent - 1/Abs(coeff))*e2 if F.is_rational_function(s): F = F.apart(s) if F.is_Add: f = Add(*[_inverse_laplace_transform_integration(X, s, t, plane, simplify)\ for X in F.args]) return _simplify(f.subs(t, t_), simplify), True try: f, cond = inverse_mellin_transform(F, s, exp(-t), (None, S.Infinity), needeval=True, noconds=False) except IntegralTransformError: f = None if f is None: f = meijerint_inversion(F, s, t) if f is None: raise IntegralTransformError('Inverse Laplace', f, '') if f.is_Piecewise: f, cond = f.args[0] if f.has(Integral): raise IntegralTransformError('Inverse Laplace', f, 'inversion integral of unrecognised form.') else: cond = S.true f = f.replace(Piecewise, pw_simp) if f.is_Piecewise: # many of the functions called below can't work with piecewise # (b/c it has a bool in args) return f.subs(t, t_), cond u = Dummy('u') def simp_heaviside(arg, H0=S.Half): a = arg.subs(exp(-t), u) if a.has(t): return Heaviside(arg, H0) from sympy.solvers.inequalities import _solve_inequality rel = _solve_inequality(a > 0, u) if rel.lts == u: k = log(rel.gts) return Heaviside(t + k, H0) else: k = log(rel.lts) return Heaviside(-(t + k), H0) f = f.replace(Heaviside, simp_heaviside) def simp_exp(arg): return expand_complex(exp(arg)) f = f.replace(exp, simp_exp) # TODO it would be nice to fix cosh and sinh ... simplify messes these # exponentials up return _simplify(f.subs(t, t_), simplify), cond def _complete_the_square_in_denom(f, s): from sympy.simplify.radsimp import fraction [n, d] = fraction(f) if d.is_polynomial(s): cf = d.as_poly(s).all_coeffs() if len(cf)==3: a, b, c = cf d = a*((s+b/(2*a))**2+c/a-(b/(2*a))**2) return n/d @cacheit def _inverse_laplace_build_rules(): """ This is an internal helper function that returns the table of inverse Laplace transform rules in terms of the time variable `t` and the frequency variable `s`. It is used by `_inverse_laplace_apply_rules`. """ s = Dummy('s') t = Dummy('t') a = Wild('a', exclude=[s]) b = Wild('b', exclude=[s]) c = Wild('c', exclude=[s]) debug('_inverse_laplace_build_rules is building rules') def _frac(f, s): try: return f.factor(s) except PolynomialError: return f same = lambda f: f # This list is sorted according to the prep function needed. _ILT_rules = [ (a/s, a, S.true, same, 1), (b*(s+a)**(-c), t**(c-1)*exp(-a*t)/gamma(c), c>0, same, 1), (1/(s**2+a**2)**2, (sin(a*t) - a*t*cos(a*t))/(2*a**3), S.true, same, 1) ] return _ILT_rules, s, t def _inverse_laplace_apply_simple_rules(f, s, t): """ Helper function for the class InverseLaplaceTransform. """ if f==1: debug('_inverse_laplace_apply_simple_rules match:') debugf(' f: %s', (1,)) debugf(' rule: 1 o---o DiracDelta(%s)', (t,)) return DiracDelta(t), S.true _ILT_rules, s_, t_ = _inverse_laplace_build_rules() _prep = '' fsubs = f.subs({s: s_}) for s_dom, t_dom, check, prep, fac in _ILT_rules: if not _prep == (prep, fac): _F = prep(fsubs*fac) _prep = (prep, fac) ma = _F.match(s_dom) if ma: try: c = check.xreplace(ma) except TypeError: continue if c: debug('_inverse_laplace_apply_simple_rules match:') debugf(' f: %s', (f,)) debugf(' rule: %s o---o %s', (s_dom, t_dom)) debugf(' ma: %s', (ma,)) return Heaviside(t)*t_dom.xreplace(ma).subs({t_: t}), S.true return None def _inverse_laplace_time_shift(F, s, t, plane): """ Helper function for the class InverseLaplaceTransform. """ a = Wild('a', exclude=[s]) g = Wild('g') if not F.has(s): return F*DiracDelta(t), S.true ma1 = F.match(exp(a*s)) if ma1: if ma1[a].is_negative: debug('_inverse_laplace_time_shift match:') debugf(' f: %s', (F,)) debug(' rule: exp(-a*s) o---o DiracDelta(t-a)') debugf(' ma: %s', (ma1,)) return DiracDelta(t+ma1[a]), S.true else: debug('_inverse_laplace_time_shift match: negative time shift') return InverseLaplaceTransform(F, s, t, plane), S.true ma1 = F.match(exp(a*s)*g) if ma1: if ma1[a].is_negative: debug('_inverse_laplace_time_shift match:') debugf(' f: %s', (F,)) debug(' rule: exp(-a*s)*F(s) o---o Heaviside(t-a)*f(t-a)') debugf(' ma: %s', (ma1,)) return _inverse_laplace_transform(ma1[g], s, t+ma1[a], plane) else: debug('_inverse_laplace_time_shift match: negative time shift') return InverseLaplaceTransform(F, s, t, plane), S.true return None def _inverse_laplace_time_diff(F, s, t, plane): """ Helper function for the class InverseLaplaceTransform. """ n = Wild('n', exclude=[s]) g = Wild('g') ma1 = F.match(s**n*g) if ma1 and ma1[n].is_integer and ma1[n].is_positive: debug('_inverse_laplace_time_diff match:') debugf(' f: %s', (F,)) debug(' rule: s**n*F(s) o---o diff(f(t), t, n)') debugf(' ma: %s', (ma1,)) r, c = _inverse_laplace_transform(ma1[g], s, t, plane) r = r.replace(Heaviside(t), 1) return diff(r, t, ma1[n]), c return None def _inverse_laplace_apply_prog_rules(F, s, t, plane): """ Helper function for the class InverseLaplaceTransform. """ prog_rules = [_inverse_laplace_time_shift, _inverse_laplace_time_diff] for p_rule in prog_rules: if (r := p_rule(F, s, t, plane)) is not None: return r return None def _inverse_laplace_expand(fn, s, t, plane): """ Helper function for the class InverseLaplaceTransform. """ if fn.is_Add: return None r = expand(fn, deep=False) if r.is_Add: return _inverse_laplace_transform(r, s, t, plane) r = expand_mul(fn) if r.is_Add: return _inverse_laplace_transform(r, s, t, plane) r = expand(fn) if r.is_Add: return _inverse_laplace_transform(r, s, t, plane) if fn.is_rational_function(s): r = fn.apart(s).doit() if r.is_Add: return _inverse_laplace_transform(r, s, t, plane) return None def _inverse_laplace_rational(fn, s, t, plane, simplify): """ Helper function for the class InverseLaplaceTransform. """ debugf('[ILT _i_l_r] (%s, %s, %s)', (fn, s, t)) x_ = symbols('x_') f = fn.apart(s) terms = Add.make_args(f) terms_t = [] conditions = [S.true] for term in terms: [n, d] = term.as_numer_denom() dc = d.as_poly(s).all_coeffs() dc_lead = dc[0] dc = [ x/dc_lead for x in dc ] nc = [ x/dc_lead for x in n.as_poly(s).all_coeffs() ] if len(dc)==1: r = nc[0]*DiracDelta(t) terms_t.append(r) elif len(dc)==2: r = nc[0]*exp(-dc[1]*t) terms_t.append(Heaviside(t)*r) elif len(dc)==3: a = dc[1]/2 b = (dc[2]-a**2).factor() if len(nc)==1: nc = [S.Zero] + nc l, m = tuple(nc) if b==0: r = (m*t+l*(1-a*t))*exp(-a*t) else: hyp = False if b.is_negative: b=-b hyp = True b2 = list(roots(x_**2-b, x_).keys())[0] bs = sqrt(b).simplify() if hyp: r = l*exp(-a*t)*cosh(b2*t) + (m-a*l)/bs*exp(-a*t)*sinh(bs*t) else: r = l*exp(-a*t)*cos(b2*t) + (m-a*l)/bs*exp(-a*t)*sin(bs*t) terms_t.append(Heaviside(t)*r) else: ft, cond = _inverse_laplace_transform(fn, s, t, plane, simplify=True, dorational=False) terms_t.append(ft) conditions.append(cond) result = Add(*terms_t) if simplify: result = result.simplify(doit=False) debugf('[ILT _i_l_r] returns %s', (result,)) return result, And(*conditions) def _inverse_laplace_transform(fn, s_, t_, plane, simplify=True, dorational=True): """ Front-end function of the inverse Laplace transform. It tries to apply all known rules recursively. If everything else fails, it tries to integrate. """ terms = Add.make_args(fn) terms_t = [] conditions = [] debugf('[ILT _i_l_t] (%s, %s, %s)', (fn, s_, t_)) for term in terms: k, f = term.as_independent(s_, as_Add=False) if dorational and term.is_rational_function(s_) and \ (r := _inverse_laplace_rational(f, s_, t_, plane, simplify)) is not None: pass elif (r := _inverse_laplace_apply_simple_rules(f, s_, t_)) is not None: pass elif (r := _inverse_laplace_apply_prog_rules(f, s_, t_, plane)) is not None: pass elif (r := _inverse_laplace_expand(f, s_, t_, plane)) is not None: pass elif any(undef.has(s_) for undef in f.atoms(AppliedUndef)): # If there are undefined functions f(t) then integration is # unlikely to do anything useful so we skip it and given an # unevaluated LaplaceTransform. r = (InverseLaplaceTransform(f, s_, t_, plane), S.true) elif (r := _inverse_laplace_transform_integration(f, s_, t_, plane, simplify=simplify)) is not None: pass else: r = (InverseLaplaceTransform(f, s_, t_, plane), S.true) (ri_, ci_) = r terms_t.append(k*ri_) conditions.append(ci_) result = Add(*terms_t) if simplify: result = result.simplify(doit=False) condition = And(*conditions) return result, condition class InverseLaplaceTransform(IntegralTransform): """ Class representing unevaluated inverse Laplace transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute inverse Laplace transforms, see the :func:`inverse_laplace_transform` docstring. """ _name = 'Inverse Laplace' _none_sentinel = Dummy('None') _c = Dummy('c') def __new__(cls, F, s, x, plane, **opts): if plane is None: plane = InverseLaplaceTransform._none_sentinel return IntegralTransform.__new__(cls, F, s, x, plane, **opts) @property def fundamental_plane(self): plane = self.args[3] if plane is InverseLaplaceTransform._none_sentinel: plane = None return plane def _compute_transform(self, F, s, t, **hints): return _inverse_laplace_transform_integration(F, s, t, self.fundamental_plane, **hints) def _as_integral(self, F, s, t): c = self.__class__._c return Integral(exp(s*t)*F, (s, c - S.ImaginaryUnit*S.Infinity, c + S.ImaginaryUnit*S.Infinity))/(2*S.Pi*S.ImaginaryUnit) def doit(self, **hints): """ Try to evaluate the transform in closed form. Explanation =========== Standard hints are the following: - ``noconds``: if True, do not return convergence conditions. The default setting is `True`. - ``simplify``: if True, it simplifies the final result. This is the default behaviour """ _noconds = hints.get('noconds', True) _simplify = hints.get('simplify', True) debugf('[ILT doit] (%s, %s, %s)', (self.function, self.function_variable, self.transform_variable)) s_ = self.function_variable t_ = self.transform_variable fn = self.function plane = self.fundamental_plane r = _inverse_laplace_transform(fn, s_, t_, plane, simplify=_simplify) if _noconds: return r[0] else: return r def inverse_laplace_transform(F, s, t, plane=None, **hints): r""" Compute the inverse Laplace transform of `F(s)`, defined as .. math :: f(t) = \frac{1}{2\pi i} \int_{c-i\infty}^{c+i\infty} e^{st} F(s) \mathrm{d}s, for `c` so large that `F(s)` has no singularites in the half-plane `\operatorname{Re}(s) > c-\epsilon`. Explanation =========== The plane can be specified by argument ``plane``, but will be inferred if passed as None. Under certain regularity conditions, this recovers `f(t)` from its Laplace Transform `F(s)`, for non-negative `t`, and vice versa. If the integral cannot be computed in closed form, this function returns an unevaluated :class:`InverseLaplaceTransform` object. Note that this function will always assume `t` to be real, regardless of the SymPy assumption on `t`. For a description of possible hints, refer to the docstring of :func:`sympy.integrals.transforms.IntegralTransform.doit`. Examples ======== >>> from sympy import inverse_laplace_transform, exp, Symbol >>> from sympy.abc import s, t >>> a = Symbol('a', positive=True) >>> inverse_laplace_transform(exp(-a*s)/s, s, t) Heaviside(-a + t) See Also ======== laplace_transform hankel_transform, inverse_hankel_transform """ if isinstance(F, MatrixBase) and hasattr(F, 'applyfunc'): return F.applyfunc(lambda Fij: inverse_laplace_transform(Fij, s, t, plane, **hints)) return InverseLaplaceTransform(F, s, t, plane).doit(**hints) def _fast_inverse_laplace(e, s, t): """Fast inverse Laplace transform of rational function including RootSum""" a, b, n = symbols('a, b, n', cls=Wild, exclude=[s]) def _ilt(e): if not e.has(s): return e elif e.is_Add: return _ilt_add(e) elif e.is_Mul: return _ilt_mul(e) elif e.is_Pow: return _ilt_pow(e) elif isinstance(e, RootSum): return _ilt_rootsum(e) else: raise NotImplementedError def _ilt_add(e): return e.func(*map(_ilt, e.args)) def _ilt_mul(e): coeff, expr = e.as_independent(s) if expr.is_Mul: raise NotImplementedError return coeff * _ilt(expr) def _ilt_pow(e): match = e.match((a*s + b)**n) if match is not None: nm, am, bm = match[n], match[a], match[b] if nm.is_Integer and nm < 0: return t**(-nm-1)*exp(-(bm/am)*t)/(am**-nm*gamma(-nm)) if nm == 1: return exp(-(bm/am)*t) / am raise NotImplementedError def _ilt_rootsum(e): expr = e.fun.expr [variable] = e.fun.variables return RootSum(e.poly, Lambda(variable, together(_ilt(expr)))) return _ilt(e)
783d1a3e6fa4f3e244459aaf05ce37687bd95898dd6947f2d0871a8ba1fbd635
from typing import Tuple as tTuple from sympy.concrete.expr_with_limits import AddWithLimits from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.containers import Tuple from sympy.core.expr import Expr from sympy.core.exprtools import factor_terms from sympy.core.function import diff from sympy.core.logic import fuzzy_bool from sympy.core.mul import Mul from sympy.core.numbers import oo, pi from sympy.core.relational import Ne from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, Wild) from sympy.core.sympify import sympify from sympy.functions import Piecewise, sqrt, piecewise_fold, tan, cot, atan from sympy.functions.elementary.exponential import log from sympy.functions.elementary.integers import floor from sympy.functions.elementary.complexes import Abs, sign from sympy.functions.elementary.miscellaneous import Min, Max from .rationaltools import ratint from sympy.matrices import MatrixBase from sympy.polys import Poly, PolynomialError from sympy.series.formal import FormalPowerSeries from sympy.series.limits import limit from sympy.series.order import Order from sympy.tensor.functions import shape from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import is_sequence from sympy.utilities.misc import filldedent class Integral(AddWithLimits): """Represents unevaluated integral.""" __slots__ = () args: tTuple[Expr, Tuple] def __new__(cls, function, *symbols, **assumptions): """Create an unevaluated integral. Explanation =========== Arguments are an integrand followed by one or more limits. If no limits are given and there is only one free symbol in the expression, that symbol will be used, otherwise an error will be raised. >>> from sympy import Integral >>> from sympy.abc import x, y >>> Integral(x) Integral(x, x) >>> Integral(y) Integral(y, y) When limits are provided, they are interpreted as follows (using ``x`` as though it were the variable of integration): (x,) or x - indefinite integral (x, a) - "evaluate at" integral is an abstract antiderivative (x, a, b) - definite integral The ``as_dummy`` method can be used to see which symbols cannot be targeted by subs: those with a prepended underscore cannot be changed with ``subs``. (Also, the integration variables themselves -- the first element of a limit -- can never be changed by subs.) >>> i = Integral(x, x) >>> at = Integral(x, (x, x)) >>> i.as_dummy() Integral(x, x) >>> at.as_dummy() Integral(_0, (_0, x)) """ #This will help other classes define their own definitions #of behaviour with Integral. if hasattr(function, '_eval_Integral'): return function._eval_Integral(*symbols, **assumptions) if isinstance(function, Poly): sympy_deprecation_warning( """ integrate(Poly) and Integral(Poly) are deprecated. Instead, use the Poly.integrate() method, or convert the Poly to an Expr first with the Poly.as_expr() method. """, deprecated_since_version="1.6", active_deprecations_target="deprecated-integrate-poly") obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions) return obj def __getnewargs__(self): return (self.function,) + tuple([tuple(xab) for xab in self.limits]) @property def free_symbols(self): """ This method returns the symbols that will exist when the integral is evaluated. This is useful if one is trying to determine whether an integral depends on a certain symbol or not. Examples ======== >>> from sympy import Integral >>> from sympy.abc import x, y >>> Integral(x, (x, y, 1)).free_symbols {y} See Also ======== sympy.concrete.expr_with_limits.ExprWithLimits.function sympy.concrete.expr_with_limits.ExprWithLimits.limits sympy.concrete.expr_with_limits.ExprWithLimits.variables """ return super().free_symbols def _eval_is_zero(self): # This is a very naive and quick test, not intended to do the integral to # answer whether it is zero or not, e.g. Integral(sin(x), (x, 0, 2*pi)) # is zero but this routine should return None for that case. But, like # Mul, there are trivial situations for which the integral will be # zero so we check for those. if self.function.is_zero: return True got_none = False for l in self.limits: if len(l) == 3: z = (l[1] == l[2]) or (l[1] - l[2]).is_zero if z: return True elif z is None: got_none = True free = self.function.free_symbols for xab in self.limits: if len(xab) == 1: free.add(xab[0]) continue if len(xab) == 2 and xab[0] not in free: if xab[1].is_zero: return True elif xab[1].is_zero is None: got_none = True # take integration symbol out of free since it will be replaced # with the free symbols in the limits free.discard(xab[0]) # add in the new symbols for i in xab[1:]: free.update(i.free_symbols) if self.function.is_zero is False and got_none is False: return False def transform(self, x, u): r""" Performs a change of variables from `x` to `u` using the relationship given by `x` and `u` which will define the transformations `f` and `F` (which are inverses of each other) as follows: 1) If `x` is a Symbol (which is a variable of integration) then `u` will be interpreted as some function, f(u), with inverse F(u). This, in effect, just makes the substitution of x with f(x). 2) If `u` is a Symbol then `x` will be interpreted as some function, F(x), with inverse f(u). This is commonly referred to as u-substitution. Once f and F have been identified, the transformation is made as follows: .. math:: \int_a^b x \mathrm{d}x \rightarrow \int_{F(a)}^{F(b)} f(x) \frac{\mathrm{d}}{\mathrm{d}x} where `F(x)` is the inverse of `f(x)` and the limits and integrand have been corrected so as to retain the same value after integration. Notes ===== The mappings, F(x) or f(u), must lead to a unique integral. Linear or rational linear expression, ``2*x``, ``1/x`` and ``sqrt(x)``, will always work; quadratic expressions like ``x**2 - 1`` are acceptable as long as the resulting integrand does not depend on the sign of the solutions (see examples). The integral will be returned unchanged if ``x`` is not a variable of integration. ``x`` must be (or contain) only one of of the integration variables. If ``u`` has more than one free symbol then it should be sent as a tuple (``u``, ``uvar``) where ``uvar`` identifies which variable is replacing the integration variable. XXX can it contain another integration variable? Examples ======== >>> from sympy.abc import a, x, u >>> from sympy import Integral, cos, sqrt >>> i = Integral(x*cos(x**2 - 1), (x, 0, 1)) transform can change the variable of integration >>> i.transform(x, u) Integral(u*cos(u**2 - 1), (u, 0, 1)) transform can perform u-substitution as long as a unique integrand is obtained: >>> i.transform(x**2 - 1, u) Integral(cos(u)/2, (u, -1, 0)) This attempt fails because x = +/-sqrt(u + 1) and the sign does not cancel out of the integrand: >>> Integral(cos(x**2 - 1), (x, 0, 1)).transform(x**2 - 1, u) Traceback (most recent call last): ... ValueError: The mapping between F(x) and f(u) did not give a unique integrand. transform can do a substitution. Here, the previous result is transformed back into the original expression using "u-substitution": >>> ui = _ >>> _.transform(sqrt(u + 1), x) == i True We can accomplish the same with a regular substitution: >>> ui.transform(u, x**2 - 1) == i True If the `x` does not contain a symbol of integration then the integral will be returned unchanged. Integral `i` does not have an integration variable `a` so no change is made: >>> i.transform(a, x) == i True When `u` has more than one free symbol the symbol that is replacing `x` must be identified by passing `u` as a tuple: >>> Integral(x, (x, 0, 1)).transform(x, (u + a, u)) Integral(a + u, (u, -a, 1 - a)) >>> Integral(x, (x, 0, 1)).transform(x, (u + a, a)) Integral(a + u, (a, -u, 1 - u)) See Also ======== sympy.concrete.expr_with_limits.ExprWithLimits.variables : Lists the integration variables as_dummy : Replace integration variables with dummy ones """ d = Dummy('d') xfree = x.free_symbols.intersection(self.variables) if len(xfree) > 1: raise ValueError( 'F(x) can only contain one of: %s' % self.variables) xvar = xfree.pop() if xfree else d if xvar not in self.variables: return self u = sympify(u) if isinstance(u, Expr): ufree = u.free_symbols if len(ufree) == 0: raise ValueError(filldedent(''' f(u) cannot be a constant''')) if len(ufree) > 1: raise ValueError(filldedent(''' When f(u) has more than one free symbol, the one replacing x must be identified: pass f(u) as (f(u), u)''')) uvar = ufree.pop() else: u, uvar = u if uvar not in u.free_symbols: raise ValueError(filldedent(''' Expecting a tuple (expr, symbol) where symbol identified a free symbol in expr, but symbol is not in expr's free symbols.''')) if not isinstance(uvar, Symbol): # This probably never evaluates to True raise ValueError(filldedent(''' Expecting a tuple (expr, symbol) but didn't get a symbol; got %s''' % uvar)) if x.is_Symbol and u.is_Symbol: return self.xreplace({x: u}) if not x.is_Symbol and not u.is_Symbol: raise ValueError('either x or u must be a symbol') if uvar == xvar: return self.transform(x, (u.subs(uvar, d), d)).xreplace({d: uvar}) if uvar in self.limits: raise ValueError(filldedent(''' u must contain the same variable as in x or a variable that is not already an integration variable''')) from sympy.solvers.solvers import solve if not x.is_Symbol: F = [x.subs(xvar, d)] soln = solve(u - x, xvar, check=False) if not soln: raise ValueError('no solution for solve(F(x) - f(u), x)') f = [fi.subs(uvar, d) for fi in soln] else: f = [u.subs(uvar, d)] from sympy.simplify.simplify import posify pdiff, reps = posify(u - x) puvar = uvar.subs([(v, k) for k, v in reps.items()]) soln = [s.subs(reps) for s in solve(pdiff, puvar)] if not soln: raise ValueError('no solution for solve(F(x) - f(u), u)') F = [fi.subs(xvar, d) for fi in soln] newfuncs = {(self.function.subs(xvar, fi)*fi.diff(d) ).subs(d, uvar) for fi in f} if len(newfuncs) > 1: raise ValueError(filldedent(''' The mapping between F(x) and f(u) did not give a unique integrand.''')) newfunc = newfuncs.pop() def _calc_limit_1(F, a, b): """ replace d with a, using subs if possible, otherwise limit where sign of b is considered """ wok = F.subs(d, a) if wok is S.NaN or wok.is_finite is False and a.is_finite: return limit(sign(b)*F, d, a) return wok def _calc_limit(a, b): """ replace d with a, using subs if possible, otherwise limit where sign of b is considered """ avals = list({_calc_limit_1(Fi, a, b) for Fi in F}) if len(avals) > 1: raise ValueError(filldedent(''' The mapping between F(x) and f(u) did not give a unique limit.''')) return avals[0] newlimits = [] for xab in self.limits: sym = xab[0] if sym == xvar: if len(xab) == 3: a, b = xab[1:] a, b = _calc_limit(a, b), _calc_limit(b, a) if fuzzy_bool(a - b > 0): a, b = b, a newfunc = -newfunc newlimits.append((uvar, a, b)) elif len(xab) == 2: a = _calc_limit(xab[1], 1) newlimits.append((uvar, a)) else: newlimits.append(uvar) else: newlimits.append(xab) return self.func(newfunc, *newlimits) def doit(self, **hints): """ Perform the integration using any hints given. Examples ======== >>> from sympy import Piecewise, S >>> from sympy.abc import x, t >>> p = x**2 + Piecewise((0, x/t < 0), (1, True)) >>> p.integrate((t, S(4)/5, 1), (x, -1, 1)) 1/3 See Also ======== sympy.integrals.trigonometry.trigintegrate sympy.integrals.heurisch.heurisch sympy.integrals.rationaltools.ratint as_sum : Approximate the integral using a sum """ if not hints.get('integrals', True): return self deep = hints.get('deep', True) meijerg = hints.get('meijerg', None) conds = hints.get('conds', 'piecewise') risch = hints.get('risch', None) heurisch = hints.get('heurisch', None) manual = hints.get('manual', None) if len(list(filter(None, (manual, meijerg, risch, heurisch)))) > 1: raise ValueError("At most one of manual, meijerg, risch, heurisch can be True") elif manual: meijerg = risch = heurisch = False elif meijerg: manual = risch = heurisch = False elif risch: manual = meijerg = heurisch = False elif heurisch: manual = meijerg = risch = False eval_kwargs = dict(meijerg=meijerg, risch=risch, manual=manual, heurisch=heurisch, conds=conds) if conds not in ('separate', 'piecewise', 'none'): raise ValueError('conds must be one of "separate", "piecewise", ' '"none", got: %s' % conds) if risch and any(len(xab) > 1 for xab in self.limits): raise ValueError('risch=True is only allowed for indefinite integrals.') # check for the trivial zero if self.is_zero: return S.Zero # hacks to handle integrals of # nested summations from sympy.concrete.summations import Sum if isinstance(self.function, Sum): if any(v in self.function.limits[0] for v in self.variables): raise ValueError('Limit of the sum cannot be an integration variable.') if any(l.is_infinite for l in self.function.limits[0][1:]): return self _i = self _sum = self.function return _sum.func(_i.func(_sum.function, *_i.limits).doit(), *_sum.limits).doit() # now compute and check the function function = self.function if deep: function = function.doit(**hints) if function.is_zero: return S.Zero # hacks to handle special cases if isinstance(function, MatrixBase): return function.applyfunc( lambda f: self.func(f, *self.limits).doit(**hints)) if isinstance(function, FormalPowerSeries): if len(self.limits) > 1: raise NotImplementedError xab = self.limits[0] if len(xab) > 1: return function.integrate(xab, **eval_kwargs) else: return function.integrate(xab[0], **eval_kwargs) # There is no trivial answer and special handling # is done so continue # first make sure any definite limits have integration # variables with matching assumptions reps = {} for xab in self.limits: if len(xab) != 3: # it makes sense to just make # all x real but in practice with the # current state of integration...this # doesn't work out well # x = xab[0] # if x not in reps and not x.is_real: # reps[x] = Dummy(real=True) continue x, a, b = xab l = (a, b) if all(i.is_nonnegative for i in l) and not x.is_nonnegative: d = Dummy(positive=True) elif all(i.is_nonpositive for i in l) and not x.is_nonpositive: d = Dummy(negative=True) elif all(i.is_real for i in l) and not x.is_real: d = Dummy(real=True) else: d = None if d: reps[x] = d if reps: undo = {v: k for k, v in reps.items()} did = self.xreplace(reps).doit(**hints) if isinstance(did, tuple): # when separate=True did = tuple([i.xreplace(undo) for i in did]) else: did = did.xreplace(undo) return did # continue with existing assumptions undone_limits = [] # ulj = free symbols of any undone limits' upper and lower limits ulj = set() for xab in self.limits: # compute uli, the free symbols in the # Upper and Lower limits of limit I if len(xab) == 1: uli = set(xab[:1]) elif len(xab) == 2: uli = xab[1].free_symbols elif len(xab) == 3: uli = xab[1].free_symbols.union(xab[2].free_symbols) # this integral can be done as long as there is no blocking # limit that has been undone. An undone limit is blocking if # it contains an integration variable that is in this limit's # upper or lower free symbols or vice versa if xab[0] in ulj or any(v[0] in uli for v in undone_limits): undone_limits.append(xab) ulj.update(uli) function = self.func(*([function] + [xab])) factored_function = function.factor() if not isinstance(factored_function, Integral): function = factored_function continue if function.has(Abs, sign) and ( (len(xab) < 3 and all(x.is_extended_real for x in xab)) or (len(xab) == 3 and all(x.is_extended_real and not x.is_infinite for x in xab[1:]))): # some improper integrals are better off with Abs xr = Dummy("xr", real=True) function = (function.xreplace({xab[0]: xr}) .rewrite(Piecewise).xreplace({xr: xab[0]})) elif function.has(Min, Max): function = function.rewrite(Piecewise) if (function.has(Piecewise) and not isinstance(function, Piecewise)): function = piecewise_fold(function) if isinstance(function, Piecewise): if len(xab) == 1: antideriv = function._eval_integral(xab[0], **eval_kwargs) else: antideriv = self._eval_integral( function, xab[0], **eval_kwargs) else: # There are a number of tradeoffs in using the # Meijer G method. It can sometimes be a lot faster # than other methods, and sometimes slower. And # there are certain types of integrals for which it # is more likely to work than others. These # heuristics are incorporated in deciding what # integration methods to try, in what order. See the # integrate() docstring for details. def try_meijerg(function, xab): ret = None if len(xab) == 3 and meijerg is not False: x, a, b = xab try: res = meijerint_definite(function, x, a, b) except NotImplementedError: _debug('NotImplementedError ' 'from meijerint_definite') res = None if res is not None: f, cond = res if conds == 'piecewise': u = self.func(function, (x, a, b)) # if Piecewise modifies cond too # much it may not be recognized by # _condsimp pattern matching so just # turn off all evaluation return Piecewise((f, cond), (u, True), evaluate=False) elif conds == 'separate': if len(self.limits) != 1: raise ValueError(filldedent(''' conds=separate not supported in multiple integrals''')) ret = f, cond else: ret = f return ret meijerg1 = meijerg if (meijerg is not False and len(xab) == 3 and xab[1].is_extended_real and xab[2].is_extended_real and not function.is_Poly and (xab[1].has(oo, -oo) or xab[2].has(oo, -oo))): ret = try_meijerg(function, xab) if ret is not None: function = ret continue meijerg1 = False # If the special meijerg code did not succeed in # finding a definite integral, then the code using # meijerint_indefinite will not either (it might # find an antiderivative, but the answer is likely # to be nonsensical). Thus if we are requested to # only use Meijer G-function methods, we give up at # this stage. Otherwise we just disable G-function # methods. if meijerg1 is False and meijerg is True: antideriv = None else: antideriv = self._eval_integral( function, xab[0], **eval_kwargs) if antideriv is None and meijerg is True: ret = try_meijerg(function, xab) if ret is not None: function = ret continue final = hints.get('final', True) # dotit may be iterated but floor terms making atan and acot # continuous should only be added in the final round if (final and not isinstance(antideriv, Integral) and antideriv is not None): for atan_term in antideriv.atoms(atan): atan_arg = atan_term.args[0] # Checking `atan_arg` to be linear combination of `tan` or `cot` for tan_part in atan_arg.atoms(tan): x1 = Dummy('x1') tan_exp1 = atan_arg.subs(tan_part, x1) # The coefficient of `tan` should be constant coeff = tan_exp1.diff(x1) if x1 not in coeff.free_symbols: a = tan_part.args[0] antideriv = antideriv.subs(atan_term, Add(atan_term, sign(coeff)*pi*floor((a-pi/2)/pi))) for cot_part in atan_arg.atoms(cot): x1 = Dummy('x1') cot_exp1 = atan_arg.subs(cot_part, x1) # The coefficient of `cot` should be constant coeff = cot_exp1.diff(x1) if x1 not in coeff.free_symbols: a = cot_part.args[0] antideriv = antideriv.subs(atan_term, Add(atan_term, sign(coeff)*pi*floor((a)/pi))) if antideriv is None: undone_limits.append(xab) function = self.func(*([function] + [xab])).factor() factored_function = function.factor() if not isinstance(factored_function, Integral): function = factored_function continue else: if len(xab) == 1: function = antideriv else: if len(xab) == 3: x, a, b = xab elif len(xab) == 2: x, b = xab a = None else: raise NotImplementedError if deep: if isinstance(a, Basic): a = a.doit(**hints) if isinstance(b, Basic): b = b.doit(**hints) if antideriv.is_Poly: gens = list(antideriv.gens) gens.remove(x) antideriv = antideriv.as_expr() function = antideriv._eval_interval(x, a, b) function = Poly(function, *gens) else: def is_indef_int(g, x): return (isinstance(g, Integral) and any(i == (x,) for i in g.limits)) def eval_factored(f, x, a, b): # _eval_interval for integrals with # (constant) factors # a single indefinite integral is assumed args = [] for g in Mul.make_args(f): if is_indef_int(g, x): args.append(g._eval_interval(x, a, b)) else: args.append(g) return Mul(*args) integrals, others, piecewises = [], [], [] for f in Add.make_args(antideriv): if any(is_indef_int(g, x) for g in Mul.make_args(f)): integrals.append(f) elif any(isinstance(g, Piecewise) for g in Mul.make_args(f)): piecewises.append(piecewise_fold(f)) else: others.append(f) uneval = Add(*[eval_factored(f, x, a, b) for f in integrals]) try: evalued = Add(*others)._eval_interval(x, a, b) evalued_pw = piecewise_fold(Add(*piecewises))._eval_interval(x, a, b) function = uneval + evalued + evalued_pw except NotImplementedError: # This can happen if _eval_interval depends in a # complicated way on limits that cannot be computed undone_limits.append(xab) function = self.func(*([function] + [xab])) factored_function = function.factor() if not isinstance(factored_function, Integral): function = factored_function return function def _eval_derivative(self, sym): """Evaluate the derivative of the current Integral object by differentiating under the integral sign [1], using the Fundamental Theorem of Calculus [2] when possible. Explanation =========== Whenever an Integral is encountered that is equivalent to zero or has an integrand that is independent of the variable of integration those integrals are performed. All others are returned as Integral instances which can be resolved with doit() (provided they are integrable). References ========== .. [1] https://en.wikipedia.org/wiki/Differentiation_under_the_integral_sign .. [2] https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus Examples ======== >>> from sympy import Integral >>> from sympy.abc import x, y >>> i = Integral(x + y, y, (y, 1, x)) >>> i.diff(x) Integral(x + y, (y, x)) + Integral(1, y, (y, 1, x)) >>> i.doit().diff(x) == i.diff(x).doit() True >>> i.diff(y) 0 The previous must be true since there is no y in the evaluated integral: >>> i.free_symbols {x} >>> i.doit() 2*x**3/3 - x/2 - 1/6 """ # differentiate under the integral sign; we do not # check for regularity conditions (TODO), see issue 4215 # get limits and the function f, limits = self.function, list(self.limits) # the order matters if variables of integration appear in the limits # so work our way in from the outside to the inside. limit = limits.pop(-1) if len(limit) == 3: x, a, b = limit elif len(limit) == 2: x, b = limit a = None else: a = b = None x = limit[0] if limits: # f is the argument to an integral f = self.func(f, *tuple(limits)) # assemble the pieces def _do(f, ab): dab_dsym = diff(ab, sym) if not dab_dsym: return S.Zero if isinstance(f, Integral): limits = [(x, x) if (len(l) == 1 and l[0] == x) else l for l in f.limits] f = self.func(f.function, *limits) return f.subs(x, ab)*dab_dsym rv = S.Zero if b is not None: rv += _do(f, b) if a is not None: rv -= _do(f, a) if len(limit) == 1 and sym == x: # the dummy variable *is* also the real-world variable arg = f rv += arg else: # the dummy variable might match sym but it's # only a dummy and the actual variable is determined # by the limits, so mask off the variable of integration # while differentiating u = Dummy('u') arg = f.subs(x, u).diff(sym).subs(u, x) if arg: rv += self.func(arg, (x, a, b)) return rv def _eval_integral(self, f, x, meijerg=None, risch=None, manual=None, heurisch=None, conds='piecewise',final=None): """ Calculate the anti-derivative to the function f(x). Explanation =========== The following algorithms are applied (roughly in this order): 1. Simple heuristics (based on pattern matching and integral table): - most frequently used functions (e.g. polynomials, products of trig functions) 2. Integration of rational functions: - A complete algorithm for integrating rational functions is implemented (the Lazard-Rioboo-Trager algorithm). The algorithm also uses the partial fraction decomposition algorithm implemented in apart() as a preprocessor to make this process faster. Note that the integral of a rational function is always elementary, but in general, it may include a RootSum. 3. Full Risch algorithm: - The Risch algorithm is a complete decision procedure for integrating elementary functions, which means that given any elementary function, it will either compute an elementary antiderivative, or else prove that none exists. Currently, part of transcendental case is implemented, meaning elementary integrals containing exponentials, logarithms, and (soon!) trigonometric functions can be computed. The algebraic case, e.g., functions containing roots, is much more difficult and is not implemented yet. - If the routine fails (because the integrand is not elementary, or because a case is not implemented yet), it continues on to the next algorithms below. If the routine proves that the integrals is nonelementary, it still moves on to the algorithms below, because we might be able to find a closed-form solution in terms of special functions. If risch=True, however, it will stop here. 4. The Meijer G-Function algorithm: - This algorithm works by first rewriting the integrand in terms of very general Meijer G-Function (meijerg in SymPy), integrating it, and then rewriting the result back, if possible. This algorithm is particularly powerful for definite integrals (which is actually part of a different method of Integral), since it can compute closed-form solutions of definite integrals even when no closed-form indefinite integral exists. But it also is capable of computing many indefinite integrals as well. - Another advantage of this method is that it can use some results about the Meijer G-Function to give a result in terms of a Piecewise expression, which allows to express conditionally convergent integrals. - Setting meijerg=True will cause integrate() to use only this method. 5. The "manual integration" algorithm: - This algorithm tries to mimic how a person would find an antiderivative by hand, for example by looking for a substitution or applying integration by parts. This algorithm does not handle as many integrands but can return results in a more familiar form. - Sometimes this algorithm can evaluate parts of an integral; in this case integrate() will try to evaluate the rest of the integrand using the other methods here. - Setting manual=True will cause integrate() to use only this method. 6. The Heuristic Risch algorithm: - This is a heuristic version of the Risch algorithm, meaning that it is not deterministic. This is tried as a last resort because it can be very slow. It is still used because not enough of the full Risch algorithm is implemented, so that there are still some integrals that can only be computed using this method. The goal is to implement enough of the Risch and Meijer G-function methods so that this can be deleted. Setting heurisch=True will cause integrate() to use only this method. Set heurisch=False to not use it. """ from sympy.integrals.risch import risch_integrate, NonElementaryIntegral from sympy.integrals.manualintegrate import manualintegrate if risch: try: return risch_integrate(f, x, conds=conds) except NotImplementedError: return None if manual: try: result = manualintegrate(f, x) if result is not None and result.func != Integral: return result except (ValueError, PolynomialError): pass eval_kwargs = dict(meijerg=meijerg, risch=risch, manual=manual, heurisch=heurisch, conds=conds) # if it is a poly(x) then let the polynomial integrate itself (fast) # # It is important to make this check first, otherwise the other code # will return a SymPy expression instead of a Polynomial. # # see Polynomial for details. if isinstance(f, Poly) and not (manual or meijerg or risch): # Note: this is deprecated, but the deprecation warning is already # issued in the Integral constructor. return f.integrate(x) # Piecewise antiderivatives need to call special integrate. if isinstance(f, Piecewise): return f.piecewise_integrate(x, **eval_kwargs) # let's cut it short if `f` does not depend on `x`; if # x is only a dummy, that will be handled below if not f.has(x): return f*x # try to convert to poly(x) and then integrate if successful (fast) poly = f.as_poly(x) if poly is not None and not (manual or meijerg or risch): return poly.integrate().as_expr() if risch is not False: try: result, i = risch_integrate(f, x, separate_integral=True, conds=conds) except NotImplementedError: pass else: if i: # There was a nonelementary integral. Try integrating it. # if no part of the NonElementaryIntegral is integrated by # the Risch algorithm, then use the original function to # integrate, instead of re-written one if result == 0: return NonElementaryIntegral(f, x).doit(risch=False) else: return result + i.doit(risch=False) else: return result # since Integral(f=g1+g2+...) == Integral(g1) + Integral(g2) + ... # we are going to handle Add terms separately, # if `f` is not Add -- we only have one term # Note that in general, this is a bad idea, because Integral(g1) + # Integral(g2) might not be computable, even if Integral(g1 + g2) is. # For example, Integral(x**x + x**x*log(x)). But many heuristics only # work term-wise. So we compute this step last, after trying # risch_integrate. We also try risch_integrate again in this loop, # because maybe the integral is a sum of an elementary part and a # nonelementary part (like erf(x) + exp(x)). risch_integrate() is # quite fast, so this is acceptable. from sympy.simplify.fu import sincos_to_sum parts = [] args = Add.make_args(f) for g in args: coeff, g = g.as_independent(x) # g(x) = const if g is S.One and not meijerg: parts.append(coeff*x) continue # g(x) = expr + O(x**n) order_term = g.getO() if order_term is not None: h = self._eval_integral(g.removeO(), x, **eval_kwargs) if h is not None: h_order_expr = self._eval_integral(order_term.expr, x, **eval_kwargs) if h_order_expr is not None: h_order_term = order_term.func( h_order_expr, *order_term.variables) parts.append(coeff*(h + h_order_term)) continue # NOTE: if there is O(x**n) and we fail to integrate then # there is no point in trying other methods because they # will fail, too. return None # c # g(x) = (a*x+b) if g.is_Pow and not g.exp.has(x) and not meijerg: a = Wild('a', exclude=[x]) b = Wild('b', exclude=[x]) M = g.base.match(a*x + b) if M is not None: if g.exp == -1: h = log(g.base) elif conds != 'piecewise': h = g.base**(g.exp + 1) / (g.exp + 1) else: h1 = log(g.base) h2 = g.base**(g.exp + 1) / (g.exp + 1) h = Piecewise((h2, Ne(g.exp, -1)), (h1, True)) parts.append(coeff * h / M[a]) continue # poly(x) # g(x) = ------- # poly(x) if g.is_rational_function(x) and not (manual or meijerg or risch): parts.append(coeff * ratint(g, x)) continue if not (manual or meijerg or risch): # g(x) = Mul(trig) h = trigintegrate(g, x, conds=conds) if h is not None: parts.append(coeff * h) continue # g(x) has at least a DiracDelta term h = deltaintegrate(g, x) if h is not None: parts.append(coeff * h) continue from .singularityfunctions import singularityintegrate # g(x) has at least a Singularity Function term h = singularityintegrate(g, x) if h is not None: parts.append(coeff * h) continue # Try risch again. if risch is not False: try: h, i = risch_integrate(g, x, separate_integral=True, conds=conds) except NotImplementedError: h = None else: if i: h = h + i.doit(risch=False) parts.append(coeff*h) continue # fall back to heurisch if heurisch is not False: from sympy.integrals.heurisch import (heurisch as heurisch_, heurisch_wrapper) try: if conds == 'piecewise': h = heurisch_wrapper(g, x, hints=[]) else: h = heurisch_(g, x, hints=[]) except PolynomialError: # XXX: this exception means there is a bug in the # implementation of heuristic Risch integration # algorithm. h = None else: h = None if meijerg is not False and h is None: # rewrite using G functions try: h = meijerint_indefinite(g, x) except NotImplementedError: _debug('NotImplementedError from meijerint_definite') if h is not None: parts.append(coeff * h) continue if h is None and manual is not False: try: result = manualintegrate(g, x) if result is not None and not isinstance(result, Integral): if result.has(Integral) and not manual: # Try to have other algorithms do the integrals # manualintegrate can't handle, # unless we were asked to use manual only. # Keep the rest of eval_kwargs in case another # method was set to False already new_eval_kwargs = eval_kwargs new_eval_kwargs["manual"] = False new_eval_kwargs["final"] = False result = result.func(*[ arg.doit(**new_eval_kwargs) if arg.has(Integral) else arg for arg in result.args ]).expand(multinomial=False, log=False, power_exp=False, power_base=False) if not result.has(Integral): parts.append(coeff * result) continue except (ValueError, PolynomialError): # can't handle some SymPy expressions pass # if we failed maybe it was because we had # a product that could have been expanded, # so let's try an expansion of the whole # thing before giving up; we don't try this # at the outset because there are things # that cannot be solved unless they are # NOT expanded e.g., x**x*(1+log(x)). There # should probably be a checker somewhere in this # routine to look for such cases and try to do # collection on the expressions if they are already # in an expanded form if not h and len(args) == 1: f = sincos_to_sum(f).expand(mul=True, deep=False) if f.is_Add: # Note: risch will be identical on the expanded # expression, but maybe it will be able to pick out parts, # like x*(exp(x) + erf(x)). return self._eval_integral(f, x, **eval_kwargs) if h is not None: parts.append(coeff * h) else: return None return Add(*parts) def _eval_lseries(self, x, logx=None, cdir=0): expr = self.as_dummy() symb = x for l in expr.limits: if x in l[1:]: symb = l[0] break for term in expr.function.lseries(symb, logx): yield integrate(term, *expr.limits) def _eval_nseries(self, x, n, logx=None, cdir=0): expr = self.as_dummy() symb = x for l in expr.limits: if x in l[1:]: symb = l[0] break terms, order = expr.function.nseries( x=symb, n=n, logx=logx).as_coeff_add(Order) order = [o.subs(symb, x) for o in order] return integrate(terms, *expr.limits) + Add(*order)*x def _eval_as_leading_term(self, x, logx=None, cdir=0): series_gen = self.args[0].lseries(x) for leading_term in series_gen: if leading_term != 0: break return integrate(leading_term, *self.args[1:]) def _eval_simplify(self, **kwargs): expr = factor_terms(self) if isinstance(expr, Integral): from sympy.simplify.simplify import simplify return expr.func(*[simplify(i, **kwargs) for i in expr.args]) return expr.simplify(**kwargs) def as_sum(self, n=None, method="midpoint", evaluate=True): """ Approximates a definite integral by a sum. Parameters ========== n : The number of subintervals to use, optional. method : One of: 'left', 'right', 'midpoint', 'trapezoid'. evaluate : bool If False, returns an unevaluated Sum expression. The default is True, evaluate the sum. Notes ===== These methods of approximate integration are described in [1]. Examples ======== >>> from sympy import Integral, sin, sqrt >>> from sympy.abc import x, n >>> e = Integral(sin(x), (x, 3, 7)) >>> e Integral(sin(x), (x, 3, 7)) For demonstration purposes, this interval will only be split into 2 regions, bounded by [3, 5] and [5, 7]. The left-hand rule uses function evaluations at the left of each interval: >>> e.as_sum(2, 'left') 2*sin(5) + 2*sin(3) The midpoint rule uses evaluations at the center of each interval: >>> e.as_sum(2, 'midpoint') 2*sin(4) + 2*sin(6) The right-hand rule uses function evaluations at the right of each interval: >>> e.as_sum(2, 'right') 2*sin(5) + 2*sin(7) The trapezoid rule uses function evaluations on both sides of the intervals. This is equivalent to taking the average of the left and right hand rule results: >>> e.as_sum(2, 'trapezoid') 2*sin(5) + sin(3) + sin(7) >>> (e.as_sum(2, 'left') + e.as_sum(2, 'right'))/2 == _ True Here, the discontinuity at x = 0 can be avoided by using the midpoint or right-hand method: >>> e = Integral(1/sqrt(x), (x, 0, 1)) >>> e.as_sum(5).n(4) 1.730 >>> e.as_sum(10).n(4) 1.809 >>> e.doit().n(4) # the actual value is 2 2.000 The left- or trapezoid method will encounter the discontinuity and return infinity: >>> e.as_sum(5, 'left') zoo The number of intervals can be symbolic. If omitted, a dummy symbol will be used for it. >>> e = Integral(x**2, (x, 0, 2)) >>> e.as_sum(n, 'right').expand() 8/3 + 4/n + 4/(3*n**2) This shows that the midpoint rule is more accurate, as its error term decays as the square of n: >>> e.as_sum(method='midpoint').expand() 8/3 - 2/(3*_n**2) A symbolic sum is returned with evaluate=False: >>> e.as_sum(n, 'midpoint', evaluate=False) 2*Sum((2*_k/n - 1/n)**2, (_k, 1, n))/n See Also ======== Integral.doit : Perform the integration using any hints References ========== .. [1] https://en.wikipedia.org/wiki/Riemann_sum#Riemann_summation_methods """ from sympy.concrete.summations import Sum limits = self.limits if len(limits) > 1: raise NotImplementedError( "Multidimensional midpoint rule not implemented yet") else: limit = limits[0] if (len(limit) != 3 or limit[1].is_finite is False or limit[2].is_finite is False): raise ValueError("Expecting a definite integral over " "a finite interval.") if n is None: n = Dummy('n', integer=True, positive=True) else: n = sympify(n) if (n.is_positive is False or n.is_integer is False or n.is_finite is False): raise ValueError("n must be a positive integer, got %s" % n) x, a, b = limit dx = (b - a)/n k = Dummy('k', integer=True, positive=True) f = self.function if method == "left": result = dx*Sum(f.subs(x, a + (k-1)*dx), (k, 1, n)) elif method == "right": result = dx*Sum(f.subs(x, a + k*dx), (k, 1, n)) elif method == "midpoint": result = dx*Sum(f.subs(x, a + k*dx - dx/2), (k, 1, n)) elif method == "trapezoid": result = dx*((f.subs(x, a) + f.subs(x, b))/2 + Sum(f.subs(x, a + k*dx), (k, 1, n - 1))) else: raise ValueError("Unknown method %s" % method) return result.doit() if evaluate else result def principal_value(self, **kwargs): """ Compute the Cauchy Principal Value of the definite integral of a real function in the given interval on the real axis. Explanation =========== In mathematics, the Cauchy principal value, is a method for assigning values to certain improper integrals which would otherwise be undefined. Examples ======== >>> from sympy import Integral, oo >>> from sympy.abc import x >>> Integral(x+1, (x, -oo, oo)).principal_value() oo >>> f = 1 / (x**3) >>> Integral(f, (x, -oo, oo)).principal_value() 0 >>> Integral(f, (x, -10, 10)).principal_value() 0 >>> Integral(f, (x, -10, oo)).principal_value() + Integral(f, (x, -oo, 10)).principal_value() 0 References ========== .. [1] https://en.wikipedia.org/wiki/Cauchy_principal_value .. [2] http://mathworld.wolfram.com/CauchyPrincipalValue.html """ if len(self.limits) != 1 or len(list(self.limits[0])) != 3: raise ValueError("You need to insert a variable, lower_limit, and upper_limit correctly to calculate " "cauchy's principal value") x, a, b = self.limits[0] if not (a.is_comparable and b.is_comparable and a <= b): raise ValueError("The lower_limit must be smaller than or equal to the upper_limit to calculate " "cauchy's principal value. Also, a and b need to be comparable.") if a == b: return S.Zero from sympy.calculus.singularities import singularities r = Dummy('r') f = self.function singularities_list = [s for s in singularities(f, x) if s.is_comparable and a <= s <= b] for i in singularities_list: if i in (a, b): raise ValueError( 'The principal value is not defined in the given interval due to singularity at %d.' % (i)) F = integrate(f, x, **kwargs) if F.has(Integral): return self if a is -oo and b is oo: I = limit(F - F.subs(x, -x), x, oo) else: I = limit(F, x, b, '-') - limit(F, x, a, '+') for s in singularities_list: I += limit(((F.subs(x, s - r)) - F.subs(x, s + r)), r, 0, '+') return I def integrate(*args, meijerg=None, conds='piecewise', risch=None, heurisch=None, manual=None, **kwargs): """integrate(f, var, ...) .. deprecated:: 1.6 Using ``integrate()`` with :class:`~.Poly` is deprecated. Use :meth:`.Poly.integrate` instead. See :ref:`deprecated-integrate-poly`. Explanation =========== Compute definite or indefinite integral of one or more variables using Risch-Norman algorithm and table lookup. This procedure is able to handle elementary algebraic and transcendental functions and also a huge class of special functions, including Airy, Bessel, Whittaker and Lambert. var can be: - a symbol -- indefinite integration - a tuple (symbol, a) -- indefinite integration with result given with ``a`` replacing ``symbol`` - a tuple (symbol, a, b) -- definite integration Several variables can be specified, in which case the result is multiple integration. (If var is omitted and the integrand is univariate, the indefinite integral in that variable will be performed.) Indefinite integrals are returned without terms that are independent of the integration variables. (see examples) Definite improper integrals often entail delicate convergence conditions. Pass conds='piecewise', 'separate' or 'none' to have these returned, respectively, as a Piecewise function, as a separate result (i.e. result will be a tuple), or not at all (default is 'piecewise'). **Strategy** SymPy uses various approaches to definite integration. One method is to find an antiderivative for the integrand, and then use the fundamental theorem of calculus. Various functions are implemented to integrate polynomial, rational and trigonometric functions, and integrands containing DiracDelta terms. SymPy also implements the part of the Risch algorithm, which is a decision procedure for integrating elementary functions, i.e., the algorithm can either find an elementary antiderivative, or prove that one does not exist. There is also a (very successful, albeit somewhat slow) general implementation of the heuristic Risch algorithm. This algorithm will eventually be phased out as more of the full Risch algorithm is implemented. See the docstring of Integral._eval_integral() for more details on computing the antiderivative using algebraic methods. The option risch=True can be used to use only the (full) Risch algorithm. This is useful if you want to know if an elementary function has an elementary antiderivative. If the indefinite Integral returned by this function is an instance of NonElementaryIntegral, that means that the Risch algorithm has proven that integral to be non-elementary. Note that by default, additional methods (such as the Meijer G method outlined below) are tried on these integrals, as they may be expressible in terms of special functions, so if you only care about elementary answers, use risch=True. Also note that an unevaluated Integral returned by this function is not necessarily a NonElementaryIntegral, even with risch=True, as it may just be an indication that the particular part of the Risch algorithm needed to integrate that function is not yet implemented. Another family of strategies comes from re-writing the integrand in terms of so-called Meijer G-functions. Indefinite integrals of a single G-function can always be computed, and the definite integral of a product of two G-functions can be computed from zero to infinity. Various strategies are implemented to rewrite integrands as G-functions, and use this information to compute integrals (see the ``meijerint`` module). The option manual=True can be used to use only an algorithm that tries to mimic integration by hand. This algorithm does not handle as many integrands as the other algorithms implemented but may return results in a more familiar form. The ``manualintegrate`` module has functions that return the steps used (see the module docstring for more information). In general, the algebraic methods work best for computing antiderivatives of (possibly complicated) combinations of elementary functions. The G-function methods work best for computing definite integrals from zero to infinity of moderately complicated combinations of special functions, or indefinite integrals of very simple combinations of special functions. The strategy employed by the integration code is as follows: - If computing a definite integral, and both limits are real, and at least one limit is +- oo, try the G-function method of definite integration first. - Try to find an antiderivative, using all available methods, ordered by performance (that is try fastest method first, slowest last; in particular polynomial integration is tried first, Meijer G-functions second to last, and heuristic Risch last). - If still not successful, try G-functions irrespective of the limits. The option meijerg=True, False, None can be used to, respectively: always use G-function methods and no others, never use G-function methods, or use all available methods (in order as described above). It defaults to None. Examples ======== >>> from sympy import integrate, log, exp, oo >>> from sympy.abc import a, x, y >>> integrate(x*y, x) x**2*y/2 >>> integrate(log(x), x) x*log(x) - x >>> integrate(log(x), (x, 1, a)) a*log(a) - a + 1 >>> integrate(x) x**2/2 Terms that are independent of x are dropped by indefinite integration: >>> from sympy import sqrt >>> integrate(sqrt(1 + x), (x, 0, x)) 2*(x + 1)**(3/2)/3 - 2/3 >>> integrate(sqrt(1 + x), x) 2*(x + 1)**(3/2)/3 >>> integrate(x*y) Traceback (most recent call last): ... ValueError: specify integration variables to integrate x*y Note that ``integrate(x)`` syntax is meant only for convenience in interactive sessions and should be avoided in library code. >>> integrate(x**a*exp(-x), (x, 0, oo)) # same as conds='piecewise' Piecewise((gamma(a + 1), re(a) > -1), (Integral(x**a*exp(-x), (x, 0, oo)), True)) >>> integrate(x**a*exp(-x), (x, 0, oo), conds='none') gamma(a + 1) >>> integrate(x**a*exp(-x), (x, 0, oo), conds='separate') (gamma(a + 1), re(a) > -1) See Also ======== Integral, Integral.doit """ doit_flags = { 'deep': False, 'meijerg': meijerg, 'conds': conds, 'risch': risch, 'heurisch': heurisch, 'manual': manual } integral = Integral(*args, **kwargs) if isinstance(integral, Integral): return integral.doit(**doit_flags) else: new_args = [a.doit(**doit_flags) if isinstance(a, Integral) else a for a in integral.args] return integral.func(*new_args) def line_integrate(field, curve, vars): """line_integrate(field, Curve, variables) Compute the line integral. Examples ======== >>> from sympy import Curve, line_integrate, E, ln >>> from sympy.abc import x, y, t >>> C = Curve([E**t + 1, E**t - 1], (t, 0, ln(2))) >>> line_integrate(x + y, C, [x, y]) 3*sqrt(2) See Also ======== sympy.integrals.integrals.integrate, Integral """ from sympy.geometry import Curve F = sympify(field) if not F: raise ValueError( "Expecting function specifying field as first argument.") if not isinstance(curve, Curve): raise ValueError("Expecting Curve entity as second argument.") if not is_sequence(vars): raise ValueError("Expecting ordered iterable for variables.") if len(curve.functions) != len(vars): raise ValueError("Field variable size does not match curve dimension.") if curve.parameter in vars: raise ValueError("Curve parameter clashes with field parameters.") # Calculate derivatives for line parameter functions # F(r) -> F(r(t)) and finally F(r(t)*r'(t)) Ft = F dldt = 0 for i, var in enumerate(vars): _f = curve.functions[i] _dn = diff(_f, curve.parameter) # ...arc length dldt = dldt + (_dn * _dn) Ft = Ft.subs(var, _f) Ft = Ft * sqrt(dldt) integral = Integral(Ft, curve.limits).doit(deep=False) return integral ### Property function dispatching ### @shape.register(Integral) def _(expr): return shape(expr.function) # Delayed imports from .deltafunctions import deltaintegrate from .meijerint import meijerint_definite, meijerint_indefinite, _debug from .trigonometry import trigintegrate
77d4d6d8a69e9dcde6c033ea40adc022ec64c32f5a26309ab39916f66fa09239
""" Integrate functions by rewriting them as Meijer G-functions. There are three user-visible functions that can be used by other parts of the sympy library to solve various integration problems: - meijerint_indefinite - meijerint_definite - meijerint_inversion They can be used to compute, respectively, indefinite integrals, definite integrals over intervals of the real line, and inverse laplace-type integrals (from c-I*oo to c+I*oo). See the respective docstrings for details. The main references for this are: [L] Luke, Y. L. (1969), The Special Functions and Their Approximations, Volume 1 [R] Kelly B. Roach. Meijer G Function Representations. In: Proceedings of the 1997 International Symposium on Symbolic and Algebraic Computation, pages 205-211, New York, 1997. ACM. [P] A. P. Prudnikov, Yu. A. Brychkov and O. I. Marichev (1990). Integrals and Series: More Special Functions, Vol. 3,. Gordon and Breach Science Publisher """ from __future__ import annotations import itertools from sympy import SYMPY_DEBUG from sympy.core import S, Expr from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.cache import cacheit from sympy.core.containers import Tuple from sympy.core.exprtools import factor_terms from sympy.core.function import (expand, expand_mul, expand_power_base, expand_trig, Function) from sympy.core.mul import Mul from sympy.core.numbers import ilcm, Rational, pi from sympy.core.relational import Eq, Ne, _canonical_coeff from sympy.core.sorting import default_sort_key, ordered from sympy.core.symbol import Dummy, symbols, Wild, Symbol from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import (re, im, arg, Abs, sign, unpolarify, polarify, polar_lift, principal_branch, unbranched_argument, periodic_argument) from sympy.functions.elementary.exponential import exp, exp_polar, log from sympy.functions.elementary.integers import ceiling from sympy.functions.elementary.hyperbolic import (cosh, sinh, _rewrite_hyperbolics_as_exp, HyperbolicFunction) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold from sympy.functions.elementary.trigonometric import (cos, sin, sinc, TrigonometricFunction) from sympy.functions.special.bessel import besselj, bessely, besseli, besselk from sympy.functions.special.delta_functions import DiracDelta, Heaviside from sympy.functions.special.elliptic_integrals import elliptic_k, elliptic_e from sympy.functions.special.error_functions import (erf, erfc, erfi, Ei, expint, Si, Ci, Shi, Chi, fresnels, fresnelc) from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import hyper, meijerg from sympy.functions.special.singularity_functions import SingularityFunction from .integrals import Integral from sympy.logic.boolalg import And, Or, BooleanAtom, Not, BooleanFunction from sympy.polys import cancel, factor from sympy.utilities.iterables import multiset_partitions from sympy.utilities.misc import debug as _debug from sympy.utilities.misc import debugf as _debugf # keep this at top for easy reference z = Dummy('z') def _has(res, *f): # return True if res has f; in the case of Piecewise # only return True if *all* pieces have f res = piecewise_fold(res) if getattr(res, 'is_Piecewise', False): return all(_has(i, *f) for i in res.args) return res.has(*f) def _create_lookup_table(table): """ Add formulae for the function -> meijerg lookup table. """ def wild(n): return Wild(n, exclude=[z]) p, q, a, b, c = list(map(wild, 'pqabc')) n = Wild('n', properties=[lambda x: x.is_Integer and x > 0]) t = p*z**q def add(formula, an, ap, bm, bq, arg=t, fac=S.One, cond=True, hint=True): table.setdefault(_mytype(formula, z), []).append((formula, [(fac, meijerg(an, ap, bm, bq, arg))], cond, hint)) def addi(formula, inst, cond, hint=True): table.setdefault( _mytype(formula, z), []).append((formula, inst, cond, hint)) def constant(a): return [(a, meijerg([1], [], [], [0], z)), (a, meijerg([], [1], [0], [], z))] table[()] = [(a, constant(a), True, True)] # [P], Section 8. class IsNonPositiveInteger(Function): @classmethod def eval(cls, arg): arg = unpolarify(arg) if arg.is_Integer is True: return arg <= 0 # Section 8.4.2 # TODO this needs more polar_lift (c/f entry for exp) add(Heaviside(t - b)*(t - b)**(a - 1), [a], [], [], [0], t/b, gamma(a)*b**(a - 1), And(b > 0)) add(Heaviside(b - t)*(b - t)**(a - 1), [], [a], [0], [], t/b, gamma(a)*b**(a - 1), And(b > 0)) add(Heaviside(z - (b/p)**(1/q))*(t - b)**(a - 1), [a], [], [], [0], t/b, gamma(a)*b**(a - 1), And(b > 0)) add(Heaviside((b/p)**(1/q) - z)*(b - t)**(a - 1), [], [a], [0], [], t/b, gamma(a)*b**(a - 1), And(b > 0)) add((b + t)**(-a), [1 - a], [], [0], [], t/b, b**(-a)/gamma(a), hint=Not(IsNonPositiveInteger(a))) add(Abs(b - t)**(-a), [1 - a], [(1 - a)/2], [0], [(1 - a)/2], t/b, 2*sin(pi*a/2)*gamma(1 - a)*Abs(b)**(-a), re(a) < 1) add((t**a - b**a)/(t - b), [0, a], [], [0, a], [], t/b, b**(a - 1)*sin(a*pi)/pi) # 12 def A1(r, sign, nu): return pi**Rational(-1, 2)*(-sign*nu/2)**(1 - 2*r) def tmpadd(r, sgn): # XXX the a**2 is bad for matching add((sqrt(a**2 + t) + sgn*a)**b/(a**2 + t)**r, [(1 + b)/2, 1 - 2*r + b/2], [], [(b - sgn*b)/2], [(b + sgn*b)/2], t/a**2, a**(b - 2*r)*A1(r, sgn, b)) tmpadd(0, 1) tmpadd(0, -1) tmpadd(S.Half, 1) tmpadd(S.Half, -1) # 13 def tmpadd(r, sgn): add((sqrt(a + p*z**q) + sgn*sqrt(p)*z**(q/2))**b/(a + p*z**q)**r, [1 - r + sgn*b/2], [1 - r - sgn*b/2], [0, S.Half], [], p*z**q/a, a**(b/2 - r)*A1(r, sgn, b)) tmpadd(0, 1) tmpadd(0, -1) tmpadd(S.Half, 1) tmpadd(S.Half, -1) # (those after look obscure) # Section 8.4.3 add(exp(polar_lift(-1)*t), [], [], [0], []) # TODO can do sin^n, sinh^n by expansion ... where? # 8.4.4 (hyperbolic functions) add(sinh(t), [], [1], [S.Half], [1, 0], t**2/4, pi**Rational(3, 2)) add(cosh(t), [], [S.Half], [0], [S.Half, S.Half], t**2/4, pi**Rational(3, 2)) # Section 8.4.5 # TODO can do t + a. but can also do by expansion... (XXX not really) add(sin(t), [], [], [S.Half], [0], t**2/4, sqrt(pi)) add(cos(t), [], [], [0], [S.Half], t**2/4, sqrt(pi)) # Section 8.4.6 (sinc function) add(sinc(t), [], [], [0], [Rational(-1, 2)], t**2/4, sqrt(pi)/2) # Section 8.5.5 def make_log1(subs): N = subs[n] return [(S.NegativeOne**N*factorial(N), meijerg([], [1]*(N + 1), [0]*(N + 1), [], t))] def make_log2(subs): N = subs[n] return [(factorial(N), meijerg([1]*(N + 1), [], [], [0]*(N + 1), t))] # TODO these only hold for positive p, and can be made more general # but who uses log(x)*Heaviside(a-x) anyway ... # TODO also it would be nice to derive them recursively ... addi(log(t)**n*Heaviside(1 - t), make_log1, True) addi(log(t)**n*Heaviside(t - 1), make_log2, True) def make_log3(subs): return make_log1(subs) + make_log2(subs) addi(log(t)**n, make_log3, True) addi(log(t + a), constant(log(a)) + [(S.One, meijerg([1, 1], [], [1], [0], t/a))], True) addi(log(Abs(t - a)), constant(log(Abs(a))) + [(pi, meijerg([1, 1], [S.Half], [1], [0, S.Half], t/a))], True) # TODO log(x)/(x+a) and log(x)/(x-1) can also be done. should they # be derivable? # TODO further formulae in this section seem obscure # Sections 8.4.9-10 # TODO # Section 8.4.11 addi(Ei(t), constant(-S.ImaginaryUnit*pi) + [(S.NegativeOne, meijerg([], [1], [0, 0], [], t*polar_lift(-1)))], True) # Section 8.4.12 add(Si(t), [1], [], [S.Half], [0, 0], t**2/4, sqrt(pi)/2) add(Ci(t), [], [1], [0, 0], [S.Half], t**2/4, -sqrt(pi)/2) # Section 8.4.13 add(Shi(t), [S.Half], [], [0], [Rational(-1, 2), Rational(-1, 2)], polar_lift(-1)*t**2/4, t*sqrt(pi)/4) add(Chi(t), [], [S.Half, 1], [0, 0], [S.Half, S.Half], t**2/4, - pi**S('3/2')/2) # generalized exponential integral add(expint(a, t), [], [a], [a - 1, 0], [], t) # Section 8.4.14 add(erf(t), [1], [], [S.Half], [0], t**2, 1/sqrt(pi)) # TODO exp(-x)*erf(I*x) does not work add(erfc(t), [], [1], [0, S.Half], [], t**2, 1/sqrt(pi)) # This formula for erfi(z) yields a wrong(?) minus sign #add(erfi(t), [1], [], [S.Half], [0], -t**2, I/sqrt(pi)) add(erfi(t), [S.Half], [], [0], [Rational(-1, 2)], -t**2, t/sqrt(pi)) # Fresnel Integrals add(fresnels(t), [1], [], [Rational(3, 4)], [0, Rational(1, 4)], pi**2*t**4/16, S.Half) add(fresnelc(t), [1], [], [Rational(1, 4)], [0, Rational(3, 4)], pi**2*t**4/16, S.Half) ##### bessel-type functions ##### # Section 8.4.19 add(besselj(a, t), [], [], [a/2], [-a/2], t**2/4) # all of the following are derivable #add(sin(t)*besselj(a, t), [Rational(1, 4), Rational(3, 4)], [], [(1+a)/2], # [-a/2, a/2, (1-a)/2], t**2, 1/sqrt(2)) #add(cos(t)*besselj(a, t), [Rational(1, 4), Rational(3, 4)], [], [a/2], # [-a/2, (1+a)/2, (1-a)/2], t**2, 1/sqrt(2)) #add(besselj(a, t)**2, [S.Half], [], [a], [-a, 0], t**2, 1/sqrt(pi)) #add(besselj(a, t)*besselj(b, t), [0, S.Half], [], [(a + b)/2], # [-(a+b)/2, (a - b)/2, (b - a)/2], t**2, 1/sqrt(pi)) # Section 8.4.20 add(bessely(a, t), [], [-(a + 1)/2], [a/2, -a/2], [-(a + 1)/2], t**2/4) # TODO all of the following should be derivable #add(sin(t)*bessely(a, t), [Rational(1, 4), Rational(3, 4)], [(1 - a - 1)/2], # [(1 + a)/2, (1 - a)/2], [(1 - a - 1)/2, (1 - 1 - a)/2, (1 - 1 + a)/2], # t**2, 1/sqrt(2)) #add(cos(t)*bessely(a, t), [Rational(1, 4), Rational(3, 4)], [(0 - a - 1)/2], # [(0 + a)/2, (0 - a)/2], [(0 - a - 1)/2, (1 - 0 - a)/2, (1 - 0 + a)/2], # t**2, 1/sqrt(2)) #add(besselj(a, t)*bessely(b, t), [0, S.Half], [(a - b - 1)/2], # [(a + b)/2, (a - b)/2], [(a - b - 1)/2, -(a + b)/2, (b - a)/2], # t**2, 1/sqrt(pi)) #addi(bessely(a, t)**2, # [(2/sqrt(pi), meijerg([], [S.Half, S.Half - a], [0, a, -a], # [S.Half - a], t**2)), # (1/sqrt(pi), meijerg([S.Half], [], [a], [-a, 0], t**2))], # True) #addi(bessely(a, t)*bessely(b, t), # [(2/sqrt(pi), meijerg([], [0, S.Half, (1 - a - b)/2], # [(a + b)/2, (a - b)/2, (b - a)/2, -(a + b)/2], # [(1 - a - b)/2], t**2)), # (1/sqrt(pi), meijerg([0, S.Half], [], [(a + b)/2], # [-(a + b)/2, (a - b)/2, (b - a)/2], t**2))], # True) # Section 8.4.21 ? # Section 8.4.22 add(besseli(a, t), [], [(1 + a)/2], [a/2], [-a/2, (1 + a)/2], t**2/4, pi) # TODO many more formulas. should all be derivable # Section 8.4.23 add(besselk(a, t), [], [], [a/2, -a/2], [], t**2/4, S.Half) # TODO many more formulas. should all be derivable # Complete elliptic integrals K(z) and E(z) add(elliptic_k(t), [S.Half, S.Half], [], [0], [0], -t, S.Half) add(elliptic_e(t), [S.Half, 3*S.Half], [], [0], [0], -t, Rational(-1, 2)/2) #################################################################### # First some helper functions. #################################################################### from sympy.utilities.timeutils import timethis timeit = timethis('meijerg') def _mytype(f: Basic, x: Symbol) -> tuple[type[Basic], ...]: """ Create a hashable entity describing the type of f. """ def key(x: type[Basic]) -> tuple[int, int, str]: return x.class_key() if x not in f.free_symbols: return () elif f.is_Function: return type(f), return tuple(sorted((t for a in f.args for t in _mytype(a, x)), key=key)) class _CoeffExpValueError(ValueError): """ Exception raised by _get_coeff_exp, for internal use only. """ pass def _get_coeff_exp(expr, x): """ When expr is known to be of the form c*x**b, with c and/or b possibly 1, return c, b. Examples ======== >>> from sympy.abc import x, a, b >>> from sympy.integrals.meijerint import _get_coeff_exp >>> _get_coeff_exp(a*x**b, x) (a, b) >>> _get_coeff_exp(x, x) (1, 1) >>> _get_coeff_exp(2*x, x) (2, 1) >>> _get_coeff_exp(x**3, x) (1, 3) """ from sympy.simplify import powsimp (c, m) = expand_power_base(powsimp(expr)).as_coeff_mul(x) if not m: return c, S.Zero [m] = m if m.is_Pow: if m.base != x: raise _CoeffExpValueError('expr not of form a*x**b') return c, m.exp elif m == x: return c, S.One else: raise _CoeffExpValueError('expr not of form a*x**b: %s' % expr) def _exponents(expr, x): """ Find the exponents of ``x`` (not including zero) in ``expr``. Examples ======== >>> from sympy.integrals.meijerint import _exponents >>> from sympy.abc import x, y >>> from sympy import sin >>> _exponents(x, x) {1} >>> _exponents(x**2, x) {2} >>> _exponents(x**2 + x, x) {1, 2} >>> _exponents(x**3*sin(x + x**y) + 1/x, x) {-1, 1, 3, y} """ def _exponents_(expr, x, res): if expr == x: res.update([1]) return if expr.is_Pow and expr.base == x: res.update([expr.exp]) return for argument in expr.args: _exponents_(argument, x, res) res = set() _exponents_(expr, x, res) return res def _functions(expr, x): """ Find the types of functions in expr, to estimate the complexity. """ return {e.func for e in expr.atoms(Function) if x in e.free_symbols} def _find_splitting_points(expr, x): """ Find numbers a such that a linear substitution x -> x + a would (hopefully) simplify expr. Examples ======== >>> from sympy.integrals.meijerint import _find_splitting_points as fsp >>> from sympy import sin >>> from sympy.abc import x >>> fsp(x, x) {0} >>> fsp((x-1)**3, x) {1} >>> fsp(sin(x+3)*x, x) {-3, 0} """ p, q = [Wild(n, exclude=[x]) for n in 'pq'] def compute_innermost(expr, res): if not isinstance(expr, Expr): return m = expr.match(p*x + q) if m and m[p] != 0: res.add(-m[q]/m[p]) return if expr.is_Atom: return for argument in expr.args: compute_innermost(argument, res) innermost = set() compute_innermost(expr, innermost) return innermost def _split_mul(f, x): """ Split expression ``f`` into fac, po, g, where fac is a constant factor, po = x**s for some s independent of s, and g is "the rest". Examples ======== >>> from sympy.integrals.meijerint import _split_mul >>> from sympy import sin >>> from sympy.abc import s, x >>> _split_mul((3*x)**s*sin(x**2)*x, x) (3**s, x*x**s, sin(x**2)) """ fac = S.One po = S.One g = S.One f = expand_power_base(f) args = Mul.make_args(f) for a in args: if a == x: po *= x elif x not in a.free_symbols: fac *= a else: if a.is_Pow and x not in a.exp.free_symbols: c, t = a.base.as_coeff_mul(x) if t != (x,): c, t = expand_mul(a.base).as_coeff_mul(x) if t == (x,): po *= x**a.exp fac *= unpolarify(polarify(c**a.exp, subs=False)) continue g *= a return fac, po, g def _mul_args(f): """ Return a list ``L`` such that ``Mul(*L) == f``. If ``f`` is not a ``Mul`` or ``Pow``, ``L=[f]``. If ``f=g**n`` for an integer ``n``, ``L=[g]*n``. If ``f`` is a ``Mul``, ``L`` comes from applying ``_mul_args`` to all factors of ``f``. """ args = Mul.make_args(f) gs = [] for g in args: if g.is_Pow and g.exp.is_Integer: n = g.exp base = g.base if n < 0: n = -n base = 1/base gs += [base]*n else: gs.append(g) return gs def _mul_as_two_parts(f): """ Find all the ways to split ``f`` into a product of two terms. Return None on failure. Explanation =========== Although the order is canonical from multiset_partitions, this is not necessarily the best order to process the terms. For example, if the case of len(gs) == 2 is removed and multiset is allowed to sort the terms, some tests fail. Examples ======== >>> from sympy.integrals.meijerint import _mul_as_two_parts >>> from sympy import sin, exp, ordered >>> from sympy.abc import x >>> list(ordered(_mul_as_two_parts(x*sin(x)*exp(x)))) [(x, exp(x)*sin(x)), (x*exp(x), sin(x)), (x*sin(x), exp(x))] """ gs = _mul_args(f) if len(gs) < 2: return None if len(gs) == 2: return [tuple(gs)] return [(Mul(*x), Mul(*y)) for (x, y) in multiset_partitions(gs, 2)] def _inflate_g(g, n): """ Return C, h such that h is a G function of argument z**n and g = C*h. """ # TODO should this be a method of meijerg? # See: [L, page 150, equation (5)] def inflate(params, n): """ (a1, .., ak) -> (a1/n, (a1+1)/n, ..., (ak + n-1)/n) """ return [(a + i)/n for a, i in itertools.product(params, range(n))] v = S(len(g.ap) - len(g.bq)) C = n**(1 + g.nu + v/2) C /= (2*pi)**((n - 1)*g.delta) return C, meijerg(inflate(g.an, n), inflate(g.aother, n), inflate(g.bm, n), inflate(g.bother, n), g.argument**n * n**(n*v)) def _flip_g(g): """ Turn the G function into one of inverse argument (i.e. G(1/x) -> G'(x)) """ # See [L], section 5.2 def tr(l): return [1 - a for a in l] return meijerg(tr(g.bm), tr(g.bother), tr(g.an), tr(g.aother), 1/g.argument) def _inflate_fox_h(g, a): r""" Let d denote the integrand in the definition of the G function ``g``. Consider the function H which is defined in the same way, but with integrand d/Gamma(a*s) (contour conventions as usual). If ``a`` is rational, the function H can be written as C*G, for a constant C and a G-function G. This function returns C, G. """ if a < 0: return _inflate_fox_h(_flip_g(g), -a) p = S(a.p) q = S(a.q) # We use the substitution s->qs, i.e. inflate g by q. We are left with an # extra factor of Gamma(p*s), for which we use Gauss' multiplication # theorem. D, g = _inflate_g(g, q) z = g.argument D /= (2*pi)**((1 - p)/2)*p**Rational(-1, 2) z /= p**p bs = [(n + 1)/p for n in range(p)] return D, meijerg(g.an, g.aother, g.bm, list(g.bother) + bs, z) _dummies: dict[tuple[str, str], Dummy] = {} def _dummy(name, token, expr, **kwargs): """ Return a dummy. This will return the same dummy if the same token+name is requested more than once, and it is not already in expr. This is for being cache-friendly. """ d = _dummy_(name, token, **kwargs) if d in expr.free_symbols: return Dummy(name, **kwargs) return d def _dummy_(name, token, **kwargs): """ Return a dummy associated to name and token. Same effect as declaring it globally. """ global _dummies if not (name, token) in _dummies: _dummies[(name, token)] = Dummy(name, **kwargs) return _dummies[(name, token)] def _is_analytic(f, x): """ Check if f(x), when expressed using G functions on the positive reals, will in fact agree with the G functions almost everywhere """ return not any(x in expr.free_symbols for expr in f.atoms(Heaviside, Abs)) def _condsimp(cond, first=True): """ Do naive simplifications on ``cond``. Explanation =========== Note that this routine is completely ad-hoc, simplification rules being added as need arises rather than following any logical pattern. Examples ======== >>> from sympy.integrals.meijerint import _condsimp as simp >>> from sympy import Or, Eq >>> from sympy.abc import x, y >>> simp(Or(x < y, Eq(x, y))) x <= y """ if first: cond = cond.replace(lambda _: _.is_Relational, _canonical_coeff) first = False if not isinstance(cond, BooleanFunction): return cond p, q, r = symbols('p q r', cls=Wild) # transforms tests use 0, 4, 5 and 11-14 # meijer tests use 0, 2, 11, 14 # joint_rv uses 6, 7 rules = [ (Or(p < q, Eq(p, q)), p <= q), # 0 # The next two obviously are instances of a general pattern, but it is # easier to spell out the few cases we care about. (And(Abs(arg(p)) <= pi, Abs(arg(p) - 2*pi) <= pi), Eq(arg(p) - pi, 0)), # 1 (And(Abs(2*arg(p) + pi) <= pi, Abs(2*arg(p) - pi) <= pi), Eq(arg(p), 0)), # 2 (And(Abs(2*arg(p) + pi) < pi, Abs(2*arg(p) - pi) <= pi), S.false), # 3 (And(Abs(arg(p) - pi/2) <= pi/2, Abs(arg(p) + pi/2) <= pi/2), Eq(arg(p), 0)), # 4 (And(Abs(arg(p) - pi/2) <= pi/2, Abs(arg(p) + pi/2) < pi/2), S.false), # 5 (And(Abs(arg(p**2/2 + 1)) < pi, Ne(Abs(arg(p**2/2 + 1)), pi)), S.true), # 6 (Or(Abs(arg(p**2/2 + 1)) < pi, Ne(1/(p**2/2 + 1), 0)), S.true), # 7 (And(Abs(unbranched_argument(p)) <= pi, Abs(unbranched_argument(exp_polar(-2*pi*S.ImaginaryUnit)*p)) <= pi), Eq(unbranched_argument(exp_polar(-S.ImaginaryUnit*pi)*p), 0)), # 8 (And(Abs(unbranched_argument(p)) <= pi/2, Abs(unbranched_argument(exp_polar(-pi*S.ImaginaryUnit)*p)) <= pi/2), Eq(unbranched_argument(exp_polar(-S.ImaginaryUnit*pi/2)*p), 0)), # 9 (Or(p <= q, And(p < q, r)), p <= q), # 10 (Ne(p**2, 1) & (p**2 > 1), p**2 > 1), # 11 (Ne(1/p, 1) & (cos(Abs(arg(p)))*Abs(p) > 1), Abs(p) > 1), # 12 (Ne(p, 2) & (cos(Abs(arg(p)))*Abs(p) > 2), Abs(p) > 2), # 13 ((Abs(arg(p)) < pi/2) & (cos(Abs(arg(p)))*sqrt(Abs(p**2)) > 1), p**2 > 1), # 14 ] cond = cond.func(*list(map(lambda _: _condsimp(_, first), cond.args))) change = True while change: change = False for irule, (fro, to) in enumerate(rules): if fro.func != cond.func: continue for n, arg1 in enumerate(cond.args): if r in fro.args[0].free_symbols: m = arg1.match(fro.args[1]) num = 1 else: num = 0 m = arg1.match(fro.args[0]) if not m: continue otherargs = [x.subs(m) for x in fro.args[:num] + fro.args[num + 1:]] otherlist = [n] for arg2 in otherargs: for k, arg3 in enumerate(cond.args): if k in otherlist: continue if arg2 == arg3: otherlist += [k] break if isinstance(arg3, And) and arg2.args[1] == r and \ isinstance(arg2, And) and arg2.args[0] in arg3.args: otherlist += [k] break if isinstance(arg3, And) and arg2.args[0] == r and \ isinstance(arg2, And) and arg2.args[1] in arg3.args: otherlist += [k] break if len(otherlist) != len(otherargs) + 1: continue newargs = [arg_ for (k, arg_) in enumerate(cond.args) if k not in otherlist] + [to.subs(m)] if SYMPY_DEBUG: if irule not in (0, 2, 4, 5, 6, 7, 11, 12, 13, 14): print('used new rule:', irule) cond = cond.func(*newargs) change = True break # final tweak def rel_touchup(rel): if rel.rel_op != '==' or rel.rhs != 0: return rel # handle Eq(*, 0) LHS = rel.lhs m = LHS.match(arg(p)**q) if not m: m = LHS.match(unbranched_argument(polar_lift(p)**q)) if not m: if isinstance(LHS, periodic_argument) and not LHS.args[0].is_polar \ and LHS.args[1] is S.Infinity: return (LHS.args[0] > 0) return rel return (m[p] > 0) cond = cond.replace(lambda _: _.is_Relational, rel_touchup) if SYMPY_DEBUG: print('_condsimp: ', cond) return cond def _eval_cond(cond): """ Re-evaluate the conditions. """ if isinstance(cond, bool): return cond return _condsimp(cond.doit()) #################################################################### # Now the "backbone" functions to do actual integration. #################################################################### def _my_principal_branch(expr, period, full_pb=False): """ Bring expr nearer to its principal branch by removing superfluous factors. This function does *not* guarantee to yield the principal branch, to avoid introducing opaque principal_branch() objects, unless full_pb=True. """ res = principal_branch(expr, period) if not full_pb: res = res.replace(principal_branch, lambda x, y: x) return res def _rewrite_saxena_1(fac, po, g, x): """ Rewrite the integral fac*po*g dx, from zero to infinity, as integral fac*G, where G has argument a*x. Note po=x**s. Return fac, G. """ _, s = _get_coeff_exp(po, x) a, b = _get_coeff_exp(g.argument, x) period = g.get_period() a = _my_principal_branch(a, period) # We substitute t = x**b. C = fac/(Abs(b)*a**((s + 1)/b - 1)) # Absorb a factor of (at)**((1 + s)/b - 1). def tr(l): return [a + (1 + s)/b - 1 for a in l] return C, meijerg(tr(g.an), tr(g.aother), tr(g.bm), tr(g.bother), a*x) def _check_antecedents_1(g, x, helper=False): r""" Return a condition under which the mellin transform of g exists. Any power of x has already been absorbed into the G function, so this is just $\int_0^\infty g\, dx$. See [L, section 5.6.1]. (Note that s=1.) If ``helper`` is True, only check if the MT exists at infinity, i.e. if $\int_1^\infty g\, dx$ exists. """ # NOTE if you update these conditions, please update the documentation as well delta = g.delta eta, _ = _get_coeff_exp(g.argument, x) m, n, p, q = S([len(g.bm), len(g.an), len(g.ap), len(g.bq)]) if p > q: def tr(l): return [1 - x for x in l] return _check_antecedents_1(meijerg(tr(g.bm), tr(g.bother), tr(g.an), tr(g.aother), x/eta), x) tmp = [-re(b) < 1 for b in g.bm] + [1 < 1 - re(a) for a in g.an] cond_3 = And(*tmp) tmp += [-re(b) < 1 for b in g.bother] tmp += [1 < 1 - re(a) for a in g.aother] cond_3_star = And(*tmp) cond_4 = (-re(g.nu) + (q + 1 - p)/2 > q - p) def debug(*msg): _debug(*msg) def debugf(string, arg): _debugf(string, arg) debug('Checking antecedents for 1 function:') debugf(' delta=%s, eta=%s, m=%s, n=%s, p=%s, q=%s', (delta, eta, m, n, p, q)) debugf(' ap = %s, %s', (list(g.an), list(g.aother))) debugf(' bq = %s, %s', (list(g.bm), list(g.bother))) debugf(' cond_3=%s, cond_3*=%s, cond_4=%s', (cond_3, cond_3_star, cond_4)) conds = [] # case 1 case1 = [] tmp1 = [1 <= n, p < q, 1 <= m] tmp2 = [1 <= p, 1 <= m, Eq(q, p + 1), Not(And(Eq(n, 0), Eq(m, p + 1)))] tmp3 = [1 <= p, Eq(q, p)] for k in range(ceiling(delta/2) + 1): tmp3 += [Ne(Abs(unbranched_argument(eta)), (delta - 2*k)*pi)] tmp = [delta > 0, Abs(unbranched_argument(eta)) < delta*pi] extra = [Ne(eta, 0), cond_3] if helper: extra = [] for t in [tmp1, tmp2, tmp3]: case1 += [And(*(t + tmp + extra))] conds += case1 debug(' case 1:', case1) # case 2 extra = [cond_3] if helper: extra = [] case2 = [And(Eq(n, 0), p + 1 <= m, m <= q, Abs(unbranched_argument(eta)) < delta*pi, *extra)] conds += case2 debug(' case 2:', case2) # case 3 extra = [cond_3, cond_4] if helper: extra = [] case3 = [And(p < q, 1 <= m, delta > 0, Eq(Abs(unbranched_argument(eta)), delta*pi), *extra)] case3 += [And(p <= q - 2, Eq(delta, 0), Eq(Abs(unbranched_argument(eta)), 0), *extra)] conds += case3 debug(' case 3:', case3) # TODO altered cases 4-7 # extra case from wofram functions site: # (reproduced verbatim from Prudnikov, section 2.24.2) # http://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/01/ case_extra = [] case_extra += [Eq(p, q), Eq(delta, 0), Eq(unbranched_argument(eta), 0), Ne(eta, 0)] if not helper: case_extra += [cond_3] s = [] for a, b in zip(g.ap, g.bq): s += [b - a] case_extra += [re(Add(*s)) < 0] case_extra = And(*case_extra) conds += [case_extra] debug(' extra case:', [case_extra]) case_extra_2 = [And(delta > 0, Abs(unbranched_argument(eta)) < delta*pi)] if not helper: case_extra_2 += [cond_3] case_extra_2 = And(*case_extra_2) conds += [case_extra_2] debug(' second extra case:', [case_extra_2]) # TODO This leaves only one case from the three listed by Prudnikov. # Investigate if these indeed cover everything; if so, remove the rest. return Or(*conds) def _int0oo_1(g, x): r""" Evaluate $\int_0^\infty g\, dx$ using G functions, assuming the necessary conditions are fulfilled. Examples ======== >>> from sympy.abc import a, b, c, d, x, y >>> from sympy import meijerg >>> from sympy.integrals.meijerint import _int0oo_1 >>> _int0oo_1(meijerg([a], [b], [c], [d], x*y), x) gamma(-a)*gamma(c + 1)/(y*gamma(-d)*gamma(b + 1)) """ from sympy.simplify import gammasimp # See [L, section 5.6.1]. Note that s=1. eta, _ = _get_coeff_exp(g.argument, x) res = 1/eta # XXX TODO we should reduce order first for b in g.bm: res *= gamma(b + 1) for a in g.an: res *= gamma(1 - a - 1) for b in g.bother: res /= gamma(1 - b - 1) for a in g.aother: res /= gamma(a + 1) return gammasimp(unpolarify(res)) def _rewrite_saxena(fac, po, g1, g2, x, full_pb=False): """ Rewrite the integral ``fac*po*g1*g2`` from 0 to oo in terms of G functions with argument ``c*x``. Explanation =========== Return C, f1, f2 such that integral C f1 f2 from 0 to infinity equals integral fac ``po``, ``g1``, ``g2`` from 0 to infinity. Examples ======== >>> from sympy.integrals.meijerint import _rewrite_saxena >>> from sympy.abc import s, t, m >>> from sympy import meijerg >>> g1 = meijerg([], [], [0], [], s*t) >>> g2 = meijerg([], [], [m/2], [-m/2], t**2/4) >>> r = _rewrite_saxena(1, t**0, g1, g2, t) >>> r[0] s/(4*sqrt(pi)) >>> r[1] meijerg(((), ()), ((-1/2, 0), ()), s**2*t/4) >>> r[2] meijerg(((), ()), ((m/2,), (-m/2,)), t/4) """ def pb(g): a, b = _get_coeff_exp(g.argument, x) per = g.get_period() return meijerg(g.an, g.aother, g.bm, g.bother, _my_principal_branch(a, per, full_pb)*x**b) _, s = _get_coeff_exp(po, x) _, b1 = _get_coeff_exp(g1.argument, x) _, b2 = _get_coeff_exp(g2.argument, x) if (b1 < 0) == True: b1 = -b1 g1 = _flip_g(g1) if (b2 < 0) == True: b2 = -b2 g2 = _flip_g(g2) if not b1.is_Rational or not b2.is_Rational: return m1, n1 = b1.p, b1.q m2, n2 = b2.p, b2.q tau = ilcm(m1*n2, m2*n1) r1 = tau//(m1*n2) r2 = tau//(m2*n1) C1, g1 = _inflate_g(g1, r1) C2, g2 = _inflate_g(g2, r2) g1 = pb(g1) g2 = pb(g2) fac *= C1*C2 a1, b = _get_coeff_exp(g1.argument, x) a2, _ = _get_coeff_exp(g2.argument, x) # arbitrarily tack on the x**s part to g1 # TODO should we try both? exp = (s + 1)/b - 1 fac = fac/(Abs(b) * a1**exp) def tr(l): return [a + exp for a in l] g1 = meijerg(tr(g1.an), tr(g1.aother), tr(g1.bm), tr(g1.bother), a1*x) g2 = meijerg(g2.an, g2.aother, g2.bm, g2.bother, a2*x) from sympy.simplify import powdenest return powdenest(fac, polar=True), g1, g2 def _check_antecedents(g1, g2, x): """ Return a condition under which the integral theorem applies. """ # Yes, this is madness. # XXX TODO this is a testing *nightmare* # NOTE if you update these conditions, please update the documentation as well # The following conditions are found in # [P], Section 2.24.1 # # They are also reproduced (verbatim!) at # http://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/03/ # # Note: k=l=r=alpha=1 sigma, _ = _get_coeff_exp(g1.argument, x) omega, _ = _get_coeff_exp(g2.argument, x) s, t, u, v = S([len(g1.bm), len(g1.an), len(g1.ap), len(g1.bq)]) m, n, p, q = S([len(g2.bm), len(g2.an), len(g2.ap), len(g2.bq)]) bstar = s + t - (u + v)/2 cstar = m + n - (p + q)/2 rho = g1.nu + (u - v)/2 + 1 mu = g2.nu + (p - q)/2 + 1 phi = q - p - (v - u) eta = 1 - (v - u) - mu - rho psi = (pi*(q - m - n) + Abs(unbranched_argument(omega)))/(q - p) theta = (pi*(v - s - t) + Abs(unbranched_argument(sigma)))/(v - u) _debug('Checking antecedents:') _debugf(' sigma=%s, s=%s, t=%s, u=%s, v=%s, b*=%s, rho=%s', (sigma, s, t, u, v, bstar, rho)) _debugf(' omega=%s, m=%s, n=%s, p=%s, q=%s, c*=%s, mu=%s,', (omega, m, n, p, q, cstar, mu)) _debugf(' phi=%s, eta=%s, psi=%s, theta=%s', (phi, eta, psi, theta)) def _c1(): for g in [g1, g2]: for i, j in itertools.product(g.an, g.bm): diff = i - j if diff.is_integer and diff.is_positive: return False return True c1 = _c1() c2 = And(*[re(1 + i + j) > 0 for i in g1.bm for j in g2.bm]) c3 = And(*[re(1 + i + j) < 1 + 1 for i in g1.an for j in g2.an]) c4 = And(*[(p - q)*re(1 + i - 1) - re(mu) > Rational(-3, 2) for i in g1.an]) c5 = And(*[(p - q)*re(1 + i) - re(mu) > Rational(-3, 2) for i in g1.bm]) c6 = And(*[(u - v)*re(1 + i - 1) - re(rho) > Rational(-3, 2) for i in g2.an]) c7 = And(*[(u - v)*re(1 + i) - re(rho) > Rational(-3, 2) for i in g2.bm]) c8 = (Abs(phi) + 2*re((rho - 1)*(q - p) + (v - u)*(q - p) + (mu - 1)*(v - u)) > 0) c9 = (Abs(phi) - 2*re((rho - 1)*(q - p) + (v - u)*(q - p) + (mu - 1)*(v - u)) > 0) c10 = (Abs(unbranched_argument(sigma)) < bstar*pi) c11 = Eq(Abs(unbranched_argument(sigma)), bstar*pi) c12 = (Abs(unbranched_argument(omega)) < cstar*pi) c13 = Eq(Abs(unbranched_argument(omega)), cstar*pi) # The following condition is *not* implemented as stated on the wolfram # function site. In the book of Prudnikov there is an additional part # (the And involving re()). However, I only have this book in russian, and # I don't read any russian. The following condition is what other people # have told me it means. # Worryingly, it is different from the condition implemented in REDUCE. # The REDUCE implementation: # https://reduce-algebra.svn.sourceforge.net/svnroot/reduce-algebra/trunk/packages/defint/definta.red # (search for tst14) # The Wolfram alpha version: # http://functions.wolfram.com/HypergeometricFunctions/MeijerG/21/02/03/03/0014/ z0 = exp(-(bstar + cstar)*pi*S.ImaginaryUnit) zos = unpolarify(z0*omega/sigma) zso = unpolarify(z0*sigma/omega) if zos == 1/zso: c14 = And(Eq(phi, 0), bstar + cstar <= 1, Or(Ne(zos, 1), re(mu + rho + v - u) < 1, re(mu + rho + q - p) < 1)) else: def _cond(z): '''Returns True if abs(arg(1-z)) < pi, avoiding arg(0). Explanation =========== If ``z`` is 1 then arg is NaN. This raises a TypeError on `NaN < pi`. Previously this gave `False` so this behavior has been hardcoded here but someone should check if this NaN is more serious! This NaN is triggered by test_meijerint() in test_meijerint.py: `meijerint_definite(exp(x), x, 0, I)` ''' return z != 1 and Abs(arg(1 - z)) < pi c14 = And(Eq(phi, 0), bstar - 1 + cstar <= 0, Or(And(Ne(zos, 1), _cond(zos)), And(re(mu + rho + v - u) < 1, Eq(zos, 1)))) c14_alt = And(Eq(phi, 0), cstar - 1 + bstar <= 0, Or(And(Ne(zso, 1), _cond(zso)), And(re(mu + rho + q - p) < 1, Eq(zso, 1)))) # Since r=k=l=1, in our case there is c14_alt which is the same as calling # us with (g1, g2) = (g2, g1). The conditions below enumerate all cases # (i.e. we don't have to try arguments reversed by hand), and indeed try # all symmetric cases. (i.e. whenever there is a condition involving c14, # there is also a dual condition which is exactly what we would get when g1, # g2 were interchanged, *but c14 was unaltered*). # Hence the following seems correct: c14 = Or(c14, c14_alt) ''' When `c15` is NaN (e.g. from `psi` being NaN as happens during 'test_issue_4992' and/or `theta` is NaN as in 'test_issue_6253', both in `test_integrals.py`) the comparison to 0 formerly gave False whereas now an error is raised. To keep the old behavior, the value of NaN is replaced with False but perhaps a closer look at this condition should be made: XXX how should conditions leading to c15=NaN be handled? ''' try: lambda_c = (q - p)*Abs(omega)**(1/(q - p))*cos(psi) \ + (v - u)*Abs(sigma)**(1/(v - u))*cos(theta) # the TypeError might be raised here, e.g. if lambda_c is NaN if _eval_cond(lambda_c > 0) != False: c15 = (lambda_c > 0) else: def lambda_s0(c1, c2): return c1*(q - p)*Abs(omega)**(1/(q - p))*sin(psi) \ + c2*(v - u)*Abs(sigma)**(1/(v - u))*sin(theta) lambda_s = Piecewise( ((lambda_s0(+1, +1)*lambda_s0(-1, -1)), And(Eq(unbranched_argument(sigma), 0), Eq(unbranched_argument(omega), 0))), (lambda_s0(sign(unbranched_argument(omega)), +1)*lambda_s0(sign(unbranched_argument(omega)), -1), And(Eq(unbranched_argument(sigma), 0), Ne(unbranched_argument(omega), 0))), (lambda_s0(+1, sign(unbranched_argument(sigma)))*lambda_s0(-1, sign(unbranched_argument(sigma))), And(Ne(unbranched_argument(sigma), 0), Eq(unbranched_argument(omega), 0))), (lambda_s0(sign(unbranched_argument(omega)), sign(unbranched_argument(sigma))), True)) tmp = [lambda_c > 0, And(Eq(lambda_c, 0), Ne(lambda_s, 0), re(eta) > -1), And(Eq(lambda_c, 0), Eq(lambda_s, 0), re(eta) > 0)] c15 = Or(*tmp) except TypeError: c15 = False for cond, i in [(c1, 1), (c2, 2), (c3, 3), (c4, 4), (c5, 5), (c6, 6), (c7, 7), (c8, 8), (c9, 9), (c10, 10), (c11, 11), (c12, 12), (c13, 13), (c14, 14), (c15, 15)]: _debugf(' c%s: %s', (i, cond)) # We will return Or(*conds) conds = [] def pr(count): _debugf(' case %s: %s', (count, conds[-1])) conds += [And(m*n*s*t != 0, bstar.is_positive is True, cstar.is_positive is True, c1, c2, c3, c10, c12)] # 1 pr(1) conds += [And(Eq(u, v), Eq(bstar, 0), cstar.is_positive is True, sigma.is_positive is True, re(rho) < 1, c1, c2, c3, c12)] # 2 pr(2) conds += [And(Eq(p, q), Eq(cstar, 0), bstar.is_positive is True, omega.is_positive is True, re(mu) < 1, c1, c2, c3, c10)] # 3 pr(3) conds += [And(Eq(p, q), Eq(u, v), Eq(bstar, 0), Eq(cstar, 0), sigma.is_positive is True, omega.is_positive is True, re(mu) < 1, re(rho) < 1, Ne(sigma, omega), c1, c2, c3)] # 4 pr(4) conds += [And(Eq(p, q), Eq(u, v), Eq(bstar, 0), Eq(cstar, 0), sigma.is_positive is True, omega.is_positive is True, re(mu + rho) < 1, Ne(omega, sigma), c1, c2, c3)] # 5 pr(5) conds += [And(p > q, s.is_positive is True, bstar.is_positive is True, cstar >= 0, c1, c2, c3, c5, c10, c13)] # 6 pr(6) conds += [And(p < q, t.is_positive is True, bstar.is_positive is True, cstar >= 0, c1, c2, c3, c4, c10, c13)] # 7 pr(7) conds += [And(u > v, m.is_positive is True, cstar.is_positive is True, bstar >= 0, c1, c2, c3, c7, c11, c12)] # 8 pr(8) conds += [And(u < v, n.is_positive is True, cstar.is_positive is True, bstar >= 0, c1, c2, c3, c6, c11, c12)] # 9 pr(9) conds += [And(p > q, Eq(u, v), Eq(bstar, 0), cstar >= 0, sigma.is_positive is True, re(rho) < 1, c1, c2, c3, c5, c13)] # 10 pr(10) conds += [And(p < q, Eq(u, v), Eq(bstar, 0), cstar >= 0, sigma.is_positive is True, re(rho) < 1, c1, c2, c3, c4, c13)] # 11 pr(11) conds += [And(Eq(p, q), u > v, bstar >= 0, Eq(cstar, 0), omega.is_positive is True, re(mu) < 1, c1, c2, c3, c7, c11)] # 12 pr(12) conds += [And(Eq(p, q), u < v, bstar >= 0, Eq(cstar, 0), omega.is_positive is True, re(mu) < 1, c1, c2, c3, c6, c11)] # 13 pr(13) conds += [And(p < q, u > v, bstar >= 0, cstar >= 0, c1, c2, c3, c4, c7, c11, c13)] # 14 pr(14) conds += [And(p > q, u < v, bstar >= 0, cstar >= 0, c1, c2, c3, c5, c6, c11, c13)] # 15 pr(15) conds += [And(p > q, u > v, bstar >= 0, cstar >= 0, c1, c2, c3, c5, c7, c8, c11, c13, c14)] # 16 pr(16) conds += [And(p < q, u < v, bstar >= 0, cstar >= 0, c1, c2, c3, c4, c6, c9, c11, c13, c14)] # 17 pr(17) conds += [And(Eq(t, 0), s.is_positive is True, bstar.is_positive is True, phi.is_positive is True, c1, c2, c10)] # 18 pr(18) conds += [And(Eq(s, 0), t.is_positive is True, bstar.is_positive is True, phi.is_negative is True, c1, c3, c10)] # 19 pr(19) conds += [And(Eq(n, 0), m.is_positive is True, cstar.is_positive is True, phi.is_negative is True, c1, c2, c12)] # 20 pr(20) conds += [And(Eq(m, 0), n.is_positive is True, cstar.is_positive is True, phi.is_positive is True, c1, c3, c12)] # 21 pr(21) conds += [And(Eq(s*t, 0), bstar.is_positive is True, cstar.is_positive is True, c1, c2, c3, c10, c12)] # 22 pr(22) conds += [And(Eq(m*n, 0), bstar.is_positive is True, cstar.is_positive is True, c1, c2, c3, c10, c12)] # 23 pr(23) # The following case is from [Luke1969]. As far as I can tell, it is *not* # covered by Prudnikov's. # Let G1 and G2 be the two G-functions. Suppose the integral exists from # 0 to a > 0 (this is easy the easy part), that G1 is exponential decay at # infinity, and that the mellin transform of G2 exists. # Then the integral exists. mt1_exists = _check_antecedents_1(g1, x, helper=True) mt2_exists = _check_antecedents_1(g2, x, helper=True) conds += [And(mt2_exists, Eq(t, 0), u < s, bstar.is_positive is True, c10, c1, c2, c3)] pr('E1') conds += [And(mt2_exists, Eq(s, 0), v < t, bstar.is_positive is True, c10, c1, c2, c3)] pr('E2') conds += [And(mt1_exists, Eq(n, 0), p < m, cstar.is_positive is True, c12, c1, c2, c3)] pr('E3') conds += [And(mt1_exists, Eq(m, 0), q < n, cstar.is_positive is True, c12, c1, c2, c3)] pr('E4') # Let's short-circuit if this worked ... # the rest is corner-cases and terrible to read. r = Or(*conds) if _eval_cond(r) != False: return r conds += [And(m + n > p, Eq(t, 0), Eq(phi, 0), s.is_positive is True, bstar.is_positive is True, cstar.is_negative is True, Abs(unbranched_argument(omega)) < (m + n - p + 1)*pi, c1, c2, c10, c14, c15)] # 24 pr(24) conds += [And(m + n > q, Eq(s, 0), Eq(phi, 0), t.is_positive is True, bstar.is_positive is True, cstar.is_negative is True, Abs(unbranched_argument(omega)) < (m + n - q + 1)*pi, c1, c3, c10, c14, c15)] # 25 pr(25) conds += [And(Eq(p, q - 1), Eq(t, 0), Eq(phi, 0), s.is_positive is True, bstar.is_positive is True, cstar >= 0, cstar*pi < Abs(unbranched_argument(omega)), c1, c2, c10, c14, c15)] # 26 pr(26) conds += [And(Eq(p, q + 1), Eq(s, 0), Eq(phi, 0), t.is_positive is True, bstar.is_positive is True, cstar >= 0, cstar*pi < Abs(unbranched_argument(omega)), c1, c3, c10, c14, c15)] # 27 pr(27) conds += [And(p < q - 1, Eq(t, 0), Eq(phi, 0), s.is_positive is True, bstar.is_positive is True, cstar >= 0, cstar*pi < Abs(unbranched_argument(omega)), Abs(unbranched_argument(omega)) < (m + n - p + 1)*pi, c1, c2, c10, c14, c15)] # 28 pr(28) conds += [And( p > q + 1, Eq(s, 0), Eq(phi, 0), t.is_positive is True, bstar.is_positive is True, cstar >= 0, cstar*pi < Abs(unbranched_argument(omega)), Abs(unbranched_argument(omega)) < (m + n - q + 1)*pi, c1, c3, c10, c14, c15)] # 29 pr(29) conds += [And(Eq(n, 0), Eq(phi, 0), s + t > 0, m.is_positive is True, cstar.is_positive is True, bstar.is_negative is True, Abs(unbranched_argument(sigma)) < (s + t - u + 1)*pi, c1, c2, c12, c14, c15)] # 30 pr(30) conds += [And(Eq(m, 0), Eq(phi, 0), s + t > v, n.is_positive is True, cstar.is_positive is True, bstar.is_negative is True, Abs(unbranched_argument(sigma)) < (s + t - v + 1)*pi, c1, c3, c12, c14, c15)] # 31 pr(31) conds += [And(Eq(n, 0), Eq(phi, 0), Eq(u, v - 1), m.is_positive is True, cstar.is_positive is True, bstar >= 0, bstar*pi < Abs(unbranched_argument(sigma)), Abs(unbranched_argument(sigma)) < (bstar + 1)*pi, c1, c2, c12, c14, c15)] # 32 pr(32) conds += [And(Eq(m, 0), Eq(phi, 0), Eq(u, v + 1), n.is_positive is True, cstar.is_positive is True, bstar >= 0, bstar*pi < Abs(unbranched_argument(sigma)), Abs(unbranched_argument(sigma)) < (bstar + 1)*pi, c1, c3, c12, c14, c15)] # 33 pr(33) conds += [And( Eq(n, 0), Eq(phi, 0), u < v - 1, m.is_positive is True, cstar.is_positive is True, bstar >= 0, bstar*pi < Abs(unbranched_argument(sigma)), Abs(unbranched_argument(sigma)) < (s + t - u + 1)*pi, c1, c2, c12, c14, c15)] # 34 pr(34) conds += [And( Eq(m, 0), Eq(phi, 0), u > v + 1, n.is_positive is True, cstar.is_positive is True, bstar >= 0, bstar*pi < Abs(unbranched_argument(sigma)), Abs(unbranched_argument(sigma)) < (s + t - v + 1)*pi, c1, c3, c12, c14, c15)] # 35 pr(35) return Or(*conds) # NOTE An alternative, but as far as I can tell weaker, set of conditions # can be found in [L, section 5.6.2]. def _int0oo(g1, g2, x): """ Express integral from zero to infinity g1*g2 using a G function, assuming the necessary conditions are fulfilled. Examples ======== >>> from sympy.integrals.meijerint import _int0oo >>> from sympy.abc import s, t, m >>> from sympy import meijerg, S >>> g1 = meijerg([], [], [-S(1)/2, 0], [], s**2*t/4) >>> g2 = meijerg([], [], [m/2], [-m/2], t/4) >>> _int0oo(g1, g2, t) 4*meijerg(((1/2, 0), ()), ((m/2,), (-m/2,)), s**(-2))/s**2 """ # See: [L, section 5.6.2, equation (1)] eta, _ = _get_coeff_exp(g1.argument, x) omega, _ = _get_coeff_exp(g2.argument, x) def neg(l): return [-x for x in l] a1 = neg(g1.bm) + list(g2.an) a2 = list(g2.aother) + neg(g1.bother) b1 = neg(g1.an) + list(g2.bm) b2 = list(g2.bother) + neg(g1.aother) return meijerg(a1, a2, b1, b2, omega/eta)/eta def _rewrite_inversion(fac, po, g, x): """ Absorb ``po`` == x**s into g. """ _, s = _get_coeff_exp(po, x) a, b = _get_coeff_exp(g.argument, x) def tr(l): return [t + s/b for t in l] from sympy.simplify import powdenest return (powdenest(fac/a**(s/b), polar=True), meijerg(tr(g.an), tr(g.aother), tr(g.bm), tr(g.bother), g.argument)) def _check_antecedents_inversion(g, x): """ Check antecedents for the laplace inversion integral. """ _debug('Checking antecedents for inversion:') z = g.argument _, e = _get_coeff_exp(z, x) if e < 0: _debug(' Flipping G.') # We want to assume that argument gets large as |x| -> oo return _check_antecedents_inversion(_flip_g(g), x) def statement_half(a, b, c, z, plus): coeff, exponent = _get_coeff_exp(z, x) a *= exponent b *= coeff**c c *= exponent conds = [] wp = b*exp(S.ImaginaryUnit*re(c)*pi/2) wm = b*exp(-S.ImaginaryUnit*re(c)*pi/2) if plus: w = wp else: w = wm conds += [And(Or(Eq(b, 0), re(c) <= 0), re(a) <= -1)] conds += [And(Ne(b, 0), Eq(im(c), 0), re(c) > 0, re(w) < 0)] conds += [And(Ne(b, 0), Eq(im(c), 0), re(c) > 0, re(w) <= 0, re(a) <= -1)] return Or(*conds) def statement(a, b, c, z): """ Provide a convergence statement for z**a * exp(b*z**c), c/f sphinx docs. """ return And(statement_half(a, b, c, z, True), statement_half(a, b, c, z, False)) # Notations from [L], section 5.7-10 m, n, p, q = S([len(g.bm), len(g.an), len(g.ap), len(g.bq)]) tau = m + n - p nu = q - m - n rho = (tau - nu)/2 sigma = q - p if sigma == 1: epsilon = S.Half elif sigma > 1: epsilon = 1 else: epsilon = S.NaN theta = ((1 - sigma)/2 + Add(*g.bq) - Add(*g.ap))/sigma delta = g.delta _debugf(' m=%s, n=%s, p=%s, q=%s, tau=%s, nu=%s, rho=%s, sigma=%s', (m, n, p, q, tau, nu, rho, sigma)) _debugf(' epsilon=%s, theta=%s, delta=%s', (epsilon, theta, delta)) # First check if the computation is valid. if not (g.delta >= e/2 or (p >= 1 and p >= q)): _debug(' Computation not valid for these parameters.') return False # Now check if the inversion integral exists. # Test "condition A" for a, b in itertools.product(g.an, g.bm): if (a - b).is_integer and a > b: _debug(' Not a valid G function.') return False # There are two cases. If p >= q, we can directly use a slater expansion # like [L], 5.2 (11). Note in particular that the asymptotics of such an # expansion even hold when some of the parameters differ by integers, i.e. # the formula itself would not be valid! (b/c G functions are cts. in their # parameters) # When p < q, we need to use the theorems of [L], 5.10. if p >= q: _debug(' Using asymptotic Slater expansion.') return And(*[statement(a - 1, 0, 0, z) for a in g.an]) def E(z): return And(*[statement(a - 1, 0, 0, z) for a in g.an]) def H(z): return statement(theta, -sigma, 1/sigma, z) def Hp(z): return statement_half(theta, -sigma, 1/sigma, z, True) def Hm(z): return statement_half(theta, -sigma, 1/sigma, z, False) # [L], section 5.10 conds = [] # Theorem 1 -- p < q from test above conds += [And(1 <= n, 1 <= m, rho*pi - delta >= pi/2, delta > 0, E(z*exp(S.ImaginaryUnit*pi*(nu + 1))))] # Theorem 2, statements (2) and (3) conds += [And(p + 1 <= m, m + 1 <= q, delta > 0, delta < pi/2, n == 0, (m - p + 1)*pi - delta >= pi/2, Hp(z*exp(S.ImaginaryUnit*pi*(q - m))), Hm(z*exp(-S.ImaginaryUnit*pi*(q - m))))] # Theorem 2, statement (5) -- p < q from test above conds += [And(m == q, n == 0, delta > 0, (sigma + epsilon)*pi - delta >= pi/2, H(z))] # Theorem 3, statements (6) and (7) conds += [And(Or(And(p <= q - 2, 1 <= tau, tau <= sigma/2), And(p + 1 <= m + n, m + n <= (p + q)/2)), delta > 0, delta < pi/2, (tau + 1)*pi - delta >= pi/2, Hp(z*exp(S.ImaginaryUnit*pi*nu)), Hm(z*exp(-S.ImaginaryUnit*pi*nu)))] # Theorem 4, statements (10) and (11) -- p < q from test above conds += [And(1 <= m, rho > 0, delta > 0, delta + rho*pi < pi/2, (tau + epsilon)*pi - delta >= pi/2, Hp(z*exp(S.ImaginaryUnit*pi*nu)), Hm(z*exp(-S.ImaginaryUnit*pi*nu)))] # Trivial case conds += [m == 0] # TODO # Theorem 5 is quite general # Theorem 6 contains special cases for q=p+1 return Or(*conds) def _int_inversion(g, x, t): """ Compute the laplace inversion integral, assuming the formula applies. """ b, a = _get_coeff_exp(g.argument, x) C, g = _inflate_fox_h(meijerg(g.an, g.aother, g.bm, g.bother, b/t**a), -a) return C/t*g #################################################################### # Finally, the real meat. #################################################################### _lookup_table = None @cacheit @timeit def _rewrite_single(f, x, recursive=True): """ Try to rewrite f as a sum of single G functions of the form C*x**s*G(a*x**b), where b is a rational number and C is independent of x. We guarantee that result.argument.as_coeff_mul(x) returns (a, (x**b,)) or (a, ()). Returns a list of tuples (C, s, G) and a condition cond. Returns None on failure. """ from .transforms import (mellin_transform, inverse_mellin_transform, IntegralTransformError, MellinTransformStripError) global _lookup_table if not _lookup_table: _lookup_table = {} _create_lookup_table(_lookup_table) if isinstance(f, meijerg): coeff, m = factor(f.argument, x).as_coeff_mul(x) if len(m) > 1: return None m = m[0] if m.is_Pow: if m.base != x or not m.exp.is_Rational: return None elif m != x: return None return [(1, 0, meijerg(f.an, f.aother, f.bm, f.bother, coeff*m))], True f_ = f f = f.subs(x, z) t = _mytype(f, z) if t in _lookup_table: l = _lookup_table[t] for formula, terms, cond, hint in l: subs = f.match(formula, old=True) if subs: subs_ = {} for fro, to in subs.items(): subs_[fro] = unpolarify(polarify(to, lift=True), exponents_only=True) subs = subs_ if not isinstance(hint, bool): hint = hint.subs(subs) if hint == False: continue if not isinstance(cond, (bool, BooleanAtom)): cond = unpolarify(cond.subs(subs)) if _eval_cond(cond) == False: continue if not isinstance(terms, list): terms = terms(subs) res = [] for fac, g in terms: r1 = _get_coeff_exp(unpolarify(fac.subs(subs).subs(z, x), exponents_only=True), x) try: g = g.subs(subs).subs(z, x) except ValueError: continue # NOTE these substitutions can in principle introduce oo, # zoo and other absurdities. It shouldn't matter, # but better be safe. if Tuple(*(r1 + (g,))).has(S.Infinity, S.ComplexInfinity, S.NegativeInfinity): continue g = meijerg(g.an, g.aother, g.bm, g.bother, unpolarify(g.argument, exponents_only=True)) res.append(r1 + (g,)) if res: return res, cond # try recursive mellin transform if not recursive: return None _debug('Trying recursive Mellin transform method.') def my_imt(F, s, x, strip): """ Calling simplify() all the time is slow and not helpful, since most of the time it only factors things in a way that has to be un-done anyway. But sometimes it can remove apparent poles. """ # XXX should this be in inverse_mellin_transform? try: return inverse_mellin_transform(F, s, x, strip, as_meijerg=True, needeval=True) except MellinTransformStripError: from sympy.simplify import simplify return inverse_mellin_transform( simplify(cancel(expand(F))), s, x, strip, as_meijerg=True, needeval=True) f = f_ s = _dummy('s', 'rewrite-single', f) # to avoid infinite recursion, we have to force the two g functions case def my_integrator(f, x): r = _meijerint_definite_4(f, x, only_double=True) if r is not None: from sympy.simplify import hyperexpand res, cond = r res = _my_unpolarify(hyperexpand(res, rewrite='nonrepsmall')) return Piecewise((res, cond), (Integral(f, (x, S.Zero, S.Infinity)), True)) return Integral(f, (x, S.Zero, S.Infinity)) try: F, strip, _ = mellin_transform(f, x, s, integrator=my_integrator, simplify=False, needeval=True) g = my_imt(F, s, x, strip) except IntegralTransformError: g = None if g is None: # We try to find an expression by analytic continuation. # (also if the dummy is already in the expression, there is no point in # putting in another one) a = _dummy_('a', 'rewrite-single') if a not in f.free_symbols and _is_analytic(f, x): try: F, strip, _ = mellin_transform(f.subs(x, a*x), x, s, integrator=my_integrator, needeval=True, simplify=False) g = my_imt(F, s, x, strip).subs(a, 1) except IntegralTransformError: g = None if g is None or g.has(S.Infinity, S.NaN, S.ComplexInfinity): _debug('Recursive Mellin transform failed.') return None args = Add.make_args(g) res = [] for f in args: c, m = f.as_coeff_mul(x) if len(m) > 1: raise NotImplementedError('Unexpected form...') g = m[0] a, b = _get_coeff_exp(g.argument, x) res += [(c, 0, meijerg(g.an, g.aother, g.bm, g.bother, unpolarify(polarify( a, lift=True), exponents_only=True) *x**b))] _debug('Recursive Mellin transform worked:', g) return res, True def _rewrite1(f, x, recursive=True): """ Try to rewrite ``f`` using a (sum of) single G functions with argument a*x**b. Return fac, po, g such that f = fac*po*g, fac is independent of ``x``. and po = x**s. Here g is a result from _rewrite_single. Return None on failure. """ fac, po, g = _split_mul(f, x) g = _rewrite_single(g, x, recursive) if g: return fac, po, g[0], g[1] def _rewrite2(f, x): """ Try to rewrite ``f`` as a product of two G functions of arguments a*x**b. Return fac, po, g1, g2 such that f = fac*po*g1*g2, where fac is independent of x and po is x**s. Here g1 and g2 are results of _rewrite_single. Returns None on failure. """ fac, po, g = _split_mul(f, x) if any(_rewrite_single(expr, x, False) is None for expr in _mul_args(g)): return None l = _mul_as_two_parts(g) if not l: return None l = list(ordered(l, [ lambda p: max(len(_exponents(p[0], x)), len(_exponents(p[1], x))), lambda p: max(len(_functions(p[0], x)), len(_functions(p[1], x))), lambda p: max(len(_find_splitting_points(p[0], x)), len(_find_splitting_points(p[1], x)))])) for recursive, (fac1, fac2) in itertools.product((False, True), l): g1 = _rewrite_single(fac1, x, recursive) g2 = _rewrite_single(fac2, x, recursive) if g1 and g2: cond = And(g1[1], g2[1]) if cond != False: return fac, po, g1[0], g2[0], cond def meijerint_indefinite(f, x): """ Compute an indefinite integral of ``f`` by rewriting it as a G function. Examples ======== >>> from sympy.integrals.meijerint import meijerint_indefinite >>> from sympy import sin >>> from sympy.abc import x >>> meijerint_indefinite(sin(x), x) -cos(x) """ f = sympify(f) results = [] for a in sorted(_find_splitting_points(f, x) | {S.Zero}, key=default_sort_key): res = _meijerint_indefinite_1(f.subs(x, x + a), x) if not res: continue res = res.subs(x, x - a) if _has(res, hyper, meijerg): results.append(res) else: return res if f.has(HyperbolicFunction): _debug('Try rewriting hyperbolics in terms of exp.') rv = meijerint_indefinite( _rewrite_hyperbolics_as_exp(f), x) if rv: if not isinstance(rv, list): from sympy.simplify.radsimp import collect return collect(factor_terms(rv), rv.atoms(exp)) results.extend(rv) if results: return next(ordered(results)) def _meijerint_indefinite_1(f, x): """ Helper that does not attempt any substitution. """ _debug('Trying to compute the indefinite integral of', f, 'wrt', x) from sympy.simplify import hyperexpand, powdenest gs = _rewrite1(f, x) if gs is None: # Note: the code that calls us will do expand() and try again return None fac, po, gl, cond = gs _debug(' could rewrite:', gs) res = S.Zero for C, s, g in gl: a, b = _get_coeff_exp(g.argument, x) _, c = _get_coeff_exp(po, x) c += s # we do a substitution t=a*x**b, get integrand fac*t**rho*g fac_ = fac * C / (b*a**((1 + c)/b)) rho = (c + 1)/b - 1 # we now use t**rho*G(params, t) = G(params + rho, t) # [L, page 150, equation (4)] # and integral G(params, t) dt = G(1, params+1, 0, t) # (or a similar expression with 1 and 0 exchanged ... pick the one # which yields a well-defined function) # [R, section 5] # (Note that this dummy will immediately go away again, so we # can safely pass S.One for ``expr``.) t = _dummy('t', 'meijerint-indefinite', S.One) def tr(p): return [a + rho + 1 for a in p] if any(b.is_integer and (b <= 0) == True for b in tr(g.bm)): r = -meijerg( tr(g.an), tr(g.aother) + [1], tr(g.bm) + [0], tr(g.bother), t) else: r = meijerg( tr(g.an) + [1], tr(g.aother), tr(g.bm), tr(g.bother) + [0], t) # The antiderivative is most often expected to be defined # in the neighborhood of x = 0. if b.is_extended_nonnegative and not f.subs(x, 0).has(S.NaN, S.ComplexInfinity): place = 0 # Assume we can expand at zero else: place = None r = hyperexpand(r.subs(t, a*x**b), place=place) # now substitute back # Note: we really do want the powers of x to combine. res += powdenest(fac_*r, polar=True) def _clean(res): """This multiplies out superfluous powers of x we created, and chops off constants: >> _clean(x*(exp(x)/x - 1/x) + 3) exp(x) cancel is used before mul_expand since it is possible for an expression to have an additive constant that does not become isolated with simple expansion. Such a situation was identified in issue 6369: Examples ======== >>> from sympy import sqrt, cancel >>> from sympy.abc import x >>> a = sqrt(2*x + 1) >>> bad = (3*x*a**5 + 2*x - a**5 + 1)/a**2 >>> bad.expand().as_independent(x)[0] 0 >>> cancel(bad).expand().as_independent(x)[0] 1 """ res = expand_mul(cancel(res), deep=False) return Add._from_args(res.as_coeff_add(x)[1]) res = piecewise_fold(res, evaluate=None) if res.is_Piecewise: newargs = [] for e, c in res.args: e = _my_unpolarify(_clean(e)) newargs += [(e, c)] res = Piecewise(*newargs, evaluate=False) else: res = _my_unpolarify(_clean(res)) return Piecewise((res, _my_unpolarify(cond)), (Integral(f, x), True)) @timeit def meijerint_definite(f, x, a, b): """ Integrate ``f`` over the interval [``a``, ``b``], by rewriting it as a product of two G functions, or as a single G function. Return res, cond, where cond are convergence conditions. Examples ======== >>> from sympy.integrals.meijerint import meijerint_definite >>> from sympy import exp, oo >>> from sympy.abc import x >>> meijerint_definite(exp(-x**2), x, -oo, oo) (sqrt(pi), True) This function is implemented as a succession of functions meijerint_definite, _meijerint_definite_2, _meijerint_definite_3, _meijerint_definite_4. Each function in the list calls the next one (presumably) several times. This means that calling meijerint_definite can be very costly. """ # This consists of three steps: # 1) Change the integration limits to 0, oo # 2) Rewrite in terms of G functions # 3) Evaluate the integral # # There are usually several ways of doing this, and we want to try all. # This function does (1), calls _meijerint_definite_2 for step (2). _debugf('Integrating %s wrt %s from %s to %s.', (f, x, a, b)) f = sympify(f) if f.has(DiracDelta): _debug('Integrand has DiracDelta terms - giving up.') return None if f.has(SingularityFunction): _debug('Integrand has Singularity Function terms - giving up.') return None f_, x_, a_, b_ = f, x, a, b # Let's use a dummy in case any of the boundaries has x. d = Dummy('x') f = f.subs(x, d) x = d if a == b: return (S.Zero, True) results = [] if a is S.NegativeInfinity and b is not S.Infinity: return meijerint_definite(f.subs(x, -x), x, -b, -a) elif a is S.NegativeInfinity: # Integrating -oo to oo. We need to find a place to split the integral. _debug(' Integrating -oo to +oo.') innermost = _find_splitting_points(f, x) _debug(' Sensible splitting points:', innermost) for c in sorted(innermost, key=default_sort_key, reverse=True) + [S.Zero]: _debug(' Trying to split at', c) if not c.is_extended_real: _debug(' Non-real splitting point.') continue res1 = _meijerint_definite_2(f.subs(x, x + c), x) if res1 is None: _debug(' But could not compute first integral.') continue res2 = _meijerint_definite_2(f.subs(x, c - x), x) if res2 is None: _debug(' But could not compute second integral.') continue res1, cond1 = res1 res2, cond2 = res2 cond = _condsimp(And(cond1, cond2)) if cond == False: _debug(' But combined condition is always false.') continue res = res1 + res2 return res, cond elif a is S.Infinity: res = meijerint_definite(f, x, b, S.Infinity) return -res[0], res[1] elif (a, b) == (S.Zero, S.Infinity): # This is a common case - try it directly first. res = _meijerint_definite_2(f, x) if res: if _has(res[0], meijerg): results.append(res) else: return res else: if b is S.Infinity: for split in _find_splitting_points(f, x): if (a - split >= 0) == True: _debugf('Trying x -> x + %s', split) res = _meijerint_definite_2(f.subs(x, x + split) *Heaviside(x + split - a), x) if res: if _has(res[0], meijerg): results.append(res) else: return res f = f.subs(x, x + a) b = b - a a = 0 if b is not S.Infinity: phi = exp(S.ImaginaryUnit*arg(b)) b = Abs(b) f = f.subs(x, phi*x) f *= Heaviside(b - x)*phi b = S.Infinity _debug('Changed limits to', a, b) _debug('Changed function to', f) res = _meijerint_definite_2(f, x) if res: if _has(res[0], meijerg): results.append(res) else: return res if f_.has(HyperbolicFunction): _debug('Try rewriting hyperbolics in terms of exp.') rv = meijerint_definite( _rewrite_hyperbolics_as_exp(f_), x_, a_, b_) if rv: if not isinstance(rv, list): from sympy.simplify.radsimp import collect rv = (collect(factor_terms(rv[0]), rv[0].atoms(exp)),) + rv[1:] return rv results.extend(rv) if results: return next(ordered(results)) def _guess_expansion(f, x): """ Try to guess sensible rewritings for integrand f(x). """ res = [(f, 'original integrand')] orig = res[-1][0] saw = {orig} expanded = expand_mul(orig) if expanded not in saw: res += [(expanded, 'expand_mul')] saw.add(expanded) expanded = expand(orig) if expanded not in saw: res += [(expanded, 'expand')] saw.add(expanded) if orig.has(TrigonometricFunction, HyperbolicFunction): expanded = expand_mul(expand_trig(orig)) if expanded not in saw: res += [(expanded, 'expand_trig, expand_mul')] saw.add(expanded) if orig.has(cos, sin): from sympy.simplify.fu import sincos_to_sum reduced = sincos_to_sum(orig) if reduced not in saw: res += [(reduced, 'trig power reduction')] saw.add(reduced) return res def _meijerint_definite_2(f, x): """ Try to integrate f dx from zero to infinity. The body of this function computes various 'simplifications' f1, f2, ... of f (e.g. by calling expand_mul(), trigexpand() - see _guess_expansion) and calls _meijerint_definite_3 with each of these in succession. If _meijerint_definite_3 succeeds with any of the simplified functions, returns this result. """ # This function does preparation for (2), calls # _meijerint_definite_3 for (2) and (3) combined. # use a positive dummy - we integrate from 0 to oo # XXX if a nonnegative symbol is used there will be test failures dummy = _dummy('x', 'meijerint-definite2', f, positive=True) f = f.subs(x, dummy) x = dummy if f == 0: return S.Zero, True for g, explanation in _guess_expansion(f, x): _debug('Trying', explanation) res = _meijerint_definite_3(g, x) if res: return res def _meijerint_definite_3(f, x): """ Try to integrate f dx from zero to infinity. This function calls _meijerint_definite_4 to try to compute the integral. If this fails, it tries using linearity. """ res = _meijerint_definite_4(f, x) if res and res[1] != False: return res if f.is_Add: _debug('Expanding and evaluating all terms.') ress = [_meijerint_definite_4(g, x) for g in f.args] if all(r is not None for r in ress): conds = [] res = S.Zero for r, c in ress: res += r conds += [c] c = And(*conds) if c != False: return res, c def _my_unpolarify(f): return _eval_cond(unpolarify(f)) @timeit def _meijerint_definite_4(f, x, only_double=False): """ Try to integrate f dx from zero to infinity. Explanation =========== This function tries to apply the integration theorems found in literature, i.e. it tries to rewrite f as either one or a product of two G-functions. The parameter ``only_double`` is used internally in the recursive algorithm to disable trying to rewrite f as a single G-function. """ from sympy.simplify import hyperexpand # This function does (2) and (3) _debug('Integrating', f) # Try single G function. if not only_double: gs = _rewrite1(f, x, recursive=False) if gs is not None: fac, po, g, cond = gs _debug('Could rewrite as single G function:', fac, po, g) res = S.Zero for C, s, f in g: if C == 0: continue C, f = _rewrite_saxena_1(fac*C, po*x**s, f, x) res += C*_int0oo_1(f, x) cond = And(cond, _check_antecedents_1(f, x)) if cond == False: break cond = _my_unpolarify(cond) if cond == False: _debug('But cond is always False.') else: _debug('Result before branch substitutions is:', res) return _my_unpolarify(hyperexpand(res)), cond # Try two G functions. gs = _rewrite2(f, x) if gs is not None: for full_pb in [False, True]: fac, po, g1, g2, cond = gs _debug('Could rewrite as two G functions:', fac, po, g1, g2) res = S.Zero for C1, s1, f1 in g1: for C2, s2, f2 in g2: r = _rewrite_saxena(fac*C1*C2, po*x**(s1 + s2), f1, f2, x, full_pb) if r is None: _debug('Non-rational exponents.') return C, f1_, f2_ = r _debug('Saxena subst for yielded:', C, f1_, f2_) cond = And(cond, _check_antecedents(f1_, f2_, x)) if cond == False: break res += C*_int0oo(f1_, f2_, x) else: continue break cond = _my_unpolarify(cond) if cond == False: _debugf('But cond is always False (full_pb=%s).', full_pb) else: _debugf('Result before branch substitutions is: %s', (res, )) if only_double: return res, cond return _my_unpolarify(hyperexpand(res)), cond def meijerint_inversion(f, x, t): r""" Compute the inverse laplace transform $\int_{c+i\infty}^{c-i\infty} f(x) e^{tx}\, dx$, for real c larger than the real part of all singularities of ``f``. Note that ``t`` is always assumed real and positive. Return None if the integral does not exist or could not be evaluated. Examples ======== >>> from sympy.abc import x, t >>> from sympy.integrals.meijerint import meijerint_inversion >>> meijerint_inversion(1/x, x, t) Heaviside(t) """ f_ = f t_ = t t = Dummy('t', polar=True) # We don't want sqrt(t**2) = abs(t) etc f = f.subs(t_, t) _debug('Laplace-inverting', f) if not _is_analytic(f, x): _debug('But expression is not analytic.') return None # Exponentials correspond to shifts; we filter them out and then # shift the result later. If we are given an Add this will not # work, but the calling code will take care of that. shift = S.Zero if f.is_Mul: args = list(f.args) elif isinstance(f, exp): args = [f] else: args = None if args: newargs = [] exponentials = [] while args: arg = args.pop() if isinstance(arg, exp): arg2 = expand(arg) if arg2.is_Mul: args += arg2.args continue try: a, b = _get_coeff_exp(arg.args[0], x) except _CoeffExpValueError: b = 0 if b == 1: exponentials.append(a) else: newargs.append(arg) elif arg.is_Pow: arg2 = expand(arg) if arg2.is_Mul: args += arg2.args continue if x not in arg.base.free_symbols: try: a, b = _get_coeff_exp(arg.exp, x) except _CoeffExpValueError: b = 0 if b == 1: exponentials.append(a*log(arg.base)) newargs.append(arg) else: newargs.append(arg) shift = Add(*exponentials) f = Mul(*newargs) if x not in f.free_symbols: _debug('Expression consists of constant and exp shift:', f, shift) cond = Eq(im(shift), 0) if cond == False: _debug('but shift is nonreal, cannot be a Laplace transform') return None res = f*DiracDelta(t + shift) _debug('Result is a delta function, possibly conditional:', res, cond) # cond is True or Eq return Piecewise((res.subs(t, t_), cond)) gs = _rewrite1(f, x) if gs is not None: fac, po, g, cond = gs _debug('Could rewrite as single G function:', fac, po, g) res = S.Zero for C, s, f in g: C, f = _rewrite_inversion(fac*C, po*x**s, f, x) res += C*_int_inversion(f, x, t) cond = And(cond, _check_antecedents_inversion(f, x)) if cond == False: break cond = _my_unpolarify(cond) if cond == False: _debug('But cond is always False.') else: _debug('Result before branch substitution:', res) from sympy.simplify import hyperexpand res = _my_unpolarify(hyperexpand(res)) if not res.has(Heaviside): res *= Heaviside(t) res = res.subs(t, t + shift) if not isinstance(cond, bool): cond = cond.subs(t, t + shift) from .transforms import InverseLaplaceTransform return Piecewise((res.subs(t, t_), cond), (InverseLaplaceTransform(f_.subs(t, t_), x, t_, None), True))
ab57976d28326f9583455adf43385cead67376b0ddf28dbac53146b965a3840b
"""Base class for all the objects in SymPy""" from __future__ import annotations from collections import defaultdict from collections.abc import Mapping from itertools import chain, zip_longest from .assumptions import ManagedProperties from .cache import cacheit from .sympify import _sympify, sympify, SympifyError, _external_converter from .sorting import ordered from .kind import Kind, UndefinedKind from ._print_helpers import Printable from sympy.utilities.decorator import deprecated from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import iterable, numbered_symbols from sympy.utilities.misc import filldedent, func_name from inspect import getmro def as_Basic(expr): """Return expr as a Basic instance using strict sympify or raise a TypeError; this is just a wrapper to _sympify, raising a TypeError instead of a SympifyError.""" try: return _sympify(expr) except SympifyError: raise TypeError( 'Argument must be a Basic object, not `%s`' % func_name( expr)) class Basic(Printable, metaclass=ManagedProperties): """ Base class for all SymPy objects. Notes and conventions ===================== 1) Always use ``.args``, when accessing parameters of some instance: >>> from sympy import cot >>> from sympy.abc import x, y >>> cot(x).args (x,) >>> cot(x).args[0] x >>> (x*y).args (x, y) >>> (x*y).args[1] y 2) Never use internal methods or variables (the ones prefixed with ``_``): >>> cot(x)._args # do not use this, use cot(x).args instead (x,) 3) By "SymPy object" we mean something that can be returned by ``sympify``. But not all objects one encounters using SymPy are subclasses of Basic. For example, mutable objects are not: >>> from sympy import Basic, Matrix, sympify >>> A = Matrix([[1, 2], [3, 4]]).as_mutable() >>> isinstance(A, Basic) False >>> B = sympify(A) >>> isinstance(B, Basic) True """ __slots__ = ('_mhash', # hash value '_args', # arguments '_assumptions' ) _args: tuple[Basic, ...] _mhash: int | None # To be overridden with True in the appropriate subclasses is_number = False is_Atom = False is_Symbol = False is_symbol = False is_Indexed = False is_Dummy = False is_Wild = False is_Function = False is_Add = False is_Mul = False is_Pow = False is_Number = False is_Float = False is_Rational = False is_Integer = False is_NumberSymbol = False is_Order = False is_Derivative = False is_Piecewise = False is_Poly = False is_AlgebraicNumber = False is_Relational = False is_Equality = False is_Boolean = False is_Not = False is_Matrix = False is_Vector = False is_Point = False is_MatAdd = False is_MatMul = False is_real: bool | None is_extended_real: bool | None is_zero: bool | None is_negative: bool | None is_commutative: bool | None kind: Kind = UndefinedKind def __new__(cls, *args): obj = object.__new__(cls) obj._assumptions = cls.default_assumptions obj._mhash = None # will be set by __hash__ method. obj._args = args # all items in args must be Basic objects return obj def copy(self): return self.func(*self.args) def __getnewargs__(self): return self.args def __getstate__(self): return None def __setstate__(self, state): for name, value in state.items(): setattr(self, name, value) def __reduce_ex__(self, protocol): if protocol < 2: msg = "Only pickle protocol 2 or higher is supported by SymPy" raise NotImplementedError(msg) return super().__reduce_ex__(protocol) def __hash__(self) -> int: # hash cannot be cached using cache_it because infinite recurrence # occurs as hash is needed for setting cache dictionary keys h = self._mhash if h is None: h = hash((type(self).__name__,) + self._hashable_content()) self._mhash = h return h def _hashable_content(self): """Return a tuple of information about self that can be used to compute the hash. If a class defines additional attributes, like ``name`` in Symbol, then this method should be updated accordingly to return such relevant attributes. Defining more than _hashable_content is necessary if __eq__ has been defined by a class. See note about this in Basic.__eq__.""" return self._args @property def assumptions0(self): """ Return object `type` assumptions. For example: Symbol('x', real=True) Symbol('x', integer=True) are different objects. In other words, besides Python type (Symbol in this case), the initial assumptions are also forming their typeinfo. Examples ======== >>> from sympy import Symbol >>> from sympy.abc import x >>> x.assumptions0 {'commutative': True} >>> x = Symbol("x", positive=True) >>> x.assumptions0 {'commutative': True, 'complex': True, 'extended_negative': False, 'extended_nonnegative': True, 'extended_nonpositive': False, 'extended_nonzero': True, 'extended_positive': True, 'extended_real': True, 'finite': True, 'hermitian': True, 'imaginary': False, 'infinite': False, 'negative': False, 'nonnegative': True, 'nonpositive': False, 'nonzero': True, 'positive': True, 'real': True, 'zero': False} """ return {} def compare(self, other): """ Return -1, 0, 1 if the object is smaller, equal, or greater than other. Not in the mathematical sense. If the object is of a different type from the "other" then their classes are ordered according to the sorted_classes list. Examples ======== >>> from sympy.abc import x, y >>> x.compare(y) -1 >>> x.compare(x) 0 >>> y.compare(x) 1 """ # all redefinitions of __cmp__ method should start with the # following lines: if self is other: return 0 n1 = self.__class__ n2 = other.__class__ c = (n1 > n2) - (n1 < n2) if c: return c # st = self._hashable_content() ot = other._hashable_content() c = (len(st) > len(ot)) - (len(st) < len(ot)) if c: return c for l, r in zip(st, ot): l = Basic(*l) if isinstance(l, frozenset) else l r = Basic(*r) if isinstance(r, frozenset) else r if isinstance(l, Basic): c = l.compare(r) else: c = (l > r) - (l < r) if c: return c return 0 @staticmethod def _compare_pretty(a, b): from sympy.series.order import Order if isinstance(a, Order) and not isinstance(b, Order): return 1 if not isinstance(a, Order) and isinstance(b, Order): return -1 if a.is_Rational and b.is_Rational: l = a.p * b.q r = b.p * a.q return (l > r) - (l < r) else: from .symbol import Wild p1, p2, p3 = Wild("p1"), Wild("p2"), Wild("p3") r_a = a.match(p1 * p2**p3) if r_a and p3 in r_a: a3 = r_a[p3] r_b = b.match(p1 * p2**p3) if r_b and p3 in r_b: b3 = r_b[p3] c = Basic.compare(a3, b3) if c != 0: return c return Basic.compare(a, b) @classmethod def fromiter(cls, args, **assumptions): """ Create a new object from an iterable. This is a convenience function that allows one to create objects from any iterable, without having to convert to a list or tuple first. Examples ======== >>> from sympy import Tuple >>> Tuple.fromiter(i for i in range(5)) (0, 1, 2, 3, 4) """ return cls(*tuple(args), **assumptions) @classmethod def class_key(cls): """Nice order of classes.""" return 5, 0, cls.__name__ @cacheit def sort_key(self, order=None): """ Return a sort key. Examples ======== >>> from sympy import S, I >>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key()) [1/2, -I, I] >>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]") [x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)] >>> sorted(_, key=lambda x: x.sort_key()) [x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2] """ # XXX: remove this when issue 5169 is fixed def inner_key(arg): if isinstance(arg, Basic): return arg.sort_key(order) else: return arg args = self._sorted_args args = len(args), tuple([inner_key(arg) for arg in args]) return self.class_key(), args, S.One.sort_key(), S.One def _do_eq_sympify(self, other): """Returns a boolean indicating whether a == b when either a or b is not a Basic. This is only done for types that were either added to `converter` by a 3rd party or when the object has `_sympy_` defined. This essentially reuses the code in `_sympify` that is specific for this use case. Non-user defined types that are meant to work with SymPy should be handled directly in the __eq__ methods of the `Basic` classes it could equate to and not be converted. Note that after conversion, `==` is used again since it is not necessarily clear whether `self` or `other`'s __eq__ method needs to be used.""" for superclass in type(other).__mro__: conv = _external_converter.get(superclass) if conv is not None: return self == conv(other) if hasattr(other, '_sympy_'): return self == other._sympy_() return NotImplemented def __eq__(self, other): """Return a boolean indicating whether a == b on the basis of their symbolic trees. This is the same as a.compare(b) == 0 but faster. Notes ===== If a class that overrides __eq__() needs to retain the implementation of __hash__() from a parent class, the interpreter must be told this explicitly by setting __hash__ : Callable[[object], int] = <ParentClass>.__hash__. Otherwise the inheritance of __hash__() will be blocked, just as if __hash__ had been explicitly set to None. References ========== from http://docs.python.org/dev/reference/datamodel.html#object.__hash__ """ if self is other: return True if not isinstance(other, Basic): return self._do_eq_sympify(other) # check for pure number expr if not (self.is_Number and other.is_Number) and ( type(self) != type(other)): return False a, b = self._hashable_content(), other._hashable_content() if a != b: return False # check number *in* an expression for a, b in zip(a, b): if not isinstance(a, Basic): continue if a.is_Number and type(a) != type(b): return False return True def __ne__(self, other): """``a != b`` -> Compare two symbolic trees and see whether they are different this is the same as: ``a.compare(b) != 0`` but faster """ return not self == other def dummy_eq(self, other, symbol=None): """ Compare two expressions and handle dummy symbols. Examples ======== >>> from sympy import Dummy >>> from sympy.abc import x, y >>> u = Dummy('u') >>> (u**2 + 1).dummy_eq(x**2 + 1) True >>> (u**2 + 1) == (x**2 + 1) False >>> (u**2 + y).dummy_eq(x**2 + y, x) True >>> (u**2 + y).dummy_eq(x**2 + y, y) False """ s = self.as_dummy() o = _sympify(other) o = o.as_dummy() dummy_symbols = [i for i in s.free_symbols if i.is_Dummy] if len(dummy_symbols) == 1: dummy = dummy_symbols.pop() else: return s == o if symbol is None: symbols = o.free_symbols if len(symbols) == 1: symbol = symbols.pop() else: return s == o tmp = dummy.__class__() return s.xreplace({dummy: tmp}) == o.xreplace({symbol: tmp}) def atoms(self, *types): """Returns the atoms that form the current object. By default, only objects that are truly atomic and cannot be divided into smaller pieces are returned: symbols, numbers, and number symbols like I and pi. It is possible to request atoms of any type, however, as demonstrated below. Examples ======== >>> from sympy import I, pi, sin >>> from sympy.abc import x, y >>> (1 + x + 2*sin(y + I*pi)).atoms() {1, 2, I, pi, x, y} If one or more types are given, the results will contain only those types of atoms. >>> from sympy import Number, NumberSymbol, Symbol >>> (1 + x + 2*sin(y + I*pi)).atoms(Symbol) {x, y} >>> (1 + x + 2*sin(y + I*pi)).atoms(Number) {1, 2} >>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol) {1, 2, pi} >>> (1 + x + 2*sin(y + I*pi)).atoms(Number, NumberSymbol, I) {1, 2, I, pi} Note that I (imaginary unit) and zoo (complex infinity) are special types of number symbols and are not part of the NumberSymbol class. The type can be given implicitly, too: >>> (1 + x + 2*sin(y + I*pi)).atoms(x) # x is a Symbol {x, y} Be careful to check your assumptions when using the implicit option since ``S(1).is_Integer = True`` but ``type(S(1))`` is ``One``, a special type of SymPy atom, while ``type(S(2))`` is type ``Integer`` and will find all integers in an expression: >>> from sympy import S >>> (1 + x + 2*sin(y + I*pi)).atoms(S(1)) {1} >>> (1 + x + 2*sin(y + I*pi)).atoms(S(2)) {1, 2} Finally, arguments to atoms() can select more than atomic atoms: any SymPy type (loaded in core/__init__.py) can be listed as an argument and those types of "atoms" as found in scanning the arguments of the expression recursively: >>> from sympy import Function, Mul >>> from sympy.core.function import AppliedUndef >>> f = Function('f') >>> (1 + f(x) + 2*sin(y + I*pi)).atoms(Function) {f(x), sin(y + I*pi)} >>> (1 + f(x) + 2*sin(y + I*pi)).atoms(AppliedUndef) {f(x)} >>> (1 + x + 2*sin(y + I*pi)).atoms(Mul) {I*pi, 2*sin(y + I*pi)} """ if types: types = tuple( [t if isinstance(t, type) else type(t) for t in types]) nodes = _preorder_traversal(self) if types: result = {node for node in nodes if isinstance(node, types)} else: result = {node for node in nodes if not node.args} return result @property def free_symbols(self) -> set[Basic]: """Return from the atoms of self those which are free symbols. Not all free symbols are ``Symbol``. Eg: IndexedBase('I')[0].free_symbols For most expressions, all symbols are free symbols. For some classes this is not true. e.g. Integrals use Symbols for the dummy variables which are bound variables, so Integral has a method to return all symbols except those. Derivative keeps track of symbols with respect to which it will perform a derivative; those are bound variables, too, so it has its own free_symbols method. Any other method that uses bound variables should implement a free_symbols method.""" empty: set[Basic] = set() return empty.union(*(a.free_symbols for a in self.args)) @property def expr_free_symbols(self): sympy_deprecation_warning(""" The expr_free_symbols property is deprecated. Use free_symbols to get the free symbols of an expression. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-expr-free-symbols") return set() def as_dummy(self): """Return the expression with any objects having structurally bound symbols replaced with unique, canonical symbols within the object in which they appear and having only the default assumption for commutativity being True. When applied to a symbol a new symbol having only the same commutativity will be returned. Examples ======== >>> from sympy import Integral, Symbol >>> from sympy.abc import x >>> r = Symbol('r', real=True) >>> Integral(r, (r, x)).as_dummy() Integral(_0, (_0, x)) >>> _.variables[0].is_real is None True >>> r.as_dummy() _r Notes ===== Any object that has structurally bound variables should have a property, `bound_symbols` that returns those symbols appearing in the object. """ from .symbol import Dummy, Symbol def can(x): # mask free that shadow bound free = x.free_symbols bound = set(x.bound_symbols) d = {i: Dummy() for i in bound & free} x = x.subs(d) # replace bound with canonical names x = x.xreplace(x.canonical_variables) # return after undoing masking return x.xreplace({v: k for k, v in d.items()}) if not self.has(Symbol): return self return self.replace( lambda x: hasattr(x, 'bound_symbols'), can, simultaneous=False) @property def canonical_variables(self): """Return a dictionary mapping any variable defined in ``self.bound_symbols`` to Symbols that do not clash with any free symbols in the expression. Examples ======== >>> from sympy import Lambda >>> from sympy.abc import x >>> Lambda(x, 2*x).canonical_variables {x: _0} """ if not hasattr(self, 'bound_symbols'): return {} dums = numbered_symbols('_') reps = {} # watch out for free symbol that are not in bound symbols; # those that are in bound symbols are about to get changed bound = self.bound_symbols names = {i.name for i in self.free_symbols - set(bound)} for b in bound: d = next(dums) if b.is_Symbol: while d.name in names: d = next(dums) reps[b] = d return reps def rcall(self, *args): """Apply on the argument recursively through the expression tree. This method is used to simulate a common abuse of notation for operators. For instance, in SymPy the following will not work: ``(x+Lambda(y, 2*y))(z) == x+2*z``, however, you can use: >>> from sympy import Lambda >>> from sympy.abc import x, y, z >>> (x + Lambda(y, 2*y)).rcall(z) x + 2*z """ return Basic._recursive_call(self, args) @staticmethod def _recursive_call(expr_to_call, on_args): """Helper for rcall method.""" from .symbol import Symbol def the_call_method_is_overridden(expr): for cls in getmro(type(expr)): if '__call__' in cls.__dict__: return cls != Basic if callable(expr_to_call) and the_call_method_is_overridden(expr_to_call): if isinstance(expr_to_call, Symbol): # XXX When you call a Symbol it is return expr_to_call # transformed into an UndefFunction else: return expr_to_call(*on_args) elif expr_to_call.args: args = [Basic._recursive_call( sub, on_args) for sub in expr_to_call.args] return type(expr_to_call)(*args) else: return expr_to_call def is_hypergeometric(self, k): from sympy.simplify.simplify import hypersimp from sympy.functions.elementary.piecewise import Piecewise if self.has(Piecewise): return None return hypersimp(self, k) is not None @property def is_comparable(self): """Return True if self can be computed to a real number (or already is a real number) with precision, else False. Examples ======== >>> from sympy import exp_polar, pi, I >>> (I*exp_polar(I*pi/2)).is_comparable True >>> (I*exp_polar(I*pi*2)).is_comparable False A False result does not mean that `self` cannot be rewritten into a form that would be comparable. For example, the difference computed below is zero but without simplification it does not evaluate to a zero with precision: >>> e = 2**pi*(1 + 2**pi) >>> dif = e - e.expand() >>> dif.is_comparable False >>> dif.n(2)._prec 1 """ is_extended_real = self.is_extended_real if is_extended_real is False: return False if not self.is_number: return False # don't re-eval numbers that are already evaluated since # this will create spurious precision n, i = [p.evalf(2) if not p.is_Number else p for p in self.as_real_imag()] if not (i.is_Number and n.is_Number): return False if i: # if _prec = 1 we can't decide and if not, # the answer is False because numbers with # imaginary parts can't be compared # so return False return False else: return n._prec != 1 @property def func(self): """ The top-level function in an expression. The following should hold for all objects:: >> x == x.func(*x.args) Examples ======== >>> from sympy.abc import x >>> a = 2*x >>> a.func <class 'sympy.core.mul.Mul'> >>> a.args (2, x) >>> a.func(*a.args) 2*x >>> a == a.func(*a.args) True """ return self.__class__ @property def args(self) -> tuple[Basic, ...]: """Returns a tuple of arguments of 'self'. Examples ======== >>> from sympy import cot >>> from sympy.abc import x, y >>> cot(x).args (x,) >>> cot(x).args[0] x >>> (x*y).args (x, y) >>> (x*y).args[1] y Notes ===== Never use self._args, always use self.args. Only use _args in __new__ when creating a new function. Do not override .args() from Basic (so that it is easy to change the interface in the future if needed). """ return self._args @property def _sorted_args(self): """ The same as ``args``. Derived classes which do not fix an order on their arguments should override this method to produce the sorted representation. """ return self.args def as_content_primitive(self, radical=False, clear=True): """A stub to allow Basic args (like Tuple) to be skipped when computing the content and primitive components of an expression. See Also ======== sympy.core.expr.Expr.as_content_primitive """ return S.One, self def subs(self, *args, **kwargs): """ Substitutes old for new in an expression after sympifying args. `args` is either: - two arguments, e.g. foo.subs(old, new) - one iterable argument, e.g. foo.subs(iterable). The iterable may be o an iterable container with (old, new) pairs. In this case the replacements are processed in the order given with successive patterns possibly affecting replacements already made. o a dict or set whose key/value items correspond to old/new pairs. In this case the old/new pairs will be sorted by op count and in case of a tie, by number of args and the default_sort_key. The resulting sorted list is then processed as an iterable container (see previous). If the keyword ``simultaneous`` is True, the subexpressions will not be evaluated until all the substitutions have been made. Examples ======== >>> from sympy import pi, exp, limit, oo >>> from sympy.abc import x, y >>> (1 + x*y).subs(x, pi) pi*y + 1 >>> (1 + x*y).subs({x:pi, y:2}) 1 + 2*pi >>> (1 + x*y).subs([(x, pi), (y, 2)]) 1 + 2*pi >>> reps = [(y, x**2), (x, 2)] >>> (x + y).subs(reps) 6 >>> (x + y).subs(reversed(reps)) x**2 + 2 >>> (x**2 + x**4).subs(x**2, y) y**2 + y To replace only the x**2 but not the x**4, use xreplace: >>> (x**2 + x**4).xreplace({x**2: y}) x**4 + y To delay evaluation until all substitutions have been made, set the keyword ``simultaneous`` to True: >>> (x/y).subs([(x, 0), (y, 0)]) 0 >>> (x/y).subs([(x, 0), (y, 0)], simultaneous=True) nan This has the added feature of not allowing subsequent substitutions to affect those already made: >>> ((x + y)/y).subs({x + y: y, y: x + y}) 1 >>> ((x + y)/y).subs({x + y: y, y: x + y}, simultaneous=True) y/(x + y) In order to obtain a canonical result, unordered iterables are sorted by count_op length, number of arguments and by the default_sort_key to break any ties. All other iterables are left unsorted. >>> from sympy import sqrt, sin, cos >>> from sympy.abc import a, b, c, d, e >>> A = (sqrt(sin(2*x)), a) >>> B = (sin(2*x), b) >>> C = (cos(2*x), c) >>> D = (x, d) >>> E = (exp(x), e) >>> expr = sqrt(sin(2*x))*sin(exp(x)*x)*cos(2*x) + sin(2*x) >>> expr.subs(dict([A, B, C, D, E])) a*c*sin(d*e) + b The resulting expression represents a literal replacement of the old arguments with the new arguments. This may not reflect the limiting behavior of the expression: >>> (x**3 - 3*x).subs({x: oo}) nan >>> limit(x**3 - 3*x, x, oo) oo If the substitution will be followed by numerical evaluation, it is better to pass the substitution to evalf as >>> (1/x).evalf(subs={x: 3.0}, n=21) 0.333333333333333333333 rather than >>> (1/x).subs({x: 3.0}).evalf(21) 0.333333333333333314830 as the former will ensure that the desired level of precision is obtained. See Also ======== replace: replacement capable of doing wildcard-like matching, parsing of match, and conditional replacements xreplace: exact node replacement in expr tree; also capable of using matching rules sympy.core.evalf.EvalfMixin.evalf: calculates the given formula to a desired level of precision """ from .containers import Dict from .symbol import Dummy, Symbol from .numbers import _illegal unordered = False if len(args) == 1: sequence = args[0] if isinstance(sequence, set): unordered = True elif isinstance(sequence, (Dict, Mapping)): unordered = True sequence = sequence.items() elif not iterable(sequence): raise ValueError(filldedent(""" When a single argument is passed to subs it should be a dictionary of old: new pairs or an iterable of (old, new) tuples.""")) elif len(args) == 2: sequence = [args] else: raise ValueError("subs accepts either 1 or 2 arguments") def sympify_old(old): if isinstance(old, str): # Use Symbol rather than parse_expr for old return Symbol(old) elif isinstance(old, type): # Allow a type e.g. Function('f') or sin return sympify(old, strict=False) else: return sympify(old, strict=True) def sympify_new(new): if isinstance(new, (str, type)): # Allow a type or parse a string input return sympify(new, strict=False) else: return sympify(new, strict=True) sequence = [(sympify_old(s1), sympify_new(s2)) for s1, s2 in sequence] # skip if there is no change sequence = [(s1, s2) for s1, s2 in sequence if not _aresame(s1, s2)] simultaneous = kwargs.pop('simultaneous', False) if unordered: from .sorting import _nodes, default_sort_key sequence = dict(sequence) # order so more complex items are first and items # of identical complexity are ordered so # f(x) < f(y) < x < y # \___ 2 __/ \_1_/ <- number of nodes # # For more complex ordering use an unordered sequence. k = list(ordered(sequence, default=False, keys=( lambda x: -_nodes(x), default_sort_key, ))) sequence = [(k, sequence[k]) for k in k] # do infinities first if not simultaneous: redo = [i for i, seq in enumerate(sequence) if seq[1] in _illegal] for i in reversed(redo): sequence.insert(0, sequence.pop(i)) if simultaneous: # XXX should this be the default for dict subs? reps = {} rv = self kwargs['hack2'] = True m = Dummy('subs_m') for old, new in sequence: com = new.is_commutative if com is None: com = True d = Dummy('subs_d', commutative=com) # using d*m so Subs will be used on dummy variables # in things like Derivative(f(x, y), x) in which x # is both free and bound rv = rv._subs(old, d*m, **kwargs) if not isinstance(rv, Basic): break reps[d] = new reps[m] = S.One # get rid of m return rv.xreplace(reps) else: rv = self for old, new in sequence: rv = rv._subs(old, new, **kwargs) if not isinstance(rv, Basic): break return rv @cacheit def _subs(self, old, new, **hints): """Substitutes an expression old -> new. If self is not equal to old then _eval_subs is called. If _eval_subs does not want to make any special replacement then a None is received which indicates that the fallback should be applied wherein a search for replacements is made amongst the arguments of self. >>> from sympy import Add >>> from sympy.abc import x, y, z Examples ======== Add's _eval_subs knows how to target x + y in the following so it makes the change: >>> (x + y + z).subs(x + y, 1) z + 1 Add's _eval_subs does not need to know how to find x + y in the following: >>> Add._eval_subs(z*(x + y) + 3, x + y, 1) is None True The returned None will cause the fallback routine to traverse the args and pass the z*(x + y) arg to Mul where the change will take place and the substitution will succeed: >>> (z*(x + y) + 3).subs(x + y, 1) z + 3 ** Developers Notes ** An _eval_subs routine for a class should be written if: 1) any arguments are not instances of Basic (e.g. bool, tuple); 2) some arguments should not be targeted (as in integration variables); 3) if there is something other than a literal replacement that should be attempted (as in Piecewise where the condition may be updated without doing a replacement). If it is overridden, here are some special cases that might arise: 1) If it turns out that no special change was made and all the original sub-arguments should be checked for replacements then None should be returned. 2) If it is necessary to do substitutions on a portion of the expression then _subs should be called. _subs will handle the case of any sub-expression being equal to old (which usually would not be the case) while its fallback will handle the recursion into the sub-arguments. For example, after Add's _eval_subs removes some matching terms it must process the remaining terms so it calls _subs on each of the un-matched terms and then adds them onto the terms previously obtained. 3) If the initial expression should remain unchanged then the original expression should be returned. (Whenever an expression is returned, modified or not, no further substitution of old -> new is attempted.) Sum's _eval_subs routine uses this strategy when a substitution is attempted on any of its summation variables. """ def fallback(self, old, new): """ Try to replace old with new in any of self's arguments. """ hit = False args = list(self.args) for i, arg in enumerate(args): if not hasattr(arg, '_eval_subs'): continue arg = arg._subs(old, new, **hints) if not _aresame(arg, args[i]): hit = True args[i] = arg if hit: rv = self.func(*args) hack2 = hints.get('hack2', False) if hack2 and self.is_Mul and not rv.is_Mul: # 2-arg hack coeff = S.One nonnumber = [] for i in args: if i.is_Number: coeff *= i else: nonnumber.append(i) nonnumber = self.func(*nonnumber) if coeff is S.One: return nonnumber else: return self.func(coeff, nonnumber, evaluate=False) return rv return self if _aresame(self, old): return new rv = self._eval_subs(old, new) if rv is None: rv = fallback(self, old, new) return rv def _eval_subs(self, old, new): """Override this stub if you want to do anything more than attempt a replacement of old with new in the arguments of self. See also ======== _subs """ return None def xreplace(self, rule): """ Replace occurrences of objects within the expression. Parameters ========== rule : dict-like Expresses a replacement rule Returns ======= xreplace : the result of the replacement Examples ======== >>> from sympy import symbols, pi, exp >>> x, y, z = symbols('x y z') >>> (1 + x*y).xreplace({x: pi}) pi*y + 1 >>> (1 + x*y).xreplace({x: pi, y: 2}) 1 + 2*pi Replacements occur only if an entire node in the expression tree is matched: >>> (x*y + z).xreplace({x*y: pi}) z + pi >>> (x*y*z).xreplace({x*y: pi}) x*y*z >>> (2*x).xreplace({2*x: y, x: z}) y >>> (2*2*x).xreplace({2*x: y, x: z}) 4*z >>> (x + y + 2).xreplace({x + y: 2}) x + y + 2 >>> (x + 2 + exp(x + 2)).xreplace({x + 2: y}) x + exp(y) + 2 xreplace does not differentiate between free and bound symbols. In the following, subs(x, y) would not change x since it is a bound symbol, but xreplace does: >>> from sympy import Integral >>> Integral(x, (x, 1, 2*x)).xreplace({x: y}) Integral(y, (y, 1, 2*y)) Trying to replace x with an expression raises an error: >>> Integral(x, (x, 1, 2*x)).xreplace({x: 2*y}) # doctest: +SKIP ValueError: Invalid limits given: ((2*y, 1, 4*y),) See Also ======== replace: replacement capable of doing wildcard-like matching, parsing of match, and conditional replacements subs: substitution of subexpressions as defined by the objects themselves. """ value, _ = self._xreplace(rule) return value def _xreplace(self, rule): """ Helper for xreplace. Tracks whether a replacement actually occurred. """ if self in rule: return rule[self], True elif rule: args = [] changed = False for a in self.args: _xreplace = getattr(a, '_xreplace', None) if _xreplace is not None: a_xr = _xreplace(rule) args.append(a_xr[0]) changed |= a_xr[1] else: args.append(a) args = tuple(args) if changed: return self.func(*args), True return self, False @cacheit def has(self, *patterns): """ Test whether any subexpression matches any of the patterns. Examples ======== >>> from sympy import sin >>> from sympy.abc import x, y, z >>> (x**2 + sin(x*y)).has(z) False >>> (x**2 + sin(x*y)).has(x, y, z) True >>> x.has(x) True Note ``has`` is a structural algorithm with no knowledge of mathematics. Consider the following half-open interval: >>> from sympy import Interval >>> i = Interval.Lopen(0, 5); i Interval.Lopen(0, 5) >>> i.args (0, 5, True, False) >>> i.has(4) # there is no "4" in the arguments False >>> i.has(0) # there *is* a "0" in the arguments True Instead, use ``contains`` to determine whether a number is in the interval or not: >>> i.contains(4) True >>> i.contains(0) False Note that ``expr.has(*patterns)`` is exactly equivalent to ``any(expr.has(p) for p in patterns)``. In particular, ``False`` is returned when the list of patterns is empty. >>> x.has() False """ return self._has(iterargs, *patterns) def has_xfree(self, s: set[Basic]): """Return True if self has any of the patterns in s as a free argument, else False. This is like `Basic.has_free` but this will only report exact argument matches. Examples ======== >>> from sympy import Function >>> from sympy.abc import x, y >>> f = Function('f') >>> f(x).has_xfree({f}) False >>> f(x).has_xfree({f(x)}) True >>> f(x + 1).has_xfree({x}) True >>> f(x + 1).has_xfree({x + 1}) True >>> f(x + y + 1).has_xfree({x + 1}) False """ # protect O(1) containment check by requiring: if type(s) is not set: raise TypeError('expecting set argument') return any(a in s for a in iterfreeargs(self)) @cacheit def has_free(self, *patterns): """Return True if self has object(s) ``x`` as a free expression else False. Examples ======== >>> from sympy import Integral, Function >>> from sympy.abc import x, y >>> f = Function('f') >>> g = Function('g') >>> expr = Integral(f(x), (f(x), 1, g(y))) >>> expr.free_symbols {y} >>> expr.has_free(g(y)) True >>> expr.has_free(*(x, f(x))) False This works for subexpressions and types, too: >>> expr.has_free(g) True >>> (x + y + 1).has_free(y + 1) True """ if not patterns: return False p0 = patterns[0] if len(patterns) == 1 and iterable(p0) and not isinstance(p0, Basic): # Basic can contain iterables (though not non-Basic, ideally) # but don't encourage mixed passing patterns raise TypeError(filldedent(''' Expecting 1 or more Basic args, not a single non-Basic iterable. Don't forget to unpack iterables: `eq.has_free(*patterns)`''')) # try quick test first s = set(patterns) rv = self.has_xfree(s) if rv: return rv # now try matching through slower _has return self._has(iterfreeargs, *patterns) def _has(self, iterargs, *patterns): # separate out types and unhashable objects type_set = set() # only types p_set = set() # hashable non-types for p in patterns: if isinstance(p, type) and issubclass(p, Basic): type_set.add(p) continue if not isinstance(p, Basic): try: p = _sympify(p) except SympifyError: continue # Basic won't have this in it p_set.add(p) # fails if object defines __eq__ but # doesn't define __hash__ types = tuple(type_set) # for i in iterargs(self): # if i in p_set: # <--- here, too return True if isinstance(i, types): return True # use matcher if defined, e.g. operations defines # matcher that checks for exact subset containment, # (x + y + 1).has(x + 1) -> True for i in p_set - type_set: # types don't have matchers if not hasattr(i, '_has_matcher'): continue match = i._has_matcher() if any(match(arg) for arg in iterargs(self)): return True # no success return False def replace(self, query, value, map=False, simultaneous=True, exact=None): """ Replace matching subexpressions of ``self`` with ``value``. If ``map = True`` then also return the mapping {old: new} where ``old`` was a sub-expression found with query and ``new`` is the replacement value for it. If the expression itself does not match the query, then the returned value will be ``self.xreplace(map)`` otherwise it should be ``self.subs(ordered(map.items()))``. Traverses an expression tree and performs replacement of matching subexpressions from the bottom to the top of the tree. The default approach is to do the replacement in a simultaneous fashion so changes made are targeted only once. If this is not desired or causes problems, ``simultaneous`` can be set to False. In addition, if an expression containing more than one Wild symbol is being used to match subexpressions and the ``exact`` flag is None it will be set to True so the match will only succeed if all non-zero values are received for each Wild that appears in the match pattern. Setting this to False accepts a match of 0; while setting it True accepts all matches that have a 0 in them. See example below for cautions. The list of possible combinations of queries and replacement values is listed below: Examples ======== Initial setup >>> from sympy import log, sin, cos, tan, Wild, Mul, Add >>> from sympy.abc import x, y >>> f = log(sin(x)) + tan(sin(x**2)) 1.1. type -> type obj.replace(type, newtype) When object of type ``type`` is found, replace it with the result of passing its argument(s) to ``newtype``. >>> f.replace(sin, cos) log(cos(x)) + tan(cos(x**2)) >>> sin(x).replace(sin, cos, map=True) (cos(x), {sin(x): cos(x)}) >>> (x*y).replace(Mul, Add) x + y 1.2. type -> func obj.replace(type, func) When object of type ``type`` is found, apply ``func`` to its argument(s). ``func`` must be written to handle the number of arguments of ``type``. >>> f.replace(sin, lambda arg: sin(2*arg)) log(sin(2*x)) + tan(sin(2*x**2)) >>> (x*y).replace(Mul, lambda *args: sin(2*Mul(*args))) sin(2*x*y) 2.1. pattern -> expr obj.replace(pattern(wild), expr(wild)) Replace subexpressions matching ``pattern`` with the expression written in terms of the Wild symbols in ``pattern``. >>> a, b = map(Wild, 'ab') >>> f.replace(sin(a), tan(a)) log(tan(x)) + tan(tan(x**2)) >>> f.replace(sin(a), tan(a/2)) log(tan(x/2)) + tan(tan(x**2/2)) >>> f.replace(sin(a), a) log(x) + tan(x**2) >>> (x*y).replace(a*x, a) y Matching is exact by default when more than one Wild symbol is used: matching fails unless the match gives non-zero values for all Wild symbols: >>> (2*x + y).replace(a*x + b, b - a) y - 2 >>> (2*x).replace(a*x + b, b - a) 2*x When set to False, the results may be non-intuitive: >>> (2*x).replace(a*x + b, b - a, exact=False) 2/x 2.2. pattern -> func obj.replace(pattern(wild), lambda wild: expr(wild)) All behavior is the same as in 2.1 but now a function in terms of pattern variables is used rather than an expression: >>> f.replace(sin(a), lambda a: sin(2*a)) log(sin(2*x)) + tan(sin(2*x**2)) 3.1. func -> func obj.replace(filter, func) Replace subexpression ``e`` with ``func(e)`` if ``filter(e)`` is True. >>> g = 2*sin(x**3) >>> g.replace(lambda expr: expr.is_Number, lambda expr: expr**2) 4*sin(x**9) The expression itself is also targeted by the query but is done in such a fashion that changes are not made twice. >>> e = x*(x*y + 1) >>> e.replace(lambda x: x.is_Mul, lambda x: 2*x) 2*x*(2*x*y + 1) When matching a single symbol, `exact` will default to True, but this may or may not be the behavior that is desired: Here, we want `exact=False`: >>> from sympy import Function >>> f = Function('f') >>> e = f(1) + f(0) >>> q = f(a), lambda a: f(a + 1) >>> e.replace(*q, exact=False) f(1) + f(2) >>> e.replace(*q, exact=True) f(0) + f(2) But here, the nature of matching makes selecting the right setting tricky: >>> e = x**(1 + y) >>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=False) x >>> (x**(1 + y)).replace(x**(1 + a), lambda a: x**-a, exact=True) x**(-x - y + 1) >>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=False) x >>> (x**y).replace(x**(1 + a), lambda a: x**-a, exact=True) x**(1 - y) It is probably better to use a different form of the query that describes the target expression more precisely: >>> (1 + x**(1 + y)).replace( ... lambda x: x.is_Pow and x.exp.is_Add and x.exp.args[0] == 1, ... lambda x: x.base**(1 - (x.exp - 1))) ... x**(1 - y) + 1 See Also ======== subs: substitution of subexpressions as defined by the objects themselves. xreplace: exact node replacement in expr tree; also capable of using matching rules """ try: query = _sympify(query) except SympifyError: pass try: value = _sympify(value) except SympifyError: pass if isinstance(query, type): _query = lambda expr: isinstance(expr, query) if isinstance(value, type): _value = lambda expr, result: value(*expr.args) elif callable(value): _value = lambda expr, result: value(*expr.args) else: raise TypeError( "given a type, replace() expects another " "type or a callable") elif isinstance(query, Basic): _query = lambda expr: expr.match(query) if exact is None: from .symbol import Wild exact = (len(query.atoms(Wild)) > 1) if isinstance(value, Basic): if exact: _value = lambda expr, result: (value.subs(result) if all(result.values()) else expr) else: _value = lambda expr, result: value.subs(result) elif callable(value): # match dictionary keys get the trailing underscore stripped # from them and are then passed as keywords to the callable; # if ``exact`` is True, only accept match if there are no null # values amongst those matched. if exact: _value = lambda expr, result: (value(** {str(k)[:-1]: v for k, v in result.items()}) if all(val for val in result.values()) else expr) else: _value = lambda expr, result: value(** {str(k)[:-1]: v for k, v in result.items()}) else: raise TypeError( "given an expression, replace() expects " "another expression or a callable") elif callable(query): _query = query if callable(value): _value = lambda expr, result: value(expr) else: raise TypeError( "given a callable, replace() expects " "another callable") else: raise TypeError( "first argument to replace() must be a " "type, an expression or a callable") def walk(rv, F): """Apply ``F`` to args and then to result. """ args = getattr(rv, 'args', None) if args is not None: if args: newargs = tuple([walk(a, F) for a in args]) if args != newargs: rv = rv.func(*newargs) if simultaneous: # if rv is something that was already # matched (that was changed) then skip # applying F again for i, e in enumerate(args): if rv == e and e != newargs[i]: return rv rv = F(rv) return rv mapping = {} # changes that took place def rec_replace(expr): result = _query(expr) if result or result == {}: v = _value(expr, result) if v is not None and v != expr: if map: mapping[expr] = v expr = v return expr rv = walk(self, rec_replace) return (rv, mapping) if map else rv def find(self, query, group=False): """Find all subexpressions matching a query.""" query = _make_find_query(query) results = list(filter(query, _preorder_traversal(self))) if not group: return set(results) else: groups = {} for result in results: if result in groups: groups[result] += 1 else: groups[result] = 1 return groups def count(self, query): """Count the number of matching subexpressions.""" query = _make_find_query(query) return sum(bool(query(sub)) for sub in _preorder_traversal(self)) def matches(self, expr, repl_dict=None, old=False): """ Helper method for match() that looks for a match between Wild symbols in self and expressions in expr. Examples ======== >>> from sympy import symbols, Wild, Basic >>> a, b, c = symbols('a b c') >>> x = Wild('x') >>> Basic(a + x, x).matches(Basic(a + b, c)) is None True >>> Basic(a + x, x).matches(Basic(a + b + c, b + c)) {x_: b + c} """ expr = sympify(expr) if not isinstance(expr, self.__class__): return None if repl_dict is None: repl_dict = {} else: repl_dict = repl_dict.copy() if self == expr: return repl_dict if len(self.args) != len(expr.args): return None d = repl_dict # already a copy for arg, other_arg in zip(self.args, expr.args): if arg == other_arg: continue if arg.is_Relational: try: d = arg.xreplace(d).matches(other_arg, d, old=old) except TypeError: # Should be InvalidComparisonError when introduced d = None else: d = arg.xreplace(d).matches(other_arg, d, old=old) if d is None: return None return d def match(self, pattern, old=False): """ Pattern matching. Wild symbols match all. Return ``None`` when expression (self) does not match with pattern. Otherwise return a dictionary such that:: pattern.xreplace(self.match(pattern)) == self Examples ======== >>> from sympy import Wild, Sum >>> from sympy.abc import x, y >>> p = Wild("p") >>> q = Wild("q") >>> r = Wild("r") >>> e = (x+y)**(x+y) >>> e.match(p**p) {p_: x + y} >>> e.match(p**q) {p_: x + y, q_: x + y} >>> e = (2*x)**2 >>> e.match(p*q**r) {p_: 4, q_: x, r_: 2} >>> (p*q**r).xreplace(e.match(p*q**r)) 4*x**2 Structurally bound symbols are ignored during matching: >>> Sum(x, (x, 1, 2)).match(Sum(y, (y, 1, p))) {p_: 2} But they can be identified if desired: >>> Sum(x, (x, 1, 2)).match(Sum(q, (q, 1, p))) {p_: 2, q_: x} The ``old`` flag will give the old-style pattern matching where expressions and patterns are essentially solved to give the match. Both of the following give None unless ``old=True``: >>> (x - 2).match(p - x, old=True) {p_: 2*x - 2} >>> (2/x).match(p*x, old=True) {p_: 2/x**2} """ pattern = sympify(pattern) # match non-bound symbols canonical = lambda x: x if x.is_Symbol else x.as_dummy() m = canonical(pattern).matches(canonical(self), old=old) if m is None: return m from .symbol import Wild from .function import WildFunction from ..tensor.tensor import WildTensor, WildTensorIndex, WildTensorHead wild = pattern.atoms(Wild, WildFunction, WildTensor, WildTensorIndex, WildTensorHead) # sanity check if set(m) - wild: raise ValueError(filldedent(''' Some `matches` routine did not use a copy of repl_dict and injected unexpected symbols. Report this as an error at https://github.com/sympy/sympy/issues''')) # now see if bound symbols were requested bwild = wild - set(m) if not bwild: return m # replace free-Wild symbols in pattern with match result # so they will match but not be in the next match wpat = pattern.xreplace(m) # identify remaining bound wild w = wpat.matches(self, old=old) # add them to m if w: m.update(w) # done return m def count_ops(self, visual=None): """Wrapper for count_ops that returns the operation count.""" from .function import count_ops return count_ops(self, visual) def doit(self, **hints): """Evaluate objects that are not evaluated by default like limits, integrals, sums and products. All objects of this kind will be evaluated recursively, unless some species were excluded via 'hints' or unless the 'deep' hint was set to 'False'. >>> from sympy import Integral >>> from sympy.abc import x >>> 2*Integral(x, x) 2*Integral(x, x) >>> (2*Integral(x, x)).doit() x**2 >>> (2*Integral(x, x)).doit(deep=False) 2*Integral(x, x) """ if hints.get('deep', True): terms = [term.doit(**hints) if isinstance(term, Basic) else term for term in self.args] return self.func(*terms) else: return self def simplify(self, **kwargs): """See the simplify function in sympy.simplify""" from sympy.simplify.simplify import simplify return simplify(self, **kwargs) def refine(self, assumption=True): """See the refine function in sympy.assumptions""" from sympy.assumptions.refine import refine return refine(self, assumption) def _eval_derivative_n_times(self, s, n): # This is the default evaluator for derivatives (as called by `diff` # and `Derivative`), it will attempt a loop to derive the expression # `n` times by calling the corresponding `_eval_derivative` method, # while leaving the derivative unevaluated if `n` is symbolic. This # method should be overridden if the object has a closed form for its # symbolic n-th derivative. from .numbers import Integer if isinstance(n, (int, Integer)): obj = self for i in range(n): obj2 = obj._eval_derivative(s) if obj == obj2 or obj2 is None: break obj = obj2 return obj2 else: return None def rewrite(self, *args, deep=True, **hints): """ Rewrite *self* using a defined rule. Rewriting transforms an expression to another, which is mathematically equivalent but structurally different. For example you can rewrite trigonometric functions as complex exponentials or combinatorial functions as gamma function. This method takes a *pattern* and a *rule* as positional arguments. *pattern* is optional parameter which defines the types of expressions that will be transformed. If it is not passed, all possible expressions will be rewritten. *rule* defines how the expression will be rewritten. Parameters ========== args : Expr A *rule*, or *pattern* and *rule*. - *pattern* is a type or an iterable of types. - *rule* can be any object. deep : bool, optional If ``True``, subexpressions are recursively transformed. Default is ``True``. Examples ======== If *pattern* is unspecified, all possible expressions are transformed. >>> from sympy import cos, sin, exp, I >>> from sympy.abc import x >>> expr = cos(x) + I*sin(x) >>> expr.rewrite(exp) exp(I*x) Pattern can be a type or an iterable of types. >>> expr.rewrite(sin, exp) exp(I*x)/2 + cos(x) - exp(-I*x)/2 >>> expr.rewrite([cos,], exp) exp(I*x)/2 + I*sin(x) + exp(-I*x)/2 >>> expr.rewrite([cos, sin], exp) exp(I*x) Rewriting behavior can be implemented by defining ``_eval_rewrite()`` method. >>> from sympy import Expr, sqrt, pi >>> class MySin(Expr): ... def _eval_rewrite(self, rule, args, **hints): ... x, = args ... if rule == cos: ... return cos(pi/2 - x, evaluate=False) ... if rule == sqrt: ... return sqrt(1 - cos(x)**2) >>> MySin(MySin(x)).rewrite(cos) cos(-cos(-x + pi/2) + pi/2) >>> MySin(x).rewrite(sqrt) sqrt(1 - cos(x)**2) Defining ``_eval_rewrite_as_[...]()`` method is supported for backwards compatibility reason. This may be removed in the future and using it is discouraged. >>> class MySin(Expr): ... def _eval_rewrite_as_cos(self, *args, **hints): ... x, = args ... return cos(pi/2 - x, evaluate=False) >>> MySin(x).rewrite(cos) cos(-x + pi/2) """ if not args: return self hints.update(deep=deep) pattern = args[:-1] rule = args[-1] # support old design by _eval_rewrite_as_[...] method if isinstance(rule, str): method = "_eval_rewrite_as_%s" % rule elif hasattr(rule, "__name__"): # rule is class or function clsname = rule.__name__ method = "_eval_rewrite_as_%s" % clsname else: # rule is instance clsname = rule.__class__.__name__ method = "_eval_rewrite_as_%s" % clsname if pattern: if iterable(pattern[0]): pattern = pattern[0] pattern = tuple(p for p in pattern if self.has(p)) if not pattern: return self # hereafter, empty pattern is interpreted as all pattern. return self._rewrite(pattern, rule, method, **hints) def _rewrite(self, pattern, rule, method, **hints): deep = hints.pop('deep', True) if deep: args = [a._rewrite(pattern, rule, method, **hints) for a in self.args] else: args = self.args if not pattern or any(isinstance(self, p) for p in pattern): meth = getattr(self, method, None) if meth is not None: rewritten = meth(*args, **hints) else: rewritten = self._eval_rewrite(rule, args, **hints) if rewritten is not None: return rewritten if not args: return self return self.func(*args) def _eval_rewrite(self, rule, args, **hints): return None _constructor_postprocessor_mapping = {} # type: ignore @classmethod def _exec_constructor_postprocessors(cls, obj): # WARNING: This API is experimental. # This is an experimental API that introduces constructor # postprosessors for SymPy Core elements. If an argument of a SymPy # expression has a `_constructor_postprocessor_mapping` attribute, it will # be interpreted as a dictionary containing lists of postprocessing # functions for matching expression node names. clsname = obj.__class__.__name__ postprocessors = defaultdict(list) for i in obj.args: try: postprocessor_mappings = ( Basic._constructor_postprocessor_mapping[cls].items() for cls in type(i).mro() if cls in Basic._constructor_postprocessor_mapping ) for k, v in chain.from_iterable(postprocessor_mappings): postprocessors[k].extend([j for j in v if j not in postprocessors[k]]) except TypeError: pass for f in postprocessors.get(clsname, []): obj = f(obj) return obj def _sage_(self): """ Convert *self* to a symbolic expression of SageMath. This version of the method is merely a placeholder. """ old_method = self._sage_ from sage.interfaces.sympy import sympy_init sympy_init() # may monkey-patch _sage_ method into self's class or superclasses if old_method == self._sage_: raise NotImplementedError('conversion to SageMath is not implemented') else: # call the freshly monkey-patched method return self._sage_() def could_extract_minus_sign(self): return False # see Expr.could_extract_minus_sign class Atom(Basic): """ A parent class for atomic things. An atom is an expression with no subexpressions. Examples ======== Symbol, Number, Rational, Integer, ... But not: Add, Mul, Pow, ... """ is_Atom = True __slots__ = () def matches(self, expr, repl_dict=None, old=False): if self == expr: if repl_dict is None: return {} return repl_dict.copy() def xreplace(self, rule, hack2=False): return rule.get(self, self) def doit(self, **hints): return self @classmethod def class_key(cls): return 2, 0, cls.__name__ @cacheit def sort_key(self, order=None): return self.class_key(), (1, (str(self),)), S.One.sort_key(), S.One def _eval_simplify(self, **kwargs): return self @property def _sorted_args(self): # this is here as a safeguard against accidentally using _sorted_args # on Atoms -- they cannot be rebuilt as atom.func(*atom._sorted_args) # since there are no args. So the calling routine should be checking # to see that this property is not called for Atoms. raise AttributeError('Atoms have no args. It might be necessary' ' to make a check for Atoms in the calling code.') def _aresame(a, b): """Return True if a and b are structurally the same, else False. Examples ======== In SymPy (as in Python) two numbers compare the same if they have the same underlying base-2 representation even though they may not be the same type: >>> from sympy import S >>> 2.0 == S(2) True >>> 0.5 == S.Half True This routine was written to provide a query for such cases that would give false when the types do not match: >>> from sympy.core.basic import _aresame >>> _aresame(S(2.0), S(2)) False """ from .numbers import Number from .function import AppliedUndef, UndefinedFunction as UndefFunc if isinstance(a, Number) and isinstance(b, Number): return a == b and a.__class__ == b.__class__ for i, j in zip_longest(_preorder_traversal(a), _preorder_traversal(b)): if i != j or type(i) != type(j): if ((isinstance(i, UndefFunc) and isinstance(j, UndefFunc)) or (isinstance(i, AppliedUndef) and isinstance(j, AppliedUndef))): if i.class_key() != j.class_key(): return False else: return False return True def _ne(a, b): # use this as a second test after `a != b` if you want to make # sure that things are truly equal, e.g. # a, b = 0.5, S.Half # a !=b or _ne(a, b) -> True from .numbers import Number # 0.5 == S.Half if isinstance(a, Number) and isinstance(b, Number): return a.__class__ != b.__class__ def _atomic(e, recursive=False): """Return atom-like quantities as far as substitution is concerned: Derivatives, Functions and Symbols. Do not return any 'atoms' that are inside such quantities unless they also appear outside, too, unless `recursive` is True. Examples ======== >>> from sympy import Derivative, Function, cos >>> from sympy.abc import x, y >>> from sympy.core.basic import _atomic >>> f = Function('f') >>> _atomic(x + y) {x, y} >>> _atomic(x + f(y)) {x, f(y)} >>> _atomic(Derivative(f(x), x) + cos(x) + y) {y, cos(x), Derivative(f(x), x)} """ pot = _preorder_traversal(e) seen = set() if isinstance(e, Basic): free = getattr(e, "free_symbols", None) if free is None: return {e} else: return set() from .symbol import Symbol from .function import Derivative, Function atoms = set() for p in pot: if p in seen: pot.skip() continue seen.add(p) if isinstance(p, Symbol) and p in free: atoms.add(p) elif isinstance(p, (Derivative, Function)): if not recursive: pot.skip() atoms.add(p) return atoms def _make_find_query(query): """Convert the argument of Basic.find() into a callable""" try: query = _sympify(query) except SympifyError: pass if isinstance(query, type): return lambda expr: isinstance(expr, query) elif isinstance(query, Basic): return lambda expr: expr.match(query) is not None return query # Delayed to avoid cyclic import from .singleton import S from .traversal import (preorder_traversal as _preorder_traversal, iterargs, iterfreeargs) preorder_traversal = deprecated( """ Using preorder_traversal from the sympy.core.basic submodule is deprecated. Instead, use preorder_traversal from the top-level sympy namespace, like sympy.preorder_traversal """, deprecated_since_version="1.10", active_deprecations_target="deprecated-traversal-functions-moved", )(_preorder_traversal)
59856624f34f16c6b179e7360f633f4dbf6f52b206dcaf02880a8771ad5854f1
from __future__ import annotations from typing import Callable from math import log as _log, sqrt as _sqrt from itertools import product from .sympify import _sympify from .cache import cacheit from .singleton import S from .expr import Expr from .evalf import PrecisionExhausted from .function import (expand_complex, expand_multinomial, expand_mul, _mexpand, PoleError) from .logic import fuzzy_bool, fuzzy_not, fuzzy_and, fuzzy_or from .parameters import global_parameters from .relational import is_gt, is_lt from .kind import NumberKind, UndefinedKind from sympy.external.gmpy import HAS_GMPY, gmpy from sympy.utilities.iterables import sift from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.misc import as_int from sympy.multipledispatch import Dispatcher from mpmath.libmp import sqrtrem as mpmath_sqrtrem def isqrt(n): """Return the largest integer less than or equal to sqrt(n).""" if n < 0: raise ValueError("n must be nonnegative") n = int(n) # Fast path: with IEEE 754 binary64 floats and a correctly-rounded # math.sqrt, int(math.sqrt(n)) works for any integer n satisfying 0 <= n < # 4503599761588224 = 2**52 + 2**27. But Python doesn't guarantee either # IEEE 754 format floats *or* correct rounding of math.sqrt, so check the # answer and fall back to the slow method if necessary. if n < 4503599761588224: s = int(_sqrt(n)) if 0 <= n - s*s <= 2*s: return s return integer_nthroot(n, 2)[0] def integer_nthroot(y, n): """ Return a tuple containing x = floor(y**(1/n)) and a boolean indicating whether the result is exact (that is, whether x**n == y). Examples ======== >>> from sympy import integer_nthroot >>> integer_nthroot(16, 2) (4, True) >>> integer_nthroot(26, 2) (5, False) To simply determine if a number is a perfect square, the is_square function should be used: >>> from sympy.ntheory.primetest import is_square >>> is_square(26) False See Also ======== sympy.ntheory.primetest.is_square integer_log """ y, n = as_int(y), as_int(n) if y < 0: raise ValueError("y must be nonnegative") if n < 1: raise ValueError("n must be positive") if HAS_GMPY and n < 2**63: # Currently it works only for n < 2**63, else it produces TypeError # sympy issue: https://github.com/sympy/sympy/issues/18374 # gmpy2 issue: https://github.com/aleaxit/gmpy/issues/257 if HAS_GMPY >= 2: x, t = gmpy.iroot(y, n) else: x, t = gmpy.root(y, n) return as_int(x), bool(t) return _integer_nthroot_python(y, n) def _integer_nthroot_python(y, n): if y in (0, 1): return y, True if n == 1: return y, True if n == 2: x, rem = mpmath_sqrtrem(y) return int(x), not rem if n >= y.bit_length(): return 1, False # Get initial estimate for Newton's method. Care must be taken to # avoid overflow try: guess = int(y**(1./n) + 0.5) except OverflowError: exp = _log(y, 2)/n if exp > 53: shift = int(exp - 53) guess = int(2.0**(exp - shift) + 1) << shift else: guess = int(2.0**exp) if guess > 2**50: # Newton iteration xprev, x = -1, guess while 1: t = x**(n - 1) xprev, x = x, ((n - 1)*x + y//t)//n if abs(x - xprev) < 2: break else: x = guess # Compensate t = x**n while t < y: x += 1 t = x**n while t > y: x -= 1 t = x**n return int(x), t == y # int converts long to int if possible def integer_log(y, x): r""" Returns ``(e, bool)`` where e is the largest nonnegative integer such that :math:`|y| \geq |x^e|` and ``bool`` is True if $y = x^e$. Examples ======== >>> from sympy import integer_log >>> integer_log(125, 5) (3, True) >>> integer_log(17, 9) (1, False) >>> integer_log(4, -2) (2, True) >>> integer_log(-125,-5) (3, True) See Also ======== integer_nthroot sympy.ntheory.primetest.is_square sympy.ntheory.factor_.multiplicity sympy.ntheory.factor_.perfect_power """ if x == 1: raise ValueError('x cannot take value as 1') if y == 0: raise ValueError('y cannot take value as 0') if x in (-2, 2): x = int(x) y = as_int(y) e = y.bit_length() - 1 return e, x**e == y if x < 0: n, b = integer_log(y if y > 0 else -y, -x) return n, b and bool(n % 2 if y < 0 else not n % 2) x = as_int(x) y = as_int(y) r = e = 0 while y >= x: d = x m = 1 while y >= d: y, rem = divmod(y, d) r = r or rem e += m if y > d: d *= d m *= 2 return e, r == 0 and y == 1 class Pow(Expr): """ Defines the expression x**y as "x raised to a power y" .. deprecated:: 1.7 Using arguments that aren't subclasses of :class:`~.Expr` in core operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is deprecated. See :ref:`non-expr-args-deprecated` for details. Singleton definitions involving (0, 1, -1, oo, -oo, I, -I): +--------------+---------+-----------------------------------------------+ | expr | value | reason | +==============+=========+===============================================+ | z**0 | 1 | Although arguments over 0**0 exist, see [2]. | +--------------+---------+-----------------------------------------------+ | z**1 | z | | +--------------+---------+-----------------------------------------------+ | (-oo)**(-1) | 0 | | +--------------+---------+-----------------------------------------------+ | (-1)**-1 | -1 | | +--------------+---------+-----------------------------------------------+ | S.Zero**-1 | zoo | This is not strictly true, as 0**-1 may be | | | | undefined, but is convenient in some contexts | | | | where the base is assumed to be positive. | +--------------+---------+-----------------------------------------------+ | 1**-1 | 1 | | +--------------+---------+-----------------------------------------------+ | oo**-1 | 0 | | +--------------+---------+-----------------------------------------------+ | 0**oo | 0 | Because for all complex numbers z near | | | | 0, z**oo -> 0. | +--------------+---------+-----------------------------------------------+ | 0**-oo | zoo | This is not strictly true, as 0**oo may be | | | | oscillating between positive and negative | | | | values or rotating in the complex plane. | | | | It is convenient, however, when the base | | | | is positive. | +--------------+---------+-----------------------------------------------+ | 1**oo | nan | Because there are various cases where | | 1**-oo | | lim(x(t),t)=1, lim(y(t),t)=oo (or -oo), | | | | but lim( x(t)**y(t), t) != 1. See [3]. | +--------------+---------+-----------------------------------------------+ | b**zoo | nan | Because b**z has no limit as z -> zoo | +--------------+---------+-----------------------------------------------+ | (-1)**oo | nan | Because of oscillations in the limit. | | (-1)**(-oo) | | | +--------------+---------+-----------------------------------------------+ | oo**oo | oo | | +--------------+---------+-----------------------------------------------+ | oo**-oo | 0 | | +--------------+---------+-----------------------------------------------+ | (-oo)**oo | nan | | | (-oo)**-oo | | | +--------------+---------+-----------------------------------------------+ | oo**I | nan | oo**e could probably be best thought of as | | (-oo)**I | | the limit of x**e for real x as x tends to | | | | oo. If e is I, then the limit does not exist | | | | and nan is used to indicate that. | +--------------+---------+-----------------------------------------------+ | oo**(1+I) | zoo | If the real part of e is positive, then the | | (-oo)**(1+I) | | limit of abs(x**e) is oo. So the limit value | | | | is zoo. | +--------------+---------+-----------------------------------------------+ | oo**(-1+I) | 0 | If the real part of e is negative, then the | | -oo**(-1+I) | | limit is 0. | +--------------+---------+-----------------------------------------------+ Because symbolic computations are more flexible than floating point calculations and we prefer to never return an incorrect answer, we choose not to conform to all IEEE 754 conventions. This helps us avoid extra test-case code in the calculation of limits. See Also ======== sympy.core.numbers.Infinity sympy.core.numbers.NegativeInfinity sympy.core.numbers.NaN References ========== .. [1] https://en.wikipedia.org/wiki/Exponentiation .. [2] https://en.wikipedia.org/wiki/Zero_to_the_power_of_zero .. [3] https://en.wikipedia.org/wiki/Indeterminate_forms """ is_Pow = True __slots__ = ('is_commutative',) args: tuple[Expr, Expr] _args: tuple[Expr, Expr] @cacheit def __new__(cls, b, e, evaluate=None): if evaluate is None: evaluate = global_parameters.evaluate b = _sympify(b) e = _sympify(e) # XXX: This can be removed when non-Expr args are disallowed rather # than deprecated. from .relational import Relational if isinstance(b, Relational) or isinstance(e, Relational): raise TypeError('Relational cannot be used in Pow') # XXX: This should raise TypeError once deprecation period is over: for arg in [b, e]: if not isinstance(arg, Expr): sympy_deprecation_warning( f""" Using non-Expr arguments in Pow is deprecated (in this case, one of the arguments is of type {type(arg).__name__!r}). If you really did intend to construct a power with this base, use the ** operator instead.""", deprecated_since_version="1.7", active_deprecations_target="non-expr-args-deprecated", stacklevel=4, ) if evaluate: if e is S.ComplexInfinity: return S.NaN if e is S.Infinity: if is_gt(b, S.One): return S.Infinity if is_gt(b, S.NegativeOne) and is_lt(b, S.One): return S.Zero if is_lt(b, S.NegativeOne): if b.is_finite: return S.ComplexInfinity if b.is_finite is False: return S.NaN if e is S.Zero: return S.One elif e is S.One: return b elif e == -1 and not b: return S.ComplexInfinity elif e.__class__.__name__ == "AccumulationBounds": if b == S.Exp1: from sympy.calculus.accumulationbounds import AccumBounds return AccumBounds(Pow(b, e.min), Pow(b, e.max)) # autosimplification if base is a number and exp odd/even # if base is Number then the base will end up positive; we # do not do this with arbitrary expressions since symbolic # cancellation might occur as in (x - 1)/(1 - x) -> -1. If # we returned Piecewise((-1, Ne(x, 1))) for such cases then # we could do this...but we don't elif (e.is_Symbol and e.is_integer or e.is_Integer ) and (b.is_number and b.is_Mul or b.is_Number ) and b.could_extract_minus_sign(): if e.is_even: b = -b elif e.is_odd: return -Pow(-b, e) if S.NaN in (b, e): # XXX S.NaN**x -> S.NaN under assumption that x != 0 return S.NaN elif b is S.One: if abs(e).is_infinite: return S.NaN return S.One else: # recognize base as E from sympy.functions.elementary.exponential import exp_polar if not e.is_Atom and b is not S.Exp1 and not isinstance(b, exp_polar): from .exprtools import factor_terms from sympy.functions.elementary.exponential import log from sympy.simplify.radsimp import fraction c, ex = factor_terms(e, sign=False).as_coeff_Mul() num, den = fraction(ex) if isinstance(den, log) and den.args[0] == b: return S.Exp1**(c*num) elif den.is_Add: from sympy.functions.elementary.complexes import sign, im s = sign(im(b)) if s.is_Number and s and den == \ log(-factor_terms(b, sign=False)) + s*S.ImaginaryUnit*S.Pi: return S.Exp1**(c*num) obj = b._eval_power(e) if obj is not None: return obj obj = Expr.__new__(cls, b, e) obj = cls._exec_constructor_postprocessors(obj) if not isinstance(obj, Pow): return obj obj.is_commutative = (b.is_commutative and e.is_commutative) return obj def inverse(self, argindex=1): if self.base == S.Exp1: from sympy.functions.elementary.exponential import log return log return None @property def base(self) -> Expr: return self._args[0] @property def exp(self) -> Expr: return self._args[1] @property def kind(self): if self.exp.kind is NumberKind: return self.base.kind else: return UndefinedKind @classmethod def class_key(cls): return 3, 2, cls.__name__ def _eval_refine(self, assumptions): from sympy.assumptions.ask import ask, Q b, e = self.as_base_exp() if ask(Q.integer(e), assumptions) and b.could_extract_minus_sign(): if ask(Q.even(e), assumptions): return Pow(-b, e) elif ask(Q.odd(e), assumptions): return -Pow(-b, e) def _eval_power(self, other): b, e = self.as_base_exp() if b is S.NaN: return (b**e)**other # let __new__ handle it s = None if other.is_integer: s = 1 elif b.is_polar: # e.g. exp_polar, besselj, var('p', polar=True)... s = 1 elif e.is_extended_real is not None: from sympy.functions.elementary.complexes import arg, im, re, sign from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.integers import floor # helper functions =========================== def _half(e): """Return True if the exponent has a literal 2 as the denominator, else None.""" if getattr(e, 'q', None) == 2: return True n, d = e.as_numer_denom() if n.is_integer and d == 2: return True def _n2(e): """Return ``e`` evaluated to a Number with 2 significant digits, else None.""" try: rv = e.evalf(2, strict=True) if rv.is_Number: return rv except PrecisionExhausted: pass # =================================================== if e.is_extended_real: # we need _half(other) with constant floor or # floor(S.Half - e*arg(b)/2/pi) == 0 # handle -1 as special case if e == -1: # floor arg. is 1/2 + arg(b)/2/pi if _half(other): if b.is_negative is True: return S.NegativeOne**other*Pow(-b, e*other) elif b.is_negative is False: # XXX ok if im(b) != 0? return Pow(b, -other) elif e.is_even: if b.is_extended_real: b = abs(b) if b.is_imaginary: b = abs(im(b))*S.ImaginaryUnit if (abs(e) < 1) == True or e == 1: s = 1 # floor = 0 elif b.is_extended_nonnegative: s = 1 # floor = 0 elif re(b).is_extended_nonnegative and (abs(e) < 2) == True: s = 1 # floor = 0 elif _half(other): s = exp(2*S.Pi*S.ImaginaryUnit*other*floor( S.Half - e*arg(b)/(2*S.Pi))) if s.is_extended_real and _n2(sign(s) - s) == 0: s = sign(s) else: s = None else: # e.is_extended_real is False requires: # _half(other) with constant floor or # floor(S.Half - im(e*log(b))/2/pi) == 0 try: s = exp(2*S.ImaginaryUnit*S.Pi*other* floor(S.Half - im(e*log(b))/2/S.Pi)) # be careful to test that s is -1 or 1 b/c sign(I) == I: # so check that s is real if s.is_extended_real and _n2(sign(s) - s) == 0: s = sign(s) else: s = None except PrecisionExhausted: s = None if s is not None: return s*Pow(b, e*other) def _eval_Mod(self, q): r"""A dispatched function to compute `b^e \bmod q`, dispatched by ``Mod``. Notes ===== Algorithms: 1. For unevaluated integer power, use built-in ``pow`` function with 3 arguments, if powers are not too large wrt base. 2. For very large powers, use totient reduction if $e \ge \log(m)$. Bound on m, is for safe factorization memory wise i.e. $m^{1/4}$. For pollard-rho to be faster than built-in pow $\log(e) > m^{1/4}$ check is added. 3. For any unevaluated power found in `b` or `e`, the step 2 will be recursed down to the base and the exponent such that the $b \bmod q$ becomes the new base and $\phi(q) + e \bmod \phi(q)$ becomes the new exponent, and then the computation for the reduced expression can be done. """ base, exp = self.base, self.exp if exp.is_integer and exp.is_positive: if q.is_integer and base % q == 0: return S.Zero from sympy.ntheory.factor_ import totient if base.is_Integer and exp.is_Integer and q.is_Integer: b, e, m = int(base), int(exp), int(q) mb = m.bit_length() if mb <= 80 and e >= mb and e.bit_length()**4 >= m: phi = int(totient(m)) return Integer(pow(b, phi + e%phi, m)) return Integer(pow(b, e, m)) from .mod import Mod if isinstance(base, Pow) and base.is_integer and base.is_number: base = Mod(base, q) return Mod(Pow(base, exp, evaluate=False), q) if isinstance(exp, Pow) and exp.is_integer and exp.is_number: bit_length = int(q).bit_length() # XXX Mod-Pow actually attempts to do a hanging evaluation # if this dispatched function returns None. # May need some fixes in the dispatcher itself. if bit_length <= 80: phi = totient(q) exp = phi + Mod(exp, phi) return Mod(Pow(base, exp, evaluate=False), q) def _eval_is_even(self): if self.exp.is_integer and self.exp.is_positive: return self.base.is_even def _eval_is_negative(self): ext_neg = Pow._eval_is_extended_negative(self) if ext_neg is True: return self.is_finite return ext_neg def _eval_is_extended_positive(self): if self.base == self.exp: if self.base.is_extended_nonnegative: return True elif self.base.is_positive: if self.exp.is_real: return True elif self.base.is_extended_negative: if self.exp.is_even: return True if self.exp.is_odd: return False elif self.base.is_zero: if self.exp.is_extended_real: return self.exp.is_zero elif self.base.is_extended_nonpositive: if self.exp.is_odd: return False elif self.base.is_imaginary: if self.exp.is_integer: m = self.exp % 4 if m.is_zero: return True if m.is_integer and m.is_zero is False: return False if self.exp.is_imaginary: from sympy.functions.elementary.exponential import log return log(self.base).is_imaginary def _eval_is_extended_negative(self): if self.exp is S.Half: if self.base.is_complex or self.base.is_extended_real: return False if self.base.is_extended_negative: if self.exp.is_odd and self.base.is_finite: return True if self.exp.is_even: return False elif self.base.is_extended_positive: if self.exp.is_extended_real: return False elif self.base.is_zero: if self.exp.is_extended_real: return False elif self.base.is_extended_nonnegative: if self.exp.is_extended_nonnegative: return False elif self.base.is_extended_nonpositive: if self.exp.is_even: return False elif self.base.is_extended_real: if self.exp.is_even: return False def _eval_is_zero(self): if self.base.is_zero: if self.exp.is_extended_positive: return True elif self.exp.is_extended_nonpositive: return False elif self.base == S.Exp1: return self.exp is S.NegativeInfinity elif self.base.is_zero is False: if self.base.is_finite and self.exp.is_finite: return False elif self.exp.is_negative: return self.base.is_infinite elif self.exp.is_nonnegative: return False elif self.exp.is_infinite and self.exp.is_extended_real: if (1 - abs(self.base)).is_extended_positive: return self.exp.is_extended_positive elif (1 - abs(self.base)).is_extended_negative: return self.exp.is_extended_negative elif self.base.is_finite and self.exp.is_negative: # when self.base.is_zero is None return False def _eval_is_integer(self): b, e = self.args if b.is_rational: if b.is_integer is False and e.is_positive: return False # rat**nonneg if b.is_integer and e.is_integer: if b is S.NegativeOne: return True if e.is_nonnegative or e.is_positive: return True if b.is_integer and e.is_negative and (e.is_finite or e.is_integer): if fuzzy_not((b - 1).is_zero) and fuzzy_not((b + 1).is_zero): return False if b.is_Number and e.is_Number: check = self.func(*self.args) return check.is_Integer if e.is_negative and b.is_positive and (b - 1).is_positive: return False if e.is_negative and b.is_negative and (b + 1).is_negative: return False def _eval_is_extended_real(self): if self.base is S.Exp1: if self.exp.is_extended_real: return True elif self.exp.is_imaginary: return (2*S.ImaginaryUnit*self.exp/S.Pi).is_even from sympy.functions.elementary.exponential import log, exp real_b = self.base.is_extended_real if real_b is None: if self.base.func == exp and self.base.exp.is_imaginary: return self.exp.is_imaginary if self.base.func == Pow and self.base.base is S.Exp1 and self.base.exp.is_imaginary: return self.exp.is_imaginary return real_e = self.exp.is_extended_real if real_e is None: return if real_b and real_e: if self.base.is_extended_positive: return True elif self.base.is_extended_nonnegative and self.exp.is_extended_nonnegative: return True elif self.exp.is_integer and self.base.is_extended_nonzero: return True elif self.exp.is_integer and self.exp.is_nonnegative: return True elif self.base.is_extended_negative: if self.exp.is_Rational: return False if real_e and self.exp.is_extended_negative and self.base.is_zero is False: return Pow(self.base, -self.exp).is_extended_real im_b = self.base.is_imaginary im_e = self.exp.is_imaginary if im_b: if self.exp.is_integer: if self.exp.is_even: return True elif self.exp.is_odd: return False elif im_e and log(self.base).is_imaginary: return True elif self.exp.is_Add: c, a = self.exp.as_coeff_Add() if c and c.is_Integer: return Mul( self.base**c, self.base**a, evaluate=False).is_extended_real elif self.base in (-S.ImaginaryUnit, S.ImaginaryUnit): if (self.exp/2).is_integer is False: return False if real_b and im_e: if self.base is S.NegativeOne: return True c = self.exp.coeff(S.ImaginaryUnit) if c: if self.base.is_rational and c.is_rational: if self.base.is_nonzero and (self.base - 1).is_nonzero and c.is_nonzero: return False ok = (c*log(self.base)/S.Pi).is_integer if ok is not None: return ok if real_b is False and real_e: # we already know it's not imag from sympy.functions.elementary.complexes import arg i = arg(self.base)*self.exp/S.Pi if i.is_complex: # finite return i.is_integer def _eval_is_complex(self): if self.base == S.Exp1: return fuzzy_or([self.exp.is_complex, self.exp.is_extended_negative]) if all(a.is_complex for a in self.args) and self._eval_is_finite(): return True def _eval_is_imaginary(self): if self.base.is_commutative is False: return False if self.base.is_imaginary: if self.exp.is_integer: odd = self.exp.is_odd if odd is not None: return odd return if self.base == S.Exp1: f = 2 * self.exp / (S.Pi*S.ImaginaryUnit) # exp(pi*integer) = 1 or -1, so not imaginary if f.is_even: return False # exp(pi*integer + pi/2) = I or -I, so it is imaginary if f.is_odd: return True return None if self.exp.is_imaginary: from sympy.functions.elementary.exponential import log imlog = log(self.base).is_imaginary if imlog is not None: return False # I**i -> real; (2*I)**i -> complex ==> not imaginary if self.base.is_extended_real and self.exp.is_extended_real: if self.base.is_positive: return False else: rat = self.exp.is_rational if not rat: return rat if self.exp.is_integer: return False else: half = (2*self.exp).is_integer if half: return self.base.is_negative return half if self.base.is_extended_real is False: # we already know it's not imag from sympy.functions.elementary.complexes import arg i = arg(self.base)*self.exp/S.Pi isodd = (2*i).is_odd if isodd is not None: return isodd def _eval_is_odd(self): if self.exp.is_integer: if self.exp.is_positive: return self.base.is_odd elif self.exp.is_nonnegative and self.base.is_odd: return True elif self.base is S.NegativeOne: return True def _eval_is_finite(self): if self.exp.is_negative: if self.base.is_zero: return False if self.base.is_infinite or self.base.is_nonzero: return True c1 = self.base.is_finite if c1 is None: return c2 = self.exp.is_finite if c2 is None: return if c1 and c2: if self.exp.is_nonnegative or fuzzy_not(self.base.is_zero): return True def _eval_is_prime(self): ''' An integer raised to the n(>=2)-th power cannot be a prime. ''' if self.base.is_integer and self.exp.is_integer and (self.exp - 1).is_positive: return False def _eval_is_composite(self): """ A power is composite if both base and exponent are greater than 1 """ if (self.base.is_integer and self.exp.is_integer and ((self.base - 1).is_positive and (self.exp - 1).is_positive or (self.base + 1).is_negative and self.exp.is_positive and self.exp.is_even)): return True def _eval_is_polar(self): return self.base.is_polar def _eval_subs(self, old, new): from sympy.calculus.accumulationbounds import AccumBounds if isinstance(self.exp, AccumBounds): b = self.base.subs(old, new) e = self.exp.subs(old, new) if isinstance(e, AccumBounds): return e.__rpow__(b) return self.func(b, e) from sympy.functions.elementary.exponential import exp, log def _check(ct1, ct2, old): """Return (bool, pow, remainder_pow) where, if bool is True, then the exponent of Pow `old` will combine with `pow` so the substitution is valid, otherwise bool will be False. For noncommutative objects, `pow` will be an integer, and a factor `Pow(old.base, remainder_pow)` needs to be included. If there is no such factor, None is returned. For commutative objects, remainder_pow is always None. cti are the coefficient and terms of an exponent of self or old In this _eval_subs routine a change like (b**(2*x)).subs(b**x, y) will give y**2 since (b**x)**2 == b**(2*x); if that equality does not hold then the substitution should not occur so `bool` will be False. """ coeff1, terms1 = ct1 coeff2, terms2 = ct2 if terms1 == terms2: if old.is_commutative: # Allow fractional powers for commutative objects pow = coeff1/coeff2 try: as_int(pow, strict=False) combines = True except ValueError: b, e = old.as_base_exp() # These conditions ensure that (b**e)**f == b**(e*f) for any f combines = b.is_positive and e.is_real or b.is_nonnegative and e.is_nonnegative return combines, pow, None else: # With noncommutative symbols, substitute only integer powers if not isinstance(terms1, tuple): terms1 = (terms1,) if not all(term.is_integer for term in terms1): return False, None, None try: # Round pow toward zero pow, remainder = divmod(as_int(coeff1), as_int(coeff2)) if pow < 0 and remainder != 0: pow += 1 remainder -= as_int(coeff2) if remainder == 0: remainder_pow = None else: remainder_pow = Mul(remainder, *terms1) return True, pow, remainder_pow except ValueError: # Can't substitute pass return False, None, None if old == self.base or (old == exp and self.base == S.Exp1): if new.is_Function and isinstance(new, Callable): return new(self.exp._subs(old, new)) else: return new**self.exp._subs(old, new) # issue 10829: (4**x - 3*y + 2).subs(2**x, y) -> y**2 - 3*y + 2 if isinstance(old, self.func) and self.exp == old.exp: l = log(self.base, old.base) if l.is_Number: return Pow(new, l) if isinstance(old, self.func) and self.base == old.base: if self.exp.is_Add is False: ct1 = self.exp.as_independent(Symbol, as_Add=False) ct2 = old.exp.as_independent(Symbol, as_Add=False) ok, pow, remainder_pow = _check(ct1, ct2, old) if ok: # issue 5180: (x**(6*y)).subs(x**(3*y),z)->z**2 result = self.func(new, pow) if remainder_pow is not None: result = Mul(result, Pow(old.base, remainder_pow)) return result else: # b**(6*x + a).subs(b**(3*x), y) -> y**2 * b**a # exp(exp(x) + exp(x**2)).subs(exp(exp(x)), w) -> w * exp(exp(x**2)) oarg = old.exp new_l = [] o_al = [] ct2 = oarg.as_coeff_mul() for a in self.exp.args: newa = a._subs(old, new) ct1 = newa.as_coeff_mul() ok, pow, remainder_pow = _check(ct1, ct2, old) if ok: new_l.append(new**pow) if remainder_pow is not None: o_al.append(remainder_pow) continue elif not old.is_commutative and not newa.is_integer: # If any term in the exponent is non-integer, # we do not do any substitutions in the noncommutative case return o_al.append(newa) if new_l: expo = Add(*o_al) new_l.append(Pow(self.base, expo, evaluate=False) if expo != 1 else self.base) return Mul(*new_l) if (isinstance(old, exp) or (old.is_Pow and old.base is S.Exp1)) and self.exp.is_extended_real and self.base.is_positive: ct1 = old.exp.as_independent(Symbol, as_Add=False) ct2 = (self.exp*log(self.base)).as_independent( Symbol, as_Add=False) ok, pow, remainder_pow = _check(ct1, ct2, old) if ok: result = self.func(new, pow) # (2**x).subs(exp(x*log(2)), z) -> z if remainder_pow is not None: result = Mul(result, Pow(old.base, remainder_pow)) return result def as_base_exp(self): """Return base and exp of self. Explanation =========== If base a Rational less than 1, then return 1/Rational, -exp. If this extra processing is not needed, the base and exp properties will give the raw arguments. Examples ======== >>> from sympy import Pow, S >>> p = Pow(S.Half, 2, evaluate=False) >>> p.as_base_exp() (2, -2) >>> p.args (1/2, 2) >>> p.base, p.exp (1/2, 2) """ b, e = self.args if b.is_Rational and b.p < b.q and b.p > 0: return 1/b, -e return b, e def _eval_adjoint(self): from sympy.functions.elementary.complexes import adjoint i, p = self.exp.is_integer, self.base.is_positive if i: return adjoint(self.base)**self.exp if p: return self.base**adjoint(self.exp) if i is False and p is False: expanded = expand_complex(self) if expanded != self: return adjoint(expanded) def _eval_conjugate(self): from sympy.functions.elementary.complexes import conjugate as c i, p = self.exp.is_integer, self.base.is_positive if i: return c(self.base)**self.exp if p: return self.base**c(self.exp) if i is False and p is False: expanded = expand_complex(self) if expanded != self: return c(expanded) if self.is_extended_real: return self def _eval_transpose(self): from sympy.functions.elementary.complexes import transpose if self.base == S.Exp1: return self.func(S.Exp1, self.exp.transpose()) i, p = self.exp.is_integer, (self.base.is_complex or self.base.is_infinite) if p: return self.base**self.exp if i: return transpose(self.base)**self.exp if i is False and p is False: expanded = expand_complex(self) if expanded != self: return transpose(expanded) def _eval_expand_power_exp(self, **hints): """a**(n + m) -> a**n*a**m""" b = self.base e = self.exp if b == S.Exp1: from sympy.concrete.summations import Sum if isinstance(e, Sum) and e.is_commutative: from sympy.concrete.products import Product return Product(self.func(b, e.function), *e.limits) if e.is_Add and (hints.get('force', False) or b.is_zero is False or e._all_nonneg_or_nonppos()): if e.is_commutative: return Mul(*[self.func(b, x) for x in e.args]) if b.is_commutative: c, nc = sift(e.args, lambda x: x.is_commutative, binary=True) if c: return Mul(*[self.func(b, x) for x in c] )*b**Add._from_args(nc) return self def _eval_expand_power_base(self, **hints): """(a*b)**n -> a**n * b**n""" force = hints.get('force', False) b = self.base e = self.exp if not b.is_Mul: return self cargs, nc = b.args_cnc(split_1=False) # expand each term - this is top-level-only # expansion but we have to watch out for things # that don't have an _eval_expand method if nc: nc = [i._eval_expand_power_base(**hints) if hasattr(i, '_eval_expand_power_base') else i for i in nc] if e.is_Integer: if e.is_positive: rv = Mul(*nc*e) else: rv = Mul(*[i**-1 for i in nc[::-1]]*-e) if cargs: rv *= Mul(*cargs)**e return rv if not cargs: return self.func(Mul(*nc), e, evaluate=False) nc = [Mul(*nc)] # sift the commutative bases other, maybe_real = sift(cargs, lambda x: x.is_extended_real is False, binary=True) def pred(x): if x is S.ImaginaryUnit: return S.ImaginaryUnit polar = x.is_polar if polar: return True if polar is None: return fuzzy_bool(x.is_extended_nonnegative) sifted = sift(maybe_real, pred) nonneg = sifted[True] other += sifted[None] neg = sifted[False] imag = sifted[S.ImaginaryUnit] if imag: I = S.ImaginaryUnit i = len(imag) % 4 if i == 0: pass elif i == 1: other.append(I) elif i == 2: if neg: nonn = -neg.pop() if nonn is not S.One: nonneg.append(nonn) else: neg.append(S.NegativeOne) else: if neg: nonn = -neg.pop() if nonn is not S.One: nonneg.append(nonn) else: neg.append(S.NegativeOne) other.append(I) del imag # bring out the bases that can be separated from the base if force or e.is_integer: # treat all commutatives the same and put nc in other cargs = nonneg + neg + other other = nc else: # this is just like what is happening automatically, except # that now we are doing it for an arbitrary exponent for which # no automatic expansion is done assert not e.is_Integer # handle negatives by making them all positive and putting # the residual -1 in other if len(neg) > 1: o = S.One if not other and neg[0].is_Number: o *= neg.pop(0) if len(neg) % 2: o = -o for n in neg: nonneg.append(-n) if o is not S.One: other.append(o) elif neg and other: if neg[0].is_Number and neg[0] is not S.NegativeOne: other.append(S.NegativeOne) nonneg.append(-neg[0]) else: other.extend(neg) else: other.extend(neg) del neg cargs = nonneg other += nc rv = S.One if cargs: if e.is_Rational: npow, cargs = sift(cargs, lambda x: x.is_Pow and x.exp.is_Rational and x.base.is_number, binary=True) rv = Mul(*[self.func(b.func(*b.args), e) for b in npow]) rv *= Mul(*[self.func(b, e, evaluate=False) for b in cargs]) if other: rv *= self.func(Mul(*other), e, evaluate=False) return rv def _eval_expand_multinomial(self, **hints): """(a + b + ..)**n -> a**n + n*a**(n-1)*b + .., n is nonzero integer""" base, exp = self.args result = self if exp.is_Rational and exp.p > 0 and base.is_Add: if not exp.is_Integer: n = Integer(exp.p // exp.q) if not n: return result else: radical, result = self.func(base, exp - n), [] expanded_base_n = self.func(base, n) if expanded_base_n.is_Pow: expanded_base_n = \ expanded_base_n._eval_expand_multinomial() for term in Add.make_args(expanded_base_n): result.append(term*radical) return Add(*result) n = int(exp) if base.is_commutative: order_terms, other_terms = [], [] for b in base.args: if b.is_Order: order_terms.append(b) else: other_terms.append(b) if order_terms: # (f(x) + O(x^n))^m -> f(x)^m + m*f(x)^{m-1} *O(x^n) f = Add(*other_terms) o = Add(*order_terms) if n == 2: return expand_multinomial(f**n, deep=False) + n*f*o else: g = expand_multinomial(f**(n - 1), deep=False) return expand_mul(f*g, deep=False) + n*g*o if base.is_number: # Efficiently expand expressions of the form (a + b*I)**n # where 'a' and 'b' are real numbers and 'n' is integer. a, b = base.as_real_imag() if a.is_Rational and b.is_Rational: if not a.is_Integer: if not b.is_Integer: k = self.func(a.q * b.q, n) a, b = a.p*b.q, a.q*b.p else: k = self.func(a.q, n) a, b = a.p, a.q*b elif not b.is_Integer: k = self.func(b.q, n) a, b = a*b.q, b.p else: k = 1 a, b, c, d = int(a), int(b), 1, 0 while n: if n & 1: c, d = a*c - b*d, b*c + a*d n -= 1 a, b = a*a - b*b, 2*a*b n //= 2 I = S.ImaginaryUnit if k == 1: return c + I*d else: return Integer(c)/k + I*d/k p = other_terms # (x + y)**3 -> x**3 + 3*x**2*y + 3*x*y**2 + y**3 # in this particular example: # p = [x,y]; n = 3 # so now it's easy to get the correct result -- we get the # coefficients first: from sympy.ntheory.multinomial import multinomial_coefficients from sympy.polys.polyutils import basic_from_dict expansion_dict = multinomial_coefficients(len(p), n) # in our example: {(3, 0): 1, (1, 2): 3, (0, 3): 1, (2, 1): 3} # and now construct the expression. return basic_from_dict(expansion_dict, *p) else: if n == 2: return Add(*[f*g for f in base.args for g in base.args]) else: multi = (base**(n - 1))._eval_expand_multinomial() if multi.is_Add: return Add(*[f*g for f in base.args for g in multi.args]) else: # XXX can this ever happen if base was an Add? return Add(*[f*multi for f in base.args]) elif (exp.is_Rational and exp.p < 0 and base.is_Add and abs(exp.p) > exp.q): return 1 / self.func(base, -exp)._eval_expand_multinomial() elif exp.is_Add and base.is_Number and (hints.get('force', False) or base.is_zero is False or exp._all_nonneg_or_nonppos()): # a + b a b # n --> n n, where n, a, b are Numbers # XXX should be in expand_power_exp? coeff, tail = [], [] for term in exp.args: if term.is_Number: coeff.append(self.func(base, term)) else: tail.append(term) return Mul(*(coeff + [self.func(base, Add._from_args(tail))])) else: return result def as_real_imag(self, deep=True, **hints): if self.exp.is_Integer: from sympy.polys.polytools import poly exp = self.exp re_e, im_e = self.base.as_real_imag(deep=deep) if not im_e: return self, S.Zero a, b = symbols('a b', cls=Dummy) if exp >= 0: if re_e.is_Number and im_e.is_Number: # We can be more efficient in this case expr = expand_multinomial(self.base**exp) if expr != self: return expr.as_real_imag() expr = poly( (a + b)**exp) # a = re, b = im; expr = (a + b*I)**exp else: mag = re_e**2 + im_e**2 re_e, im_e = re_e/mag, -im_e/mag if re_e.is_Number and im_e.is_Number: # We can be more efficient in this case expr = expand_multinomial((re_e + im_e*S.ImaginaryUnit)**-exp) if expr != self: return expr.as_real_imag() expr = poly((a + b)**-exp) # Terms with even b powers will be real r = [i for i in expr.terms() if not i[0][1] % 2] re_part = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r]) # Terms with odd b powers will be imaginary r = [i for i in expr.terms() if i[0][1] % 4 == 1] im_part1 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r]) r = [i for i in expr.terms() if i[0][1] % 4 == 3] im_part3 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r]) return (re_part.subs({a: re_e, b: S.ImaginaryUnit*im_e}), im_part1.subs({a: re_e, b: im_e}) + im_part3.subs({a: re_e, b: -im_e})) from sympy.functions.elementary.trigonometric import atan2, cos, sin if self.exp.is_Rational: re_e, im_e = self.base.as_real_imag(deep=deep) if im_e.is_zero and self.exp is S.Half: if re_e.is_extended_nonnegative: return self, S.Zero if re_e.is_extended_nonpositive: return S.Zero, (-self.base)**self.exp # XXX: This is not totally correct since for x**(p/q) with # x being imaginary there are actually q roots, but # only a single one is returned from here. r = self.func(self.func(re_e, 2) + self.func(im_e, 2), S.Half) t = atan2(im_e, re_e) rp, tp = self.func(r, self.exp), t*self.exp return rp*cos(tp), rp*sin(tp) elif self.base is S.Exp1: from sympy.functions.elementary.exponential import exp re_e, im_e = self.exp.as_real_imag() if deep: re_e = re_e.expand(deep, **hints) im_e = im_e.expand(deep, **hints) c, s = cos(im_e), sin(im_e) return exp(re_e)*c, exp(re_e)*s else: from sympy.functions.elementary.complexes import im, re if deep: hints['complex'] = False expanded = self.expand(deep, **hints) if hints.get('ignore') == expanded: return None else: return (re(expanded), im(expanded)) else: return re(self), im(self) def _eval_derivative(self, s): from sympy.functions.elementary.exponential import log dbase = self.base.diff(s) dexp = self.exp.diff(s) return self * (dexp * log(self.base) + dbase * self.exp/self.base) def _eval_evalf(self, prec): base, exp = self.as_base_exp() if base == S.Exp1: # Use mpmath function associated to class "exp": from sympy.functions.elementary.exponential import exp as exp_function return exp_function(self.exp, evaluate=False)._eval_evalf(prec) base = base._evalf(prec) if not exp.is_Integer: exp = exp._evalf(prec) if exp.is_negative and base.is_number and base.is_extended_real is False: base = base.conjugate() / (base * base.conjugate())._evalf(prec) exp = -exp return self.func(base, exp).expand() return self.func(base, exp) def _eval_is_polynomial(self, syms): if self.exp.has(*syms): return False if self.base.has(*syms): return bool(self.base._eval_is_polynomial(syms) and self.exp.is_Integer and (self.exp >= 0)) else: return True def _eval_is_rational(self): # The evaluation of self.func below can be very expensive in the case # of integer**integer if the exponent is large. We should try to exit # before that if possible: if (self.exp.is_integer and self.base.is_rational and fuzzy_not(fuzzy_and([self.exp.is_negative, self.base.is_zero]))): return True p = self.func(*self.as_base_exp()) # in case it's unevaluated if not p.is_Pow: return p.is_rational b, e = p.as_base_exp() if e.is_Rational and b.is_Rational: # we didn't check that e is not an Integer # because Rational**Integer autosimplifies return False if e.is_integer: if b.is_rational: if fuzzy_not(b.is_zero) or e.is_nonnegative: return True if b == e: # always rational, even for 0**0 return True elif b.is_irrational: return e.is_zero if b is S.Exp1: if e.is_rational and e.is_nonzero: return False def _eval_is_algebraic(self): def _is_one(expr): try: return (expr - 1).is_zero except ValueError: # when the operation is not allowed return False if self.base.is_zero or _is_one(self.base): return True elif self.base is S.Exp1: s = self.func(*self.args) if s.func == self.func: if self.exp.is_nonzero: if self.exp.is_algebraic: return False elif (self.exp/S.Pi).is_rational: return False elif (self.exp/(S.ImaginaryUnit*S.Pi)).is_rational: return True else: return s.is_algebraic elif self.exp.is_rational: if self.base.is_algebraic is False: return self.exp.is_zero if self.base.is_zero is False: if self.exp.is_nonzero: return self.base.is_algebraic elif self.base.is_algebraic: return True if self.exp.is_positive: return self.base.is_algebraic elif self.base.is_algebraic and self.exp.is_algebraic: if ((fuzzy_not(self.base.is_zero) and fuzzy_not(_is_one(self.base))) or self.base.is_integer is False or self.base.is_irrational): return self.exp.is_rational def _eval_is_rational_function(self, syms): if self.exp.has(*syms): return False if self.base.has(*syms): return self.base._eval_is_rational_function(syms) and \ self.exp.is_Integer else: return True def _eval_is_meromorphic(self, x, a): # f**g is meromorphic if g is an integer and f is meromorphic. # E**(log(f)*g) is meromorphic if log(f)*g is meromorphic # and finite. base_merom = self.base._eval_is_meromorphic(x, a) exp_integer = self.exp.is_Integer if exp_integer: return base_merom exp_merom = self.exp._eval_is_meromorphic(x, a) if base_merom is False: # f**g = E**(log(f)*g) may be meromorphic if the # singularities of log(f) and g cancel each other, # for example, if g = 1/log(f). Hence, return False if exp_merom else None elif base_merom is None: return None b = self.base.subs(x, a) # b is extended complex as base is meromorphic. # log(base) is finite and meromorphic when b != 0, zoo. b_zero = b.is_zero if b_zero: log_defined = False else: log_defined = fuzzy_and((b.is_finite, fuzzy_not(b_zero))) if log_defined is False: # zero or pole of base return exp_integer # False or None elif log_defined is None: return None if not exp_merom: return exp_merom # False or None return self.exp.subs(x, a).is_finite def _eval_is_algebraic_expr(self, syms): if self.exp.has(*syms): return False if self.base.has(*syms): return self.base._eval_is_algebraic_expr(syms) and \ self.exp.is_Rational else: return True def _eval_rewrite_as_exp(self, base, expo, **kwargs): from sympy.functions.elementary.exponential import exp, log if base.is_zero or base.has(exp) or expo.has(exp): return base**expo if base.has(Symbol): # delay evaluation if expo is non symbolic # (as exp(x*log(5)) automatically reduces to x**5) if global_parameters.exp_is_pow: return Pow(S.Exp1, log(base)*expo, evaluate=expo.has(Symbol)) else: return exp(log(base)*expo, evaluate=expo.has(Symbol)) else: from sympy.functions.elementary.complexes import arg, Abs return exp((log(Abs(base)) + S.ImaginaryUnit*arg(base))*expo) def as_numer_denom(self): if not self.is_commutative: return self, S.One base, exp = self.as_base_exp() n, d = base.as_numer_denom() # this should be the same as ExpBase.as_numer_denom wrt # exponent handling neg_exp = exp.is_negative if exp.is_Mul and not neg_exp and not exp.is_positive: neg_exp = exp.could_extract_minus_sign() int_exp = exp.is_integer # the denominator cannot be separated from the numerator if # its sign is unknown unless the exponent is an integer, e.g. # sqrt(a/b) != sqrt(a)/sqrt(b) when a=1 and b=-1. But if the # denominator is negative the numerator and denominator can # be negated and the denominator (now positive) separated. if not (d.is_extended_real or int_exp): n = base d = S.One dnonpos = d.is_nonpositive if dnonpos: n, d = -n, -d elif dnonpos is None and not int_exp: n = base d = S.One if neg_exp: n, d = d, n exp = -exp if exp.is_infinite: if n is S.One and d is not S.One: return n, self.func(d, exp) if n is not S.One and d is S.One: return self.func(n, exp), d return self.func(n, exp), self.func(d, exp) def matches(self, expr, repl_dict=None, old=False): expr = _sympify(expr) if repl_dict is None: repl_dict = {} # special case, pattern = 1 and expr.exp can match to 0 if expr is S.One: d = self.exp.matches(S.Zero, repl_dict) if d is not None: return d # make sure the expression to be matched is an Expr if not isinstance(expr, Expr): return None b, e = expr.as_base_exp() # special case number sb, se = self.as_base_exp() if sb.is_Symbol and se.is_Integer and expr: if e.is_rational: return sb.matches(b**(e/se), repl_dict) return sb.matches(expr**(1/se), repl_dict) d = repl_dict.copy() d = self.base.matches(b, d) if d is None: return None d = self.exp.xreplace(d).matches(e, d) if d is None: return Expr.matches(self, expr, repl_dict) return d def _eval_nseries(self, x, n, logx, cdir=0): # NOTE! This function is an important part of the gruntz algorithm # for computing limits. It has to return a generalized power # series with coefficients in C(log, log(x)). In more detail: # It has to return an expression # c_0*x**e_0 + c_1*x**e_1 + ... (finitely many terms) # where e_i are numbers (not necessarily integers) and c_i are # expressions involving only numbers, the log function, and log(x). # The series expansion of b**e is computed as follows: # 1) We express b as f*(1 + g) where f is the leading term of b. # g has order O(x**d) where d is strictly positive. # 2) Then b**e = (f**e)*((1 + g)**e). # (1 + g)**e is computed using binomial series. from sympy.functions.elementary.exponential import exp, log from sympy.series.limits import limit from sympy.series.order import Order from sympy.core.sympify import sympify if self.base is S.Exp1: e_series = self.exp.nseries(x, n=n, logx=logx) if e_series.is_Order: return 1 + e_series e0 = limit(e_series.removeO(), x, 0) if e0 is S.NegativeInfinity: return Order(x**n, x) if e0 is S.Infinity: return self t = e_series - e0 exp_series = term = exp(e0) # series of exp(e0 + t) in t for i in range(1, n): term *= t/i term = term.nseries(x, n=n, logx=logx) exp_series += term exp_series += Order(t**n, x) from sympy.simplify.powsimp import powsimp return powsimp(exp_series, deep=True, combine='exp') from sympy.simplify.powsimp import powdenest from .numbers import _illegal self = powdenest(self, force=True).trigsimp() b, e = self.as_base_exp() if e.has(*_illegal): raise PoleError() if e.has(x): return exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir) if logx is not None and b.has(log): from .symbol import Wild c, ex = symbols('c, ex', cls=Wild, exclude=[x]) b = b.replace(log(c*x**ex), log(c) + ex*logx) self = b**e b = b.removeO() try: from sympy.functions.special.gamma_functions import polygamma if b.has(polygamma, S.EulerGamma) and logx is not None: raise ValueError() _, m = b.leadterm(x) except (ValueError, NotImplementedError, PoleError): b = b._eval_nseries(x, n=max(2, n), logx=logx, cdir=cdir).removeO() if b.has(S.NaN, S.ComplexInfinity): raise NotImplementedError() _, m = b.leadterm(x) if e.has(log): from sympy.simplify.simplify import logcombine e = logcombine(e).cancel() if not (m.is_zero or e.is_number and e.is_real): if self == self._eval_as_leading_term(x, logx=logx, cdir=cdir): res = exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir) if res == exp(e*log(b)): return self return res f = b.as_leading_term(x, logx=logx) g = (b/f - S.One).cancel(expand=False) if not m.is_number: raise NotImplementedError() maxpow = n - m*e if maxpow.has(Symbol): maxpow = sympify(n) if maxpow.is_negative: return Order(x**(m*e), x) if g.is_zero: r = f**e if r != self: r += Order(x**n, x) return r def coeff_exp(term, x): coeff, exp = S.One, S.Zero for factor in Mul.make_args(term): if factor.has(x): base, exp = factor.as_base_exp() if base != x: try: return term.leadterm(x) except ValueError: return term, S.Zero else: coeff *= factor return coeff, exp def mul(d1, d2): res = {} for e1, e2 in product(d1, d2): ex = e1 + e2 if ex < maxpow: res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2] return res try: c, d = g.leadterm(x, logx=logx) except (ValueError, NotImplementedError): if limit(g/x**maxpow, x, 0) == 0: # g has higher order zero return f**e + e*f**e*g # first term of binomial series else: raise NotImplementedError() if c.is_Float and d == S.Zero: # Convert floats like 0.5 to exact SymPy numbers like S.Half, to # prevent rounding errors which can induce wrong values of d leading # to a NotImplementedError being returned from the block below. from sympy.simplify.simplify import nsimplify _, d = nsimplify(g).leadterm(x, logx=logx) if not d.is_positive: g = g.simplify() if g.is_zero: return f**e _, d = g.leadterm(x, logx=logx) if not d.is_positive: g = ((b - f)/f).expand() _, d = g.leadterm(x, logx=logx) if not d.is_positive: raise NotImplementedError() from sympy.functions.elementary.integers import ceiling gpoly = g._eval_nseries(x, n=ceiling(maxpow), logx=logx, cdir=cdir).removeO() gterms = {} for term in Add.make_args(gpoly): co1, e1 = coeff_exp(term, x) gterms[e1] = gterms.get(e1, S.Zero) + co1 k = S.One terms = {S.Zero: S.One} tk = gterms from sympy.functions.combinatorial.factorials import factorial, ff while (k*d - maxpow).is_negative: coeff = ff(e, k)/factorial(k) for ex in tk: terms[ex] = terms.get(ex, S.Zero) + coeff*tk[ex] tk = mul(tk, gterms) k += S.One from sympy.functions.elementary.complexes import im if not e.is_integer and m.is_zero and f.is_negative: ndir = (b - f).dir(x, cdir) if im(ndir).is_negative: inco, inex = coeff_exp(f**e*(-1)**(-2*e), x) elif im(ndir).is_zero: inco, inex = coeff_exp(exp(e*log(b)).as_leading_term(x, logx=logx, cdir=cdir), x) else: inco, inex = coeff_exp(f**e, x) else: inco, inex = coeff_exp(f**e, x) res = S.Zero for e1 in terms: ex = e1 + inex res += terms[e1]*inco*x**(ex) if not (e.is_integer and e.is_positive and (e*d - n).is_nonpositive and res == _mexpand(self)): try: res += Order(x**n, x) except NotImplementedError: return exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir) return res def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.functions.elementary.exponential import exp, log e = self.exp b = self.base if self.base is S.Exp1: arg = e.as_leading_term(x, logx=logx) arg0 = arg.subs(x, 0) if arg0 is S.NaN: arg0 = arg.limit(x, 0) if arg0.is_infinite is False: return S.Exp1**arg0 raise PoleError("Cannot expand %s around 0" % (self)) elif e.has(x): lt = exp(e * log(b)) return lt.as_leading_term(x, logx=logx, cdir=cdir) else: from sympy.functions.elementary.complexes import im try: f = b.as_leading_term(x, logx=logx, cdir=cdir) except PoleError: return self if not e.is_integer and f.is_negative and not f.has(x): ndir = (b - f).dir(x, cdir) if im(ndir).is_negative: # Normally, f**e would evaluate to exp(e*log(f)) but on branch cuts # an other value is expected through the following computation # exp(e*(log(f) - 2*pi*I)) == f**e*exp(-2*e*pi*I) == f**e*(-1)**(-2*e). return self.func(f, e) * (-1)**(-2*e) elif im(ndir).is_zero: log_leadterm = log(b)._eval_as_leading_term(x, logx=logx, cdir=cdir) if log_leadterm.is_infinite is False: return exp(e*log_leadterm) return self.func(f, e) @cacheit def _taylor_term(self, n, x, *previous_terms): # of (1 + x)**e from sympy.functions.combinatorial.factorials import binomial return binomial(self.exp, n) * self.func(x, n) def taylor_term(self, n, x, *previous_terms): if self.base is not S.Exp1: return super().taylor_term(n, x, *previous_terms) if n < 0: return S.Zero if n == 0: return S.One from .sympify import sympify x = sympify(x) if previous_terms: p = previous_terms[-1] if p is not None: return p * x / n from sympy.functions.combinatorial.factorials import factorial return x**n/factorial(n) def _eval_rewrite_as_sin(self, base, exp): if self.base is S.Exp1: from sympy.functions.elementary.trigonometric import sin return sin(S.ImaginaryUnit*self.exp + S.Pi/2) - S.ImaginaryUnit*sin(S.ImaginaryUnit*self.exp) def _eval_rewrite_as_cos(self, base, exp): if self.base is S.Exp1: from sympy.functions.elementary.trigonometric import cos return cos(S.ImaginaryUnit*self.exp) + S.ImaginaryUnit*cos(S.ImaginaryUnit*self.exp + S.Pi/2) def _eval_rewrite_as_tanh(self, base, exp): if self.base is S.Exp1: from sympy.functions.elementary.hyperbolic import tanh return (1 + tanh(self.exp/2))/(1 - tanh(self.exp/2)) def _eval_rewrite_as_sqrt(self, base, exp, **kwargs): from sympy.functions.elementary.trigonometric import sin, cos if base is not S.Exp1: return None if exp.is_Mul: coeff = exp.coeff(S.Pi * S.ImaginaryUnit) if coeff and coeff.is_number: cosine, sine = cos(S.Pi*coeff), sin(S.Pi*coeff) if not isinstance(cosine, cos) and not isinstance (sine, sin): return cosine + S.ImaginaryUnit*sine def as_content_primitive(self, radical=False, clear=True): """Return the tuple (R, self/R) where R is the positive Rational extracted from self. Examples ======== >>> from sympy import sqrt >>> sqrt(4 + 4*sqrt(2)).as_content_primitive() (2, sqrt(1 + sqrt(2))) >>> sqrt(3 + 3*sqrt(2)).as_content_primitive() (1, sqrt(3)*sqrt(1 + sqrt(2))) >>> from sympy import expand_power_base, powsimp, Mul >>> from sympy.abc import x, y >>> ((2*x + 2)**2).as_content_primitive() (4, (x + 1)**2) >>> (4**((1 + y)/2)).as_content_primitive() (2, 4**(y/2)) >>> (3**((1 + y)/2)).as_content_primitive() (1, 3**((y + 1)/2)) >>> (3**((5 + y)/2)).as_content_primitive() (9, 3**((y + 1)/2)) >>> eq = 3**(2 + 2*x) >>> powsimp(eq) == eq True >>> eq.as_content_primitive() (9, 3**(2*x)) >>> powsimp(Mul(*_)) 3**(2*x + 2) >>> eq = (2 + 2*x)**y >>> s = expand_power_base(eq); s.is_Mul, s (False, (2*x + 2)**y) >>> eq.as_content_primitive() (1, (2*(x + 1))**y) >>> s = expand_power_base(_[1]); s.is_Mul, s (True, 2**y*(x + 1)**y) See docstring of Expr.as_content_primitive for more examples. """ b, e = self.as_base_exp() b = _keep_coeff(*b.as_content_primitive(radical=radical, clear=clear)) ce, pe = e.as_content_primitive(radical=radical, clear=clear) if b.is_Rational: #e #= ce*pe #= ce*(h + t) #= ce*h + ce*t #=> self #= b**(ce*h)*b**(ce*t) #= b**(cehp/cehq)*b**(ce*t) #= b**(iceh + r/cehq)*b**(ce*t) #= b**(iceh)*b**(r/cehq)*b**(ce*t) #= b**(iceh)*b**(ce*t + r/cehq) h, t = pe.as_coeff_Add() if h.is_Rational and b != S.Zero: ceh = ce*h c = self.func(b, ceh) r = S.Zero if not c.is_Rational: iceh, r = divmod(ceh.p, ceh.q) c = self.func(b, iceh) return c, self.func(b, _keep_coeff(ce, t + r/ce/ceh.q)) e = _keep_coeff(ce, pe) # b**e = (h*t)**e = h**e*t**e = c*m*t**e if e.is_Rational and b.is_Mul: h, t = b.as_content_primitive(radical=radical, clear=clear) # h is positive c, m = self.func(h, e).as_coeff_Mul() # so c is positive m, me = m.as_base_exp() if m is S.One or me == e: # probably always true # return the following, not return c, m*Pow(t, e) # which would change Pow into Mul; we let SymPy # decide what to do by using the unevaluated Mul, e.g # should it stay as sqrt(2 + 2*sqrt(5)) or become # sqrt(2)*sqrt(1 + sqrt(5)) return c, self.func(_keep_coeff(m, t), e) return S.One, self.func(b, e) def is_constant(self, *wrt, **flags): expr = self if flags.get('simplify', True): expr = expr.simplify() b, e = expr.as_base_exp() bz = b.equals(0) if bz: # recalculate with assumptions in case it's unevaluated new = b**e if new != expr: return new.is_constant() econ = e.is_constant(*wrt) bcon = b.is_constant(*wrt) if bcon: if econ: return True bz = b.equals(0) if bz is False: return False elif bcon is None: return None return e.equals(0) def _eval_difference_delta(self, n, step): b, e = self.args if e.has(n) and not b.has(n): new_e = e.subs(n, n + step) return (b**(new_e - e) - 1) * self power = Dispatcher('power') power.add((object, object), Pow) from .add import Add from .numbers import Integer from .mul import Mul, _keep_coeff from .symbol import Symbol, Dummy, symbols
982531cb24190d271e53b7873f15770b49815162386b6433fcb859c49e455d8f
"""Tools for manipulating of large commutative expressions. """ from .add import Add from .mul import Mul, _keep_coeff from .power import Pow from .basic import Basic from .expr import Expr from .function import expand_power_exp from .sympify import sympify from .numbers import Rational, Integer, Number, I, equal_valued from .singleton import S from .sorting import default_sort_key, ordered from .symbol import Dummy from .traversal import preorder_traversal from .coreerrors import NonCommutativeExpression from .containers import Tuple, Dict from sympy.external.gmpy import SYMPY_INTS from sympy.utilities.iterables import (common_prefix, common_suffix, variations, iterable, is_sequence) from collections import defaultdict from typing import Tuple as tTuple _eps = Dummy(positive=True) def _isnumber(i): return isinstance(i, (SYMPY_INTS, float)) or i.is_Number def _monotonic_sign(self): """Return the value closest to 0 that ``self`` may have if all symbols are signed and the result is uniformly the same sign for all values of symbols. If a symbol is only signed but not known to be an integer or the result is 0 then a symbol representative of the sign of self will be returned. Otherwise, None is returned if a) the sign could be positive or negative or b) self is not in one of the following forms: - L(x, y, ...) + A: a function linear in all symbols x, y, ... with an additive constant; if A is zero then the function can be a monomial whose sign is monotonic over the range of the variables, e.g. (x + 1)**3 if x is nonnegative. - A/L(x, y, ...) + B: the inverse of a function linear in all symbols x, y, ... that does not have a sign change from positive to negative for any set of values for the variables. - M(x, y, ...) + A: a monomial M whose factors are all signed and a constant, A. - A/M(x, y, ...) + B: the inverse of a monomial and constants A and B. - P(x): a univariate polynomial Examples ======== >>> from sympy.core.exprtools import _monotonic_sign as F >>> from sympy import Dummy >>> nn = Dummy(integer=True, nonnegative=True) >>> p = Dummy(integer=True, positive=True) >>> p2 = Dummy(integer=True, positive=True) >>> F(nn + 1) 1 >>> F(p - 1) _nneg >>> F(nn*p + 1) 1 >>> F(p2*p + 1) 2 >>> F(nn - 1) # could be negative, zero or positive """ if not self.is_extended_real: return if (-self).is_Symbol: rv = _monotonic_sign(-self) return rv if rv is None else -rv if not self.is_Add and self.as_numer_denom()[1].is_number: s = self if s.is_prime: if s.is_odd: return Integer(3) else: return Integer(2) elif s.is_composite: if s.is_odd: return Integer(9) else: return Integer(4) elif s.is_positive: if s.is_even: if s.is_prime is False: return Integer(4) else: return Integer(2) elif s.is_integer: return S.One else: return _eps elif s.is_extended_negative: if s.is_even: return Integer(-2) elif s.is_integer: return S.NegativeOne else: return -_eps if s.is_zero or s.is_extended_nonpositive or s.is_extended_nonnegative: return S.Zero return None # univariate polynomial free = self.free_symbols if len(free) == 1: if self.is_polynomial(): from sympy.polys.polytools import real_roots from sympy.polys.polyroots import roots from sympy.polys.polyerrors import PolynomialError x = free.pop() x0 = _monotonic_sign(x) if x0 in (_eps, -_eps): x0 = S.Zero if x0 is not None: d = self.diff(x) if d.is_number: currentroots = [] else: try: currentroots = real_roots(d) except (PolynomialError, NotImplementedError): currentroots = [r for r in roots(d, x) if r.is_extended_real] y = self.subs(x, x0) if x.is_nonnegative and all( (r - x0).is_nonpositive for r in currentroots): if y.is_nonnegative and d.is_positive: if y: return y if y.is_positive else Dummy('pos', positive=True) else: return Dummy('nneg', nonnegative=True) if y.is_nonpositive and d.is_negative: if y: return y if y.is_negative else Dummy('neg', negative=True) else: return Dummy('npos', nonpositive=True) elif x.is_nonpositive and all( (r - x0).is_nonnegative for r in currentroots): if y.is_nonnegative and d.is_negative: if y: return Dummy('pos', positive=True) else: return Dummy('nneg', nonnegative=True) if y.is_nonpositive and d.is_positive: if y: return Dummy('neg', negative=True) else: return Dummy('npos', nonpositive=True) else: n, d = self.as_numer_denom() den = None if n.is_number: den = _monotonic_sign(d) elif not d.is_number: if _monotonic_sign(n) is not None: den = _monotonic_sign(d) if den is not None and (den.is_positive or den.is_negative): v = n*den if v.is_positive: return Dummy('pos', positive=True) elif v.is_nonnegative: return Dummy('nneg', nonnegative=True) elif v.is_negative: return Dummy('neg', negative=True) elif v.is_nonpositive: return Dummy('npos', nonpositive=True) return None # multivariate c, a = self.as_coeff_Add() v = None if not a.is_polynomial(): # F/A or A/F where A is a number and F is a signed, rational monomial n, d = a.as_numer_denom() if not (n.is_number or d.is_number): return if ( a.is_Mul or a.is_Pow) and \ a.is_rational and \ all(p.exp.is_Integer for p in a.atoms(Pow) if p.is_Pow) and \ (a.is_positive or a.is_negative): v = S.One for ai in Mul.make_args(a): if ai.is_number: v *= ai continue reps = {} for x in ai.free_symbols: reps[x] = _monotonic_sign(x) if reps[x] is None: return v *= ai.subs(reps) elif c: # signed linear expression if not any(p for p in a.atoms(Pow) if not p.is_number) and (a.is_nonpositive or a.is_nonnegative): free = list(a.free_symbols) p = {} for i in free: v = _monotonic_sign(i) if v is None: return p[i] = v or (_eps if i.is_nonnegative else -_eps) v = a.xreplace(p) if v is not None: rv = v + c if v.is_nonnegative and rv.is_positive: return rv.subs(_eps, 0) if v.is_nonpositive and rv.is_negative: return rv.subs(_eps, 0) def decompose_power(expr: Expr) -> tTuple[Expr, int]: """ Decompose power into symbolic base and integer exponent. Examples ======== >>> from sympy.core.exprtools import decompose_power >>> from sympy.abc import x, y >>> from sympy import exp >>> decompose_power(x) (x, 1) >>> decompose_power(x**2) (x, 2) >>> decompose_power(exp(2*y/3)) (exp(y/3), 2) """ base, exp = expr.as_base_exp() if exp.is_Number: if exp.is_Rational: if not exp.is_Integer: base = Pow(base, Rational(1, exp.q)) # type: ignore e = exp.p # type: ignore else: base, e = expr, 1 else: exp, tail = exp.as_coeff_Mul(rational=True) if exp is S.NegativeOne: base, e = Pow(base, tail), -1 elif exp is not S.One: # todo: after dropping python 3.7 support, use overload and Literal # in as_coeff_Mul to make exp Rational, and remove these 2 ignores tail = _keep_coeff(Rational(1, exp.q), tail) # type: ignore base, e = Pow(base, tail), exp.p # type: ignore else: base, e = expr, 1 return base, e def decompose_power_rat(expr: Expr) -> tTuple[Expr, Rational]: """ Decompose power into symbolic base and rational exponent; if the exponent is not a Rational, then separate only the integer coefficient. Examples ======== >>> from sympy.core.exprtools import decompose_power_rat >>> from sympy.abc import x >>> from sympy import sqrt, exp >>> decompose_power_rat(sqrt(x)) (x, 1/2) >>> decompose_power_rat(exp(-3*x/2)) (exp(x/2), -3) """ _ = base, exp = expr.as_base_exp() return _ if exp.is_Rational else decompose_power(expr) class Factors: """Efficient representation of ``f_1*f_2*...*f_n``.""" __slots__ = ('factors', 'gens') def __init__(self, factors=None): # Factors """Initialize Factors from dict or expr. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x >>> from sympy import I >>> e = 2*x**3 >>> Factors(e) Factors({2: 1, x: 3}) >>> Factors(e.as_powers_dict()) Factors({2: 1, x: 3}) >>> f = _ >>> f.factors # underlying dictionary {2: 1, x: 3} >>> f.gens # base of each factor frozenset({2, x}) >>> Factors(0) Factors({0: 1}) >>> Factors(I) Factors({I: 1}) Notes ===== Although a dictionary can be passed, only minimal checking is performed: powers of -1 and I are made canonical. """ if isinstance(factors, (SYMPY_INTS, float)): factors = S(factors) if isinstance(factors, Factors): factors = factors.factors.copy() elif factors in (None, S.One): factors = {} elif factors is S.Zero or factors == 0: factors = {S.Zero: S.One} elif isinstance(factors, Number): n = factors factors = {} if n < 0: factors[S.NegativeOne] = S.One n = -n if n is not S.One: if n.is_Float or n.is_Integer or n is S.Infinity: factors[n] = S.One elif n.is_Rational: # since we're processing Numbers, the denominator is # stored with a negative exponent; all other factors # are left . if n.p != 1: factors[Integer(n.p)] = S.One factors[Integer(n.q)] = S.NegativeOne else: raise ValueError('Expected Float|Rational|Integer, not %s' % n) elif isinstance(factors, Basic) and not factors.args: factors = {factors: S.One} elif isinstance(factors, Expr): c, nc = factors.args_cnc() i = c.count(I) for _ in range(i): c.remove(I) factors = dict(Mul._from_args(c).as_powers_dict()) # Handle all rational Coefficients for f in list(factors.keys()): if isinstance(f, Rational) and not isinstance(f, Integer): p, q = Integer(f.p), Integer(f.q) factors[p] = (factors[p] if p in factors else S.Zero) + factors[f] factors[q] = (factors[q] if q in factors else S.Zero) - factors[f] factors.pop(f) if i: factors[I] = factors.get(I, S.Zero) + i if nc: factors[Mul(*nc, evaluate=False)] = S.One else: factors = factors.copy() # /!\ should be dict-like # tidy up -/+1 and I exponents if Rational handle = [k for k in factors if k is I or k in (-1, 1)] if handle: i1 = S.One for k in handle: if not _isnumber(factors[k]): continue i1 *= k**factors.pop(k) if i1 is not S.One: for a in i1.args if i1.is_Mul else [i1]: # at worst, -1.0*I*(-1)**e if a is S.NegativeOne: factors[a] = S.One elif a is I: factors[I] = S.One elif a.is_Pow: factors[a.base] = factors.get(a.base, S.Zero) + a.exp elif equal_valued(a, 1): factors[a] = S.One elif equal_valued(a, -1): factors[-a] = S.One factors[S.NegativeOne] = S.One else: raise ValueError('unexpected factor in i1: %s' % a) self.factors = factors keys = getattr(factors, 'keys', None) if keys is None: raise TypeError('expecting Expr or dictionary') self.gens = frozenset(keys()) def __hash__(self): # Factors keys = tuple(ordered(self.factors.keys())) values = [self.factors[k] for k in keys] return hash((keys, values)) def __repr__(self): # Factors return "Factors({%s})" % ', '.join( ['%s: %s' % (k, v) for k, v in ordered(self.factors.items())]) @property def is_zero(self): # Factors """ >>> from sympy.core.exprtools import Factors >>> Factors(0).is_zero True """ f = self.factors return len(f) == 1 and S.Zero in f @property def is_one(self): # Factors """ >>> from sympy.core.exprtools import Factors >>> Factors(1).is_one True """ return not self.factors def as_expr(self): # Factors """Return the underlying expression. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x, y >>> Factors((x*y**2).as_powers_dict()).as_expr() x*y**2 """ args = [] for factor, exp in self.factors.items(): if exp != 1: if isinstance(exp, Integer): b, e = factor.as_base_exp() e = _keep_coeff(exp, e) args.append(b**e) else: args.append(factor**exp) else: args.append(factor) return Mul(*args) def mul(self, other): # Factors """Return Factors of ``self * other``. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x, y, z >>> a = Factors((x*y**2).as_powers_dict()) >>> b = Factors((x*y/z).as_powers_dict()) >>> a.mul(b) Factors({x: 2, y: 3, z: -1}) >>> a*b Factors({x: 2, y: 3, z: -1}) """ if not isinstance(other, Factors): other = Factors(other) if any(f.is_zero for f in (self, other)): return Factors(S.Zero) factors = dict(self.factors) for factor, exp in other.factors.items(): if factor in factors: exp = factors[factor] + exp if not exp: del factors[factor] continue factors[factor] = exp return Factors(factors) def normal(self, other): """Return ``self`` and ``other`` with ``gcd`` removed from each. The only differences between this and method ``div`` is that this is 1) optimized for the case when there are few factors in common and 2) this does not raise an error if ``other`` is zero. See Also ======== div """ if not isinstance(other, Factors): other = Factors(other) if other.is_zero: return (Factors(), Factors(S.Zero)) if self.is_zero: return (Factors(S.Zero), Factors()) self_factors = dict(self.factors) other_factors = dict(other.factors) for factor, self_exp in self.factors.items(): try: other_exp = other.factors[factor] except KeyError: continue exp = self_exp - other_exp if not exp: del self_factors[factor] del other_factors[factor] elif _isnumber(exp): if exp > 0: self_factors[factor] = exp del other_factors[factor] else: del self_factors[factor] other_factors[factor] = -exp else: r = self_exp.extract_additively(other_exp) if r is not None: if r: self_factors[factor] = r del other_factors[factor] else: # should be handled already del self_factors[factor] del other_factors[factor] else: sc, sa = self_exp.as_coeff_Add() if sc: oc, oa = other_exp.as_coeff_Add() diff = sc - oc if diff > 0: self_factors[factor] -= oc other_exp = oa elif diff < 0: self_factors[factor] -= sc other_factors[factor] -= sc other_exp = oa - diff else: self_factors[factor] = sa other_exp = oa if other_exp: other_factors[factor] = other_exp else: del other_factors[factor] return Factors(self_factors), Factors(other_factors) def div(self, other): # Factors """Return ``self`` and ``other`` with ``gcd`` removed from each. This is optimized for the case when there are many factors in common. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x, y, z >>> from sympy import S >>> a = Factors((x*y**2).as_powers_dict()) >>> a.div(a) (Factors({}), Factors({})) >>> a.div(x*z) (Factors({y: 2}), Factors({z: 1})) The ``/`` operator only gives ``quo``: >>> a/x Factors({y: 2}) Factors treats its factors as though they are all in the numerator, so if you violate this assumption the results will be correct but will not strictly correspond to the numerator and denominator of the ratio: >>> a.div(x/z) (Factors({y: 2}), Factors({z: -1})) Factors is also naive about bases: it does not attempt any denesting of Rational-base terms, for example the following does not become 2**(2*x)/2. >>> Factors(2**(2*x + 2)).div(S(8)) (Factors({2: 2*x + 2}), Factors({8: 1})) factor_terms can clean up such Rational-bases powers: >>> from sympy import factor_terms >>> n, d = Factors(2**(2*x + 2)).div(S(8)) >>> n.as_expr()/d.as_expr() 2**(2*x + 2)/8 >>> factor_terms(_) 2**(2*x)/2 """ quo, rem = dict(self.factors), {} if not isinstance(other, Factors): other = Factors(other) if other.is_zero: raise ZeroDivisionError if self.is_zero: return (Factors(S.Zero), Factors()) for factor, exp in other.factors.items(): if factor in quo: d = quo[factor] - exp if _isnumber(d): if d <= 0: del quo[factor] if d >= 0: if d: quo[factor] = d continue exp = -d else: r = quo[factor].extract_additively(exp) if r is not None: if r: quo[factor] = r else: # should be handled already del quo[factor] else: other_exp = exp sc, sa = quo[factor].as_coeff_Add() if sc: oc, oa = other_exp.as_coeff_Add() diff = sc - oc if diff > 0: quo[factor] -= oc other_exp = oa elif diff < 0: quo[factor] -= sc other_exp = oa - diff else: quo[factor] = sa other_exp = oa if other_exp: rem[factor] = other_exp else: assert factor not in rem continue rem[factor] = exp return Factors(quo), Factors(rem) def quo(self, other): # Factors """Return numerator Factor of ``self / other``. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x, y, z >>> a = Factors((x*y**2).as_powers_dict()) >>> b = Factors((x*y/z).as_powers_dict()) >>> a.quo(b) # same as a/b Factors({y: 1}) """ return self.div(other)[0] def rem(self, other): # Factors """Return denominator Factors of ``self / other``. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x, y, z >>> a = Factors((x*y**2).as_powers_dict()) >>> b = Factors((x*y/z).as_powers_dict()) >>> a.rem(b) Factors({z: -1}) >>> a.rem(a) Factors({}) """ return self.div(other)[1] def pow(self, other): # Factors """Return self raised to a non-negative integer power. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x, y >>> a = Factors((x*y**2).as_powers_dict()) >>> a**2 Factors({x: 2, y: 4}) """ if isinstance(other, Factors): other = other.as_expr() if other.is_Integer: other = int(other) if isinstance(other, SYMPY_INTS) and other >= 0: factors = {} if other: for factor, exp in self.factors.items(): factors[factor] = exp*other return Factors(factors) else: raise ValueError("expected non-negative integer, got %s" % other) def gcd(self, other): # Factors """Return Factors of ``gcd(self, other)``. The keys are the intersection of factors with the minimum exponent for each factor. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x, y, z >>> a = Factors((x*y**2).as_powers_dict()) >>> b = Factors((x*y/z).as_powers_dict()) >>> a.gcd(b) Factors({x: 1, y: 1}) """ if not isinstance(other, Factors): other = Factors(other) if other.is_zero: return Factors(self.factors) factors = {} for factor, exp in self.factors.items(): factor, exp = sympify(factor), sympify(exp) if factor in other.factors: lt = (exp - other.factors[factor]).is_negative if lt == True: factors[factor] = exp elif lt == False: factors[factor] = other.factors[factor] return Factors(factors) def lcm(self, other): # Factors """Return Factors of ``lcm(self, other)`` which are the union of factors with the maximum exponent for each factor. Examples ======== >>> from sympy.core.exprtools import Factors >>> from sympy.abc import x, y, z >>> a = Factors((x*y**2).as_powers_dict()) >>> b = Factors((x*y/z).as_powers_dict()) >>> a.lcm(b) Factors({x: 1, y: 2, z: -1}) """ if not isinstance(other, Factors): other = Factors(other) if any(f.is_zero for f in (self, other)): return Factors(S.Zero) factors = dict(self.factors) for factor, exp in other.factors.items(): if factor in factors: exp = max(exp, factors[factor]) factors[factor] = exp return Factors(factors) def __mul__(self, other): # Factors return self.mul(other) def __divmod__(self, other): # Factors return self.div(other) def __truediv__(self, other): # Factors return self.quo(other) def __mod__(self, other): # Factors return self.rem(other) def __pow__(self, other): # Factors return self.pow(other) def __eq__(self, other): # Factors if not isinstance(other, Factors): other = Factors(other) return self.factors == other.factors def __ne__(self, other): # Factors return not self == other class Term: """Efficient representation of ``coeff*(numer/denom)``. """ __slots__ = ('coeff', 'numer', 'denom') def __init__(self, term, numer=None, denom=None): # Term if numer is None and denom is None: if not term.is_commutative: raise NonCommutativeExpression( 'commutative expression expected') coeff, factors = term.as_coeff_mul() numer, denom = defaultdict(int), defaultdict(int) for factor in factors: base, exp = decompose_power(factor) if base.is_Add: cont, base = base.primitive() coeff *= cont**exp if exp > 0: numer[base] += exp else: denom[base] += -exp numer = Factors(numer) denom = Factors(denom) else: coeff = term if numer is None: numer = Factors() if denom is None: denom = Factors() self.coeff = coeff self.numer = numer self.denom = denom def __hash__(self): # Term return hash((self.coeff, self.numer, self.denom)) def __repr__(self): # Term return "Term(%s, %s, %s)" % (self.coeff, self.numer, self.denom) def as_expr(self): # Term return self.coeff*(self.numer.as_expr()/self.denom.as_expr()) def mul(self, other): # Term coeff = self.coeff*other.coeff numer = self.numer.mul(other.numer) denom = self.denom.mul(other.denom) numer, denom = numer.normal(denom) return Term(coeff, numer, denom) def inv(self): # Term return Term(1/self.coeff, self.denom, self.numer) def quo(self, other): # Term return self.mul(other.inv()) def pow(self, other): # Term if other < 0: return self.inv().pow(-other) else: return Term(self.coeff ** other, self.numer.pow(other), self.denom.pow(other)) def gcd(self, other): # Term return Term(self.coeff.gcd(other.coeff), self.numer.gcd(other.numer), self.denom.gcd(other.denom)) def lcm(self, other): # Term return Term(self.coeff.lcm(other.coeff), self.numer.lcm(other.numer), self.denom.lcm(other.denom)) def __mul__(self, other): # Term if isinstance(other, Term): return self.mul(other) else: return NotImplemented def __truediv__(self, other): # Term if isinstance(other, Term): return self.quo(other) else: return NotImplemented def __pow__(self, other): # Term if isinstance(other, SYMPY_INTS): return self.pow(other) else: return NotImplemented def __eq__(self, other): # Term return (self.coeff == other.coeff and self.numer == other.numer and self.denom == other.denom) def __ne__(self, other): # Term return not self == other def _gcd_terms(terms, isprimitive=False, fraction=True): """Helper function for :func:`gcd_terms`. Parameters ========== isprimitive : boolean, optional If ``isprimitive`` is True then the call to primitive for an Add will be skipped. This is useful when the content has already been extracted. fraction : boolean, optional If ``fraction`` is True then the expression will appear over a common denominator, the lcm of all term denominators. """ if isinstance(terms, Basic) and not isinstance(terms, Tuple): terms = Add.make_args(terms) terms = list(map(Term, [t for t in terms if t])) # there is some simplification that may happen if we leave this # here rather than duplicate it before the mapping of Term onto # the terms if len(terms) == 0: return S.Zero, S.Zero, S.One if len(terms) == 1: cont = terms[0].coeff numer = terms[0].numer.as_expr() denom = terms[0].denom.as_expr() else: cont = terms[0] for term in terms[1:]: cont = cont.gcd(term) for i, term in enumerate(terms): terms[i] = term.quo(cont) if fraction: denom = terms[0].denom for term in terms[1:]: denom = denom.lcm(term.denom) numers = [] for term in terms: numer = term.numer.mul(denom.quo(term.denom)) numers.append(term.coeff*numer.as_expr()) else: numers = [t.as_expr() for t in terms] denom = Term(S.One).numer cont = cont.as_expr() numer = Add(*numers) denom = denom.as_expr() if not isprimitive and numer.is_Add: _cont, numer = numer.primitive() cont *= _cont return cont, numer, denom def gcd_terms(terms, isprimitive=False, clear=True, fraction=True): """Compute the GCD of ``terms`` and put them together. Parameters ========== terms : Expr Can be an expression or a non-Basic sequence of expressions which will be handled as though they are terms from a sum. isprimitive : bool, optional If ``isprimitive`` is True the _gcd_terms will not run the primitive method on the terms. clear : bool, optional It controls the removal of integers from the denominator of an Add expression. When True (default), all numerical denominator will be cleared; when False the denominators will be cleared only if all terms had numerical denominators other than 1. fraction : bool, optional When True (default), will put the expression over a common denominator. Examples ======== >>> from sympy import gcd_terms >>> from sympy.abc import x, y >>> gcd_terms((x + 1)**2*y + (x + 1)*y**2) y*(x + 1)*(x + y + 1) >>> gcd_terms(x/2 + 1) (x + 2)/2 >>> gcd_terms(x/2 + 1, clear=False) x/2 + 1 >>> gcd_terms(x/2 + y/2, clear=False) (x + y)/2 >>> gcd_terms(x/2 + 1/x) (x**2 + 2)/(2*x) >>> gcd_terms(x/2 + 1/x, fraction=False) (x + 2/x)/2 >>> gcd_terms(x/2 + 1/x, fraction=False, clear=False) x/2 + 1/x >>> gcd_terms(x/2/y + 1/x/y) (x**2 + 2)/(2*x*y) >>> gcd_terms(x/2/y + 1/x/y, clear=False) (x**2/2 + 1)/(x*y) >>> gcd_terms(x/2/y + 1/x/y, clear=False, fraction=False) (x/2 + 1/x)/y The ``clear`` flag was ignored in this case because the returned expression was a rational expression, not a simple sum. See Also ======== factor_terms, sympy.polys.polytools.terms_gcd """ def mask(terms): """replace nc portions of each term with a unique Dummy symbols and return the replacements to restore them""" args = [(a, []) if a.is_commutative else a.args_cnc() for a in terms] reps = [] for i, (c, nc) in enumerate(args): if nc: nc = Mul(*nc) d = Dummy() reps.append((d, nc)) c.append(d) args[i] = Mul(*c) else: args[i] = c return args, dict(reps) isadd = isinstance(terms, Add) addlike = isadd or not isinstance(terms, Basic) and \ is_sequence(terms, include=set) and \ not isinstance(terms, Dict) if addlike: if isadd: # i.e. an Add terms = list(terms.args) else: terms = sympify(terms) terms, reps = mask(terms) cont, numer, denom = _gcd_terms(terms, isprimitive, fraction) numer = numer.xreplace(reps) coeff, factors = cont.as_coeff_Mul() if not clear: c, _coeff = coeff.as_coeff_Mul() if not c.is_Integer and not clear and numer.is_Add: n, d = c.as_numer_denom() _numer = numer/d if any(a.as_coeff_Mul()[0].is_Integer for a in _numer.args): numer = _numer coeff = n*_coeff return _keep_coeff(coeff, factors*numer/denom, clear=clear) if not isinstance(terms, Basic): return terms if terms.is_Atom: return terms if terms.is_Mul: c, args = terms.as_coeff_mul() return _keep_coeff(c, Mul(*[gcd_terms(i, isprimitive, clear, fraction) for i in args]), clear=clear) def handle(a): # don't treat internal args like terms of an Add if not isinstance(a, Expr): if isinstance(a, Basic): if not a.args: return a return a.func(*[handle(i) for i in a.args]) return type(a)([handle(i) for i in a]) return gcd_terms(a, isprimitive, clear, fraction) if isinstance(terms, Dict): return Dict(*[(k, handle(v)) for k, v in terms.args]) return terms.func(*[handle(i) for i in terms.args]) def _factor_sum_int(expr, **kwargs): """Return Sum or Integral object with factors that are not in the wrt variables removed. In cases where there are additive terms in the function of the object that are independent, the object will be separated into two objects. Examples ======== >>> from sympy import Sum, factor_terms >>> from sympy.abc import x, y >>> factor_terms(Sum(x + y, (x, 1, 3))) y*Sum(1, (x, 1, 3)) + Sum(x, (x, 1, 3)) >>> factor_terms(Sum(x*y, (x, 1, 3))) y*Sum(x, (x, 1, 3)) Notes ===== If a function in the summand or integrand is replaced with a symbol, then this simplification should not be done or else an incorrect result will be obtained when the symbol is replaced with an expression that depends on the variables of summation/integration: >>> eq = Sum(y, (x, 1, 3)) >>> factor_terms(eq).subs(y, x).doit() 3*x >>> eq.subs(y, x).doit() 6 """ result = expr.function if result == 0: return S.Zero limits = expr.limits # get the wrt variables wrt = {i.args[0] for i in limits} # factor out any common terms that are independent of wrt f = factor_terms(result, **kwargs) i, d = f.as_independent(*wrt) if isinstance(f, Add): return i * expr.func(1, *limits) + expr.func(d, *limits) else: return i * expr.func(d, *limits) def factor_terms(expr, radical=False, clear=False, fraction=False, sign=True): """Remove common factors from terms in all arguments without changing the underlying structure of the expr. No expansion or simplification (and no processing of non-commutatives) is performed. Parameters ========== radical: bool, optional If radical=True then a radical common to all terms will be factored out of any Add sub-expressions of the expr. clear : bool, optional If clear=False (default) then coefficients will not be separated from a single Add if they can be distributed to leave one or more terms with integer coefficients. fraction : bool, optional If fraction=True (default is False) then a common denominator will be constructed for the expression. sign : bool, optional If sign=True (default) then even if the only factor in common is a -1, it will be factored out of the expression. Examples ======== >>> from sympy import factor_terms, Symbol >>> from sympy.abc import x, y >>> factor_terms(x + x*(2 + 4*y)**3) x*(8*(2*y + 1)**3 + 1) >>> A = Symbol('A', commutative=False) >>> factor_terms(x*A + x*A + x*y*A) x*(y*A + 2*A) When ``clear`` is False, a rational will only be factored out of an Add expression if all terms of the Add have coefficients that are fractions: >>> factor_terms(x/2 + 1, clear=False) x/2 + 1 >>> factor_terms(x/2 + 1, clear=True) (x + 2)/2 If a -1 is all that can be factored out, to *not* factor it out, the flag ``sign`` must be False: >>> factor_terms(-x - y) -(x + y) >>> factor_terms(-x - y, sign=False) -x - y >>> factor_terms(-2*x - 2*y, sign=False) -2*(x + y) See Also ======== gcd_terms, sympy.polys.polytools.terms_gcd """ def do(expr): from sympy.concrete.summations import Sum from sympy.integrals.integrals import Integral is_iterable = iterable(expr) if not isinstance(expr, Basic) or expr.is_Atom: if is_iterable: return type(expr)([do(i) for i in expr]) return expr if expr.is_Pow or expr.is_Function or \ is_iterable or not hasattr(expr, 'args_cnc'): args = expr.args newargs = tuple([do(i) for i in args]) if newargs == args: return expr return expr.func(*newargs) if isinstance(expr, (Sum, Integral)): return _factor_sum_int(expr, radical=radical, clear=clear, fraction=fraction, sign=sign) cont, p = expr.as_content_primitive(radical=radical, clear=clear) if p.is_Add: list_args = [do(a) for a in Add.make_args(p)] # get a common negative (if there) which gcd_terms does not remove if not any(a.as_coeff_Mul()[0].extract_multiplicatively(-1) is None for a in list_args): cont = -cont list_args = [-a for a in list_args] # watch out for exp(-(x+2)) which gcd_terms will change to exp(-x-2) special = {} for i, a in enumerate(list_args): b, e = a.as_base_exp() if e.is_Mul and e != Mul(*e.args): list_args[i] = Dummy() special[list_args[i]] = a # rebuild p not worrying about the order which gcd_terms will fix p = Add._from_args(list_args) p = gcd_terms(p, isprimitive=True, clear=clear, fraction=fraction).xreplace(special) elif p.args: p = p.func( *[do(a) for a in p.args]) rv = _keep_coeff(cont, p, clear=clear, sign=sign) return rv expr = sympify(expr) return do(expr) def _mask_nc(eq, name=None): """ Return ``eq`` with non-commutative objects replaced with Dummy symbols. A dictionary that can be used to restore the original values is returned: if it is None, the expression is noncommutative and cannot be made commutative. The third value returned is a list of any non-commutative symbols that appear in the returned equation. Explanation =========== All non-commutative objects other than Symbols are replaced with a non-commutative Symbol. Identical objects will be identified by identical symbols. If there is only 1 non-commutative object in an expression it will be replaced with a commutative symbol. Otherwise, the non-commutative entities are retained and the calling routine should handle replacements in this case since some care must be taken to keep track of the ordering of symbols when they occur within Muls. Parameters ========== name : str ``name``, if given, is the name that will be used with numbered Dummy variables that will replace the non-commutative objects and is mainly used for doctesting purposes. Examples ======== >>> from sympy.physics.secondquant import Commutator, NO, F, Fd >>> from sympy import symbols >>> from sympy.core.exprtools import _mask_nc >>> from sympy.abc import x, y >>> A, B, C = symbols('A,B,C', commutative=False) One nc-symbol: >>> _mask_nc(A**2 - x**2, 'd') (_d0**2 - x**2, {_d0: A}, []) Multiple nc-symbols: >>> _mask_nc(A**2 - B**2, 'd') (A**2 - B**2, {}, [A, B]) An nc-object with nc-symbols but no others outside of it: >>> _mask_nc(1 + x*Commutator(A, B), 'd') (_d0*x + 1, {_d0: Commutator(A, B)}, []) >>> _mask_nc(NO(Fd(x)*F(y)), 'd') (_d0, {_d0: NO(CreateFermion(x)*AnnihilateFermion(y))}, []) Multiple nc-objects: >>> eq = x*Commutator(A, B) + x*Commutator(A, C)*Commutator(A, B) >>> _mask_nc(eq, 'd') (x*_d0 + x*_d1*_d0, {_d0: Commutator(A, B), _d1: Commutator(A, C)}, [_d0, _d1]) Multiple nc-objects and nc-symbols: >>> eq = A*Commutator(A, B) + B*Commutator(A, C) >>> _mask_nc(eq, 'd') (A*_d0 + B*_d1, {_d0: Commutator(A, B), _d1: Commutator(A, C)}, [_d0, _d1, A, B]) """ name = name or 'mask' # Make Dummy() append sequential numbers to the name def numbered_names(): i = 0 while True: yield name + str(i) i += 1 names = numbered_names() def Dummy(*args, **kwargs): from .symbol import Dummy return Dummy(next(names), *args, **kwargs) expr = eq if expr.is_commutative: return eq, {}, [] # identify nc-objects; symbols and other rep = [] nc_obj = set() nc_syms = set() pot = preorder_traversal(expr, keys=default_sort_key) for i, a in enumerate(pot): if any(a == r[0] for r in rep): pot.skip() elif not a.is_commutative: if a.is_symbol: nc_syms.add(a) pot.skip() elif not (a.is_Add or a.is_Mul or a.is_Pow): nc_obj.add(a) pot.skip() # If there is only one nc symbol or object, it can be factored regularly # but polys is going to complain, so replace it with a Dummy. if len(nc_obj) == 1 and not nc_syms: rep.append((nc_obj.pop(), Dummy())) elif len(nc_syms) == 1 and not nc_obj: rep.append((nc_syms.pop(), Dummy())) # Any remaining nc-objects will be replaced with an nc-Dummy and # identified as an nc-Symbol to watch out for nc_obj = sorted(nc_obj, key=default_sort_key) for n in nc_obj: nc = Dummy(commutative=False) rep.append((n, nc)) nc_syms.add(nc) expr = expr.subs(rep) nc_syms = list(nc_syms) nc_syms.sort(key=default_sort_key) return expr, {v: k for k, v in rep}, nc_syms def factor_nc(expr): """Return the factored form of ``expr`` while handling non-commutative expressions. Examples ======== >>> from sympy import factor_nc, Symbol >>> from sympy.abc import x >>> A = Symbol('A', commutative=False) >>> B = Symbol('B', commutative=False) >>> factor_nc((x**2 + 2*A*x + A**2).expand()) (x + A)**2 >>> factor_nc(((x + A)*(x + B)).expand()) (x + A)*(x + B) """ expr = sympify(expr) if not isinstance(expr, Expr) or not expr.args: return expr if not expr.is_Add: return expr.func(*[factor_nc(a) for a in expr.args]) expr = expr.func(*[expand_power_exp(i) for i in expr.args]) from sympy.polys.polytools import gcd, factor expr, rep, nc_symbols = _mask_nc(expr) if rep: return factor(expr).subs(rep) else: args = [a.args_cnc() for a in Add.make_args(expr)] c = g = l = r = S.One hit = False # find any commutative gcd term for i, a in enumerate(args): if i == 0: c = Mul._from_args(a[0]) elif a[0]: c = gcd(c, Mul._from_args(a[0])) else: c = S.One if c is not S.One: hit = True c, g = c.as_coeff_Mul() if g is not S.One: for i, (cc, _) in enumerate(args): cc = list(Mul.make_args(Mul._from_args(list(cc))/g)) args[i][0] = cc for i, (cc, _) in enumerate(args): if cc: cc[0] = cc[0]/c else: cc = [1/c] args[i][0] = cc # find any noncommutative common prefix for i, a in enumerate(args): if i == 0: n = a[1][:] else: n = common_prefix(n, a[1]) if not n: # is there a power that can be extracted? if not args[0][1]: break b, e = args[0][1][0].as_base_exp() ok = False if e.is_Integer: for t in args: if not t[1]: break bt, et = t[1][0].as_base_exp() if et.is_Integer and bt == b: e = min(e, et) else: break else: ok = hit = True l = b**e il = b**-e for _ in args: _[1][0] = il*_[1][0] break if not ok: break else: hit = True lenn = len(n) l = Mul(*n) for _ in args: _[1] = _[1][lenn:] # find any noncommutative common suffix for i, a in enumerate(args): if i == 0: n = a[1][:] else: n = common_suffix(n, a[1]) if not n: # is there a power that can be extracted? if not args[0][1]: break b, e = args[0][1][-1].as_base_exp() ok = False if e.is_Integer: for t in args: if not t[1]: break bt, et = t[1][-1].as_base_exp() if et.is_Integer and bt == b: e = min(e, et) else: break else: ok = hit = True r = b**e il = b**-e for _ in args: _[1][-1] = _[1][-1]*il break if not ok: break else: hit = True lenn = len(n) r = Mul(*n) for _ in args: _[1] = _[1][:len(_[1]) - lenn] if hit: mid = Add(*[Mul(*cc)*Mul(*nc) for cc, nc in args]) else: mid = expr from sympy.simplify.powsimp import powsimp # sort the symbols so the Dummys would appear in the same # order as the original symbols, otherwise you may introduce # a factor of -1, e.g. A**2 - B**2) -- {A:y, B:x} --> y**2 - x**2 # and the former factors into two terms, (A - B)*(A + B) while the # latter factors into 3 terms, (-1)*(x - y)*(x + y) rep1 = [(n, Dummy()) for n in sorted(nc_symbols, key=default_sort_key)] unrep1 = [(v, k) for k, v in rep1] unrep1.reverse() new_mid, r2, _ = _mask_nc(mid.subs(rep1)) new_mid = powsimp(factor(new_mid)) new_mid = new_mid.subs(r2).subs(unrep1) if new_mid.is_Pow: return _keep_coeff(c, g*l*new_mid*r) if new_mid.is_Mul: def _pemexpand(expr): "Expand with the minimal set of hints necessary to check the result." return expr.expand(deep=True, mul=True, power_exp=True, power_base=False, basic=False, multinomial=True, log=False) # XXX TODO there should be a way to inspect what order the terms # must be in and just select the plausible ordering without # checking permutations cfac = [] ncfac = [] for f in new_mid.args: if f.is_commutative: cfac.append(f) else: b, e = f.as_base_exp() if e.is_Integer: ncfac.extend([b]*e) else: ncfac.append(f) pre_mid = g*Mul(*cfac)*l target = _pemexpand(expr/c) for s in variations(ncfac, len(ncfac)): ok = pre_mid*Mul(*s)*r if _pemexpand(ok) == target: return _keep_coeff(c, ok) # mid was an Add that didn't factor successfully return _keep_coeff(c, g*l*mid*r)
ca765f9903d75aae537ba58ecfa0b3691f1cae525f71f2933f6e20cd57fe405d
from collections import defaultdict from .sympify import sympify, SympifyError from sympy.utilities.iterables import iterable, uniq __all__ = ['default_sort_key', 'ordered'] def default_sort_key(item, order=None): """Return a key that can be used for sorting. The key has the structure: (class_key, (len(args), args), exponent.sort_key(), coefficient) This key is supplied by the sort_key routine of Basic objects when ``item`` is a Basic object or an object (other than a string) that sympifies to a Basic object. Otherwise, this function produces the key. The ``order`` argument is passed along to the sort_key routine and is used to determine how the terms *within* an expression are ordered. (See examples below) ``order`` options are: 'lex', 'grlex', 'grevlex', and reversed values of the same (e.g. 'rev-lex'). The default order value is None (which translates to 'lex'). Examples ======== >>> from sympy import S, I, default_sort_key, sin, cos, sqrt >>> from sympy.core.function import UndefinedFunction >>> from sympy.abc import x The following are equivalent ways of getting the key for an object: >>> x.sort_key() == default_sort_key(x) True Here are some examples of the key that is produced: >>> default_sort_key(UndefinedFunction('f')) ((0, 0, 'UndefinedFunction'), (1, ('f',)), ((1, 0, 'Number'), (0, ()), (), 1), 1) >>> default_sort_key('1') ((0, 0, 'str'), (1, ('1',)), ((1, 0, 'Number'), (0, ()), (), 1), 1) >>> default_sort_key(S.One) ((1, 0, 'Number'), (0, ()), (), 1) >>> default_sort_key(2) ((1, 0, 'Number'), (0, ()), (), 2) While sort_key is a method only defined for SymPy objects, default_sort_key will accept anything as an argument so it is more robust as a sorting key. For the following, using key= lambda i: i.sort_key() would fail because 2 does not have a sort_key method; that's why default_sort_key is used. Note, that it also handles sympification of non-string items likes ints: >>> a = [2, I, -I] >>> sorted(a, key=default_sort_key) [2, -I, I] The returned key can be used anywhere that a key can be specified for a function, e.g. sort, min, max, etc...: >>> a.sort(key=default_sort_key); a[0] 2 >>> min(a, key=default_sort_key) 2 Notes ===== The key returned is useful for getting items into a canonical order that will be the same across platforms. It is not directly useful for sorting lists of expressions: >>> a, b = x, 1/x Since ``a`` has only 1 term, its value of sort_key is unaffected by ``order``: >>> a.sort_key() == a.sort_key('rev-lex') True If ``a`` and ``b`` are combined then the key will differ because there are terms that can be ordered: >>> eq = a + b >>> eq.sort_key() == eq.sort_key('rev-lex') False >>> eq.as_ordered_terms() [x, 1/x] >>> eq.as_ordered_terms('rev-lex') [1/x, x] But since the keys for each of these terms are independent of ``order``'s value, they do not sort differently when they appear separately in a list: >>> sorted(eq.args, key=default_sort_key) [1/x, x] >>> sorted(eq.args, key=lambda i: default_sort_key(i, order='rev-lex')) [1/x, x] The order of terms obtained when using these keys is the order that would be obtained if those terms were *factors* in a product. Although it is useful for quickly putting expressions in canonical order, it does not sort expressions based on their complexity defined by the number of operations, power of variables and others: >>> sorted([sin(x)*cos(x), sin(x)], key=default_sort_key) [sin(x)*cos(x), sin(x)] >>> sorted([x, x**2, sqrt(x), x**3], key=default_sort_key) [sqrt(x), x, x**2, x**3] See Also ======== ordered, sympy.core.expr.Expr.as_ordered_factors, sympy.core.expr.Expr.as_ordered_terms """ from .basic import Basic from .singleton import S if isinstance(item, Basic): return item.sort_key(order=order) if iterable(item, exclude=str): if isinstance(item, dict): args = item.items() unordered = True elif isinstance(item, set): args = item unordered = True else: # e.g. tuple, list args = list(item) unordered = False args = [default_sort_key(arg, order=order) for arg in args] if unordered: # e.g. dict, set args = sorted(args) cls_index, args = 10, (len(args), tuple(args)) else: if not isinstance(item, str): try: item = sympify(item, strict=True) except SympifyError: # e.g. lambda x: x pass else: if isinstance(item, Basic): # e.g int -> Integer return default_sort_key(item) # e.g. UndefinedFunction # e.g. str cls_index, args = 0, (1, (str(item),)) return (cls_index, 0, item.__class__.__name__ ), args, S.One.sort_key(), S.One def _node_count(e): # this not only counts nodes, it affirms that the # args are Basic (i.e. have an args property). If # some object has a non-Basic arg, it needs to be # fixed since it is intended that all Basic args # are of Basic type (though this is not easy to enforce). if e.is_Float: return 0.5 return 1 + sum(map(_node_count, e.args)) def _nodes(e): """ A helper for ordered() which returns the node count of ``e`` which for Basic objects is the number of Basic nodes in the expression tree but for other objects is 1 (unless the object is an iterable or dict for which the sum of nodes is returned). """ from .basic import Basic from .function import Derivative if isinstance(e, Basic): if isinstance(e, Derivative): return _nodes(e.expr) + sum(i[1] if i[1].is_Number else _nodes(i[1]) for i in e.variable_count) return _node_count(e) elif iterable(e): return 1 + sum(_nodes(ei) for ei in e) elif isinstance(e, dict): return 1 + sum(_nodes(k) + _nodes(v) for k, v in e.items()) else: return 1 def ordered(seq, keys=None, default=True, warn=False): """Return an iterator of the seq where keys are used to break ties in a conservative fashion: if, after applying a key, there are no ties then no other keys will be computed. Two default keys will be applied if 1) keys are not provided or 2) the given keys do not resolve all ties (but only if ``default`` is True). The two keys are ``_nodes`` (which places smaller expressions before large) and ``default_sort_key`` which (if the ``sort_key`` for an object is defined properly) should resolve any ties. If ``warn`` is True then an error will be raised if there were no keys remaining to break ties. This can be used if it was expected that there should be no ties between items that are not identical. Examples ======== >>> from sympy import ordered, count_ops >>> from sympy.abc import x, y The count_ops is not sufficient to break ties in this list and the first two items appear in their original order (i.e. the sorting is stable): >>> list(ordered([y + 2, x + 2, x**2 + y + 3], ... count_ops, default=False, warn=False)) ... [y + 2, x + 2, x**2 + y + 3] The default_sort_key allows the tie to be broken: >>> list(ordered([y + 2, x + 2, x**2 + y + 3])) ... [x + 2, y + 2, x**2 + y + 3] Here, sequences are sorted by length, then sum: >>> seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]], [ ... lambda x: len(x), ... lambda x: sum(x)]] ... >>> list(ordered(seq, keys, default=False, warn=False)) [[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]] If ``warn`` is True, an error will be raised if there were not enough keys to break ties: >>> list(ordered(seq, keys, default=False, warn=True)) Traceback (most recent call last): ... ValueError: not enough keys to break ties Notes ===== The decorated sort is one of the fastest ways to sort a sequence for which special item comparison is desired: the sequence is decorated, sorted on the basis of the decoration (e.g. making all letters lower case) and then undecorated. If one wants to break ties for items that have the same decorated value, a second key can be used. But if the second key is expensive to compute then it is inefficient to decorate all items with both keys: only those items having identical first key values need to be decorated. This function applies keys successively only when needed to break ties. By yielding an iterator, use of the tie-breaker is delayed as long as possible. This function is best used in cases when use of the first key is expected to be a good hashing function; if there are no unique hashes from application of a key, then that key should not have been used. The exception, however, is that even if there are many collisions, if the first group is small and one does not need to process all items in the list then time will not be wasted sorting what one was not interested in. For example, if one were looking for the minimum in a list and there were several criteria used to define the sort order, then this function would be good at returning that quickly if the first group of candidates is small relative to the number of items being processed. """ d = defaultdict(list) if keys: if isinstance(keys, (list, tuple)): keys = list(keys) f = keys.pop(0) else: f = keys keys = [] for a in seq: d[f(a)].append(a) else: if not default: raise ValueError('if default=False then keys must be provided') d[None].extend(seq) for k, value in sorted(d.items()): if len(value) > 1: if keys: value = ordered(value, keys, default, warn) elif default: value = ordered(value, (_nodes, default_sort_key,), default=False, warn=warn) elif warn: u = list(uniq(value)) if len(u) > 1: raise ValueError( 'not enough keys to break ties: %s' % u) yield from value
171e23f18f6e283cc79072f311f1354eb3505aa4f2910885066a987d27bb7805
""" The core's core. """ # used for canonical ordering of symbolic sequences # via __cmp__ method: # FIXME this is *so* irrelevant and outdated! ordering_of_classes = [ # singleton numbers 'Zero', 'One', 'Half', 'Infinity', 'NaN', 'NegativeOne', 'NegativeInfinity', # numbers 'Integer', 'Rational', 'Float', # singleton symbols 'Exp1', 'Pi', 'ImaginaryUnit', # symbols 'Symbol', 'Wild', 'Temporary', # arithmetic operations 'Pow', 'Mul', 'Add', # function values 'Derivative', 'Integral', # defined singleton functions 'Abs', 'Sign', 'Sqrt', 'Floor', 'Ceiling', 'Re', 'Im', 'Arg', 'Conjugate', 'Exp', 'Log', 'Sin', 'Cos', 'Tan', 'Cot', 'ASin', 'ACos', 'ATan', 'ACot', 'Sinh', 'Cosh', 'Tanh', 'Coth', 'ASinh', 'ACosh', 'ATanh', 'ACoth', 'RisingFactorial', 'FallingFactorial', 'factorial', 'binomial', 'Gamma', 'LowerGamma', 'UpperGamma', 'PolyGamma', 'Erf', # special polynomials 'Chebyshev', 'Chebyshev2', # undefined functions 'Function', 'WildFunction', # anonymous functions 'Lambda', # Landau O symbol 'Order', # relational operations 'Equality', 'Unequality', 'StrictGreaterThan', 'StrictLessThan', 'GreaterThan', 'LessThan', ] class Registry: """ Base class for registry objects. Registries map a name to an object using attribute notation. Registry classes behave singletonically: all their instances share the same state, which is stored in the class object. All subclasses should set `__slots__ = ()`. """ __slots__ = () def __setattr__(self, name, obj): setattr(self.__class__, name, obj) def __delattr__(self, name): delattr(self.__class__, name) class BasicMeta(type): def __init__(cls, *args, **kws): cls.__sympy__ = property(lambda self: True) def __cmp__(cls, other): # If the other object is not a Basic subclass, then we are not equal to # it. if not isinstance(other, BasicMeta): return -1 n1 = cls.__name__ n2 = other.__name__ if n1 == n2: return 0 UNKNOWN = len(ordering_of_classes) + 1 try: i1 = ordering_of_classes.index(n1) except ValueError: i1 = UNKNOWN try: i2 = ordering_of_classes.index(n2) except ValueError: i2 = UNKNOWN if i1 == UNKNOWN and i2 == UNKNOWN: return (n1 > n2) - (n1 < n2) return (i1 > i2) - (i1 < i2) def __lt__(cls, other): if cls.__cmp__(other) == -1: return True return False def __gt__(cls, other): if cls.__cmp__(other) == 1: return True return False
b8561692c5cc0349df9c842e584be1606983ba1d77e73a3528714d6c8c305baa
""" This module contains the machinery handling assumptions. Do also consider the guide :ref:`assumptions-guide`. All symbolic objects have assumption attributes that can be accessed via ``.is_<assumption name>`` attribute. Assumptions determine certain properties of symbolic objects and can have 3 possible values: ``True``, ``False``, ``None``. ``True`` is returned if the object has the property and ``False`` is returned if it does not or cannot (i.e. does not make sense): >>> from sympy import I >>> I.is_algebraic True >>> I.is_real False >>> I.is_prime False When the property cannot be determined (or when a method is not implemented) ``None`` will be returned. For example, a generic symbol, ``x``, may or may not be positive so a value of ``None`` is returned for ``x.is_positive``. By default, all symbolic values are in the largest set in the given context without specifying the property. For example, a symbol that has a property being integer, is also real, complex, etc. Here follows a list of possible assumption names: .. glossary:: commutative object commutes with any other object with respect to multiplication operation. See [12]_. complex object can have only values from the set of complex numbers. See [13]_. imaginary object value is a number that can be written as a real number multiplied by the imaginary unit ``I``. See [3]_. Please note that ``0`` is not considered to be an imaginary number, see `issue #7649 <https://github.com/sympy/sympy/issues/7649>`_. real object can have only values from the set of real numbers. extended_real object can have only values from the set of real numbers, ``oo`` and ``-oo``. integer object can have only values from the set of integers. odd even object can have only values from the set of odd (even) integers [2]_. prime object is a natural number greater than 1 that has no positive divisors other than 1 and itself. See [6]_. composite object is a positive integer that has at least one positive divisor other than 1 or the number itself. See [4]_. zero object has the value of 0. nonzero object is a real number that is not zero. rational object can have only values from the set of rationals. algebraic object can have only values from the set of algebraic numbers [11]_. transcendental object can have only values from the set of transcendental numbers [10]_. irrational object value cannot be represented exactly by :class:`~.Rational`, see [5]_. finite infinite object absolute value is bounded (arbitrarily large). See [7]_, [8]_, [9]_. negative nonnegative object can have only negative (nonnegative) values [1]_. positive nonpositive object can have only positive (nonpositive) values. extended_negative extended_nonnegative extended_positive extended_nonpositive extended_nonzero as without the extended part, but also including infinity with corresponding sign, e.g., extended_positive includes ``oo`` hermitian antihermitian object belongs to the field of Hermitian (antihermitian) operators. Examples ======== >>> from sympy import Symbol >>> x = Symbol('x', real=True); x x >>> x.is_real True >>> x.is_complex True See Also ======== .. seealso:: :py:class:`sympy.core.numbers.ImaginaryUnit` :py:class:`sympy.core.numbers.Zero` :py:class:`sympy.core.numbers.One` :py:class:`sympy.core.numbers.Infinity` :py:class:`sympy.core.numbers.NegativeInfinity` :py:class:`sympy.core.numbers.ComplexInfinity` Notes ===== The fully-resolved assumptions for any SymPy expression can be obtained as follows: >>> from sympy.core.assumptions import assumptions >>> x = Symbol('x',positive=True) >>> assumptions(x + I) {'commutative': True, 'complex': True, 'composite': False, 'even': False, 'extended_negative': False, 'extended_nonnegative': False, 'extended_nonpositive': False, 'extended_nonzero': False, 'extended_positive': False, 'extended_real': False, 'finite': True, 'imaginary': False, 'infinite': False, 'integer': False, 'irrational': False, 'negative': False, 'noninteger': False, 'nonnegative': False, 'nonpositive': False, 'nonzero': False, 'odd': False, 'positive': False, 'prime': False, 'rational': False, 'real': False, 'zero': False} Developers Notes ================ The current (and possibly incomplete) values are stored in the ``obj._assumptions dictionary``; queries to getter methods (with property decorators) or attributes of objects/classes will return values and update the dictionary. >>> eq = x**2 + I >>> eq._assumptions {} >>> eq.is_finite True >>> eq._assumptions {'finite': True, 'infinite': False} For a :class:`~.Symbol`, there are two locations for assumptions that may be of interest. The ``assumptions0`` attribute gives the full set of assumptions derived from a given set of initial assumptions. The latter assumptions are stored as ``Symbol._assumptions.generator`` >>> Symbol('x', prime=True, even=True)._assumptions.generator {'even': True, 'prime': True} The ``generator`` is not necessarily canonical nor is it filtered in any way: it records the assumptions used to instantiate a Symbol and (for storage purposes) represents a more compact representation of the assumptions needed to recreate the full set in ``Symbol.assumptions0``. References ========== .. [1] https://en.wikipedia.org/wiki/Negative_number .. [2] https://en.wikipedia.org/wiki/Parity_%28mathematics%29 .. [3] https://en.wikipedia.org/wiki/Imaginary_number .. [4] https://en.wikipedia.org/wiki/Composite_number .. [5] https://en.wikipedia.org/wiki/Irrational_number .. [6] https://en.wikipedia.org/wiki/Prime_number .. [7] https://en.wikipedia.org/wiki/Finite .. [8] https://docs.python.org/3/library/math.html#math.isfinite .. [9] http://docs.scipy.org/doc/numpy/reference/generated/numpy.isfinite.html .. [10] https://en.wikipedia.org/wiki/Transcendental_number .. [11] https://en.wikipedia.org/wiki/Algebraic_number .. [12] https://en.wikipedia.org/wiki/Commutative_property .. [13] https://en.wikipedia.org/wiki/Complex_number """ from .facts import FactRules, FactKB from .core import BasicMeta from .sympify import sympify from sympy.core.random import _assumptions_shuffle as shuffle from sympy.core.assumptions_generated import generated_assumptions as _assumptions def _load_pre_generated_assumption_rules(): """ Load the assumption rules from pre-generated data To update the pre-generated data, see :method::`_generate_assumption_rules` """ _assume_rules=FactRules._from_python(_assumptions) return _assume_rules def _generate_assumption_rules(): """ Generate the default assumption rules This method should only be called to update the pre-generated assumption rules. To update the pre-generated assumptions run: bin/ask_update.py """ _assume_rules = FactRules([ 'integer -> rational', 'rational -> real', 'rational -> algebraic', 'algebraic -> complex', 'transcendental == complex & !algebraic', 'real -> hermitian', 'imaginary -> complex', 'imaginary -> antihermitian', 'extended_real -> commutative', 'complex -> commutative', 'complex -> finite', 'odd == integer & !even', 'even == integer & !odd', 'real -> complex', 'extended_real -> real | infinite', 'real == extended_real & finite', 'extended_real == extended_negative | zero | extended_positive', 'extended_negative == extended_nonpositive & extended_nonzero', 'extended_positive == extended_nonnegative & extended_nonzero', 'extended_nonpositive == extended_real & !extended_positive', 'extended_nonnegative == extended_real & !extended_negative', 'real == negative | zero | positive', 'negative == nonpositive & nonzero', 'positive == nonnegative & nonzero', 'nonpositive == real & !positive', 'nonnegative == real & !negative', 'positive == extended_positive & finite', 'negative == extended_negative & finite', 'nonpositive == extended_nonpositive & finite', 'nonnegative == extended_nonnegative & finite', 'nonzero == extended_nonzero & finite', 'zero -> even & finite', 'zero == extended_nonnegative & extended_nonpositive', 'zero == nonnegative & nonpositive', 'nonzero -> real', 'prime -> integer & positive', 'composite -> integer & positive & !prime', '!composite -> !positive | !even | prime', 'irrational == real & !rational', 'imaginary -> !extended_real', 'infinite == !finite', 'noninteger == extended_real & !integer', 'extended_nonzero == extended_real & !zero', ]) return _assume_rules _assume_rules = _load_pre_generated_assumption_rules() _assume_defined = _assume_rules.defined_facts.copy() _assume_defined.add('polar') _assume_defined = frozenset(_assume_defined) def assumptions(expr, _check=None): """return the T/F assumptions of ``expr``""" n = sympify(expr) if n.is_Symbol: rv = n.assumptions0 # are any important ones missing? if _check is not None: rv = {k: rv[k] for k in set(rv) & set(_check)} return rv rv = {} for k in _assume_defined if _check is None else _check: v = getattr(n, 'is_{}'.format(k)) if v is not None: rv[k] = v return rv def common_assumptions(exprs, check=None): """return those assumptions which have the same True or False value for all the given expressions. Examples ======== >>> from sympy.core import common_assumptions >>> from sympy import oo, pi, sqrt >>> common_assumptions([-4, 0, sqrt(2), 2, pi, oo]) {'commutative': True, 'composite': False, 'extended_real': True, 'imaginary': False, 'odd': False} By default, all assumptions are tested; pass an iterable of the assumptions to limit those that are reported: >>> common_assumptions([0, 1, 2], ['positive', 'integer']) {'integer': True} """ check = _assume_defined if check is None else set(check) if not check or not exprs: return {} # get all assumptions for each assume = [assumptions(i, _check=check) for i in sympify(exprs)] # focus on those of interest that are True for i, e in enumerate(assume): assume[i] = {k: e[k] for k in set(e) & check} # what assumptions are in common? common = set.intersection(*[set(i) for i in assume]) # which ones hold the same value a = assume[0] return {k: a[k] for k in common if all(a[k] == b[k] for b in assume)} def failing_assumptions(expr, **assumptions): """ Return a dictionary containing assumptions with values not matching those of the passed assumptions. Examples ======== >>> from sympy import failing_assumptions, Symbol >>> x = Symbol('x', positive=True) >>> y = Symbol('y') >>> failing_assumptions(6*x + y, positive=True) {'positive': None} >>> failing_assumptions(x**2 - 1, positive=True) {'positive': None} If *expr* satisfies all of the assumptions, an empty dictionary is returned. >>> failing_assumptions(x**2, positive=True) {} """ expr = sympify(expr) failed = {} for k in assumptions: test = getattr(expr, 'is_%s' % k, None) if test is not assumptions[k]: failed[k] = test return failed # {} or {assumption: value != desired} def check_assumptions(expr, against=None, **assume): """ Checks whether assumptions of ``expr`` match the T/F assumptions given (or possessed by ``against``). True is returned if all assumptions match; False is returned if there is a mismatch and the assumption in ``expr`` is not None; else None is returned. Explanation =========== *assume* is a dict of assumptions with True or False values Examples ======== >>> from sympy import Symbol, pi, I, exp, check_assumptions >>> check_assumptions(-5, integer=True) True >>> check_assumptions(pi, real=True, integer=False) True >>> check_assumptions(pi, negative=True) False >>> check_assumptions(exp(I*pi/7), real=False) True >>> x = Symbol('x', positive=True) >>> check_assumptions(2*x + 1, positive=True) True >>> check_assumptions(-2*x - 5, positive=True) False To check assumptions of *expr* against another variable or expression, pass the expression or variable as ``against``. >>> check_assumptions(2*x + 1, x) True To see if a number matches the assumptions of an expression, pass the number as the first argument, else its specific assumptions may not have a non-None value in the expression: >>> check_assumptions(x, 3) >>> check_assumptions(3, x) True ``None`` is returned if ``check_assumptions()`` could not conclude. >>> check_assumptions(2*x - 1, x) >>> z = Symbol('z') >>> check_assumptions(z, real=True) See Also ======== failing_assumptions """ expr = sympify(expr) if against is not None: if assume: raise ValueError( 'Expecting `against` or `assume`, not both.') assume = assumptions(against) known = True for k, v in assume.items(): if v is None: continue e = getattr(expr, 'is_' + k, None) if e is None: known = None elif v != e: return False return known class StdFactKB(FactKB): """A FactKB specialized for the built-in rules This is the only kind of FactKB that Basic objects should use. """ def __init__(self, facts=None): super().__init__(_assume_rules) # save a copy of the facts dict if not facts: self._generator = {} elif not isinstance(facts, FactKB): self._generator = facts.copy() else: self._generator = facts.generator if facts: self.deduce_all_facts(facts) def copy(self): return self.__class__(self) @property def generator(self): return self._generator.copy() def as_property(fact): """Convert a fact name to the name of the corresponding property""" return 'is_%s' % fact def make_property(fact): """Create the automagic property corresponding to a fact.""" def getit(self): try: return self._assumptions[fact] except KeyError: if self._assumptions is self.default_assumptions: self._assumptions = self.default_assumptions.copy() return _ask(fact, self) getit.func_name = as_property(fact) return property(getit) def _ask(fact, obj): """ Find the truth value for a property of an object. This function is called when a request is made to see what a fact value is. For this we use several techniques: First, the fact-evaluation function is tried, if it exists (for example _eval_is_integer). Then we try related facts. For example rational --> integer another example is joined rule: integer & !odd --> even so in the latter case if we are looking at what 'even' value is, 'integer' and 'odd' facts will be asked. In all cases, when we settle on some fact value, its implications are deduced, and the result is cached in ._assumptions. """ # FactKB which is dict-like and maps facts to their known values: assumptions = obj._assumptions # A dict that maps facts to their handlers: handler_map = obj._prop_handler # This is our queue of facts to check: facts_to_check = [fact] facts_queued = {fact} # Loop over the queue as it extends for fact_i in facts_to_check: # If fact_i has already been determined then we don't need to rerun the # handler. There is a potential race condition for multithreaded code # though because it's possible that fact_i was checked in another # thread. The main logic of the loop below would potentially skip # checking assumptions[fact] in this case so we check it once after the # loop to be sure. if fact_i in assumptions: continue # Now we call the associated handler for fact_i if it exists. fact_i_value = None handler_i = handler_map.get(fact_i) if handler_i is not None: fact_i_value = handler_i(obj) # If we get a new value for fact_i then we should update our knowledge # of fact_i as well as any related facts that can be inferred using the # inference rules connecting the fact_i and any other fact values that # are already known. if fact_i_value is not None: assumptions.deduce_all_facts(((fact_i, fact_i_value),)) # Usually if assumptions[fact] is now not None then that is because of # the call to deduce_all_facts above. The handler for fact_i returned # True or False and knowing fact_i (which is equal to fact in the first # iteration) implies knowing a value for fact. It is also possible # though that independent code e.g. called indirectly by the handler or # called in another thread in a multithreaded context might have # resulted in assumptions[fact] being set. Either way we return it. fact_value = assumptions.get(fact) if fact_value is not None: return fact_value # Extend the queue with other facts that might determine fact_i. Here # we randomise the order of the facts that are checked. This should not # lead to any non-determinism if all handlers are logically consistent # with the inference rules for the facts. Non-deterministic assumptions # queries can result from bugs in the handlers that are exposed by this # call to shuffle. These are pushed to the back of the queue meaning # that the inference graph is traversed in breadth-first order. new_facts_to_check = list(_assume_rules.prereq[fact_i] - facts_queued) shuffle(new_facts_to_check) facts_to_check.extend(new_facts_to_check) facts_queued.update(new_facts_to_check) # The above loop should be able to handle everything fine in a # single-threaded context but in multithreaded code it is possible that # this thread skipped computing a particular fact that was computed in # another thread (due to the continue). In that case it is possible that # fact was inferred and is now stored in the assumptions dict but it wasn't # checked for in the body of the loop. This is an obscure case but to make # sure we catch it we check once here at the end of the loop. if fact in assumptions: return assumptions[fact] # This query can not be answered. It's possible that e.g. another thread # has already stored None for fact but assumptions._tell does not mind if # we call _tell twice setting the same value. If this raises # InconsistentAssumptions then it probably means that another thread # attempted to compute this and got a value of True or False rather than # None. In that case there must be a bug in at least one of the handlers. # If the handlers are all deterministic and are consistent with the # inference rules then the same value should be computed for fact in all # threads. assumptions._tell(fact, None) return None class ManagedProperties(BasicMeta): """Metaclass for classes with old-style assumptions""" def __init__(cls, *args, **kws): BasicMeta.__init__(cls, *args, **kws) local_defs = {} for k in _assume_defined: attrname = as_property(k) v = cls.__dict__.get(attrname, '') if isinstance(v, (bool, int, type(None))): if v is not None: v = bool(v) local_defs[k] = v defs = {} for base in reversed(cls.__bases__): assumptions = getattr(base, '_explicit_class_assumptions', None) if assumptions is not None: defs.update(assumptions) defs.update(local_defs) cls._explicit_class_assumptions = defs cls.default_assumptions = StdFactKB(defs) cls._prop_handler = {} for k in _assume_defined: eval_is_meth = getattr(cls, '_eval_is_%s' % k, None) if eval_is_meth is not None: cls._prop_handler[k] = eval_is_meth # Put definite results directly into the class dict, for speed for k, v in cls.default_assumptions.items(): setattr(cls, as_property(k), v) # protection e.g. for Integer.is_even=F <- (Rational.is_integer=F) derived_from_bases = set() for base in cls.__bases__: default_assumptions = getattr(base, 'default_assumptions', None) # is an assumption-aware class if default_assumptions is not None: derived_from_bases.update(default_assumptions) for fact in derived_from_bases - set(cls.default_assumptions): pname = as_property(fact) if pname not in cls.__dict__: setattr(cls, pname, make_property(fact)) # Finally, add any missing automagic property (e.g. for Basic) for fact in _assume_defined: pname = as_property(fact) if not hasattr(cls, pname): setattr(cls, pname, make_property(fact))
1c8be0f7452f531d190b9d964c03b019c97fd7ee6f62104bc2ac401a13dafccd
""" There are three types of functions implemented in SymPy: 1) defined functions (in the sense that they can be evaluated) like exp or sin; they have a name and a body: f = exp 2) undefined function which have a name but no body. Undefined functions can be defined using a Function class as follows: f = Function('f') (the result will be a Function instance) 3) anonymous function (or lambda function) which have a body (defined with dummy variables) but have no name: f = Lambda(x, exp(x)*x) f = Lambda((x, y), exp(x)*y) The fourth type of functions are composites, like (sin + cos)(x); these work in SymPy core, but are not yet part of SymPy. Examples ======== >>> import sympy >>> f = sympy.Function("f") >>> from sympy.abc import x >>> f(x) f(x) >>> print(sympy.srepr(f(x).func)) Function('f') >>> f(x).args (x,) """ from __future__ import annotations from typing import Any from collections.abc import Iterable from .add import Add from .assumptions import ManagedProperties from .basic import Basic, _atomic from .cache import cacheit from .containers import Tuple, Dict from .decorators import _sympifyit from .evalf import pure_complex from .expr import Expr, AtomicExpr from .logic import fuzzy_and, fuzzy_or, fuzzy_not, FuzzyBool from .mul import Mul from .numbers import Rational, Float, Integer from .operations import LatticeOp from .parameters import global_parameters from .rules import Transform from .singleton import S from .sympify import sympify, _sympify from .sorting import default_sort_key, ordered from sympy.utilities.exceptions import (sympy_deprecation_warning, SymPyDeprecationWarning, ignore_warnings) from sympy.utilities.iterables import (has_dups, sift, iterable, is_sequence, uniq, topological_sort) from sympy.utilities.lambdify import MPMATH_TRANSLATIONS from sympy.utilities.misc import as_int, filldedent, func_name import mpmath from mpmath.libmp.libmpf import prec_to_dps import inspect from collections import Counter def _coeff_isneg(a): """Return True if the leading Number is negative. Examples ======== >>> from sympy.core.function import _coeff_isneg >>> from sympy import S, Symbol, oo, pi >>> _coeff_isneg(-3*pi) True >>> _coeff_isneg(S(3)) False >>> _coeff_isneg(-oo) True >>> _coeff_isneg(Symbol('n', negative=True)) # coeff is 1 False For matrix expressions: >>> from sympy import MatrixSymbol, sqrt >>> A = MatrixSymbol("A", 3, 3) >>> _coeff_isneg(-sqrt(2)*A) True >>> _coeff_isneg(sqrt(2)*A) False """ if a.is_MatMul: a = a.args[0] if a.is_Mul: a = a.args[0] return a.is_Number and a.is_extended_negative class PoleError(Exception): pass class ArgumentIndexError(ValueError): def __str__(self): return ("Invalid operation with argument number %s for Function %s" % (self.args[1], self.args[0])) class BadSignatureError(TypeError): '''Raised when a Lambda is created with an invalid signature''' pass class BadArgumentsError(TypeError): '''Raised when a Lambda is called with an incorrect number of arguments''' pass # Python 3 version that does not raise a Deprecation warning def arity(cls): """Return the arity of the function if it is known, else None. Explanation =========== When default values are specified for some arguments, they are optional and the arity is reported as a tuple of possible values. Examples ======== >>> from sympy import arity, log >>> arity(lambda x: x) 1 >>> arity(log) (1, 2) >>> arity(lambda *x: sum(x)) is None True """ eval_ = getattr(cls, 'eval', cls) parameters = inspect.signature(eval_).parameters.items() if [p for _, p in parameters if p.kind == p.VAR_POSITIONAL]: return p_or_k = [p for _, p in parameters if p.kind == p.POSITIONAL_OR_KEYWORD] # how many have no default and how many have a default value no, yes = map(len, sift(p_or_k, lambda p:p.default == p.empty, binary=True)) return no if not yes else tuple(range(no, no + yes + 1)) class FunctionClass(ManagedProperties): """ Base class for function classes. FunctionClass is a subclass of type. Use Function('<function name>' [ , signature ]) to create undefined function classes. """ _new = type.__new__ def __init__(cls, *args, **kwargs): # honor kwarg value or class-defined value before using # the number of arguments in the eval function (if present) nargs = kwargs.pop('nargs', cls.__dict__.get('nargs', arity(cls))) if nargs is None and 'nargs' not in cls.__dict__: for supcls in cls.__mro__: if hasattr(supcls, '_nargs'): nargs = supcls._nargs break else: continue # Canonicalize nargs here; change to set in nargs. if is_sequence(nargs): if not nargs: raise ValueError(filldedent(''' Incorrectly specified nargs as %s: if there are no arguments, it should be `nargs = 0`; if there are any number of arguments, it should be `nargs = None`''' % str(nargs))) nargs = tuple(ordered(set(nargs))) elif nargs is not None: nargs = (as_int(nargs),) cls._nargs = nargs # When __init__ is called from UndefinedFunction it is called with # just one arg but when it is called from subclassing Function it is # called with the usual (name, bases, namespace) type() signature. if len(args) == 3: namespace = args[2] if 'eval' in namespace and not isinstance(namespace['eval'], classmethod): raise TypeError("eval on Function subclasses should be a class method (defined with @classmethod)") super().__init__(*args, **kwargs) @property def __signature__(self): """ Allow Python 3's inspect.signature to give a useful signature for Function subclasses. """ # Python 3 only, but backports (like the one in IPython) still might # call this. try: from inspect import signature except ImportError: return None # TODO: Look at nargs return signature(self.eval) @property def free_symbols(self): return set() @property def xreplace(self): # Function needs args so we define a property that returns # a function that takes args...and then use that function # to return the right value return lambda rule, **_: rule.get(self, self) @property def nargs(self): """Return a set of the allowed number of arguments for the function. Examples ======== >>> from sympy import Function >>> f = Function('f') If the function can take any number of arguments, the set of whole numbers is returned: >>> Function('f').nargs Naturals0 If the function was initialized to accept one or more arguments, a corresponding set will be returned: >>> Function('f', nargs=1).nargs {1} >>> Function('f', nargs=(2, 1)).nargs {1, 2} The undefined function, after application, also has the nargs attribute; the actual number of arguments is always available by checking the ``args`` attribute: >>> f = Function('f') >>> f(1).nargs Naturals0 >>> len(f(1).args) 1 """ from sympy.sets.sets import FiniteSet # XXX it would be nice to handle this in __init__ but there are import # problems with trying to import FiniteSet there return FiniteSet(*self._nargs) if self._nargs else S.Naturals0 def _valid_nargs(self, n : int) -> bool: """ Return True if the specified integer is a valid number of arguments The number of arguments n is guaranteed to be an integer and positive """ if self._nargs: return n in self._nargs nargs = self.nargs return nargs is S.Naturals0 or n in nargs def __repr__(cls): return cls.__name__ class Application(Basic, metaclass=FunctionClass): """ Base class for applied functions. Explanation =========== Instances of Application represent the result of applying an application of any type to any object. """ is_Function = True @cacheit def __new__(cls, *args, **options): from sympy.sets.fancysets import Naturals0 from sympy.sets.sets import FiniteSet args = list(map(sympify, args)) evaluate = options.pop('evaluate', global_parameters.evaluate) # WildFunction (and anything else like it) may have nargs defined # and we throw that value away here options.pop('nargs', None) if options: raise ValueError("Unknown options: %s" % options) if evaluate: evaluated = cls.eval(*args) if evaluated is not None: return evaluated obj = super().__new__(cls, *args, **options) # make nargs uniform here sentinel = object() objnargs = getattr(obj, "nargs", sentinel) if objnargs is not sentinel: # things passing through here: # - functions subclassed from Function (e.g. myfunc(1).nargs) # - functions like cos(1).nargs # - AppliedUndef with given nargs like Function('f', nargs=1)(1).nargs # Canonicalize nargs here if is_sequence(objnargs): nargs = tuple(ordered(set(objnargs))) elif objnargs is not None: nargs = (as_int(objnargs),) else: nargs = None else: # things passing through here: # - WildFunction('f').nargs # - AppliedUndef with no nargs like Function('f')(1).nargs nargs = obj._nargs # note the underscore here # convert to FiniteSet obj.nargs = FiniteSet(*nargs) if nargs else Naturals0() return obj @classmethod def eval(cls, *args): """ Returns a canonical form of cls applied to arguments args. Explanation =========== The ``eval()`` method is called when the class ``cls`` is about to be instantiated and it should return either some simplified instance (possible of some other class), or if the class ``cls`` should be unmodified, return None. Examples of ``eval()`` for the function "sign" .. code-block:: python @classmethod def eval(cls, arg): if arg is S.NaN: return S.NaN if arg.is_zero: return S.Zero if arg.is_positive: return S.One if arg.is_negative: return S.NegativeOne if isinstance(arg, Mul): coeff, terms = arg.as_coeff_Mul(rational=True) if coeff is not S.One: return cls(coeff) * cls(terms) """ return @property def func(self): return self.__class__ def _eval_subs(self, old, new): if (old.is_Function and new.is_Function and callable(old) and callable(new) and old == self.func and len(self.args) in new.nargs): return new(*[i._subs(old, new) for i in self.args]) class Function(Application, Expr): r""" Base class for applied mathematical functions. It also serves as a constructor for undefined function classes. See the :ref:`custom-functions` guide for details on how to subclass ``Function`` and what methods can be defined. Examples ======== **Undefined Functions** To create an undefined function, pass a string of the function name to ``Function``. >>> from sympy import Function, Symbol >>> x = Symbol('x') >>> f = Function('f') >>> g = Function('g')(x) >>> f f >>> f(x) f(x) >>> g g(x) >>> f(x).diff(x) Derivative(f(x), x) >>> g.diff(x) Derivative(g(x), x) Assumptions can be passed to ``Function`` the same as with a :class:`~.Symbol`. Alternatively, you can use a ``Symbol`` with assumptions for the function name and the function will inherit the name and assumptions associated with the ``Symbol``: >>> f_real = Function('f', real=True) >>> f_real(x).is_real True >>> f_real_inherit = Function(Symbol('f', real=True)) >>> f_real_inherit(x).is_real True Note that assumptions on a function are unrelated to the assumptions on the variables it is called on. If you want to add a relationship, subclass ``Function`` and define custom assumptions handler methods. See the :ref:`custom-functions-assumptions` section of the :ref:`custom-functions` guide for more details. **Custom Function Subclasses** The :ref:`custom-functions` guide has several :ref:`custom-functions-complete-examples` of how to subclass ``Function`` to create a custom function. """ @property def _diff_wrt(self): return False @cacheit def __new__(cls, *args, **options): # Handle calls like Function('f') if cls is Function: return UndefinedFunction(*args, **options) n = len(args) if not cls._valid_nargs(n): # XXX: exception message must be in exactly this format to # make it work with NumPy's functions like vectorize(). See, # for example, https://github.com/numpy/numpy/issues/1697. # The ideal solution would be just to attach metadata to # the exception and change NumPy to take advantage of this. temp = ('%(name)s takes %(qual)s %(args)s ' 'argument%(plural)s (%(given)s given)') raise TypeError(temp % { 'name': cls, 'qual': 'exactly' if len(cls.nargs) == 1 else 'at least', 'args': min(cls.nargs), 'plural': 's'*(min(cls.nargs) != 1), 'given': n}) evaluate = options.get('evaluate', global_parameters.evaluate) result = super().__new__(cls, *args, **options) if evaluate and isinstance(result, cls) and result.args: _should_evalf = [cls._should_evalf(a) for a in result.args] pr2 = min(_should_evalf) if pr2 > 0: pr = max(_should_evalf) result = result.evalf(prec_to_dps(pr)) return _sympify(result) @classmethod def _should_evalf(cls, arg): """ Decide if the function should automatically evalf(). Explanation =========== By default (in this implementation), this happens if (and only if) the ARG is a floating point number (including complex numbers). This function is used by __new__. Returns the precision to evalf to, or -1 if it should not evalf. """ if arg.is_Float: return arg._prec if not arg.is_Add: return -1 m = pure_complex(arg) if m is None: return -1 # the elements of m are of type Number, so have a _prec return max(m[0]._prec, m[1]._prec) @classmethod def class_key(cls): from sympy.sets.fancysets import Naturals0 funcs = { 'exp': 10, 'log': 11, 'sin': 20, 'cos': 21, 'tan': 22, 'cot': 23, 'sinh': 30, 'cosh': 31, 'tanh': 32, 'coth': 33, 'conjugate': 40, 're': 41, 'im': 42, 'arg': 43, } name = cls.__name__ try: i = funcs[name] except KeyError: i = 0 if isinstance(cls.nargs, Naturals0) else 10000 return 4, i, name def _eval_evalf(self, prec): def _get_mpmath_func(fname): """Lookup mpmath function based on name""" if isinstance(self, AppliedUndef): # Shouldn't lookup in mpmath but might have ._imp_ return None if not hasattr(mpmath, fname): fname = MPMATH_TRANSLATIONS.get(fname, None) if fname is None: return None return getattr(mpmath, fname) _eval_mpmath = getattr(self, '_eval_mpmath', None) if _eval_mpmath is None: func = _get_mpmath_func(self.func.__name__) args = self.args else: func, args = _eval_mpmath() # Fall-back evaluation if func is None: imp = getattr(self, '_imp_', None) if imp is None: return None try: return Float(imp(*[i.evalf(prec) for i in self.args]), prec) except (TypeError, ValueError): return None # Convert all args to mpf or mpc # Convert the arguments to *higher* precision than requested for the # final result. # XXX + 5 is a guess, it is similar to what is used in evalf.py. Should # we be more intelligent about it? try: args = [arg._to_mpmath(prec + 5) for arg in args] def bad(m): from mpmath import mpf, mpc # the precision of an mpf value is the last element # if that is 1 (and m[1] is not 1 which would indicate a # power of 2), then the eval failed; so check that none of # the arguments failed to compute to a finite precision. # Note: An mpc value has two parts, the re and imag tuple; # check each of those parts, too. Anything else is allowed to # pass if isinstance(m, mpf): m = m._mpf_ return m[1] !=1 and m[-1] == 1 elif isinstance(m, mpc): m, n = m._mpc_ return m[1] !=1 and m[-1] == 1 and \ n[1] !=1 and n[-1] == 1 else: return False if any(bad(a) for a in args): raise ValueError # one or more args failed to compute with significance except ValueError: return with mpmath.workprec(prec): v = func(*args) return Expr._from_mpmath(v, prec) def _eval_derivative(self, s): # f(x).diff(s) -> x.diff(s) * f.fdiff(1)(s) i = 0 l = [] for a in self.args: i += 1 da = a.diff(s) if da.is_zero: continue try: df = self.fdiff(i) except ArgumentIndexError: df = Function.fdiff(self, i) l.append(df * da) return Add(*l) def _eval_is_commutative(self): return fuzzy_and(a.is_commutative for a in self.args) def _eval_is_meromorphic(self, x, a): if not self.args: return True if any(arg.has(x) for arg in self.args[1:]): return False arg = self.args[0] if not arg._eval_is_meromorphic(x, a): return None return fuzzy_not(type(self).is_singular(arg.subs(x, a))) _singularities: FuzzyBool | tuple[Expr, ...] = None @classmethod def is_singular(cls, a): """ Tests whether the argument is an essential singularity or a branch point, or the functions is non-holomorphic. """ ss = cls._singularities if ss in (True, None, False): return ss return fuzzy_or(a.is_infinite if s is S.ComplexInfinity else (a - s).is_zero for s in ss) def as_base_exp(self): """ Returns the method as the 2-tuple (base, exponent). """ return self, S.One def _eval_aseries(self, n, args0, x, logx): """ Compute an asymptotic expansion around args0, in terms of self.args. This function is only used internally by _eval_nseries and should not be called directly; derived classes can overwrite this to implement asymptotic expansions. """ raise PoleError(filldedent(''' Asymptotic expansion of %s around %s is not implemented.''' % (type(self), args0))) def _eval_nseries(self, x, n, logx, cdir=0): """ This function does compute series for multivariate functions, but the expansion is always in terms of *one* variable. Examples ======== >>> from sympy import atan2 >>> from sympy.abc import x, y >>> atan2(x, y).series(x, n=2) atan2(0, y) + x/y + O(x**2) >>> atan2(x, y).series(y, n=2) -y/x + atan2(x, 0) + O(y**2) This function also computes asymptotic expansions, if necessary and possible: >>> from sympy import loggamma >>> loggamma(1/x)._eval_nseries(x,0,None) -1/x - log(x)/x + log(x)/2 + O(1) """ from .symbol import uniquely_named_symbol from sympy.series.order import Order from sympy.sets.sets import FiniteSet args = self.args args0 = [t.limit(x, 0) for t in args] if any(t.is_finite is False for t in args0): from .numbers import oo, zoo, nan a = [t.as_leading_term(x, logx=logx) for t in args] a0 = [t.limit(x, 0) for t in a] if any(t.has(oo, -oo, zoo, nan) for t in a0): return self._eval_aseries(n, args0, x, logx) # Careful: the argument goes to oo, but only logarithmically so. We # are supposed to do a power series expansion "around the # logarithmic term". e.g. # f(1+x+log(x)) # -> f(1+logx) + x*f'(1+logx) + O(x**2) # where 'logx' is given in the argument a = [t._eval_nseries(x, n, logx) for t in args] z = [r - r0 for (r, r0) in zip(a, a0)] p = [Dummy() for _ in z] q = [] v = None for ai, zi, pi in zip(a0, z, p): if zi.has(x): if v is not None: raise NotImplementedError q.append(ai + pi) v = pi else: q.append(ai) e1 = self.func(*q) if v is None: return e1 s = e1._eval_nseries(v, n, logx) o = s.getO() s = s.removeO() s = s.subs(v, zi).expand() + Order(o.expr.subs(v, zi), x) return s if (self.func.nargs is S.Naturals0 or (self.func.nargs == FiniteSet(1) and args0[0]) or any(c > 1 for c in self.func.nargs)): e = self e1 = e.expand() if e == e1: #for example when e = sin(x+1) or e = sin(cos(x)) #let's try the general algorithm if len(e.args) == 1: # issue 14411 e = e.func(e.args[0].cancel()) term = e.subs(x, S.Zero) if term.is_finite is False or term is S.NaN: raise PoleError("Cannot expand %s around 0" % (self)) series = term fact = S.One _x = uniquely_named_symbol('xi', self) e = e.subs(x, _x) for i in range(1, n): fact *= Rational(i) e = e.diff(_x) subs = e.subs(_x, S.Zero) if subs is S.NaN: # try to evaluate a limit if we have to subs = e.limit(_x, S.Zero) if subs.is_finite is False: raise PoleError("Cannot expand %s around 0" % (self)) term = subs*(x**i)/fact term = term.expand() series += term return series + Order(x**n, x) return e1.nseries(x, n=n, logx=logx) arg = self.args[0] l = [] g = None # try to predict a number of terms needed nterms = n + 2 cf = Order(arg.as_leading_term(x), x).getn() if cf != 0: nterms = (n/cf).ceiling() for i in range(nterms): g = self.taylor_term(i, arg, g) g = g.nseries(x, n=n, logx=logx) l.append(g) return Add(*l) + Order(x**n, x) def fdiff(self, argindex=1): """ Returns the first derivative of the function. """ if not (1 <= argindex <= len(self.args)): raise ArgumentIndexError(self, argindex) ix = argindex - 1 A = self.args[ix] if A._diff_wrt: if len(self.args) == 1 or not A.is_Symbol: return _derivative_dispatch(self, A) for i, v in enumerate(self.args): if i != ix and A in v.free_symbols: # it can't be in any other argument's free symbols # issue 8510 break else: return _derivative_dispatch(self, A) # See issue 4624 and issue 4719, 5600 and 8510 D = Dummy('xi_%i' % argindex, dummy_index=hash(A)) args = self.args[:ix] + (D,) + self.args[ix + 1:] return Subs(Derivative(self.func(*args), D), D, A) def _eval_as_leading_term(self, x, logx=None, cdir=0): """Stub that should be overridden by new Functions to return the first non-zero term in a series if ever an x-dependent argument whose leading term vanishes as x -> 0 might be encountered. See, for example, cos._eval_as_leading_term. """ from sympy.series.order import Order args = [a.as_leading_term(x, logx=logx) for a in self.args] o = Order(1, x) if any(x in a.free_symbols and o.contains(a) for a in args): # Whereas x and any finite number are contained in O(1, x), # expressions like 1/x are not. If any arg simplified to a # vanishing expression as x -> 0 (like x or x**2, but not # 3, 1/x, etc...) then the _eval_as_leading_term is needed # to supply the first non-zero term of the series, # # e.g. expression leading term # ---------- ------------ # cos(1/x) cos(1/x) # cos(cos(x)) cos(1) # cos(x) 1 <- _eval_as_leading_term needed # sin(x) x <- _eval_as_leading_term needed # raise NotImplementedError( '%s has no _eval_as_leading_term routine' % self.func) else: return self.func(*args) class AppliedUndef(Function): """ Base class for expressions resulting from the application of an undefined function. """ is_number = False def __new__(cls, *args, **options): args = list(map(sympify, args)) u = [a.name for a in args if isinstance(a, UndefinedFunction)] if u: raise TypeError('Invalid argument: expecting an expression, not UndefinedFunction%s: %s' % ( 's'*(len(u) > 1), ', '.join(u))) obj = super().__new__(cls, *args, **options) return obj def _eval_as_leading_term(self, x, logx=None, cdir=0): return self @property def _diff_wrt(self): """ Allow derivatives wrt to undefined functions. Examples ======== >>> from sympy import Function, Symbol >>> f = Function('f') >>> x = Symbol('x') >>> f(x)._diff_wrt True >>> f(x).diff(x) Derivative(f(x), x) """ return True class UndefSageHelper: """ Helper to facilitate Sage conversion. """ def __get__(self, ins, typ): import sage.all as sage if ins is None: return lambda: sage.function(typ.__name__) else: args = [arg._sage_() for arg in ins.args] return lambda : sage.function(ins.__class__.__name__)(*args) _undef_sage_helper = UndefSageHelper() class UndefinedFunction(FunctionClass): """ The (meta)class of undefined functions. """ def __new__(mcl, name, bases=(AppliedUndef,), __dict__=None, **kwargs): from .symbol import _filter_assumptions # Allow Function('f', real=True) # and/or Function(Symbol('f', real=True)) assumptions, kwargs = _filter_assumptions(kwargs) if isinstance(name, Symbol): assumptions = name._merge(assumptions) name = name.name elif not isinstance(name, str): raise TypeError('expecting string or Symbol for name') else: commutative = assumptions.get('commutative', None) assumptions = Symbol(name, **assumptions).assumptions0 if commutative is None: assumptions.pop('commutative') __dict__ = __dict__ or {} # put the `is_*` for into __dict__ __dict__.update({'is_%s' % k: v for k, v in assumptions.items()}) # You can add other attributes, although they do have to be hashable # (but seriously, if you want to add anything other than assumptions, # just subclass Function) __dict__.update(kwargs) # add back the sanitized assumptions without the is_ prefix kwargs.update(assumptions) # Save these for __eq__ __dict__.update({'_kwargs': kwargs}) # do this for pickling __dict__['__module__'] = None obj = super().__new__(mcl, name, bases, __dict__) obj.name = name obj._sage_ = _undef_sage_helper return obj def __instancecheck__(cls, instance): return cls in type(instance).__mro__ _kwargs: dict[str, bool | None] = {} def __hash__(self): return hash((self.class_key(), frozenset(self._kwargs.items()))) def __eq__(self, other): return (isinstance(other, self.__class__) and self.class_key() == other.class_key() and self._kwargs == other._kwargs) def __ne__(self, other): return not self == other @property def _diff_wrt(self): return False # XXX: The type: ignore on WildFunction is because mypy complains: # # sympy/core/function.py:939: error: Cannot determine type of 'sort_key' in # base class 'Expr' # # Somehow this is because of the @cacheit decorator but it is not clear how to # fix it. class WildFunction(Function, AtomicExpr): # type: ignore """ A WildFunction function matches any function (with its arguments). Examples ======== >>> from sympy import WildFunction, Function, cos >>> from sympy.abc import x, y >>> F = WildFunction('F') >>> f = Function('f') >>> F.nargs Naturals0 >>> x.match(F) >>> F.match(F) {F_: F_} >>> f(x).match(F) {F_: f(x)} >>> cos(x).match(F) {F_: cos(x)} >>> f(x, y).match(F) {F_: f(x, y)} To match functions with a given number of arguments, set ``nargs`` to the desired value at instantiation: >>> F = WildFunction('F', nargs=2) >>> F.nargs {2} >>> f(x).match(F) >>> f(x, y).match(F) {F_: f(x, y)} To match functions with a range of arguments, set ``nargs`` to a tuple containing the desired number of arguments, e.g. if ``nargs = (1, 2)`` then functions with 1 or 2 arguments will be matched. >>> F = WildFunction('F', nargs=(1, 2)) >>> F.nargs {1, 2} >>> f(x).match(F) {F_: f(x)} >>> f(x, y).match(F) {F_: f(x, y)} >>> f(x, y, 1).match(F) """ # XXX: What is this class attribute used for? include: set[Any] = set() def __init__(cls, name, **assumptions): from sympy.sets.sets import Set, FiniteSet cls.name = name nargs = assumptions.pop('nargs', S.Naturals0) if not isinstance(nargs, Set): # Canonicalize nargs here. See also FunctionClass. if is_sequence(nargs): nargs = tuple(ordered(set(nargs))) elif nargs is not None: nargs = (as_int(nargs),) nargs = FiniteSet(*nargs) cls.nargs = nargs def matches(self, expr, repl_dict=None, old=False): if not isinstance(expr, (AppliedUndef, Function)): return None if len(expr.args) not in self.nargs: return None if repl_dict is None: repl_dict = {} else: repl_dict = repl_dict.copy() repl_dict[self] = expr return repl_dict class Derivative(Expr): """ Carries out differentiation of the given expression with respect to symbols. Examples ======== >>> from sympy import Derivative, Function, symbols, Subs >>> from sympy.abc import x, y >>> f, g = symbols('f g', cls=Function) >>> Derivative(x**2, x, evaluate=True) 2*x Denesting of derivatives retains the ordering of variables: >>> Derivative(Derivative(f(x, y), y), x) Derivative(f(x, y), y, x) Contiguously identical symbols are merged into a tuple giving the symbol and the count: >>> Derivative(f(x), x, x, y, x) Derivative(f(x), (x, 2), y, x) If the derivative cannot be performed, and evaluate is True, the order of the variables of differentiation will be made canonical: >>> Derivative(f(x, y), y, x, evaluate=True) Derivative(f(x, y), x, y) Derivatives with respect to undefined functions can be calculated: >>> Derivative(f(x)**2, f(x), evaluate=True) 2*f(x) Such derivatives will show up when the chain rule is used to evalulate a derivative: >>> f(g(x)).diff(x) Derivative(f(g(x)), g(x))*Derivative(g(x), x) Substitution is used to represent derivatives of functions with arguments that are not symbols or functions: >>> f(2*x + 3).diff(x) == 2*Subs(f(y).diff(y), y, 2*x + 3) True Notes ===== Simplification of high-order derivatives: Because there can be a significant amount of simplification that can be done when multiple differentiations are performed, results will be automatically simplified in a fairly conservative fashion unless the keyword ``simplify`` is set to False. >>> from sympy import sqrt, diff, Function, symbols >>> from sympy.abc import x, y, z >>> f, g = symbols('f,g', cls=Function) >>> e = sqrt((x + 1)**2 + x) >>> diff(e, (x, 5), simplify=False).count_ops() 136 >>> diff(e, (x, 5)).count_ops() 30 Ordering of variables: If evaluate is set to True and the expression cannot be evaluated, the list of differentiation symbols will be sorted, that is, the expression is assumed to have continuous derivatives up to the order asked. Derivative wrt non-Symbols: For the most part, one may not differentiate wrt non-symbols. For example, we do not allow differentiation wrt `x*y` because there are multiple ways of structurally defining where x*y appears in an expression: a very strict definition would make (x*y*z).diff(x*y) == 0. Derivatives wrt defined functions (like cos(x)) are not allowed, either: >>> (x*y*z).diff(x*y) Traceback (most recent call last): ... ValueError: Can't calculate derivative wrt x*y. To make it easier to work with variational calculus, however, derivatives wrt AppliedUndef and Derivatives are allowed. For example, in the Euler-Lagrange method one may write F(t, u, v) where u = f(t) and v = f'(t). These variables can be written explicitly as functions of time:: >>> from sympy.abc import t >>> F = Function('F') >>> U = f(t) >>> V = U.diff(t) The derivative wrt f(t) can be obtained directly: >>> direct = F(t, U, V).diff(U) When differentiation wrt a non-Symbol is attempted, the non-Symbol is temporarily converted to a Symbol while the differentiation is performed and the same answer is obtained: >>> indirect = F(t, U, V).subs(U, x).diff(x).subs(x, U) >>> assert direct == indirect The implication of this non-symbol replacement is that all functions are treated as independent of other functions and the symbols are independent of the functions that contain them:: >>> x.diff(f(x)) 0 >>> g(x).diff(f(x)) 0 It also means that derivatives are assumed to depend only on the variables of differentiation, not on anything contained within the expression being differentiated:: >>> F = f(x) >>> Fx = F.diff(x) >>> Fx.diff(F) # derivative depends on x, not F 0 >>> Fxx = Fx.diff(x) >>> Fxx.diff(Fx) # derivative depends on x, not Fx 0 The last example can be made explicit by showing the replacement of Fx in Fxx with y: >>> Fxx.subs(Fx, y) Derivative(y, x) Since that in itself will evaluate to zero, differentiating wrt Fx will also be zero: >>> _.doit() 0 Replacing undefined functions with concrete expressions One must be careful to replace undefined functions with expressions that contain variables consistent with the function definition and the variables of differentiation or else insconsistent result will be obtained. Consider the following example: >>> eq = f(x)*g(y) >>> eq.subs(f(x), x*y).diff(x, y).doit() y*Derivative(g(y), y) + g(y) >>> eq.diff(x, y).subs(f(x), x*y).doit() y*Derivative(g(y), y) The results differ because `f(x)` was replaced with an expression that involved both variables of differentiation. In the abstract case, differentiation of `f(x)` by `y` is 0; in the concrete case, the presence of `y` made that derivative nonvanishing and produced the extra `g(y)` term. Defining differentiation for an object An object must define ._eval_derivative(symbol) method that returns the differentiation result. This function only needs to consider the non-trivial case where expr contains symbol and it should call the diff() method internally (not _eval_derivative); Derivative should be the only one to call _eval_derivative. Any class can allow derivatives to be taken with respect to itself (while indicating its scalar nature). See the docstring of Expr._diff_wrt. See Also ======== _sort_variable_count """ is_Derivative = True @property def _diff_wrt(self): """An expression may be differentiated wrt a Derivative if it is in elementary form. Examples ======== >>> from sympy import Function, Derivative, cos >>> from sympy.abc import x >>> f = Function('f') >>> Derivative(f(x), x)._diff_wrt True >>> Derivative(cos(x), x)._diff_wrt False >>> Derivative(x + 1, x)._diff_wrt False A Derivative might be an unevaluated form of what will not be a valid variable of differentiation if evaluated. For example, >>> Derivative(f(f(x)), x).doit() Derivative(f(x), x)*Derivative(f(f(x)), f(x)) Such an expression will present the same ambiguities as arise when dealing with any other product, like ``2*x``, so ``_diff_wrt`` is False: >>> Derivative(f(f(x)), x)._diff_wrt False """ return self.expr._diff_wrt and isinstance(self.doit(), Derivative) def __new__(cls, expr, *variables, **kwargs): expr = sympify(expr) symbols_or_none = getattr(expr, "free_symbols", None) has_symbol_set = isinstance(symbols_or_none, set) if not has_symbol_set: raise ValueError(filldedent(''' Since there are no variables in the expression %s, it cannot be differentiated.''' % expr)) # determine value for variables if it wasn't given if not variables: variables = expr.free_symbols if len(variables) != 1: if expr.is_number: return S.Zero if len(variables) == 0: raise ValueError(filldedent(''' Since there are no variables in the expression, the variable(s) of differentiation must be supplied to differentiate %s''' % expr)) else: raise ValueError(filldedent(''' Since there is more than one variable in the expression, the variable(s) of differentiation must be supplied to differentiate %s''' % expr)) # Split the list of variables into a list of the variables we are diff # wrt, where each element of the list has the form (s, count) where # s is the entity to diff wrt and count is the order of the # derivative. variable_count = [] array_likes = (tuple, list, Tuple) from sympy.tensor.array import Array, NDimArray for i, v in enumerate(variables): if isinstance(v, UndefinedFunction): raise TypeError( "cannot differentiate wrt " "UndefinedFunction: %s" % v) if isinstance(v, array_likes): if len(v) == 0: # Ignore empty tuples: Derivative(expr, ... , (), ... ) continue if isinstance(v[0], array_likes): # Derive by array: Derivative(expr, ... , [[x, y, z]], ... ) if len(v) == 1: v = Array(v[0]) count = 1 else: v, count = v v = Array(v) else: v, count = v if count == 0: continue variable_count.append(Tuple(v, count)) continue v = sympify(v) if isinstance(v, Integer): if i == 0: raise ValueError("First variable cannot be a number: %i" % v) count = v prev, prevcount = variable_count[-1] if prevcount != 1: raise TypeError("tuple {} followed by number {}".format((prev, prevcount), v)) if count == 0: variable_count.pop() else: variable_count[-1] = Tuple(prev, count) else: count = 1 variable_count.append(Tuple(v, count)) # light evaluation of contiguous, identical # items: (x, 1), (x, 1) -> (x, 2) merged = [] for t in variable_count: v, c = t if c.is_negative: raise ValueError( 'order of differentiation must be nonnegative') if merged and merged[-1][0] == v: c += merged[-1][1] if not c: merged.pop() else: merged[-1] = Tuple(v, c) else: merged.append(t) variable_count = merged # sanity check of variables of differentation; we waited # until the counts were computed since some variables may # have been removed because the count was 0 for v, c in variable_count: # v must have _diff_wrt True if not v._diff_wrt: __ = '' # filler to make error message neater raise ValueError(filldedent(''' Can't calculate derivative wrt %s.%s''' % (v, __))) # We make a special case for 0th derivative, because there is no # good way to unambiguously print this. if len(variable_count) == 0: return expr evaluate = kwargs.get('evaluate', False) if evaluate: if isinstance(expr, Derivative): expr = expr.canonical variable_count = [ (v.canonical if isinstance(v, Derivative) else v, c) for v, c in variable_count] # Look for a quick exit if there are symbols that don't appear in # expression at all. Note, this cannot check non-symbols like # Derivatives as those can be created by intermediate # derivatives. zero = False free = expr.free_symbols from sympy.matrices.expressions.matexpr import MatrixExpr for v, c in variable_count: vfree = v.free_symbols if c.is_positive and vfree: if isinstance(v, AppliedUndef): # these match exactly since # x.diff(f(x)) == g(x).diff(f(x)) == 0 # and are not created by differentiation D = Dummy() if not expr.xreplace({v: D}).has(D): zero = True break elif isinstance(v, MatrixExpr): zero = False break elif isinstance(v, Symbol) and v not in free: zero = True break else: if not free & vfree: # e.g. v is IndexedBase or Matrix zero = True break if zero: return cls._get_zero_with_shape_like(expr) # make the order of symbols canonical #TODO: check if assumption of discontinuous derivatives exist variable_count = cls._sort_variable_count(variable_count) # denest if isinstance(expr, Derivative): variable_count = list(expr.variable_count) + variable_count expr = expr.expr return _derivative_dispatch(expr, *variable_count, **kwargs) # we return here if evaluate is False or if there is no # _eval_derivative method if not evaluate or not hasattr(expr, '_eval_derivative'): # return an unevaluated Derivative if evaluate and variable_count == [(expr, 1)] and expr.is_scalar: # special hack providing evaluation for classes # that have defined is_scalar=True but have no # _eval_derivative defined return S.One return Expr.__new__(cls, expr, *variable_count) # evaluate the derivative by calling _eval_derivative method # of expr for each variable # ------------------------------------------------------------- nderivs = 0 # how many derivatives were performed unhandled = [] from sympy.matrices.common import MatrixCommon for i, (v, count) in enumerate(variable_count): old_expr = expr old_v = None is_symbol = v.is_symbol or isinstance(v, (Iterable, Tuple, MatrixCommon, NDimArray)) if not is_symbol: old_v = v v = Dummy('xi') expr = expr.xreplace({old_v: v}) # Derivatives and UndefinedFunctions are independent # of all others clashing = not (isinstance(old_v, Derivative) or \ isinstance(old_v, AppliedUndef)) if v not in expr.free_symbols and not clashing: return expr.diff(v) # expr's version of 0 if not old_v.is_scalar and not hasattr( old_v, '_eval_derivative'): # special hack providing evaluation for classes # that have defined is_scalar=True but have no # _eval_derivative defined expr *= old_v.diff(old_v) obj = cls._dispatch_eval_derivative_n_times(expr, v, count) if obj is not None and obj.is_zero: return obj nderivs += count if old_v is not None: if obj is not None: # remove the dummy that was used obj = obj.subs(v, old_v) # restore expr expr = old_expr if obj is None: # we've already checked for quick-exit conditions # that give 0 so the remaining variables # are contained in the expression but the expression # did not compute a derivative so we stop taking # derivatives unhandled = variable_count[i:] break expr = obj # what we have so far can be made canonical expr = expr.replace( lambda x: isinstance(x, Derivative), lambda x: x.canonical) if unhandled: if isinstance(expr, Derivative): unhandled = list(expr.variable_count) + unhandled expr = expr.expr expr = Expr.__new__(cls, expr, *unhandled) if (nderivs > 1) == True and kwargs.get('simplify', True): from .exprtools import factor_terms from sympy.simplify.simplify import signsimp expr = factor_terms(signsimp(expr)) return expr @property def canonical(cls): return cls.func(cls.expr, *Derivative._sort_variable_count(cls.variable_count)) @classmethod def _sort_variable_count(cls, vc): """ Sort (variable, count) pairs into canonical order while retaining order of variables that do not commute during differentiation: * symbols and functions commute with each other * derivatives commute with each other * a derivative does not commute with anything it contains * any other object is not allowed to commute if it has free symbols in common with another object Examples ======== >>> from sympy import Derivative, Function, symbols >>> vsort = Derivative._sort_variable_count >>> x, y, z = symbols('x y z') >>> f, g, h = symbols('f g h', cls=Function) Contiguous items are collapsed into one pair: >>> vsort([(x, 1), (x, 1)]) [(x, 2)] >>> vsort([(y, 1), (f(x), 1), (y, 1), (f(x), 1)]) [(y, 2), (f(x), 2)] Ordering is canonical. >>> def vsort0(*v): ... # docstring helper to ... # change vi -> (vi, 0), sort, and return vi vals ... return [i[0] for i in vsort([(i, 0) for i in v])] >>> vsort0(y, x) [x, y] >>> vsort0(g(y), g(x), f(y)) [f(y), g(x), g(y)] Symbols are sorted as far to the left as possible but never move to the left of a derivative having the same symbol in its variables; the same applies to AppliedUndef which are always sorted after Symbols: >>> dfx = f(x).diff(x) >>> assert vsort0(dfx, y) == [y, dfx] >>> assert vsort0(dfx, x) == [dfx, x] """ if not vc: return [] vc = list(vc) if len(vc) == 1: return [Tuple(*vc[0])] V = list(range(len(vc))) E = [] v = lambda i: vc[i][0] D = Dummy() def _block(d, v, wrt=False): # return True if v should not come before d else False if d == v: return wrt if d.is_Symbol: return False if isinstance(d, Derivative): # a derivative blocks if any of it's variables contain # v; the wrt flag will return True for an exact match # and will cause an AppliedUndef to block if v is in # the arguments if any(_block(k, v, wrt=True) for k in d._wrt_variables): return True return False if not wrt and isinstance(d, AppliedUndef): return False if v.is_Symbol: return v in d.free_symbols if isinstance(v, AppliedUndef): return _block(d.xreplace({v: D}), D) return d.free_symbols & v.free_symbols for i in range(len(vc)): for j in range(i): if _block(v(j), v(i)): E.append((j,i)) # this is the default ordering to use in case of ties O = dict(zip(ordered(uniq([i for i, c in vc])), range(len(vc)))) ix = topological_sort((V, E), key=lambda i: O[v(i)]) # merge counts of contiguously identical items merged = [] for v, c in [vc[i] for i in ix]: if merged and merged[-1][0] == v: merged[-1][1] += c else: merged.append([v, c]) return [Tuple(*i) for i in merged] def _eval_is_commutative(self): return self.expr.is_commutative def _eval_derivative(self, v): # If v (the variable of differentiation) is not in # self.variables, we might be able to take the derivative. if v not in self._wrt_variables: dedv = self.expr.diff(v) if isinstance(dedv, Derivative): return dedv.func(dedv.expr, *(self.variable_count + dedv.variable_count)) # dedv (d(self.expr)/dv) could have simplified things such that the # derivative wrt things in self.variables can now be done. Thus, # we set evaluate=True to see if there are any other derivatives # that can be done. The most common case is when dedv is a simple # number so that the derivative wrt anything else will vanish. return self.func(dedv, *self.variables, evaluate=True) # In this case v was in self.variables so the derivative wrt v has # already been attempted and was not computed, either because it # couldn't be or evaluate=False originally. variable_count = list(self.variable_count) variable_count.append((v, 1)) return self.func(self.expr, *variable_count, evaluate=False) def doit(self, **hints): expr = self.expr if hints.get('deep', True): expr = expr.doit(**hints) hints['evaluate'] = True rv = self.func(expr, *self.variable_count, **hints) if rv!= self and rv.has(Derivative): rv = rv.doit(**hints) return rv @_sympifyit('z0', NotImplementedError) def doit_numerically(self, z0): """ Evaluate the derivative at z numerically. When we can represent derivatives at a point, this should be folded into the normal evalf. For now, we need a special method. """ if len(self.free_symbols) != 1 or len(self.variables) != 1: raise NotImplementedError('partials and higher order derivatives') z = list(self.free_symbols)[0] def eval(x): f0 = self.expr.subs(z, Expr._from_mpmath(x, prec=mpmath.mp.prec)) f0 = f0.evalf(prec_to_dps(mpmath.mp.prec)) return f0._to_mpmath(mpmath.mp.prec) return Expr._from_mpmath(mpmath.diff(eval, z0._to_mpmath(mpmath.mp.prec)), mpmath.mp.prec) @property def expr(self): return self._args[0] @property def _wrt_variables(self): # return the variables of differentiation without # respect to the type of count (int or symbolic) return [i[0] for i in self.variable_count] @property def variables(self): # TODO: deprecate? YES, make this 'enumerated_variables' and # name _wrt_variables as variables # TODO: support for `d^n`? rv = [] for v, count in self.variable_count: if not count.is_Integer: raise TypeError(filldedent(''' Cannot give expansion for symbolic count. If you just want a list of all variables of differentiation, use _wrt_variables.''')) rv.extend([v]*count) return tuple(rv) @property def variable_count(self): return self._args[1:] @property def derivative_count(self): return sum([count for _, count in self.variable_count], 0) @property def free_symbols(self): ret = self.expr.free_symbols # Add symbolic counts to free_symbols for _, count in self.variable_count: ret.update(count.free_symbols) return ret @property def kind(self): return self.args[0].kind def _eval_subs(self, old, new): # The substitution (old, new) cannot be done inside # Derivative(expr, vars) for a variety of reasons # as handled below. if old in self._wrt_variables: # first handle the counts expr = self.func(self.expr, *[(v, c.subs(old, new)) for v, c in self.variable_count]) if expr != self: return expr._eval_subs(old, new) # quick exit case if not getattr(new, '_diff_wrt', False): # case (0): new is not a valid variable of # differentiation if isinstance(old, Symbol): # don't introduce a new symbol if the old will do return Subs(self, old, new) else: xi = Dummy('xi') return Subs(self.xreplace({old: xi}), xi, new) # If both are Derivatives with the same expr, check if old is # equivalent to self or if old is a subderivative of self. if old.is_Derivative and old.expr == self.expr: if self.canonical == old.canonical: return new # collections.Counter doesn't have __le__ def _subset(a, b): return all((a[i] <= b[i]) == True for i in a) old_vars = Counter(dict(reversed(old.variable_count))) self_vars = Counter(dict(reversed(self.variable_count))) if _subset(old_vars, self_vars): return _derivative_dispatch(new, *(self_vars - old_vars).items()).canonical args = list(self.args) newargs = list(x._subs(old, new) for x in args) if args[0] == old: # complete replacement of self.expr # we already checked that the new is valid so we know # it won't be a problem should it appear in variables return _derivative_dispatch(*newargs) if newargs[0] != args[0]: # case (1) can't change expr by introducing something that is in # the _wrt_variables if it was already in the expr # e.g. # for Derivative(f(x, g(y)), y), x cannot be replaced with # anything that has y in it; for f(g(x), g(y)).diff(g(y)) # g(x) cannot be replaced with anything that has g(y) syms = {vi: Dummy() for vi in self._wrt_variables if not vi.is_Symbol} wrt = {syms.get(vi, vi) for vi in self._wrt_variables} forbidden = args[0].xreplace(syms).free_symbols & wrt nfree = new.xreplace(syms).free_symbols ofree = old.xreplace(syms).free_symbols if (nfree - ofree) & forbidden: return Subs(self, old, new) viter = ((i, j) for ((i, _), (j, _)) in zip(newargs[1:], args[1:])) if any(i != j for i, j in viter): # a wrt-variable change # case (2) can't change vars by introducing a variable # that is contained in expr, e.g. # for Derivative(f(z, g(h(x), y)), y), y cannot be changed to # x, h(x), or g(h(x), y) for a in _atomic(self.expr, recursive=True): for i in range(1, len(newargs)): vi, _ = newargs[i] if a == vi and vi != args[i][0]: return Subs(self, old, new) # more arg-wise checks vc = newargs[1:] oldv = self._wrt_variables newe = self.expr subs = [] for i, (vi, ci) in enumerate(vc): if not vi._diff_wrt: # case (3) invalid differentiation expression so # create a replacement dummy xi = Dummy('xi_%i' % i) # replace the old valid variable with the dummy # in the expression newe = newe.xreplace({oldv[i]: xi}) # and replace the bad variable with the dummy vc[i] = (xi, ci) # and record the dummy with the new (invalid) # differentiation expression subs.append((xi, vi)) if subs: # handle any residual substitution in the expression newe = newe._subs(old, new) # return the Subs-wrapped derivative return Subs(Derivative(newe, *vc), *zip(*subs)) # everything was ok return _derivative_dispatch(*newargs) def _eval_lseries(self, x, logx, cdir=0): dx = self.variables for term in self.expr.lseries(x, logx=logx, cdir=cdir): yield self.func(term, *dx) def _eval_nseries(self, x, n, logx, cdir=0): arg = self.expr.nseries(x, n=n, logx=logx) o = arg.getO() dx = self.variables rv = [self.func(a, *dx) for a in Add.make_args(arg.removeO())] if o: rv.append(o/x) return Add(*rv) def _eval_as_leading_term(self, x, logx=None, cdir=0): series_gen = self.expr.lseries(x) d = S.Zero for leading_term in series_gen: d = diff(leading_term, *self.variables) if d != 0: break return d def as_finite_difference(self, points=1, x0=None, wrt=None): """ Expresses a Derivative instance as a finite difference. Parameters ========== points : sequence or coefficient, optional If sequence: discrete values (length >= order+1) of the independent variable used for generating the finite difference weights. If it is a coefficient, it will be used as the step-size for generating an equidistant sequence of length order+1 centered around ``x0``. Default: 1 (step-size 1) x0 : number or Symbol, optional the value of the independent variable (``wrt``) at which the derivative is to be approximated. Default: same as ``wrt``. wrt : Symbol, optional "with respect to" the variable for which the (partial) derivative is to be approximated for. If not provided it is required that the derivative is ordinary. Default: ``None``. Examples ======== >>> from sympy import symbols, Function, exp, sqrt, Symbol >>> x, h = symbols('x h') >>> f = Function('f') >>> f(x).diff(x).as_finite_difference() -f(x - 1/2) + f(x + 1/2) The default step size and number of points are 1 and ``order + 1`` respectively. We can change the step size by passing a symbol as a parameter: >>> f(x).diff(x).as_finite_difference(h) -f(-h/2 + x)/h + f(h/2 + x)/h We can also specify the discretized values to be used in a sequence: >>> f(x).diff(x).as_finite_difference([x, x+h, x+2*h]) -3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h) The algorithm is not restricted to use equidistant spacing, nor do we need to make the approximation around ``x0``, but we can get an expression estimating the derivative at an offset: >>> e, sq2 = exp(1), sqrt(2) >>> xl = [x-h, x+h, x+e*h] >>> f(x).diff(x, 1).as_finite_difference(xl, x+h*sq2) # doctest: +ELLIPSIS 2*h*((h + sqrt(2)*h)/(2*h) - (-sqrt(2)*h + h)/(2*h))*f(E*h + x)/... To approximate ``Derivative`` around ``x0`` using a non-equidistant spacing step, the algorithm supports assignment of undefined functions to ``points``: >>> dx = Function('dx') >>> f(x).diff(x).as_finite_difference(points=dx(x), x0=x-h) -f(-h + x - dx(-h + x)/2)/dx(-h + x) + f(-h + x + dx(-h + x)/2)/dx(-h + x) Partial derivatives are also supported: >>> y = Symbol('y') >>> d2fdxdy=f(x,y).diff(x,y) >>> d2fdxdy.as_finite_difference(wrt=x) -Derivative(f(x - 1/2, y), y) + Derivative(f(x + 1/2, y), y) We can apply ``as_finite_difference`` to ``Derivative`` instances in compound expressions using ``replace``: >>> (1 + 42**f(x).diff(x)).replace(lambda arg: arg.is_Derivative, ... lambda arg: arg.as_finite_difference()) 42**(-f(x - 1/2) + f(x + 1/2)) + 1 See also ======== sympy.calculus.finite_diff.apply_finite_diff sympy.calculus.finite_diff.differentiate_finite sympy.calculus.finite_diff.finite_diff_weights """ from sympy.calculus.finite_diff import _as_finite_diff return _as_finite_diff(self, points, x0, wrt) @classmethod def _get_zero_with_shape_like(cls, expr): return S.Zero @classmethod def _dispatch_eval_derivative_n_times(cls, expr, v, count): # Evaluate the derivative `n` times. If # `_eval_derivative_n_times` is not overridden by the current # object, the default in `Basic` will call a loop over # `_eval_derivative`: return expr._eval_derivative_n_times(v, count) def _derivative_dispatch(expr, *variables, **kwargs): from sympy.matrices.common import MatrixCommon from sympy.matrices.expressions.matexpr import MatrixExpr from sympy.tensor.array import NDimArray array_types = (MatrixCommon, MatrixExpr, NDimArray, list, tuple, Tuple) if isinstance(expr, array_types) or any(isinstance(i[0], array_types) if isinstance(i, (tuple, list, Tuple)) else isinstance(i, array_types) for i in variables): from sympy.tensor.array.array_derivatives import ArrayDerivative return ArrayDerivative(expr, *variables, **kwargs) return Derivative(expr, *variables, **kwargs) class Lambda(Expr): """ Lambda(x, expr) represents a lambda function similar to Python's 'lambda x: expr'. A function of several variables is written as Lambda((x, y, ...), expr). Examples ======== A simple example: >>> from sympy import Lambda >>> from sympy.abc import x >>> f = Lambda(x, x**2) >>> f(4) 16 For multivariate functions, use: >>> from sympy.abc import y, z, t >>> f2 = Lambda((x, y, z, t), x + y**z + t**z) >>> f2(1, 2, 3, 4) 73 It is also possible to unpack tuple arguments: >>> f = Lambda(((x, y), z), x + y + z) >>> f((1, 2), 3) 6 A handy shortcut for lots of arguments: >>> p = x, y, z >>> f = Lambda(p, x + y*z) >>> f(*p) x + y*z """ is_Function = True def __new__(cls, signature, expr): if iterable(signature) and not isinstance(signature, (tuple, Tuple)): sympy_deprecation_warning( """ Using a non-tuple iterable as the first argument to Lambda is deprecated. Use Lambda(tuple(args), expr) instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-non-tuple-lambda", ) signature = tuple(signature) sig = signature if iterable(signature) else (signature,) sig = sympify(sig) cls._check_signature(sig) if len(sig) == 1 and sig[0] == expr: return S.IdentityFunction return Expr.__new__(cls, sig, sympify(expr)) @classmethod def _check_signature(cls, sig): syms = set() def rcheck(args): for a in args: if a.is_symbol: if a in syms: raise BadSignatureError("Duplicate symbol %s" % a) syms.add(a) elif isinstance(a, Tuple): rcheck(a) else: raise BadSignatureError("Lambda signature should be only tuples" " and symbols, not %s" % a) if not isinstance(sig, Tuple): raise BadSignatureError("Lambda signature should be a tuple not %s" % sig) # Recurse through the signature: rcheck(sig) @property def signature(self): """The expected form of the arguments to be unpacked into variables""" return self._args[0] @property def expr(self): """The return value of the function""" return self._args[1] @property def variables(self): """The variables used in the internal representation of the function""" def _variables(args): if isinstance(args, Tuple): for arg in args: yield from _variables(arg) else: yield args return tuple(_variables(self.signature)) @property def nargs(self): from sympy.sets.sets import FiniteSet return FiniteSet(len(self.signature)) bound_symbols = variables @property def free_symbols(self): return self.expr.free_symbols - set(self.variables) def __call__(self, *args): n = len(args) if n not in self.nargs: # Lambda only ever has 1 value in nargs # XXX: exception message must be in exactly this format to # make it work with NumPy's functions like vectorize(). See, # for example, https://github.com/numpy/numpy/issues/1697. # The ideal solution would be just to attach metadata to # the exception and change NumPy to take advantage of this. ## XXX does this apply to Lambda? If not, remove this comment. temp = ('%(name)s takes exactly %(args)s ' 'argument%(plural)s (%(given)s given)') raise BadArgumentsError(temp % { 'name': self, 'args': list(self.nargs)[0], 'plural': 's'*(list(self.nargs)[0] != 1), 'given': n}) d = self._match_signature(self.signature, args) return self.expr.xreplace(d) def _match_signature(self, sig, args): symargmap = {} def rmatch(pars, args): for par, arg in zip(pars, args): if par.is_symbol: symargmap[par] = arg elif isinstance(par, Tuple): if not isinstance(arg, (tuple, Tuple)) or len(args) != len(pars): raise BadArgumentsError("Can't match %s and %s" % (args, pars)) rmatch(par, arg) rmatch(sig, args) return symargmap @property def is_identity(self): """Return ``True`` if this ``Lambda`` is an identity function. """ return self.signature == self.expr def _eval_evalf(self, prec): return self.func(self.args[0], self.args[1].evalf(n=prec_to_dps(prec))) class Subs(Expr): """ Represents unevaluated substitutions of an expression. ``Subs(expr, x, x0)`` represents the expression resulting from substituting x with x0 in expr. Parameters ========== expr : Expr An expression. x : tuple, variable A variable or list of distinct variables. x0 : tuple or list of tuples A point or list of evaluation points corresponding to those variables. Examples ======== >>> from sympy import Subs, Function, sin, cos >>> from sympy.abc import x, y, z >>> f = Function('f') Subs are created when a particular substitution cannot be made. The x in the derivative cannot be replaced with 0 because 0 is not a valid variables of differentiation: >>> f(x).diff(x).subs(x, 0) Subs(Derivative(f(x), x), x, 0) Once f is known, the derivative and evaluation at 0 can be done: >>> _.subs(f, sin).doit() == sin(x).diff(x).subs(x, 0) == cos(0) True Subs can also be created directly with one or more variables: >>> Subs(f(x)*sin(y) + z, (x, y), (0, 1)) Subs(z + f(x)*sin(y), (x, y), (0, 1)) >>> _.doit() z + f(0)*sin(1) Notes ===== ``Subs`` objects are generally useful to represent unevaluated derivatives calculated at a point. The variables may be expressions, but they are subjected to the limitations of subs(), so it is usually a good practice to use only symbols for variables, since in that case there can be no ambiguity. There's no automatic expansion - use the method .doit() to effect all possible substitutions of the object and also of objects inside the expression. When evaluating derivatives at a point that is not a symbol, a Subs object is returned. One is also able to calculate derivatives of Subs objects - in this case the expression is always expanded (for the unevaluated form, use Derivative()). In order to allow expressions to combine before doit is done, a representation of the Subs expression is used internally to make expressions that are superficially different compare the same: >>> a, b = Subs(x, x, 0), Subs(y, y, 0) >>> a + b 2*Subs(x, x, 0) This can lead to unexpected consequences when using methods like `has` that are cached: >>> s = Subs(x, x, 0) >>> s.has(x), s.has(y) (True, False) >>> ss = s.subs(x, y) >>> ss.has(x), ss.has(y) (True, False) >>> s, ss (Subs(x, x, 0), Subs(y, y, 0)) """ def __new__(cls, expr, variables, point, **assumptions): if not is_sequence(variables, Tuple): variables = [variables] variables = Tuple(*variables) if has_dups(variables): repeated = [str(v) for v, i in Counter(variables).items() if i > 1] __ = ', '.join(repeated) raise ValueError(filldedent(''' The following expressions appear more than once: %s ''' % __)) point = Tuple(*(point if is_sequence(point, Tuple) else [point])) if len(point) != len(variables): raise ValueError('Number of point values must be the same as ' 'the number of variables.') if not point: return sympify(expr) # denest if isinstance(expr, Subs): variables = expr.variables + variables point = expr.point + point expr = expr.expr else: expr = sympify(expr) # use symbols with names equal to the point value (with prepended _) # to give a variable-independent expression pre = "_" pts = sorted(set(point), key=default_sort_key) from sympy.printing.str import StrPrinter class CustomStrPrinter(StrPrinter): def _print_Dummy(self, expr): return str(expr) + str(expr.dummy_index) def mystr(expr, **settings): p = CustomStrPrinter(settings) return p.doprint(expr) while 1: s_pts = {p: Symbol(pre + mystr(p)) for p in pts} reps = [(v, s_pts[p]) for v, p in zip(variables, point)] # if any underscore-prepended symbol is already a free symbol # and is a variable with a different point value, then there # is a clash, e.g. _0 clashes in Subs(_0 + _1, (_0, _1), (1, 0)) # because the new symbol that would be created is _1 but _1 # is already mapped to 0 so __0 and __1 are used for the new # symbols if any(r in expr.free_symbols and r in variables and Symbol(pre + mystr(point[variables.index(r)])) != r for _, r in reps): pre += "_" continue break obj = Expr.__new__(cls, expr, Tuple(*variables), point) obj._expr = expr.xreplace(dict(reps)) return obj def _eval_is_commutative(self): return self.expr.is_commutative def doit(self, **hints): e, v, p = self.args # remove self mappings for i, (vi, pi) in enumerate(zip(v, p)): if vi == pi: v = v[:i] + v[i + 1:] p = p[:i] + p[i + 1:] if not v: return self.expr if isinstance(e, Derivative): # apply functions first, e.g. f -> cos undone = [] for i, vi in enumerate(v): if isinstance(vi, FunctionClass): e = e.subs(vi, p[i]) else: undone.append((vi, p[i])) if not isinstance(e, Derivative): e = e.doit() if isinstance(e, Derivative): # do Subs that aren't related to differentiation undone2 = [] D = Dummy() arg = e.args[0] for vi, pi in undone: if D not in e.xreplace({vi: D}).free_symbols: if arg.has(vi): e = e.subs(vi, pi) else: undone2.append((vi, pi)) undone = undone2 # differentiate wrt variables that are present wrt = [] D = Dummy() expr = e.expr free = expr.free_symbols for vi, ci in e.variable_count: if isinstance(vi, Symbol) and vi in free: expr = expr.diff((vi, ci)) elif D in expr.subs(vi, D).free_symbols: expr = expr.diff((vi, ci)) else: wrt.append((vi, ci)) # inject remaining subs rv = expr.subs(undone) # do remaining differentiation *in order given* for vc in wrt: rv = rv.diff(vc) else: # inject remaining subs rv = e.subs(undone) else: rv = e.doit(**hints).subs(list(zip(v, p))) if hints.get('deep', True) and rv != self: rv = rv.doit(**hints) return rv def evalf(self, prec=None, **options): return self.doit().evalf(prec, **options) n = evalf # type:ignore @property def variables(self): """The variables to be evaluated""" return self._args[1] bound_symbols = variables @property def expr(self): """The expression on which the substitution operates""" return self._args[0] @property def point(self): """The values for which the variables are to be substituted""" return self._args[2] @property def free_symbols(self): return (self.expr.free_symbols - set(self.variables) | set(self.point.free_symbols)) @property def expr_free_symbols(self): sympy_deprecation_warning(""" The expr_free_symbols property is deprecated. Use free_symbols to get the free symbols of an expression. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-expr-free-symbols") # Don't show the warning twice from the recursive call with ignore_warnings(SymPyDeprecationWarning): return (self.expr.expr_free_symbols - set(self.variables) | set(self.point.expr_free_symbols)) def __eq__(self, other): if not isinstance(other, Subs): return False return self._hashable_content() == other._hashable_content() def __ne__(self, other): return not(self == other) def __hash__(self): return super().__hash__() def _hashable_content(self): return (self._expr.xreplace(self.canonical_variables), ) + tuple(ordered([(v, p) for v, p in zip(self.variables, self.point) if not self.expr.has(v)])) def _eval_subs(self, old, new): # Subs doit will do the variables in order; the semantics # of subs for Subs is have the following invariant for # Subs object foo: # foo.doit().subs(reps) == foo.subs(reps).doit() pt = list(self.point) if old in self.variables: if _atomic(new) == {new} and not any( i.has(new) for i in self.args): # the substitution is neutral return self.xreplace({old: new}) # any occurrence of old before this point will get # handled by replacements from here on i = self.variables.index(old) for j in range(i, len(self.variables)): pt[j] = pt[j]._subs(old, new) return self.func(self.expr, self.variables, pt) v = [i._subs(old, new) for i in self.variables] if v != list(self.variables): return self.func(self.expr, self.variables + (old,), pt + [new]) expr = self.expr._subs(old, new) pt = [i._subs(old, new) for i in self.point] return self.func(expr, v, pt) def _eval_derivative(self, s): # Apply the chain rule of the derivative on the substitution variables: f = self.expr vp = V, P = self.variables, self.point val = Add.fromiter(p.diff(s)*Subs(f.diff(v), *vp).doit() for v, p in zip(V, P)) # these are all the free symbols in the expr efree = f.free_symbols # some symbols like IndexedBase include themselves and args # as free symbols compound = {i for i in efree if len(i.free_symbols) > 1} # hide them and see what independent free symbols remain dums = {Dummy() for i in compound} masked = f.xreplace(dict(zip(compound, dums))) ifree = masked.free_symbols - dums # include the compound symbols free = ifree | compound # remove the variables already handled free -= set(V) # add back any free symbols of remaining compound symbols free |= {i for j in free & compound for i in j.free_symbols} # if symbols of s are in free then there is more to do if free & s.free_symbols: val += Subs(f.diff(s), self.variables, self.point).doit() return val def _eval_nseries(self, x, n, logx, cdir=0): if x in self.point: # x is the variable being substituted into apos = self.point.index(x) other = self.variables[apos] else: other = x arg = self.expr.nseries(other, n=n, logx=logx) o = arg.getO() terms = Add.make_args(arg.removeO()) rv = Add(*[self.func(a, *self.args[1:]) for a in terms]) if o: rv += o.subs(other, x) return rv def _eval_as_leading_term(self, x, logx=None, cdir=0): if x in self.point: ipos = self.point.index(x) xvar = self.variables[ipos] return self.expr.as_leading_term(xvar) if x in self.variables: # if `x` is a dummy variable, it means it won't exist after the # substitution has been performed: return self # The variable is independent of the substitution: return self.expr.as_leading_term(x) def diff(f, *symbols, **kwargs): """ Differentiate f with respect to symbols. Explanation =========== This is just a wrapper to unify .diff() and the Derivative class; its interface is similar to that of integrate(). You can use the same shortcuts for multiple variables as with Derivative. For example, diff(f(x), x, x, x) and diff(f(x), x, 3) both return the third derivative of f(x). You can pass evaluate=False to get an unevaluated Derivative class. Note that if there are 0 symbols (such as diff(f(x), x, 0), then the result will be the function (the zeroth derivative), even if evaluate=False. Examples ======== >>> from sympy import sin, cos, Function, diff >>> from sympy.abc import x, y >>> f = Function('f') >>> diff(sin(x), x) cos(x) >>> diff(f(x), x, x, x) Derivative(f(x), (x, 3)) >>> diff(f(x), x, 3) Derivative(f(x), (x, 3)) >>> diff(sin(x)*cos(y), x, 2, y, 2) sin(x)*cos(y) >>> type(diff(sin(x), x)) cos >>> type(diff(sin(x), x, evaluate=False)) <class 'sympy.core.function.Derivative'> >>> type(diff(sin(x), x, 0)) sin >>> type(diff(sin(x), x, 0, evaluate=False)) sin >>> diff(sin(x)) cos(x) >>> diff(sin(x*y)) Traceback (most recent call last): ... ValueError: specify differentiation variables to differentiate sin(x*y) Note that ``diff(sin(x))`` syntax is meant only for convenience in interactive sessions and should be avoided in library code. References ========== .. [1] http://reference.wolfram.com/legacy/v5_2/Built-inFunctions/AlgebraicComputation/Calculus/D.html See Also ======== Derivative idiff: computes the derivative implicitly """ if hasattr(f, 'diff'): return f.diff(*symbols, **kwargs) kwargs.setdefault('evaluate', True) return _derivative_dispatch(f, *symbols, **kwargs) def expand(e, deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints): r""" Expand an expression using methods given as hints. Explanation =========== Hints evaluated unless explicitly set to False are: ``basic``, ``log``, ``multinomial``, ``mul``, ``power_base``, and ``power_exp`` The following hints are supported but not applied unless set to True: ``complex``, ``func``, and ``trig``. In addition, the following meta-hints are supported by some or all of the other hints: ``frac``, ``numer``, ``denom``, ``modulus``, and ``force``. ``deep`` is supported by all hints. Additionally, subclasses of Expr may define their own hints or meta-hints. The ``basic`` hint is used for any special rewriting of an object that should be done automatically (along with the other hints like ``mul``) when expand is called. This is a catch-all hint to handle any sort of expansion that may not be described by the existing hint names. To use this hint an object should override the ``_eval_expand_basic`` method. Objects may also define their own expand methods, which are not run by default. See the API section below. If ``deep`` is set to ``True`` (the default), things like arguments of functions are recursively expanded. Use ``deep=False`` to only expand on the top level. If the ``force`` hint is used, assumptions about variables will be ignored in making the expansion. Hints ===== These hints are run by default mul --- Distributes multiplication over addition: >>> from sympy import cos, exp, sin >>> from sympy.abc import x, y, z >>> (y*(x + z)).expand(mul=True) x*y + y*z multinomial ----------- Expand (x + y + ...)**n where n is a positive integer. >>> ((x + y + z)**2).expand(multinomial=True) x**2 + 2*x*y + 2*x*z + y**2 + 2*y*z + z**2 power_exp --------- Expand addition in exponents into multiplied bases. >>> exp(x + y).expand(power_exp=True) exp(x)*exp(y) >>> (2**(x + y)).expand(power_exp=True) 2**x*2**y power_base ---------- Split powers of multiplied bases. This only happens by default if assumptions allow, or if the ``force`` meta-hint is used: >>> ((x*y)**z).expand(power_base=True) (x*y)**z >>> ((x*y)**z).expand(power_base=True, force=True) x**z*y**z >>> ((2*y)**z).expand(power_base=True) 2**z*y**z Note that in some cases where this expansion always holds, SymPy performs it automatically: >>> (x*y)**2 x**2*y**2 log --- Pull out power of an argument as a coefficient and split logs products into sums of logs. Note that these only work if the arguments of the log function have the proper assumptions--the arguments must be positive and the exponents must be real--or else the ``force`` hint must be True: >>> from sympy import log, symbols >>> log(x**2*y).expand(log=True) log(x**2*y) >>> log(x**2*y).expand(log=True, force=True) 2*log(x) + log(y) >>> x, y = symbols('x,y', positive=True) >>> log(x**2*y).expand(log=True) 2*log(x) + log(y) basic ----- This hint is intended primarily as a way for custom subclasses to enable expansion by default. These hints are not run by default: complex ------- Split an expression into real and imaginary parts. >>> x, y = symbols('x,y') >>> (x + y).expand(complex=True) re(x) + re(y) + I*im(x) + I*im(y) >>> cos(x).expand(complex=True) -I*sin(re(x))*sinh(im(x)) + cos(re(x))*cosh(im(x)) Note that this is just a wrapper around ``as_real_imag()``. Most objects that wish to redefine ``_eval_expand_complex()`` should consider redefining ``as_real_imag()`` instead. func ---- Expand other functions. >>> from sympy import gamma >>> gamma(x + 1).expand(func=True) x*gamma(x) trig ---- Do trigonometric expansions. >>> cos(x + y).expand(trig=True) -sin(x)*sin(y) + cos(x)*cos(y) >>> sin(2*x).expand(trig=True) 2*sin(x)*cos(x) Note that the forms of ``sin(n*x)`` and ``cos(n*x)`` in terms of ``sin(x)`` and ``cos(x)`` are not unique, due to the identity `\sin^2(x) + \cos^2(x) = 1`. The current implementation uses the form obtained from Chebyshev polynomials, but this may change. See `this MathWorld article <http://mathworld.wolfram.com/Multiple-AngleFormulas.html>`_ for more information. Notes ===== - You can shut off unwanted methods:: >>> (exp(x + y)*(x + y)).expand() x*exp(x)*exp(y) + y*exp(x)*exp(y) >>> (exp(x + y)*(x + y)).expand(power_exp=False) x*exp(x + y) + y*exp(x + y) >>> (exp(x + y)*(x + y)).expand(mul=False) (x + y)*exp(x)*exp(y) - Use deep=False to only expand on the top level:: >>> exp(x + exp(x + y)).expand() exp(x)*exp(exp(x)*exp(y)) >>> exp(x + exp(x + y)).expand(deep=False) exp(x)*exp(exp(x + y)) - Hints are applied in an arbitrary, but consistent order (in the current implementation, they are applied in alphabetical order, except multinomial comes before mul, but this may change). Because of this, some hints may prevent expansion by other hints if they are applied first. For example, ``mul`` may distribute multiplications and prevent ``log`` and ``power_base`` from expanding them. Also, if ``mul`` is applied before ``multinomial`, the expression might not be fully distributed. The solution is to use the various ``expand_hint`` helper functions or to use ``hint=False`` to this function to finely control which hints are applied. Here are some examples:: >>> from sympy import expand, expand_mul, expand_power_base >>> x, y, z = symbols('x,y,z', positive=True) >>> expand(log(x*(y + z))) log(x) + log(y + z) Here, we see that ``log`` was applied before ``mul``. To get the mul expanded form, either of the following will work:: >>> expand_mul(log(x*(y + z))) log(x*y + x*z) >>> expand(log(x*(y + z)), log=False) log(x*y + x*z) A similar thing can happen with the ``power_base`` hint:: >>> expand((x*(y + z))**x) (x*y + x*z)**x To get the ``power_base`` expanded form, either of the following will work:: >>> expand((x*(y + z))**x, mul=False) x**x*(y + z)**x >>> expand_power_base((x*(y + z))**x) x**x*(y + z)**x >>> expand((x + y)*y/x) y + y**2/x The parts of a rational expression can be targeted:: >>> expand((x + y)*y/x/(x + 1), frac=True) (x*y + y**2)/(x**2 + x) >>> expand((x + y)*y/x/(x + 1), numer=True) (x*y + y**2)/(x*(x + 1)) >>> expand((x + y)*y/x/(x + 1), denom=True) y*(x + y)/(x**2 + x) - The ``modulus`` meta-hint can be used to reduce the coefficients of an expression post-expansion:: >>> expand((3*x + 1)**2) 9*x**2 + 6*x + 1 >>> expand((3*x + 1)**2, modulus=5) 4*x**2 + x + 1 - Either ``expand()`` the function or ``.expand()`` the method can be used. Both are equivalent:: >>> expand((x + 1)**2) x**2 + 2*x + 1 >>> ((x + 1)**2).expand() x**2 + 2*x + 1 API === Objects can define their own expand hints by defining ``_eval_expand_hint()``. The function should take the form:: def _eval_expand_hint(self, **hints): # Only apply the method to the top-level expression ... See also the example below. Objects should define ``_eval_expand_hint()`` methods only if ``hint`` applies to that specific object. The generic ``_eval_expand_hint()`` method defined in Expr will handle the no-op case. Each hint should be responsible for expanding that hint only. Furthermore, the expansion should be applied to the top-level expression only. ``expand()`` takes care of the recursion that happens when ``deep=True``. You should only call ``_eval_expand_hint()`` methods directly if you are 100% sure that the object has the method, as otherwise you are liable to get unexpected ``AttributeError``s. Note, again, that you do not need to recursively apply the hint to args of your object: this is handled automatically by ``expand()``. ``_eval_expand_hint()`` should generally not be used at all outside of an ``_eval_expand_hint()`` method. If you want to apply a specific expansion from within another method, use the public ``expand()`` function, method, or ``expand_hint()`` functions. In order for expand to work, objects must be rebuildable by their args, i.e., ``obj.func(*obj.args) == obj`` must hold. Expand methods are passed ``**hints`` so that expand hints may use 'metahints'--hints that control how different expand methods are applied. For example, the ``force=True`` hint described above that causes ``expand(log=True)`` to ignore assumptions is such a metahint. The ``deep`` meta-hint is handled exclusively by ``expand()`` and is not passed to ``_eval_expand_hint()`` methods. Note that expansion hints should generally be methods that perform some kind of 'expansion'. For hints that simply rewrite an expression, use the .rewrite() API. Examples ======== >>> from sympy import Expr, sympify >>> class MyClass(Expr): ... def __new__(cls, *args): ... args = sympify(args) ... return Expr.__new__(cls, *args) ... ... def _eval_expand_double(self, *, force=False, **hints): ... ''' ... Doubles the args of MyClass. ... ... If there more than four args, doubling is not performed, ... unless force=True is also used (False by default). ... ''' ... if not force and len(self.args) > 4: ... return self ... return self.func(*(self.args + self.args)) ... >>> a = MyClass(1, 2, MyClass(3, 4)) >>> a MyClass(1, 2, MyClass(3, 4)) >>> a.expand(double=True) MyClass(1, 2, MyClass(3, 4, 3, 4), 1, 2, MyClass(3, 4, 3, 4)) >>> a.expand(double=True, deep=False) MyClass(1, 2, MyClass(3, 4), 1, 2, MyClass(3, 4)) >>> b = MyClass(1, 2, 3, 4, 5) >>> b.expand(double=True) MyClass(1, 2, 3, 4, 5) >>> b.expand(double=True, force=True) MyClass(1, 2, 3, 4, 5, 1, 2, 3, 4, 5) See Also ======== expand_log, expand_mul, expand_multinomial, expand_complex, expand_trig, expand_power_base, expand_power_exp, expand_func, sympy.simplify.hyperexpand.hyperexpand """ # don't modify this; modify the Expr.expand method hints['power_base'] = power_base hints['power_exp'] = power_exp hints['mul'] = mul hints['log'] = log hints['multinomial'] = multinomial hints['basic'] = basic return sympify(e).expand(deep=deep, modulus=modulus, **hints) # This is a special application of two hints def _mexpand(expr, recursive=False): # expand multinomials and then expand products; this may not always # be sufficient to give a fully expanded expression (see # test_issue_8247_8354 in test_arit) if expr is None: return was = None while was != expr: was, expr = expr, expand_mul(expand_multinomial(expr)) if not recursive: break return expr # These are simple wrappers around single hints. def expand_mul(expr, deep=True): """ Wrapper around expand that only uses the mul hint. See the expand docstring for more information. Examples ======== >>> from sympy import symbols, expand_mul, exp, log >>> x, y = symbols('x,y', positive=True) >>> expand_mul(exp(x+y)*(x+y)*log(x*y**2)) x*exp(x + y)*log(x*y**2) + y*exp(x + y)*log(x*y**2) """ return sympify(expr).expand(deep=deep, mul=True, power_exp=False, power_base=False, basic=False, multinomial=False, log=False) def expand_multinomial(expr, deep=True): """ Wrapper around expand that only uses the multinomial hint. See the expand docstring for more information. Examples ======== >>> from sympy import symbols, expand_multinomial, exp >>> x, y = symbols('x y', positive=True) >>> expand_multinomial((x + exp(x + 1))**2) x**2 + 2*x*exp(x + 1) + exp(2*x + 2) """ return sympify(expr).expand(deep=deep, mul=False, power_exp=False, power_base=False, basic=False, multinomial=True, log=False) def expand_log(expr, deep=True, force=False, factor=False): """ Wrapper around expand that only uses the log hint. See the expand docstring for more information. Examples ======== >>> from sympy import symbols, expand_log, exp, log >>> x, y = symbols('x,y', positive=True) >>> expand_log(exp(x+y)*(x+y)*log(x*y**2)) (x + y)*(log(x) + 2*log(y))*exp(x + y) """ from sympy.functions.elementary.exponential import log if factor is False: def _handle(x): x1 = expand_mul(expand_log(x, deep=deep, force=force, factor=True)) if x1.count(log) <= x.count(log): return x1 return x expr = expr.replace( lambda x: x.is_Mul and all(any(isinstance(i, log) and i.args[0].is_Rational for i in Mul.make_args(j)) for j in x.as_numer_denom()), _handle) return sympify(expr).expand(deep=deep, log=True, mul=False, power_exp=False, power_base=False, multinomial=False, basic=False, force=force, factor=factor) def expand_func(expr, deep=True): """ Wrapper around expand that only uses the func hint. See the expand docstring for more information. Examples ======== >>> from sympy import expand_func, gamma >>> from sympy.abc import x >>> expand_func(gamma(x + 2)) x*(x + 1)*gamma(x) """ return sympify(expr).expand(deep=deep, func=True, basic=False, log=False, mul=False, power_exp=False, power_base=False, multinomial=False) def expand_trig(expr, deep=True): """ Wrapper around expand that only uses the trig hint. See the expand docstring for more information. Examples ======== >>> from sympy import expand_trig, sin >>> from sympy.abc import x, y >>> expand_trig(sin(x+y)*(x+y)) (x + y)*(sin(x)*cos(y) + sin(y)*cos(x)) """ return sympify(expr).expand(deep=deep, trig=True, basic=False, log=False, mul=False, power_exp=False, power_base=False, multinomial=False) def expand_complex(expr, deep=True): """ Wrapper around expand that only uses the complex hint. See the expand docstring for more information. Examples ======== >>> from sympy import expand_complex, exp, sqrt, I >>> from sympy.abc import z >>> expand_complex(exp(z)) I*exp(re(z))*sin(im(z)) + exp(re(z))*cos(im(z)) >>> expand_complex(sqrt(I)) sqrt(2)/2 + sqrt(2)*I/2 See Also ======== sympy.core.expr.Expr.as_real_imag """ return sympify(expr).expand(deep=deep, complex=True, basic=False, log=False, mul=False, power_exp=False, power_base=False, multinomial=False) def expand_power_base(expr, deep=True, force=False): """ Wrapper around expand that only uses the power_base hint. A wrapper to expand(power_base=True) which separates a power with a base that is a Mul into a product of powers, without performing any other expansions, provided that assumptions about the power's base and exponent allow. deep=False (default is True) will only apply to the top-level expression. force=True (default is False) will cause the expansion to ignore assumptions about the base and exponent. When False, the expansion will only happen if the base is non-negative or the exponent is an integer. >>> from sympy.abc import x, y, z >>> from sympy import expand_power_base, sin, cos, exp, Symbol >>> (x*y)**2 x**2*y**2 >>> (2*x)**y (2*x)**y >>> expand_power_base(_) 2**y*x**y >>> expand_power_base((x*y)**z) (x*y)**z >>> expand_power_base((x*y)**z, force=True) x**z*y**z >>> expand_power_base(sin((x*y)**z), deep=False) sin((x*y)**z) >>> expand_power_base(sin((x*y)**z), force=True) sin(x**z*y**z) >>> expand_power_base((2*sin(x))**y + (2*cos(x))**y) 2**y*sin(x)**y + 2**y*cos(x)**y >>> expand_power_base((2*exp(y))**x) 2**x*exp(y)**x >>> expand_power_base((2*cos(x))**y) 2**y*cos(x)**y Notice that sums are left untouched. If this is not the desired behavior, apply full ``expand()`` to the expression: >>> expand_power_base(((x+y)*z)**2) z**2*(x + y)**2 >>> (((x+y)*z)**2).expand() x**2*z**2 + 2*x*y*z**2 + y**2*z**2 >>> expand_power_base((2*y)**(1+z)) 2**(z + 1)*y**(z + 1) >>> ((2*y)**(1+z)).expand() 2*2**z*y**(z + 1) The power that is unexpanded can be expanded safely when ``y != 0``, otherwise different values might be obtained for the expression: >>> prev = _ If we indicate that ``y`` is positive but then replace it with a value of 0 after expansion, the expression becomes 0: >>> p = Symbol('p', positive=True) >>> prev.subs(y, p).expand().subs(p, 0) 0 But if ``z = -1`` the expression would not be zero: >>> prev.subs(y, 0).subs(z, -1) 1 See Also ======== expand """ return sympify(expr).expand(deep=deep, log=False, mul=False, power_exp=False, power_base=True, multinomial=False, basic=False, force=force) def expand_power_exp(expr, deep=True): """ Wrapper around expand that only uses the power_exp hint. See the expand docstring for more information. Examples ======== >>> from sympy import expand_power_exp, Symbol >>> from sympy.abc import x, y >>> expand_power_exp(3**(y + 2)) 9*3**y >>> expand_power_exp(x**(y + 2)) x**(y + 2) If ``x = 0`` the value of the expression depends on the value of ``y``; if the expression were expanded the result would be 0. So expansion is only done if ``x != 0``: >>> expand_power_exp(Symbol('x', zero=False)**(y + 2)) x**2*x**y """ return sympify(expr).expand(deep=deep, complex=False, basic=False, log=False, mul=False, power_exp=True, power_base=False, multinomial=False) def count_ops(expr, visual=False): """ Return a representation (integer or expression) of the operations in expr. Parameters ========== expr : Expr If expr is an iterable, the sum of the op counts of the items will be returned. visual : bool, optional If ``False`` (default) then the sum of the coefficients of the visual expression will be returned. If ``True`` then the number of each type of operation is shown with the core class types (or their virtual equivalent) multiplied by the number of times they occur. Examples ======== >>> from sympy.abc import a, b, x, y >>> from sympy import sin, count_ops Although there is not a SUB object, minus signs are interpreted as either negations or subtractions: >>> (x - y).count_ops(visual=True) SUB >>> (-x).count_ops(visual=True) NEG Here, there are two Adds and a Pow: >>> (1 + a + b**2).count_ops(visual=True) 2*ADD + POW In the following, an Add, Mul, Pow and two functions: >>> (sin(x)*x + sin(x)**2).count_ops(visual=True) ADD + MUL + POW + 2*SIN for a total of 5: >>> (sin(x)*x + sin(x)**2).count_ops(visual=False) 5 Note that "what you type" is not always what you get. The expression 1/x/y is translated by sympy into 1/(x*y) so it gives a DIV and MUL rather than two DIVs: >>> (1/x/y).count_ops(visual=True) DIV + MUL The visual option can be used to demonstrate the difference in operations for expressions in different forms. Here, the Horner representation is compared with the expanded form of a polynomial: >>> eq=x*(1 + x*(2 + x*(3 + x))) >>> count_ops(eq.expand(), visual=True) - count_ops(eq, visual=True) -MUL + 3*POW The count_ops function also handles iterables: >>> count_ops([x, sin(x), None, True, x + 2], visual=False) 2 >>> count_ops([x, sin(x), None, True, x + 2], visual=True) ADD + SIN >>> count_ops({x: sin(x), x + 2: y + 1}, visual=True) 2*ADD + SIN """ from .relational import Relational from sympy.concrete.summations import Sum from sympy.integrals.integrals import Integral from sympy.logic.boolalg import BooleanFunction from sympy.simplify.radsimp import fraction expr = sympify(expr) if isinstance(expr, Expr) and not expr.is_Relational: ops = [] args = [expr] NEG = Symbol('NEG') DIV = Symbol('DIV') SUB = Symbol('SUB') ADD = Symbol('ADD') EXP = Symbol('EXP') while args: a = args.pop() # if the following fails because the object is # not Basic type, then the object should be fixed # since it is the intention that all args of Basic # should themselves be Basic if a.is_Rational: #-1/3 = NEG + DIV if a is not S.One: if a.p < 0: ops.append(NEG) if a.q != 1: ops.append(DIV) continue elif a.is_Mul or a.is_MatMul: if _coeff_isneg(a): ops.append(NEG) if a.args[0] is S.NegativeOne: a = a.as_two_terms()[1] else: a = -a n, d = fraction(a) if n.is_Integer: ops.append(DIV) if n < 0: ops.append(NEG) args.append(d) continue # won't be -Mul but could be Add elif d is not S.One: if not d.is_Integer: args.append(d) ops.append(DIV) args.append(n) continue # could be -Mul elif a.is_Add or a.is_MatAdd: aargs = list(a.args) negs = 0 for i, ai in enumerate(aargs): if _coeff_isneg(ai): negs += 1 args.append(-ai) if i > 0: ops.append(SUB) else: args.append(ai) if i > 0: ops.append(ADD) if negs == len(aargs): # -x - y = NEG + SUB ops.append(NEG) elif _coeff_isneg(aargs[0]): # -x + y = SUB, but already recorded ADD ops.append(SUB - ADD) continue if a.is_Pow and a.exp is S.NegativeOne: ops.append(DIV) args.append(a.base) # won't be -Mul but could be Add continue if a == S.Exp1: ops.append(EXP) continue if a.is_Pow and a.base == S.Exp1: ops.append(EXP) args.append(a.exp) continue if a.is_Mul or isinstance(a, LatticeOp): o = Symbol(a.func.__name__.upper()) # count the args ops.append(o*(len(a.args) - 1)) elif a.args and ( a.is_Pow or a.is_Function or isinstance(a, Derivative) or isinstance(a, Integral) or isinstance(a, Sum)): # if it's not in the list above we don't # consider a.func something to count, e.g. # Tuple, MatrixSymbol, etc... if isinstance(a.func, UndefinedFunction): o = Symbol("FUNC_" + a.func.__name__.upper()) else: o = Symbol(a.func.__name__.upper()) ops.append(o) if not a.is_Symbol: args.extend(a.args) elif isinstance(expr, Dict): ops = [count_ops(k, visual=visual) + count_ops(v, visual=visual) for k, v in expr.items()] elif iterable(expr): ops = [count_ops(i, visual=visual) for i in expr] elif isinstance(expr, (Relational, BooleanFunction)): ops = [] for arg in expr.args: ops.append(count_ops(arg, visual=True)) o = Symbol(func_name(expr, short=True).upper()) ops.append(o) elif not isinstance(expr, Basic): ops = [] else: # it's Basic not isinstance(expr, Expr): if not isinstance(expr, Basic): raise TypeError("Invalid type of expr") else: ops = [] args = [expr] while args: a = args.pop() if a.args: o = Symbol(type(a).__name__.upper()) if a.is_Boolean: ops.append(o*(len(a.args)-1)) else: ops.append(o) args.extend(a.args) if not ops: if visual: return S.Zero return 0 ops = Add(*ops) if visual: return ops if ops.is_Number: return int(ops) return sum(int((a.args or [1])[0]) for a in Add.make_args(ops)) def nfloat(expr, n=15, exponent=False, dkeys=False): """Make all Rationals in expr Floats except those in exponents (unless the exponents flag is set to True) and those in undefined functions. When processing dictionaries, do not modify the keys unless ``dkeys=True``. Examples ======== >>> from sympy import nfloat, cos, pi, sqrt >>> from sympy.abc import x, y >>> nfloat(x**4 + x/2 + cos(pi/3) + 1 + sqrt(y)) x**4 + 0.5*x + sqrt(y) + 1.5 >>> nfloat(x**4 + sqrt(y), exponent=True) x**4.0 + y**0.5 Container types are not modified: >>> type(nfloat((1, 2))) is tuple True """ from sympy.matrices.matrices import MatrixBase kw = dict(n=n, exponent=exponent, dkeys=dkeys) if isinstance(expr, MatrixBase): return expr.applyfunc(lambda e: nfloat(e, **kw)) # handling of iterable containers if iterable(expr, exclude=str): if isinstance(expr, (dict, Dict)): if dkeys: args = [tuple(map(lambda i: nfloat(i, **kw), a)) for a in expr.items()] else: args = [(k, nfloat(v, **kw)) for k, v in expr.items()] if isinstance(expr, dict): return type(expr)(args) else: return expr.func(*args) elif isinstance(expr, Basic): return expr.func(*[nfloat(a, **kw) for a in expr.args]) return type(expr)([nfloat(a, **kw) for a in expr]) rv = sympify(expr) if rv.is_Number: return Float(rv, n) elif rv.is_number: # evalf doesn't always set the precision rv = rv.n(n) if rv.is_Number: rv = Float(rv.n(n), n) else: pass # pure_complex(rv) is likely True return rv elif rv.is_Atom: return rv elif rv.is_Relational: args_nfloat = (nfloat(arg, **kw) for arg in rv.args) return rv.func(*args_nfloat) # watch out for RootOf instances that don't like to have # their exponents replaced with Dummies and also sometimes have # problems with evaluating at low precision (issue 6393) from sympy.polys.rootoftools import RootOf rv = rv.xreplace({ro: ro.n(n) for ro in rv.atoms(RootOf)}) from .power import Pow if not exponent: reps = [(p, Pow(p.base, Dummy())) for p in rv.atoms(Pow)] rv = rv.xreplace(dict(reps)) rv = rv.n(n) if not exponent: rv = rv.xreplace({d.exp: p.exp for p, d in reps}) else: # Pow._eval_evalf special cases Integer exponents so if # exponent is suppose to be handled we have to do so here rv = rv.xreplace(Transform( lambda x: Pow(x.base, Float(x.exp, n)), lambda x: x.is_Pow and x.exp.is_Integer)) return rv.xreplace(Transform( lambda x: x.func(*nfloat(x.args, n, exponent)), lambda x: isinstance(x, Function) and not isinstance(x, AppliedUndef))) from .symbol import Dummy, Symbol
4fc3096f0dc52394771fabe810c8358d927dad438ba526ff4e8950c3029aaf04
from typing import Tuple as tTuple from collections import defaultdict from functools import cmp_to_key, reduce from operator import attrgetter from .basic import Basic from .parameters import global_parameters from .logic import _fuzzy_group, fuzzy_or, fuzzy_not from .singleton import S from .operations import AssocOp, AssocOpDispatcher from .cache import cacheit from .numbers import ilcm, igcd, equal_valued from .expr import Expr from .kind import UndefinedKind from sympy.utilities.iterables import is_sequence, sift # Key for sorting commutative args in canonical order _args_sortkey = cmp_to_key(Basic.compare) def _could_extract_minus_sign(expr): # assume expr is Add-like # We choose the one with less arguments with minus signs negative_args = sum(1 for i in expr.args if i.could_extract_minus_sign()) positive_args = len(expr.args) - negative_args if positive_args > negative_args: return False elif positive_args < negative_args: return True # choose based on .sort_key() to prefer # x - 1 instead of 1 - x and # 3 - sqrt(2) instead of -3 + sqrt(2) return bool(expr.sort_key() < (-expr).sort_key()) def _addsort(args): # in-place sorting of args args.sort(key=_args_sortkey) def _unevaluated_Add(*args): """Return a well-formed unevaluated Add: Numbers are collected and put in slot 0 and args are sorted. Use this when args have changed but you still want to return an unevaluated Add. Examples ======== >>> from sympy.core.add import _unevaluated_Add as uAdd >>> from sympy import S, Add >>> from sympy.abc import x, y >>> a = uAdd(*[S(1.0), x, S(2)]) >>> a.args[0] 3.00000000000000 >>> a.args[1] x Beyond the Number being in slot 0, there is no other assurance of order for the arguments since they are hash sorted. So, for testing purposes, output produced by this in some other function can only be tested against the output of this function or as one of several options: >>> opts = (Add(x, y, evaluate=False), Add(y, x, evaluate=False)) >>> a = uAdd(x, y) >>> assert a in opts and a == uAdd(x, y) >>> uAdd(x + 1, x + 2) x + x + 3 """ args = list(args) newargs = [] co = S.Zero while args: a = args.pop() if a.is_Add: # this will keep nesting from building up # so that x + (x + 1) -> x + x + 1 (3 args) args.extend(a.args) elif a.is_Number: co += a else: newargs.append(a) _addsort(newargs) if co: newargs.insert(0, co) return Add._from_args(newargs) class Add(Expr, AssocOp): """ Expression representing addition operation for algebraic group. .. deprecated:: 1.7 Using arguments that aren't subclasses of :class:`~.Expr` in core operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is deprecated. See :ref:`non-expr-args-deprecated` for details. Every argument of ``Add()`` must be ``Expr``. Infix operator ``+`` on most scalar objects in SymPy calls this class. Another use of ``Add()`` is to represent the structure of abstract addition so that its arguments can be substituted to return different class. Refer to examples section for this. ``Add()`` evaluates the argument unless ``evaluate=False`` is passed. The evaluation logic includes: 1. Flattening ``Add(x, Add(y, z))`` -> ``Add(x, y, z)`` 2. Identity removing ``Add(x, 0, y)`` -> ``Add(x, y)`` 3. Coefficient collecting by ``.as_coeff_Mul()`` ``Add(x, 2*x)`` -> ``Mul(3, x)`` 4. Term sorting ``Add(y, x, 2)`` -> ``Add(2, x, y)`` If no argument is passed, identity element 0 is returned. If single element is passed, that element is returned. Note that ``Add(*args)`` is more efficient than ``sum(args)`` because it flattens the arguments. ``sum(a, b, c, ...)`` recursively adds the arguments as ``a + (b + (c + ...))``, which has quadratic complexity. On the other hand, ``Add(a, b, c, d)`` does not assume nested structure, making the complexity linear. Since addition is group operation, every argument should have the same :obj:`sympy.core.kind.Kind()`. Examples ======== >>> from sympy import Add, I >>> from sympy.abc import x, y >>> Add(x, 1) x + 1 >>> Add(x, x) 2*x >>> 2*x**2 + 3*x + I*y + 2*y + 2*x/5 + 1.0*y + 1 2*x**2 + 17*x/5 + 3.0*y + I*y + 1 If ``evaluate=False`` is passed, result is not evaluated. >>> Add(1, 2, evaluate=False) 1 + 2 >>> Add(x, x, evaluate=False) x + x ``Add()`` also represents the general structure of addition operation. >>> from sympy import MatrixSymbol >>> A,B = MatrixSymbol('A', 2,2), MatrixSymbol('B', 2,2) >>> expr = Add(x,y).subs({x:A, y:B}) >>> expr A + B >>> type(expr) <class 'sympy.matrices.expressions.matadd.MatAdd'> Note that the printers do not display in args order. >>> Add(x, 1) x + 1 >>> Add(x, 1).args (1, x) See Also ======== MatAdd """ __slots__ = () args: tTuple[Expr, ...] is_Add = True _args_type = Expr @classmethod def flatten(cls, seq): """ Takes the sequence "seq" of nested Adds and returns a flatten list. Returns: (commutative_part, noncommutative_part, order_symbols) Applies associativity, all terms are commutable with respect to addition. NB: the removal of 0 is already handled by AssocOp.__new__ See Also ======== sympy.core.mul.Mul.flatten """ from sympy.calculus.accumulationbounds import AccumBounds from sympy.matrices.expressions import MatrixExpr from sympy.tensor.tensor import TensExpr rv = None if len(seq) == 2: a, b = seq if b.is_Rational: a, b = b, a if a.is_Rational: if b.is_Mul: rv = [a, b], [], None if rv: if all(s.is_commutative for s in rv[0]): return rv return [], rv[0], None terms = {} # term -> coeff # e.g. x**2 -> 5 for ... + 5*x**2 + ... coeff = S.Zero # coefficient (Number or zoo) to always be in slot 0 # e.g. 3 + ... order_factors = [] extra = [] for o in seq: # O(x) if o.is_Order: if o.expr.is_zero: continue for o1 in order_factors: if o1.contains(o): o = None break if o is None: continue order_factors = [o] + [ o1 for o1 in order_factors if not o.contains(o1)] continue # 3 or NaN elif o.is_Number: if (o is S.NaN or coeff is S.ComplexInfinity and o.is_finite is False) and not extra: # we know for sure the result will be nan return [S.NaN], [], None if coeff.is_Number or isinstance(coeff, AccumBounds): coeff += o if coeff is S.NaN and not extra: # we know for sure the result will be nan return [S.NaN], [], None continue elif isinstance(o, AccumBounds): coeff = o.__add__(coeff) continue elif isinstance(o, MatrixExpr): # can't add 0 to Matrix so make sure coeff is not 0 extra.append(o) continue elif isinstance(o, TensExpr): coeff = o.__add__(coeff) if coeff else o continue elif o is S.ComplexInfinity: if coeff.is_finite is False and not extra: # we know for sure the result will be nan return [S.NaN], [], None coeff = S.ComplexInfinity continue # Add([...]) elif o.is_Add: # NB: here we assume Add is always commutative seq.extend(o.args) # TODO zerocopy? continue # Mul([...]) elif o.is_Mul: c, s = o.as_coeff_Mul() # check for unevaluated Pow, e.g. 2**3 or 2**(-1/2) elif o.is_Pow: b, e = o.as_base_exp() if b.is_Number and (e.is_Integer or (e.is_Rational and e.is_negative)): seq.append(b**e) continue c, s = S.One, o else: # everything else c = S.One s = o # now we have: # o = c*s, where # # c is a Number # s is an expression with number factor extracted # let's collect terms with the same s, so e.g. # 2*x**2 + 3*x**2 -> 5*x**2 if s in terms: terms[s] += c if terms[s] is S.NaN and not extra: # we know for sure the result will be nan return [S.NaN], [], None else: terms[s] = c # now let's construct new args: # [2*x**2, x**3, 7*x**4, pi, ...] newseq = [] noncommutative = False for s, c in terms.items(): # 0*s if c.is_zero: continue # 1*s elif c is S.One: newseq.append(s) # c*s else: if s.is_Mul: # Mul, already keeps its arguments in perfect order. # so we can simply put c in slot0 and go the fast way. cs = s._new_rawargs(*((c,) + s.args)) newseq.append(cs) elif s.is_Add: # we just re-create the unevaluated Mul newseq.append(Mul(c, s, evaluate=False)) else: # alternatively we have to call all Mul's machinery (slow) newseq.append(Mul(c, s)) noncommutative = noncommutative or not s.is_commutative # oo, -oo if coeff is S.Infinity: newseq = [f for f in newseq if not (f.is_extended_nonnegative or f.is_real)] elif coeff is S.NegativeInfinity: newseq = [f for f in newseq if not (f.is_extended_nonpositive or f.is_real)] if coeff is S.ComplexInfinity: # zoo might be # infinite_real + finite_im # finite_real + infinite_im # infinite_real + infinite_im # addition of a finite real or imaginary number won't be able to # change the zoo nature; adding an infinite qualtity would result # in a NaN condition if it had sign opposite of the infinite # portion of zoo, e.g., infinite_real - infinite_real. newseq = [c for c in newseq if not (c.is_finite and c.is_extended_real is not None)] # process O(x) if order_factors: newseq2 = [] for t in newseq: for o in order_factors: # x + O(x) -> O(x) if o.contains(t): t = None break # x + O(x**2) -> x + O(x**2) if t is not None: newseq2.append(t) newseq = newseq2 + order_factors # 1 + O(1) -> O(1) for o in order_factors: if o.contains(coeff): coeff = S.Zero break # order args canonically _addsort(newseq) # current code expects coeff to be first if coeff is not S.Zero: newseq.insert(0, coeff) if extra: newseq += extra noncommutative = True # we are done if noncommutative: return [], newseq, None else: return newseq, [], None @classmethod def class_key(cls): return 3, 1, cls.__name__ @property def kind(self): k = attrgetter('kind') kinds = map(k, self.args) kinds = frozenset(kinds) if len(kinds) != 1: # Since addition is group operator, kind must be same. # We know that this is unexpected signature, so return this. result = UndefinedKind else: result, = kinds return result def could_extract_minus_sign(self): return _could_extract_minus_sign(self) @cacheit def as_coeff_add(self, *deps): """ Returns a tuple (coeff, args) where self is treated as an Add and coeff is the Number term and args is a tuple of all other terms. Examples ======== >>> from sympy.abc import x >>> (7 + 3*x).as_coeff_add() (7, (3*x,)) >>> (7*x).as_coeff_add() (0, (7*x,)) """ if deps: l1, l2 = sift(self.args, lambda x: x.has_free(*deps), binary=True) return self._new_rawargs(*l2), tuple(l1) coeff, notrat = self.args[0].as_coeff_add() if coeff is not S.Zero: return coeff, notrat + self.args[1:] return S.Zero, self.args def as_coeff_Add(self, rational=False, deps=None): """ Efficiently extract the coefficient of a summation. """ coeff, args = self.args[0], self.args[1:] if coeff.is_Number and not rational or coeff.is_Rational: return coeff, self._new_rawargs(*args) return S.Zero, self # Note, we intentionally do not implement Add.as_coeff_mul(). Rather, we # let Expr.as_coeff_mul() just always return (S.One, self) for an Add. See # issue 5524. def _eval_power(self, e): from .evalf import pure_complex from .relational import is_eq if len(self.args) == 2 and any(_.is_infinite for _ in self.args): if e.is_zero is False and is_eq(e, S.One) is False: # looking for literal a + I*b a, b = self.args if a.coeff(S.ImaginaryUnit): a, b = b, a ico = b.coeff(S.ImaginaryUnit) if ico and ico.is_extended_real and a.is_extended_real: if e.is_extended_negative: return S.Zero if e.is_extended_positive: return S.ComplexInfinity return if e.is_Rational and self.is_number: ri = pure_complex(self) if ri: r, i = ri if e.q == 2: from sympy.functions.elementary.miscellaneous import sqrt D = sqrt(r**2 + i**2) if D.is_Rational: from .exprtools import factor_terms from sympy.functions.elementary.complexes import sign from .function import expand_multinomial # (r, i, D) is a Pythagorean triple root = sqrt(factor_terms((D - r)/2))**e.p return root*expand_multinomial(( # principle value (D + r)/abs(i) + sign(i)*S.ImaginaryUnit)**e.p) elif e == -1: return _unevaluated_Mul( r - i*S.ImaginaryUnit, 1/(r**2 + i**2)) elif e.is_Number and abs(e) != 1: # handle the Float case: (2.0 + 4*x)**e -> 4**e*(0.5 + x)**e c, m = zip(*[i.as_coeff_Mul() for i in self.args]) if any(i.is_Float for i in c): # XXX should this always be done? big = -1 for i in c: if abs(i) >= big: big = abs(i) if big > 0 and not equal_valued(big, 1): from sympy.functions.elementary.complexes import sign bigs = (big, -big) c = [sign(i) if i in bigs else i/big for i in c] addpow = Add(*[c*m for c, m in zip(c, m)])**e return big**e*addpow @cacheit def _eval_derivative(self, s): return self.func(*[a.diff(s) for a in self.args]) def _eval_nseries(self, x, n, logx, cdir=0): terms = [t.nseries(x, n=n, logx=logx, cdir=cdir) for t in self.args] return self.func(*terms) def _matches_simple(self, expr, repl_dict): # handle (w+3).matches('x+5') -> {w: x+2} coeff, terms = self.as_coeff_add() if len(terms) == 1: return terms[0].matches(expr - coeff, repl_dict) return def matches(self, expr, repl_dict=None, old=False): return self._matches_commutative(expr, repl_dict, old) @staticmethod def _combine_inverse(lhs, rhs): """ Returns lhs - rhs, but treats oo like a symbol so oo - oo returns 0, instead of a nan. """ from sympy.simplify.simplify import signsimp inf = (S.Infinity, S.NegativeInfinity) if lhs.has(*inf) or rhs.has(*inf): from .symbol import Dummy oo = Dummy('oo') reps = { S.Infinity: oo, S.NegativeInfinity: -oo} ireps = {v: k for k, v in reps.items()} eq = lhs.xreplace(reps) - rhs.xreplace(reps) if eq.has(oo): eq = eq.replace( lambda x: x.is_Pow and x.base is oo, lambda x: x.base) rv = eq.xreplace(ireps) else: rv = lhs - rhs srv = signsimp(rv) return srv if srv.is_Number else rv @cacheit def as_two_terms(self): """Return head and tail of self. This is the most efficient way to get the head and tail of an expression. - if you want only the head, use self.args[0]; - if you want to process the arguments of the tail then use self.as_coef_add() which gives the head and a tuple containing the arguments of the tail when treated as an Add. - if you want the coefficient when self is treated as a Mul then use self.as_coeff_mul()[0] >>> from sympy.abc import x, y >>> (3*x - 2*y + 5).as_two_terms() (5, 3*x - 2*y) """ return self.args[0], self._new_rawargs(*self.args[1:]) def as_numer_denom(self): """ Decomposes an expression to its numerator part and its denominator part. Examples ======== >>> from sympy.abc import x, y, z >>> (x*y/z).as_numer_denom() (x*y, z) >>> (x*(y + 1)/y**7).as_numer_denom() (x*(y + 1), y**7) See Also ======== sympy.core.expr.Expr.as_numer_denom """ # clear rational denominator content, expr = self.primitive() if not isinstance(expr, Add): return Mul(content, expr, evaluate=False).as_numer_denom() ncon, dcon = content.as_numer_denom() # collect numerators and denominators of the terms nd = defaultdict(list) for f in expr.args: ni, di = f.as_numer_denom() nd[di].append(ni) # check for quick exit if len(nd) == 1: d, n = nd.popitem() return self.func( *[_keep_coeff(ncon, ni) for ni in n]), _keep_coeff(dcon, d) # sum up the terms having a common denominator for d, n in nd.items(): if len(n) == 1: nd[d] = n[0] else: nd[d] = self.func(*n) # assemble single numerator and denominator denoms, numers = [list(i) for i in zip(*iter(nd.items()))] n, d = self.func(*[Mul(*(denoms[:i] + [numers[i]] + denoms[i + 1:])) for i in range(len(numers))]), Mul(*denoms) return _keep_coeff(ncon, n), _keep_coeff(dcon, d) def _eval_is_polynomial(self, syms): return all(term._eval_is_polynomial(syms) for term in self.args) def _eval_is_rational_function(self, syms): return all(term._eval_is_rational_function(syms) for term in self.args) def _eval_is_meromorphic(self, x, a): return _fuzzy_group((arg.is_meromorphic(x, a) for arg in self.args), quick_exit=True) def _eval_is_algebraic_expr(self, syms): return all(term._eval_is_algebraic_expr(syms) for term in self.args) # assumption methods _eval_is_real = lambda self: _fuzzy_group( (a.is_real for a in self.args), quick_exit=True) _eval_is_extended_real = lambda self: _fuzzy_group( (a.is_extended_real for a in self.args), quick_exit=True) _eval_is_complex = lambda self: _fuzzy_group( (a.is_complex for a in self.args), quick_exit=True) _eval_is_antihermitian = lambda self: _fuzzy_group( (a.is_antihermitian for a in self.args), quick_exit=True) _eval_is_finite = lambda self: _fuzzy_group( (a.is_finite for a in self.args), quick_exit=True) _eval_is_hermitian = lambda self: _fuzzy_group( (a.is_hermitian for a in self.args), quick_exit=True) _eval_is_integer = lambda self: _fuzzy_group( (a.is_integer for a in self.args), quick_exit=True) _eval_is_rational = lambda self: _fuzzy_group( (a.is_rational for a in self.args), quick_exit=True) _eval_is_algebraic = lambda self: _fuzzy_group( (a.is_algebraic for a in self.args), quick_exit=True) _eval_is_commutative = lambda self: _fuzzy_group( a.is_commutative for a in self.args) def _eval_is_infinite(self): sawinf = False for a in self.args: ainf = a.is_infinite if ainf is None: return None elif ainf is True: # infinite+infinite might not be infinite if sawinf is True: return None sawinf = True return sawinf def _eval_is_imaginary(self): nz = [] im_I = [] for a in self.args: if a.is_extended_real: if a.is_zero: pass elif a.is_zero is False: nz.append(a) else: return elif a.is_imaginary: im_I.append(a*S.ImaginaryUnit) elif (S.ImaginaryUnit*a).is_extended_real: im_I.append(a*S.ImaginaryUnit) else: return b = self.func(*nz) if b != self: if b.is_zero: return fuzzy_not(self.func(*im_I).is_zero) elif b.is_zero is False: return False def _eval_is_zero(self): if self.is_commutative is False: # issue 10528: there is no way to know if a nc symbol # is zero or not return nz = [] z = 0 im_or_z = False im = 0 for a in self.args: if a.is_extended_real: if a.is_zero: z += 1 elif a.is_zero is False: nz.append(a) else: return elif a.is_imaginary: im += 1 elif (S.ImaginaryUnit*a).is_extended_real: im_or_z = True else: return if z == len(self.args): return True if len(nz) in [0, len(self.args)]: return None b = self.func(*nz) if b.is_zero: if not im_or_z: if im == 0: return True elif im == 1: return False if b.is_zero is False: return False def _eval_is_odd(self): l = [f for f in self.args if not (f.is_even is True)] if not l: return False if l[0].is_odd: return self._new_rawargs(*l[1:]).is_even def _eval_is_irrational(self): for t in self.args: a = t.is_irrational if a: others = list(self.args) others.remove(t) if all(x.is_rational is True for x in others): return True return None if a is None: return return False def _all_nonneg_or_nonppos(self): nn = np = 0 for a in self.args: if a.is_nonnegative: if np: return False nn = 1 elif a.is_nonpositive: if nn: return False np = 1 else: break else: return True def _eval_is_extended_positive(self): if self.is_number: return super()._eval_is_extended_positive() c, a = self.as_coeff_Add() if not c.is_zero: from .exprtools import _monotonic_sign v = _monotonic_sign(a) if v is not None: s = v + c if s != self and s.is_extended_positive and a.is_extended_nonnegative: return True if len(self.free_symbols) == 1: v = _monotonic_sign(self) if v is not None and v != self and v.is_extended_positive: return True pos = nonneg = nonpos = unknown_sign = False saw_INF = set() args = [a for a in self.args if not a.is_zero] if not args: return False for a in args: ispos = a.is_extended_positive infinite = a.is_infinite if infinite: saw_INF.add(fuzzy_or((ispos, a.is_extended_nonnegative))) if True in saw_INF and False in saw_INF: return if ispos: pos = True continue elif a.is_extended_nonnegative: nonneg = True continue elif a.is_extended_nonpositive: nonpos = True continue if infinite is None: return unknown_sign = True if saw_INF: if len(saw_INF) > 1: return return saw_INF.pop() elif unknown_sign: return elif not nonpos and not nonneg and pos: return True elif not nonpos and pos: return True elif not pos and not nonneg: return False def _eval_is_extended_nonnegative(self): if not self.is_number: c, a = self.as_coeff_Add() if not c.is_zero and a.is_extended_nonnegative: from .exprtools import _monotonic_sign v = _monotonic_sign(a) if v is not None: s = v + c if s != self and s.is_extended_nonnegative: return True if len(self.free_symbols) == 1: v = _monotonic_sign(self) if v is not None and v != self and v.is_extended_nonnegative: return True def _eval_is_extended_nonpositive(self): if not self.is_number: c, a = self.as_coeff_Add() if not c.is_zero and a.is_extended_nonpositive: from .exprtools import _monotonic_sign v = _monotonic_sign(a) if v is not None: s = v + c if s != self and s.is_extended_nonpositive: return True if len(self.free_symbols) == 1: v = _monotonic_sign(self) if v is not None and v != self and v.is_extended_nonpositive: return True def _eval_is_extended_negative(self): if self.is_number: return super()._eval_is_extended_negative() c, a = self.as_coeff_Add() if not c.is_zero: from .exprtools import _monotonic_sign v = _monotonic_sign(a) if v is not None: s = v + c if s != self and s.is_extended_negative and a.is_extended_nonpositive: return True if len(self.free_symbols) == 1: v = _monotonic_sign(self) if v is not None and v != self and v.is_extended_negative: return True neg = nonpos = nonneg = unknown_sign = False saw_INF = set() args = [a for a in self.args if not a.is_zero] if not args: return False for a in args: isneg = a.is_extended_negative infinite = a.is_infinite if infinite: saw_INF.add(fuzzy_or((isneg, a.is_extended_nonpositive))) if True in saw_INF and False in saw_INF: return if isneg: neg = True continue elif a.is_extended_nonpositive: nonpos = True continue elif a.is_extended_nonnegative: nonneg = True continue if infinite is None: return unknown_sign = True if saw_INF: if len(saw_INF) > 1: return return saw_INF.pop() elif unknown_sign: return elif not nonneg and not nonpos and neg: return True elif not nonneg and neg: return True elif not neg and not nonpos: return False def _eval_subs(self, old, new): if not old.is_Add: if old is S.Infinity and -old in self.args: # foo - oo is foo + (-oo) internally return self.xreplace({-old: -new}) return None coeff_self, terms_self = self.as_coeff_Add() coeff_old, terms_old = old.as_coeff_Add() if coeff_self.is_Rational and coeff_old.is_Rational: if terms_self == terms_old: # (2 + a).subs( 3 + a, y) -> -1 + y return self.func(new, coeff_self, -coeff_old) if terms_self == -terms_old: # (2 + a).subs(-3 - a, y) -> -1 - y return self.func(-new, coeff_self, coeff_old) if coeff_self.is_Rational and coeff_old.is_Rational \ or coeff_self == coeff_old: args_old, args_self = self.func.make_args( terms_old), self.func.make_args(terms_self) if len(args_old) < len(args_self): # (a+b+c).subs(b+c,x) -> a+x self_set = set(args_self) old_set = set(args_old) if old_set < self_set: ret_set = self_set - old_set return self.func(new, coeff_self, -coeff_old, *[s._subs(old, new) for s in ret_set]) args_old = self.func.make_args( -terms_old) # (a+b+c+d).subs(-b-c,x) -> a-x+d old_set = set(args_old) if old_set < self_set: ret_set = self_set - old_set return self.func(-new, coeff_self, coeff_old, *[s._subs(old, new) for s in ret_set]) def removeO(self): args = [a for a in self.args if not a.is_Order] return self._new_rawargs(*args) def getO(self): args = [a for a in self.args if a.is_Order] if args: return self._new_rawargs(*args) @cacheit def extract_leading_order(self, symbols, point=None): """ Returns the leading term and its order. Examples ======== >>> from sympy.abc import x >>> (x + 1 + 1/x**5).extract_leading_order(x) ((x**(-5), O(x**(-5))),) >>> (1 + x).extract_leading_order(x) ((1, O(1)),) >>> (x + x**2).extract_leading_order(x) ((x, O(x)),) """ from sympy.series.order import Order lst = [] symbols = list(symbols if is_sequence(symbols) else [symbols]) if not point: point = [0]*len(symbols) seq = [(f, Order(f, *zip(symbols, point))) for f in self.args] for ef, of in seq: for e, o in lst: if o.contains(of) and o != of: of = None break if of is None: continue new_lst = [(ef, of)] for e, o in lst: if of.contains(o) and o != of: continue new_lst.append((e, o)) lst = new_lst return tuple(lst) def as_real_imag(self, deep=True, **hints): """ Return a tuple representing a complex number. Examples ======== >>> from sympy import I >>> (7 + 9*I).as_real_imag() (7, 9) >>> ((1 + I)/(1 - I)).as_real_imag() (0, 1) >>> ((1 + 2*I)*(1 + 3*I)).as_real_imag() (-5, 5) """ sargs = self.args re_part, im_part = [], [] for term in sargs: re, im = term.as_real_imag(deep=deep) re_part.append(re) im_part.append(im) return (self.func(*re_part), self.func(*im_part)) def _eval_as_leading_term(self, x, logx=None, cdir=0): from sympy.core.symbol import Dummy, Symbol from sympy.series.order import Order from sympy.functions.elementary.exponential import log from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold from .function import expand_mul o = self.getO() if o is None: o = Order(0) old = self.removeO() if old.has(Piecewise): old = piecewise_fold(old) # This expansion is the last part of expand_log. expand_log also calls # expand_mul with factor=True, which would be more expensive if any(isinstance(a, log) for a in self.args): logflags = dict(deep=True, log=True, mul=False, power_exp=False, power_base=False, multinomial=False, basic=False, force=False, factor=False) old = old.expand(**logflags) expr = expand_mul(old) if not expr.is_Add: return expr.as_leading_term(x, logx=logx, cdir=cdir) infinite = [t for t in expr.args if t.is_infinite] _logx = Dummy('logx') if logx is None else logx leading_terms = [t.as_leading_term(x, logx=_logx, cdir=cdir) for t in expr.args] min, new_expr = Order(0), 0 try: for term in leading_terms: order = Order(term, x) if not min or order not in min: min = order new_expr = term elif min in order: new_expr += term except TypeError: return expr if logx is None: new_expr = new_expr.subs(_logx, log(x)) is_zero = new_expr.is_zero if is_zero is None: new_expr = new_expr.trigsimp().cancel() is_zero = new_expr.is_zero if is_zero is True: # simple leading term analysis gave us cancelled terms but we have to send # back a term, so compute the leading term (via series) try: n0 = min.getn() except NotImplementedError: n0 = S.One if n0.has(Symbol): n0 = S.One res = Order(1) incr = S.One while res.is_Order: res = old._eval_nseries(x, n=n0+incr, logx=logx, cdir=cdir).cancel().powsimp().trigsimp() incr *= 2 return res.as_leading_term(x, logx=logx, cdir=cdir) elif new_expr is S.NaN: return old.func._from_args(infinite) + o else: return new_expr def _eval_adjoint(self): return self.func(*[t.adjoint() for t in self.args]) def _eval_conjugate(self): return self.func(*[t.conjugate() for t in self.args]) def _eval_transpose(self): return self.func(*[t.transpose() for t in self.args]) def primitive(self): """ Return ``(R, self/R)`` where ``R``` is the Rational GCD of ``self```. ``R`` is collected only from the leading coefficient of each term. Examples ======== >>> from sympy.abc import x, y >>> (2*x + 4*y).primitive() (2, x + 2*y) >>> (2*x/3 + 4*y/9).primitive() (2/9, 3*x + 2*y) >>> (2*x/3 + 4.2*y).primitive() (1/3, 2*x + 12.6*y) No subprocessing of term factors is performed: >>> ((2 + 2*x)*x + 2).primitive() (1, x*(2*x + 2) + 2) Recursive processing can be done with the ``as_content_primitive()`` method: >>> ((2 + 2*x)*x + 2).as_content_primitive() (2, x*(x + 1) + 1) See also: primitive() function in polytools.py """ terms = [] inf = False for a in self.args: c, m = a.as_coeff_Mul() if not c.is_Rational: c = S.One m = a inf = inf or m is S.ComplexInfinity terms.append((c.p, c.q, m)) if not inf: ngcd = reduce(igcd, [t[0] for t in terms], 0) dlcm = reduce(ilcm, [t[1] for t in terms], 1) else: ngcd = reduce(igcd, [t[0] for t in terms if t[1]], 0) dlcm = reduce(ilcm, [t[1] for t in terms if t[1]], 1) if ngcd == dlcm == 1: return S.One, self if not inf: for i, (p, q, term) in enumerate(terms): terms[i] = _keep_coeff(Rational((p//ngcd)*(dlcm//q)), term) else: for i, (p, q, term) in enumerate(terms): if q: terms[i] = _keep_coeff(Rational((p//ngcd)*(dlcm//q)), term) else: terms[i] = _keep_coeff(Rational(p, q), term) # we don't need a complete re-flattening since no new terms will join # so we just use the same sort as is used in Add.flatten. When the # coefficient changes, the ordering of terms may change, e.g. # (3*x, 6*y) -> (2*y, x) # # We do need to make sure that term[0] stays in position 0, however. # if terms[0].is_Number or terms[0] is S.ComplexInfinity: c = terms.pop(0) else: c = None _addsort(terms) if c: terms.insert(0, c) return Rational(ngcd, dlcm), self._new_rawargs(*terms) def as_content_primitive(self, radical=False, clear=True): """Return the tuple (R, self/R) where R is the positive Rational extracted from self. If radical is True (default is False) then common radicals will be removed and included as a factor of the primitive expression. Examples ======== >>> from sympy import sqrt >>> (3 + 3*sqrt(2)).as_content_primitive() (3, 1 + sqrt(2)) Radical content can also be factored out of the primitive: >>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True) (2, sqrt(2)*(1 + 2*sqrt(5))) See docstring of Expr.as_content_primitive for more examples. """ con, prim = self.func(*[_keep_coeff(*a.as_content_primitive( radical=radical, clear=clear)) for a in self.args]).primitive() if not clear and not con.is_Integer and prim.is_Add: con, d = con.as_numer_denom() _p = prim/d if any(a.as_coeff_Mul()[0].is_Integer for a in _p.args): prim = _p else: con /= d if radical and prim.is_Add: # look for common radicals that can be removed args = prim.args rads = [] common_q = None for m in args: term_rads = defaultdict(list) for ai in Mul.make_args(m): if ai.is_Pow: b, e = ai.as_base_exp() if e.is_Rational and b.is_Integer: term_rads[e.q].append(abs(int(b))**e.p) if not term_rads: break if common_q is None: common_q = set(term_rads.keys()) else: common_q = common_q & set(term_rads.keys()) if not common_q: break rads.append(term_rads) else: # process rads # keep only those in common_q for r in rads: for q in list(r.keys()): if q not in common_q: r.pop(q) for q in r: r[q] = Mul(*r[q]) # find the gcd of bases for each q G = [] for q in common_q: g = reduce(igcd, [r[q] for r in rads], 0) if g != 1: G.append(g**Rational(1, q)) if G: G = Mul(*G) args = [ai/G for ai in args] prim = G*prim.func(*args) return con, prim @property def _sorted_args(self): from .sorting import default_sort_key return tuple(sorted(self.args, key=default_sort_key)) def _eval_difference_delta(self, n, step): from sympy.series.limitseq import difference_delta as dd return self.func(*[dd(a, n, step) for a in self.args]) @property def _mpc_(self): """ Convert self to an mpmath mpc if possible """ from .numbers import Float re_part, rest = self.as_coeff_Add() im_part, imag_unit = rest.as_coeff_Mul() if not imag_unit == S.ImaginaryUnit: # ValueError may seem more reasonable but since it's a @property, # we need to use AttributeError to keep from confusing things like # hasattr. raise AttributeError("Cannot convert Add to mpc. Must be of the form Number + Number*I") return (Float(re_part)._mpf_, Float(im_part)._mpf_) def __neg__(self): if not global_parameters.distribute: return super().__neg__() return Mul(S.NegativeOne, self) add = AssocOpDispatcher('add') from .mul import Mul, _keep_coeff, _unevaluated_Mul from .numbers import Rational
b2e8f2b79b7da1fc061f9dc85d84418710c4078980c6c6eb127b517555792e58
from __future__ import annotations from typing import TYPE_CHECKING from collections.abc import Iterable from functools import reduce import re from .sympify import sympify, _sympify from .basic import Basic, Atom from .singleton import S from .evalf import EvalfMixin, pure_complex, DEFAULT_MAXPREC from .decorators import call_highest_priority, sympify_method_args, sympify_return from .cache import cacheit from .sorting import default_sort_key from .kind import NumberKind from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.misc import as_int, func_name, filldedent from sympy.utilities.iterables import has_variety, sift from mpmath.libmp import mpf_log, prec_to_dps from mpmath.libmp.libintmath import giant_steps if TYPE_CHECKING: from .numbers import Number from collections import defaultdict def _corem(eq, c): # helper for extract_additively # return co, diff from co*c + diff co = [] non = [] for i in Add.make_args(eq): ci = i.coeff(c) if not ci: non.append(i) else: co.append(ci) return Add(*co), Add(*non) @sympify_method_args class Expr(Basic, EvalfMixin): """ Base class for algebraic expressions. Explanation =========== Everything that requires arithmetic operations to be defined should subclass this class, instead of Basic (which should be used only for argument storage and expression manipulation, i.e. pattern matching, substitutions, etc). If you want to override the comparisons of expressions: Should use _eval_is_ge for inequality, or _eval_is_eq, with multiple dispatch. _eval_is_ge return true if x >= y, false if x < y, and None if the two types are not comparable or the comparison is indeterminate See Also ======== sympy.core.basic.Basic """ __slots__: tuple[str, ...] = () is_scalar = True # self derivative is 1 @property def _diff_wrt(self): """Return True if one can differentiate with respect to this object, else False. Explanation =========== Subclasses such as Symbol, Function and Derivative return True to enable derivatives wrt them. The implementation in Derivative separates the Symbol and non-Symbol (_diff_wrt=True) variables and temporarily converts the non-Symbols into Symbols when performing the differentiation. By default, any object deriving from Expr will behave like a scalar with self.diff(self) == 1. If this is not desired then the object must also set `is_scalar = False` or else define an _eval_derivative routine. Note, see the docstring of Derivative for how this should work mathematically. In particular, note that expr.subs(yourclass, Symbol) should be well-defined on a structural level, or this will lead to inconsistent results. Examples ======== >>> from sympy import Expr >>> e = Expr() >>> e._diff_wrt False >>> class MyScalar(Expr): ... _diff_wrt = True ... >>> MyScalar().diff(MyScalar()) 1 >>> class MySymbol(Expr): ... _diff_wrt = True ... is_scalar = False ... >>> MySymbol().diff(MySymbol()) Derivative(MySymbol(), MySymbol()) """ return False @cacheit def sort_key(self, order=None): coeff, expr = self.as_coeff_Mul() if expr.is_Pow: if expr.base is S.Exp1: # If we remove this, many doctests will go crazy: # (keeps E**x sorted like the exp(x) function, # part of exp(x) to E**x transition) expr, exp = Function("exp")(expr.exp), S.One else: expr, exp = expr.args else: exp = S.One if expr.is_Dummy: args = (expr.sort_key(),) elif expr.is_Atom: args = (str(expr),) else: if expr.is_Add: args = expr.as_ordered_terms(order=order) elif expr.is_Mul: args = expr.as_ordered_factors(order=order) else: args = expr.args args = tuple( [ default_sort_key(arg, order=order) for arg in args ]) args = (len(args), tuple(args)) exp = exp.sort_key(order=order) return expr.class_key(), args, exp, coeff def _hashable_content(self): """Return a tuple of information about self that can be used to compute the hash. If a class defines additional attributes, like ``name`` in Symbol, then this method should be updated accordingly to return such relevant attributes. Defining more than _hashable_content is necessary if __eq__ has been defined by a class. See note about this in Basic.__eq__.""" return self._args # *************** # * Arithmetics * # *************** # Expr and its subclasses 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) -> Expr: from sympy.functions.elementary.complexes import Abs return Abs(self) @sympify_return([('other', 'Expr')], NotImplemented) @call_highest_priority('__radd__') def __add__(self, other): return Add(self, other) @sympify_return([('other', 'Expr')], NotImplemented) @call_highest_priority('__add__') def __radd__(self, other): return Add(other, self) @sympify_return([('other', 'Expr')], NotImplemented) @call_highest_priority('__rsub__') def __sub__(self, other): return Add(self, -other) @sympify_return([('other', 'Expr')], NotImplemented) @call_highest_priority('__sub__') def __rsub__(self, other): return Add(other, -self) @sympify_return([('other', 'Expr')], NotImplemented) @call_highest_priority('__rmul__') def __mul__(self, other): return Mul(self, other) @sympify_return([('other', 'Expr')], NotImplemented) @call_highest_priority('__mul__') def __rmul__(self, other): return Mul(other, self) @sympify_return([('other', 'Expr')], NotImplemented) @call_highest_priority('__rpow__') def _pow(self, other): return Pow(self, other) def __pow__(self, other, mod=None) -> Expr: 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 _sympify(pow(_self, other, mod)) else: from .numbers import mod_inverse return _sympify(mod_inverse(pow(_self, -other, mod), mod)) except ValueError: power = self._pow(other) try: return power%mod except TypeError: return NotImplemented @sympify_return([('other', 'Expr')], NotImplemented) @call_highest_priority('__pow__') def __rpow__(self, other): return Pow(other, self) @sympify_return([('other', 'Expr')], NotImplemented) @call_highest_priority('__rtruediv__') def __truediv__(self, other): denom = Pow(other, S.NegativeOne) if self is S.One: return denom else: return Mul(self, denom) @sympify_return([('other', 'Expr')], NotImplemented) @call_highest_priority('__truediv__') def __rtruediv__(self, other): denom = Pow(self, S.NegativeOne) if other is S.One: return denom else: return Mul(other, denom) @sympify_return([('other', 'Expr')], NotImplemented) @call_highest_priority('__rmod__') def __mod__(self, other): return Mod(self, other) @sympify_return([('other', 'Expr')], NotImplemented) @call_highest_priority('__mod__') def __rmod__(self, other): return Mod(other, self) @sympify_return([('other', 'Expr')], NotImplemented) @call_highest_priority('__rfloordiv__') def __floordiv__(self, other): from sympy.functions.elementary.integers import floor return floor(self / other) @sympify_return([('other', 'Expr')], NotImplemented) @call_highest_priority('__floordiv__') def __rfloordiv__(self, other): from sympy.functions.elementary.integers import floor return floor(other / self) @sympify_return([('other', 'Expr')], NotImplemented) @call_highest_priority('__rdivmod__') def __divmod__(self, other): from sympy.functions.elementary.integers import floor return floor(self / other), Mod(self, other) @sympify_return([('other', 'Expr')], NotImplemented) @call_highest_priority('__divmod__') def __rdivmod__(self, other): from sympy.functions.elementary.integers import floor return floor(other / self), Mod(other, self) def __int__(self): # Although we only need to round to the units position, we'll # get one more digit so the extra testing below can be avoided # unless the rounded value rounded to an integer, e.g. if an # expression were equal to 1.9 and we rounded to the unit position # we would get a 2 and would not know if this rounded up or not # without doing a test (as done below). But if we keep an extra # digit we know that 1.9 is not the same as 1 and there is no # need for further testing: our int value is correct. If the value # were 1.99, however, this would round to 2.0 and our int value is # off by one. So...if our round value is the same as the int value # (regardless of how much extra work we do to calculate extra decimal # places) we need to test whether we are off by one. from .symbol import Dummy if not self.is_number: raise TypeError("Cannot convert symbols to int") r = self.round(2) if not r.is_Number: raise TypeError("Cannot convert complex to int") if r in (S.NaN, S.Infinity, S.NegativeInfinity): raise TypeError("Cannot convert %s to int" % r) i = int(r) if not i: return 0 # off-by-one check if i == r and not (self - i).equals(0): isign = 1 if i > 0 else -1 x = Dummy() # in the following (self - i).evalf(2) will not always work while # (self - r).evalf(2) and the use of subs does; if the test that # was added when this comment was added passes, it might be safe # to simply use sign to compute this rather than doing this by hand: diff_sign = 1 if (self - x).evalf(2, subs={x: i}) > 0 else -1 if diff_sign != isign: i -= isign return i def __float__(self): # Don't bother testing if it's a number; if it's not this is going # to fail, and if it is we still need to check that it evalf'ed to # a number. result = self.evalf() if result.is_Number: return float(result) if result.is_number and result.as_real_imag()[1]: raise TypeError("Cannot convert complex to float") raise TypeError("Cannot convert expression to float") def __complex__(self): result = self.evalf() re, im = result.as_real_imag() return complex(float(re), float(im)) @sympify_return([('other', 'Expr')], NotImplemented) def __ge__(self, other): from .relational import GreaterThan return GreaterThan(self, other) @sympify_return([('other', 'Expr')], NotImplemented) def __le__(self, other): from .relational import LessThan return LessThan(self, other) @sympify_return([('other', 'Expr')], NotImplemented) def __gt__(self, other): from .relational import StrictGreaterThan return StrictGreaterThan(self, other) @sympify_return([('other', 'Expr')], NotImplemented) def __lt__(self, other): from .relational import StrictLessThan return StrictLessThan(self, other) def __trunc__(self): if not self.is_number: raise TypeError("Cannot truncate symbols and expressions") else: return Integer(self) def __format__(self, format_spec: str): if self.is_number: mt = re.match(r'\+?\d*\.(\d+)f', format_spec) if mt: prec = int(mt.group(1)) rounded = self.round(prec) if rounded.is_Integer: return format(int(rounded), format_spec) if rounded.is_Float: return format(rounded, format_spec) return super().__format__(format_spec) @staticmethod def _from_mpmath(x, prec): if hasattr(x, "_mpf_"): return Float._new(x._mpf_, prec) elif hasattr(x, "_mpc_"): re, im = x._mpc_ re = Float._new(re, prec) im = Float._new(im, prec)*S.ImaginaryUnit return re + im else: raise TypeError("expected mpmath number (mpf or mpc)") @property def is_number(self): """Returns True if ``self`` has no free symbols and no undefined functions (AppliedUndef, to be precise). It will be faster than ``if not self.free_symbols``, however, since ``is_number`` will fail as soon as it hits a free symbol or undefined function. Examples ======== >>> from sympy import Function, Integral, cos, sin, pi >>> from sympy.abc import x >>> f = Function('f') >>> x.is_number False >>> f(1).is_number False >>> (2*x).is_number False >>> (2 + Integral(2, x)).is_number False >>> (2 + Integral(2, (x, 1, 2))).is_number True Not all numbers are Numbers in the SymPy sense: >>> pi.is_number, pi.is_Number (True, False) If something is a number it should evaluate to a number with real and imaginary parts that are Numbers; the result may not be comparable, however, since the real and/or imaginary part of the result may not have precision. >>> cos(1).is_number and cos(1).is_comparable True >>> z = cos(1)**2 + sin(1)**2 - 1 >>> z.is_number True >>> z.is_comparable False See Also ======== sympy.core.basic.Basic.is_comparable """ return all(obj.is_number for obj in self.args) def _random(self, n=None, re_min=-1, im_min=-1, re_max=1, im_max=1): """Return self evaluated, if possible, replacing free symbols with random complex values, if necessary. Explanation =========== The random complex value for each free symbol is generated by the random_complex_number routine giving real and imaginary parts in the range given by the re_min, re_max, im_min, and im_max values. The returned value is evaluated to a precision of n (if given) else the maximum of 15 and the precision needed to get more than 1 digit of precision. If the expression could not be evaluated to a number, or could not be evaluated to more than 1 digit of precision, then None is returned. Examples ======== >>> from sympy import sqrt >>> from sympy.abc import x, y >>> x._random() # doctest: +SKIP 0.0392918155679172 + 0.916050214307199*I >>> x._random(2) # doctest: +SKIP -0.77 - 0.87*I >>> (x + y/2)._random(2) # doctest: +SKIP -0.57 + 0.16*I >>> sqrt(2)._random(2) 1.4 See Also ======== sympy.core.random.random_complex_number """ free = self.free_symbols prec = 1 if free: from sympy.core.random import random_complex_number a, c, b, d = re_min, re_max, im_min, im_max reps = dict(list(zip(free, [random_complex_number(a, b, c, d, rational=True) for zi in free]))) try: nmag = abs(self.evalf(2, subs=reps)) except (ValueError, TypeError): # if an out of range value resulted in evalf problems # then return None -- XXX is there a way to know how to # select a good random number for a given expression? # e.g. when calculating n! negative values for n should not # be used return None else: reps = {} nmag = abs(self.evalf(2)) if not hasattr(nmag, '_prec'): # e.g. exp_polar(2*I*pi) doesn't evaluate but is_number is True return None if nmag._prec == 1: # increase the precision up to the default maximum # precision to see if we can get any significance # evaluate for prec in giant_steps(2, DEFAULT_MAXPREC): nmag = abs(self.evalf(prec, subs=reps)) if nmag._prec != 1: break if nmag._prec != 1: if n is None: n = max(prec, 15) return self.evalf(n, subs=reps) # never got any significance return None def is_constant(self, *wrt, **flags): """Return True if self is constant, False if not, or None if the constancy could not be determined conclusively. Explanation =========== If an expression has no free symbols then it is a constant. If there are free symbols it is possible that the expression is a constant, perhaps (but not necessarily) zero. To test such expressions, a few strategies are tried: 1) numerical evaluation at two random points. If two such evaluations give two different values and the values have a precision greater than 1 then self is not constant. If the evaluations agree or could not be obtained with any precision, no decision is made. The numerical testing is done only if ``wrt`` is different than the free symbols. 2) differentiation with respect to variables in 'wrt' (or all free symbols if omitted) to see if the expression is constant or not. This will not always lead to an expression that is zero even though an expression is constant (see added test in test_expr.py). If all derivatives are zero then self is constant with respect to the given symbols. 3) finding out zeros of denominator expression with free_symbols. It will not be constant if there are zeros. It gives more negative answers for expression that are not constant. If neither evaluation nor differentiation can prove the expression is constant, None is returned unless two numerical values happened to be the same and the flag ``failing_number`` is True -- in that case the numerical value will be returned. If flag simplify=False is passed, self will not be simplified; the default is True since self should be simplified before testing. Examples ======== >>> from sympy import cos, sin, Sum, S, pi >>> from sympy.abc import a, n, x, y >>> x.is_constant() False >>> S(2).is_constant() True >>> Sum(x, (x, 1, 10)).is_constant() True >>> Sum(x, (x, 1, n)).is_constant() False >>> Sum(x, (x, 1, n)).is_constant(y) True >>> Sum(x, (x, 1, n)).is_constant(n) False >>> Sum(x, (x, 1, n)).is_constant(x) True >>> eq = a*cos(x)**2 + a*sin(x)**2 - a >>> eq.is_constant() True >>> eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0 True >>> (0**x).is_constant() False >>> x.is_constant() False >>> (x**x).is_constant() False >>> one = cos(x)**2 + sin(x)**2 >>> one.is_constant() True >>> ((one - 1)**(x + 1)).is_constant() in (True, False) # could be 0 or 1 True """ def check_denominator_zeros(expression): from sympy.solvers.solvers import denoms retNone = False for den in denoms(expression): z = den.is_zero if z is True: return True if z is None: retNone = True if retNone: return None return False simplify = flags.get('simplify', True) if self.is_number: return True free = self.free_symbols if not free: return True # assume f(1) is some constant # if we are only interested in some symbols and they are not in the # free symbols then this expression is constant wrt those symbols wrt = set(wrt) if wrt and not wrt & free: return True wrt = wrt or free # simplify unless this has already been done expr = self if simplify: expr = expr.simplify() # is_zero should be a quick assumptions check; it can be wrong for # numbers (see test_is_not_constant test), giving False when it # shouldn't, but hopefully it will never give True unless it is sure. if expr.is_zero: return True # Don't attempt substitution or differentiation with non-number symbols wrt_number = {sym for sym in wrt if sym.kind is NumberKind} # try numerical evaluation to see if we get two different values failing_number = None if wrt_number == free: # try 0 (for a) and 1 (for b) try: a = expr.subs(list(zip(free, [0]*len(free))), simultaneous=True) if a is S.NaN: # evaluation may succeed when substitution fails a = expr._random(None, 0, 0, 0, 0) except ZeroDivisionError: a = None if a is not None and a is not S.NaN: try: b = expr.subs(list(zip(free, [1]*len(free))), simultaneous=True) if b is S.NaN: # evaluation may succeed when substitution fails b = expr._random(None, 1, 0, 1, 0) except ZeroDivisionError: b = None if b is not None and b is not S.NaN and b.equals(a) is False: return False # try random real b = expr._random(None, -1, 0, 1, 0) if b is not None and b is not S.NaN and b.equals(a) is False: return False # try random complex b = expr._random() if b is not None and b is not S.NaN: if b.equals(a) is False: return False failing_number = a if a.is_number else b # now we will test each wrt symbol (or all free symbols) to see if the # expression depends on them or not using differentiation. This is # not sufficient for all expressions, however, so we don't return # False if we get a derivative other than 0 with free symbols. for w in wrt_number: deriv = expr.diff(w) if simplify: deriv = deriv.simplify() if deriv != 0: if not (pure_complex(deriv, or_real=True)): if flags.get('failing_number', False): return failing_number return False cd = check_denominator_zeros(self) if cd is True: return False elif cd is None: return None return True def equals(self, other, failing_expression=False): """Return True if self == other, False if it does not, or None. If failing_expression is True then the expression which did not simplify to a 0 will be returned instead of None. Explanation =========== If ``self`` is a Number (or complex number) that is not zero, then the result is False. If ``self`` is a number and has not evaluated to zero, evalf will be used to test whether the expression evaluates to zero. If it does so and the result has significance (i.e. the precision is either -1, for a Rational result, or is greater than 1) then the evalf value will be used to return True or False. """ from sympy.simplify.simplify import nsimplify, simplify from sympy.solvers.solvers import solve from sympy.polys.polyerrors import NotAlgebraic from sympy.polys.numberfields import minimal_polynomial other = sympify(other) if self == other: return True # they aren't the same so see if we can make the difference 0; # don't worry about doing simplification steps one at a time # because if the expression ever goes to 0 then the subsequent # simplification steps that are done will be very fast. diff = factor_terms(simplify(self - other), radical=True) if not diff: return True if not diff.has(Add, Mod): # if there is no expanding to be done after simplifying # then this can't be a zero return False factors = diff.as_coeff_mul()[1] if len(factors) > 1: # avoid infinity recursion fac_zero = [fac.equals(0) for fac in factors] if None not in fac_zero: # every part can be decided return any(fac_zero) constant = diff.is_constant(simplify=False, failing_number=True) if constant is False: return False if not diff.is_number: if constant is None: # e.g. unless the right simplification is done, a symbolic # zero is possible (see expression of issue 6829: without # simplification constant will be None). return if constant is True: # this gives a number whether there are free symbols or not ndiff = diff._random() # is_comparable will work whether the result is real # or complex; it could be None, however. if ndiff and ndiff.is_comparable: return False # sometimes we can use a simplified result to give a clue as to # what the expression should be; if the expression is *not* zero # then we should have been able to compute that and so now # we can just consider the cases where the approximation appears # to be zero -- we try to prove it via minimal_polynomial. # # removed # ns = nsimplify(diff) # if diff.is_number and (not ns or ns == diff): # # The thought was that if it nsimplifies to 0 that's a sure sign # to try the following to prove it; or if it changed but wasn't # zero that might be a sign that it's not going to be easy to # prove. But tests seem to be working without that logic. # if diff.is_number: # try to prove via self-consistency surds = [s for s in diff.atoms(Pow) if s.args[0].is_Integer] # it seems to work better to try big ones first surds.sort(key=lambda x: -x.args[0]) for s in surds: try: # simplify is False here -- this expression has already # been identified as being hard to identify as zero; # we will handle the checking ourselves using nsimplify # to see if we are in the right ballpark or not and if so # *then* the simplification will be attempted. sol = solve(diff, s, simplify=False) if sol: if s in sol: # the self-consistent result is present return True if all(si.is_Integer for si in sol): # perfect powers are removed at instantiation # so surd s cannot be an integer return False if all(i.is_algebraic is False for i in sol): # a surd is algebraic return False if any(si in surds for si in sol): # it wasn't equal to s but it is in surds # and different surds are not equal return False if any(nsimplify(s - si) == 0 and simplify(s - si) == 0 for si in sol): return True if s.is_real: if any(nsimplify(si, [s]) == s and simplify(si) == s for si in sol): return True except NotImplementedError: pass # try to prove with minimal_polynomial but know when # *not* to use this or else it can take a long time. e.g. issue 8354 if True: # change True to condition that assures non-hang try: mp = minimal_polynomial(diff) if mp.is_Symbol: return True return False except (NotAlgebraic, NotImplementedError): pass # diff has not simplified to zero; constant is either None, True # or the number with significance (is_comparable) that was randomly # calculated twice as the same value. if constant not in (True, None) and constant != 0: return False if failing_expression: return diff return None def _eval_is_extended_positive_negative(self, positive): from sympy.polys.numberfields import minimal_polynomial from sympy.polys.polyerrors import NotAlgebraic if self.is_number: # check to see that we can get a value try: n2 = self._eval_evalf(2) # XXX: This shouldn't be caught here # Catches ValueError: hypsum() failed to converge to the requested # 34 bits of accuracy except ValueError: return None if n2 is None: return None if getattr(n2, '_prec', 1) == 1: # no significance return None if n2 is S.NaN: return None f = self.evalf(2) if f.is_Float: match = f, S.Zero else: match = pure_complex(f) if match is None: return False r, i = match if not (i.is_Number and r.is_Number): return False if r._prec != 1 and i._prec != 1: return bool(not i and ((r > 0) if positive else (r < 0))) elif r._prec == 1 and (not i or i._prec == 1) and \ self._eval_is_algebraic() and not self.has(Function): try: if minimal_polynomial(self).is_Symbol: return False except (NotAlgebraic, NotImplementedError): pass def _eval_is_extended_positive(self): return self._eval_is_extended_positive_negative(positive=True) def _eval_is_extended_negative(self): return self._eval_is_extended_positive_negative(positive=False) def _eval_interval(self, x, a, b): """ Returns evaluation over an interval. For most functions this is: self.subs(x, b) - self.subs(x, a), possibly using limit() if NaN is returned from subs, or if singularities are found between a and b. If b or a is None, it only evaluates -self.subs(x, a) or self.subs(b, x), respectively. """ from sympy.calculus.accumulationbounds import AccumBounds from sympy.functions.elementary.exponential import log from sympy.series.limits import limit, Limit from sympy.sets.sets import Interval from sympy.solvers.solveset import solveset if (a is None and b is None): raise ValueError('Both interval ends cannot be None.') def _eval_endpoint(left): c = a if left else b if c is None: return S.Zero else: C = self.subs(x, c) if C.has(S.NaN, S.Infinity, S.NegativeInfinity, S.ComplexInfinity, AccumBounds): if (a < b) != False: C = limit(self, x, c, "+" if left else "-") else: C = limit(self, x, c, "-" if left else "+") if isinstance(C, Limit): raise NotImplementedError("Could not compute limit") return C if a == b: return S.Zero A = _eval_endpoint(left=True) if A is S.NaN: return A B = _eval_endpoint(left=False) if (a and b) is None: return B - A value = B - A if a.is_comparable and b.is_comparable: if a < b: domain = Interval(a, b) else: domain = Interval(b, a) # check the singularities of self within the interval # if singularities is a ConditionSet (not iterable), catch the exception and pass singularities = solveset(self.cancel().as_numer_denom()[1], x, domain=domain) for logterm in self.atoms(log): singularities = singularities | solveset(logterm.args[0], x, domain=domain) try: for s in singularities: if value is S.NaN: # no need to keep adding, it will stay NaN break if not s.is_comparable: continue if (a < s) == (s < b) == True: value += -limit(self, x, s, "+") + limit(self, x, s, "-") elif (b < s) == (s < a) == True: value += limit(self, x, s, "+") - limit(self, x, s, "-") except TypeError: pass return value def _eval_power(self, other): # subclass to compute self**other for cases when # other is not NaN, 0, or 1 return None def _eval_conjugate(self): if self.is_extended_real: return self elif self.is_imaginary: return -self def conjugate(self): """Returns the complex conjugate of 'self'.""" from sympy.functions.elementary.complexes import conjugate as c return c(self) def dir(self, x, cdir): if self.is_zero: return S.Zero from sympy.functions.elementary.exponential import log minexp = S.Zero arg = self while arg: minexp += S.One arg = arg.diff(x) coeff = arg.subs(x, 0) if coeff is S.NaN: coeff = arg.limit(x, 0) if coeff is S.ComplexInfinity: try: coeff, _ = arg.leadterm(x) if coeff.has(log(x)): raise ValueError() except ValueError: coeff = arg.limit(x, 0) if coeff != S.Zero: break return coeff*cdir**minexp def _eval_transpose(self): from sympy.functions.elementary.complexes import conjugate if (self.is_complex or self.is_infinite): return self elif self.is_hermitian: return conjugate(self) elif self.is_antihermitian: return -conjugate(self) def transpose(self): from sympy.functions.elementary.complexes import transpose return transpose(self) def _eval_adjoint(self): from sympy.functions.elementary.complexes import conjugate, transpose if self.is_hermitian: return self elif self.is_antihermitian: return -self obj = self._eval_conjugate() if obj is not None: return transpose(obj) obj = self._eval_transpose() if obj is not None: return conjugate(obj) def adjoint(self): from sympy.functions.elementary.complexes import adjoint return adjoint(self) @classmethod def _parse_order(cls, order): """Parse and configure the ordering of terms. """ from sympy.polys.orderings import monomial_key startswith = getattr(order, "startswith", None) if startswith is None: reverse = False else: reverse = startswith('rev-') if reverse: order = order[4:] monom_key = monomial_key(order) def neg(monom): return tuple([neg(m) if isinstance(m, tuple) else -m for m in monom]) def key(term): _, ((re, im), monom, ncpart) = term monom = neg(monom_key(monom)) ncpart = tuple([e.sort_key(order=order) for e in ncpart]) coeff = ((bool(im), im), (re, im)) return monom, ncpart, coeff return key, reverse def as_ordered_factors(self, order=None): """Return list of ordered factors (if Mul) else [self].""" return [self] def as_poly(self, *gens, **args): """Converts ``self`` to a polynomial or returns ``None``. Explanation =========== >>> from sympy import sin >>> from sympy.abc import x, y >>> print((x**2 + x*y).as_poly()) Poly(x**2 + x*y, x, y, domain='ZZ') >>> print((x**2 + x*y).as_poly(x, y)) Poly(x**2 + x*y, x, y, domain='ZZ') >>> print((x**2 + sin(y)).as_poly(x, y)) None """ from sympy.polys.polyerrors import PolynomialError, GeneratorsNeeded from sympy.polys.polytools import Poly try: poly = Poly(self, *gens, **args) if not poly.is_Poly: return None else: return poly except (PolynomialError, GeneratorsNeeded): # PolynomialError is caught for e.g. exp(x).as_poly(x) # GeneratorsNeeded is caught for e.g. S(2).as_poly() return None def as_ordered_terms(self, order=None, data=False): """ Transform an expression to an ordered list of terms. Examples ======== >>> from sympy import sin, cos >>> from sympy.abc import x >>> (sin(x)**2*cos(x) + sin(x)**2 + 1).as_ordered_terms() [sin(x)**2*cos(x), sin(x)**2, 1] """ from .numbers import Number, NumberSymbol if order is None and self.is_Add: # Spot the special case of Add(Number, Mul(Number, expr)) with the # first number positive and the second number negative key = lambda x:not isinstance(x, (Number, NumberSymbol)) add_args = sorted(Add.make_args(self), key=key) if (len(add_args) == 2 and isinstance(add_args[0], (Number, NumberSymbol)) and isinstance(add_args[1], Mul)): mul_args = sorted(Mul.make_args(add_args[1]), key=key) if (len(mul_args) == 2 and isinstance(mul_args[0], Number) and add_args[0].is_positive and mul_args[0].is_negative): return add_args key, reverse = self._parse_order(order) terms, gens = self.as_terms() if not any(term.is_Order for term, _ in terms): ordered = sorted(terms, key=key, reverse=reverse) else: _terms, _order = [], [] for term, repr in terms: if not term.is_Order: _terms.append((term, repr)) else: _order.append((term, repr)) ordered = sorted(_terms, key=key, reverse=True) \ + sorted(_order, key=key, reverse=True) if data: return ordered, gens else: return [term for term, _ in ordered] def as_terms(self): """Transform an expression to a list of terms. """ from .exprtools import decompose_power gens, terms = set(), [] for term in Add.make_args(self): coeff, _term = term.as_coeff_Mul() coeff = complex(coeff) cpart, ncpart = {}, [] if _term is not S.One: for factor in Mul.make_args(_term): if factor.is_number: try: coeff *= complex(factor) except (TypeError, ValueError): pass else: continue if factor.is_commutative: base, exp = decompose_power(factor) cpart[base] = exp gens.add(base) else: ncpart.append(factor) coeff = coeff.real, coeff.imag ncpart = tuple(ncpart) terms.append((term, (coeff, cpart, ncpart))) gens = sorted(gens, key=default_sort_key) k, indices = len(gens), {} for i, g in enumerate(gens): indices[g] = i result = [] for term, (coeff, cpart, ncpart) in terms: monom = [0]*k for base, exp in cpart.items(): monom[indices[base]] = exp result.append((term, (coeff, tuple(monom), ncpart))) return result, gens def removeO(self): """Removes the additive O(..) symbol if there is one""" return self def getO(self): """Returns the additive O(..) symbol if there is one, else None.""" return None def getn(self): """ Returns the order of the expression. Explanation =========== The order is determined either from the O(...) term. If there is no O(...) term, it returns None. Examples ======== >>> from sympy import O >>> from sympy.abc import x >>> (1 + x + O(x**2)).getn() 2 >>> (1 + x).getn() """ o = self.getO() if o is None: return None elif o.is_Order: o = o.expr if o is S.One: return S.Zero if o.is_Symbol: return S.One if o.is_Pow: return o.args[1] if o.is_Mul: # x**n*log(x)**n or x**n/log(x)**n for oi in o.args: if oi.is_Symbol: return S.One if oi.is_Pow: from .symbol import Dummy, Symbol syms = oi.atoms(Symbol) if len(syms) == 1: x = syms.pop() oi = oi.subs(x, Dummy('x', positive=True)) if oi.base.is_Symbol and oi.exp.is_Rational: return abs(oi.exp) raise NotImplementedError('not sure of order of %s' % o) def count_ops(self, visual=None): from .function import count_ops return count_ops(self, visual) def args_cnc(self, cset=False, warn=True, split_1=True): """Return [commutative factors, non-commutative factors] of self. Explanation =========== self is treated as a Mul and the ordering of the factors is maintained. If ``cset`` is True the commutative factors will be returned in a set. If there were repeated factors (as may happen with an unevaluated Mul) then an error will be raised unless it is explicitly suppressed by setting ``warn`` to False. Note: -1 is always separated from a Number unless split_1 is False. Examples ======== >>> from sympy import symbols, oo >>> A, B = symbols('A B', commutative=0) >>> x, y = symbols('x y') >>> (-2*x*y).args_cnc() [[-1, 2, x, y], []] >>> (-2.5*x).args_cnc() [[-1, 2.5, x], []] >>> (-2*x*A*B*y).args_cnc() [[-1, 2, x, y], [A, B]] >>> (-2*x*A*B*y).args_cnc(split_1=False) [[-2, x, y], [A, B]] >>> (-2*x*y).args_cnc(cset=True) [{-1, 2, x, y}, []] The arg is always treated as a Mul: >>> (-2 + x + A).args_cnc() [[], [x - 2 + A]] >>> (-oo).args_cnc() # -oo is a singleton [[-1, oo], []] """ if self.is_Mul: args = list(self.args) else: args = [self] for i, mi in enumerate(args): if not mi.is_commutative: c = args[:i] nc = args[i:] break else: c = args nc = [] if c and split_1 and ( c[0].is_Number and c[0].is_extended_negative and c[0] is not S.NegativeOne): c[:1] = [S.NegativeOne, -c[0]] if cset: clen = len(c) c = set(c) if clen and warn and len(c) != clen: raise ValueError('repeated commutative arguments: %s' % [ci for ci in c if list(self.args).count(ci) > 1]) return [c, nc] def coeff(self, x, n=1, right=False, _first=True): """ Returns the coefficient from the term(s) containing ``x**n``. If ``n`` is zero then all terms independent of ``x`` will be returned. Explanation =========== When ``x`` is noncommutative, the coefficient to the left (default) or right of ``x`` can be returned. The keyword 'right' is ignored when ``x`` is commutative. Examples ======== >>> from sympy import symbols >>> from sympy.abc import x, y, z You can select terms that have an explicit negative in front of them: >>> (-x + 2*y).coeff(-1) x >>> (x - 2*y).coeff(-1) 2*y You can select terms with no Rational coefficient: >>> (x + 2*y).coeff(1) x >>> (3 + 2*x + 4*x**2).coeff(1) 0 You can select terms independent of x by making n=0; in this case expr.as_independent(x)[0] is returned (and 0 will be returned instead of None): >>> (3 + 2*x + 4*x**2).coeff(x, 0) 3 >>> eq = ((x + 1)**3).expand() + 1 >>> eq x**3 + 3*x**2 + 3*x + 2 >>> [eq.coeff(x, i) for i in reversed(range(4))] [1, 3, 3, 2] >>> eq -= 2 >>> [eq.coeff(x, i) for i in reversed(range(4))] [1, 3, 3, 0] You can select terms that have a numerical term in front of them: >>> (-x - 2*y).coeff(2) -y >>> from sympy import sqrt >>> (x + sqrt(2)*x).coeff(sqrt(2)) x The matching is exact: >>> (3 + 2*x + 4*x**2).coeff(x) 2 >>> (3 + 2*x + 4*x**2).coeff(x**2) 4 >>> (3 + 2*x + 4*x**2).coeff(x**3) 0 >>> (z*(x + y)**2).coeff((x + y)**2) z >>> (z*(x + y)**2).coeff(x + y) 0 In addition, no factoring is done, so 1 + z*(1 + y) is not obtained from the following: >>> (x + z*(x + x*y)).coeff(x) 1 If such factoring is desired, factor_terms can be used first: >>> from sympy import factor_terms >>> factor_terms(x + z*(x + x*y)).coeff(x) z*(y + 1) + 1 >>> n, m, o = symbols('n m o', commutative=False) >>> n.coeff(n) 1 >>> (3*n).coeff(n) 3 >>> (n*m + m*n*m).coeff(n) # = (1 + m)*n*m 1 + m >>> (n*m + m*n*m).coeff(n, right=True) # = (1 + m)*n*m m If there is more than one possible coefficient 0 is returned: >>> (n*m + m*n).coeff(n) 0 If there is only one possible coefficient, it is returned: >>> (n*m + x*m*n).coeff(m*n) x >>> (n*m + x*m*n).coeff(m*n, right=1) 1 See Also ======== as_coefficient: separate the expression into a coefficient and factor as_coeff_Add: separate the additive constant from an expression as_coeff_Mul: separate the multiplicative constant from an expression as_independent: separate x-dependent terms/factors from others sympy.polys.polytools.Poly.coeff_monomial: efficiently find the single coefficient of a monomial in Poly sympy.polys.polytools.Poly.nth: like coeff_monomial but powers of monomial terms are used """ x = sympify(x) if not isinstance(x, Basic): return S.Zero n = as_int(n) if not x: return S.Zero if x == self: if n == 1: return S.One return S.Zero if x is S.One: co = [a for a in Add.make_args(self) if a.as_coeff_Mul()[0] is S.One] if not co: return S.Zero return Add(*co) if n == 0: if x.is_Add and self.is_Add: c = self.coeff(x, right=right) if not c: return S.Zero if not right: return self - Add(*[a*x for a in Add.make_args(c)]) return self - Add(*[x*a for a in Add.make_args(c)]) return self.as_independent(x, as_Add=True)[0] # continue with the full method, looking for this power of x: x = x**n def incommon(l1, l2): if not l1 or not l2: return [] n = min(len(l1), len(l2)) for i in range(n): if l1[i] != l2[i]: return l1[:i] return l1[:] def find(l, sub, first=True): """ Find where list sub appears in list l. When ``first`` is True the first occurrence from the left is returned, else the last occurrence is returned. Return None if sub is not in l. Examples ======== >> l = range(5)*2 >> find(l, [2, 3]) 2 >> find(l, [2, 3], first=0) 7 >> find(l, [2, 4]) None """ if not sub or not l or len(sub) > len(l): return None n = len(sub) if not first: l.reverse() sub.reverse() for i in range(len(l) - n + 1): if all(l[i + j] == sub[j] for j in range(n)): break else: i = None if not first: l.reverse() sub.reverse() if i is not None and not first: i = len(l) - (i + n) return i co = [] args = Add.make_args(self) self_c = self.is_commutative x_c = x.is_commutative if self_c and not x_c: return S.Zero if _first and self.is_Add and not self_c and not x_c: # get the part that depends on x exactly xargs = Mul.make_args(x) d = Add(*[i for i in Add.make_args(self.as_independent(x)[1]) if all(xi in Mul.make_args(i) for xi in xargs)]) rv = d.coeff(x, right=right, _first=False) if not rv.is_Add or not right: return rv c_part, nc_part = zip(*[i.args_cnc() for i in rv.args]) if has_variety(c_part): return rv return Add(*[Mul._from_args(i) for i in nc_part]) one_c = self_c or x_c xargs, nx = x.args_cnc(cset=True, warn=bool(not x_c)) # find the parts that pass the commutative terms for a in args: margs, nc = a.args_cnc(cset=True, warn=bool(not self_c)) if nc is None: nc = [] if len(xargs) > len(margs): continue resid = margs.difference(xargs) if len(resid) + len(xargs) == len(margs): if one_c: co.append(Mul(*(list(resid) + nc))) else: co.append((resid, nc)) if one_c: if co == []: return S.Zero elif co: return Add(*co) else: # both nc # now check the non-comm parts if not co: return S.Zero if all(n == co[0][1] for r, n in co): ii = find(co[0][1], nx, right) if ii is not None: if not right: return Mul(Add(*[Mul(*r) for r, c in co]), Mul(*co[0][1][:ii])) else: return Mul(*co[0][1][ii + len(nx):]) beg = reduce(incommon, (n[1] for n in co)) if beg: ii = find(beg, nx, right) if ii is not None: if not right: gcdc = co[0][0] for i in range(1, len(co)): gcdc = gcdc.intersection(co[i][0]) if not gcdc: break return Mul(*(list(gcdc) + beg[:ii])) else: m = ii + len(nx) return Add(*[Mul(*(list(r) + n[m:])) for r, n in co]) end = list(reversed( reduce(incommon, (list(reversed(n[1])) for n in co)))) if end: ii = find(end, nx, right) if ii is not None: if not right: return Add(*[Mul(*(list(r) + n[:-len(end) + ii])) for r, n in co]) else: return Mul(*end[ii + len(nx):]) # look for single match hit = None for i, (r, n) in enumerate(co): ii = find(n, nx, right) if ii is not None: if not hit: hit = ii, r, n else: break else: if hit: ii, r, n = hit if not right: return Mul(*(list(r) + n[:ii])) else: return Mul(*n[ii + len(nx):]) return S.Zero def as_expr(self, *gens): """ Convert a polynomial to a SymPy expression. Examples ======== >>> from sympy import sin >>> from sympy.abc import x, y >>> f = (x**2 + x*y).as_poly(x, y) >>> f.as_expr() x**2 + x*y >>> sin(x).as_expr() sin(x) """ return self def as_coefficient(self, expr): """ Extracts symbolic coefficient at the given expression. In other words, this functions separates 'self' into the product of 'expr' and 'expr'-free coefficient. If such separation is not possible it will return None. Examples ======== >>> from sympy import E, pi, sin, I, Poly >>> from sympy.abc import x >>> E.as_coefficient(E) 1 >>> (2*E).as_coefficient(E) 2 >>> (2*sin(E)*E).as_coefficient(E) Two terms have E in them so a sum is returned. (If one were desiring the coefficient of the term exactly matching E then the constant from the returned expression could be selected. Or, for greater precision, a method of Poly can be used to indicate the desired term from which the coefficient is desired.) >>> (2*E + x*E).as_coefficient(E) x + 2 >>> _.args[0] # just want the exact match 2 >>> p = Poly(2*E + x*E); p Poly(x*E + 2*E, x, E, domain='ZZ') >>> p.coeff_monomial(E) 2 >>> p.nth(0, 1) 2 Since the following cannot be written as a product containing E as a factor, None is returned. (If the coefficient ``2*x`` is desired then the ``coeff`` method should be used.) >>> (2*E*x + x).as_coefficient(E) >>> (2*E*x + x).coeff(E) 2*x >>> (E*(x + 1) + x).as_coefficient(E) >>> (2*pi*I).as_coefficient(pi*I) 2 >>> (2*I).as_coefficient(pi*I) See Also ======== coeff: return sum of terms have a given factor as_coeff_Add: separate the additive constant from an expression as_coeff_Mul: separate the multiplicative constant from an expression as_independent: separate x-dependent terms/factors from others sympy.polys.polytools.Poly.coeff_monomial: efficiently find the single coefficient of a monomial in Poly sympy.polys.polytools.Poly.nth: like coeff_monomial but powers of monomial terms are used """ r = self.extract_multiplicatively(expr) if r and not r.has(expr): return r def as_independent(self, *deps, **hint) -> tuple[Expr, Expr]: """ 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 sympy.core.add.Add.as_two_terms sympy.core.mul.Mul.as_two_terms as_coeff_mul """ from .symbol import Symbol from .add import _unevaluated_Add from .mul import _unevaluated_Mul if self is S.Zero: return (self, self) func = self.func if hint.get('as_Add', isinstance(self, Add) ): want = Add else: want = Mul # sift out deps into symbolic and other and ignore # all symbols but those that are in the free symbols sym = set() other = [] for d in deps: if isinstance(d, Symbol): # Symbol.is_Symbol is True sym.add(d) else: other.append(d) def has(e): """return the standard has() if there are no literal symbols, else check to see that symbol-deps are in the free symbols.""" has_other = e.has(*other) if not sym: return has_other return has_other or e.has(*(e.free_symbols & sym)) if (want is not func or func is not Add and func is not Mul): if has(self): return (want.identity, self) else: return (self, want.identity) else: if func is Add: args = list(self.args) else: args, nc = self.args_cnc() d = sift(args, has) depend = d[True] indep = d[False] if func is Add: # all terms were treated as commutative return (Add(*indep), _unevaluated_Add(*depend)) else: # handle noncommutative by stopping at first dependent term for i, n in enumerate(nc): if has(n): depend.extend(nc[i:]) break indep.append(n) return Mul(*indep), ( Mul(*depend, evaluate=False) if nc else _unevaluated_Mul(*depend)) def as_real_imag(self, deep=True, **hints): """Performs complex expansion on 'self' and returns a tuple containing collected both real and imaginary parts. This method cannot be confused with re() and im() functions, which does not perform complex expansion at evaluation. However it is possible to expand both re() and im() functions and get exactly the same results as with a single call to this function. >>> from sympy import symbols, I >>> x, y = symbols('x,y', real=True) >>> (x + y*I).as_real_imag() (x, y) >>> from sympy.abc import z, w >>> (z + w*I).as_real_imag() (re(z) - im(w), re(w) + im(z)) """ if hints.get('ignore') == self: return None else: from sympy.functions.elementary.complexes import im, re return (re(self), im(self)) def as_powers_dict(self): """Return self as a dictionary of factors with each factor being treated as a power. The keys are the bases of the factors and the values, the corresponding exponents. The resulting dictionary should be used with caution if the expression is a Mul and contains non- commutative factors since the order that they appeared will be lost in the dictionary. See Also ======== as_ordered_factors: An alternative for noncommutative applications, returning an ordered list of factors. args_cnc: Similar to as_ordered_factors, but guarantees separation of commutative and noncommutative factors. """ d = defaultdict(int) d.update(dict([self.as_base_exp()])) return d def as_coefficients_dict(self, *syms): """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 symbols ``syms`` are provided, any multiplicative terms independent of them will be considered a coefficient and a regular dictionary of syms-dependent generators as keys and their corresponding coefficients as values will be returned. Examples ======== >>> from sympy.abc import a, x, y >>> (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} >>> (3*a*x).as_coefficients_dict(x) {x: 3*a} >>> (3*a*x).as_coefficients_dict(y) {1: 3*a*x} """ d = defaultdict(list) if not syms: for ai in Add.make_args(self): c, m = ai.as_coeff_Mul() d[m].append(c) for k, v in d.items(): if len(v) == 1: d[k] = v[0] else: d[k] = Add(*v) else: ind, dep = self.as_independent(*syms, as_Add=True) for i in Add.make_args(dep): if i.is_Mul: c, x = i.as_coeff_mul(*syms) if c is S.One: d[i].append(c) else: d[i._new_rawargs(*x)].append(c) elif i: d[i].append(S.One) d = {k: Add(*d[k]) for k in d} if ind is not S.Zero: d.update({S.One: ind}) di = defaultdict(int) di.update(d) return di def as_base_exp(self) -> tuple[Expr, Expr]: # a -> b ** e return self, S.One def as_coeff_mul(self, *deps, **kwargs) -> tuple[Expr, tuple[Expr, ...]]: """Return the tuple (c, args) where self is written as a Mul, ``m``. c should be a Rational multiplied by any factors of the Mul that are independent of deps. args should be a tuple of all other factors of m; args is empty if self is a Number or if self is independent of deps (when given). This should be used when you do not know if self is a Mul or not but you want to treat self as a Mul or if you want to process the individual arguments of the tail of self as a Mul. - if you know self is a Mul and want only the head, use self.args[0]; - if you do not want to process the arguments of the tail but need the tail then use self.as_two_terms() which gives the head and tail; - if you want to split self into an independent and dependent parts use ``self.as_independent(*deps)`` >>> from sympy import S >>> from sympy.abc import x, y >>> (S(3)).as_coeff_mul() (3, ()) >>> (3*x*y).as_coeff_mul() (3, (x, y)) >>> (3*x*y).as_coeff_mul(x) (3*y, (x,)) >>> (3*y).as_coeff_mul(x) (3*y, ()) """ if deps: if not self.has(*deps): return self, tuple() return S.One, (self,) def as_coeff_add(self, *deps) -> tuple[Expr, tuple[Expr, ...]]: """Return the tuple (c, args) where self is written as an Add, ``a``. c should be a Rational added to any terms of the Add that are independent of deps. args should be a tuple of all other terms of ``a``; args is empty if self is a Number or if self is independent of deps (when given). This should be used when you do not know if self is an Add or not but you want to treat self as an Add or if you want to process the individual arguments of the tail of self as an Add. - if you know self is an Add and want only the head, use self.args[0]; - if you do not want to process the arguments of the tail but need the tail then use self.as_two_terms() which gives the head and tail. - if you want to split self into an independent and dependent parts use ``self.as_independent(*deps)`` >>> from sympy import S >>> from sympy.abc import x, y >>> (S(3)).as_coeff_add() (3, ()) >>> (3 + x).as_coeff_add() (3, (x,)) >>> (3 + x + y).as_coeff_add(x) (y + 3, (x,)) >>> (3 + y).as_coeff_add(x) (y + 3, ()) """ if deps: if not self.has_free(*deps): return self, tuple() return S.Zero, (self,) def primitive(self): """Return the positive Rational that can be extracted non-recursively from every term of self (i.e., self is treated like an Add). This is like the as_coeff_Mul() method but primitive always extracts a positive Rational (never a negative or a Float). Examples ======== >>> from sympy.abc import x >>> (3*(x + 1)**2).primitive() (3, (x + 1)**2) >>> a = (6*x + 2); a.primitive() (2, 3*x + 1) >>> b = (x/2 + 3); b.primitive() (1/2, x + 6) >>> (a*b).primitive() == (1, a*b) True """ if not self: return S.One, S.Zero c, r = self.as_coeff_Mul(rational=True) if c.is_negative: c, r = -c, -r return c, r def as_content_primitive(self, radical=False, clear=True): """This method should recursively remove a Rational from all arguments and return that (content) and the new self (primitive). The content should always be positive and ``Mul(*foo.as_content_primitive()) == foo``. The primitive need not be in canonical form and should try to preserve the underlying structure if possible (i.e. expand_mul should not be applied to self). Examples ======== >>> from sympy import sqrt >>> from sympy.abc import x, y, z >>> eq = 2 + 2*x + 2*y*(3 + 3*y) The as_content_primitive function is recursive and retains structure: >>> eq.as_content_primitive() (2, x + 3*y*(y + 1) + 1) Integer powers will have Rationals extracted from the base: >>> ((2 + 6*x)**2).as_content_primitive() (4, (3*x + 1)**2) >>> ((2 + 6*x)**(2*y)).as_content_primitive() (1, (2*(3*x + 1))**(2*y)) Terms may end up joining once their as_content_primitives are added: >>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive() (11, x*(y + 1)) >>> ((3*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive() (9, x*(y + 1)) >>> ((3*(z*(1 + y)) + 2.0*x*(3 + 3*y))).as_content_primitive() (1, 6.0*x*(y + 1) + 3*z*(y + 1)) >>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive() (121, x**2*(y + 1)**2) >>> ((x*(1 + y) + 0.4*x*(3 + 3*y))**2).as_content_primitive() (1, 4.84*x**2*(y + 1)**2) Radical content can also be factored out of the primitive: >>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True) (2, sqrt(2)*(1 + 2*sqrt(5))) If clear=False (default is True) then content will not be removed from an Add if it can be distributed to leave one or more terms with integer coefficients. >>> (x/2 + y).as_content_primitive() (1/2, x + 2*y) >>> (x/2 + y).as_content_primitive(clear=False) (1, x/2 + y) """ return S.One, self def as_numer_denom(self): """Return the numerator and the denominator of an expression. 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): """Return the expression as a fraction. expression -> a/b See Also ======== as_numer_denom: return ``(a, b)`` instead of ``a/b`` """ from .mul import _unevaluated_Mul n, d = self.as_numer_denom() if d is S.One: return n if d.is_Number: return _unevaluated_Mul(n, 1/d) else: return n/d def extract_multiplicatively(self, c): """Return None if it's not possible to make self in the form c * something in a nice way, i.e. preserving the properties of arguments of self. Examples ======== >>> from sympy import symbols, Rational >>> x, y = symbols('x,y', real=True) >>> ((x*y)**3).extract_multiplicatively(x**2 * y) x*y**2 >>> ((x*y)**3).extract_multiplicatively(x**4 * y) >>> (2*x).extract_multiplicatively(2) x >>> (2*x).extract_multiplicatively(3) >>> (Rational(1, 2)*x).extract_multiplicatively(3) x/6 """ from sympy.functions.elementary.exponential import exp from .add import _unevaluated_Add c = sympify(c) if self is S.NaN: return None if c is S.One: return self elif c == self: return S.One if c.is_Add: cc, pc = c.primitive() if cc is not S.One: c = Mul(cc, pc, evaluate=False) if c.is_Mul: a, b = c.as_two_terms() x = self.extract_multiplicatively(a) if x is not None: return x.extract_multiplicatively(b) else: return x quotient = self / c if self.is_Number: if self is S.Infinity: if c.is_positive: return S.Infinity elif self is S.NegativeInfinity: if c.is_negative: return S.Infinity elif c.is_positive: return S.NegativeInfinity elif self is S.ComplexInfinity: if not c.is_zero: return S.ComplexInfinity elif self.is_Integer: if not quotient.is_Integer: return None elif self.is_positive and quotient.is_negative: return None else: return quotient elif self.is_Rational: if not quotient.is_Rational: return None elif self.is_positive and quotient.is_negative: return None else: return quotient elif self.is_Float: if not quotient.is_Float: return None elif self.is_positive and quotient.is_negative: return None else: return quotient elif self.is_NumberSymbol or self.is_Symbol or self is S.ImaginaryUnit: if quotient.is_Mul and len(quotient.args) == 2: if quotient.args[0].is_Integer and quotient.args[0].is_positive and quotient.args[1] == self: return quotient elif quotient.is_Integer and c.is_Number: return quotient elif self.is_Add: cs, ps = self.primitive() # assert cs >= 1 if c.is_Number and c is not S.NegativeOne: # assert c != 1 (handled at top) if cs is not S.One: if c.is_negative: xc = -(cs.extract_multiplicatively(-c)) else: xc = cs.extract_multiplicatively(c) if xc is not None: return xc*ps # rely on 2-arg Mul to restore Add return # |c| != 1 can only be extracted from cs if c == ps: return cs # check args of ps newargs = [] for arg in ps.args: newarg = arg.extract_multiplicatively(c) if newarg is None: return # all or nothing newargs.append(newarg) if cs is not S.One: args = [cs*t for t in newargs] # args may be in different order return _unevaluated_Add(*args) else: return Add._from_args(newargs) elif self.is_Mul: args = list(self.args) for i, arg in enumerate(args): newarg = arg.extract_multiplicatively(c) if newarg is not None: args[i] = newarg return Mul(*args) elif self.is_Pow or isinstance(self, exp): sb, se = self.as_base_exp() cb, ce = c.as_base_exp() if cb == sb: new_exp = se.extract_additively(ce) if new_exp is not None: return Pow(sb, new_exp) elif c == sb: new_exp = self.exp.extract_additively(1) if new_exp is not None: return Pow(sb, new_exp) def extract_additively(self, c): """Return self - c if it's possible to subtract c from self and make all matching coefficients move towards zero, else return None. Examples ======== >>> from sympy.abc import x, y >>> e = 2*x + 3 >>> e.extract_additively(x + 1) x + 2 >>> e.extract_additively(3*x) >>> e.extract_additively(4) >>> (y*(x + 1)).extract_additively(x + 1) >>> ((x + 1)*(x + 2*y + 1) + 3).extract_additively(x + 1) (x + 1)*(x + 2*y) + 3 See Also ======== extract_multiplicatively coeff as_coefficient """ c = sympify(c) if self is S.NaN: return None if c.is_zero: return self elif c == self: return S.Zero elif self == S.Zero: return None if self.is_Number: if not c.is_Number: return None co = self diff = co - c # XXX should we match types? i.e should 3 - .1 succeed? if (co > 0 and diff >= 0 and diff < co or co < 0 and diff <= 0 and diff > co): return diff return None if c.is_Number: co, t = self.as_coeff_Add() xa = co.extract_additively(c) if xa is None: return None return xa + t # handle the args[0].is_Number case separately # since we will have trouble looking for the coeff of # a number. if c.is_Add and c.args[0].is_Number: # whole term as a term factor co = self.coeff(c) xa0 = (co.extract_additively(1) or 0)*c if xa0: diff = self - co*c return (xa0 + (diff.extract_additively(c) or diff)) or None # term-wise h, t = c.as_coeff_Add() sh, st = self.as_coeff_Add() xa = sh.extract_additively(h) if xa is None: return None xa2 = st.extract_additively(t) if xa2 is None: return None return xa + xa2 # whole term as a term factor co, diff = _corem(self, c) xa0 = (co.extract_additively(1) or 0)*c if xa0: return (xa0 + (diff.extract_additively(c) or diff)) or None # term-wise coeffs = [] for a in Add.make_args(c): ac, at = a.as_coeff_Mul() co = self.coeff(at) if not co: return None coc, cot = co.as_coeff_Add() xa = coc.extract_additively(ac) if xa is None: return None self -= co*at coeffs.append((cot + xa)*at) coeffs.append(self) return Add(*coeffs) @property def expr_free_symbols(self): """ Like ``free_symbols``, but returns the free symbols only if they are contained in an expression node. Examples ======== >>> from sympy.abc import x, y >>> (x + y).expr_free_symbols # doctest: +SKIP {x, y} If the expression is contained in a non-expression object, do not return the free symbols. Compare: >>> from sympy import Tuple >>> t = Tuple(x + y) >>> t.expr_free_symbols # doctest: +SKIP set() >>> t.free_symbols {x, y} """ sympy_deprecation_warning(""" The expr_free_symbols property is deprecated. Use free_symbols to get the free symbols of an expression. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-expr-free-symbols") return {j for i in self.args for j in i.expr_free_symbols} def could_extract_minus_sign(self): """Return True if self has -1 as a leading factor or has more literal negative signs than positive signs in a sum, otherwise False. Examples ======== >>> from sympy.abc import x, y >>> e = x - y >>> {i.could_extract_minus_sign() for i in (e, -e)} {False, True} Though the ``y - x`` is considered like ``-(x - y)``, since it is in a product without a leading factor of -1, the result is false below: >>> (x*(y - x)).could_extract_minus_sign() False To put something in canonical form wrt to sign, use `signsimp`: >>> from sympy import signsimp >>> signsimp(x*(y - x)) -x*(x - y) >>> _.could_extract_minus_sign() True """ return False def extract_branch_factor(self, allow_half=False): """ Try to write self as ``exp_polar(2*pi*I*n)*z`` in a nice way. Return (z, n). >>> from sympy import exp_polar, I, pi >>> from sympy.abc import x, y >>> exp_polar(I*pi).extract_branch_factor() (exp_polar(I*pi), 0) >>> exp_polar(2*I*pi).extract_branch_factor() (1, 1) >>> exp_polar(-pi*I).extract_branch_factor() (exp_polar(I*pi), -1) >>> exp_polar(3*pi*I + x).extract_branch_factor() (exp_polar(x + I*pi), 1) >>> (y*exp_polar(-5*pi*I)*exp_polar(3*pi*I + 2*pi*x)).extract_branch_factor() (y*exp_polar(2*pi*x), -1) >>> exp_polar(-I*pi/2).extract_branch_factor() (exp_polar(-I*pi/2), 0) If allow_half is True, also extract exp_polar(I*pi): >>> exp_polar(I*pi).extract_branch_factor(allow_half=True) (1, 1/2) >>> exp_polar(2*I*pi).extract_branch_factor(allow_half=True) (1, 1) >>> exp_polar(3*I*pi).extract_branch_factor(allow_half=True) (1, 3/2) >>> exp_polar(-I*pi).extract_branch_factor(allow_half=True) (1, -1/2) """ from sympy.functions.elementary.exponential import exp_polar from sympy.functions.elementary.integers import ceiling n = S.Zero res = S.One args = Mul.make_args(self) exps = [] for arg in args: if isinstance(arg, exp_polar): exps += [arg.exp] else: res *= arg piimult = S.Zero extras = [] ipi = S.Pi*S.ImaginaryUnit while exps: exp = exps.pop() if exp.is_Add: exps += exp.args continue if exp.is_Mul: coeff = exp.as_coefficient(ipi) if coeff is not None: piimult += coeff continue extras += [exp] if piimult.is_number: coeff = piimult tail = () else: coeff, tail = piimult.as_coeff_add(*piimult.free_symbols) # round down to nearest multiple of 2 branchfact = ceiling(coeff/2 - S.Half)*2 n += branchfact/2 c = coeff - branchfact if allow_half: nc = c.extract_additively(1) if nc is not None: n += S.Half c = nc newexp = ipi*Add(*((c, ) + tail)) + Add(*extras) if newexp != 0: res *= exp_polar(newexp) return res, n def is_polynomial(self, *syms): r""" Return True if self is a polynomial in syms and False otherwise. This checks if self is an exact polynomial in syms. This function returns False for expressions that are "polynomials" with symbolic exponents. Thus, you should be able to apply polynomial algorithms to expressions for which this returns True, and Poly(expr, \*syms) should work if and only if expr.is_polynomial(\*syms) returns True. The polynomial does not have to be in expanded form. If no symbols are given, all free symbols in the expression will be used. This is not part of the assumptions system. You cannot do Symbol('z', polynomial=True). Examples ======== >>> from sympy import Symbol, Function >>> x = Symbol('x') >>> ((x**2 + 1)**4).is_polynomial(x) True >>> ((x**2 + 1)**4).is_polynomial() True >>> (2**x + 1).is_polynomial(x) False >>> (2**x + 1).is_polynomial(2**x) True >>> f = Function('f') >>> (f(x) + 1).is_polynomial(x) False >>> (f(x) + 1).is_polynomial(f(x)) True >>> (1/f(x) + 1).is_polynomial(f(x)) False >>> n = Symbol('n', nonnegative=True, integer=True) >>> (x**n + 1).is_polynomial(x) False This function does not attempt any nontrivial simplifications that may result in an expression that does not appear to be a polynomial to become one. >>> from sympy import sqrt, factor, cancel >>> y = Symbol('y', positive=True) >>> a = sqrt(y**2 + 2*y + 1) >>> a.is_polynomial(y) False >>> factor(a) y + 1 >>> factor(a).is_polynomial(y) True >>> b = (y**2 + 2*y + 1)/(y + 1) >>> b.is_polynomial(y) False >>> cancel(b) y + 1 >>> cancel(b).is_polynomial(y) True See also .is_rational_function() """ if syms: syms = set(map(sympify, syms)) else: syms = self.free_symbols if not syms: return True return self._eval_is_polynomial(syms) def _eval_is_polynomial(self, syms): if self in syms: return True if not self.has_free(*syms): # constant polynomial return True # subclasses should return True or False def is_rational_function(self, *syms): """ Test whether function is a ratio of two polynomials in the given symbols, syms. When syms is not given, all free symbols will be used. The rational function does not have to be in expanded or in any kind of canonical form. This function returns False for expressions that are "rational functions" with symbolic exponents. Thus, you should be able to call .as_numer_denom() and apply polynomial algorithms to the result for expressions for which this returns True. This is not part of the assumptions system. You cannot do Symbol('z', rational_function=True). Examples ======== >>> from sympy import Symbol, sin >>> from sympy.abc import x, y >>> (x/y).is_rational_function() True >>> (x**2).is_rational_function() True >>> (x/sin(y)).is_rational_function(y) False >>> n = Symbol('n', integer=True) >>> (x**n + 1).is_rational_function(x) False This function does not attempt any nontrivial simplifications that may result in an expression that does not appear to be a rational function to become one. >>> from sympy import sqrt, factor >>> y = Symbol('y', positive=True) >>> a = sqrt(y**2 + 2*y + 1)/y >>> a.is_rational_function(y) False >>> factor(a) (y + 1)/y >>> factor(a).is_rational_function(y) True See also is_algebraic_expr(). """ if syms: syms = set(map(sympify, syms)) else: syms = self.free_symbols if not syms: return self not in _illegal return self._eval_is_rational_function(syms) def _eval_is_rational_function(self, syms): if self in syms: return True if not self.has_xfree(syms): return True # subclasses should return True or False def is_meromorphic(self, x, a): """ This tests whether an expression is meromorphic as a function of the given symbol ``x`` at the point ``a``. This method is intended as a quick test that will return None if no decision can be made without simplification or more detailed analysis. Examples ======== >>> from sympy import zoo, log, sin, sqrt >>> from sympy.abc import x >>> f = 1/x**2 + 1 - 2*x**3 >>> f.is_meromorphic(x, 0) True >>> f.is_meromorphic(x, 1) True >>> f.is_meromorphic(x, zoo) True >>> g = x**log(3) >>> g.is_meromorphic(x, 0) False >>> g.is_meromorphic(x, 1) True >>> g.is_meromorphic(x, zoo) False >>> h = sin(1/x)*x**2 >>> h.is_meromorphic(x, 0) False >>> h.is_meromorphic(x, 1) True >>> h.is_meromorphic(x, zoo) True Multivalued functions are considered meromorphic when their branches are meromorphic. Thus most functions are meromorphic everywhere except at essential singularities and branch points. In particular, they will be meromorphic also on branch cuts except at their endpoints. >>> log(x).is_meromorphic(x, -1) True >>> log(x).is_meromorphic(x, 0) False >>> sqrt(x).is_meromorphic(x, -1) True >>> sqrt(x).is_meromorphic(x, 0) False """ if not x.is_symbol: raise TypeError("{} should be of symbol type".format(x)) a = sympify(a) return self._eval_is_meromorphic(x, a) def _eval_is_meromorphic(self, x, a): if self == x: return True if not self.has_free(x): return True # subclasses should return True or False def is_algebraic_expr(self, *syms): """ This tests whether a given expression is algebraic or not, in the given symbols, syms. When syms is not given, all free symbols will be used. The rational function does not have to be in expanded or in any kind of canonical form. This function returns False for expressions that are "algebraic expressions" with symbolic exponents. This is a simple extension to the is_rational_function, including rational exponentiation. Examples ======== >>> from sympy import Symbol, sqrt >>> x = Symbol('x', real=True) >>> sqrt(1 + x).is_rational_function() False >>> sqrt(1 + x).is_algebraic_expr() True This function does not attempt any nontrivial simplifications that may result in an expression that does not appear to be an algebraic expression to become one. >>> from sympy import exp, factor >>> a = sqrt(exp(x)**2 + 2*exp(x) + 1)/(exp(x) + 1) >>> a.is_algebraic_expr(x) False >>> factor(a).is_algebraic_expr() True See Also ======== is_rational_function References ========== .. [1] https://en.wikipedia.org/wiki/Algebraic_expression """ if syms: syms = set(map(sympify, syms)) else: syms = self.free_symbols if not syms: return True return self._eval_is_algebraic_expr(syms) def _eval_is_algebraic_expr(self, syms): if self in syms: return True if not self.has_free(*syms): return True # subclasses should return True or False ################################################################################### ##################### SERIES, LEADING TERM, LIMIT, ORDER METHODS ################## ################################################################################### def series(self, x=None, x0=0, n=6, dir="+", logx=None, cdir=0): """ Series expansion of "self" around ``x = x0`` yielding either terms of the series one by one (the lazy series given when n=None), else all the terms at once when n != None. Returns the series expansion of "self" around the point ``x = x0`` with respect to ``x`` up to ``O((x - x0)**n, x, x0)`` (default n is 6). If ``x=None`` and ``self`` is univariate, the univariate symbol will be supplied, otherwise an error will be raised. Parameters ========== expr : Expression The expression whose series is to be expanded. x : Symbol It is the variable of the expression to be calculated. x0 : Value The value around which ``x`` is calculated. Can be any value from ``-oo`` to ``oo``. n : Value The value used to represent the order in terms of ``x**n``, up to 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)) For rational expressions this method may return original expression without the Order term. >>> (1/x).series(x, n=8) 1/x Returns ======= Expr : Expression Series expansion of the expression about x0 Raises ====== TypeError If "n" and "x0" are infinity objects PoleError If "x0" is an infinity object """ if x is None: syms = self.free_symbols if not syms: return self elif len(syms) > 1: raise ValueError('x must be given for multivariate functions.') x = syms.pop() from .symbol import Dummy, Symbol if isinstance(x, Symbol): dep = x in self.free_symbols else: d = Dummy() dep = d in self.xreplace({x: d}).free_symbols if not dep: if n is None: return (s for s in [self]) else: return self if len(dir) != 1 or dir not in '+-': raise ValueError("Dir must be '+' or '-'") x0 = sympify(x0) cdir = sympify(cdir) from sympy.functions.elementary.complexes import im, sign if not cdir.is_zero: if cdir.is_real: dir = '+' if cdir.is_positive else '-' else: dir = '+' if im(cdir).is_positive else '-' else: if x0 and x0.is_infinite: cdir = sign(x0).simplify() elif str(dir) == "+": cdir = S.One elif str(dir) == "-": cdir = S.NegativeOne elif cdir == S.Zero: cdir = S.One cdir = cdir/abs(cdir) if x0 and x0.is_infinite: from .function import PoleError try: s = self.subs(x, cdir/x).series(x, n=n, dir='+', cdir=1) if n is None: return (si.subs(x, cdir/x) for si in s) return s.subs(x, cdir/x) except PoleError: s = self.subs(x, cdir*x).aseries(x, n=n) return s.subs(x, cdir*x) # use rep to shift origin to x0 and change sign (if dir is negative) # and undo the process with rep2 if x0 or cdir != 1: s = self.subs({x: x0 + cdir*x}).series(x, x0=0, n=n, dir='+', logx=logx, cdir=1) if n is None: # lseries... return (si.subs({x: x/cdir - x0/cdir}) for si in s) return s.subs({x: x/cdir - x0/cdir}) # from here on it's x0=0 and dir='+' handling if x.is_positive is x.is_negative is None or x.is_Symbol is not True: # replace x with an x that has a positive assumption xpos = Dummy('x', positive=True) rv = self.subs(x, xpos).series(xpos, x0, n, dir, logx=logx, cdir=cdir) if n is None: return (s.subs(xpos, x) for s in rv) else: return rv.subs(xpos, x) from sympy.series.order import Order if n is not None: # nseries handling s1 = self._eval_nseries(x, n=n, logx=logx, cdir=cdir) o = s1.getO() or S.Zero if o: # make sure the requested order is returned ngot = o.getn() if ngot > n: # leave o in its current form (e.g. with x*log(x)) so # it eats terms properly, then replace it below if n != 0: s1 += o.subs(x, x**Rational(n, ngot)) else: s1 += Order(1, x) elif ngot < n: # increase the requested number of terms to get the desired # number keep increasing (up to 9) until the received order # is different than the original order and then predict how # many additional terms are needed from sympy.functions.elementary.integers import ceiling for more in range(1, 9): s1 = self._eval_nseries(x, n=n + more, logx=logx, cdir=cdir) newn = s1.getn() if newn != ngot: ndo = n + ceiling((n - ngot)*more/(newn - ngot)) s1 = self._eval_nseries(x, n=ndo, logx=logx, cdir=cdir) while s1.getn() < n: s1 = self._eval_nseries(x, n=ndo, logx=logx, cdir=cdir) ndo += 1 break else: raise ValueError('Could not calculate %s terms for %s' % (str(n), self)) s1 += Order(x**n, x) o = s1.getO() s1 = s1.removeO() elif s1.has(Order): # asymptotic expansion return s1 else: o = Order(x**n, x) s1done = s1.doit() try: if (s1done + o).removeO() == s1done: o = S.Zero except NotImplementedError: return s1 try: from sympy.simplify.radsimp import collect return collect(s1, x) + o except NotImplementedError: return s1 + o else: # lseries handling def yield_lseries(s): """Return terms of lseries one at a time.""" for si in s: if not si.is_Add: yield si continue # yield terms 1 at a time if possible # by increasing order until all the # terms have been returned yielded = 0 o = Order(si, x)*x ndid = 0 ndo = len(si.args) while 1: do = (si - yielded + o).removeO() o *= x if not do or do.is_Order: continue if do.is_Add: ndid += len(do.args) else: ndid += 1 yield do if ndid == ndo: break yielded += do return yield_lseries(self.removeO()._eval_lseries(x, logx=logx, cdir=cdir)) def aseries(self, x=None, n=6, bound=0, hir=False): """Asymptotic Series expansion of self. This is equivalent to ``self.series(x, oo, n)``. Parameters ========== self : Expression The expression whose series is to be expanded. x : Symbol It is the variable of the expression to be calculated. n : Value The value used to represent the order in terms of ``x**n``, up to which the series is to be expanded. hir : Boolean Set this parameter to be True to produce hierarchical series. It stops the recursion at an early level and may provide nicer and more useful results. bound : Value, Integer Use the ``bound`` parameter to give limit on rewriting coefficients in its normalised form. Examples ======== >>> from sympy import sin, exp >>> from sympy.abc import x >>> e = sin(1/x + exp(-x)) - sin(1/x) >>> e.aseries(x) (1/(24*x**4) - 1/(2*x**2) + 1 + O(x**(-6), (x, oo)))*exp(-x) >>> e.aseries(x, n=3, hir=True) -exp(-2*x)*sin(1/x)/2 + exp(-x)*cos(1/x) + O(exp(-3*x), (x, oo)) >>> e = exp(exp(x)/(1 - 1/x)) >>> e.aseries(x) exp(exp(x)/(1 - 1/x)) >>> e.aseries(x, bound=3) # doctest: +SKIP exp(exp(x)/x**2)*exp(exp(x)/x)*exp(-exp(x) + exp(x)/(1 - 1/x) - exp(x)/x - exp(x)/x**2)*exp(exp(x)) For rational expressions this method may return original expression without the Order term. >>> (1/x).aseries(x, n=8) 1/x Returns ======= Expr Asymptotic series expansion of the expression. Notes ===== This algorithm is directly induced from the limit computational algorithm provided by Gruntz. It majorly uses the mrv and rewrite sub-routines. The overall idea of this algorithm is first to look for the most rapidly varying subexpression w of a given expression f and then expands f in a series in w. Then same thing is recursively done on the leading coefficient till we get constant coefficients. If the most rapidly varying subexpression of a given expression f is f itself, the algorithm tries to find a normalised representation of the mrv set and rewrites f using this normalised representation. If the expansion contains an order term, it will be either ``O(x ** (-n))`` or ``O(w ** (-n))`` where ``w`` belongs to the most rapidly varying expression of ``self``. References ========== .. [1] Gruntz, Dominik. A new algorithm for computing asymptotic series. In: Proc. 1993 Int. Symp. Symbolic and Algebraic Computation. 1993. pp. 239-244. .. [2] Gruntz thesis - p90 .. [3] http://en.wikipedia.org/wiki/Asymptotic_expansion See Also ======== Expr.aseries: See the docstring of this function for complete details of this wrapper. """ from .symbol import Dummy if x.is_positive is x.is_negative is None: xpos = Dummy('x', positive=True) return self.subs(x, xpos).aseries(xpos, n, bound, hir).subs(xpos, x) from .function import PoleError from sympy.series.gruntz import mrv, rewrite try: om, exps = mrv(self, x) except PoleError: return self # We move one level up by replacing `x` by `exp(x)`, and then # computing the asymptotic series for f(exp(x)). Then asymptotic series # can be obtained by moving one-step back, by replacing x by ln(x). from sympy.functions.elementary.exponential import exp, log from sympy.series.order import Order if x in om: s = self.subs(x, exp(x)).aseries(x, n, bound, hir).subs(x, log(x)) if s.getO(): return s + Order(1/x**n, (x, S.Infinity)) return s k = Dummy('k', positive=True) # f is rewritten in terms of omega func, logw = rewrite(exps, om, x, k) if self in om: if bound <= 0: return self s = (self.exp).aseries(x, n, bound=bound) s = s.func(*[t.removeO() for t in s.args]) try: res = exp(s.subs(x, 1/x).as_leading_term(x).subs(x, 1/x)) except PoleError: res = self func = exp(self.args[0] - res.args[0]) / k logw = log(1/res) s = func.series(k, 0, n) # Hierarchical series if hir: return s.subs(k, exp(logw)) o = s.getO() terms = sorted(Add.make_args(s.removeO()), key=lambda i: int(i.as_coeff_exponent(k)[1])) s = S.Zero has_ord = False # Then we recursively expand these coefficients one by one into # their asymptotic series in terms of their most rapidly varying subexpressions. for t in terms: coeff, expo = t.as_coeff_exponent(k) if coeff.has(x): # Recursive step snew = coeff.aseries(x, n, bound=bound-1) if has_ord and snew.getO(): break elif snew.getO(): has_ord = True s += (snew * k**expo) else: s += t if not o or has_ord: return s.subs(k, exp(logw)) return (s + o).subs(k, exp(logw)) def taylor_term(self, n, x, *previous_terms): """General method for the taylor term. This method is slow, because it differentiates n-times. Subclasses can redefine it to make it faster by using the "previous_terms". """ from .symbol import Dummy from sympy.functions.combinatorial.factorials import factorial x = sympify(x) _x = Dummy('x') return self.subs(x, _x).diff(_x, n).subs(_x, x).subs(x, 0) * x**n / factorial(n) def lseries(self, x=None, x0=0, dir='+', logx=None, cdir=0): """ Wrapper for series yielding an iterator of the terms of the series. Note: an infinite series will yield an infinite iterator. The following, for exaxmple, will never terminate. It will just keep printing terms of the sin(x) series:: for term in sin(x).lseries(x): print term The advantage of lseries() over nseries() is that many times you are just interested in the next term in the series (i.e. the first term for example), but you do not know how many you should ask for in nseries() using the "n" parameter. See also nseries(). """ return self.series(x, x0, n=None, dir=dir, logx=logx, cdir=cdir) def _eval_lseries(self, x, logx=None, cdir=0): # default implementation of lseries is using nseries(), and adaptively # increasing the "n". As you can see, it is not very efficient, because # we are calculating the series over and over again. Subclasses should # override this method and implement much more efficient yielding of # terms. n = 0 series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir) while series.is_Order: n += 1 series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir) e = series.removeO() yield e if e is S.Zero: return while 1: while 1: n += 1 series = self._eval_nseries(x, n=n, logx=logx, cdir=cdir).removeO() if e != series: break if (series - self).cancel() is S.Zero: return yield series - e e = series def nseries(self, x=None, x0=0, n=6, dir='+', logx=None, cdir=0): """ Wrapper to _eval_nseries if assumptions allow, else to series. If x is given, x0 is 0, dir='+', and self has x, then _eval_nseries is called. This calculates "n" terms in the innermost expressions and then builds up the final series just by "cross-multiplying" everything out. The optional ``logx`` parameter can be used to replace any log(x) in the returned series with a symbolic value to avoid evaluating log(x) at 0. A symbol to use in place of log(x) should be provided. Advantage -- it's fast, because we do not have to determine how many terms we need to calculate in advance. Disadvantage -- you may end up with less terms than you may have expected, but the O(x**n) term appended will always be correct and so the result, though perhaps shorter, will also be correct. If any of those assumptions is not met, this is treated like a wrapper to series which will try harder to return the correct number of terms. See also lseries(). Examples ======== >>> from sympy import sin, log, Symbol >>> from sympy.abc import x, y >>> sin(x).nseries(x, 0, 6) x - x**3/6 + x**5/120 + O(x**6) >>> log(x+1).nseries(x, 0, 5) x - x**2/2 + x**3/3 - x**4/4 + O(x**5) Handling of the ``logx`` parameter --- in the following example the expansion fails since ``sin`` does not have an asymptotic expansion at -oo (the limit of log(x) as x approaches 0): >>> e = sin(log(x)) >>> e.nseries(x, 0, 6) Traceback (most recent call last): ... PoleError: ... ... >>> logx = Symbol('logx') >>> e.nseries(x, 0, 6, logx=logx) sin(logx) In the following example, the expansion works but only returns self unless the ``logx`` parameter is used: >>> e = x**y >>> e.nseries(x, 0, 2) x**y >>> e.nseries(x, 0, 2, logx=logx) exp(logx*y) """ if x and x not in self.free_symbols: return self if x is None or x0 or dir != '+': # {see XPOS above} or (x.is_positive == x.is_negative == None): return self.series(x, x0, n, dir, cdir=cdir) else: return self._eval_nseries(x, n=n, logx=logx, cdir=cdir) def _eval_nseries(self, x, n, logx, cdir): """ Return terms of series for self up to O(x**n) at x=0 from the positive direction. This is a method that should be overridden in subclasses. Users should never call this method directly (use .nseries() instead), so you do not have to write docstrings for _eval_nseries(). """ raise NotImplementedError(filldedent(""" The _eval_nseries method should be added to %s to give terms up to O(x**n) at x=0 from the positive direction so it is available when nseries calls it.""" % self.func) ) def limit(self, x, xlim, dir='+'): """ Compute limit x->xlim. """ from sympy.series.limits import limit return limit(self, x, xlim, dir) def compute_leading_term(self, x, logx=None): """Deprecated function to compute the leading term of a series. as_leading_term is only allowed for results of .series() This is a wrapper to compute a series first. """ from sympy.utilities.exceptions import SymPyDeprecationWarning SymPyDeprecationWarning( feature="compute_leading_term", useinstead="as_leading_term", issue=21843, deprecated_since_version="1.12" ).warn() from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold if self.has(Piecewise): expr = piecewise_fold(self) else: expr = self if self.removeO() == 0: return self from .symbol import Dummy from sympy.functions.elementary.exponential import log from sympy.series.order import Order _logx = logx logx = Dummy('logx') if logx is None else logx res = Order(1) incr = S.One while res.is_Order: res = expr._eval_nseries(x, n=1+incr, logx=logx).cancel().powsimp().trigsimp() incr *= 2 if _logx is None: res = res.subs(logx, log(x)) return res.as_leading_term(x) @cacheit def as_leading_term(self, *symbols, logx=None, cdir=0): """ Returns the leading (nonzero) term of the series expansion of self. The _eval_as_leading_term routines are used to do this, and they must always return a non-zero value. Examples ======== >>> from sympy.abc import x >>> (1 + x + x**2).as_leading_term(x) 1 >>> (1/x**2 + x + x**2).as_leading_term(x) x**(-2) """ if len(symbols) > 1: c = self for x in symbols: c = c.as_leading_term(x, logx=logx, cdir=cdir) return c elif not symbols: return self x = sympify(symbols[0]) if not x.is_symbol: raise ValueError('expecting a Symbol but got %s' % x) if x not in self.free_symbols: return self obj = self._eval_as_leading_term(x, logx=logx, cdir=cdir) if obj is not None: from sympy.simplify.powsimp import powsimp return powsimp(obj, deep=True, combine='exp') raise NotImplementedError('as_leading_term(%s, %s)' % (self, x)) def _eval_as_leading_term(self, x, logx=None, cdir=0): return self def as_coeff_exponent(self, x) -> tuple[Expr, Expr]: """ ``c*x**e -> c,e`` where x can be any symbolic expression. """ from sympy.simplify.radsimp import collect s = collect(self, x) c, p = s.as_coeff_mul(x) if len(p) == 1: b, e = p[0].as_base_exp() if b == x: return c, e return s, S.Zero def leadterm(self, x, logx=None, cdir=0): """ Returns the leading term a*x**b as a tuple (a, b). Examples ======== >>> from sympy.abc import x >>> (1+x+x**2).leadterm(x) (1, 0) >>> (1/x**2+x+x**2).leadterm(x) (1, -2) """ from .symbol import Dummy from sympy.functions.elementary.exponential import log l = self.as_leading_term(x, logx=logx, cdir=cdir) d = Dummy('logx') if l.has(log(x)): l = l.subs(log(x), d) c, e = l.as_coeff_exponent(x) if x in c.free_symbols: raise ValueError(filldedent(""" cannot compute leadterm(%s, %s). The coefficient should have been free of %s but got %s""" % (self, x, x, c))) c = c.subs(d, log(x)) return c, e def as_coeff_Mul(self, rational: bool = False) -> tuple['Number', Expr]: """Efficiently extract the coefficient of a product.""" return S.One, self def as_coeff_Add(self, rational=False) -> tuple['Number', Expr]: """Efficiently extract the coefficient of a summation.""" return S.Zero, self def fps(self, x=None, x0=0, dir=1, hyper=True, order=4, rational=True, full=False): """ Compute formal power power series of self. See the docstring of the :func:`fps` function in sympy.series.formal for more information. """ from sympy.series.formal import fps return fps(self, x, x0, dir, hyper, order, rational, full) def fourier_series(self, limits=None): """Compute fourier sine/cosine series of self. See the docstring of the :func:`fourier_series` in sympy.series.fourier for more information. """ from sympy.series.fourier import fourier_series return fourier_series(self, limits) ################################################################################### ##################### DERIVATIVE, INTEGRAL, FUNCTIONAL METHODS #################### ################################################################################### def diff(self, *symbols, **assumptions): assumptions.setdefault("evaluate", True) return _derivative_dispatch(self, *symbols, **assumptions) ########################################################################### ###################### EXPRESSION EXPANSION METHODS ####################### ########################################################################### # Relevant subclasses should override _eval_expand_hint() methods. See # the docstring of expand() for more info. def _eval_expand_complex(self, **hints): real, imag = self.as_real_imag(**hints) return real + S.ImaginaryUnit*imag @staticmethod def _expand_hint(expr, hint, deep=True, **hints): """ Helper for ``expand()``. Recursively calls ``expr._eval_expand_hint()``. Returns ``(expr, hit)``, where expr is the (possibly) expanded ``expr`` and ``hit`` is ``True`` if ``expr`` was truly expanded and ``False`` otherwise. """ hit = False # XXX: Hack to support non-Basic args # | # V if deep and getattr(expr, 'args', ()) and not expr.is_Atom: sargs = [] for arg in expr.args: arg, arghit = Expr._expand_hint(arg, hint, **hints) hit |= arghit sargs.append(arg) if hit: expr = expr.func(*sargs) if hasattr(expr, hint): newexpr = getattr(expr, hint)(**hints) if newexpr != expr: return (newexpr, True) return (expr, hit) @cacheit def expand(self, deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints): """ Expand an expression using hints. See the docstring of the expand() function in sympy.core.function for more information. """ from sympy.simplify.radsimp import fraction hints.update(power_base=power_base, power_exp=power_exp, mul=mul, log=log, multinomial=multinomial, basic=basic) expr = self if hints.pop('frac', False): n, d = [a.expand(deep=deep, modulus=modulus, **hints) for a in fraction(self)] return n/d elif hints.pop('denom', False): n, d = fraction(self) return n/d.expand(deep=deep, modulus=modulus, **hints) elif hints.pop('numer', False): n, d = fraction(self) return n.expand(deep=deep, modulus=modulus, **hints)/d # Although the hints are sorted here, an earlier hint may get applied # at a given node in the expression tree before another because of how # the hints are applied. e.g. expand(log(x*(y + z))) -> log(x*y + # x*z) because while applying log at the top level, log and mul are # applied at the deeper level in the tree so that when the log at the # upper level gets applied, the mul has already been applied at the # lower level. # Additionally, because hints are only applied once, the expression # may not be expanded all the way. For example, if mul is applied # before multinomial, x*(x + 1)**2 won't be expanded all the way. For # now, we just use a special case to make multinomial run before mul, # so that at least polynomials will be expanded all the way. In the # future, smarter heuristics should be applied. # TODO: Smarter heuristics def _expand_hint_key(hint): """Make multinomial come before mul""" if hint == 'mul': return 'mulz' return hint for hint in sorted(hints.keys(), key=_expand_hint_key): use_hint = hints[hint] if use_hint: hint = '_eval_expand_' + hint expr, hit = Expr._expand_hint(expr, hint, deep=deep, **hints) while True: was = expr if hints.get('multinomial', False): expr, _ = Expr._expand_hint( expr, '_eval_expand_multinomial', deep=deep, **hints) if hints.get('mul', False): expr, _ = Expr._expand_hint( expr, '_eval_expand_mul', deep=deep, **hints) if hints.get('log', False): expr, _ = Expr._expand_hint( expr, '_eval_expand_log', deep=deep, **hints) if expr == was: break if modulus is not None: modulus = sympify(modulus) if not modulus.is_Integer or modulus <= 0: raise ValueError( "modulus must be a positive integer, got %s" % modulus) terms = [] for term in Add.make_args(expr): coeff, tail = term.as_coeff_Mul(rational=True) coeff %= modulus if coeff: terms.append(coeff*tail) expr = Add(*terms) return expr ########################################################################### ################### GLOBAL ACTION VERB WRAPPER METHODS #################### ########################################################################### def integrate(self, *args, **kwargs): """See the integrate function in sympy.integrals""" from sympy.integrals.integrals import integrate return integrate(self, *args, **kwargs) def nsimplify(self, constants=(), tolerance=None, full=False): """See the nsimplify function in sympy.simplify""" from sympy.simplify.simplify import nsimplify return nsimplify(self, constants, tolerance, full) def separate(self, deep=False, force=False): """See the separate function in sympy.simplify""" from .function import expand_power_base return expand_power_base(self, deep=deep, force=force) def collect(self, syms, func=None, evaluate=True, exact=False, distribute_order_term=True): """See the collect function in sympy.simplify""" from sympy.simplify.radsimp import collect return collect(self, syms, func, evaluate, exact, distribute_order_term) def together(self, *args, **kwargs): """See the together function in sympy.polys""" from sympy.polys.rationaltools import together return together(self, *args, **kwargs) def apart(self, x=None, **args): """See the apart function in sympy.polys""" from sympy.polys.partfrac import apart return apart(self, x, **args) def ratsimp(self): """See the ratsimp function in sympy.simplify""" from sympy.simplify.ratsimp import ratsimp return ratsimp(self) def trigsimp(self, **args): """See the trigsimp function in sympy.simplify""" from sympy.simplify.trigsimp import trigsimp return trigsimp(self, **args) def radsimp(self, **kwargs): """See the radsimp function in sympy.simplify""" from sympy.simplify.radsimp import radsimp return radsimp(self, **kwargs) def powsimp(self, *args, **kwargs): """See the powsimp function in sympy.simplify""" from sympy.simplify.powsimp import powsimp return powsimp(self, *args, **kwargs) def combsimp(self): """See the combsimp function in sympy.simplify""" from sympy.simplify.combsimp import combsimp return combsimp(self) def gammasimp(self): """See the gammasimp function in sympy.simplify""" from sympy.simplify.gammasimp import gammasimp return gammasimp(self) def factor(self, *gens, **args): """See the factor() function in sympy.polys.polytools""" from sympy.polys.polytools import factor return factor(self, *gens, **args) def cancel(self, *gens, **args): """See the cancel function in sympy.polys""" from sympy.polys.polytools import cancel return cancel(self, *gens, **args) def invert(self, g, *gens, **args): """Return the multiplicative inverse of ``self`` mod ``g`` where ``self`` (and ``g``) may be symbolic expressions). See Also ======== sympy.core.numbers.mod_inverse, sympy.polys.polytools.invert """ if self.is_number and getattr(g, 'is_number', True): from .numbers import mod_inverse return mod_inverse(self, g) from sympy.polys.polytools import invert return invert(self, g, *gens, **args) def round(self, n=None): """Return x rounded to the given decimal place. If a complex number would results, apply round to the real and imaginary components of the number. Examples ======== >>> from sympy import pi, E, I, S, Number >>> pi.round() 3 >>> pi.round(2) 3.14 >>> (2*pi + E*I).round() 6 + 3*I The round method has a chopping effect: >>> (2*pi + I/10).round() 6 >>> (pi/10 + 2*I).round() 2*I >>> (pi/10 + E*I).round(2) 0.31 + 2.72*I Notes ===== The Python ``round`` function uses the SymPy ``round`` method so it will always return a SymPy number (not a Python float or int): >>> isinstance(round(S(123), -2), Number) True """ x = self if not x.is_number: raise TypeError("Cannot round symbolic expression") if not x.is_Atom: if not pure_complex(x.n(2), or_real=True): raise TypeError( 'Expected a number but got %s:' % func_name(x)) elif x in _illegal: return x if x.is_extended_real is False: r, i = x.as_real_imag() return r.round(n) + S.ImaginaryUnit*i.round(n) if not x: return S.Zero if n is None else x p = as_int(n or 0) if x.is_Integer: return Integer(round(int(x), p)) digits_to_decimal = _mag(x) # _mag(12) = 2, _mag(.012) = -1 allow = digits_to_decimal + p precs = [f._prec for f in x.atoms(Float)] dps = prec_to_dps(max(precs)) if precs else None if dps is None: # assume everything is exact so use the Python # float default or whatever was requested dps = max(15, allow) else: allow = min(allow, dps) # this will shift all digits to right of decimal # and give us dps to work with as an int shift = -digits_to_decimal + dps extra = 1 # how far we look past known digits # NOTE # mpmath will calculate the binary representation to # an arbitrary number of digits but we must base our # answer on a finite number of those digits, e.g. # .575 2589569785738035/2**52 in binary. # mpmath shows us that the first 18 digits are # >>> Float(.575).n(18) # 0.574999999999999956 # The default precision is 15 digits and if we ask # for 15 we get # >>> Float(.575).n(15) # 0.575000000000000 # mpmath handles rounding at the 15th digit. But we # need to be careful since the user might be asking # for rounding at the last digit and our semantics # are to round toward the even final digit when there # is a tie. So the extra digit will be used to make # that decision. In this case, the value is the same # to 15 digits: # >>> Float(.575).n(16) # 0.5750000000000000 # Now converting this to the 15 known digits gives # 575000000000000.0 # which rounds to integer # 5750000000000000 # And now we can round to the desired digt, e.g. at # the second from the left and we get # 5800000000000000 # and rescaling that gives # 0.58 # as the final result. # If the value is made slightly less than 0.575 we might # still obtain the same value: # >>> Float(.575-1e-16).n(16)*10**15 # 574999999999999.8 # What 15 digits best represents the known digits (which are # to the left of the decimal? 5750000000000000, the same as # before. The only way we will round down (in this case) is # if we declared that we had more than 15 digits of precision. # For example, if we use 16 digits of precision, the integer # we deal with is # >>> Float(.575-1e-16).n(17)*10**16 # 5749999999999998.4 # and this now rounds to 5749999999999998 and (if we round to # the 2nd digit from the left) we get 5700000000000000. # xf = x.n(dps + extra)*Pow(10, shift) xi = Integer(xf) # use the last digit to select the value of xi # nearest to x before rounding at the desired digit sign = 1 if x > 0 else -1 dif2 = sign*(xf - xi).n(extra) if dif2 < 0: raise NotImplementedError( 'not expecting int(x) to round away from 0') if dif2 > .5: xi += sign # round away from 0 elif dif2 == .5: xi += sign if xi%2 else -sign # round toward even # shift p to the new position ip = p - shift # let Python handle the int rounding then rescale xr = round(xi.p, ip) # restore scale rv = Rational(xr, Pow(10, shift)) # return Float or Integer if rv.is_Integer: if n is None: # the single-arg case return rv # use str or else it won't be a float return Float(str(rv), dps) # keep same precision else: if not allow and rv > self: allow += 1 return Float(rv, allow) __round__ = round def _eval_derivative_matrix_lines(self, x): from sympy.matrices.expressions.matexpr import _LeftRightArgs return [_LeftRightArgs([S.One, S.One], higher=self._eval_derivative(x))] class AtomicExpr(Atom, Expr): """ A parent class for object which are both atoms and Exprs. For example: Symbol, Number, Rational, Integer, ... But not: Add, Mul, Pow, ... """ is_number = False is_Atom = True __slots__ = () def _eval_derivative(self, s): if self == s: return S.One return S.Zero def _eval_derivative_n_times(self, s, n): from .containers import Tuple from sympy.matrices.expressions.matexpr import MatrixExpr from sympy.matrices.common import MatrixCommon if isinstance(s, (MatrixCommon, Tuple, Iterable, MatrixExpr)): return super()._eval_derivative_n_times(s, n) from .relational import Eq from sympy.functions.elementary.piecewise import Piecewise if self == s: return Piecewise((self, Eq(n, 0)), (1, Eq(n, 1)), (0, True)) else: return Piecewise((self, Eq(n, 0)), (0, True)) def _eval_is_polynomial(self, syms): return True def _eval_is_rational_function(self, syms): return self not in _illegal def _eval_is_meromorphic(self, x, a): from sympy.calculus.accumulationbounds import AccumBounds return (not self.is_Number or self.is_finite) and not isinstance(self, AccumBounds) def _eval_is_algebraic_expr(self, syms): return True def _eval_nseries(self, x, n, logx, cdir=0): return self @property def expr_free_symbols(self): sympy_deprecation_warning(""" The expr_free_symbols property is deprecated. Use free_symbols to get the free symbols of an expression. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-expr-free-symbols") return {self} def _mag(x): r"""Return integer $i$ such that $0.1 \le x/10^i < 1$ Examples ======== >>> from sympy.core.expr import _mag >>> from sympy import Float >>> _mag(Float(.1)) 0 >>> _mag(Float(.01)) -1 >>> _mag(Float(1234)) 4 """ from math import log10, ceil, log xpos = abs(x.n()) if not xpos: return S.Zero try: mag_first_dig = int(ceil(log10(xpos))) except (ValueError, OverflowError): mag_first_dig = int(ceil(Float(mpf_log(xpos._mpf_, 53))/log(10))) # check that we aren't off by 1 if (xpos/10**mag_first_dig) >= 1: assert 1 <= (xpos/10**mag_first_dig) < 10 mag_first_dig += 1 return mag_first_dig class UnevaluatedExpr(Expr): """ Expression that is not evaluated unless released. Examples ======== >>> from sympy import UnevaluatedExpr >>> from sympy.abc import x >>> x*(1/x) 1 >>> x*UnevaluatedExpr(1/x) x*1/x """ def __new__(cls, arg, **kwargs): arg = _sympify(arg) obj = Expr.__new__(cls, arg, **kwargs) return obj def doit(self, **hints): if hints.get("deep", True): return self.args[0].doit(**hints) else: return self.args[0] def unchanged(func, *args): """Return True if `func` applied to the `args` is unchanged. Can be used instead of `assert foo == foo`. Examples ======== >>> from sympy import Piecewise, cos, pi >>> from sympy.core.expr import unchanged >>> from sympy.abc import x >>> unchanged(cos, 1) # instead of assert cos(1) == cos(1) True >>> unchanged(cos, pi) False Comparison of args uses the builtin capabilities of the object's arguments to test for equality so args can be defined loosely. Here, the ExprCondPair arguments of Piecewise compare as equal to the tuples that can be used to create the Piecewise: >>> unchanged(Piecewise, (x, x > 1), (0, True)) True """ f = func(*args) return f.func == func and f.args == args class ExprBuilder: def __init__(self, op, args=None, validator=None, check=True): if not hasattr(op, "__call__"): raise TypeError("op {} needs to be callable".format(op)) self.op = op if args is None: self.args = [] else: self.args = args self.validator = validator if (validator is not None) and check: self.validate() @staticmethod def _build_args(args): return [i.build() if isinstance(i, ExprBuilder) else i for i in args] def validate(self): if self.validator is None: return args = self._build_args(self.args) self.validator(*args) def build(self, check=True): args = self._build_args(self.args) if self.validator and check: self.validator(*args) return self.op(*args) def append_argument(self, arg, check=True): self.args.append(arg) if self.validator and check: self.validate(*self.args) def __getitem__(self, item): if item == 0: return self.op else: return self.args[item-1] def __repr__(self): return str(self.build()) def search_element(self, elem): for i, arg in enumerate(self.args): if isinstance(arg, ExprBuilder): ret = arg.search_index(elem) if ret is not None: return (i,) + ret elif id(arg) == id(elem): return (i,) return None from .mul import Mul from .add import Add from .power import Pow from .function import Function, _derivative_dispatch from .mod import Mod from .exprtools import factor_terms from .numbers import Float, Integer, Rational, _illegal
4f1274625ba754b8da61fbd4a58918149be77fc96b18cc7af05e721d013e8c26
from __future__ import annotations import numbers import decimal import fractions import math import re as regex import sys from functools import lru_cache from .containers import Tuple from .sympify import (SympifyError, _sympy_converter, sympify, _convert_numpy_types, _sympify, _is_numpy_instance) from .singleton import S, Singleton from .basic import Basic from .expr import Expr, AtomicExpr from .evalf import pure_complex from .cache import cacheit, clear_cache from .decorators import _sympifyit from .logic import fuzzy_not from .kind import NumberKind from sympy.external.gmpy import SYMPY_INTS, HAS_GMPY, gmpy from sympy.multipledispatch import dispatch import mpmath import mpmath.libmp as mlib from mpmath.libmp import bitcount, round_nearest as rnd from mpmath.libmp.backend import MPZ from mpmath.libmp import mpf_pow, mpf_pi, mpf_e, phi_fixed from mpmath.ctx_mp import mpnumeric from mpmath.libmp.libmpf import ( finf as _mpf_inf, fninf as _mpf_ninf, fnan as _mpf_nan, fzero, _normalize as mpf_normalize, prec_to_dps, dps_to_prec) from sympy.utilities.misc import as_int, debug, filldedent from .parameters import global_parameters _LOG2 = math.log(2) def comp(z1, z2, tol=None): r"""Return a bool indicating whether the error between z1 and z2 is $\le$ ``tol``. Examples ======== If ``tol`` is ``None`` then ``True`` will be returned if :math:`|z1 - z2|\times 10^p \le 5` where $p$ is minimum value of the decimal precision of each value. >>> from sympy import comp, pi >>> pi4 = pi.n(4); pi4 3.142 >>> comp(_, 3.142) True >>> comp(pi4, 3.141) False >>> comp(pi4, 3.143) False A comparison of strings will be made if ``z1`` is a Number and ``z2`` is a string or ``tol`` is ''. >>> comp(pi4, 3.1415) True >>> comp(pi4, 3.1415, '') False When ``tol`` is provided and $z2$ is non-zero and :math:`|z1| > 1` the error is normalized by :math:`|z1|`: >>> abs(pi4 - 3.14)/pi4 0.000509791731426756 >>> comp(pi4, 3.14, .001) # difference less than 0.1% True >>> comp(pi4, 3.14, .0005) # difference less than 0.1% False When :math:`|z1| \le 1` the absolute error is used: >>> 1/pi4 0.3183 >>> abs(1/pi4 - 0.3183)/(1/pi4) 3.07371499106316e-5 >>> abs(1/pi4 - 0.3183) 9.78393554684764e-6 >>> comp(1/pi4, 0.3183, 1e-5) True To see if the absolute error between ``z1`` and ``z2`` is less than or equal to ``tol``, call this as ``comp(z1 - z2, 0, tol)`` or ``comp(z1 - z2, tol=tol)``: >>> abs(pi4 - 3.14) 0.00160156249999988 >>> comp(pi4 - 3.14, 0, .002) True >>> comp(pi4 - 3.14, 0, .001) False """ if isinstance(z2, str): if not pure_complex(z1, or_real=True): raise ValueError('when z2 is a str z1 must be a Number') return str(z1) == z2 if not z1: z1, z2 = z2, z1 if not z1: return True if not tol: a, b = z1, z2 if tol == '': return str(a) == str(b) if tol is None: a, b = sympify(a), sympify(b) if not all(i.is_number for i in (a, b)): raise ValueError('expecting 2 numbers') fa = a.atoms(Float) fb = b.atoms(Float) if not fa and not fb: # no floats -- compare exactly return a == b # get a to be pure_complex for _ in range(2): ca = pure_complex(a, or_real=True) if not ca: if fa: a = a.n(prec_to_dps(min([i._prec for i in fa]))) ca = pure_complex(a, or_real=True) break else: fa, fb = fb, fa a, b = b, a cb = pure_complex(b) if not cb and fb: b = b.n(prec_to_dps(min([i._prec for i in fb]))) cb = pure_complex(b, or_real=True) if ca and cb and (ca[1] or cb[1]): return all(comp(i, j) for i, j in zip(ca, cb)) tol = 10**prec_to_dps(min(a._prec, getattr(b, '_prec', a._prec))) return int(abs(a - b)*tol) <= 5 diff = abs(z1 - z2) az1 = abs(z1) if z2 and az1 > 1: return diff/az1 <= tol else: return diff <= tol def mpf_norm(mpf, prec): """Return the mpf tuple normalized appropriately for the indicated precision after doing a check to see if zero should be returned or not when the mantissa is 0. ``mpf_normlize`` always assumes that this is zero, but it may not be since the mantissa for mpf's values "+inf", "-inf" and "nan" have a mantissa of zero, too. Note: this is not intended to validate a given mpf tuple, so sending mpf tuples that were not created by mpmath may produce bad results. This is only a wrapper to ``mpf_normalize`` which provides the check for non- zero mpfs that have a 0 for the mantissa. """ sign, man, expt, bc = mpf if not man: # hack for mpf_normalize which does not do this; # it assumes that if man is zero the result is 0 # (see issue 6639) if not bc: return fzero else: # don't change anything; this should already # be a well formed mpf tuple return mpf # Necessary if mpmath is using the gmpy backend from mpmath.libmp.backend import MPZ rv = mpf_normalize(sign, MPZ(man), expt, bc, prec, rnd) return rv # TODO: we should use the warnings module _errdict = {"divide": False} def seterr(divide=False): """ Should SymPy raise an exception on 0/0 or return a nan? divide == True .... raise an exception divide == False ... return nan """ if _errdict["divide"] != divide: clear_cache() _errdict["divide"] = divide def _as_integer_ratio(p): neg_pow, man, expt, _ = getattr(p, '_mpf_', mpmath.mpf(p)._mpf_) p = [1, -1][neg_pow % 2]*man if expt < 0: q = 2**-expt else: q = 1 p *= 2**expt return int(p), int(q) def _decimal_to_Rational_prec(dec): """Convert an ordinary decimal instance to a Rational.""" if not dec.is_finite(): raise TypeError("dec must be finite, got %s." % dec) s, d, e = dec.as_tuple() prec = len(d) if e >= 0: # it's an integer rv = Integer(int(dec)) else: s = (-1)**s d = sum([di*10**i for i, di in enumerate(reversed(d))]) rv = Rational(s*d, 10**-e) return rv, prec _floatpat = regex.compile(r"[-+]?((\d*\.\d+)|(\d+\.?))") def _literal_float(f): """Return True if n starts like a floating point number.""" return bool(_floatpat.match(f)) # (a,b) -> gcd(a,b) # TODO caching with decorator, but not to degrade performance @lru_cache(1024) def igcd(*args): """Computes nonnegative integer greatest common divisor. Explanation =========== The algorithm is based on the well known Euclid's algorithm [1]_. To improve speed, ``igcd()`` has its own caching mechanism. Examples ======== >>> from sympy import igcd >>> igcd(2, 4) 2 >>> igcd(5, 10, 15) 5 References ========== .. [1] https://en.wikipedia.org/wiki/Euclidean_algorithm """ if len(args) < 2: raise TypeError( 'igcd() takes at least 2 arguments (%s given)' % len(args)) args_temp = [abs(as_int(i)) for i in args] if 1 in args_temp: return 1 a = args_temp.pop() if HAS_GMPY: # Using gmpy if present to speed up. for b in args_temp: a = gmpy.gcd(a, b) if b else a return as_int(a) for b in args_temp: a = math.gcd(a, b) return a igcd2 = math.gcd def igcd_lehmer(a, b): r"""Computes greatest common divisor of two integers. Explanation =========== Euclid's algorithm for the computation of the greatest common divisor ``gcd(a, b)`` of two (positive) integers $a$ and $b$ is based on the division identity $$ a = q \times b + r$$, where the quotient $q$ and the remainder $r$ are integers and $0 \le r < b$. Then each common divisor of $a$ and $b$ divides $r$, and it follows that ``gcd(a, b) == gcd(b, r)``. The algorithm works by constructing the sequence r0, r1, r2, ..., where r0 = a, r1 = b, and each rn is the remainder from the division of the two preceding elements. In Python, ``q = a // b`` and ``r = a % b`` are obtained by the floor division and the remainder operations, respectively. These are the most expensive arithmetic operations, especially for large a and b. Lehmer's algorithm [1]_ is based on the observation that the quotients ``qn = r(n-1) // rn`` are in general small integers even when a and b are very large. Hence the quotients can be usually determined from a relatively small number of most significant bits. The efficiency of the algorithm is further enhanced by not computing each long remainder in Euclid's sequence. The remainders are linear combinations of a and b with integer coefficients derived from the quotients. The coefficients can be computed as far as the quotients can be determined from the chosen most significant parts of a and b. Only then a new pair of consecutive remainders is computed and the algorithm starts anew with this pair. References ========== .. [1] https://en.wikipedia.org/wiki/Lehmer%27s_GCD_algorithm """ a, b = abs(as_int(a)), abs(as_int(b)) if a < b: a, b = b, a # The algorithm works by using one or two digit division # whenever possible. The outer loop will replace the # pair (a, b) with a pair of shorter consecutive elements # of the Euclidean gcd sequence until a and b # fit into two Python (long) int digits. nbits = 2*sys.int_info.bits_per_digit while a.bit_length() > nbits and b != 0: # Quotients are mostly small integers that can # be determined from most significant bits. n = a.bit_length() - nbits x, y = int(a >> n), int(b >> n) # most significant bits # Elements of the Euclidean gcd sequence are linear # combinations of a and b with integer coefficients. # Compute the coefficients of consecutive pairs # a' = A*a + B*b, b' = C*a + D*b # using small integer arithmetic as far as possible. A, B, C, D = 1, 0, 0, 1 # initial values while True: # The coefficients alternate in sign while looping. # The inner loop combines two steps to keep track # of the signs. # At this point we have # A > 0, B <= 0, C <= 0, D > 0, # x' = x + B <= x < x" = x + A, # y' = y + C <= y < y" = y + D, # and # x'*N <= a' < x"*N, y'*N <= b' < y"*N, # where N = 2**n. # Now, if y' > 0, and x"//y' and x'//y" agree, # then their common value is equal to q = a'//b'. # In addition, # x'%y" = x' - q*y" < x" - q*y' = x"%y', # and # (x'%y")*N < a'%b' < (x"%y')*N. # On the other hand, we also have x//y == q, # and therefore # x'%y" = x + B - q*(y + D) = x%y + B', # x"%y' = x + A - q*(y + C) = x%y + A', # where # B' = B - q*D < 0, A' = A - q*C > 0. if y + C <= 0: break q = (x + A) // (y + C) # Now x'//y" <= q, and equality holds if # x' - q*y" = (x - q*y) + (B - q*D) >= 0. # This is a minor optimization to avoid division. x_qy, B_qD = x - q*y, B - q*D if x_qy + B_qD < 0: break # Next step in the Euclidean sequence. x, y = y, x_qy A, B, C, D = C, D, A - q*C, B_qD # At this point the signs of the coefficients # change and their roles are interchanged. # A <= 0, B > 0, C > 0, D < 0, # x' = x + A <= x < x" = x + B, # y' = y + D < y < y" = y + C. if y + D <= 0: break q = (x + B) // (y + D) x_qy, A_qC = x - q*y, A - q*C if x_qy + A_qC < 0: break x, y = y, x_qy A, B, C, D = C, D, A_qC, B - q*D # Now the conditions on top of the loop # are again satisfied. # A > 0, B < 0, C < 0, D > 0. if B == 0: # This can only happen when y == 0 in the beginning # and the inner loop does nothing. # Long division is forced. a, b = b, a % b continue # Compute new long arguments using the coefficients. a, b = A*a + B*b, C*a + D*b # Small divisors. Finish with the standard algorithm. while b: a, b = b, a % b return a def ilcm(*args): """Computes integer least common multiple. Examples ======== >>> from sympy import ilcm >>> ilcm(5, 10) 10 >>> ilcm(7, 3) 21 >>> ilcm(5, 10, 15) 30 """ if len(args) < 2: raise TypeError( 'ilcm() takes at least 2 arguments (%s given)' % len(args)) if 0 in args: return 0 a = args[0] for b in args[1:]: a = a // igcd(a, b) * b # since gcd(a,b) | a return a def igcdex(a, b): """Returns x, y, g such that g = x*a + y*b = gcd(a, b). Examples ======== >>> from sympy.core.numbers import igcdex >>> igcdex(2, 3) (-1, 1, 1) >>> igcdex(10, 12) (-1, 1, 2) >>> x, y, g = igcdex(100, 2004) >>> x, y, g (-20, 1, 4) >>> x*100 + y*2004 4 """ if (not a) and (not b): return (0, 1, 0) if not a: return (0, b//abs(b), abs(b)) if not b: return (a//abs(a), 0, abs(a)) if a < 0: a, x_sign = -a, -1 else: x_sign = 1 if b < 0: b, y_sign = -b, -1 else: y_sign = 1 x, y, r, s = 1, 0, 0, 1 while b: (c, q) = (a % b, a // b) (a, b, r, s, x, y) = (b, c, x - q*r, y - q*s, r, s) return (x*x_sign, y*y_sign, a) def mod_inverse(a, m): r""" Return the number $c$ such that, $a \times c = 1 \pmod{m}$ where $c$ has the same sign as $m$. If no such value exists, a ValueError is raised. Examples ======== >>> from sympy import mod_inverse, S Suppose we wish to find multiplicative inverse $x$ of 3 modulo 11. This is the same as finding $x$ such that $3x = 1 \pmod{11}$. One value of x that satisfies this congruence is 4. Because $3 \times 4 = 12$ and $12 = 1 \pmod{11}$. This is the value returned by ``mod_inverse``: >>> mod_inverse(3, 11) 4 >>> mod_inverse(-3, 11) 7 When there is a common factor between the numerators of `a` and `m` the inverse does not exist: >>> mod_inverse(2, 4) Traceback (most recent call last): ... ValueError: inverse of 2 mod 4 does not exist >>> mod_inverse(S(2)/7, S(5)/2) 7/2 References ========== .. [1] https://en.wikipedia.org/wiki/Modular_multiplicative_inverse .. [2] https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm """ c = None try: a, m = as_int(a), as_int(m) if m != 1 and m != -1: x, _, g = igcdex(a, m) if g == 1: c = x % m except ValueError: a, m = sympify(a), sympify(m) if not (a.is_number and m.is_number): raise TypeError(filldedent(''' Expected numbers for arguments; symbolic `mod_inverse` is not implemented but symbolic expressions can be handled with the similar function, sympy.polys.polytools.invert''')) big = (m > 1) if big not in (S.true, S.false): raise ValueError('m > 1 did not evaluate; try to simplify %s' % m) elif big: c = 1/a if c is None: raise ValueError('inverse of %s (mod %s) does not exist' % (a, m)) return c class Number(AtomicExpr): """Represents atomic numbers in SymPy. Explanation =========== Floating point numbers are represented by the Float class. Rational numbers (of any size) are represented by the Rational class. Integer numbers (of any size) are represented by the Integer class. Float and Rational are subclasses of Number; Integer is a subclass of Rational. For example, ``2/3`` is represented as ``Rational(2, 3)`` which is a different object from the floating point number obtained with Python division ``2/3``. Even for numbers that are exactly represented in binary, there is a difference between how two forms, such as ``Rational(1, 2)`` and ``Float(0.5)``, are used in SymPy. The rational form is to be preferred in symbolic computations. Other kinds of numbers, such as algebraic numbers ``sqrt(2)`` or complex numbers ``3 + 4*I``, are not instances of Number class as they are not atomic. See Also ======== Float, Integer, Rational """ is_commutative = True is_number = True is_Number = True __slots__ = () # Used to make max(x._prec, y._prec) return x._prec when only x is a float _prec = -1 kind = NumberKind def __new__(cls, *obj): if len(obj) == 1: obj = obj[0] if isinstance(obj, Number): return obj if isinstance(obj, SYMPY_INTS): return Integer(obj) if isinstance(obj, tuple) and len(obj) == 2: return Rational(*obj) if isinstance(obj, (float, mpmath.mpf, decimal.Decimal)): return Float(obj) if isinstance(obj, str): _obj = obj.lower() # float('INF') == float('inf') if _obj == 'nan': return S.NaN elif _obj == 'inf': return S.Infinity elif _obj == '+inf': return S.Infinity elif _obj == '-inf': return S.NegativeInfinity val = sympify(obj) if isinstance(val, Number): return val else: raise ValueError('String "%s" does not denote a Number' % obj) msg = "expected str|int|long|float|Decimal|Number object but got %r" raise TypeError(msg % type(obj).__name__) def could_extract_minus_sign(self): return bool(self.is_extended_negative) def invert(self, other, *gens, **args): from sympy.polys.polytools import invert if getattr(other, 'is_number', True): return mod_inverse(self, other) return invert(self, other, *gens, **args) def __divmod__(self, other): from sympy.functions.elementary.complexes import sign try: other = Number(other) if self.is_infinite or S.NaN in (self, other): return (S.NaN, S.NaN) except TypeError: return NotImplemented if not other: raise ZeroDivisionError('modulo by zero') if self.is_Integer and other.is_Integer: return Tuple(*divmod(self.p, other.p)) elif isinstance(other, Float): rat = self/Rational(other) else: rat = self/other if other.is_finite: w = int(rat) if rat >= 0 else int(rat) - 1 r = self - other*w else: w = 0 if not self or (sign(self) == sign(other)) else -1 r = other if w else self return Tuple(w, r) def __rdivmod__(self, other): try: other = Number(other) except TypeError: return NotImplemented return divmod(other, self) def _as_mpf_val(self, prec): """Evaluation of mpf tuple accurate to at least prec bits.""" raise NotImplementedError('%s needs ._as_mpf_val() method' % (self.__class__.__name__)) def _eval_evalf(self, prec): return Float._new(self._as_mpf_val(prec), prec) def _as_mpf_op(self, prec): prec = max(prec, self._prec) return self._as_mpf_val(prec), prec def __float__(self): return mlib.to_float(self._as_mpf_val(53)) def floor(self): raise NotImplementedError('%s needs .floor() method' % (self.__class__.__name__)) def ceiling(self): raise NotImplementedError('%s needs .ceiling() method' % (self.__class__.__name__)) def __floor__(self): return self.floor() def __ceil__(self): return self.ceiling() def _eval_conjugate(self): return self def _eval_order(self, *symbols): from sympy.series.order import Order # Order(5, x, y) -> Order(1,x,y) return Order(S.One, *symbols) def _eval_subs(self, old, new): if old == -self: return -new return self # there is no other possibility @classmethod def class_key(cls): return 1, 0, 'Number' @cacheit def sort_key(self, order=None): return self.class_key(), (0, ()), (), self @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other is S.NaN: return S.NaN elif other is S.Infinity: return S.Infinity elif other is S.NegativeInfinity: return S.NegativeInfinity return AtomicExpr.__add__(self, other) @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other is S.NaN: return S.NaN elif other is S.Infinity: return S.NegativeInfinity elif other is S.NegativeInfinity: return S.Infinity return AtomicExpr.__sub__(self, other) @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other is S.NaN: return S.NaN elif other is S.Infinity: if self.is_zero: return S.NaN elif self.is_positive: return S.Infinity else: return S.NegativeInfinity elif other is S.NegativeInfinity: if self.is_zero: return S.NaN elif self.is_positive: return S.NegativeInfinity else: return S.Infinity elif isinstance(other, Tuple): return NotImplemented return AtomicExpr.__mul__(self, other) @_sympifyit('other', NotImplemented) def __truediv__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other is S.NaN: return S.NaN elif other in (S.Infinity, S.NegativeInfinity): return S.Zero return AtomicExpr.__truediv__(self, other) def __eq__(self, other): raise NotImplementedError('%s needs .__eq__() method' % (self.__class__.__name__)) def __ne__(self, other): raise NotImplementedError('%s needs .__ne__() method' % (self.__class__.__name__)) def __lt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s < %s" % (self, other)) raise NotImplementedError('%s needs .__lt__() method' % (self.__class__.__name__)) def __le__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s <= %s" % (self, other)) raise NotImplementedError('%s needs .__le__() method' % (self.__class__.__name__)) def __gt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s > %s" % (self, other)) return _sympify(other).__lt__(self) def __ge__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s >= %s" % (self, other)) return _sympify(other).__le__(self) def __hash__(self): return super().__hash__() def is_constant(self, *wrt, **flags): return True def as_coeff_mul(self, *deps, rational=True, **kwargs): # a -> c*t if self.is_Rational or not rational: return self, tuple() elif self.is_negative: return S.NegativeOne, (-self,) return S.One, (self,) def as_coeff_add(self, *deps): # a -> c + t if self.is_Rational: return self, tuple() return S.Zero, (self,) def as_coeff_Mul(self, rational=False): """Efficiently extract the coefficient of a product.""" if rational and not self.is_Rational: return S.One, self return (self, S.One) if self else (S.One, self) def as_coeff_Add(self, rational=False): """Efficiently extract the coefficient of a summation.""" if not rational: return self, S.Zero return S.Zero, self def gcd(self, other): """Compute GCD of `self` and `other`. """ from sympy.polys.polytools import gcd return gcd(self, other) def lcm(self, other): """Compute LCM of `self` and `other`. """ from sympy.polys.polytools import lcm return lcm(self, other) def cofactors(self, other): """Compute GCD and cofactors of `self` and `other`. """ from sympy.polys.polytools import cofactors return cofactors(self, other) class Float(Number): """Represent a floating-point number of arbitrary precision. Examples ======== >>> from sympy import Float >>> Float(3.5) 3.50000000000000 >>> Float(3) 3.00000000000000 Creating Floats from strings (and Python ``int`` and ``long`` types) will give a minimum precision of 15 digits, but the precision will automatically increase to capture all digits entered. >>> Float(1) 1.00000000000000 >>> Float(10**20) 100000000000000000000. >>> Float('1e20') 100000000000000000000. However, *floating-point* numbers (Python ``float`` types) retain only 15 digits of precision: >>> Float(1e20) 1.00000000000000e+20 >>> Float(1.23456789123456789) 1.23456789123457 It may be preferable to enter high-precision decimal numbers as strings: >>> Float('1.23456789123456789') 1.23456789123456789 The desired number of digits can also be specified: >>> Float('1e-3', 3) 0.00100 >>> Float(100, 4) 100.0 Float can automatically count significant figures if a null string is sent for the precision; spaces or underscores are also allowed. (Auto- counting is only allowed for strings, ints and longs). >>> Float('123 456 789.123_456', '') 123456789.123456 >>> Float('12e-3', '') 0.012 >>> Float(3, '') 3. If a number is written in scientific notation, only the digits before the exponent are considered significant if a decimal appears, otherwise the "e" signifies only how to move the decimal: >>> Float('60.e2', '') # 2 digits significant 6.0e+3 >>> Float('60e2', '') # 4 digits significant 6000. >>> Float('600e-2', '') # 3 digits significant 6.00 Notes ===== Floats are inexact by their nature unless their value is a binary-exact value. >>> approx, exact = Float(.1, 1), Float(.125, 1) For calculation purposes, evalf needs to be able to change the precision but this will not increase the accuracy of the inexact value. The following is the most accurate 5-digit approximation of a value of 0.1 that had only 1 digit of precision: >>> approx.evalf(5) 0.099609 By contrast, 0.125 is exact in binary (as it is in base 10) and so it can be passed to Float or evalf to obtain an arbitrary precision with matching accuracy: >>> Float(exact, 5) 0.12500 >>> exact.evalf(20) 0.12500000000000000000 Trying to make a high-precision Float from a float is not disallowed, but one must keep in mind that the *underlying float* (not the apparent decimal value) is being obtained with high precision. For example, 0.3 does not have a finite binary representation. The closest rational is the fraction 5404319552844595/2**54. So if you try to obtain a Float of 0.3 to 20 digits of precision you will not see the same thing as 0.3 followed by 19 zeros: >>> Float(0.3, 20) 0.29999999999999998890 If you want a 20-digit value of the decimal 0.3 (not the floating point approximation of 0.3) you should send the 0.3 as a string. The underlying representation is still binary but a higher precision than Python's float is used: >>> Float('0.3', 20) 0.30000000000000000000 Although you can increase the precision of an existing Float using Float it will not increase the accuracy -- the underlying value is not changed: >>> def show(f): # binary rep of Float ... from sympy import Mul, Pow ... s, m, e, b = f._mpf_ ... v = Mul(int(m), Pow(2, int(e), evaluate=False), evaluate=False) ... print('%s at prec=%s' % (v, f._prec)) ... >>> t = Float('0.3', 3) >>> show(t) 4915/2**14 at prec=13 >>> show(Float(t, 20)) # higher prec, not higher accuracy 4915/2**14 at prec=70 >>> show(Float(t, 2)) # lower prec 307/2**10 at prec=10 The same thing happens when evalf is used on a Float: >>> show(t.evalf(20)) 4915/2**14 at prec=70 >>> show(t.evalf(2)) 307/2**10 at prec=10 Finally, Floats can be instantiated with an mpf tuple (n, c, p) to produce the number (-1)**n*c*2**p: >>> n, c, p = 1, 5, 0 >>> (-1)**n*c*2**p -5 >>> Float((1, 5, 0)) -5.00000000000000 An actual mpf tuple also contains the number of bits in c as the last element of the tuple: >>> _._mpf_ (1, 5, 0, 3) This is not needed for instantiation and is not the same thing as the precision. The mpf tuple and the precision are two separate quantities that Float tracks. In SymPy, a Float is a number that can be computed with arbitrary precision. Although floating point 'inf' and 'nan' are not such numbers, Float can create these numbers: >>> Float('-inf') -oo >>> _.is_Float False Zero in Float only has a single value. Values are not separate for positive and negative zeroes. """ __slots__ = ('_mpf_', '_prec') _mpf_: tuple[int, int, int, int] # A Float represents many real numbers, # both rational and irrational. is_rational = None is_irrational = None is_number = True is_real = True is_extended_real = True is_Float = True def __new__(cls, num, dps=None, precision=None): if dps is not None and precision is not None: raise ValueError('Both decimal and binary precision supplied. ' 'Supply only one. ') if isinstance(num, str): # Float accepts spaces as digit separators num = num.replace(' ', '').lower() if num.startswith('.') and len(num) > 1: num = '0' + num elif num.startswith('-.') and len(num) > 2: num = '-0.' + num[2:] elif num in ('inf', '+inf'): return S.Infinity elif num == '-inf': return S.NegativeInfinity elif isinstance(num, float) and num == 0: num = '0' elif isinstance(num, float) and num == float('inf'): return S.Infinity elif isinstance(num, float) and num == float('-inf'): return S.NegativeInfinity elif isinstance(num, float) and math.isnan(num): return S.NaN elif isinstance(num, (SYMPY_INTS, Integer)): num = str(num) elif num is S.Infinity: return num elif num is S.NegativeInfinity: return num elif num is S.NaN: return num elif _is_numpy_instance(num): # support for numpy datatypes num = _convert_numpy_types(num) elif isinstance(num, mpmath.mpf): if precision is None: if dps is None: precision = num.context.prec num = num._mpf_ if dps is None and precision is None: dps = 15 if isinstance(num, Float): return num if isinstance(num, str) and _literal_float(num): try: Num = decimal.Decimal(num) except decimal.InvalidOperation: pass else: isint = '.' not in num num, dps = _decimal_to_Rational_prec(Num) if num.is_Integer and isint: dps = max(dps, len(str(num).lstrip('-'))) dps = max(15, dps) precision = dps_to_prec(dps) elif precision == '' and dps is None or precision is None and dps == '': if not isinstance(num, str): raise ValueError('The null string can only be used when ' 'the number to Float is passed as a string or an integer.') ok = None if _literal_float(num): try: Num = decimal.Decimal(num) except decimal.InvalidOperation: pass else: isint = '.' not in num num, dps = _decimal_to_Rational_prec(Num) if num.is_Integer and isint: dps = max(dps, len(str(num).lstrip('-'))) precision = dps_to_prec(dps) ok = True if ok is None: raise ValueError('string-float not recognized: %s' % num) # decimal precision(dps) is set and maybe binary precision(precision) # as well.From here on binary precision is used to compute the Float. # Hence, if supplied use binary precision else translate from decimal # precision. if precision is None or precision == '': precision = dps_to_prec(dps) precision = int(precision) if isinstance(num, float): _mpf_ = mlib.from_float(num, precision, rnd) elif isinstance(num, str): _mpf_ = mlib.from_str(num, precision, rnd) elif isinstance(num, decimal.Decimal): if num.is_finite(): _mpf_ = mlib.from_str(str(num), precision, rnd) elif num.is_nan(): return S.NaN elif num.is_infinite(): if num > 0: return S.Infinity return S.NegativeInfinity else: raise ValueError("unexpected decimal value %s" % str(num)) elif isinstance(num, tuple) and len(num) in (3, 4): if isinstance(num[1], str): # it's a hexadecimal (coming from a pickled object) num = list(num) # If we're loading an object pickled in Python 2 into # Python 3, we may need to strip a tailing 'L' because # of a shim for int on Python 3, see issue #13470. if num[1].endswith('L'): num[1] = num[1][:-1] # Strip leading '0x' - gmpy2 only documents such inputs # with base prefix as valid when the 2nd argument (base) is 0. # When mpmath uses Sage as the backend, however, it # ends up including '0x' when preparing the picklable tuple. # See issue #19690. if num[1].startswith('0x'): num[1] = num[1][2:] # Now we can assume that it is in standard form num[1] = MPZ(num[1], 16) _mpf_ = tuple(num) else: if len(num) == 4: # handle normalization hack return Float._new(num, precision) else: if not all(( num[0] in (0, 1), num[1] >= 0, all(type(i) in (int, int) for i in num) )): raise ValueError('malformed mpf: %s' % (num,)) # don't compute number or else it may # over/underflow return Float._new( (num[0], num[1], num[2], bitcount(num[1])), precision) else: try: _mpf_ = num._as_mpf_val(precision) except (NotImplementedError, AttributeError): _mpf_ = mpmath.mpf(num, prec=precision)._mpf_ return cls._new(_mpf_, precision, zero=False) @classmethod def _new(cls, _mpf_, _prec, zero=True): # special cases if zero and _mpf_ == fzero: return S.Zero # Float(0) -> 0.0; Float._new((0,0,0,0)) -> 0 elif _mpf_ == _mpf_nan: return S.NaN elif _mpf_ == _mpf_inf: return S.Infinity elif _mpf_ == _mpf_ninf: return S.NegativeInfinity obj = Expr.__new__(cls) obj._mpf_ = mpf_norm(_mpf_, _prec) obj._prec = _prec return obj # mpz can't be pickled def __getnewargs_ex__(self): return ((mlib.to_pickable(self._mpf_),), {'precision': self._prec}) def _hashable_content(self): return (self._mpf_, self._prec) def floor(self): return Integer(int(mlib.to_int( mlib.mpf_floor(self._mpf_, self._prec)))) def ceiling(self): return Integer(int(mlib.to_int( mlib.mpf_ceil(self._mpf_, self._prec)))) def __floor__(self): return self.floor() def __ceil__(self): return self.ceiling() @property def num(self): return mpmath.mpf(self._mpf_) def _as_mpf_val(self, prec): rv = mpf_norm(self._mpf_, prec) if rv != self._mpf_ and self._prec == prec: debug(self._mpf_, rv) return rv def _as_mpf_op(self, prec): return self._mpf_, max(prec, self._prec) def _eval_is_finite(self): if self._mpf_ in (_mpf_inf, _mpf_ninf): return False return True def _eval_is_infinite(self): if self._mpf_ in (_mpf_inf, _mpf_ninf): return True return False def _eval_is_integer(self): return self._mpf_ == fzero def _eval_is_negative(self): if self._mpf_ in (_mpf_ninf, _mpf_inf): return False return self.num < 0 def _eval_is_positive(self): if self._mpf_ in (_mpf_ninf, _mpf_inf): return False return self.num > 0 def _eval_is_extended_negative(self): if self._mpf_ == _mpf_ninf: return True if self._mpf_ == _mpf_inf: return False return self.num < 0 def _eval_is_extended_positive(self): if self._mpf_ == _mpf_inf: return True if self._mpf_ == _mpf_ninf: return False return self.num > 0 def _eval_is_zero(self): return self._mpf_ == fzero def __bool__(self): return self._mpf_ != fzero def __neg__(self): if not self: return self return Float._new(mlib.mpf_neg(self._mpf_), self._prec) @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Number) and global_parameters.evaluate: rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_add(self._mpf_, rhs, prec, rnd), prec) return Number.__add__(self, other) @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Number) and global_parameters.evaluate: rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_sub(self._mpf_, rhs, prec, rnd), prec) return Number.__sub__(self, other) @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Number) and global_parameters.evaluate: rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_mul(self._mpf_, rhs, prec, rnd), prec) return Number.__mul__(self, other) @_sympifyit('other', NotImplemented) def __truediv__(self, other): if isinstance(other, Number) and other != 0 and global_parameters.evaluate: rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_div(self._mpf_, rhs, prec, rnd), prec) return Number.__truediv__(self, other) @_sympifyit('other', NotImplemented) def __mod__(self, other): if isinstance(other, Rational) and other.q != 1 and global_parameters.evaluate: # calculate mod with Rationals, *then* round the result return Float(Rational.__mod__(Rational(self), other), precision=self._prec) if isinstance(other, Float) and global_parameters.evaluate: r = self/other if r == int(r): return Float(0, precision=max(self._prec, other._prec)) if isinstance(other, Number) and global_parameters.evaluate: rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_mod(self._mpf_, rhs, prec, rnd), prec) return Number.__mod__(self, other) @_sympifyit('other', NotImplemented) def __rmod__(self, other): if isinstance(other, Float) and global_parameters.evaluate: return other.__mod__(self) if isinstance(other, Number) and global_parameters.evaluate: rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_mod(rhs, self._mpf_, prec, rnd), prec) return Number.__rmod__(self, other) def _eval_power(self, expt): """ expt is symbolic object but not equal to 0, 1 (-p)**r -> exp(r*log(-p)) -> exp(r*(log(p) + I*Pi)) -> -> p**r*(sin(Pi*r) + cos(Pi*r)*I) """ if equal_valued(self, 0): if expt.is_extended_positive: return self if expt.is_extended_negative: return S.ComplexInfinity if isinstance(expt, Number): if isinstance(expt, Integer): prec = self._prec return Float._new( mlib.mpf_pow_int(self._mpf_, expt.p, prec, rnd), prec) elif isinstance(expt, Rational) and \ expt.p == 1 and expt.q % 2 and self.is_negative: return Pow(S.NegativeOne, expt, evaluate=False)*( -self)._eval_power(expt) expt, prec = expt._as_mpf_op(self._prec) mpfself = self._mpf_ try: y = mpf_pow(mpfself, expt, prec, rnd) return Float._new(y, prec) except mlib.ComplexResult: re, im = mlib.mpc_pow( (mpfself, fzero), (expt, fzero), prec, rnd) return Float._new(re, prec) + \ Float._new(im, prec)*S.ImaginaryUnit def __abs__(self): return Float._new(mlib.mpf_abs(self._mpf_), self._prec) def __int__(self): if self._mpf_ == fzero: return 0 return int(mlib.to_int(self._mpf_)) # uses round_fast = round_down def __eq__(self, other): from sympy.logic.boolalg import Boolean try: other = _sympify(other) except SympifyError: return NotImplemented if isinstance(other, Boolean): return False if other.is_NumberSymbol: if other.is_irrational: return False return other.__eq__(self) if other.is_Float: # comparison is exact # so Float(.1, 3) != Float(.1, 33) return self._mpf_ == other._mpf_ if other.is_Rational: return other.__eq__(self) if other.is_Number: # numbers should compare at the same precision; # all _as_mpf_val routines should be sure to abide # by the request to change the prec if necessary; if # they don't, the equality test will fail since it compares # the mpf tuples ompf = other._as_mpf_val(self._prec) return bool(mlib.mpf_eq(self._mpf_, ompf)) if not self: return not other return False # Float != non-Number def __ne__(self, other): return not self == other def _Frel(self, other, op): try: other = _sympify(other) except SympifyError: return NotImplemented if other.is_Rational: # test self*other.q <?> other.p without losing precision ''' >>> f = Float(.1,2) >>> i = 1234567890 >>> (f*i)._mpf_ (0, 471, 18, 9) >>> mlib.mpf_mul(f._mpf_, mlib.from_int(i)) (0, 505555550955, -12, 39) ''' smpf = mlib.mpf_mul(self._mpf_, mlib.from_int(other.q)) ompf = mlib.from_int(other.p) return _sympify(bool(op(smpf, ompf))) elif other.is_Float: return _sympify(bool( op(self._mpf_, other._mpf_))) elif other.is_comparable and other not in ( S.Infinity, S.NegativeInfinity): other = other.evalf(prec_to_dps(self._prec)) if other._prec > 1: if other.is_Number: return _sympify(bool( op(self._mpf_, other._as_mpf_val(self._prec)))) def __gt__(self, other): if isinstance(other, NumberSymbol): return other.__lt__(self) rv = self._Frel(other, mlib.mpf_gt) if rv is None: return Expr.__gt__(self, other) return rv def __ge__(self, other): if isinstance(other, NumberSymbol): return other.__le__(self) rv = self._Frel(other, mlib.mpf_ge) if rv is None: return Expr.__ge__(self, other) return rv def __lt__(self, other): if isinstance(other, NumberSymbol): return other.__gt__(self) rv = self._Frel(other, mlib.mpf_lt) if rv is None: return Expr.__lt__(self, other) return rv def __le__(self, other): if isinstance(other, NumberSymbol): return other.__ge__(self) rv = self._Frel(other, mlib.mpf_le) if rv is None: return Expr.__le__(self, other) return rv def __hash__(self): return super().__hash__() def epsilon_eq(self, other, epsilon="1e-15"): return abs(self - other) < Float(epsilon) def __format__(self, format_spec): return format(decimal.Decimal(str(self)), format_spec) # Add sympify converters _sympy_converter[float] = _sympy_converter[decimal.Decimal] = Float # this is here to work nicely in Sage RealNumber = Float class Rational(Number): """Represents rational numbers (p/q) of any size. Examples ======== >>> from sympy import Rational, nsimplify, S, pi >>> Rational(1, 2) 1/2 Rational is unprejudiced in accepting input. If a float is passed, the underlying value of the binary representation will be returned: >>> Rational(.5) 1/2 >>> Rational(.2) 3602879701896397/18014398509481984 If the simpler representation of the float is desired then consider limiting the denominator to the desired value or convert the float to a string (which is roughly equivalent to limiting the denominator to 10**12): >>> Rational(str(.2)) 1/5 >>> Rational(.2).limit_denominator(10**12) 1/5 An arbitrarily precise Rational is obtained when a string literal is passed: >>> Rational("1.23") 123/100 >>> Rational('1e-2') 1/100 >>> Rational(".1") 1/10 >>> Rational('1e-2/3.2') 1/320 The conversion of other types of strings can be handled by the sympify() function, and conversion of floats to expressions or simple fractions can be handled with nsimplify: >>> S('.[3]') # repeating digits in brackets 1/3 >>> S('3**2/10') # general expressions 9/10 >>> nsimplify(.3) # numbers that have a simple form 3/10 But if the input does not reduce to a literal Rational, an error will be raised: >>> Rational(pi) Traceback (most recent call last): ... TypeError: invalid input: pi Low-level --------- Access numerator and denominator as .p and .q: >>> r = Rational(3, 4) >>> r 3/4 >>> r.p 3 >>> r.q 4 Note that p and q return integers (not SymPy Integers) so some care is needed when using them in expressions: >>> r.p/r.q 0.75 If an unevaluated Rational is desired, ``gcd=1`` can be passed and this will keep common divisors of the numerator and denominator from being eliminated. It is not possible, however, to leave a negative value in the denominator. >>> Rational(2, 4, gcd=1) 2/4 >>> Rational(2, -4, gcd=1).q 4 See Also ======== sympy.core.sympify.sympify, sympy.simplify.simplify.nsimplify """ is_real = True is_integer = False is_rational = True is_number = True __slots__ = ('p', 'q') p: int q: int is_Rational = True @cacheit def __new__(cls, p, q=None, gcd=None): if q is None: if isinstance(p, Rational): return p if isinstance(p, SYMPY_INTS): pass else: if isinstance(p, (float, Float)): return Rational(*_as_integer_ratio(p)) if not isinstance(p, str): try: p = sympify(p) except (SympifyError, SyntaxError): pass # error will raise below else: if p.count('/') > 1: raise TypeError('invalid input: %s' % p) p = p.replace(' ', '') pq = p.rsplit('/', 1) if len(pq) == 2: p, q = pq fp = fractions.Fraction(p) fq = fractions.Fraction(q) p = fp/fq try: p = fractions.Fraction(p) except ValueError: pass # error will raise below else: return Rational(p.numerator, p.denominator, 1) if not isinstance(p, Rational): raise TypeError('invalid input: %s' % p) q = 1 gcd = 1 Q = 1 if not isinstance(p, SYMPY_INTS): p = Rational(p) Q *= p.q p = p.p else: p = int(p) if not isinstance(q, SYMPY_INTS): q = Rational(q) p *= q.q Q *= q.p else: Q *= int(q) q = Q # p and q are now ints if q == 0: if p == 0: if _errdict["divide"]: raise ValueError("Indeterminate 0/0") else: return S.NaN return S.ComplexInfinity if q < 0: q = -q p = -p if not gcd: gcd = igcd(abs(p), q) if gcd > 1: p //= gcd q //= gcd if q == 1: return Integer(p) if p == 1 and q == 2: return S.Half obj = Expr.__new__(cls) obj.p = p obj.q = q return obj def limit_denominator(self, max_denominator=1000000): """Closest Rational to self with denominator at most max_denominator. Examples ======== >>> from sympy import Rational >>> Rational('3.141592653589793').limit_denominator(10) 22/7 >>> Rational('3.141592653589793').limit_denominator(100) 311/99 """ f = fractions.Fraction(self.p, self.q) return Rational(f.limit_denominator(fractions.Fraction(int(max_denominator)))) def __getnewargs__(self): return (self.p, self.q) def _hashable_content(self): return (self.p, self.q) def _eval_is_positive(self): return self.p > 0 def _eval_is_zero(self): return self.p == 0 def __neg__(self): return Rational(-self.p, self.q) @_sympifyit('other', NotImplemented) def __add__(self, other): if global_parameters.evaluate: if isinstance(other, Integer): return Rational(self.p + self.q*other.p, self.q, 1) elif isinstance(other, Rational): #TODO: this can probably be optimized more return Rational(self.p*other.q + self.q*other.p, self.q*other.q) elif isinstance(other, Float): return other + self else: return Number.__add__(self, other) return Number.__add__(self, other) __radd__ = __add__ @_sympifyit('other', NotImplemented) def __sub__(self, other): if global_parameters.evaluate: if isinstance(other, Integer): return Rational(self.p - self.q*other.p, self.q, 1) elif isinstance(other, Rational): return Rational(self.p*other.q - self.q*other.p, self.q*other.q) elif isinstance(other, Float): return -other + self else: return Number.__sub__(self, other) return Number.__sub__(self, other) @_sympifyit('other', NotImplemented) def __rsub__(self, other): if global_parameters.evaluate: if isinstance(other, Integer): return Rational(self.q*other.p - self.p, self.q, 1) elif isinstance(other, Rational): return Rational(self.q*other.p - self.p*other.q, self.q*other.q) elif isinstance(other, Float): return -self + other else: return Number.__rsub__(self, other) return Number.__rsub__(self, other) @_sympifyit('other', NotImplemented) def __mul__(self, other): if global_parameters.evaluate: if isinstance(other, Integer): return Rational(self.p*other.p, self.q, igcd(other.p, self.q)) elif isinstance(other, Rational): return Rational(self.p*other.p, self.q*other.q, igcd(self.p, other.q)*igcd(self.q, other.p)) elif isinstance(other, Float): return other*self else: return Number.__mul__(self, other) return Number.__mul__(self, other) __rmul__ = __mul__ @_sympifyit('other', NotImplemented) def __truediv__(self, other): if global_parameters.evaluate: if isinstance(other, Integer): if self.p and other.p == S.Zero: return S.ComplexInfinity else: return Rational(self.p, self.q*other.p, igcd(self.p, other.p)) elif isinstance(other, Rational): return Rational(self.p*other.q, self.q*other.p, igcd(self.p, other.p)*igcd(self.q, other.q)) elif isinstance(other, Float): return self*(1/other) else: return Number.__truediv__(self, other) return Number.__truediv__(self, other) @_sympifyit('other', NotImplemented) def __rtruediv__(self, other): if global_parameters.evaluate: if isinstance(other, Integer): return Rational(other.p*self.q, self.p, igcd(self.p, other.p)) elif isinstance(other, Rational): return Rational(other.p*self.q, other.q*self.p, igcd(self.p, other.p)*igcd(self.q, other.q)) elif isinstance(other, Float): return other*(1/self) else: return Number.__rtruediv__(self, other) return Number.__rtruediv__(self, other) @_sympifyit('other', NotImplemented) def __mod__(self, other): if global_parameters.evaluate: if isinstance(other, Rational): n = (self.p*other.q) // (other.p*self.q) return Rational(self.p*other.q - n*other.p*self.q, self.q*other.q) if isinstance(other, Float): # calculate mod with Rationals, *then* round the answer return Float(self.__mod__(Rational(other)), precision=other._prec) return Number.__mod__(self, other) return Number.__mod__(self, other) @_sympifyit('other', NotImplemented) def __rmod__(self, other): if isinstance(other, Rational): return Rational.__mod__(other, self) return Number.__rmod__(self, other) def _eval_power(self, expt): if isinstance(expt, Number): if isinstance(expt, Float): return self._eval_evalf(expt._prec)**expt if expt.is_extended_negative: # (3/4)**-2 -> (4/3)**2 ne = -expt if (ne is S.One): return Rational(self.q, self.p) if self.is_negative: return S.NegativeOne**expt*Rational(self.q, -self.p)**ne else: return Rational(self.q, self.p)**ne if expt is S.Infinity: # -oo already caught by test for negative if self.p > self.q: # (3/2)**oo -> oo return S.Infinity if self.p < -self.q: # (-3/2)**oo -> oo + I*oo return S.Infinity + S.Infinity*S.ImaginaryUnit return S.Zero if isinstance(expt, Integer): # (4/3)**2 -> 4**2 / 3**2 return Rational(self.p**expt.p, self.q**expt.p, 1) if isinstance(expt, Rational): intpart = expt.p // expt.q if intpart: intpart += 1 remfracpart = intpart*expt.q - expt.p ratfracpart = Rational(remfracpart, expt.q) if self.p != 1: return Integer(self.p)**expt*Integer(self.q)**ratfracpart*Rational(1, self.q**intpart, 1) return Integer(self.q)**ratfracpart*Rational(1, self.q**intpart, 1) else: remfracpart = expt.q - expt.p ratfracpart = Rational(remfracpart, expt.q) if self.p != 1: return Integer(self.p)**expt*Integer(self.q)**ratfracpart*Rational(1, self.q, 1) return Integer(self.q)**ratfracpart*Rational(1, self.q, 1) if self.is_extended_negative and expt.is_even: return (-self)**expt return def _as_mpf_val(self, prec): return mlib.from_rational(self.p, self.q, prec, rnd) def _mpmath_(self, prec, rnd): return mpmath.make_mpf(mlib.from_rational(self.p, self.q, prec, rnd)) def __abs__(self): return Rational(abs(self.p), self.q) def __int__(self): p, q = self.p, self.q if p < 0: return -int(-p//q) return int(p//q) def floor(self): return Integer(self.p // self.q) def ceiling(self): return -Integer(-self.p // self.q) def __floor__(self): return self.floor() def __ceil__(self): return self.ceiling() def __eq__(self, other): try: other = _sympify(other) except SympifyError: return NotImplemented if not isinstance(other, Number): # S(0) == S.false is False # S(0) == False is True return False if not self: return not other if other.is_NumberSymbol: if other.is_irrational: return False return other.__eq__(self) if other.is_Rational: # a Rational is always in reduced form so will never be 2/4 # so we can just check equivalence of args return self.p == other.p and self.q == other.q if other.is_Float: # all Floats have a denominator that is a power of 2 # so if self doesn't, it can't be equal to other if self.q & (self.q - 1): return False s, m, t = other._mpf_[:3] if s: m = -m if not t: # other is an odd integer if not self.is_Integer or self.is_even: return False return m == self.p from .power import integer_log if t > 0: # other is an even integer if not self.is_Integer: return False # does m*2**t == self.p return self.p and not self.p % m and \ integer_log(self.p//m, 2) == (t, True) # does non-integer s*m/2**-t = p/q? if self.is_Integer: return False return m == self.p and integer_log(self.q, 2) == (-t, True) return False def __ne__(self, other): return not self == other def _Rrel(self, other, attr): # if you want self < other, pass self, other, __gt__ try: other = _sympify(other) except SympifyError: return NotImplemented if other.is_Number: op = None s, o = self, other if other.is_NumberSymbol: op = getattr(o, attr) elif other.is_Float: op = getattr(o, attr) elif other.is_Rational: s, o = Integer(s.p*o.q), Integer(s.q*o.p) op = getattr(o, attr) if op: return op(s) if o.is_number and o.is_extended_real: return Integer(s.p), s.q*o def __gt__(self, other): rv = self._Rrel(other, '__lt__') if rv is None: rv = self, other elif not isinstance(rv, tuple): return rv return Expr.__gt__(*rv) def __ge__(self, other): rv = self._Rrel(other, '__le__') if rv is None: rv = self, other elif not isinstance(rv, tuple): return rv return Expr.__ge__(*rv) def __lt__(self, other): rv = self._Rrel(other, '__gt__') if rv is None: rv = self, other elif not isinstance(rv, tuple): return rv return Expr.__lt__(*rv) def __le__(self, other): rv = self._Rrel(other, '__ge__') if rv is None: rv = self, other elif not isinstance(rv, tuple): return rv return Expr.__le__(*rv) def __hash__(self): return super().__hash__() def factors(self, limit=None, use_trial=True, use_rho=False, use_pm1=False, verbose=False, visual=False): """A wrapper to factorint which return factors of self that are smaller than limit (or cheap to compute). Special methods of factoring are disabled by default so that only trial division is used. """ from sympy.ntheory.factor_ import factorrat return factorrat(self, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose).copy() @property def numerator(self): return self.p @property def denominator(self): return self.q @_sympifyit('other', NotImplemented) def gcd(self, other): if isinstance(other, Rational): if other == S.Zero: return other return Rational( igcd(self.p, other.p), ilcm(self.q, other.q)) return Number.gcd(self, other) @_sympifyit('other', NotImplemented) def lcm(self, other): if isinstance(other, Rational): return Rational( self.p // igcd(self.p, other.p) * other.p, igcd(self.q, other.q)) return Number.lcm(self, other) def as_numer_denom(self): return Integer(self.p), Integer(self.q) def as_content_primitive(self, radical=False, clear=True): """Return the tuple (R, self/R) where R is the positive Rational extracted from self. Examples ======== >>> from sympy import S >>> (S(-3)/2).as_content_primitive() (3/2, -1) See docstring of Expr.as_content_primitive for more examples. """ if self: if self.is_positive: return self, S.One return -self, S.NegativeOne return S.One, self def as_coeff_Mul(self, rational=False): """Efficiently extract the coefficient of a product.""" return self, S.One def as_coeff_Add(self, rational=False): """Efficiently extract the coefficient of a summation.""" return self, S.Zero class Integer(Rational): """Represents integer numbers of any size. Examples ======== >>> from sympy import Integer >>> Integer(3) 3 If a float or a rational is passed to Integer, the fractional part will be discarded; the effect is of rounding toward zero. >>> Integer(3.8) 3 >>> Integer(-3.8) -3 A string is acceptable input if it can be parsed as an integer: >>> Integer("9" * 20) 99999999999999999999 It is rarely needed to explicitly instantiate an Integer, because Python integers are automatically converted to Integer when they are used in SymPy expressions. """ q = 1 is_integer = True is_number = True is_Integer = True __slots__ = () def _as_mpf_val(self, prec): return mlib.from_int(self.p, prec, rnd) def _mpmath_(self, prec, rnd): return mpmath.make_mpf(self._as_mpf_val(prec)) @cacheit def __new__(cls, i): if isinstance(i, str): i = i.replace(' ', '') # whereas we cannot, in general, make a Rational from an # arbitrary expression, we can make an Integer unambiguously # (except when a non-integer expression happens to round to # an integer). So we proceed by taking int() of the input and # let the int routines determine whether the expression can # be made into an int or whether an error should be raised. try: ival = int(i) except TypeError: raise TypeError( "Argument of Integer should be of numeric type, got %s." % i) # We only work with well-behaved integer types. This converts, for # example, numpy.int32 instances. if ival == 1: return S.One if ival == -1: return S.NegativeOne if ival == 0: return S.Zero obj = Expr.__new__(cls) obj.p = ival return obj def __getnewargs__(self): return (self.p,) # Arithmetic operations are here for efficiency def __int__(self): return self.p def floor(self): return Integer(self.p) def ceiling(self): return Integer(self.p) def __floor__(self): return self.floor() def __ceil__(self): return self.ceiling() def __neg__(self): return Integer(-self.p) def __abs__(self): if self.p >= 0: return self else: return Integer(-self.p) def __divmod__(self, other): if isinstance(other, Integer) and global_parameters.evaluate: return Tuple(*(divmod(self.p, other.p))) else: return Number.__divmod__(self, other) def __rdivmod__(self, other): if isinstance(other, int) and global_parameters.evaluate: return Tuple(*(divmod(other, self.p))) else: try: other = Number(other) except TypeError: msg = "unsupported operand type(s) for divmod(): '%s' and '%s'" oname = type(other).__name__ sname = type(self).__name__ raise TypeError(msg % (oname, sname)) return Number.__divmod__(other, self) # TODO make it decorator + bytecodehacks? def __add__(self, other): if global_parameters.evaluate: if isinstance(other, int): return Integer(self.p + other) elif isinstance(other, Integer): return Integer(self.p + other.p) elif isinstance(other, Rational): return Rational(self.p*other.q + other.p, other.q, 1) return Rational.__add__(self, other) else: return Add(self, other) def __radd__(self, other): if global_parameters.evaluate: if isinstance(other, int): return Integer(other + self.p) elif isinstance(other, Rational): return Rational(other.p + self.p*other.q, other.q, 1) return Rational.__radd__(self, other) return Rational.__radd__(self, other) def __sub__(self, other): if global_parameters.evaluate: if isinstance(other, int): return Integer(self.p - other) elif isinstance(other, Integer): return Integer(self.p - other.p) elif isinstance(other, Rational): return Rational(self.p*other.q - other.p, other.q, 1) return Rational.__sub__(self, other) return Rational.__sub__(self, other) def __rsub__(self, other): if global_parameters.evaluate: if isinstance(other, int): return Integer(other - self.p) elif isinstance(other, Rational): return Rational(other.p - self.p*other.q, other.q, 1) return Rational.__rsub__(self, other) return Rational.__rsub__(self, other) def __mul__(self, other): if global_parameters.evaluate: if isinstance(other, int): return Integer(self.p*other) elif isinstance(other, Integer): return Integer(self.p*other.p) elif isinstance(other, Rational): return Rational(self.p*other.p, other.q, igcd(self.p, other.q)) return Rational.__mul__(self, other) return Rational.__mul__(self, other) def __rmul__(self, other): if global_parameters.evaluate: if isinstance(other, int): return Integer(other*self.p) elif isinstance(other, Rational): return Rational(other.p*self.p, other.q, igcd(self.p, other.q)) return Rational.__rmul__(self, other) return Rational.__rmul__(self, other) def __mod__(self, other): if global_parameters.evaluate: if isinstance(other, int): return Integer(self.p % other) elif isinstance(other, Integer): return Integer(self.p % other.p) return Rational.__mod__(self, other) return Rational.__mod__(self, other) def __rmod__(self, other): if global_parameters.evaluate: if isinstance(other, int): return Integer(other % self.p) elif isinstance(other, Integer): return Integer(other.p % self.p) return Rational.__rmod__(self, other) return Rational.__rmod__(self, other) def __eq__(self, other): if isinstance(other, int): return (self.p == other) elif isinstance(other, Integer): return (self.p == other.p) return Rational.__eq__(self, other) def __ne__(self, other): return not self == other def __gt__(self, other): try: other = _sympify(other) except SympifyError: return NotImplemented if other.is_Integer: return _sympify(self.p > other.p) return Rational.__gt__(self, other) def __lt__(self, other): try: other = _sympify(other) except SympifyError: return NotImplemented if other.is_Integer: return _sympify(self.p < other.p) return Rational.__lt__(self, other) def __ge__(self, other): try: other = _sympify(other) except SympifyError: return NotImplemented if other.is_Integer: return _sympify(self.p >= other.p) return Rational.__ge__(self, other) def __le__(self, other): try: other = _sympify(other) except SympifyError: return NotImplemented if other.is_Integer: return _sympify(self.p <= other.p) return Rational.__le__(self, other) def __hash__(self): return hash(self.p) def __index__(self): return self.p ######################################## def _eval_is_odd(self): return bool(self.p % 2) def _eval_power(self, expt): """ Tries to do some simplifications on self**expt Returns None if no further simplifications can be done. Explanation =========== When exponent is a fraction (so we have for example a square root), we try to find a simpler representation by factoring the argument up to factors of 2**15, e.g. - sqrt(4) becomes 2 - sqrt(-4) becomes 2*I - (2**(3+7)*3**(6+7))**Rational(1,7) becomes 6*18**(3/7) Further simplification would require a special call to factorint on the argument which is not done here for sake of speed. """ from sympy.ntheory.factor_ import perfect_power if expt is S.Infinity: if self.p > S.One: return S.Infinity # cases -1, 0, 1 are done in their respective classes return S.Infinity + S.ImaginaryUnit*S.Infinity if expt is S.NegativeInfinity: return Rational(1, self, 1)**S.Infinity if not isinstance(expt, Number): # simplify when expt is even # (-2)**k --> 2**k if self.is_negative and expt.is_even: return (-self)**expt if isinstance(expt, Float): # Rational knows how to exponentiate by a Float return super()._eval_power(expt) if not isinstance(expt, Rational): return if expt is S.Half and self.is_negative: # we extract I for this special case since everyone is doing so return S.ImaginaryUnit*Pow(-self, expt) if expt.is_negative: # invert base and change sign on exponent ne = -expt if self.is_negative: return S.NegativeOne**expt*Rational(1, -self, 1)**ne else: return Rational(1, self.p, 1)**ne # see if base is a perfect root, sqrt(4) --> 2 x, xexact = integer_nthroot(abs(self.p), expt.q) if xexact: # if it's a perfect root we've finished result = Integer(x**abs(expt.p)) if self.is_negative: result *= S.NegativeOne**expt return result # The following is an algorithm where we collect perfect roots # from the factors of base. # if it's not an nth root, it still might be a perfect power b_pos = int(abs(self.p)) p = perfect_power(b_pos) if p is not False: dict = {p[0]: p[1]} else: dict = Integer(b_pos).factors(limit=2**15) # now process the dict of factors out_int = 1 # integer part out_rad = 1 # extracted radicals sqr_int = 1 sqr_gcd = 0 sqr_dict = {} for prime, exponent in dict.items(): exponent *= expt.p # remove multiples of expt.q: (2**12)**(1/10) -> 2*(2**2)**(1/10) div_e, div_m = divmod(exponent, expt.q) if div_e > 0: out_int *= prime**div_e if div_m > 0: # see if the reduced exponent shares a gcd with e.q # (2**2)**(1/10) -> 2**(1/5) g = igcd(div_m, expt.q) if g != 1: out_rad *= Pow(prime, Rational(div_m//g, expt.q//g, 1)) else: sqr_dict[prime] = div_m # identify gcd of remaining powers for p, ex in sqr_dict.items(): if sqr_gcd == 0: sqr_gcd = ex else: sqr_gcd = igcd(sqr_gcd, ex) if sqr_gcd == 1: break for k, v in sqr_dict.items(): sqr_int *= k**(v//sqr_gcd) if sqr_int == b_pos and out_int == 1 and out_rad == 1: result = None else: result = out_int*out_rad*Pow(sqr_int, Rational(sqr_gcd, expt.q)) if self.is_negative: result *= Pow(S.NegativeOne, expt) return result def _eval_is_prime(self): from sympy.ntheory.primetest import isprime return isprime(self) def _eval_is_composite(self): if self > 1: return fuzzy_not(self.is_prime) else: return False def as_numer_denom(self): return self, S.One @_sympifyit('other', NotImplemented) def __floordiv__(self, other): if not isinstance(other, Expr): return NotImplemented if isinstance(other, Integer): return Integer(self.p // other) return divmod(self, other)[0] def __rfloordiv__(self, other): return Integer(Integer(other).p // self.p) # These bitwise operations (__lshift__, __rlshift__, ..., __invert__) are defined # for Integer only and not for general SymPy expressions. This is to achieve # compatibility with the numbers.Integral ABC which only defines these operations # among instances of numbers.Integral. Therefore, these methods check explicitly for # integer types rather than using sympify because they should not accept arbitrary # symbolic expressions and there is no symbolic analogue of numbers.Integral's # bitwise operations. def __lshift__(self, other): if isinstance(other, (int, Integer, numbers.Integral)): return Integer(self.p << int(other)) else: return NotImplemented def __rlshift__(self, other): if isinstance(other, (int, numbers.Integral)): return Integer(int(other) << self.p) else: return NotImplemented def __rshift__(self, other): if isinstance(other, (int, Integer, numbers.Integral)): return Integer(self.p >> int(other)) else: return NotImplemented def __rrshift__(self, other): if isinstance(other, (int, numbers.Integral)): return Integer(int(other) >> self.p) else: return NotImplemented def __and__(self, other): if isinstance(other, (int, Integer, numbers.Integral)): return Integer(self.p & int(other)) else: return NotImplemented def __rand__(self, other): if isinstance(other, (int, numbers.Integral)): return Integer(int(other) & self.p) else: return NotImplemented def __xor__(self, other): if isinstance(other, (int, Integer, numbers.Integral)): return Integer(self.p ^ int(other)) else: return NotImplemented def __rxor__(self, other): if isinstance(other, (int, numbers.Integral)): return Integer(int(other) ^ self.p) else: return NotImplemented def __or__(self, other): if isinstance(other, (int, Integer, numbers.Integral)): return Integer(self.p | int(other)) else: return NotImplemented def __ror__(self, other): if isinstance(other, (int, numbers.Integral)): return Integer(int(other) | self.p) else: return NotImplemented def __invert__(self): return Integer(~self.p) # Add sympify converters _sympy_converter[int] = Integer class AlgebraicNumber(Expr): r""" Class for representing algebraic numbers in SymPy. Symbolically, an instance of this class represents an element $\alpha \in \mathbb{Q}(\theta) \hookrightarrow \mathbb{C}$. That is, the algebraic number $\alpha$ is represented as an element of a particular number field $\mathbb{Q}(\theta)$, with a particular embedding of this field into the complex numbers. Formally, the primitive element $\theta$ is given by two data points: (1) its minimal polynomial (which defines $\mathbb{Q}(\theta)$), and (2) a particular complex number that is a root of this polynomial (which defines the embedding $\mathbb{Q}(\theta) \hookrightarrow \mathbb{C}$). Finally, the algebraic number $\alpha$ which we represent is then given by the coefficients of a polynomial in $\theta$. """ __slots__ = ('rep', 'root', 'alias', 'minpoly', '_own_minpoly') is_AlgebraicNumber = True is_algebraic = True is_number = True kind = NumberKind # Optional alias symbol is not free. # Actually, alias should be a Str, but some methods # expect that it be an instance of Expr. free_symbols: set[Basic] = set() def __new__(cls, expr, coeffs=None, alias=None, **args): r""" Construct a new algebraic number $\alpha$ belonging to a number field $k = \mathbb{Q}(\theta)$. There are four instance attributes to be determined: =========== ============================================================================ Attribute Type/Meaning =========== ============================================================================ ``root`` :py:class:`~.Expr` for $\theta$ as a complex number ``minpoly`` :py:class:`~.Poly`, the minimal polynomial of $\theta$ ``rep`` :py:class:`~sympy.polys.polyclasses.DMP` giving $\alpha$ as poly in $\theta$ ``alias`` :py:class:`~.Symbol` for $\theta$, or ``None`` =========== ============================================================================ See Parameters section for how they are determined. Parameters ========== expr : :py:class:`~.Expr`, or pair $(m, r)$ There are three distinct modes of construction, depending on what is passed as *expr*. **(1)** *expr* is an :py:class:`~.AlgebraicNumber`: In this case we begin by copying all four instance attributes from *expr*. If *coeffs* were also given, we compose the two coeff polynomials (see below). If an *alias* was given, it overrides. **(2)** *expr* is any other type of :py:class:`~.Expr`: Then ``root`` will equal *expr*. Therefore it must express an algebraic quantity, and we will compute its ``minpoly``. **(3)** *expr* is an ordered pair $(m, r)$ giving the ``minpoly`` $m$, and a ``root`` $r$ thereof, which together define $\theta$. In this case $m$ may be either a univariate :py:class:`~.Poly` or any :py:class:`~.Expr` which represents the same, while $r$ must be some :py:class:`~.Expr` representing a complex number that is a root of $m$, including both explicit expressions in radicals, and instances of :py:class:`~.ComplexRootOf` or :py:class:`~.AlgebraicNumber`. coeffs : list, :py:class:`~.ANP`, None, optional (default=None) This defines ``rep``, giving the algebraic number $\alpha$ as a polynomial in $\theta$. If a list, the elements should be integers or rational numbers. If an :py:class:`~.ANP`, we take its coefficients (using its :py:meth:`~.ANP.to_list()` method). If ``None``, then the list of coefficients defaults to ``[1, 0]``, meaning that $\alpha = \theta$ is the primitive element of the field. If *expr* was an :py:class:`~.AlgebraicNumber`, let $g(x)$ be its ``rep`` polynomial, and let $f(x)$ be the polynomial defined by *coeffs*. Then ``self.rep`` will represent the composition $(f \circ g)(x)$. alias : str, :py:class:`~.Symbol`, None, optional (default=None) This is a way to provide a name for the primitive element. We described several ways in which the *expr* argument can define the value of the primitive element, but none of these methods gave it a name. Here, for example, *alias* could be set as ``Symbol('theta')``, in order to make this symbol appear when $\alpha$ is printed, or rendered as a polynomial, using the :py:meth:`~.as_poly()` method. Examples ======== Recall that we are constructing an algebraic number as a field element $\alpha \in \mathbb{Q}(\theta)$. >>> from sympy import AlgebraicNumber, sqrt, CRootOf, S >>> from sympy.abc import x Example (1): $\alpha = \theta = \sqrt{2}$ >>> a1 = AlgebraicNumber(sqrt(2)) >>> a1.minpoly_of_element().as_expr(x) x**2 - 2 >>> a1.evalf(10) 1.414213562 Example (2): $\alpha = 3 \sqrt{2} - 5$, $\theta = \sqrt{2}$. We can either build on the last example: >>> a2 = AlgebraicNumber(a1, [3, -5]) >>> a2.as_expr() -5 + 3*sqrt(2) or start from scratch: >>> a2 = AlgebraicNumber(sqrt(2), [3, -5]) >>> a2.as_expr() -5 + 3*sqrt(2) Example (3): $\alpha = 6 \sqrt{2} - 11$, $\theta = \sqrt{2}$. Again we can build on the previous example, and we see that the coeff polys are composed: >>> a3 = AlgebraicNumber(a2, [2, -1]) >>> a3.as_expr() -11 + 6*sqrt(2) reflecting the fact that $(2x - 1) \circ (3x - 5) = 6x - 11$. Example (4): $\alpha = \sqrt{2}$, $\theta = \sqrt{2} + \sqrt{3}$. The easiest way is to use the :py:func:`~.to_number_field()` function: >>> from sympy import to_number_field >>> a4 = to_number_field(sqrt(2), sqrt(2) + sqrt(3)) >>> a4.minpoly_of_element().as_expr(x) x**2 - 2 >>> a4.to_root() sqrt(2) >>> a4.primitive_element() sqrt(2) + sqrt(3) >>> a4.coeffs() [1/2, 0, -9/2, 0] but if you already knew the right coefficients, you could construct it directly: >>> a4 = AlgebraicNumber(sqrt(2) + sqrt(3), [S(1)/2, 0, S(-9)/2, 0]) >>> a4.to_root() sqrt(2) >>> a4.primitive_element() sqrt(2) + sqrt(3) Example (5): Construct the Golden Ratio as an element of the 5th cyclotomic field, supposing we already know its coefficients. This time we introduce the alias $\zeta$ for the primitive element of the field: >>> from sympy import cyclotomic_poly >>> from sympy.abc import zeta >>> a5 = AlgebraicNumber(CRootOf(cyclotomic_poly(5), -1), ... [-1, -1, 0, 0], alias=zeta) >>> a5.as_poly().as_expr() -zeta**3 - zeta**2 >>> a5.evalf() 1.61803398874989 (The index ``-1`` to ``CRootOf`` selects the complex root with the largest real and imaginary parts, which in this case is $\mathrm{e}^{2i\pi/5}$. See :py:class:`~.ComplexRootOf`.) Example (6): Building on the last example, construct the number $2 \phi \in \mathbb{Q}(\phi)$, where $\phi$ is the Golden Ratio: >>> from sympy.abc import phi >>> a6 = AlgebraicNumber(a5.to_root(), coeffs=[2, 0], alias=phi) >>> a6.as_poly().as_expr() 2*phi >>> a6.primitive_element().evalf() 1.61803398874989 Note that we needed to use ``a5.to_root()``, since passing ``a5`` as the first argument would have constructed the number $2 \phi$ as an element of the field $\mathbb{Q}(\zeta)$: >>> a6_wrong = AlgebraicNumber(a5, coeffs=[2, 0]) >>> a6_wrong.as_poly().as_expr() -2*zeta**3 - 2*zeta**2 >>> a6_wrong.primitive_element().evalf() 0.309016994374947 + 0.951056516295154*I """ from sympy.polys.polyclasses import ANP, DMP from sympy.polys.numberfields import minimal_polynomial expr = sympify(expr) rep0 = None alias0 = None if isinstance(expr, (tuple, Tuple)): minpoly, root = expr if not minpoly.is_Poly: from sympy.polys.polytools import Poly minpoly = Poly(minpoly) elif expr.is_AlgebraicNumber: minpoly, root, rep0, alias0 = (expr.minpoly, expr.root, expr.rep, expr.alias) else: minpoly, root = minimal_polynomial( expr, args.get('gen'), polys=True), expr dom = minpoly.get_domain() if coeffs is not None: if not isinstance(coeffs, ANP): rep = DMP.from_sympy_list(sympify(coeffs), 0, dom) scoeffs = Tuple(*coeffs) else: rep = DMP.from_list(coeffs.to_list(), 0, dom) scoeffs = Tuple(*coeffs.to_list()) else: rep = DMP.from_list([1, 0], 0, dom) scoeffs = Tuple(1, 0) if rep0 is not None: from sympy.polys.densetools import dup_compose c = dup_compose(rep.rep, rep0.rep, dom) rep = DMP.from_list(c, 0, dom) scoeffs = Tuple(*c) if rep.degree() >= minpoly.degree(): rep = rep.rem(minpoly.rep) sargs = (root, scoeffs) alias = alias or alias0 if alias is not None: from .symbol import Symbol if not isinstance(alias, Symbol): alias = Symbol(alias) sargs = sargs + (alias,) obj = Expr.__new__(cls, *sargs) obj.rep = rep obj.root = root obj.alias = alias obj.minpoly = minpoly obj._own_minpoly = None return obj def __hash__(self): return super().__hash__() def _eval_evalf(self, prec): return self.as_expr()._evalf(prec) @property def is_aliased(self): """Returns ``True`` if ``alias`` was set. """ return self.alias is not None def as_poly(self, x=None): """Create a Poly instance from ``self``. """ from sympy.polys.polytools import Poly, PurePoly if x is not None: return Poly.new(self.rep, x) else: if self.alias is not None: return Poly.new(self.rep, self.alias) else: from .symbol import Dummy return PurePoly.new(self.rep, Dummy('x')) def as_expr(self, x=None): """Create a Basic expression from ``self``. """ return self.as_poly(x or self.root).as_expr().expand() def coeffs(self): """Returns all SymPy coefficients of an algebraic number. """ return [ self.rep.dom.to_sympy(c) for c in self.rep.all_coeffs() ] def native_coeffs(self): """Returns all native coefficients of an algebraic number. """ return self.rep.all_coeffs() def to_algebraic_integer(self): """Convert ``self`` to an algebraic integer. """ from sympy.polys.polytools import Poly f = self.minpoly if f.LC() == 1: return self coeff = f.LC()**(f.degree() - 1) poly = f.compose(Poly(f.gen/f.LC())) minpoly = poly*coeff root = f.LC()*self.root return AlgebraicNumber((minpoly, root), self.coeffs()) def _eval_simplify(self, **kwargs): from sympy.polys.rootoftools import CRootOf from sympy.polys import minpoly measure, ratio = kwargs['measure'], kwargs['ratio'] for r in [r for r in self.minpoly.all_roots() if r.func != CRootOf]: if minpoly(self.root - r).is_Symbol: # use the matching root if it's simpler if measure(r) < ratio*measure(self.root): return AlgebraicNumber(r) return self def field_element(self, coeffs): r""" Form another element of the same number field. Explanation =========== If we represent $\alpha \in \mathbb{Q}(\theta)$, form another element $\beta \in \mathbb{Q}(\theta)$ of the same number field. Parameters ========== coeffs : list, :py:class:`~.ANP` Like the *coeffs* arg to the class :py:meth:`constructor<.AlgebraicNumber.__new__>`, defines the new element as a polynomial in the primitive element. If a list, the elements should be integers or rational numbers. If an :py:class:`~.ANP`, we take its coefficients (using its :py:meth:`~.ANP.to_list()` method). Examples ======== >>> from sympy import AlgebraicNumber, sqrt >>> a = AlgebraicNumber(sqrt(5), [-1, 1]) >>> b = a.field_element([3, 2]) >>> print(a) 1 - sqrt(5) >>> print(b) 2 + 3*sqrt(5) >>> print(b.primitive_element() == a.primitive_element()) True See Also ======== AlgebraicNumber """ return AlgebraicNumber( (self.minpoly, self.root), coeffs=coeffs, alias=self.alias) @property def is_primitive_element(self): r""" Say whether this algebraic number $\alpha \in \mathbb{Q}(\theta)$ is equal to the primitive element $\theta$ for its field. """ c = self.coeffs() # Second case occurs if self.minpoly is linear: return c == [1, 0] or c == [self.root] def primitive_element(self): r""" Get the primitive element $\theta$ for the number field $\mathbb{Q}(\theta)$ to which this algebraic number $\alpha$ belongs. Returns ======= AlgebraicNumber """ if self.is_primitive_element: return self return self.field_element([1, 0]) def to_primitive_element(self, radicals=True): r""" Convert ``self`` to an :py:class:`~.AlgebraicNumber` instance that is equal to its own primitive element. Explanation =========== If we represent $\alpha \in \mathbb{Q}(\theta)$, $\alpha \neq \theta$, construct a new :py:class:`~.AlgebraicNumber` that represents $\alpha \in \mathbb{Q}(\alpha)$. Examples ======== >>> from sympy import sqrt, to_number_field >>> from sympy.abc import x >>> a = to_number_field(sqrt(2), sqrt(2) + sqrt(3)) The :py:class:`~.AlgebraicNumber` ``a`` represents the number $\sqrt{2}$ in the field $\mathbb{Q}(\sqrt{2} + \sqrt{3})$. Rendering ``a`` as a polynomial, >>> a.as_poly().as_expr(x) x**3/2 - 9*x/2 reflects the fact that $\sqrt{2} = \theta^3/2 - 9 \theta/2$, where $\theta = \sqrt{2} + \sqrt{3}$. ``a`` is not equal to its own primitive element. Its minpoly >>> a.minpoly.as_poly().as_expr(x) x**4 - 10*x**2 + 1 is that of $\theta$. Converting to a primitive element, >>> a_prim = a.to_primitive_element() >>> a_prim.minpoly.as_poly().as_expr(x) x**2 - 2 we obtain an :py:class:`~.AlgebraicNumber` whose ``minpoly`` is that of the number itself. Parameters ========== radicals : boolean, optional (default=True) If ``True``, then we will try to return an :py:class:`~.AlgebraicNumber` whose ``root`` is an expression in radicals. If that is not possible (or if *radicals* is ``False``), ``root`` will be a :py:class:`~.ComplexRootOf`. Returns ======= AlgebraicNumber See Also ======== is_primitive_element """ if self.is_primitive_element: return self m = self.minpoly_of_element() r = self.to_root(radicals=radicals) return AlgebraicNumber((m, r)) def minpoly_of_element(self): r""" Compute the minimal polynomial for this algebraic number. Explanation =========== Recall that we represent an element $\alpha \in \mathbb{Q}(\theta)$. Our instance attribute ``self.minpoly`` is the minimal polynomial for our primitive element $\theta$. This method computes the minimal polynomial for $\alpha$. """ if self._own_minpoly is None: if self.is_primitive_element: self._own_minpoly = self.minpoly else: from sympy.polys.numberfields.minpoly import minpoly theta = self.primitive_element() self._own_minpoly = minpoly(self.as_expr(theta), polys=True) return self._own_minpoly def to_root(self, radicals=True, minpoly=None): """ Convert to an :py:class:`~.Expr` that is not an :py:class:`~.AlgebraicNumber`, specifically, either a :py:class:`~.ComplexRootOf`, or, optionally and where possible, an expression in radicals. Parameters ========== radicals : boolean, optional (default=True) If ``True``, then we will try to return the root as an expression in radicals. If that is not possible, we will return a :py:class:`~.ComplexRootOf`. minpoly : :py:class:`~.Poly` If the minimal polynomial for `self` has been pre-computed, it can be passed in order to save time. """ if self.is_primitive_element and not isinstance(self.root, AlgebraicNumber): return self.root m = minpoly or self.minpoly_of_element() roots = m.all_roots(radicals=radicals) if len(roots) == 1: return roots[0] ex = self.as_expr() for b in roots: if m.same_root(b, ex): return b class RationalConstant(Rational): """ Abstract base class for rationals with specific behaviors Derived classes must define class attributes p and q and should probably all be singletons. """ __slots__ = () def __new__(cls): return AtomicExpr.__new__(cls) class IntegerConstant(Integer): __slots__ = () def __new__(cls): return AtomicExpr.__new__(cls) class Zero(IntegerConstant, metaclass=Singleton): """The number zero. Zero is a singleton, and can be accessed by ``S.Zero`` Examples ======== >>> from sympy import S, Integer >>> Integer(0) is S.Zero True >>> 1/S.Zero zoo References ========== .. [1] https://en.wikipedia.org/wiki/Zero """ p = 0 q = 1 is_positive = False is_negative = False is_zero = True is_number = True is_comparable = True __slots__ = () def __getnewargs__(self): return () @staticmethod def __abs__(): return S.Zero @staticmethod def __neg__(): return S.Zero def _eval_power(self, expt): if expt.is_extended_positive: return self if expt.is_extended_negative: return S.ComplexInfinity if expt.is_extended_real is False: return S.NaN if expt.is_zero: return S.One # infinities are already handled with pos and neg # tests above; now throw away leading numbers on Mul # exponent since 0**-x = zoo**x even when x == 0 coeff, terms = expt.as_coeff_Mul() if coeff.is_negative: return S.ComplexInfinity**terms if coeff is not S.One: # there is a Number to discard return self**terms def _eval_order(self, *symbols): # Order(0,x) -> 0 return self def __bool__(self): return False class One(IntegerConstant, metaclass=Singleton): """The number one. One is a singleton, and can be accessed by ``S.One``. Examples ======== >>> from sympy import S, Integer >>> Integer(1) is S.One True References ========== .. [1] https://en.wikipedia.org/wiki/1_%28number%29 """ is_number = True is_positive = True p = 1 q = 1 __slots__ = () def __getnewargs__(self): return () @staticmethod def __abs__(): return S.One @staticmethod def __neg__(): return S.NegativeOne def _eval_power(self, expt): return self def _eval_order(self, *symbols): return @staticmethod def factors(limit=None, use_trial=True, use_rho=False, use_pm1=False, verbose=False, visual=False): if visual: return S.One else: return {} class NegativeOne(IntegerConstant, metaclass=Singleton): """The number negative one. NegativeOne is a singleton, and can be accessed by ``S.NegativeOne``. Examples ======== >>> from sympy import S, Integer >>> Integer(-1) is S.NegativeOne True See Also ======== One References ========== .. [1] https://en.wikipedia.org/wiki/%E2%88%921_%28number%29 """ is_number = True p = -1 q = 1 __slots__ = () def __getnewargs__(self): return () @staticmethod def __abs__(): return S.One @staticmethod def __neg__(): return S.One def _eval_power(self, expt): if expt.is_odd: return S.NegativeOne if expt.is_even: return S.One if isinstance(expt, Number): if isinstance(expt, Float): return Float(-1.0)**expt if expt is S.NaN: return S.NaN if expt in (S.Infinity, S.NegativeInfinity): return S.NaN if expt is S.Half: return S.ImaginaryUnit if isinstance(expt, Rational): if expt.q == 2: return S.ImaginaryUnit**Integer(expt.p) i, r = divmod(expt.p, expt.q) if i: return self**i*self**Rational(r, expt.q) return class Half(RationalConstant, metaclass=Singleton): """The rational number 1/2. Half is a singleton, and can be accessed by ``S.Half``. Examples ======== >>> from sympy import S, Rational >>> Rational(1, 2) is S.Half True References ========== .. [1] https://en.wikipedia.org/wiki/One_half """ is_number = True p = 1 q = 2 __slots__ = () def __getnewargs__(self): return () @staticmethod def __abs__(): return S.Half class Infinity(Number, metaclass=Singleton): r"""Positive infinite quantity. Explanation =========== In real analysis the symbol `\infty` denotes an unbounded limit: `x\to\infty` means that `x` grows without bound. Infinity is often used not only to define a limit but as a value in the affinely extended real number system. Points labeled `+\infty` and `-\infty` can be added to the topological space of the real numbers, producing the two-point compactification of the real numbers. Adding algebraic properties to this gives us the extended real numbers. Infinity is a singleton, and can be accessed by ``S.Infinity``, or can be imported as ``oo``. Examples ======== >>> from sympy import oo, exp, limit, Symbol >>> 1 + oo oo >>> 42/oo 0 >>> x = Symbol('x') >>> limit(exp(x), x, oo) oo See Also ======== NegativeInfinity, NaN References ========== .. [1] https://en.wikipedia.org/wiki/Infinity """ is_commutative = True is_number = True is_complex = False is_extended_real = True is_infinite = True is_comparable = True is_extended_positive = True is_prime = False __slots__ = () def __new__(cls): return AtomicExpr.__new__(cls) def _latex(self, printer): return r"\infty" def _eval_subs(self, old, new): if self == old: return new def _eval_evalf(self, prec=None): return Float('inf') def evalf(self, prec=None, **options): return self._eval_evalf(prec) @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other in (S.NegativeInfinity, S.NaN): return S.NaN return self return Number.__add__(self, other) __radd__ = __add__ @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other in (S.Infinity, S.NaN): return S.NaN return self return Number.__sub__(self, other) @_sympifyit('other', NotImplemented) def __rsub__(self, other): return (-self).__add__(other) @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other.is_zero or other is S.NaN: return S.NaN if other.is_extended_positive: return self return S.NegativeInfinity return Number.__mul__(self, other) __rmul__ = __mul__ @_sympifyit('other', NotImplemented) def __truediv__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other is S.Infinity or \ other is S.NegativeInfinity or \ other is S.NaN: return S.NaN if other.is_extended_nonnegative: return self return S.NegativeInfinity return Number.__truediv__(self, other) def __abs__(self): return S.Infinity def __neg__(self): return S.NegativeInfinity def _eval_power(self, expt): """ ``expt`` is symbolic object but not equal to 0 or 1. ================ ======= ============================== Expression Result Notes ================ ======= ============================== ``oo ** nan`` ``nan`` ``oo ** -p`` ``0`` ``p`` is number, ``oo`` ================ ======= ============================== See Also ======== Pow NaN NegativeInfinity """ if expt.is_extended_positive: return S.Infinity if expt.is_extended_negative: return S.Zero if expt is S.NaN: return S.NaN if expt is S.ComplexInfinity: return S.NaN if expt.is_extended_real is False and expt.is_number: from sympy.functions.elementary.complexes import re expt_real = re(expt) if expt_real.is_positive: return S.ComplexInfinity if expt_real.is_negative: return S.Zero if expt_real.is_zero: return S.NaN return self**expt.evalf() def _as_mpf_val(self, prec): return mlib.finf def __hash__(self): return super().__hash__() def __eq__(self, other): return other is S.Infinity or other == float('inf') def __ne__(self, other): return other is not S.Infinity and other != float('inf') __gt__ = Expr.__gt__ __ge__ = Expr.__ge__ __lt__ = Expr.__lt__ __le__ = Expr.__le__ @_sympifyit('other', NotImplemented) def __mod__(self, other): if not isinstance(other, Expr): return NotImplemented return S.NaN __rmod__ = __mod__ def floor(self): return self def ceiling(self): return self oo = S.Infinity class NegativeInfinity(Number, metaclass=Singleton): """Negative infinite quantity. NegativeInfinity is a singleton, and can be accessed by ``S.NegativeInfinity``. See Also ======== Infinity """ is_extended_real = True is_complex = False is_commutative = True is_infinite = True is_comparable = True is_extended_negative = True is_number = True is_prime = False __slots__ = () def __new__(cls): return AtomicExpr.__new__(cls) def _latex(self, printer): return r"-\infty" def _eval_subs(self, old, new): if self == old: return new def _eval_evalf(self, prec=None): return Float('-inf') def evalf(self, prec=None, **options): return self._eval_evalf(prec) @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other in (S.Infinity, S.NaN): return S.NaN return self return Number.__add__(self, other) __radd__ = __add__ @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other in (S.NegativeInfinity, S.NaN): return S.NaN return self return Number.__sub__(self, other) @_sympifyit('other', NotImplemented) def __rsub__(self, other): return (-self).__add__(other) @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other.is_zero or other is S.NaN: return S.NaN if other.is_extended_positive: return self return S.Infinity return Number.__mul__(self, other) __rmul__ = __mul__ @_sympifyit('other', NotImplemented) def __truediv__(self, other): if isinstance(other, Number) and global_parameters.evaluate: if other is S.Infinity or \ other is S.NegativeInfinity or \ other is S.NaN: return S.NaN if other.is_extended_nonnegative: return self return S.Infinity return Number.__truediv__(self, other) def __abs__(self): return S.Infinity def __neg__(self): return S.Infinity def _eval_power(self, expt): """ ``expt`` is symbolic object but not equal to 0 or 1. ================ ======= ============================== Expression Result Notes ================ ======= ============================== ``(-oo) ** nan`` ``nan`` ``(-oo) ** oo`` ``nan`` ``(-oo) ** -oo`` ``nan`` ``(-oo) ** e`` ``oo`` ``e`` is positive even integer ``(-oo) ** o`` ``-oo`` ``o`` is positive odd integer ================ ======= ============================== See Also ======== Infinity Pow NaN """ if expt.is_number: if expt is S.NaN or \ expt is S.Infinity or \ expt is S.NegativeInfinity: return S.NaN if isinstance(expt, Integer) and expt.is_extended_positive: if expt.is_odd: return S.NegativeInfinity else: return S.Infinity inf_part = S.Infinity**expt s_part = S.NegativeOne**expt if inf_part == 0 and s_part.is_finite: return inf_part if (inf_part is S.ComplexInfinity and s_part.is_finite and not s_part.is_zero): return S.ComplexInfinity return s_part*inf_part def _as_mpf_val(self, prec): return mlib.fninf def __hash__(self): return super().__hash__() def __eq__(self, other): return other is S.NegativeInfinity or other == float('-inf') def __ne__(self, other): return other is not S.NegativeInfinity and other != float('-inf') __gt__ = Expr.__gt__ __ge__ = Expr.__ge__ __lt__ = Expr.__lt__ __le__ = Expr.__le__ @_sympifyit('other', NotImplemented) def __mod__(self, other): if not isinstance(other, Expr): return NotImplemented return S.NaN __rmod__ = __mod__ def floor(self): return self def ceiling(self): return self def as_powers_dict(self): return {S.NegativeOne: 1, S.Infinity: 1} class NaN(Number, metaclass=Singleton): """ Not a Number. Explanation =========== This serves as a place holder for numeric values that are indeterminate. Most operations on NaN, produce another NaN. Most indeterminate forms, such as ``0/0`` or ``oo - oo` produce NaN. Two exceptions are ``0**0`` and ``oo**0``, which all produce ``1`` (this is consistent with Python's float). NaN is loosely related to floating point nan, which is defined in the IEEE 754 floating point standard, and corresponds to the Python ``float('nan')``. Differences are noted below. NaN is mathematically not equal to anything else, even NaN itself. This explains the initially counter-intuitive results with ``Eq`` and ``==`` in the examples below. NaN is not comparable so inequalities raise a TypeError. This is in contrast with floating point nan where all inequalities are false. NaN is a singleton, and can be accessed by ``S.NaN``, or can be imported as ``nan``. Examples ======== >>> from sympy import nan, S, oo, Eq >>> nan is S.NaN True >>> oo - oo nan >>> nan + 1 nan >>> Eq(nan, nan) # mathematical equality False >>> nan == nan # structural equality True References ========== .. [1] https://en.wikipedia.org/wiki/NaN """ is_commutative = True is_extended_real = None is_real = None is_rational = None is_algebraic = None is_transcendental = None is_integer = None is_comparable = False is_finite = None is_zero = None is_prime = None is_positive = None is_negative = None is_number = True __slots__ = () def __new__(cls): return AtomicExpr.__new__(cls) def _latex(self, printer): return r"\text{NaN}" def __neg__(self): return self @_sympifyit('other', NotImplemented) def __add__(self, other): return self @_sympifyit('other', NotImplemented) def __sub__(self, other): return self @_sympifyit('other', NotImplemented) def __mul__(self, other): return self @_sympifyit('other', NotImplemented) def __truediv__(self, other): return self def floor(self): return self def ceiling(self): return self def _as_mpf_val(self, prec): return _mpf_nan def __hash__(self): return super().__hash__() def __eq__(self, other): # NaN is structurally equal to another NaN return other is S.NaN def __ne__(self, other): return other is not S.NaN # Expr will _sympify and raise TypeError __gt__ = Expr.__gt__ __ge__ = Expr.__ge__ __lt__ = Expr.__lt__ __le__ = Expr.__le__ nan = S.NaN @dispatch(NaN, Expr) # type:ignore def _eval_is_eq(a, b): # noqa:F811 return False class ComplexInfinity(AtomicExpr, metaclass=Singleton): r"""Complex infinity. Explanation =========== In complex analysis the symbol `\tilde\infty`, called "complex infinity", represents a quantity with infinite magnitude, but undetermined complex phase. ComplexInfinity is a singleton, and can be accessed by ``S.ComplexInfinity``, or can be imported as ``zoo``. Examples ======== >>> from sympy import zoo >>> zoo + 42 zoo >>> 42/zoo 0 >>> zoo + zoo nan >>> zoo*zoo zoo See Also ======== Infinity """ is_commutative = True is_infinite = True is_number = True is_prime = False is_complex = False is_extended_real = False kind = NumberKind __slots__ = () def __new__(cls): return AtomicExpr.__new__(cls) def _latex(self, printer): return r"\tilde{\infty}" @staticmethod def __abs__(): return S.Infinity def floor(self): return self def ceiling(self): return self @staticmethod def __neg__(): return S.ComplexInfinity def _eval_power(self, expt): if expt is S.ComplexInfinity: return S.NaN if isinstance(expt, Number): if expt.is_zero: return S.NaN else: if expt.is_positive: return S.ComplexInfinity else: return S.Zero zoo = S.ComplexInfinity class NumberSymbol(AtomicExpr): is_commutative = True is_finite = True is_number = True __slots__ = () is_NumberSymbol = True kind = NumberKind def __new__(cls): return AtomicExpr.__new__(cls) def approximation(self, number_cls): """ Return an interval with number_cls endpoints that contains the value of NumberSymbol. If not implemented, then return None. """ def _eval_evalf(self, prec): return Float._new(self._as_mpf_val(prec), prec) def __eq__(self, other): try: other = _sympify(other) except SympifyError: return NotImplemented if self is other: return True if other.is_Number and self.is_irrational: return False return False # NumberSymbol != non-(Number|self) def __ne__(self, other): return not self == other def __le__(self, other): if self is other: return S.true return Expr.__le__(self, other) def __ge__(self, other): if self is other: return S.true return Expr.__ge__(self, other) def __int__(self): # subclass with appropriate return value raise NotImplementedError def __hash__(self): return super().__hash__() class Exp1(NumberSymbol, metaclass=Singleton): r"""The `e` constant. Explanation =========== The transcendental number `e = 2.718281828\ldots` is the base of the natural logarithm and of the exponential function, `e = \exp(1)`. Sometimes called Euler's number or Napier's constant. Exp1 is a singleton, and can be accessed by ``S.Exp1``, or can be imported as ``E``. Examples ======== >>> from sympy import exp, log, E >>> E is exp(1) True >>> log(E) 1 References ========== .. [1] https://en.wikipedia.org/wiki/E_%28mathematical_constant%29 """ is_real = True is_positive = True is_negative = False # XXX Forces is_negative/is_nonnegative is_irrational = True is_number = True is_algebraic = False is_transcendental = True __slots__ = () def _latex(self, printer): return r"e" @staticmethod def __abs__(): return S.Exp1 def __int__(self): return 2 def _as_mpf_val(self, prec): return mpf_e(prec) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (Integer(2), Integer(3)) elif issubclass(number_cls, Rational): pass def _eval_power(self, expt): if global_parameters.exp_is_pow: return self._eval_power_exp_is_pow(expt) else: from sympy.functions.elementary.exponential import exp return exp(expt) def _eval_power_exp_is_pow(self, arg): if arg.is_Number: if arg is oo: return oo elif arg == -oo: return S.Zero from sympy.functions.elementary.exponential import log if isinstance(arg, log): return arg.args[0] # don't autoexpand Pow or Mul (see the issue 3351): elif not arg.is_Add: Ioo = I*oo if arg in [Ioo, -Ioo]: return nan coeff = arg.coeff(pi*I) if coeff: if (2*coeff).is_integer: if coeff.is_even: return S.One elif coeff.is_odd: return S.NegativeOne elif (coeff + S.Half).is_even: return -I elif (coeff + S.Half).is_odd: return I elif coeff.is_Rational: ncoeff = coeff % 2 # restrict to [0, 2pi) if ncoeff > 1: # restrict to (-pi, pi] ncoeff -= 2 if ncoeff != coeff: return S.Exp1**(ncoeff*S.Pi*S.ImaginaryUnit) # Warning: code in risch.py will be very sensitive to changes # in this (see DifferentialExtension). # look for a single log factor coeff, terms = arg.as_coeff_Mul() # but it can't be multiplied by oo if coeff in (oo, -oo): return coeffs, log_term = [coeff], None for term in Mul.make_args(terms): if isinstance(term, log): if log_term is None: log_term = term.args[0] else: return elif term.is_comparable: coeffs.append(term) else: return return log_term**Mul(*coeffs) if log_term else None elif arg.is_Add: out = [] add = [] argchanged = False for a in arg.args: if a is S.One: add.append(a) continue newa = self**a if isinstance(newa, Pow) and newa.base is self: if newa.exp != a: add.append(newa.exp) argchanged = True else: add.append(a) else: out.append(newa) if out or argchanged: return Mul(*out)*Pow(self, Add(*add), evaluate=False) elif arg.is_Matrix: return arg.exp() def _eval_rewrite_as_sin(self, **kwargs): from sympy.functions.elementary.trigonometric import sin return sin(I + S.Pi/2) - I*sin(I) def _eval_rewrite_as_cos(self, **kwargs): from sympy.functions.elementary.trigonometric import cos return cos(I) + I*cos(I + S.Pi/2) E = S.Exp1 class Pi(NumberSymbol, metaclass=Singleton): r"""The `\pi` constant. Explanation =========== The transcendental number `\pi = 3.141592654\ldots` represents the ratio of a circle's circumference to its diameter, the area of the unit circle, the half-period of trigonometric functions, and many other things in mathematics. Pi is a singleton, and can be accessed by ``S.Pi``, or can be imported as ``pi``. Examples ======== >>> from sympy import S, pi, oo, sin, exp, integrate, Symbol >>> S.Pi pi >>> pi > 3 True >>> pi.is_irrational True >>> x = Symbol('x') >>> sin(x + 2*pi) sin(x) >>> integrate(exp(-x**2), (x, -oo, oo)) sqrt(pi) References ========== .. [1] https://en.wikipedia.org/wiki/Pi """ is_real = True is_positive = True is_negative = False is_irrational = True is_number = True is_algebraic = False is_transcendental = True __slots__ = () def _latex(self, printer): return r"\pi" @staticmethod def __abs__(): return S.Pi def __int__(self): return 3 def _as_mpf_val(self, prec): return mpf_pi(prec) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (Integer(3), Integer(4)) elif issubclass(number_cls, Rational): return (Rational(223, 71, 1), Rational(22, 7, 1)) pi = S.Pi class GoldenRatio(NumberSymbol, metaclass=Singleton): r"""The golden ratio, `\phi`. Explanation =========== `\phi = \frac{1 + \sqrt{5}}{2}` is an algebraic number. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities, i.e. their maximum. GoldenRatio is a singleton, and can be accessed by ``S.GoldenRatio``. Examples ======== >>> from sympy import S >>> S.GoldenRatio > 1 True >>> S.GoldenRatio.expand(func=True) 1/2 + sqrt(5)/2 >>> S.GoldenRatio.is_irrational True References ========== .. [1] https://en.wikipedia.org/wiki/Golden_ratio """ is_real = True is_positive = True is_negative = False is_irrational = True is_number = True is_algebraic = True is_transcendental = False __slots__ = () def _latex(self, printer): return r"\phi" def __int__(self): return 1 def _as_mpf_val(self, prec): # XXX track down why this has to be increased rv = mlib.from_man_exp(phi_fixed(prec + 10), -prec - 10) return mpf_norm(rv, prec) def _eval_expand_func(self, **hints): from sympy.functions.elementary.miscellaneous import sqrt return S.Half + S.Half*sqrt(5) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (S.One, Rational(2)) elif issubclass(number_cls, Rational): pass _eval_rewrite_as_sqrt = _eval_expand_func class TribonacciConstant(NumberSymbol, metaclass=Singleton): r"""The tribonacci constant. Explanation =========== The tribonacci numbers are like the Fibonacci numbers, but instead of starting with two predetermined terms, the sequence starts with three predetermined terms and each term afterwards is the sum of the preceding three terms. The tribonacci constant is the ratio toward which adjacent tribonacci numbers tend. It is a root of the polynomial `x^3 - x^2 - x - 1 = 0`, and also satisfies the equation `x + x^{-3} = 2`. TribonacciConstant is a singleton, and can be accessed by ``S.TribonacciConstant``. Examples ======== >>> from sympy import S >>> S.TribonacciConstant > 1 True >>> S.TribonacciConstant.expand(func=True) 1/3 + (19 - 3*sqrt(33))**(1/3)/3 + (3*sqrt(33) + 19)**(1/3)/3 >>> S.TribonacciConstant.is_irrational True >>> S.TribonacciConstant.n(20) 1.8392867552141611326 References ========== .. [1] https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Tribonacci_numbers """ is_real = True is_positive = True is_negative = False is_irrational = True is_number = True is_algebraic = True is_transcendental = False __slots__ = () def _latex(self, printer): return r"\text{TribonacciConstant}" def __int__(self): return 1 def _eval_evalf(self, prec): rv = self._eval_expand_func(function=True)._eval_evalf(prec + 4) return Float(rv, precision=prec) def _eval_expand_func(self, **hints): from sympy.functions.elementary.miscellaneous import cbrt, sqrt return (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3 def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (S.One, Rational(2)) elif issubclass(number_cls, Rational): pass _eval_rewrite_as_sqrt = _eval_expand_func class EulerGamma(NumberSymbol, metaclass=Singleton): r"""The Euler-Mascheroni constant. Explanation =========== `\gamma = 0.5772157\ldots` (also called Euler's constant) is a mathematical constant recurring in analysis and number theory. It is defined as the limiting difference between the harmonic series and the natural logarithm: .. math:: \gamma = \lim\limits_{n\to\infty} \left(\sum\limits_{k=1}^n\frac{1}{k} - \ln n\right) EulerGamma is a singleton, and can be accessed by ``S.EulerGamma``. Examples ======== >>> from sympy import S >>> S.EulerGamma.is_irrational >>> S.EulerGamma > 0 True >>> S.EulerGamma > 1 False References ========== .. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant """ is_real = True is_positive = True is_negative = False is_irrational = None is_number = True __slots__ = () def _latex(self, printer): return r"\gamma" def __int__(self): return 0 def _as_mpf_val(self, prec): # XXX track down why this has to be increased v = mlib.libhyper.euler_fixed(prec + 10) rv = mlib.from_man_exp(v, -prec - 10) return mpf_norm(rv, prec) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (S.Zero, S.One) elif issubclass(number_cls, Rational): return (S.Half, Rational(3, 5, 1)) class Catalan(NumberSymbol, metaclass=Singleton): r"""Catalan's constant. Explanation =========== $G = 0.91596559\ldots$ is given by the infinite series .. math:: G = \sum_{k=0}^{\infty} \frac{(-1)^k}{(2k+1)^2} Catalan is a singleton, and can be accessed by ``S.Catalan``. Examples ======== >>> from sympy import S >>> S.Catalan.is_irrational >>> S.Catalan > 0 True >>> S.Catalan > 1 False References ========== .. [1] https://en.wikipedia.org/wiki/Catalan%27s_constant """ is_real = True is_positive = True is_negative = False is_irrational = None is_number = True __slots__ = () def __int__(self): return 0 def _as_mpf_val(self, prec): # XXX track down why this has to be increased v = mlib.catalan_fixed(prec + 10) rv = mlib.from_man_exp(v, -prec - 10) return mpf_norm(rv, prec) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (S.Zero, S.One) elif issubclass(number_cls, Rational): return (Rational(9, 10, 1), S.One) def _eval_rewrite_as_Sum(self, k_sym=None, symbols=None): if (k_sym is not None) or (symbols is not None): return self from .symbol import Dummy from sympy.concrete.summations import Sum k = Dummy('k', integer=True, nonnegative=True) return Sum(S.NegativeOne**k / (2*k+1)**2, (k, 0, S.Infinity)) def _latex(self, printer): return "G" class ImaginaryUnit(AtomicExpr, metaclass=Singleton): r"""The imaginary unit, `i = \sqrt{-1}`. I is a singleton, and can be accessed by ``S.I``, or can be imported as ``I``. Examples ======== >>> from sympy import I, sqrt >>> sqrt(-1) I >>> I*I -1 >>> 1/I -I References ========== .. [1] https://en.wikipedia.org/wiki/Imaginary_unit """ is_commutative = True is_imaginary = True is_finite = True is_number = True is_algebraic = True is_transcendental = False kind = NumberKind __slots__ = () def _latex(self, printer): return printer._settings['imaginary_unit_latex'] @staticmethod def __abs__(): return S.One def _eval_evalf(self, prec): return self def _eval_conjugate(self): return -S.ImaginaryUnit def _eval_power(self, expt): """ b is I = sqrt(-1) e is symbolic object but not equal to 0, 1 I**r -> (-1)**(r/2) -> exp(r/2*Pi*I) -> sin(Pi*r/2) + cos(Pi*r/2)*I, r is decimal I**0 mod 4 -> 1 I**1 mod 4 -> I I**2 mod 4 -> -1 I**3 mod 4 -> -I """ if isinstance(expt, Integer): expt = expt % 4 if expt == 0: return S.One elif expt == 1: return S.ImaginaryUnit elif expt == 2: return S.NegativeOne elif expt == 3: return -S.ImaginaryUnit if isinstance(expt, Rational): i, r = divmod(expt, 2) rv = Pow(S.ImaginaryUnit, r, evaluate=False) if i % 2: return Mul(S.NegativeOne, rv, evaluate=False) return rv def as_base_exp(self): return S.NegativeOne, S.Half @property def _mpc_(self): return (Float(0)._mpf_, Float(1)._mpf_) I = S.ImaginaryUnit def equal_valued(x, y): """Compare expressions treating plain floats as rationals. Examples ======== >>> from sympy import S, symbols, Rational, Float >>> from sympy.core.numbers import equal_valued >>> equal_valued(1, 2) False >>> equal_valued(1, 1) True In SymPy expressions with Floats compare unequal to corresponding expressions with rationals: >>> x = symbols('x') >>> x**2 == x**2.0 False However an individual Float compares equal to a Rational: >>> Rational(1, 2) == Float(0.5) True In a future version of SymPy this might change so that Rational and Float compare unequal. This function provides the behavior currently expected of ``==`` so that it could still be used if the behavior of ``==`` were to change in future. >>> equal_valued(1, 1.0) # Float vs Rational True >>> equal_valued(S(1).n(3), S(1).n(5)) # Floats of different precision True Explanation =========== In future SymPy verions Float and Rational might compare unequal and floats with different precisions might compare unequal. In that context a function is needed that can check if a number is equal to 1 or 0 etc. The idea is that instead of testing ``if x == 1:`` if we want to accept floats like ``1.0`` as well then the test can be written as ``if equal_valued(x, 1):`` or ``if equal_valued(x, 2):``. Since this function is intended to be used in situations where one or both operands are expected to be concrete numbers like 1 or 0 the function does not recurse through the args of any compound expression to compare any nested floats. References ========== .. [1] https://github.com/sympy/sympy/pull/20033 """ x = _sympify(x) y = _sympify(y) # Handle everything except Float/Rational first if not x.is_Float and not y.is_Float: return x == y elif x.is_Float and y.is_Float: # Compare values without regard for precision return x._mpf_ == y._mpf_ elif x.is_Float: x, y = y, x if not x.is_Rational: return False # Now y is Float and x is Rational. A simple approach at this point would # just be x == Rational(y) but if y has a large exponent creating a # Rational could be prohibitively expensive. sign, man, exp, _ = y._mpf_ p, q = x.p, x.q if sign: man = -man if exp == 0: # y odd integer return q == 1 and man == p elif exp > 0: # y even integer if q != 1: return False if p.bit_length() != man.bit_length() + exp: return False return man << exp == p else: # y non-integer. Need p == man and q == 2**-exp if p != man: return False neg_exp = -exp if q.bit_length() - 1 != neg_exp: return False return (1 << neg_exp) == q @dispatch(Tuple, Number) # type:ignore def _eval_is_eq(self, other): # noqa: F811 return False def sympify_fractions(f): return Rational(f.numerator, f.denominator, 1) _sympy_converter[fractions.Fraction] = sympify_fractions if HAS_GMPY: def sympify_mpz(x): return Integer(int(x)) # XXX: The sympify_mpq function here was never used because it is # overridden by the other sympify_mpq function below. Maybe it should just # be removed or maybe it should be used for something... def sympify_mpq(x): return Rational(int(x.numerator), int(x.denominator)) _sympy_converter[type(gmpy.mpz(1))] = sympify_mpz _sympy_converter[type(gmpy.mpq(1, 2))] = sympify_mpq def sympify_mpmath_mpq(x): p, q = x._mpq_ return Rational(p, q, 1) _sympy_converter[type(mpmath.rational.mpq(1, 2))] = sympify_mpmath_mpq def sympify_mpmath(x): return Expr._from_mpmath(x, x.context.prec) _sympy_converter[mpnumeric] = sympify_mpmath def sympify_complex(a): real, imag = list(map(sympify, (a.real, a.imag))) return real + S.ImaginaryUnit*imag _sympy_converter[complex] = sympify_complex from .power import Pow, integer_nthroot from .mul import Mul Mul.identity = One() from .add import Add Add.identity = Zero() def _register_classes(): numbers.Number.register(Number) numbers.Real.register(Float) numbers.Rational.register(Rational) numbers.Integral.register(Integer) _register_classes() _illegal = (S.NaN, S.Infinity, S.NegativeInfinity, S.ComplexInfinity)
bdab0202c4f8694f572717eb1068cbfb3795225d85b08d64b7356d3da26aff47
from __future__ import annotations from operator import attrgetter from collections import defaultdict from sympy.utilities.exceptions import sympy_deprecation_warning from .sympify import _sympify as _sympify_, sympify from .basic import Basic from .cache import cacheit from .sorting import ordered from .logic import fuzzy_and from .parameters import global_parameters from sympy.utilities.iterables import sift from sympy.multipledispatch.dispatcher import (Dispatcher, ambiguity_register_error_ignore_dup, str_signature, RaiseNotImplementedError) class AssocOp(Basic): """ Associative operations, can separate noncommutative and commutative parts. (a op b) op c == a op (b op c) == a op b op c. Base class for Add and Mul. This is an abstract base class, concrete derived classes must define the attribute `identity`. .. deprecated:: 1.7 Using arguments that aren't subclasses of :class:`~.Expr` in core operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is deprecated. See :ref:`non-expr-args-deprecated` for details. Parameters ========== *args : Arguments which are operated evaluate : bool, optional Evaluate the operation. If not passed, refer to ``global_parameters.evaluate``. """ # for performance reason, we don't let is_commutative go to assumptions, # and keep it right here __slots__: tuple[str, ...] = ('is_commutative',) _args_type: type[Basic] | None = None @cacheit def __new__(cls, *args, evaluate=None, _sympify=True): # Allow faster processing by passing ``_sympify=False``, if all arguments # are already sympified. if _sympify: args = list(map(_sympify_, args)) # Disallow non-Expr args in Add/Mul typ = cls._args_type if typ is not None: from .relational import Relational if any(isinstance(arg, Relational) for arg in args): raise TypeError("Relational cannot be used in %s" % cls.__name__) # This should raise TypeError once deprecation period is over: for arg in args: if not isinstance(arg, typ): sympy_deprecation_warning( f""" Using non-Expr arguments in {cls.__name__} is deprecated (in this case, one of the arguments has type {type(arg).__name__!r}). If you really did intend to use a multiplication or addition operation with this object, use the * or + operator instead. """, deprecated_since_version="1.7", active_deprecations_target="non-expr-args-deprecated", stacklevel=4, ) if evaluate is None: evaluate = global_parameters.evaluate if not evaluate: obj = cls._from_args(args) obj = cls._exec_constructor_postprocessors(obj) return obj args = [a for a in args if a is not cls.identity] if len(args) == 0: return cls.identity if len(args) == 1: return args[0] c_part, nc_part, order_symbols = cls.flatten(args) is_commutative = not nc_part obj = cls._from_args(c_part + nc_part, is_commutative) obj = cls._exec_constructor_postprocessors(obj) if order_symbols is not None: from sympy.series.order import Order return Order(obj, *order_symbols) return obj @classmethod def _from_args(cls, args, is_commutative=None): """Create new instance with already-processed args. If the args are not in canonical order, then a non-canonical result will be returned, so use with caution. The order of args may change if the sign of the args is changed.""" if len(args) == 0: return cls.identity elif len(args) == 1: return args[0] obj = super().__new__(cls, *args) if is_commutative is None: is_commutative = fuzzy_and(a.is_commutative for a in args) obj.is_commutative = is_commutative return obj def _new_rawargs(self, *args, reeval=True, **kwargs): """Create new instance of own class with args exactly as provided by caller but returning the self class identity if args is empty. Examples ======== This is handy when we want to optimize things, e.g. >>> from sympy import Mul, S >>> from sympy.abc import x, y >>> e = Mul(3, x, y) >>> e.args (3, x, y) >>> Mul(*e.args[1:]) x*y >>> e._new_rawargs(*e.args[1:]) # the same as above, but faster x*y Note: use this with caution. There is no checking of arguments at all. This is best used when you are rebuilding an Add or Mul after simply removing one or more args. If, for example, modifications, result in extra 1s being inserted they will show up in the result: >>> m = (x*y)._new_rawargs(S.One, x); m 1*x >>> m == x False >>> m.is_Mul True Another issue to be aware of is that the commutativity of the result is based on the commutativity of self. If you are rebuilding the terms that came from a commutative object then there will be no problem, but if self was non-commutative then what you are rebuilding may now be commutative. Although this routine tries to do as little as possible with the input, getting the commutativity right is important, so this level of safety is enforced: commutativity will always be recomputed if self is non-commutative and kwarg `reeval=False` has not been passed. """ if reeval and self.is_commutative is False: is_commutative = None else: is_commutative = self.is_commutative return self._from_args(args, is_commutative) @classmethod def flatten(cls, seq): """Return seq so that none of the elements are of type `cls`. This is the vanilla routine that will be used if a class derived from AssocOp does not define its own flatten routine.""" # apply associativity, no commutativity property is used new_seq = [] while seq: o = seq.pop() if o.__class__ is cls: # classes must match exactly seq.extend(o.args) else: new_seq.append(o) new_seq.reverse() # c_part, nc_part, order_symbols return [], new_seq, None def _matches_commutative(self, expr, repl_dict=None, old=False): """ Matches Add/Mul "pattern" to an expression "expr". repl_dict ... a dictionary of (wild: expression) pairs, that get returned with the results This function is the main workhorse for Add/Mul. Examples ======== >>> from sympy import symbols, Wild, sin >>> a = Wild("a") >>> b = Wild("b") >>> c = Wild("c") >>> x, y, z = symbols("x y z") >>> (a+sin(b)*c)._matches_commutative(x+sin(y)*z) {a_: x, b_: y, c_: z} In the example above, "a+sin(b)*c" is the pattern, and "x+sin(y)*z" is the expression. The repl_dict contains parts that were already matched. For example here: >>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z, repl_dict={a: x}) {a_: x, b_: y, c_: z} the only function of the repl_dict is to return it in the result, e.g. if you omit it: >>> (x+sin(b)*c)._matches_commutative(x+sin(y)*z) {b_: y, c_: z} the "a: x" is not returned in the result, but otherwise it is equivalent. """ from .function import _coeff_isneg # make sure expr is Expr if pattern is Expr from .expr import Expr if isinstance(self, Expr) and not isinstance(expr, Expr): return None if repl_dict is None: repl_dict = {} # handle simple patterns if self == expr: return repl_dict d = self._matches_simple(expr, repl_dict) if d is not None: return d # eliminate exact part from pattern: (2+a+w1+w2).matches(expr) -> (w1+w2).matches(expr-a-2) from .function import WildFunction from .symbol import Wild wild_part, exact_part = sift(self.args, lambda p: p.has(Wild, WildFunction) and not expr.has(p), binary=True) if not exact_part: wild_part = list(ordered(wild_part)) if self.is_Add: # in addition to normal ordered keys, impose # sorting on Muls with leading Number to put # them in order wild_part = sorted(wild_part, key=lambda x: x.args[0] if x.is_Mul and x.args[0].is_Number else 0) else: exact = self._new_rawargs(*exact_part) free = expr.free_symbols if free and (exact.free_symbols - free): # there are symbols in the exact part that are not # in the expr; but if there are no free symbols, let # the matching continue return None newexpr = self._combine_inverse(expr, exact) if not old and (expr.is_Add or expr.is_Mul): check = newexpr if _coeff_isneg(check): check = -check if check.count_ops() > expr.count_ops(): return None newpattern = self._new_rawargs(*wild_part) return newpattern.matches(newexpr, repl_dict) # now to real work ;) i = 0 saw = set() while expr not in saw: saw.add(expr) args = tuple(ordered(self.make_args(expr))) if self.is_Add and expr.is_Add: # in addition to normal ordered keys, impose # sorting on Muls with leading Number to put # them in order args = tuple(sorted(args, key=lambda x: x.args[0] if x.is_Mul and x.args[0].is_Number else 0)) expr_list = (self.identity,) + args for last_op in reversed(expr_list): for w in reversed(wild_part): d1 = w.matches(last_op, repl_dict) if d1 is not None: d2 = self.xreplace(d1).matches(expr, d1) if d2 is not None: return d2 if i == 0: if self.is_Mul: # make e**i look like Mul if expr.is_Pow and expr.exp.is_Integer: from .mul import Mul if expr.exp > 0: expr = Mul(*[expr.base, expr.base**(expr.exp - 1)], evaluate=False) else: expr = Mul(*[1/expr.base, expr.base**(expr.exp + 1)], evaluate=False) i += 1 continue elif self.is_Add: # make i*e look like Add c, e = expr.as_coeff_Mul() if abs(c) > 1: from .add import Add if c > 0: expr = Add(*[e, (c - 1)*e], evaluate=False) else: expr = Add(*[-e, (c + 1)*e], evaluate=False) i += 1 continue # try collection on non-Wild symbols from sympy.simplify.radsimp import collect was = expr did = set() for w in reversed(wild_part): c, w = w.as_coeff_mul(Wild) free = c.free_symbols - did if free: did.update(free) expr = collect(expr, free) if expr != was: i += 0 continue break # if we didn't continue, there is nothing more to do return def _has_matcher(self): """Helper for .has() that checks for containment of subexpressions within an expr by using sets of args of similar nodes, e.g. x + 1 in x + y + 1 checks to see that {x, 1} & {x, y, 1} == {x, 1} """ def _ncsplit(expr): # this is not the same as args_cnc because here # we don't assume expr is a Mul -- hence deal with args -- # and always return a set. cpart, ncpart = sift(expr.args, lambda arg: arg.is_commutative is True, binary=True) return set(cpart), ncpart c, nc = _ncsplit(self) cls = self.__class__ def is_in(expr): if isinstance(expr, cls): if expr == self: return True _c, _nc = _ncsplit(expr) if (c & _c) == c: if not nc: return True elif len(nc) <= len(_nc): for i in range(len(_nc) - len(nc) + 1): if _nc[i:i + len(nc)] == nc: return True return False return is_in def _eval_evalf(self, prec): """ Evaluate the parts of self that are numbers; if the whole thing was a number with no functions it would have been evaluated, but it wasn't so we must judiciously extract the numbers and reconstruct the object. This is *not* simply replacing numbers with evaluated numbers. Numbers should be handled in the largest pure-number expression as possible. So the code below separates ``self`` into number and non-number parts and evaluates the number parts and walks the args of the non-number part recursively (doing the same thing). """ from .add import Add from .mul import Mul from .symbol import Symbol from .function import AppliedUndef if isinstance(self, (Mul, Add)): x, tail = self.as_independent(Symbol, AppliedUndef) # if x is an AssocOp Function then the _evalf below will # call _eval_evalf (here) so we must break the recursion if not (tail is self.identity or isinstance(x, AssocOp) and x.is_Function or x is self.identity and isinstance(tail, AssocOp)): # here, we have a number so we just call to _evalf with prec; # prec is not the same as n, it is the binary precision so # that's why we don't call to evalf. x = x._evalf(prec) if x is not self.identity else self.identity args = [] tail_args = tuple(self.func.make_args(tail)) for a in tail_args: # here we call to _eval_evalf since we don't know what we # are dealing with and all other _eval_evalf routines should # be doing the same thing (i.e. taking binary prec and # finding the evalf-able args) newa = a._eval_evalf(prec) if newa is None: args.append(a) else: args.append(newa) return self.func(x, *args) # this is the same as above, but there were no pure-number args to # deal with args = [] for a in self.args: newa = a._eval_evalf(prec) if newa is None: args.append(a) else: args.append(newa) return self.func(*args) @classmethod def make_args(cls, expr): """ Return a sequence of elements `args` such that cls(*args) == expr Examples ======== >>> from sympy import Symbol, Mul, Add >>> x, y = map(Symbol, 'xy') >>> Mul.make_args(x*y) (x, y) >>> Add.make_args(x*y) (x*y,) >>> set(Add.make_args(x*y + y)) == set([y, x*y]) True """ if isinstance(expr, cls): return expr.args else: return (sympify(expr),) def doit(self, **hints): if hints.get('deep', True): terms = [term.doit(**hints) for term in self.args] else: terms = self.args return self.func(*terms, evaluate=True) class ShortCircuit(Exception): pass class LatticeOp(AssocOp): """ Join/meet operations of an algebraic lattice[1]. Explanation =========== These binary operations are associative (op(op(a, b), c) = op(a, op(b, c))), commutative (op(a, b) = op(b, a)) and idempotent (op(a, a) = op(a) = a). Common examples are AND, OR, Union, Intersection, max or min. They have an identity element (op(identity, a) = a) and an absorbing element conventionally called zero (op(zero, a) = zero). This is an abstract base class, concrete derived classes must declare attributes zero and identity. All defining properties are then respected. Examples ======== >>> from sympy import Integer >>> from sympy.core.operations import LatticeOp >>> class my_join(LatticeOp): ... zero = Integer(0) ... identity = Integer(1) >>> my_join(2, 3) == my_join(3, 2) True >>> my_join(2, my_join(3, 4)) == my_join(2, 3, 4) True >>> my_join(0, 1, 4, 2, 3, 4) 0 >>> my_join(1, 2) 2 References ========== .. [1] https://en.wikipedia.org/wiki/Lattice_%28order%29 """ is_commutative = True def __new__(cls, *args, **options): args = (_sympify_(arg) for arg in args) try: # /!\ args is a generator and _new_args_filter # must be careful to handle as such; this # is done so short-circuiting can be done # without having to sympify all values _args = frozenset(cls._new_args_filter(args)) except ShortCircuit: return sympify(cls.zero) if not _args: return sympify(cls.identity) elif len(_args) == 1: return set(_args).pop() else: # XXX in almost every other case for __new__, *_args is # passed along, but the expectation here is for _args obj = super(AssocOp, cls).__new__(cls, *ordered(_args)) obj._argset = _args return obj @classmethod def _new_args_filter(cls, arg_sequence, call_cls=None): """Generator filtering args""" ncls = call_cls or cls for arg in arg_sequence: if arg == ncls.zero: raise ShortCircuit(arg) elif arg == ncls.identity: continue elif arg.func == ncls: yield from arg.args else: yield arg @classmethod def make_args(cls, expr): """ Return a set of args such that cls(*arg_set) == expr. """ if isinstance(expr, cls): return expr._argset else: return frozenset([sympify(expr)]) @staticmethod def _compare_pretty(a, b): return (str(a) > str(b)) - (str(a) < str(b)) class AssocOpDispatcher: """ Handler dispatcher for associative operators .. notes:: This approach is experimental, and can be replaced or deleted in the future. See https://github.com/sympy/sympy/pull/19463. Explanation =========== If arguments of different types are passed, the classes which handle the operation for each type are collected. Then, a class which performs the operation is selected by recursive binary dispatching. Dispatching relation can be registered by ``register_handlerclass`` method. Priority registration is unordered. You cannot make ``A*B`` and ``B*A`` refer to different handler classes. All logic dealing with the order of arguments must be implemented in the handler class. Examples ======== >>> from sympy import Add, Expr, Symbol >>> from sympy.core.add import add >>> class NewExpr(Expr): ... @property ... def _add_handler(self): ... return NewAdd >>> class NewAdd(NewExpr, Add): ... pass >>> add.register_handlerclass((Add, NewAdd), NewAdd) >>> a, b = Symbol('a'), NewExpr() >>> add(a, b) == NewAdd(a, b) True """ def __init__(self, name, doc=None): self.name = name self.doc = doc self.handlerattr = "_%s_handler" % name self._handlergetter = attrgetter(self.handlerattr) self._dispatcher = Dispatcher(name) def __repr__(self): return "<dispatched %s>" % self.name def register_handlerclass(self, classes, typ, on_ambiguity=ambiguity_register_error_ignore_dup): """ Register the handler class for two classes, in both straight and reversed order. Paramteters =========== classes : tuple of two types Classes who are compared with each other. typ: Class which is registered to represent *cls1* and *cls2*. Handler method of *self* must be implemented in this class. """ if not len(classes) == 2: raise RuntimeError( "Only binary dispatch is supported, but got %s types: <%s>." % ( len(classes), str_signature(classes) )) if len(set(classes)) == 1: raise RuntimeError( "Duplicate types <%s> cannot be dispatched." % str_signature(classes) ) self._dispatcher.add(tuple(classes), typ, on_ambiguity=on_ambiguity) self._dispatcher.add(tuple(reversed(classes)), typ, on_ambiguity=on_ambiguity) @cacheit def __call__(self, *args, _sympify=True, **kwargs): """ Parameters ========== *args : Arguments which are operated """ if _sympify: args = tuple(map(_sympify_, args)) handlers = frozenset(map(self._handlergetter, args)) # no need to sympify again return self.dispatch(handlers)(*args, _sympify=False, **kwargs) @cacheit def dispatch(self, handlers): """ Select the handler class, and return its handler method. """ # Quick exit for the case where all handlers are same if len(handlers) == 1: h, = handlers if not isinstance(h, type): raise RuntimeError("Handler {!r} is not a type.".format(h)) return h # Recursively select with registered binary priority for i, typ in enumerate(handlers): if not isinstance(typ, type): raise RuntimeError("Handler {!r} is not a type.".format(typ)) if i == 0: handler = typ else: prev_handler = handler handler = self._dispatcher.dispatch(prev_handler, typ) if not isinstance(handler, type): raise RuntimeError( "Dispatcher for {!r} and {!r} must return a type, but got {!r}".format( prev_handler, typ, handler )) # return handler class return handler @property def __doc__(self): docs = [ "Multiply dispatched associative operator: %s" % self.name, "Note that support for this is experimental, see the docs for :class:`AssocOpDispatcher` for details" ] if self.doc: docs.append(self.doc) s = "Registered handler classes\n" s += '=' * len(s) docs.append(s) amb_sigs = [] typ_sigs = defaultdict(list) for sigs in self._dispatcher.ordering[::-1]: key = self._dispatcher.funcs[sigs] typ_sigs[key].append(sigs) for typ, sigs in typ_sigs.items(): sigs_str = ', '.join('<%s>' % str_signature(sig) for sig in sigs) if isinstance(typ, RaiseNotImplementedError): amb_sigs.append(sigs_str) continue s = 'Inputs: %s\n' % sigs_str s += '-' * len(s) + '\n' s += typ.__name__ docs.append(s) if amb_sigs: s = "Ambiguous handler classes\n" s += '=' * len(s) docs.append(s) s = '\n'.join(amb_sigs) docs.append(s) return '\n\n'.join(docs)
b2eaef9377b91323627d51caa6a2d9e4d5286c5752d3ec0460de17a14933308f
from .add import Add from .exprtools import gcd_terms from .function import Function from .kind import NumberKind from .logic import fuzzy_and, fuzzy_not from .mul import Mul from .numbers import equal_valued from .singleton import S class Mod(Function): """Represents a modulo operation on symbolic expressions. Parameters ========== p : Expr Dividend. q : Expr Divisor. Notes ===== The convention used is the same as Python's: the remainder always has the same sign as the divisor. Examples ======== >>> from sympy.abc import x, y >>> x**2 % y Mod(x**2, y) >>> _.subs({x: 5, y: 6}) 1 """ kind = NumberKind @classmethod def eval(cls, p, q): def number_eval(p, q): """Try to return p % q if both are numbers or +/-p is known to be less than or equal q. """ if q.is_zero: raise ZeroDivisionError("Modulo by zero") if p is S.NaN or q is S.NaN or p.is_finite is False or q.is_finite is False: return S.NaN if p is S.Zero or p in (q, -q) or (p.is_integer and q == 1): return S.Zero if q.is_Number: if p.is_Number: return p%q if q == 2: if p.is_even: return S.Zero elif p.is_odd: return S.One if hasattr(p, '_eval_Mod'): rv = getattr(p, '_eval_Mod')(q) if rv is not None: return rv # by ratio r = p/q if r.is_integer: return S.Zero try: d = int(r) except TypeError: pass else: if isinstance(d, int): rv = p - d*q if (rv*q < 0) == True: rv += q return rv # by difference # -2|q| < p < 2|q| d = abs(p) for _ in range(2): d -= abs(q) if d.is_negative: if q.is_positive: if p.is_positive: return d + q elif p.is_negative: return -d elif q.is_negative: if p.is_positive: return d elif p.is_negative: return -d + q break rv = number_eval(p, q) if rv is not None: return rv # denest if isinstance(p, cls): qinner = p.args[1] if qinner % q == 0: return cls(p.args[0], q) elif (qinner*(q - qinner)).is_nonnegative: # |qinner| < |q| and have same sign return p elif isinstance(-p, cls): qinner = (-p).args[1] if qinner % q == 0: return cls(-(-p).args[0], q) elif (qinner*(q + qinner)).is_nonpositive: # |qinner| < |q| and have different sign return p elif isinstance(p, Add): # separating into modulus and non modulus both_l = non_mod_l, mod_l = [], [] for arg in p.args: both_l[isinstance(arg, cls)].append(arg) # if q same for all if mod_l and all(inner.args[1] == q for inner in mod_l): net = Add(*non_mod_l) + Add(*[i.args[0] for i in mod_l]) return cls(net, q) elif isinstance(p, Mul): # separating into modulus and non modulus both_l = non_mod_l, mod_l = [], [] for arg in p.args: both_l[isinstance(arg, cls)].append(arg) if mod_l and all(inner.args[1] == q for inner in mod_l) and all(t.is_integer for t in p.args) and q.is_integer: # finding distributive term non_mod_l = [cls(x, q) for x in non_mod_l] mod = [] non_mod = [] for j in non_mod_l: if isinstance(j, cls): mod.append(j.args[0]) else: non_mod.append(j) prod_mod = Mul(*mod) prod_non_mod = Mul(*non_mod) prod_mod1 = Mul(*[i.args[0] for i in mod_l]) net = prod_mod1*prod_mod return prod_non_mod*cls(net, q) if q.is_Integer and q is not S.One: non_mod_l = [i % q if i.is_Integer and (i % q is not S.Zero) else i for i in non_mod_l] p = Mul(*(non_mod_l + mod_l)) # XXX other possibilities? from sympy.polys.polyerrors import PolynomialError from sympy.polys.polytools import gcd # extract gcd; any further simplification should be done by the user try: G = gcd(p, q) if not equal_valued(G, 1): p, q = [gcd_terms(i/G, clear=False, fraction=False) for i in (p, q)] except PolynomialError: # issue 21373 G = S.One pwas, qwas = p, q # simplify terms # (x + y + 2) % x -> Mod(y + 2, x) if p.is_Add: args = [] for i in p.args: a = cls(i, q) if a.count(cls) > i.count(cls): args.append(i) else: args.append(a) if args != list(p.args): p = Add(*args) else: # handle coefficients if they are not Rational # since those are not handled by factor_terms # e.g. Mod(.6*x, .3*y) -> 0.3*Mod(2*x, y) cp, p = p.as_coeff_Mul() cq, q = q.as_coeff_Mul() ok = False if not cp.is_Rational or not cq.is_Rational: r = cp % cq if equal_valued(r, 0): G *= cq p *= int(cp/cq) ok = True if not ok: p = cp*p q = cq*q # simple -1 extraction if p.could_extract_minus_sign() and q.could_extract_minus_sign(): G, p, q = [-i for i in (G, p, q)] # check again to see if p and q can now be handled as numbers rv = number_eval(p, q) if rv is not None: return rv*G # put 1.0 from G on inside if G.is_Float and equal_valued(G, 1): p *= G return cls(p, q, evaluate=False) elif G.is_Mul and G.args[0].is_Float and equal_valued(G.args[0], 1): p = G.args[0]*p G = Mul._from_args(G.args[1:]) return G*cls(p, q, evaluate=(p, q) != (pwas, qwas)) def _eval_is_integer(self): p, q = self.args if fuzzy_and([p.is_integer, q.is_integer, fuzzy_not(q.is_zero)]): return True def _eval_is_nonnegative(self): if self.args[1].is_positive: return True def _eval_is_nonpositive(self): if self.args[1].is_negative: return True def _eval_rewrite_as_floor(self, a, b, **kwargs): from sympy.functions.elementary.integers import floor return a - b*floor(a/b)
a5bbacadfbf546e09a0c09085ca62827eb3a440b9d08381addb4c22bbd7d5e51
""" Adaptive numerical evaluation of SymPy expressions, using mpmath for mathematical functions. """ from __future__ import annotations from typing import Tuple as tTuple, Optional, Union as tUnion, Callable, List, Dict as tDict, Type, TYPE_CHECKING, \ Any, overload import math import mpmath.libmp as libmp from mpmath import ( make_mpc, make_mpf, mp, mpc, mpf, nsum, quadts, quadosc, workprec) from mpmath import inf as mpmath_inf from mpmath.libmp import (from_int, from_man_exp, from_rational, fhalf, fnan, finf, fninf, fnone, fone, fzero, mpf_abs, mpf_add, mpf_atan, mpf_atan2, mpf_cmp, mpf_cos, mpf_e, mpf_exp, mpf_log, mpf_lt, mpf_mul, mpf_neg, mpf_pi, mpf_pow, mpf_pow_int, mpf_shift, mpf_sin, mpf_sqrt, normalize, round_nearest, to_int, to_str) from mpmath.libmp import bitcount as mpmath_bitcount from mpmath.libmp.backend import MPZ from mpmath.libmp.libmpc import _infs_nan from mpmath.libmp.libmpf import dps_to_prec, prec_to_dps from .sympify import sympify from .singleton import S from sympy.external.gmpy import SYMPY_INTS from sympy.utilities.iterables import is_sequence from sympy.utilities.lambdify import lambdify from sympy.utilities.misc import as_int if TYPE_CHECKING: from sympy.core.expr import Expr from sympy.core.add import Add from sympy.core.mul import Mul from sympy.core.power import Pow from sympy.core.symbol import Symbol from sympy.integrals.integrals import Integral from sympy.concrete.summations import Sum from sympy.concrete.products import Product from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.complexes import Abs, re, im from sympy.functions.elementary.integers import ceiling, floor from sympy.functions.elementary.trigonometric import atan from .numbers import Float, Rational, Integer, AlgebraicNumber, Number LG10 = math.log(10, 2) rnd = round_nearest def bitcount(n): """Return smallest integer, b, such that |n|/2**b < 1. """ return mpmath_bitcount(abs(int(n))) # Used in a few places as placeholder values to denote exponents and # precision levels, e.g. of exact numbers. Must be careful to avoid # passing these to mpmath functions or returning them in final results. INF = float(mpmath_inf) MINUS_INF = float(-mpmath_inf) # ~= 100 digits. Real men set this to INF. DEFAULT_MAXPREC = 333 class PrecisionExhausted(ArithmeticError): pass #----------------------------------------------------------------------------# # # # Helper functions for arithmetic and complex parts # # # #----------------------------------------------------------------------------# """ An mpf value tuple is a tuple of integers (sign, man, exp, bc) representing a floating-point number: [1, -1][sign]*man*2**exp where sign is 0 or 1 and bc should correspond to the number of bits used to represent the mantissa (man) in binary notation, e.g. """ MPF_TUP = tTuple[int, int, int, int] # mpf value tuple """ Explanation =========== >>> from sympy.core.evalf import bitcount >>> sign, man, exp, bc = 0, 5, 1, 3 >>> n = [1, -1][sign]*man*2**exp >>> n, bitcount(man) (10, 3) A temporary result is a tuple (re, im, re_acc, im_acc) where re and im are nonzero mpf value tuples representing approximate numbers, or None to denote exact zeros. re_acc, im_acc are integers denoting log2(e) where e is the estimated relative accuracy of the respective complex part, but may be anything if the corresponding complex part is None. """ TMP_RES = Any # temporary result, should be some variant of # tUnion[tTuple[Optional[MPF_TUP], Optional[MPF_TUP], # Optional[int], Optional[int]], # 'ComplexInfinity'] # but mypy reports error because it doesn't know as we know # 1. re and re_acc are either both None or both MPF_TUP # 2. sometimes the result can't be zoo # type of the "options" parameter in internal evalf functions OPT_DICT = tDict[str, Any] def fastlog(x: Optional[MPF_TUP]) -> tUnion[int, Any]: """Fast approximation of log2(x) for an mpf value tuple x. Explanation =========== Calculated as exponent + width of mantissa. This is an approximation for two reasons: 1) it gives the ceil(log2(abs(x))) value and 2) it is too high by 1 in the case that x is an exact power of 2. Although this is easy to remedy by testing to see if the odd mpf mantissa is 1 (indicating that one was dealing with an exact power of 2) that would decrease the speed and is not necessary as this is only being used as an approximation for the number of bits in x. The correct return value could be written as "x[2] + (x[3] if x[1] != 1 else 0)". Since mpf tuples always have an odd mantissa, no check is done to see if the mantissa is a multiple of 2 (in which case the result would be too large by 1). Examples ======== >>> from sympy import log >>> from sympy.core.evalf import fastlog, bitcount >>> s, m, e = 0, 5, 1 >>> bc = bitcount(m) >>> n = [1, -1][s]*m*2**e >>> n, (log(n)/log(2)).evalf(2), fastlog((s, m, e, bc)) (10, 3.3, 4) """ if not x or x == fzero: return MINUS_INF return x[2] + x[3] def pure_complex(v: 'Expr', or_real=False) -> tuple['Number', 'Number'] | None: """Return a and b if v matches a + I*b where b is not zero and a and b are Numbers, else None. If `or_real` is True then 0 will be returned for `b` if `v` is a real number. Examples ======== >>> from sympy.core.evalf import pure_complex >>> from sympy import sqrt, I, S >>> a, b, surd = S(2), S(3), sqrt(2) >>> pure_complex(a) >>> pure_complex(a, or_real=True) (2, 0) >>> pure_complex(surd) >>> pure_complex(a + b*I) (2, 3) >>> pure_complex(I) (0, 1) """ h, t = v.as_coeff_Add() if t: c, i = t.as_coeff_Mul() if i is S.ImaginaryUnit: return h, c elif or_real: return h, S.Zero return None # I don't know what this is, see function scaled_zero below SCALED_ZERO_TUP = tTuple[List[int], int, int, int] @overload def scaled_zero(mag: SCALED_ZERO_TUP, sign=1) -> MPF_TUP: ... @overload def scaled_zero(mag: int, sign=1) -> tTuple[SCALED_ZERO_TUP, int]: ... def scaled_zero(mag: tUnion[SCALED_ZERO_TUP, int], sign=1) -> \ tUnion[MPF_TUP, tTuple[SCALED_ZERO_TUP, int]]: """Return an mpf representing a power of two with magnitude ``mag`` and -1 for precision. Or, if ``mag`` is a scaled_zero tuple, then just remove the sign from within the list that it was initially wrapped in. Examples ======== >>> from sympy.core.evalf import scaled_zero >>> from sympy import Float >>> z, p = scaled_zero(100) >>> z, p (([0], 1, 100, 1), -1) >>> ok = scaled_zero(z) >>> ok (0, 1, 100, 1) >>> Float(ok) 1.26765060022823e+30 >>> Float(ok, p) 0.e+30 >>> ok, p = scaled_zero(100, -1) >>> Float(scaled_zero(ok), p) -0.e+30 """ if isinstance(mag, tuple) and len(mag) == 4 and iszero(mag, scaled=True): return (mag[0][0],) + mag[1:] elif isinstance(mag, SYMPY_INTS): if sign not in [-1, 1]: raise ValueError('sign must be +/-1') rv, p = mpf_shift(fone, mag), -1 s = 0 if sign == 1 else 1 rv = ([s],) + rv[1:] return rv, p else: raise ValueError('scaled zero expects int or scaled_zero tuple.') def iszero(mpf: tUnion[MPF_TUP, SCALED_ZERO_TUP, None], scaled=False) -> Optional[bool]: if not scaled: return not mpf or not mpf[1] and not mpf[-1] return mpf and isinstance(mpf[0], list) and mpf[1] == mpf[-1] == 1 def complex_accuracy(result: TMP_RES) -> tUnion[int, Any]: """ Returns relative accuracy of a complex number with given accuracies for the real and imaginary parts. The relative accuracy is defined in the complex norm sense as ||z|+|error|| / |z| where error is equal to (real absolute error) + (imag absolute error)*i. The full expression for the (logarithmic) error can be approximated easily by using the max norm to approximate the complex norm. In the worst case (re and im equal), this is wrong by a factor sqrt(2), or by log2(sqrt(2)) = 0.5 bit. """ if result is S.ComplexInfinity: return INF re, im, re_acc, im_acc = result if not im: if not re: return INF return re_acc if not re: return im_acc re_size = fastlog(re) im_size = fastlog(im) absolute_error = max(re_size - re_acc, im_size - im_acc) relative_error = absolute_error - max(re_size, im_size) return -relative_error def get_abs(expr: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES: result = evalf(expr, prec + 2, options) if result is S.ComplexInfinity: return finf, None, prec, None re, im, re_acc, im_acc = result if not re: re, re_acc, im, im_acc = im, im_acc, re, re_acc if im: if expr.is_number: abs_expr, _, acc, _ = evalf(abs(N(expr, prec + 2)), prec + 2, options) return abs_expr, None, acc, None else: if 'subs' in options: return libmp.mpc_abs((re, im), prec), None, re_acc, None return abs(expr), None, prec, None elif re: return mpf_abs(re), None, re_acc, None else: return None, None, None, None def get_complex_part(expr: 'Expr', no: int, prec: int, options: OPT_DICT) -> TMP_RES: """no = 0 for real part, no = 1 for imaginary part""" workprec = prec i = 0 while 1: res = evalf(expr, workprec, options) if res is S.ComplexInfinity: return fnan, None, prec, None value, accuracy = res[no::2] # XXX is the last one correct? Consider re((1+I)**2).n() if (not value) or accuracy >= prec or -value[2] > prec: return value, None, accuracy, None workprec += max(30, 2**i) i += 1 def evalf_abs(expr: 'Abs', prec: int, options: OPT_DICT) -> TMP_RES: return get_abs(expr.args[0], prec, options) def evalf_re(expr: 're', prec: int, options: OPT_DICT) -> TMP_RES: return get_complex_part(expr.args[0], 0, prec, options) def evalf_im(expr: 'im', prec: int, options: OPT_DICT) -> TMP_RES: return get_complex_part(expr.args[0], 1, prec, options) def finalize_complex(re: MPF_TUP, im: MPF_TUP, prec: int) -> TMP_RES: if re == fzero and im == fzero: raise ValueError("got complex zero with unknown accuracy") elif re == fzero: return None, im, None, prec elif im == fzero: return re, None, prec, None size_re = fastlog(re) size_im = fastlog(im) if size_re > size_im: re_acc = prec im_acc = prec + min(-(size_re - size_im), 0) else: im_acc = prec re_acc = prec + min(-(size_im - size_re), 0) return re, im, re_acc, im_acc def chop_parts(value: TMP_RES, prec: int) -> TMP_RES: """ Chop off tiny real or complex parts. """ if value is S.ComplexInfinity: return value re, im, re_acc, im_acc = value # Method 1: chop based on absolute value if re and re not in _infs_nan and (fastlog(re) < -prec + 4): re, re_acc = None, None if im and im not in _infs_nan and (fastlog(im) < -prec + 4): im, im_acc = None, None # Method 2: chop if inaccurate and relatively small if re and im: delta = fastlog(re) - fastlog(im) if re_acc < 2 and (delta - re_acc <= -prec + 4): re, re_acc = None, None if im_acc < 2 and (delta - im_acc >= prec - 4): im, im_acc = None, None return re, im, re_acc, im_acc def check_target(expr: 'Expr', result: TMP_RES, prec: int): a = complex_accuracy(result) if a < prec: raise PrecisionExhausted("Failed to distinguish the expression: \n\n%s\n\n" "from zero. Try simplifying the input, using chop=True, or providing " "a higher maxn for evalf" % (expr)) def get_integer_part(expr: 'Expr', no: int, options: OPT_DICT, return_ints=False) -> \ tUnion[TMP_RES, tTuple[int, int]]: """ With no = 1, computes ceiling(expr) With no = -1, computes floor(expr) Note: this function either gives the exact result or signals failure. """ from sympy.functions.elementary.complexes import re, im # The expression is likely less than 2^30 or so assumed_size = 30 result = evalf(expr, assumed_size, options) if result is S.ComplexInfinity: raise ValueError("Cannot get integer part of Complex Infinity") ire, iim, ire_acc, iim_acc = result # We now know the size, so we can calculate how much extra precision # (if any) is needed to get within the nearest integer if ire and iim: gap = max(fastlog(ire) - ire_acc, fastlog(iim) - iim_acc) elif ire: gap = fastlog(ire) - ire_acc elif iim: gap = fastlog(iim) - iim_acc else: # ... or maybe the expression was exactly zero if return_ints: return 0, 0 else: return None, None, None, None margin = 10 if gap >= -margin: prec = margin + assumed_size + gap ire, iim, ire_acc, iim_acc = evalf( expr, prec, options) else: prec = assumed_size # We can now easily find the nearest integer, but to find floor/ceil, we # must also calculate whether the difference to the nearest integer is # positive or negative (which may fail if very close). def calc_part(re_im: 'Expr', nexpr: MPF_TUP): from .add import Add _, _, exponent, _ = nexpr is_int = exponent == 0 nint = int(to_int(nexpr, rnd)) if is_int: # make sure that we had enough precision to distinguish # between nint and the re or im part (re_im) of expr that # was passed to calc_part ire, iim, ire_acc, iim_acc = evalf( re_im - nint, 10, options) # don't need much precision assert not iim size = -fastlog(ire) + 2 # -ve b/c ire is less than 1 if size > prec: ire, iim, ire_acc, iim_acc = evalf( re_im, size, options) assert not iim nexpr = ire nint = int(to_int(nexpr, rnd)) _, _, new_exp, _ = ire is_int = new_exp == 0 if not is_int: # if there are subs and they all contain integer re/im parts # then we can (hopefully) safely substitute them into the # expression s = options.get('subs', False) if s: doit = True # use strict=False with as_int because we take # 2.0 == 2 for v in s.values(): try: as_int(v, strict=False) except ValueError: try: [as_int(i, strict=False) for i in v.as_real_imag()] continue except (ValueError, AttributeError): doit = False break if doit: re_im = re_im.subs(s) re_im = Add(re_im, -nint, evaluate=False) x, _, x_acc, _ = evalf(re_im, 10, options) try: check_target(re_im, (x, None, x_acc, None), 3) except PrecisionExhausted: if not re_im.equals(0): raise PrecisionExhausted x = fzero nint += int(no*(mpf_cmp(x or fzero, fzero) == no)) nint = from_int(nint) return nint, INF re_, im_, re_acc, im_acc = None, None, None, None if ire: re_, re_acc = calc_part(re(expr, evaluate=False), ire) if iim: im_, im_acc = calc_part(im(expr, evaluate=False), iim) if return_ints: return int(to_int(re_ or fzero)), int(to_int(im_ or fzero)) return re_, im_, re_acc, im_acc def evalf_ceiling(expr: 'ceiling', prec: int, options: OPT_DICT) -> TMP_RES: return get_integer_part(expr.args[0], 1, options) def evalf_floor(expr: 'floor', prec: int, options: OPT_DICT) -> TMP_RES: return get_integer_part(expr.args[0], -1, options) def evalf_float(expr: 'Float', prec: int, options: OPT_DICT) -> TMP_RES: return expr._mpf_, None, prec, None def evalf_rational(expr: 'Rational', prec: int, options: OPT_DICT) -> TMP_RES: return from_rational(expr.p, expr.q, prec), None, prec, None def evalf_integer(expr: 'Integer', prec: int, options: OPT_DICT) -> TMP_RES: return from_int(expr.p, prec), None, prec, None #----------------------------------------------------------------------------# # # # Arithmetic operations # # # #----------------------------------------------------------------------------# def add_terms(terms: list, prec: int, target_prec: int) -> \ tTuple[tUnion[MPF_TUP, SCALED_ZERO_TUP, None], Optional[int]]: """ Helper for evalf_add. Adds a list of (mpfval, accuracy) terms. Returns ======= - None, None if there are no non-zero terms; - terms[0] if there is only 1 term; - scaled_zero if the sum of the terms produces a zero by cancellation e.g. mpfs representing 1 and -1 would produce a scaled zero which need special handling since they are not actually zero and they are purposely malformed to ensure that they cannot be used in anything but accuracy calculations; - a tuple that is scaled to target_prec that corresponds to the sum of the terms. The returned mpf tuple will be normalized to target_prec; the input prec is used to define the working precision. XXX explain why this is needed and why one cannot just loop using mpf_add """ terms = [t for t in terms if not iszero(t[0])] if not terms: return None, None elif len(terms) == 1: return terms[0] # see if any argument is NaN or oo and thus warrants a special return special = [] from .numbers import Float for t in terms: arg = Float._new(t[0], 1) if arg is S.NaN or arg.is_infinite: special.append(arg) if special: from .add import Add rv = evalf(Add(*special), prec + 4, {}) return rv[0], rv[2] working_prec = 2*prec sum_man, sum_exp = 0, 0 absolute_err: List[int] = [] for x, accuracy in terms: sign, man, exp, bc = x if sign: man = -man absolute_err.append(bc + exp - accuracy) delta = exp - sum_exp if exp >= sum_exp: # x much larger than existing sum? # first: quick test if ((delta > working_prec) and ((not sum_man) or delta - bitcount(abs(sum_man)) > working_prec)): sum_man = man sum_exp = exp else: sum_man += (man << delta) else: delta = -delta # x much smaller than existing sum? if delta - bc > working_prec: if not sum_man: sum_man, sum_exp = man, exp else: sum_man = (sum_man << delta) + man sum_exp = exp absolute_error = max(absolute_err) if not sum_man: return scaled_zero(absolute_error) if sum_man < 0: sum_sign = 1 sum_man = -sum_man else: sum_sign = 0 sum_bc = bitcount(sum_man) sum_accuracy = sum_exp + sum_bc - absolute_error r = normalize(sum_sign, sum_man, sum_exp, sum_bc, target_prec, rnd), sum_accuracy return r def evalf_add(v: 'Add', prec: int, options: OPT_DICT) -> TMP_RES: res = pure_complex(v) if res: h, c = res re, _, re_acc, _ = evalf(h, prec, options) im, _, im_acc, _ = evalf(c, prec, options) return re, im, re_acc, im_acc oldmaxprec = options.get('maxprec', DEFAULT_MAXPREC) i = 0 target_prec = prec while 1: options['maxprec'] = min(oldmaxprec, 2*prec) terms = [evalf(arg, prec + 10, options) for arg in v.args] n = terms.count(S.ComplexInfinity) if n >= 2: return fnan, None, prec, None re, re_acc = add_terms( [a[0::2] for a in terms if isinstance(a, tuple) and a[0]], prec, target_prec) im, im_acc = add_terms( [a[1::2] for a in terms if isinstance(a, tuple) and a[1]], prec, target_prec) if n == 1: if re in (finf, fninf, fnan) or im in (finf, fninf, fnan): return fnan, None, prec, None return S.ComplexInfinity acc = complex_accuracy((re, im, re_acc, im_acc)) if acc >= target_prec: if options.get('verbose'): print("ADD: wanted", target_prec, "accurate bits, got", re_acc, im_acc) break else: if (prec - target_prec) > options['maxprec']: break prec = prec + max(10 + 2**i, target_prec - acc) i += 1 if options.get('verbose'): print("ADD: restarting with prec", prec) options['maxprec'] = oldmaxprec if iszero(re, scaled=True): re = scaled_zero(re) if iszero(im, scaled=True): im = scaled_zero(im) return re, im, re_acc, im_acc def evalf_mul(v: 'Mul', prec: int, options: OPT_DICT) -> TMP_RES: res = pure_complex(v) if res: # the only pure complex that is a mul is h*I _, h = res im, _, im_acc, _ = evalf(h, prec, options) return None, im, None, im_acc args = list(v.args) # see if any argument is NaN or oo and thus warrants a special return has_zero = False special = [] from .numbers import Float for arg in args: result = evalf(arg, prec, options) if result is S.ComplexInfinity: special.append(result) continue if result[0] is None: if result[1] is None: has_zero = True continue num = Float._new(result[0], 1) if num is S.NaN: return fnan, None, prec, None if num.is_infinite: special.append(num) if special: if has_zero: return fnan, None, prec, None from .mul import Mul return evalf(Mul(*special), prec + 4, {}) if has_zero: return None, None, None, None # With guard digits, multiplication in the real case does not destroy # accuracy. This is also true in the complex case when considering the # total accuracy; however accuracy for the real or imaginary parts # separately may be lower. acc = prec # XXX: big overestimate working_prec = prec + len(args) + 5 # Empty product is 1 start = man, exp, bc = MPZ(1), 0, 1 # First, we multiply all pure real or pure imaginary numbers. # direction tells us that the result should be multiplied by # I**direction; all other numbers get put into complex_factors # to be multiplied out after the first phase. last = len(args) direction = 0 args.append(S.One) complex_factors = [] for i, arg in enumerate(args): if i != last and pure_complex(arg): args[-1] = (args[-1]*arg).expand() continue elif i == last and arg is S.One: continue re, im, re_acc, im_acc = evalf(arg, working_prec, options) if re and im: complex_factors.append((re, im, re_acc, im_acc)) continue elif re: (s, m, e, b), w_acc = re, re_acc elif im: (s, m, e, b), w_acc = im, im_acc direction += 1 else: return None, None, None, None direction += 2*s man *= m exp += e bc += b while bc > 3*working_prec: man >>= working_prec exp += working_prec bc -= working_prec acc = min(acc, w_acc) sign = (direction & 2) >> 1 if not complex_factors: v = normalize(sign, man, exp, bitcount(man), prec, rnd) # multiply by i if direction & 1: return None, v, None, acc else: return v, None, acc, None else: # initialize with the first term if (man, exp, bc) != start: # there was a real part; give it an imaginary part re, im = (sign, man, exp, bitcount(man)), (0, MPZ(0), 0, 0) i0 = 0 else: # there is no real part to start (other than the starting 1) wre, wim, wre_acc, wim_acc = complex_factors[0] acc = min(acc, complex_accuracy((wre, wim, wre_acc, wim_acc))) re = wre im = wim i0 = 1 for wre, wim, wre_acc, wim_acc in complex_factors[i0:]: # acc is the overall accuracy of the product; we aren't # computing exact accuracies of the product. acc = min(acc, complex_accuracy((wre, wim, wre_acc, wim_acc))) use_prec = working_prec A = mpf_mul(re, wre, use_prec) B = mpf_mul(mpf_neg(im), wim, use_prec) C = mpf_mul(re, wim, use_prec) D = mpf_mul(im, wre, use_prec) re = mpf_add(A, B, use_prec) im = mpf_add(C, D, use_prec) if options.get('verbose'): print("MUL: wanted", prec, "accurate bits, got", acc) # multiply by I if direction & 1: re, im = mpf_neg(im), re return re, im, acc, acc def evalf_pow(v: 'Pow', prec: int, options) -> TMP_RES: target_prec = prec base, exp = v.args # We handle x**n separately. This has two purposes: 1) it is much # faster, because we avoid calling evalf on the exponent, and 2) it # allows better handling of real/imaginary parts that are exactly zero if exp.is_Integer: p: int = exp.p # type: ignore # Exact if not p: return fone, None, prec, None # Exponentiation by p magnifies relative error by |p|, so the # base must be evaluated with increased precision if p is large prec += int(math.log(abs(p), 2)) result = evalf(base, prec + 5, options) if result is S.ComplexInfinity: if p < 0: return None, None, None, None return result re, im, re_acc, im_acc = result # Real to integer power if re and not im: return mpf_pow_int(re, p, target_prec), None, target_prec, None # (x*I)**n = I**n * x**n if im and not re: z = mpf_pow_int(im, p, target_prec) case = p % 4 if case == 0: return z, None, target_prec, None if case == 1: return None, z, None, target_prec if case == 2: return mpf_neg(z), None, target_prec, None if case == 3: return None, mpf_neg(z), None, target_prec # Zero raised to an integer power if not re: if p < 0: return S.ComplexInfinity return None, None, None, None # General complex number to arbitrary integer power re, im = libmp.mpc_pow_int((re, im), p, prec) # Assumes full accuracy in input return finalize_complex(re, im, target_prec) result = evalf(base, prec + 5, options) if result is S.ComplexInfinity: if exp.is_Rational: if exp < 0: return None, None, None, None return result raise NotImplementedError # Pure square root if exp is S.Half: xre, xim, _, _ = result # General complex square root if xim: re, im = libmp.mpc_sqrt((xre or fzero, xim), prec) return finalize_complex(re, im, prec) if not xre: return None, None, None, None # Square root of a negative real number if mpf_lt(xre, fzero): return None, mpf_sqrt(mpf_neg(xre), prec), None, prec # Positive square root return mpf_sqrt(xre, prec), None, prec, None # We first evaluate the exponent to find its magnitude # This determines the working precision that must be used prec += 10 result = evalf(exp, prec, options) if result is S.ComplexInfinity: return fnan, None, prec, None yre, yim, _, _ = result # Special cases: x**0 if not (yre or yim): return fone, None, prec, None ysize = fastlog(yre) # Restart if too big # XXX: prec + ysize might exceed maxprec if ysize > 5: prec += ysize yre, yim, _, _ = evalf(exp, prec, options) # Pure exponential function; no need to evalf the base if base is S.Exp1: if yim: re, im = libmp.mpc_exp((yre or fzero, yim), prec) return finalize_complex(re, im, target_prec) return mpf_exp(yre, target_prec), None, target_prec, None xre, xim, _, _ = evalf(base, prec + 5, options) # 0**y if not (xre or xim): if yim: return fnan, None, prec, None if yre[0] == 1: # y < 0 return S.ComplexInfinity return None, None, None, None # (real ** complex) or (complex ** complex) if yim: re, im = libmp.mpc_pow( (xre or fzero, xim or fzero), (yre or fzero, yim), target_prec) return finalize_complex(re, im, target_prec) # complex ** real if xim: re, im = libmp.mpc_pow_mpf((xre or fzero, xim), yre, target_prec) return finalize_complex(re, im, target_prec) # negative ** real elif mpf_lt(xre, fzero): re, im = libmp.mpc_pow_mpf((xre, fzero), yre, target_prec) return finalize_complex(re, im, target_prec) # positive ** real else: return mpf_pow(xre, yre, target_prec), None, target_prec, None #----------------------------------------------------------------------------# # # # Special functions # # # #----------------------------------------------------------------------------# def evalf_exp(expr: 'exp', prec: int, options: OPT_DICT) -> TMP_RES: from .power import Pow return evalf_pow(Pow(S.Exp1, expr.exp, evaluate=False), prec, options) def evalf_trig(v: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES: """ This function handles sin and cos of complex arguments. TODO: should also handle tan of complex arguments. """ from sympy.functions.elementary.trigonometric import cos, sin if isinstance(v, cos): func = mpf_cos elif isinstance(v, sin): func = mpf_sin else: raise NotImplementedError arg = v.args[0] # 20 extra bits is possibly overkill. It does make the need # to restart very unlikely xprec = prec + 20 re, im, re_acc, im_acc = evalf(arg, xprec, options) if im: if 'subs' in options: v = v.subs(options['subs']) return evalf(v._eval_evalf(prec), prec, options) if not re: if isinstance(v, cos): return fone, None, prec, None elif isinstance(v, sin): return None, None, None, None else: raise NotImplementedError # For trigonometric functions, we are interested in the # fixed-point (absolute) accuracy of the argument. xsize = fastlog(re) # Magnitude <= 1.0. OK to compute directly, because there is no # danger of hitting the first root of cos (with sin, magnitude # <= 2.0 would actually be ok) if xsize < 1: return func(re, prec, rnd), None, prec, None # Very large if xsize >= 10: xprec = prec + xsize re, im, re_acc, im_acc = evalf(arg, xprec, options) # Need to repeat in case the argument is very close to a # multiple of pi (or pi/2), hitting close to a root while 1: y = func(re, prec, rnd) ysize = fastlog(y) gap = -ysize accuracy = (xprec - xsize) - gap if accuracy < prec: if options.get('verbose'): print("SIN/COS", accuracy, "wanted", prec, "gap", gap) print(to_str(y, 10)) if xprec > options.get('maxprec', DEFAULT_MAXPREC): return y, None, accuracy, None xprec += gap re, im, re_acc, im_acc = evalf(arg, xprec, options) continue else: return y, None, prec, None def evalf_log(expr: 'log', prec: int, options: OPT_DICT) -> TMP_RES: if len(expr.args)>1: expr = expr.doit() return evalf(expr, prec, options) arg = expr.args[0] workprec = prec + 10 result = evalf(arg, workprec, options) if result is S.ComplexInfinity: return result xre, xim, xacc, _ = result # evalf can return NoneTypes if chop=True # issue 18516, 19623 if xre is xim is None: # Dear reviewer, I do not know what -inf is; # it looks to be (1, 0, -789, -3) # but I'm not sure in general, # so we just let mpmath figure # it out by taking log of 0 directly. # It would be better to return -inf instead. xre = fzero if xim: from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import log # XXX: use get_abs etc instead re = evalf_log( log(Abs(arg, evaluate=False), evaluate=False), prec, options) im = mpf_atan2(xim, xre or fzero, prec) return re[0], im, re[2], prec imaginary_term = (mpf_cmp(xre, fzero) < 0) re = mpf_log(mpf_abs(xre), prec, rnd) size = fastlog(re) if prec - size > workprec and re != fzero: from .add import Add # We actually need to compute 1+x accurately, not x add = Add(S.NegativeOne, arg, evaluate=False) xre, xim, _, _ = evalf_add(add, prec, options) prec2 = workprec - fastlog(xre) # xre is now x - 1 so we add 1 back here to calculate x re = mpf_log(mpf_abs(mpf_add(xre, fone, prec2)), prec, rnd) re_acc = prec if imaginary_term: return re, mpf_pi(prec), re_acc, prec else: return re, None, re_acc, None def evalf_atan(v: 'atan', prec: int, options: OPT_DICT) -> TMP_RES: arg = v.args[0] xre, xim, reacc, imacc = evalf(arg, prec + 5, options) if xre is xim is None: return (None,)*4 if xim: raise NotImplementedError return mpf_atan(xre, prec, rnd), None, prec, None def evalf_subs(prec: int, subs: dict) -> dict: """ Change all Float entries in `subs` to have precision prec. """ newsubs = {} for a, b in subs.items(): b = S(b) if b.is_Float: b = b._eval_evalf(prec) newsubs[a] = b return newsubs def evalf_piecewise(expr: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES: from .numbers import Float, Integer if 'subs' in options: expr = expr.subs(evalf_subs(prec, options['subs'])) newopts = options.copy() del newopts['subs'] if hasattr(expr, 'func'): return evalf(expr, prec, newopts) if isinstance(expr, float): return evalf(Float(expr), prec, newopts) if isinstance(expr, int): return evalf(Integer(expr), prec, newopts) # We still have undefined symbols raise NotImplementedError def evalf_alg_num(a: 'AlgebraicNumber', prec: int, options: OPT_DICT) -> TMP_RES: return evalf(a.to_root(), prec, options) #----------------------------------------------------------------------------# # # # High-level operations # # # #----------------------------------------------------------------------------# def as_mpmath(x: Any, prec: int, options: OPT_DICT) -> tUnion[mpc, mpf]: from .numbers import Infinity, NegativeInfinity, Zero x = sympify(x) if isinstance(x, Zero) or x == 0.0: return mpf(0) if isinstance(x, Infinity): return mpf('inf') if isinstance(x, NegativeInfinity): return mpf('-inf') # XXX result = evalf(x, prec, options) return quad_to_mpmath(result) def do_integral(expr: 'Integral', prec: int, options: OPT_DICT) -> TMP_RES: func = expr.args[0] x, xlow, xhigh = expr.args[1] if xlow == xhigh: xlow = xhigh = 0 elif x not in func.free_symbols: # only the difference in limits matters in this case # so if there is a symbol in common that will cancel # out when taking the difference, then use that # difference if xhigh.free_symbols & xlow.free_symbols: diff = xhigh - xlow if diff.is_number: xlow, xhigh = 0, diff oldmaxprec = options.get('maxprec', DEFAULT_MAXPREC) options['maxprec'] = min(oldmaxprec, 2*prec) with workprec(prec + 5): xlow = as_mpmath(xlow, prec + 15, options) xhigh = as_mpmath(xhigh, prec + 15, options) # Integration is like summation, and we can phone home from # the integrand function to update accuracy summation style # Note that this accuracy is inaccurate, since it fails # to account for the variable quadrature weights, # but it is better than nothing from sympy.functions.elementary.trigonometric import cos, sin from .symbol import Wild have_part = [False, False] max_real_term: tUnion[float, int] = MINUS_INF max_imag_term: tUnion[float, int] = MINUS_INF def f(t: 'Expr') -> tUnion[mpc, mpf]: nonlocal max_real_term, max_imag_term re, im, re_acc, im_acc = evalf(func, mp.prec, {'subs': {x: t}}) have_part[0] = re or have_part[0] have_part[1] = im or have_part[1] max_real_term = max(max_real_term, fastlog(re)) max_imag_term = max(max_imag_term, fastlog(im)) if im: return mpc(re or fzero, im) return mpf(re or fzero) if options.get('quad') == 'osc': A = Wild('A', exclude=[x]) B = Wild('B', exclude=[x]) D = Wild('D') m = func.match(cos(A*x + B)*D) if not m: m = func.match(sin(A*x + B)*D) if not m: raise ValueError("An integrand of the form sin(A*x+B)*f(x) " "or cos(A*x+B)*f(x) is required for oscillatory quadrature") period = as_mpmath(2*S.Pi/m[A], prec + 15, options) result = quadosc(f, [xlow, xhigh], period=period) # XXX: quadosc does not do error detection yet quadrature_error = MINUS_INF else: result, quadrature_err = quadts(f, [xlow, xhigh], error=1) quadrature_error = fastlog(quadrature_err._mpf_) options['maxprec'] = oldmaxprec if have_part[0]: re: Optional[MPF_TUP] = result.real._mpf_ re_acc: Optional[int] if re == fzero: re_s, re_acc = scaled_zero(int(-max(prec, max_real_term, quadrature_error))) re = scaled_zero(re_s) # handled ok in evalf_integral else: re_acc = int(-max(max_real_term - fastlog(re) - prec, quadrature_error)) else: re, re_acc = None, None if have_part[1]: im: Optional[MPF_TUP] = result.imag._mpf_ im_acc: Optional[int] if im == fzero: im_s, im_acc = scaled_zero(int(-max(prec, max_imag_term, quadrature_error))) im = scaled_zero(im_s) # handled ok in evalf_integral else: im_acc = int(-max(max_imag_term - fastlog(im) - prec, quadrature_error)) else: im, im_acc = None, None result = re, im, re_acc, im_acc return result def evalf_integral(expr: 'Integral', prec: int, options: OPT_DICT) -> TMP_RES: limits = expr.limits if len(limits) != 1 or len(limits[0]) != 3: raise NotImplementedError workprec = prec i = 0 maxprec = options.get('maxprec', INF) while 1: result = do_integral(expr, workprec, options) accuracy = complex_accuracy(result) if accuracy >= prec: # achieved desired precision break if workprec >= maxprec: # can't increase accuracy any more break if accuracy == -1: # maybe the answer really is zero and maybe we just haven't increased # the precision enough. So increase by doubling to not take too long # to get to maxprec. workprec *= 2 else: workprec += max(prec, 2**i) workprec = min(workprec, maxprec) i += 1 return result def check_convergence(numer: 'Expr', denom: 'Expr', n: 'Symbol') -> tTuple[int, Any, Any]: """ Returns ======= (h, g, p) where -- h is: > 0 for convergence of rate 1/factorial(n)**h < 0 for divergence of rate factorial(n)**(-h) = 0 for geometric or polynomial convergence or divergence -- abs(g) is: > 1 for geometric convergence of rate 1/h**n < 1 for geometric divergence of rate h**n = 1 for polynomial convergence or divergence (g < 0 indicates an alternating series) -- p is: > 1 for polynomial convergence of rate 1/n**h <= 1 for polynomial divergence of rate n**(-h) """ from sympy.polys.polytools import Poly npol = Poly(numer, n) dpol = Poly(denom, n) p = npol.degree() q = dpol.degree() rate = q - p if rate: return rate, None, None constant = dpol.LC() / npol.LC() from .numbers import equal_valued if not equal_valued(abs(constant), 1): return rate, constant, None if npol.degree() == dpol.degree() == 0: return rate, constant, 0 pc = npol.all_coeffs()[1] qc = dpol.all_coeffs()[1] return rate, constant, (qc - pc)/dpol.LC() def hypsum(expr: 'Expr', n: 'Symbol', start: int, prec: int) -> mpf: """ Sum a rapidly convergent infinite hypergeometric series with given general term, e.g. e = hypsum(1/factorial(n), n). The quotient between successive terms must be a quotient of integer polynomials. """ from .numbers import Float, equal_valued from sympy.simplify.simplify import hypersimp if prec == float('inf'): raise NotImplementedError('does not support inf prec') if start: expr = expr.subs(n, n + start) hs = hypersimp(expr, n) if hs is None: raise NotImplementedError("a hypergeometric series is required") num, den = hs.as_numer_denom() func1 = lambdify(n, num) func2 = lambdify(n, den) h, g, p = check_convergence(num, den, n) if h < 0: raise ValueError("Sum diverges like (n!)^%i" % (-h)) term = expr.subs(n, 0) if not term.is_Rational: raise NotImplementedError("Non rational term functionality is not implemented.") # Direct summation if geometric or faster if h > 0 or (h == 0 and abs(g) > 1): term = (MPZ(term.p) << prec) // term.q s = term k = 1 while abs(term) > 5: term *= MPZ(func1(k - 1)) term //= MPZ(func2(k - 1)) s += term k += 1 return from_man_exp(s, -prec) else: alt = g < 0 if abs(g) < 1: raise ValueError("Sum diverges like (%i)^n" % abs(1/g)) if p < 1 or (equal_valued(p, 1) and not alt): raise ValueError("Sum diverges like n^%i" % (-p)) # We have polynomial convergence: use Richardson extrapolation vold = None ndig = prec_to_dps(prec) while True: # Need to use at least quad precision because a lot of cancellation # might occur in the extrapolation process; we check the answer to # make sure that the desired precision has been reached, too. prec2 = 4*prec term0 = (MPZ(term.p) << prec2) // term.q def summand(k, _term=[term0]): if k: k = int(k) _term[0] *= MPZ(func1(k - 1)) _term[0] //= MPZ(func2(k - 1)) return make_mpf(from_man_exp(_term[0], -prec2)) with workprec(prec): v = nsum(summand, [0, mpmath_inf], method='richardson') vf = Float(v, ndig) if vold is not None and vold == vf: break prec += prec # double precision each time vold = vf return v._mpf_ def evalf_prod(expr: 'Product', prec: int, options: OPT_DICT) -> TMP_RES: if all((l[1] - l[2]).is_Integer for l in expr.limits): result = evalf(expr.doit(), prec=prec, options=options) else: from sympy.concrete.summations import Sum result = evalf(expr.rewrite(Sum), prec=prec, options=options) return result def evalf_sum(expr: 'Sum', prec: int, options: OPT_DICT) -> TMP_RES: from .numbers import Float if 'subs' in options: expr = expr.subs(options['subs']) func = expr.function limits = expr.limits if len(limits) != 1 or len(limits[0]) != 3: raise NotImplementedError if func.is_zero: return None, None, prec, None prec2 = prec + 10 try: n, a, b = limits[0] if b is not S.Infinity or a is S.NegativeInfinity or a != int(a): raise NotImplementedError # Use fast hypergeometric summation if possible v = hypsum(func, n, int(a), prec2) delta = prec - fastlog(v) if fastlog(v) < -10: v = hypsum(func, n, int(a), delta) return v, None, min(prec, delta), None except NotImplementedError: # Euler-Maclaurin summation for general series eps = Float(2.0)**(-prec) for i in range(1, 5): m = n = 2**i * prec s, err = expr.euler_maclaurin(m=m, n=n, eps=eps, eval_integral=False) err = err.evalf() if err is S.NaN: raise NotImplementedError if err <= eps: break err = fastlog(evalf(abs(err), 20, options)[0]) re, im, re_acc, im_acc = evalf(s, prec2, options) if re_acc is None: re_acc = -err if im_acc is None: im_acc = -err return re, im, re_acc, im_acc #----------------------------------------------------------------------------# # # # Symbolic interface # # # #----------------------------------------------------------------------------# def evalf_symbol(x: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES: val = options['subs'][x] if isinstance(val, mpf): if not val: return None, None, None, None return val._mpf_, None, prec, None else: if '_cache' not in options: options['_cache'] = {} cache = options['_cache'] cached, cached_prec = cache.get(x, (None, MINUS_INF)) if cached_prec >= prec: return cached v = evalf(sympify(val), prec, options) cache[x] = (v, prec) return v evalf_table: tDict[Type['Expr'], Callable[['Expr', int, OPT_DICT], TMP_RES]] = {} def _create_evalf_table(): global evalf_table from sympy.concrete.products import Product from sympy.concrete.summations import Sum from .add import Add from .mul import Mul from .numbers import Exp1, Float, Half, ImaginaryUnit, Integer, NaN, NegativeOne, One, Pi, Rational, \ Zero, ComplexInfinity, AlgebraicNumber from .power import Pow from .symbol import Dummy, Symbol from sympy.functions.elementary.complexes import Abs, im, re from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.integers import ceiling, floor from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import atan, cos, sin from sympy.integrals.integrals import Integral evalf_table = { Symbol: evalf_symbol, Dummy: evalf_symbol, Float: evalf_float, Rational: evalf_rational, Integer: evalf_integer, Zero: lambda x, prec, options: (None, None, prec, None), One: lambda x, prec, options: (fone, None, prec, None), Half: lambda x, prec, options: (fhalf, None, prec, None), Pi: lambda x, prec, options: (mpf_pi(prec), None, prec, None), Exp1: lambda x, prec, options: (mpf_e(prec), None, prec, None), ImaginaryUnit: lambda x, prec, options: (None, fone, None, prec), NegativeOne: lambda x, prec, options: (fnone, None, prec, None), ComplexInfinity: lambda x, prec, options: S.ComplexInfinity, NaN: lambda x, prec, options: (fnan, None, prec, None), exp: evalf_exp, cos: evalf_trig, sin: evalf_trig, Add: evalf_add, Mul: evalf_mul, Pow: evalf_pow, log: evalf_log, atan: evalf_atan, Abs: evalf_abs, re: evalf_re, im: evalf_im, floor: evalf_floor, ceiling: evalf_ceiling, Integral: evalf_integral, Sum: evalf_sum, Product: evalf_prod, Piecewise: evalf_piecewise, AlgebraicNumber: evalf_alg_num, } def evalf(x: 'Expr', prec: int, options: OPT_DICT) -> TMP_RES: """ Evaluate the ``Expr`` instance, ``x`` to a binary precision of ``prec``. This function is supposed to be used internally. Parameters ========== x : Expr The formula to evaluate to a float. prec : int The binary precision that the output should have. options : dict A dictionary with the same entries as ``EvalfMixin.evalf`` and in addition, ``maxprec`` which is the maximum working precision. Returns ======= An optional tuple, ``(re, im, re_acc, im_acc)`` which are the real, imaginary, real accuracy and imaginary accuracy respectively. ``re`` is an mpf value tuple and so is ``im``. ``re_acc`` and ``im_acc`` are ints. NB: all these return values can be ``None``. If all values are ``None``, then that represents 0. Note that 0 is also represented as ``fzero = (0, 0, 0, 0)``. """ from sympy.functions.elementary.complexes import re as re_, im as im_ try: rf = evalf_table[type(x)] r = rf(x, prec, options) except KeyError: # Fall back to ordinary evalf if possible if 'subs' in options: x = x.subs(evalf_subs(prec, options['subs'])) xe = x._eval_evalf(prec) if xe is None: raise NotImplementedError as_real_imag = getattr(xe, "as_real_imag", None) if as_real_imag is None: raise NotImplementedError # e.g. FiniteSet(-1.0, 1.0).evalf() re, im = as_real_imag() if re.has(re_) or im.has(im_): raise NotImplementedError if re == 0.0: re = None reprec = None elif re.is_number: re = re._to_mpmath(prec, allow_ints=False)._mpf_ reprec = prec else: raise NotImplementedError if im == 0.0: im = None imprec = None elif im.is_number: im = im._to_mpmath(prec, allow_ints=False)._mpf_ imprec = prec else: raise NotImplementedError r = re, im, reprec, imprec if options.get("verbose"): print("### input", x) print("### output", to_str(r[0] or fzero, 50) if isinstance(r, tuple) else r) print("### raw", r) # r[0], r[2] print() chop = options.get('chop', False) if chop: if chop is True: chop_prec = prec else: # convert (approximately) from given tolerance; # the formula here will will make 1e-i rounds to 0 for # i in the range +/-27 while 2e-i will not be chopped chop_prec = int(round(-3.321*math.log10(chop) + 2.5)) if chop_prec == 3: chop_prec -= 1 r = chop_parts(r, chop_prec) if options.get("strict"): check_target(x, r, prec) return r def quad_to_mpmath(q): """Turn the quad returned by ``evalf`` into an ``mpf`` or ``mpc``. """ if q is S.ComplexInfinity: raise NotImplementedError re, im, _, _ = q if im: if not re: re = fzero return make_mpc((re, im)) elif re: return make_mpf(re) else: return make_mpf(fzero) class EvalfMixin: """Mixin class adding evalf capability.""" __slots__ = () # type: tTuple[str, ...] def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False): """ Evaluate the given formula to an accuracy of *n* digits. Parameters ========== subs : dict, optional Substitute numerical values for symbols, e.g. ``subs={x:3, y:1+pi}``. The substitutions must be given as a dictionary. maxn : int, optional Allow a maximum temporary working precision of maxn digits. chop : bool or number, optional Specifies how to replace tiny real or imaginary parts in subresults by exact zeros. When ``True`` the chop value defaults to standard precision. Otherwise the chop value is used to determine the magnitude of "small" for purposes of chopping. >>> from sympy import N >>> x = 1e-4 >>> N(x, chop=True) 0.000100000000000000 >>> N(x, chop=1e-5) 0.000100000000000000 >>> N(x, chop=1e-4) 0 strict : bool, optional Raise ``PrecisionExhausted`` if any subresult fails to evaluate to full accuracy, given the available maxprec. quad : str, optional Choose algorithm for numerical quadrature. By default, tanh-sinh quadrature is used. For oscillatory integrals on an infinite interval, try ``quad='osc'``. verbose : bool, optional Print debug information. Notes ===== When Floats are naively substituted into an expression, precision errors may adversely affect the result. For example, adding 1e16 (a Float) to 1 will truncate to 1e16; if 1e16 is then subtracted, the result will be 0. That is exactly what happens in the following: >>> from sympy.abc import x, y, z >>> values = {x: 1e16, y: 1, z: 1e16} >>> (x + y - z).subs(values) 0 Using the subs argument for evalf is the accurate way to evaluate such an expression: >>> (x + y - z).evalf(subs=values) 1.00000000000000 """ from .numbers import Float, Number n = n if n is not None else 15 if subs and is_sequence(subs): raise TypeError('subs must be given as a dictionary') # for sake of sage that doesn't like evalf(1) if n == 1 and isinstance(self, Number): from .expr import _mag rv = self.evalf(2, subs, maxn, chop, strict, quad, verbose) m = _mag(rv) rv = rv.round(1 - m) return rv if not evalf_table: _create_evalf_table() prec = dps_to_prec(n) options = {'maxprec': max(prec, int(maxn*LG10)), 'chop': chop, 'strict': strict, 'verbose': verbose} if subs is not None: options['subs'] = subs if quad is not None: options['quad'] = quad try: result = evalf(self, prec + 4, options) except NotImplementedError: # Fall back to the ordinary evalf if hasattr(self, 'subs') and subs is not None: # issue 20291 v = self.subs(subs)._eval_evalf(prec) else: v = self._eval_evalf(prec) if v is None: return self elif not v.is_number: return v try: # If the result is numerical, normalize it result = evalf(v, prec, options) except NotImplementedError: # Probably contains symbols or unknown functions return v if result is S.ComplexInfinity: return result re, im, re_acc, im_acc = result if re is S.NaN or im is S.NaN: return S.NaN if re: p = max(min(prec, re_acc), 1) re = Float._new(re, p) else: re = S.Zero if im: p = max(min(prec, im_acc), 1) im = Float._new(im, p) return re + im*S.ImaginaryUnit else: return re n = evalf def _evalf(self, prec): """Helper for evalf. Does the same thing but takes binary precision""" r = self._eval_evalf(prec) if r is None: r = self return r def _eval_evalf(self, prec): return def _to_mpmath(self, prec, allow_ints=True): # mpmath functions accept ints as input errmsg = "cannot convert to mpmath number" if allow_ints and self.is_Integer: return self.p if hasattr(self, '_as_mpf_val'): return make_mpf(self._as_mpf_val(prec)) try: result = evalf(self, prec, {}) return quad_to_mpmath(result) except NotImplementedError: v = self._eval_evalf(prec) if v is None: raise ValueError(errmsg) if v.is_Float: return make_mpf(v._mpf_) # Number + Number*I is also fine re, im = v.as_real_imag() if allow_ints and re.is_Integer: re = from_int(re.p) elif re.is_Float: re = re._mpf_ else: raise ValueError(errmsg) if allow_ints and im.is_Integer: im = from_int(im.p) elif im.is_Float: im = im._mpf_ else: raise ValueError(errmsg) return make_mpc((re, im)) def N(x, n=15, **options): r""" Calls x.evalf(n, \*\*options). Explanations ============ Both .n() and N() are equivalent to .evalf(); use the one that you like better. See also the docstring of .evalf() for information on the options. Examples ======== >>> from sympy import Sum, oo, N >>> from sympy.abc import k >>> Sum(1/k**k, (k, 1, oo)) Sum(k**(-k), (k, 1, oo)) >>> N(_, 4) 1.291 """ # by using rational=True, any evaluation of a string # will be done using exact values for the Floats return sympify(x, rational=True).evalf(n, **options) def _evalf_with_bounded_error(x: 'Expr', eps: 'Optional[Expr]' = None, m: int = 0, options: Optional[OPT_DICT] = None) -> TMP_RES: """ Evaluate *x* to within a bounded absolute error. Parameters ========== x : Expr The quantity to be evaluated. eps : Expr, None, optional (default=None) Positive real upper bound on the acceptable error. m : int, optional (default=0) If *eps* is None, then use 2**(-m) as the upper bound on the error. options: OPT_DICT As in the ``evalf`` function. Returns ======= A tuple ``(re, im, re_acc, im_acc)``, as returned by ``evalf``. See Also ======== evalf """ if eps is not None: if not (eps.is_Rational or eps.is_Float) or not eps > 0: raise ValueError("eps must be positive") r, _, _, _ = evalf(1/eps, 1, {}) m = fastlog(r) c, d, _, _ = evalf(x, 1, {}) # Note: If x = a + b*I, then |a| <= 2|c| and |b| <= 2|d|, with equality # only in the zero case. # If a is non-zero, then |c| = 2**nc for some integer nc, and c has # bitcount 1. Therefore 2**fastlog(c) = 2**(nc+1) = 2|c| is an upper bound # on |a|. Likewise for b and d. nr, ni = fastlog(c), fastlog(d) n = max(nr, ni) + 1 # If x is 0, then n is MINUS_INF, and p will be 1. Otherwise, # n - 1 bits get us past the integer parts of a and b, and +1 accounts for # the factor of <= sqrt(2) that is |x|/max(|a|, |b|). p = max(1, m + n + 1) options = options or {} return evalf(x, p, options)
0321bb9206a7c95d23571f9a34111416882a44b1d0aaa167f315376527c9a1a3
""" Caching facility for SymPy """ from importlib import import_module from typing import Callable class _cache(list): """ List of cached functions """ def print_cache(self): """print cache info""" for item in self: name = item.__name__ myfunc = item while hasattr(myfunc, '__wrapped__'): if hasattr(myfunc, 'cache_info'): info = myfunc.cache_info() break else: myfunc = myfunc.__wrapped__ else: info = None print(name, info) def clear_cache(self): """clear cache content""" for item in self: myfunc = item while hasattr(myfunc, '__wrapped__'): if hasattr(myfunc, 'cache_clear'): myfunc.cache_clear() break else: myfunc = myfunc.__wrapped__ # global cache registry: CACHE = _cache() # make clear and print methods available print_cache = CACHE.print_cache clear_cache = CACHE.clear_cache from functools import lru_cache, wraps def __cacheit(maxsize): """caching decorator. important: the result of cached function must be *immutable* Examples ======== >>> from sympy import cacheit >>> @cacheit ... def f(a, b): ... return a+b >>> @cacheit ... def f(a, b): # noqa: F811 ... return [a, b] # <-- WRONG, returns mutable object to force cacheit to check returned results mutability and consistency, set environment variable SYMPY_USE_CACHE to 'debug' """ def func_wrapper(func): cfunc = lru_cache(maxsize, typed=True)(func) @wraps(func) def wrapper(*args, **kwargs): try: retval = cfunc(*args, **kwargs) except TypeError as e: if not e.args or not e.args[0].startswith('unhashable type:'): raise retval = func(*args, **kwargs) return retval wrapper.cache_info = cfunc.cache_info wrapper.cache_clear = cfunc.cache_clear CACHE.append(wrapper) return wrapper return func_wrapper ######################################## def __cacheit_nocache(func): return func def __cacheit_debug(maxsize): """cacheit + code to check cache consistency""" def func_wrapper(func): cfunc = __cacheit(maxsize)(func) @wraps(func) def wrapper(*args, **kw_args): # always call function itself and compare it with cached version r1 = func(*args, **kw_args) r2 = cfunc(*args, **kw_args) # try to see if the result is immutable # # this works because: # # hash([1,2,3]) -> raise TypeError # hash({'a':1, 'b':2}) -> raise TypeError # hash((1,[2,3])) -> raise TypeError # # hash((1,2,3)) -> just computes the hash hash(r1), hash(r2) # also see if returned values are the same if r1 != r2: raise RuntimeError("Returned values are not the same") return r1 return wrapper return func_wrapper def _getenv(key, default=None): from os import getenv return getenv(key, default) # SYMPY_USE_CACHE=yes/no/debug USE_CACHE = _getenv('SYMPY_USE_CACHE', 'yes').lower() # SYMPY_CACHE_SIZE=some_integer/None # special cases : # SYMPY_CACHE_SIZE=0 -> No caching # SYMPY_CACHE_SIZE=None -> Unbounded caching scs = _getenv('SYMPY_CACHE_SIZE', '1000') if scs.lower() == 'none': SYMPY_CACHE_SIZE = None else: try: SYMPY_CACHE_SIZE = int(scs) except ValueError: raise RuntimeError( 'SYMPY_CACHE_SIZE must be a valid integer or None. ' + \ 'Got: %s' % SYMPY_CACHE_SIZE) if USE_CACHE == 'no': cacheit = __cacheit_nocache elif USE_CACHE == 'yes': cacheit = __cacheit(SYMPY_CACHE_SIZE) elif USE_CACHE == 'debug': cacheit = __cacheit_debug(SYMPY_CACHE_SIZE) # a lot slower else: raise RuntimeError( 'unrecognized value for SYMPY_USE_CACHE: %s' % USE_CACHE) def cached_property(func): '''Decorator to cache property method''' attrname = '__' + func.__name__ _cached_property_sentinel = object() def propfunc(self): val = getattr(self, attrname, _cached_property_sentinel) if val is _cached_property_sentinel: val = func(self) setattr(self, attrname, val) return val return property(propfunc) def lazy_function(module : str, name : str) -> Callable: """Create a lazy proxy for a function in a module. The module containing the function is not imported until the function is used. """ func = None def _get_function(): nonlocal func if func is None: func = getattr(import_module(module), name) return func # The metaclass is needed so that help() shows the docstring class LazyFunctionMeta(type): @property def __doc__(self): docstring = _get_function().__doc__ docstring += f"\n\nNote: this is a {self.__class__.__name__} wrapper of '{module}.{name}'" return docstring class LazyFunction(metaclass=LazyFunctionMeta): def __call__(self, *args, **kwargs): # inline get of function for performance gh-23832 nonlocal func if func is None: func = getattr(import_module(module), name) return func(*args, **kwargs) @property def __doc__(self): docstring = _get_function().__doc__ docstring += f"\n\nNote: this is a {self.__class__.__name__} wrapper of '{module}.{name}'" return docstring def __str__(self): return _get_function().__str__() def __repr__(self): return f"<{__class__.__name__} object at 0x{id(self):x}>: wrapping '{module}.{name}'" return LazyFunction()
89ceae48d22dcf92602fc0f1f13f3b81c9e9886c0ec6f7fa15a4158084565a8a
"""Module for SymPy containers (SymPy objects that store other SymPy objects) The containers implemented in this module are subclassed to Basic. They are supposed to work seamlessly within the SymPy framework. """ from collections import OrderedDict from collections.abc import MutableSet from typing import Any, Callable from .basic import Basic from .sorting import default_sort_key, ordered from .sympify import _sympify, sympify, _sympy_converter, SympifyError from sympy.core.kind import Kind from sympy.utilities.iterables import iterable from sympy.utilities.misc import as_int class Tuple(Basic): """ Wrapper around the builtin tuple object. Explanation =========== The Tuple is a subclass of Basic, so that it works well in the SymPy framework. The wrapped tuple is available as self.args, but you can also access elements or slices with [:] syntax. Parameters ========== sympify : bool If ``False``, ``sympify`` is not called on ``args``. This can be used for speedups for very large tuples where the elements are known to already be SymPy objects. Examples ======== >>> from sympy import Tuple, symbols >>> a, b, c, d = symbols('a b c d') >>> Tuple(a, b, c)[1:] (b, c) >>> Tuple(a, b, c).subs(a, d) (d, b, c) """ def __new__(cls, *args, **kwargs): if kwargs.get('sympify', True): args = (sympify(arg) for arg in args) obj = Basic.__new__(cls, *args) return obj def __getitem__(self, i): if isinstance(i, slice): indices = i.indices(len(self)) return Tuple(*(self.args[j] for j in range(*indices))) return self.args[i] def __len__(self): return len(self.args) def __contains__(self, item): return item in self.args def __iter__(self): return iter(self.args) def __add__(self, other): if isinstance(other, Tuple): return Tuple(*(self.args + other.args)) elif isinstance(other, tuple): return Tuple(*(self.args + other)) else: return NotImplemented def __radd__(self, other): if isinstance(other, Tuple): return Tuple(*(other.args + self.args)) elif isinstance(other, tuple): return Tuple(*(other + self.args)) else: return NotImplemented def __mul__(self, other): try: n = as_int(other) except ValueError: raise TypeError("Can't multiply sequence by non-integer of type '%s'" % type(other)) return self.func(*(self.args*n)) __rmul__ = __mul__ def __eq__(self, other): if isinstance(other, Basic): return super().__eq__(other) return self.args == other def __ne__(self, other): if isinstance(other, Basic): return super().__ne__(other) return self.args != other def __hash__(self): return hash(self.args) def _to_mpmath(self, prec): return tuple(a._to_mpmath(prec) for a in self.args) def __lt__(self, other): return _sympify(self.args < other.args) def __le__(self, other): return _sympify(self.args <= other.args) # XXX: Basic defines count() as something different, so we can't # redefine it here. Originally this lead to cse() test failure. def tuple_count(self, value) -> int: """Return number of occurrences of value.""" return self.args.count(value) def index(self, value, start=None, stop=None): """Searches and returns the first index of the value.""" # XXX: One would expect: # # return self.args.index(value, start, stop) # # here. Any trouble with that? Yes: # # >>> (1,).index(1, None, None) # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # TypeError: slice indices must be integers or None or have an __index__ method # # See: http://bugs.python.org/issue13340 if start is None and stop is None: return self.args.index(value) elif stop is None: return self.args.index(value, start) else: return self.args.index(value, start, stop) @property def kind(self): """ The kind of a Tuple instance. The kind of a Tuple is always of :class:`TupleKind` but parametrised by the number of elements and the kind of each element. Examples ======== >>> from sympy import Tuple, Matrix >>> Tuple(1, 2).kind TupleKind(NumberKind, NumberKind) >>> Tuple(Matrix([1, 2]), 1).kind TupleKind(MatrixKind(NumberKind), NumberKind) >>> Tuple(1, 2).kind.element_kind (NumberKind, NumberKind) See Also ======== sympy.matrices.common.MatrixKind sympy.core.kind.NumberKind """ return TupleKind(*(i.kind for i in self.args)) _sympy_converter[tuple] = lambda tup: Tuple(*tup) def tuple_wrapper(method): """ Decorator that converts any tuple in the function arguments into a Tuple. Explanation =========== The motivation for this is to provide simple user interfaces. The user can call a function with regular tuples in the argument, and the wrapper will convert them to Tuples before handing them to the function. Explanation =========== >>> from sympy.core.containers import tuple_wrapper >>> def f(*args): ... return args >>> g = tuple_wrapper(f) The decorated function g sees only the Tuple argument: >>> g(0, (1, 2), 3) (0, (1, 2), 3) """ def wrap_tuples(*args, **kw_args): newargs = [] for arg in args: if isinstance(arg, tuple): newargs.append(Tuple(*arg)) else: newargs.append(arg) return method(*newargs, **kw_args) return wrap_tuples class Dict(Basic): """ Wrapper around the builtin dict object. Explanation =========== The Dict is a subclass of Basic, so that it works well in the SymPy framework. Because it is immutable, it may be included in sets, but its values must all be given at instantiation and cannot be changed afterwards. Otherwise it behaves identically to the Python dict. Examples ======== >>> from sympy import Dict, Symbol >>> D = Dict({1: 'one', 2: 'two'}) >>> for key in D: ... if key == 1: ... print('%s %s' % (key, D[key])) 1 one The args are sympified so the 1 and 2 are Integers and the values are Symbols. Queries automatically sympify args so the following work: >>> 1 in D True >>> D.has(Symbol('one')) # searches keys and values True >>> 'one' in D # not in the keys False >>> D[1] one """ def __new__(cls, *args): if len(args) == 1 and isinstance(args[0], (dict, Dict)): items = [Tuple(k, v) for k, v in args[0].items()] elif iterable(args) and all(len(arg) == 2 for arg in args): items = [Tuple(k, v) for k, v in args] else: raise TypeError('Pass Dict args as Dict((k1, v1), ...) or Dict({k1: v1, ...})') elements = frozenset(items) obj = Basic.__new__(cls, *ordered(items)) obj.elements = elements obj._dict = dict(items) # In case Tuple decides it wants to sympify return obj def __getitem__(self, key): """x.__getitem__(y) <==> x[y]""" try: key = _sympify(key) except SympifyError: raise KeyError(key) return self._dict[key] def __setitem__(self, key, value): raise NotImplementedError("SymPy Dicts are Immutable") def items(self): '''Returns a set-like object providing a view on dict's items. ''' return self._dict.items() def keys(self): '''Returns the list of the dict's keys.''' return self._dict.keys() def values(self): '''Returns the list of the dict's values.''' return self._dict.values() def __iter__(self): '''x.__iter__() <==> iter(x)''' return iter(self._dict) def __len__(self): '''x.__len__() <==> len(x)''' return self._dict.__len__() def get(self, key, default=None): '''Returns the value for key if the key is in the dictionary.''' try: key = _sympify(key) except SympifyError: return default return self._dict.get(key, default) def __contains__(self, key): '''D.__contains__(k) -> True if D has a key k, else False''' try: key = _sympify(key) except SympifyError: return False return key in self._dict def __lt__(self, other): return _sympify(self.args < other.args) @property def _sorted_args(self): return tuple(sorted(self.args, key=default_sort_key)) def __eq__(self, other): if isinstance(other, dict): return self == Dict(other) return super().__eq__(other) __hash__ : Callable[[Basic], Any] = Basic.__hash__ # this handles dict, defaultdict, OrderedDict _sympy_converter[dict] = lambda d: Dict(*d.items()) class OrderedSet(MutableSet): def __init__(self, iterable=None): if iterable: self.map = OrderedDict((item, None) for item in iterable) else: self.map = OrderedDict() def __len__(self): return len(self.map) def __contains__(self, key): return key in self.map def add(self, key): self.map[key] = None def discard(self, key): self.map.pop(key) def pop(self, last=True): return self.map.popitem(last=last)[0] def __iter__(self): yield from self.map.keys() def __repr__(self): if not self.map: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, list(self.map.keys())) def intersection(self, other): return self.__class__([val for val in self if val in other]) def difference(self, other): return self.__class__([val for val in self if val not in other]) def update(self, iterable): for val in iterable: self.add(val) class TupleKind(Kind): """ TupleKind is a subclass of Kind, which is used to define Kind of ``Tuple``. Parameters of TupleKind will be kinds of all the arguments in Tuples, for example Parameters ========== args : tuple(element_kind) element_kind is kind of element. args is tuple of kinds of element Examples ======== >>> from sympy import Tuple >>> Tuple(1, 2).kind TupleKind(NumberKind, NumberKind) >>> Tuple(1, 2).kind.element_kind (NumberKind, NumberKind) See Also ======== sympy.core.kind.NumberKind MatrixKind sympy.sets.sets.SetKind """ def __new__(cls, *args): obj = super().__new__(cls, *args) obj.element_kind = args return obj def __repr__(self): return "TupleKind{}".format(self.element_kind)
9774755c2d5a385be6b1fa18b15f7a0eb8d0e220f7c8687c7638d4f240aa1902
"""User-friendly public interface to polynomial functions. """ from functools import wraps, reduce from operator import mul from typing import Optional from sympy.core import ( S, Expr, Add, Tuple ) from sympy.core.basic import Basic from sympy.core.decorators import _sympifyit from sympy.core.exprtools import Factors, factor_nc, factor_terms from sympy.core.evalf import ( pure_complex, evalf, fastlog, _evalf_with_bounded_error, quad_to_mpmath) from sympy.core.function import Derivative from sympy.core.mul import Mul, _keep_coeff from sympy.core.numbers import ilcm, I, Integer, equal_valued from sympy.core.relational import Relational, Equality from sympy.core.sorting import ordered from sympy.core.symbol import Dummy, Symbol from sympy.core.sympify import sympify, _sympify from sympy.core.traversal import preorder_traversal, bottom_up from sympy.logic.boolalg import BooleanAtom from sympy.polys import polyoptions as options from sympy.polys.constructor import construct_domain from sympy.polys.domains import FF, QQ, ZZ from sympy.polys.domains.domainelement import DomainElement from sympy.polys.fglmtools import matrix_fglm from sympy.polys.groebnertools import groebner as _groebner from sympy.polys.monomials import Monomial from sympy.polys.orderings import monomial_key from sympy.polys.polyclasses import DMP, DMF, ANP from sympy.polys.polyerrors import ( OperationNotSupported, DomainError, CoercionFailed, UnificationFailed, GeneratorsNeeded, PolynomialError, MultivariatePolynomialError, ExactQuotientFailed, PolificationFailed, ComputationFailed, GeneratorsError, ) from sympy.polys.polyutils import ( basic_from_dict, _sort_gens, _unify_gens, _dict_reorder, _dict_from_expr, _parallel_dict_from_expr, ) from sympy.polys.rationaltools import together from sympy.polys.rootisolation import dup_isolate_real_roots_list from sympy.utilities import group, public, filldedent from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import iterable, sift # Required to avoid errors import sympy.polys import mpmath from mpmath.libmp.libhyper import NoConvergence def _polifyit(func): @wraps(func) def wrapper(f, g): g = _sympify(g) if isinstance(g, Poly): return func(f, g) elif isinstance(g, Expr): try: g = f.from_expr(g, *f.gens) except PolynomialError: if g.is_Matrix: return NotImplemented expr_method = getattr(f.as_expr(), func.__name__) result = expr_method(g) if result is not NotImplemented: sympy_deprecation_warning( """ Mixing Poly with non-polynomial expressions in binary operations is deprecated. Either explicitly convert the non-Poly operand to a Poly with as_poly() or convert the Poly to an Expr with as_expr(). """, deprecated_since_version="1.6", active_deprecations_target="deprecated-poly-nonpoly-binary-operations", ) return result else: return func(f, g) else: return NotImplemented return wrapper @public class Poly(Basic): """ Generic class for representing and operating on polynomial expressions. See :ref:`polys-docs` for general documentation. Poly is a subclass of Basic rather than Expr but instances can be converted to Expr with the :py:meth:`~.Poly.as_expr` method. .. deprecated:: 1.6 Combining Poly with non-Poly objects in binary operations is deprecated. Explicitly convert both objects to either Poly or Expr first. See :ref:`deprecated-poly-nonpoly-binary-operations`. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y Create a univariate polynomial: >>> Poly(x*(x**2 + x - 1)**2) Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ') Create a univariate polynomial with specific domain: >>> from sympy import sqrt >>> Poly(x**2 + 2*x + sqrt(3), domain='R') Poly(1.0*x**2 + 2.0*x + 1.73205080756888, x, domain='RR') Create a multivariate polynomial: >>> Poly(y*x**2 + x*y + 1) Poly(x**2*y + x*y + 1, x, y, domain='ZZ') Create a univariate polynomial, where y is a constant: >>> Poly(y*x**2 + x*y + 1,x) Poly(y*x**2 + y*x + 1, x, domain='ZZ[y]') You can evaluate the above polynomial as a function of y: >>> Poly(y*x**2 + x*y + 1,x).eval(2) 6*y + 1 See Also ======== sympy.core.expr.Expr """ __slots__ = ('rep', 'gens') is_commutative = True is_Poly = True _op_priority = 10.001 def __new__(cls, rep, *gens, **args): """Create a new polynomial instance out of something useful. """ opt = options.build_options(gens, args) if 'order' in opt: raise NotImplementedError("'order' keyword is not implemented yet") if isinstance(rep, (DMP, DMF, ANP, DomainElement)): return cls._from_domain_element(rep, opt) elif iterable(rep, exclude=str): if isinstance(rep, dict): return cls._from_dict(rep, opt) else: return cls._from_list(list(rep), opt) else: rep = sympify(rep) if rep.is_Poly: return cls._from_poly(rep, opt) else: return cls._from_expr(rep, opt) # Poly does not pass its args to Basic.__new__ to be stored in _args so we # have to emulate them here with an args property that derives from rep # and gens which are instance attributes. This also means we need to # define _hashable_content. The _hashable_content is rep and gens but args # uses expr instead of rep (expr is the Basic version of rep). Passing # expr in args means that Basic methods like subs should work. Using rep # otherwise means that Poly can remain more efficient than Basic by # avoiding creating a Basic instance just to be hashable. @classmethod def new(cls, rep, *gens): """Construct :class:`Poly` instance from raw representation. """ if not isinstance(rep, DMP): raise PolynomialError( "invalid polynomial representation: %s" % rep) elif rep.lev != len(gens) - 1: raise PolynomialError("invalid arguments: %s, %s" % (rep, gens)) obj = Basic.__new__(cls) obj.rep = rep obj.gens = gens return obj @property def expr(self): return basic_from_dict(self.rep.to_sympy_dict(), *self.gens) @property def args(self): return (self.expr,) + self.gens def _hashable_content(self): return (self.rep,) + self.gens @classmethod def from_dict(cls, rep, *gens, **args): """Construct a polynomial from a ``dict``. """ opt = options.build_options(gens, args) return cls._from_dict(rep, opt) @classmethod def from_list(cls, rep, *gens, **args): """Construct a polynomial from a ``list``. """ opt = options.build_options(gens, args) return cls._from_list(rep, opt) @classmethod def from_poly(cls, rep, *gens, **args): """Construct a polynomial from a polynomial. """ opt = options.build_options(gens, args) return cls._from_poly(rep, opt) @classmethod def from_expr(cls, rep, *gens, **args): """Construct a polynomial from an expression. """ opt = options.build_options(gens, args) return cls._from_expr(rep, opt) @classmethod def _from_dict(cls, rep, opt): """Construct a polynomial from a ``dict``. """ gens = opt.gens if not gens: raise GeneratorsNeeded( "Cannot initialize from 'dict' without generators") level = len(gens) - 1 domain = opt.domain if domain is None: domain, rep = construct_domain(rep, opt=opt) else: for monom, coeff in rep.items(): rep[monom] = domain.convert(coeff) return cls.new(DMP.from_dict(rep, level, domain), *gens) @classmethod def _from_list(cls, rep, opt): """Construct a polynomial from a ``list``. """ gens = opt.gens if not gens: raise GeneratorsNeeded( "Cannot initialize from 'list' without generators") elif len(gens) != 1: raise MultivariatePolynomialError( "'list' representation not supported") level = len(gens) - 1 domain = opt.domain if domain is None: domain, rep = construct_domain(rep, opt=opt) else: rep = list(map(domain.convert, rep)) return cls.new(DMP.from_list(rep, level, domain), *gens) @classmethod def _from_poly(cls, rep, opt): """Construct a polynomial from a polynomial. """ if cls != rep.__class__: rep = cls.new(rep.rep, *rep.gens) gens = opt.gens field = opt.field domain = opt.domain if gens and rep.gens != gens: if set(rep.gens) != set(gens): return cls._from_expr(rep.as_expr(), opt) else: rep = rep.reorder(*gens) if 'domain' in opt and domain: rep = rep.set_domain(domain) elif field is True: rep = rep.to_field() return rep @classmethod def _from_expr(cls, rep, opt): """Construct a polynomial from an expression. """ rep, opt = _dict_from_expr(rep, opt) return cls._from_dict(rep, opt) @classmethod def _from_domain_element(cls, rep, opt): gens = opt.gens domain = opt.domain level = len(gens) - 1 rep = [domain.convert(rep)] return cls.new(DMP.from_list(rep, level, domain), *gens) def __hash__(self): return super().__hash__() @property def free_symbols(self): """ Free symbols of a polynomial expression. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(x**2 + 1).free_symbols {x} >>> Poly(x**2 + y).free_symbols {x, y} >>> Poly(x**2 + y, x).free_symbols {x, y} >>> Poly(x**2 + y, x, z).free_symbols {x, y} """ symbols = set() gens = self.gens for i in range(len(gens)): for monom in self.monoms(): if monom[i]: symbols |= gens[i].free_symbols break return symbols | self.free_symbols_in_domain @property def free_symbols_in_domain(self): """ Free symbols of the domain of ``self``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 1).free_symbols_in_domain set() >>> Poly(x**2 + y).free_symbols_in_domain set() >>> Poly(x**2 + y, x).free_symbols_in_domain {y} """ domain, symbols = self.rep.dom, set() if domain.is_Composite: for gen in domain.symbols: symbols |= gen.free_symbols elif domain.is_EX: for coeff in self.coeffs(): symbols |= coeff.free_symbols return symbols @property def gen(self): """ Return the principal generator. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).gen x """ return self.gens[0] @property def domain(self): """Get the ground domain of a :py:class:`~.Poly` Returns ======= :py:class:`~.Domain`: Ground domain of the :py:class:`~.Poly`. Examples ======== >>> from sympy import Poly, Symbol >>> x = Symbol('x') >>> p = Poly(x**2 + x) >>> p Poly(x**2 + x, x, domain='ZZ') >>> p.domain ZZ """ return self.get_domain() @property def zero(self): """Return zero polynomial with ``self``'s properties. """ return self.new(self.rep.zero(self.rep.lev, self.rep.dom), *self.gens) @property def one(self): """Return one polynomial with ``self``'s properties. """ return self.new(self.rep.one(self.rep.lev, self.rep.dom), *self.gens) @property def unit(self): """Return unit polynomial with ``self``'s properties. """ return self.new(self.rep.unit(self.rep.lev, self.rep.dom), *self.gens) def unify(f, g): """ Make ``f`` and ``g`` belong to the same domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f, g = Poly(x/2 + 1), Poly(2*x + 1) >>> f Poly(1/2*x + 1, x, domain='QQ') >>> g Poly(2*x + 1, x, domain='ZZ') >>> F, G = f.unify(g) >>> F Poly(1/2*x + 1, x, domain='QQ') >>> G Poly(2*x + 1, x, domain='QQ') """ _, per, F, G = f._unify(g) return per(F), per(G) def _unify(f, g): g = sympify(g) if not g.is_Poly: try: return f.rep.dom, f.per, f.rep, f.rep.per(f.rep.dom.from_sympy(g)) except CoercionFailed: raise UnificationFailed("Cannot unify %s with %s" % (f, g)) if isinstance(f.rep, DMP) and isinstance(g.rep, DMP): gens = _unify_gens(f.gens, g.gens) dom, lev = f.rep.dom.unify(g.rep.dom, gens), len(gens) - 1 if f.gens != gens: f_monoms, f_coeffs = _dict_reorder( f.rep.to_dict(), f.gens, gens) if f.rep.dom != dom: f_coeffs = [dom.convert(c, f.rep.dom) for c in f_coeffs] F = DMP(dict(list(zip(f_monoms, f_coeffs))), dom, lev) else: F = f.rep.convert(dom) if g.gens != gens: g_monoms, g_coeffs = _dict_reorder( g.rep.to_dict(), g.gens, gens) if g.rep.dom != dom: g_coeffs = [dom.convert(c, g.rep.dom) for c in g_coeffs] G = DMP(dict(list(zip(g_monoms, g_coeffs))), dom, lev) else: G = g.rep.convert(dom) else: raise UnificationFailed("Cannot unify %s with %s" % (f, g)) cls = f.__class__ def per(rep, dom=dom, gens=gens, remove=None): if remove is not None: gens = gens[:remove] + gens[remove + 1:] if not gens: return dom.to_sympy(rep) return cls.new(rep, *gens) return dom, per, F, G def per(f, rep, gens=None, remove=None): """ Create a Poly out of the given representation. Examples ======== >>> from sympy import Poly, ZZ >>> from sympy.abc import x, y >>> from sympy.polys.polyclasses import DMP >>> a = Poly(x**2 + 1) >>> a.per(DMP([ZZ(1), ZZ(1)], ZZ), gens=[y]) Poly(y + 1, y, domain='ZZ') """ if gens is None: gens = f.gens if remove is not None: gens = gens[:remove] + gens[remove + 1:] if not gens: return f.rep.dom.to_sympy(rep) return f.__class__.new(rep, *gens) def set_domain(f, domain): """Set the ground domain of ``f``. """ opt = options.build_options(f.gens, {'domain': domain}) return f.per(f.rep.convert(opt.domain)) def get_domain(f): """Get the ground domain of ``f``. """ return f.rep.dom def set_modulus(f, modulus): """ Set the modulus of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(5*x**2 + 2*x - 1, x).set_modulus(2) Poly(x**2 + 1, x, modulus=2) """ modulus = options.Modulus.preprocess(modulus) return f.set_domain(FF(modulus)) def get_modulus(f): """ Get the modulus of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, modulus=2).get_modulus() 2 """ domain = f.get_domain() if domain.is_FiniteField: return Integer(domain.characteristic()) else: raise PolynomialError("not a polynomial over a Galois field") def _eval_subs(f, old, new): """Internal implementation of :func:`subs`. """ if old in f.gens: if new.is_number: return f.eval(old, new) else: try: return f.replace(old, new) except PolynomialError: pass return f.as_expr().subs(old, new) def exclude(f): """ Remove unnecessary generators from ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import a, b, c, d, x >>> Poly(a + x, a, b, c, d, x).exclude() Poly(a + x, a, x, domain='ZZ') """ J, new = f.rep.exclude() gens = [gen for j, gen in enumerate(f.gens) if j not in J] return f.per(new, gens=gens) def replace(f, x, y=None, **_ignore): # XXX this does not match Basic's signature """ Replace ``x`` with ``y`` in generators list. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 1, x).replace(x, y) Poly(y**2 + 1, y, domain='ZZ') """ if y is None: if f.is_univariate: x, y = f.gen, x else: raise PolynomialError( "syntax supported only in univariate case") if x == y or x not in f.gens: return f if x in f.gens and y not in f.gens: dom = f.get_domain() if not dom.is_Composite or y not in dom.symbols: gens = list(f.gens) gens[gens.index(x)] = y return f.per(f.rep, gens=gens) raise PolynomialError("Cannot replace %s with %s in %s" % (x, y, f)) def match(f, *args, **kwargs): """Match expression from Poly. See Basic.match()""" return f.as_expr().match(*args, **kwargs) def reorder(f, *gens, **args): """ Efficiently apply new order of generators. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x*y**2, x, y).reorder(y, x) Poly(y**2*x + x**2, y, x, domain='ZZ') """ opt = options.Options((), args) if not gens: gens = _sort_gens(f.gens, opt=opt) elif set(f.gens) != set(gens): raise PolynomialError( "generators list can differ only up to order of elements") rep = dict(list(zip(*_dict_reorder(f.rep.to_dict(), f.gens, gens)))) return f.per(DMP(rep, f.rep.dom, len(gens) - 1), gens=gens) def ltrim(f, gen): """ Remove dummy generators from ``f`` that are to the left of specified ``gen`` in the generators as ordered. When ``gen`` is an integer, it refers to the generator located at that position within the tuple of generators of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(y**2 + y*z**2, x, y, z).ltrim(y) Poly(y**2 + y*z**2, y, z, domain='ZZ') >>> Poly(z, x, y, z).ltrim(-1) Poly(z, z, domain='ZZ') """ rep = f.as_dict(native=True) j = f._gen_to_level(gen) terms = {} for monom, coeff in rep.items(): if any(monom[:j]): # some generator is used in the portion to be trimmed raise PolynomialError("Cannot left trim %s" % f) terms[monom[j:]] = coeff gens = f.gens[j:] return f.new(DMP.from_dict(terms, len(gens) - 1, f.rep.dom), *gens) def has_only_gens(f, *gens): """ Return ``True`` if ``Poly(f, *gens)`` retains ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(x*y + 1, x, y, z).has_only_gens(x, y) True >>> Poly(x*y + z, x, y, z).has_only_gens(x, y) False """ indices = set() for gen in gens: try: index = f.gens.index(gen) except ValueError: raise GeneratorsError( "%s doesn't have %s as generator" % (f, gen)) else: indices.add(index) for monom in f.monoms(): for i, elt in enumerate(monom): if i not in indices and elt: return False return True def to_ring(f): """ Make the ground domain a ring. Examples ======== >>> from sympy import Poly, QQ >>> from sympy.abc import x >>> Poly(x**2 + 1, domain=QQ).to_ring() Poly(x**2 + 1, x, domain='ZZ') """ if hasattr(f.rep, 'to_ring'): result = f.rep.to_ring() else: # pragma: no cover raise OperationNotSupported(f, 'to_ring') return f.per(result) def to_field(f): """ Make the ground domain a field. Examples ======== >>> from sympy import Poly, ZZ >>> from sympy.abc import x >>> Poly(x**2 + 1, x, domain=ZZ).to_field() Poly(x**2 + 1, x, domain='QQ') """ if hasattr(f.rep, 'to_field'): result = f.rep.to_field() else: # pragma: no cover raise OperationNotSupported(f, 'to_field') return f.per(result) def to_exact(f): """ Make the ground domain exact. Examples ======== >>> from sympy import Poly, RR >>> from sympy.abc import x >>> Poly(x**2 + 1.0, x, domain=RR).to_exact() Poly(x**2 + 1, x, domain='QQ') """ if hasattr(f.rep, 'to_exact'): result = f.rep.to_exact() else: # pragma: no cover raise OperationNotSupported(f, 'to_exact') return f.per(result) def retract(f, field=None): """ Recalculate the ground domain of a polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(x**2 + 1, x, domain='QQ[y]') >>> f Poly(x**2 + 1, x, domain='QQ[y]') >>> f.retract() Poly(x**2 + 1, x, domain='ZZ') >>> f.retract(field=True) Poly(x**2 + 1, x, domain='QQ') """ dom, rep = construct_domain(f.as_dict(zero=True), field=field, composite=f.domain.is_Composite or None) return f.from_dict(rep, f.gens, domain=dom) def slice(f, x, m, n=None): """Take a continuous subsequence of terms of ``f``. """ if n is None: j, m, n = 0, x, m else: j = f._gen_to_level(x) m, n = int(m), int(n) if hasattr(f.rep, 'slice'): result = f.rep.slice(m, n, j) else: # pragma: no cover raise OperationNotSupported(f, 'slice') return f.per(result) def coeffs(f, order=None): """ Returns all non-zero coefficients from ``f`` in lex order. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x + 3, x).coeffs() [1, 2, 3] See Also ======== all_coeffs coeff_monomial nth """ return [f.rep.dom.to_sympy(c) for c in f.rep.coeffs(order=order)] def monoms(f, order=None): """ Returns all non-zero monomials from ``f`` in lex order. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).monoms() [(2, 0), (1, 2), (1, 1), (0, 1)] See Also ======== all_monoms """ return f.rep.monoms(order=order) def terms(f, order=None): """ Returns all non-zero terms from ``f`` in lex order. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x*y**2 + x*y + 3*y, x, y).terms() [((2, 0), 1), ((1, 2), 2), ((1, 1), 1), ((0, 1), 3)] See Also ======== all_terms """ return [(m, f.rep.dom.to_sympy(c)) for m, c in f.rep.terms(order=order)] def all_coeffs(f): """ Returns all coefficients from a univariate polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x - 1, x).all_coeffs() [1, 0, 2, -1] """ return [f.rep.dom.to_sympy(c) for c in f.rep.all_coeffs()] def all_monoms(f): """ Returns all monomials from a univariate polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x - 1, x).all_monoms() [(3,), (2,), (1,), (0,)] See Also ======== all_terms """ return f.rep.all_monoms() def all_terms(f): """ Returns all terms from a univariate polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x - 1, x).all_terms() [((3,), 1), ((2,), 0), ((1,), 2), ((0,), -1)] """ return [(m, f.rep.dom.to_sympy(c)) for m, c in f.rep.all_terms()] def termwise(f, func, *gens, **args): """ Apply a function to all terms of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> def func(k, coeff): ... k = k[0] ... return coeff//10**(2-k) >>> Poly(x**2 + 20*x + 400).termwise(func) Poly(x**2 + 2*x + 4, x, domain='ZZ') """ terms = {} for monom, coeff in f.terms(): result = func(monom, coeff) if isinstance(result, tuple): monom, coeff = result else: coeff = result if coeff: if monom not in terms: terms[monom] = coeff else: raise PolynomialError( "%s monomial was generated twice" % monom) return f.from_dict(terms, *(gens or f.gens), **args) def length(f): """ Returns the number of non-zero terms in ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 2*x - 1).length() 3 """ return len(f.as_dict()) def as_dict(f, native=False, zero=False): """ Switch to a ``dict`` representation. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x*y**2 - y, x, y).as_dict() {(0, 1): -1, (1, 2): 2, (2, 0): 1} """ if native: return f.rep.to_dict(zero=zero) else: return f.rep.to_sympy_dict(zero=zero) def as_list(f, native=False): """Switch to a ``list`` representation. """ if native: return f.rep.to_list() else: return f.rep.to_sympy_list() def as_expr(f, *gens): """ Convert a Poly instance to an Expr instance. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2 + 2*x*y**2 - y, x, y) >>> f.as_expr() x**2 + 2*x*y**2 - y >>> f.as_expr({x: 5}) 10*y**2 - y + 25 >>> f.as_expr(5, 6) 379 """ if not gens: return f.expr if len(gens) == 1 and isinstance(gens[0], dict): mapping = gens[0] gens = list(f.gens) for gen, value in mapping.items(): try: index = gens.index(gen) except ValueError: raise GeneratorsError( "%s doesn't have %s as generator" % (f, gen)) else: gens[index] = value return basic_from_dict(f.rep.to_sympy_dict(), *gens) def as_poly(self, *gens, **args): """Converts ``self`` to a polynomial or returns ``None``. >>> 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 """ try: poly = Poly(self, *gens, **args) if not poly.is_Poly: return None else: return poly except PolynomialError: return None def lift(f): """ Convert algebraic coefficients to rationals. Examples ======== >>> from sympy import Poly, I >>> from sympy.abc import x >>> Poly(x**2 + I*x + 1, x, extension=I).lift() Poly(x**4 + 3*x**2 + 1, x, domain='QQ') """ if hasattr(f.rep, 'lift'): result = f.rep.lift() else: # pragma: no cover raise OperationNotSupported(f, 'lift') return f.per(result) def deflate(f): """ Reduce degree of ``f`` by mapping ``x_i**m`` to ``y_i``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**6*y**2 + x**3 + 1, x, y).deflate() ((3, 2), Poly(x**2*y + x + 1, x, y, domain='ZZ')) """ if hasattr(f.rep, 'deflate'): J, result = f.rep.deflate() else: # pragma: no cover raise OperationNotSupported(f, 'deflate') return J, f.per(result) def inject(f, front=False): """ Inject ground domain generators into ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2*y + x*y**3 + x*y + 1, x) >>> f.inject() Poly(x**2*y + x*y**3 + x*y + 1, x, y, domain='ZZ') >>> f.inject(front=True) Poly(y**3*x + y*x**2 + y*x + 1, y, x, domain='ZZ') """ dom = f.rep.dom if dom.is_Numerical: return f elif not dom.is_Poly: raise DomainError("Cannot inject generators over %s" % dom) if hasattr(f.rep, 'inject'): result = f.rep.inject(front=front) else: # pragma: no cover raise OperationNotSupported(f, 'inject') if front: gens = dom.symbols + f.gens else: gens = f.gens + dom.symbols return f.new(result, *gens) def eject(f, *gens): """ Eject selected generators into the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2*y + x*y**3 + x*y + 1, x, y) >>> f.eject(x) Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]') >>> f.eject(y) Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]') """ dom = f.rep.dom if not dom.is_Numerical: raise DomainError("Cannot eject generators over %s" % dom) k = len(gens) if f.gens[:k] == gens: _gens, front = f.gens[k:], True elif f.gens[-k:] == gens: _gens, front = f.gens[:-k], False else: raise NotImplementedError( "can only eject front or back generators") dom = dom.inject(*gens) if hasattr(f.rep, 'eject'): result = f.rep.eject(dom, front=front) else: # pragma: no cover raise OperationNotSupported(f, 'eject') return f.new(result, *_gens) def terms_gcd(f): """ Remove GCD of terms from the polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**6*y**2 + x**3*y, x, y).terms_gcd() ((3, 1), Poly(x**3*y + 1, x, y, domain='ZZ')) """ if hasattr(f.rep, 'terms_gcd'): J, result = f.rep.terms_gcd() else: # pragma: no cover raise OperationNotSupported(f, 'terms_gcd') return J, f.per(result) def add_ground(f, coeff): """ Add an element of the ground domain to ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 1).add_ground(2) Poly(x + 3, x, domain='ZZ') """ if hasattr(f.rep, 'add_ground'): result = f.rep.add_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'add_ground') return f.per(result) def sub_ground(f, coeff): """ Subtract an element of the ground domain from ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 1).sub_ground(2) Poly(x - 1, x, domain='ZZ') """ if hasattr(f.rep, 'sub_ground'): result = f.rep.sub_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'sub_ground') return f.per(result) def mul_ground(f, coeff): """ Multiply ``f`` by a an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 1).mul_ground(2) Poly(2*x + 2, x, domain='ZZ') """ if hasattr(f.rep, 'mul_ground'): result = f.rep.mul_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'mul_ground') return f.per(result) def quo_ground(f, coeff): """ Quotient of ``f`` by a an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x + 4).quo_ground(2) Poly(x + 2, x, domain='ZZ') >>> Poly(2*x + 3).quo_ground(2) Poly(x + 1, x, domain='ZZ') """ if hasattr(f.rep, 'quo_ground'): result = f.rep.quo_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'quo_ground') return f.per(result) def exquo_ground(f, coeff): """ Exact quotient of ``f`` by a an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x + 4).exquo_ground(2) Poly(x + 2, x, domain='ZZ') >>> Poly(2*x + 3).exquo_ground(2) Traceback (most recent call last): ... ExactQuotientFailed: 2 does not divide 3 in ZZ """ if hasattr(f.rep, 'exquo_ground'): result = f.rep.exquo_ground(coeff) else: # pragma: no cover raise OperationNotSupported(f, 'exquo_ground') return f.per(result) def abs(f): """ Make all coefficients in ``f`` positive. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).abs() Poly(x**2 + 1, x, domain='ZZ') """ if hasattr(f.rep, 'abs'): result = f.rep.abs() else: # pragma: no cover raise OperationNotSupported(f, 'abs') return f.per(result) def neg(f): """ Negate all coefficients in ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).neg() Poly(-x**2 + 1, x, domain='ZZ') >>> -Poly(x**2 - 1, x) Poly(-x**2 + 1, x, domain='ZZ') """ if hasattr(f.rep, 'neg'): result = f.rep.neg() else: # pragma: no cover raise OperationNotSupported(f, 'neg') return f.per(result) def add(f, g): """ Add two polynomials ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).add(Poly(x - 2, x)) Poly(x**2 + x - 1, x, domain='ZZ') >>> Poly(x**2 + 1, x) + Poly(x - 2, x) Poly(x**2 + x - 1, x, domain='ZZ') """ g = sympify(g) if not g.is_Poly: return f.add_ground(g) _, per, F, G = f._unify(g) if hasattr(f.rep, 'add'): result = F.add(G) else: # pragma: no cover raise OperationNotSupported(f, 'add') return per(result) def sub(f, g): """ Subtract two polynomials ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).sub(Poly(x - 2, x)) Poly(x**2 - x + 3, x, domain='ZZ') >>> Poly(x**2 + 1, x) - Poly(x - 2, x) Poly(x**2 - x + 3, x, domain='ZZ') """ g = sympify(g) if not g.is_Poly: return f.sub_ground(g) _, per, F, G = f._unify(g) if hasattr(f.rep, 'sub'): result = F.sub(G) else: # pragma: no cover raise OperationNotSupported(f, 'sub') return per(result) def mul(f, g): """ Multiply two polynomials ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).mul(Poly(x - 2, x)) Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ') >>> Poly(x**2 + 1, x)*Poly(x - 2, x) Poly(x**3 - 2*x**2 + x - 2, x, domain='ZZ') """ g = sympify(g) if not g.is_Poly: return f.mul_ground(g) _, per, F, G = f._unify(g) if hasattr(f.rep, 'mul'): result = F.mul(G) else: # pragma: no cover raise OperationNotSupported(f, 'mul') return per(result) def sqr(f): """ Square a polynomial ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x - 2, x).sqr() Poly(x**2 - 4*x + 4, x, domain='ZZ') >>> Poly(x - 2, x)**2 Poly(x**2 - 4*x + 4, x, domain='ZZ') """ if hasattr(f.rep, 'sqr'): result = f.rep.sqr() else: # pragma: no cover raise OperationNotSupported(f, 'sqr') return f.per(result) def pow(f, n): """ Raise ``f`` to a non-negative power ``n``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x - 2, x).pow(3) Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ') >>> Poly(x - 2, x)**3 Poly(x**3 - 6*x**2 + 12*x - 8, x, domain='ZZ') """ n = int(n) if hasattr(f.rep, 'pow'): result = f.rep.pow(n) else: # pragma: no cover raise OperationNotSupported(f, 'pow') return f.per(result) def pdiv(f, g): """ Polynomial pseudo-division of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).pdiv(Poly(2*x - 4, x)) (Poly(2*x + 4, x, domain='ZZ'), Poly(20, x, domain='ZZ')) """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'pdiv'): q, r = F.pdiv(G) else: # pragma: no cover raise OperationNotSupported(f, 'pdiv') return per(q), per(r) def prem(f, g): """ Polynomial pseudo-remainder of ``f`` by ``g``. Caveat: The function prem(f, g, x) can be safely used to compute in Z[x] _only_ subresultant polynomial remainder sequences (prs's). To safely compute Euclidean and Sturmian prs's in Z[x] employ anyone of the corresponding functions found in the module sympy.polys.subresultants_qq_zz. The functions in the module with suffix _pg compute prs's in Z[x] employing rem(f, g, x), whereas the functions with suffix _amv compute prs's in Z[x] employing rem_z(f, g, x). The function rem_z(f, g, x) differs from prem(f, g, x) in that to compute the remainder polynomials in Z[x] it premultiplies the divident times the absolute value of the leading coefficient of the divisor raised to the power degree(f, x) - degree(g, x) + 1. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).prem(Poly(2*x - 4, x)) Poly(20, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'prem'): result = F.prem(G) else: # pragma: no cover raise OperationNotSupported(f, 'prem') return per(result) def pquo(f, g): """ Polynomial pseudo-quotient of ``f`` by ``g``. See the Caveat note in the function prem(f, g). Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).pquo(Poly(2*x - 4, x)) Poly(2*x + 4, x, domain='ZZ') >>> Poly(x**2 - 1, x).pquo(Poly(2*x - 2, x)) Poly(2*x + 2, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'pquo'): result = F.pquo(G) else: # pragma: no cover raise OperationNotSupported(f, 'pquo') return per(result) def pexquo(f, g): """ Polynomial exact pseudo-quotient of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).pexquo(Poly(2*x - 2, x)) Poly(2*x + 2, x, domain='ZZ') >>> Poly(x**2 + 1, x).pexquo(Poly(2*x - 4, x)) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'pexquo'): try: result = F.pexquo(G) except ExactQuotientFailed as exc: raise exc.new(f.as_expr(), g.as_expr()) else: # pragma: no cover raise OperationNotSupported(f, 'pexquo') return per(result) def div(f, g, auto=True): """ Polynomial division with remainder of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x)) (Poly(1/2*x + 1, x, domain='QQ'), Poly(5, x, domain='QQ')) >>> Poly(x**2 + 1, x).div(Poly(2*x - 4, x), auto=False) (Poly(0, x, domain='ZZ'), Poly(x**2 + 1, x, domain='ZZ')) """ dom, per, F, G = f._unify(g) retract = False if auto and dom.is_Ring and not dom.is_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'div'): q, r = F.div(G) else: # pragma: no cover raise OperationNotSupported(f, 'div') if retract: try: Q, R = q.to_ring(), r.to_ring() except CoercionFailed: pass else: q, r = Q, R return per(q), per(r) def rem(f, g, auto=True): """ Computes the polynomial remainder of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x)) Poly(5, x, domain='ZZ') >>> Poly(x**2 + 1, x).rem(Poly(2*x - 4, x), auto=False) Poly(x**2 + 1, x, domain='ZZ') """ dom, per, F, G = f._unify(g) retract = False if auto and dom.is_Ring and not dom.is_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'rem'): r = F.rem(G) else: # pragma: no cover raise OperationNotSupported(f, 'rem') if retract: try: r = r.to_ring() except CoercionFailed: pass return per(r) def quo(f, g, auto=True): """ Computes polynomial quotient of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).quo(Poly(2*x - 4, x)) Poly(1/2*x + 1, x, domain='QQ') >>> Poly(x**2 - 1, x).quo(Poly(x - 1, x)) Poly(x + 1, x, domain='ZZ') """ dom, per, F, G = f._unify(g) retract = False if auto and dom.is_Ring and not dom.is_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'quo'): q = F.quo(G) else: # pragma: no cover raise OperationNotSupported(f, 'quo') if retract: try: q = q.to_ring() except CoercionFailed: pass return per(q) def exquo(f, g, auto=True): """ Computes polynomial exact quotient of ``f`` by ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).exquo(Poly(x - 1, x)) Poly(x + 1, x, domain='ZZ') >>> Poly(x**2 + 1, x).exquo(Poly(2*x - 4, x)) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ dom, per, F, G = f._unify(g) retract = False if auto and dom.is_Ring and not dom.is_Field: F, G = F.to_field(), G.to_field() retract = True if hasattr(f.rep, 'exquo'): try: q = F.exquo(G) except ExactQuotientFailed as exc: raise exc.new(f.as_expr(), g.as_expr()) else: # pragma: no cover raise OperationNotSupported(f, 'exquo') if retract: try: q = q.to_ring() except CoercionFailed: pass return per(q) def _gen_to_level(f, gen): """Returns level associated with the given generator. """ if isinstance(gen, int): length = len(f.gens) if -length <= gen < length: if gen < 0: return length + gen else: return gen else: raise PolynomialError("-%s <= gen < %s expected, got %s" % (length, length, gen)) else: try: return f.gens.index(sympify(gen)) except ValueError: raise PolynomialError( "a valid generator expected, got %s" % gen) def degree(f, gen=0): """ Returns degree of ``f`` in ``x_j``. The degree of 0 is negative infinity. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + y*x + 1, x, y).degree() 2 >>> Poly(x**2 + y*x + y, x, y).degree(y) 1 >>> Poly(0, x).degree() -oo """ j = f._gen_to_level(gen) if hasattr(f.rep, 'degree'): return f.rep.degree(j) else: # pragma: no cover raise OperationNotSupported(f, 'degree') def degree_list(f): """ Returns a list of degrees of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + y*x + 1, x, y).degree_list() (2, 1) """ if hasattr(f.rep, 'degree_list'): return f.rep.degree_list() else: # pragma: no cover raise OperationNotSupported(f, 'degree_list') def total_degree(f): """ Returns the total degree of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + y*x + 1, x, y).total_degree() 2 >>> Poly(x + y**5, x, y).total_degree() 5 """ if hasattr(f.rep, 'total_degree'): return f.rep.total_degree() else: # pragma: no cover raise OperationNotSupported(f, 'total_degree') def homogenize(f, s): """ Returns the homogeneous polynomial of ``f``. A homogeneous polynomial is a polynomial whose all monomials with non-zero coefficients have the same total degree. If you only want to check if a polynomial is homogeneous, then use :func:`Poly.is_homogeneous`. If you want not only to check if a polynomial is homogeneous but also compute its homogeneous order, then use :func:`Poly.homogeneous_order`. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> f = Poly(x**5 + 2*x**2*y**2 + 9*x*y**3) >>> f.homogenize(z) Poly(x**5 + 2*x**2*y**2*z + 9*x*y**3*z, x, y, z, domain='ZZ') """ if not isinstance(s, Symbol): raise TypeError("``Symbol`` expected, got %s" % type(s)) if s in f.gens: i = f.gens.index(s) gens = f.gens else: i = len(f.gens) gens = f.gens + (s,) if hasattr(f.rep, 'homogenize'): return f.per(f.rep.homogenize(i), gens=gens) raise OperationNotSupported(f, 'homogeneous_order') def homogeneous_order(f): """ Returns the homogeneous order of ``f``. A homogeneous polynomial is a polynomial whose all monomials with non-zero coefficients have the same total degree. This degree is the homogeneous order of ``f``. If you only want to check if a polynomial is homogeneous, then use :func:`Poly.is_homogeneous`. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**5 + 2*x**3*y**2 + 9*x*y**4) >>> f.homogeneous_order() 5 """ if hasattr(f.rep, 'homogeneous_order'): return f.rep.homogeneous_order() else: # pragma: no cover raise OperationNotSupported(f, 'homogeneous_order') def LC(f, order=None): """ Returns the leading coefficient of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(4*x**3 + 2*x**2 + 3*x, x).LC() 4 """ if order is not None: return f.coeffs(order)[0] if hasattr(f.rep, 'LC'): result = f.rep.LC() else: # pragma: no cover raise OperationNotSupported(f, 'LC') return f.rep.dom.to_sympy(result) def TC(f): """ Returns the trailing coefficient of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x**2 + 3*x, x).TC() 0 """ if hasattr(f.rep, 'TC'): result = f.rep.TC() else: # pragma: no cover raise OperationNotSupported(f, 'TC') return f.rep.dom.to_sympy(result) def EC(f, order=None): """ Returns the last non-zero coefficient of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 + 2*x**2 + 3*x, x).EC() 3 """ if hasattr(f.rep, 'coeffs'): return f.coeffs(order)[-1] else: # pragma: no cover raise OperationNotSupported(f, 'EC') def coeff_monomial(f, monom): """ Returns the coefficient of ``monom`` in ``f`` if there, else None. Examples ======== >>> from sympy import Poly, exp >>> from sympy.abc import x, y >>> p = Poly(24*x*y*exp(8) + 23*x, x, y) >>> p.coeff_monomial(x) 23 >>> p.coeff_monomial(y) 0 >>> p.coeff_monomial(x*y) 24*exp(8) Note that ``Expr.coeff()`` behaves differently, collecting terms if possible; the Poly must be converted to an Expr to use that method, however: >>> p.as_expr().coeff(x) 24*y*exp(8) + 23 >>> p.as_expr().coeff(y) 24*x*exp(8) >>> p.as_expr().coeff(x*y) 24*exp(8) See Also ======== nth: more efficient query using exponents of the monomial's generators """ return f.nth(*Monomial(monom, f.gens).exponents) def nth(f, *N): """ Returns the ``n``-th coefficient of ``f`` where ``N`` are the exponents of the generators in the term of interest. Examples ======== >>> from sympy import Poly, sqrt >>> from sympy.abc import x, y >>> Poly(x**3 + 2*x**2 + 3*x, x).nth(2) 2 >>> Poly(x**3 + 2*x*y**2 + y**2, x, y).nth(1, 2) 2 >>> Poly(4*sqrt(x)*y) Poly(4*y*(sqrt(x)), y, sqrt(x), domain='ZZ') >>> _.nth(1, 1) 4 See Also ======== coeff_monomial """ if hasattr(f.rep, 'nth'): if len(N) != len(f.gens): raise ValueError('exponent of each generator must be specified') result = f.rep.nth(*list(map(int, N))) else: # pragma: no cover raise OperationNotSupported(f, 'nth') return f.rep.dom.to_sympy(result) def coeff(f, x, n=1, right=False): # the semantics of coeff_monomial and Expr.coeff are different; # if someone is working with a Poly, they should be aware of the # differences and chose the method best suited for the query. # Alternatively, a pure-polys method could be written here but # at this time the ``right`` keyword would be ignored because Poly # doesn't work with non-commutatives. raise NotImplementedError( 'Either convert to Expr with `as_expr` method ' 'to use Expr\'s coeff method or else use the ' '`coeff_monomial` method of Polys.') def LM(f, order=None): """ Returns the leading monomial of ``f``. The Leading monomial signifies the monomial having the highest power of the principal generator in the expression f. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LM() x**2*y**0 """ return Monomial(f.monoms(order)[0], f.gens) def EM(f, order=None): """ Returns the last non-zero monomial of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).EM() x**0*y**1 """ return Monomial(f.monoms(order)[-1], f.gens) def LT(f, order=None): """ Returns the leading term of ``f``. The Leading term signifies the term having the highest power of the principal generator in the expression f along with its coefficient. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).LT() (x**2*y**0, 4) """ monom, coeff = f.terms(order)[0] return Monomial(monom, f.gens), coeff def ET(f, order=None): """ Returns the last non-zero term of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(4*x**2 + 2*x*y**2 + x*y + 3*y, x, y).ET() (x**0*y**1, 3) """ monom, coeff = f.terms(order)[-1] return Monomial(monom, f.gens), coeff def max_norm(f): """ Returns maximum norm of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(-x**2 + 2*x - 3, x).max_norm() 3 """ if hasattr(f.rep, 'max_norm'): result = f.rep.max_norm() else: # pragma: no cover raise OperationNotSupported(f, 'max_norm') return f.rep.dom.to_sympy(result) def l1_norm(f): """ Returns l1 norm of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(-x**2 + 2*x - 3, x).l1_norm() 6 """ if hasattr(f.rep, 'l1_norm'): result = f.rep.l1_norm() else: # pragma: no cover raise OperationNotSupported(f, 'l1_norm') return f.rep.dom.to_sympy(result) def clear_denoms(self, convert=False): """ Clear denominators, but keep the ground domain. Examples ======== >>> from sympy import Poly, S, QQ >>> from sympy.abc import x >>> f = Poly(x/2 + S(1)/3, x, domain=QQ) >>> f.clear_denoms() (6, Poly(3*x + 2, x, domain='QQ')) >>> f.clear_denoms(convert=True) (6, Poly(3*x + 2, x, domain='ZZ')) """ f = self if not f.rep.dom.is_Field: return S.One, f dom = f.get_domain() if dom.has_assoc_Ring: dom = f.rep.dom.get_ring() if hasattr(f.rep, 'clear_denoms'): coeff, result = f.rep.clear_denoms() else: # pragma: no cover raise OperationNotSupported(f, 'clear_denoms') coeff, f = dom.to_sympy(coeff), f.per(result) if not convert or not dom.has_assoc_Ring: return coeff, f else: return coeff, f.to_ring() def rat_clear_denoms(self, g): """ Clear denominators in a rational function ``f/g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = Poly(x**2/y + 1, x) >>> g = Poly(x**3 + y, x) >>> p, q = f.rat_clear_denoms(g) >>> p Poly(x**2 + y, x, domain='ZZ[y]') >>> q Poly(y*x**3 + y**2, x, domain='ZZ[y]') """ f = self dom, per, f, g = f._unify(g) f = per(f) g = per(g) if not (dom.is_Field and dom.has_assoc_Ring): return f, g a, f = f.clear_denoms(convert=True) b, g = g.clear_denoms(convert=True) f = f.mul_ground(b) g = g.mul_ground(a) return f, g def integrate(self, *specs, **args): """ Computes indefinite integral of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x + 1, x).integrate() Poly(1/3*x**3 + x**2 + x, x, domain='QQ') >>> Poly(x*y**2 + x, x, y).integrate((0, 1), (1, 0)) Poly(1/2*x**2*y**2 + 1/2*x**2, x, y, domain='QQ') """ f = self if args.get('auto', True) and f.rep.dom.is_Ring: f = f.to_field() if hasattr(f.rep, 'integrate'): if not specs: return f.per(f.rep.integrate(m=1)) rep = f.rep for spec in specs: if isinstance(spec, tuple): gen, m = spec else: gen, m = spec, 1 rep = rep.integrate(int(m), f._gen_to_level(gen)) return f.per(rep) else: # pragma: no cover raise OperationNotSupported(f, 'integrate') def diff(f, *specs, **kwargs): """ Computes partial derivative of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + 2*x + 1, x).diff() Poly(2*x + 2, x, domain='ZZ') >>> Poly(x*y**2 + x, x, y).diff((0, 0), (1, 1)) Poly(2*x*y, x, y, domain='ZZ') """ if not kwargs.get('evaluate', True): return Derivative(f, *specs, **kwargs) if hasattr(f.rep, 'diff'): if not specs: return f.per(f.rep.diff(m=1)) rep = f.rep for spec in specs: if isinstance(spec, tuple): gen, m = spec else: gen, m = spec, 1 rep = rep.diff(int(m), f._gen_to_level(gen)) return f.per(rep) else: # pragma: no cover raise OperationNotSupported(f, 'diff') _eval_derivative = diff def eval(self, x, a=None, auto=True): """ Evaluate ``f`` at ``a`` in the given variable. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> Poly(x**2 + 2*x + 3, x).eval(2) 11 >>> Poly(2*x*y + 3*x + y + 2, x, y).eval(x, 2) Poly(5*y + 8, y, domain='ZZ') >>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z) >>> f.eval({x: 2}) Poly(5*y + 2*z + 6, y, z, domain='ZZ') >>> f.eval({x: 2, y: 5}) Poly(2*z + 31, z, domain='ZZ') >>> f.eval({x: 2, y: 5, z: 7}) 45 >>> f.eval((2, 5)) Poly(2*z + 31, z, domain='ZZ') >>> f(2, 5) Poly(2*z + 31, z, domain='ZZ') """ f = self if a is None: if isinstance(x, dict): mapping = x for gen, value in mapping.items(): f = f.eval(gen, value) return f elif isinstance(x, (tuple, list)): values = x if len(values) > len(f.gens): raise ValueError("too many values provided") for gen, value in zip(f.gens, values): f = f.eval(gen, value) return f else: j, a = 0, x else: j = f._gen_to_level(x) if not hasattr(f.rep, 'eval'): # pragma: no cover raise OperationNotSupported(f, 'eval') try: result = f.rep.eval(a, j) except CoercionFailed: if not auto: raise DomainError("Cannot evaluate at %s in %s" % (a, f.rep.dom)) else: a_domain, [a] = construct_domain([a]) new_domain = f.get_domain().unify_with_symbols(a_domain, f.gens) f = f.set_domain(new_domain) a = new_domain.convert(a, a_domain) result = f.rep.eval(a, j) return f.per(result, remove=j) def __call__(f, *values): """ Evaluate ``f`` at the give values. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y, z >>> f = Poly(2*x*y + 3*x + y + 2*z, x, y, z) >>> f(2) Poly(5*y + 2*z + 6, y, z, domain='ZZ') >>> f(2, 5) Poly(2*z + 31, z, domain='ZZ') >>> f(2, 5, 7) 45 """ return f.eval(values) def half_gcdex(f, g, auto=True): """ Half extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15 >>> g = x**3 + x**2 - 4*x - 4 >>> Poly(f).half_gcdex(Poly(g)) (Poly(-1/5*x + 3/5, x, domain='QQ'), Poly(x + 1, x, domain='QQ')) """ dom, per, F, G = f._unify(g) if auto and dom.is_Ring: F, G = F.to_field(), G.to_field() if hasattr(f.rep, 'half_gcdex'): s, h = F.half_gcdex(G) else: # pragma: no cover raise OperationNotSupported(f, 'half_gcdex') return per(s), per(h) def gcdex(f, g, auto=True): """ Extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**4 - 2*x**3 - 6*x**2 + 12*x + 15 >>> g = x**3 + x**2 - 4*x - 4 >>> Poly(f).gcdex(Poly(g)) (Poly(-1/5*x + 3/5, x, domain='QQ'), Poly(1/5*x**2 - 6/5*x + 2, x, domain='QQ'), Poly(x + 1, x, domain='QQ')) """ dom, per, F, G = f._unify(g) if auto and dom.is_Ring: F, G = F.to_field(), G.to_field() if hasattr(f.rep, 'gcdex'): s, t, h = F.gcdex(G) else: # pragma: no cover raise OperationNotSupported(f, 'gcdex') return per(s), per(t), per(h) def invert(f, g, auto=True): """ Invert ``f`` modulo ``g`` when possible. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).invert(Poly(2*x - 1, x)) Poly(-4/3, x, domain='QQ') >>> Poly(x**2 - 1, x).invert(Poly(x - 1, x)) Traceback (most recent call last): ... NotInvertible: zero divisor """ dom, per, F, G = f._unify(g) if auto and dom.is_Ring: F, G = F.to_field(), G.to_field() if hasattr(f.rep, 'invert'): result = F.invert(G) else: # pragma: no cover raise OperationNotSupported(f, 'invert') return per(result) def revert(f, n): """ Compute ``f**(-1)`` mod ``x**n``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(1, x).revert(2) Poly(1, x, domain='ZZ') >>> Poly(1 + x, x).revert(1) Poly(1, x, domain='ZZ') >>> Poly(x**2 - 2, x).revert(2) Traceback (most recent call last): ... NotReversible: only units are reversible in a ring >>> Poly(1/x, x).revert(1) Traceback (most recent call last): ... PolynomialError: 1/x contains an element of the generators set """ if hasattr(f.rep, 'revert'): result = f.rep.revert(int(n)) else: # pragma: no cover raise OperationNotSupported(f, 'revert') return f.per(result) def subresultants(f, g): """ Computes the subresultant PRS of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 1, x).subresultants(Poly(x**2 - 1, x)) [Poly(x**2 + 1, x, domain='ZZ'), Poly(x**2 - 1, x, domain='ZZ'), Poly(-2, x, domain='ZZ')] """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'subresultants'): result = F.subresultants(G) else: # pragma: no cover raise OperationNotSupported(f, 'subresultants') return list(map(per, result)) def resultant(f, g, includePRS=False): """ Computes the resultant of ``f`` and ``g`` via PRS. If includePRS=True, it includes the subresultant PRS in the result. Because the PRS is used to calculate the resultant, this is more efficient than calling :func:`subresultants` separately. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(x**2 + 1, x) >>> f.resultant(Poly(x**2 - 1, x)) 4 >>> f.resultant(Poly(x**2 - 1, x), includePRS=True) (4, [Poly(x**2 + 1, x, domain='ZZ'), Poly(x**2 - 1, x, domain='ZZ'), Poly(-2, x, domain='ZZ')]) """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'resultant'): if includePRS: result, R = F.resultant(G, includePRS=includePRS) else: result = F.resultant(G) else: # pragma: no cover raise OperationNotSupported(f, 'resultant') if includePRS: return (per(result, remove=0), list(map(per, R))) return per(result, remove=0) def discriminant(f): """ Computes the discriminant of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + 2*x + 3, x).discriminant() -8 """ if hasattr(f.rep, 'discriminant'): result = f.rep.discriminant() else: # pragma: no cover raise OperationNotSupported(f, 'discriminant') return f.per(result, remove=0) def dispersionset(f, g=None): r"""Compute the *dispersion set* of two polynomials. For two polynomials `f(x)` and `g(x)` with `\deg f > 0` and `\deg g > 0` the dispersion set `\operatorname{J}(f, g)` is defined as: .. math:: \operatorname{J}(f, g) & := \{a \in \mathbb{N}_0 | \gcd(f(x), g(x+a)) \neq 1\} \\ & = \{a \in \mathbb{N}_0 | \deg \gcd(f(x), g(x+a)) \geq 1\} For a single polynomial one defines `\operatorname{J}(f) := \operatorname{J}(f, f)`. Examples ======== >>> from sympy import poly >>> from sympy.polys.dispersion import dispersion, dispersionset >>> from sympy.abc import x Dispersion set and dispersion of a simple polynomial: >>> fp = poly((x - 3)*(x + 3), x) >>> sorted(dispersionset(fp)) [0, 6] >>> dispersion(fp) 6 Note that the definition of the dispersion is not symmetric: >>> fp = poly(x**4 - 3*x**2 + 1, x) >>> gp = fp.shift(-3) >>> sorted(dispersionset(fp, gp)) [2, 3, 4] >>> dispersion(fp, gp) 4 >>> sorted(dispersionset(gp, fp)) [] >>> dispersion(gp, fp) -oo Computing the dispersion also works over field extensions: >>> from sympy import sqrt >>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>') >>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>') >>> sorted(dispersionset(fp, gp)) [2] >>> sorted(dispersionset(gp, fp)) [1, 4] We can even perform the computations for polynomials having symbolic coefficients: >>> from sympy.abc import a >>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x) >>> sorted(dispersionset(fp)) [0, 1] See Also ======== dispersion References ========== 1. [ManWright94]_ 2. [Koepf98]_ 3. [Abramov71]_ 4. [Man93]_ """ from sympy.polys.dispersion import dispersionset return dispersionset(f, g) def dispersion(f, g=None): r"""Compute the *dispersion* of polynomials. For two polynomials `f(x)` and `g(x)` with `\deg f > 0` and `\deg g > 0` the dispersion `\operatorname{dis}(f, g)` is defined as: .. math:: \operatorname{dis}(f, g) & := \max\{ J(f,g) \cup \{0\} \} \\ & = \max\{ \{a \in \mathbb{N} | \gcd(f(x), g(x+a)) \neq 1\} \cup \{0\} \} and for a single polynomial `\operatorname{dis}(f) := \operatorname{dis}(f, f)`. Examples ======== >>> from sympy import poly >>> from sympy.polys.dispersion import dispersion, dispersionset >>> from sympy.abc import x Dispersion set and dispersion of a simple polynomial: >>> fp = poly((x - 3)*(x + 3), x) >>> sorted(dispersionset(fp)) [0, 6] >>> dispersion(fp) 6 Note that the definition of the dispersion is not symmetric: >>> fp = poly(x**4 - 3*x**2 + 1, x) >>> gp = fp.shift(-3) >>> sorted(dispersionset(fp, gp)) [2, 3, 4] >>> dispersion(fp, gp) 4 >>> sorted(dispersionset(gp, fp)) [] >>> dispersion(gp, fp) -oo Computing the dispersion also works over field extensions: >>> from sympy import sqrt >>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>') >>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>') >>> sorted(dispersionset(fp, gp)) [2] >>> sorted(dispersionset(gp, fp)) [1, 4] We can even perform the computations for polynomials having symbolic coefficients: >>> from sympy.abc import a >>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x) >>> sorted(dispersionset(fp)) [0, 1] See Also ======== dispersionset References ========== 1. [ManWright94]_ 2. [Koepf98]_ 3. [Abramov71]_ 4. [Man93]_ """ from sympy.polys.dispersion import dispersion return dispersion(f, g) def cofactors(f, g): """ Returns the GCD of ``f`` and ``g`` and their cofactors. Returns polynomials ``(h, cff, cfg)`` such that ``h = gcd(f, g)``, and ``cff = quo(f, h)`` and ``cfg = quo(g, h)`` are, so called, cofactors of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).cofactors(Poly(x**2 - 3*x + 2, x)) (Poly(x - 1, x, domain='ZZ'), Poly(x + 1, x, domain='ZZ'), Poly(x - 2, x, domain='ZZ')) """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'cofactors'): h, cff, cfg = F.cofactors(G) else: # pragma: no cover raise OperationNotSupported(f, 'cofactors') return per(h), per(cff), per(cfg) def gcd(f, g): """ Returns the polynomial GCD of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).gcd(Poly(x**2 - 3*x + 2, x)) Poly(x - 1, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'gcd'): result = F.gcd(G) else: # pragma: no cover raise OperationNotSupported(f, 'gcd') return per(result) def lcm(f, g): """ Returns polynomial LCM of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 1, x).lcm(Poly(x**2 - 3*x + 2, x)) Poly(x**3 - 2*x**2 - x + 2, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'lcm'): result = F.lcm(G) else: # pragma: no cover raise OperationNotSupported(f, 'lcm') return per(result) def trunc(f, p): """ Reduce ``f`` modulo a constant ``p``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**3 + 3*x**2 + 5*x + 7, x).trunc(3) Poly(-x**3 - x + 1, x, domain='ZZ') """ p = f.rep.dom.convert(p) if hasattr(f.rep, 'trunc'): result = f.rep.trunc(p) else: # pragma: no cover raise OperationNotSupported(f, 'trunc') return f.per(result) def monic(self, auto=True): """ Divides all coefficients by ``LC(f)``. Examples ======== >>> from sympy import Poly, ZZ >>> from sympy.abc import x >>> Poly(3*x**2 + 6*x + 9, x, domain=ZZ).monic() Poly(x**2 + 2*x + 3, x, domain='QQ') >>> Poly(3*x**2 + 4*x + 2, x, domain=ZZ).monic() Poly(x**2 + 4/3*x + 2/3, x, domain='QQ') """ f = self if auto and f.rep.dom.is_Ring: f = f.to_field() if hasattr(f.rep, 'monic'): result = f.rep.monic() else: # pragma: no cover raise OperationNotSupported(f, 'monic') return f.per(result) def content(f): """ Returns the GCD of polynomial coefficients. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(6*x**2 + 8*x + 12, x).content() 2 """ if hasattr(f.rep, 'content'): result = f.rep.content() else: # pragma: no cover raise OperationNotSupported(f, 'content') return f.rep.dom.to_sympy(result) def primitive(f): """ Returns the content and a primitive form of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**2 + 8*x + 12, x).primitive() (2, Poly(x**2 + 4*x + 6, x, domain='ZZ')) """ if hasattr(f.rep, 'primitive'): cont, result = f.rep.primitive() else: # pragma: no cover raise OperationNotSupported(f, 'primitive') return f.rep.dom.to_sympy(cont), f.per(result) def compose(f, g): """ Computes the functional composition of ``f`` and ``g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + x, x).compose(Poly(x - 1, x)) Poly(x**2 - x, x, domain='ZZ') """ _, per, F, G = f._unify(g) if hasattr(f.rep, 'compose'): result = F.compose(G) else: # pragma: no cover raise OperationNotSupported(f, 'compose') return per(result) def decompose(f): """ Computes a functional decomposition of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**4 + 2*x**3 - x - 1, x, domain='ZZ').decompose() [Poly(x**2 - x - 1, x, domain='ZZ'), Poly(x**2 + x, x, domain='ZZ')] """ if hasattr(f.rep, 'decompose'): result = f.rep.decompose() else: # pragma: no cover raise OperationNotSupported(f, 'decompose') return list(map(f.per, result)) def shift(f, a): """ Efficiently compute Taylor shift ``f(x + a)``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 2*x + 1, x).shift(2) Poly(x**2 + 2*x + 1, x, domain='ZZ') """ if hasattr(f.rep, 'shift'): result = f.rep.shift(a) else: # pragma: no cover raise OperationNotSupported(f, 'shift') return f.per(result) def transform(f, p, q): """ Efficiently evaluate the functional transformation ``q**n * f(p/q)``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1, x), Poly(x - 1, x)) Poly(4, x, domain='ZZ') """ P, Q = p.unify(q) F, P = f.unify(P) F, Q = F.unify(Q) if hasattr(F.rep, 'transform'): result = F.rep.transform(P.rep, Q.rep) else: # pragma: no cover raise OperationNotSupported(F, 'transform') return F.per(result) def sturm(self, auto=True): """ Computes the Sturm sequence of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 - 2*x**2 + x - 3, x).sturm() [Poly(x**3 - 2*x**2 + x - 3, x, domain='QQ'), Poly(3*x**2 - 4*x + 1, x, domain='QQ'), Poly(2/9*x + 25/9, x, domain='QQ'), Poly(-2079/4, x, domain='QQ')] """ f = self if auto and f.rep.dom.is_Ring: f = f.to_field() if hasattr(f.rep, 'sturm'): result = f.rep.sturm() else: # pragma: no cover raise OperationNotSupported(f, 'sturm') return list(map(f.per, result)) def gff_list(f): """ Computes greatest factorial factorization of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**5 + 2*x**4 - x**3 - 2*x**2 >>> Poly(f).gff_list() [(Poly(x, x, domain='ZZ'), 1), (Poly(x + 2, x, domain='ZZ'), 4)] """ if hasattr(f.rep, 'gff_list'): result = f.rep.gff_list() else: # pragma: no cover raise OperationNotSupported(f, 'gff_list') return [(f.per(g), k) for g, k in result] def norm(f): """ Computes the product, ``Norm(f)``, of the conjugates of a polynomial ``f`` defined over a number field ``K``. Examples ======== >>> from sympy import Poly, sqrt >>> from sympy.abc import x >>> a, b = sqrt(2), sqrt(3) A polynomial over a quadratic extension. Two conjugates x - a and x + a. >>> f = Poly(x - a, x, extension=a) >>> f.norm() Poly(x**2 - 2, x, domain='QQ') A polynomial over a quartic extension. Four conjugates x - a, x - a, x + a and x + a. >>> f = Poly(x - a, x, extension=(a, b)) >>> f.norm() Poly(x**4 - 4*x**2 + 4, x, domain='QQ') """ if hasattr(f.rep, 'norm'): r = f.rep.norm() else: # pragma: no cover raise OperationNotSupported(f, 'norm') return f.per(r) def sqf_norm(f): """ Computes square-free norm of ``f``. Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and ``r(x) = Norm(g(x))`` is a square-free polynomial over ``K``, where ``a`` is the algebraic extension of the ground domain. Examples ======== >>> from sympy import Poly, sqrt >>> from sympy.abc import x >>> s, f, r = Poly(x**2 + 1, x, extension=[sqrt(3)]).sqf_norm() >>> s 1 >>> f Poly(x**2 - 2*sqrt(3)*x + 4, x, domain='QQ<sqrt(3)>') >>> r Poly(x**4 - 4*x**2 + 16, x, domain='QQ') """ if hasattr(f.rep, 'sqf_norm'): s, g, r = f.rep.sqf_norm() else: # pragma: no cover raise OperationNotSupported(f, 'sqf_norm') return s, f.per(g), f.per(r) def sqf_part(f): """ Computes square-free part of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**3 - 3*x - 2, x).sqf_part() Poly(x**2 - x - 2, x, domain='ZZ') """ if hasattr(f.rep, 'sqf_part'): result = f.rep.sqf_part() else: # pragma: no cover raise OperationNotSupported(f, 'sqf_part') return f.per(result) def sqf_list(f, all=False): """ Returns a list of square-free factors of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = 2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16 >>> Poly(f).sqf_list() (2, [(Poly(x + 1, x, domain='ZZ'), 2), (Poly(x + 2, x, domain='ZZ'), 3)]) >>> Poly(f).sqf_list(all=True) (2, [(Poly(1, x, domain='ZZ'), 1), (Poly(x + 1, x, domain='ZZ'), 2), (Poly(x + 2, x, domain='ZZ'), 3)]) """ if hasattr(f.rep, 'sqf_list'): coeff, factors = f.rep.sqf_list(all) else: # pragma: no cover raise OperationNotSupported(f, 'sqf_list') return f.rep.dom.to_sympy(coeff), [(f.per(g), k) for g, k in factors] def sqf_list_include(f, all=False): """ Returns a list of square-free factors of ``f``. Examples ======== >>> from sympy import Poly, expand >>> from sympy.abc import x >>> f = expand(2*(x + 1)**3*x**4) >>> f 2*x**7 + 6*x**6 + 6*x**5 + 2*x**4 >>> Poly(f).sqf_list_include() [(Poly(2, x, domain='ZZ'), 1), (Poly(x + 1, x, domain='ZZ'), 3), (Poly(x, x, domain='ZZ'), 4)] >>> Poly(f).sqf_list_include(all=True) [(Poly(2, x, domain='ZZ'), 1), (Poly(1, x, domain='ZZ'), 2), (Poly(x + 1, x, domain='ZZ'), 3), (Poly(x, x, domain='ZZ'), 4)] """ if hasattr(f.rep, 'sqf_list_include'): factors = f.rep.sqf_list_include(all) else: # pragma: no cover raise OperationNotSupported(f, 'sqf_list_include') return [(f.per(g), k) for g, k in factors] def factor_list(f): """ Returns a list of irreducible factors of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y >>> Poly(f).factor_list() (2, [(Poly(x + y, x, y, domain='ZZ'), 1), (Poly(x**2 + 1, x, y, domain='ZZ'), 2)]) """ if hasattr(f.rep, 'factor_list'): try: coeff, factors = f.rep.factor_list() except DomainError: return S.One, [(f, 1)] else: # pragma: no cover raise OperationNotSupported(f, 'factor_list') return f.rep.dom.to_sympy(coeff), [(f.per(g), k) for g, k in factors] def factor_list_include(f): """ Returns a list of irreducible factors of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> f = 2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y >>> Poly(f).factor_list_include() [(Poly(2*x + 2*y, x, y, domain='ZZ'), 1), (Poly(x**2 + 1, x, y, domain='ZZ'), 2)] """ if hasattr(f.rep, 'factor_list_include'): try: factors = f.rep.factor_list_include() except DomainError: return [(f, 1)] else: # pragma: no cover raise OperationNotSupported(f, 'factor_list_include') return [(f.per(g), k) for g, k in factors] def intervals(f, all=False, eps=None, inf=None, sup=None, fast=False, sqf=False): """ Compute isolating intervals for roots of ``f``. For real roots the Vincent-Akritas-Strzebonski (VAS) continued fractions method is used. References ========== .. [#] Alkiviadis G. Akritas and Adam W. Strzebonski: A Comparative Study of Two Real Root Isolation Methods . Nonlinear Analysis: Modelling and Control, Vol. 10, No. 4, 297-304, 2005. .. [#] Alkiviadis G. Akritas, Adam W. Strzebonski and Panagiotis S. Vigklas: Improving the Performance of the Continued Fractions Method Using new Bounds of Positive Roots. Nonlinear Analysis: Modelling and Control, Vol. 13, No. 3, 265-279, 2008. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 3, x).intervals() [((-2, -1), 1), ((1, 2), 1)] >>> Poly(x**2 - 3, x).intervals(eps=1e-2) [((-26/15, -19/11), 1), ((19/11, 26/15), 1)] """ if eps is not None: eps = QQ.convert(eps) if eps <= 0: raise ValueError("'eps' must be a positive rational") if inf is not None: inf = QQ.convert(inf) if sup is not None: sup = QQ.convert(sup) if hasattr(f.rep, 'intervals'): result = f.rep.intervals( all=all, eps=eps, inf=inf, sup=sup, fast=fast, sqf=sqf) else: # pragma: no cover raise OperationNotSupported(f, 'intervals') if sqf: def _real(interval): s, t = interval return (QQ.to_sympy(s), QQ.to_sympy(t)) if not all: return list(map(_real, result)) def _complex(rectangle): (u, v), (s, t) = rectangle return (QQ.to_sympy(u) + I*QQ.to_sympy(v), QQ.to_sympy(s) + I*QQ.to_sympy(t)) real_part, complex_part = result return list(map(_real, real_part)), list(map(_complex, complex_part)) else: def _real(interval): (s, t), k = interval return ((QQ.to_sympy(s), QQ.to_sympy(t)), k) if not all: return list(map(_real, result)) def _complex(rectangle): ((u, v), (s, t)), k = rectangle return ((QQ.to_sympy(u) + I*QQ.to_sympy(v), QQ.to_sympy(s) + I*QQ.to_sympy(t)), k) real_part, complex_part = result return list(map(_real, real_part)), list(map(_complex, complex_part)) def refine_root(f, s, t, eps=None, steps=None, fast=False, check_sqf=False): """ Refine an isolating interval of a root to the given precision. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 3, x).refine_root(1, 2, eps=1e-2) (19/11, 26/15) """ if check_sqf and not f.is_sqf: raise PolynomialError("only square-free polynomials supported") s, t = QQ.convert(s), QQ.convert(t) if eps is not None: eps = QQ.convert(eps) if eps <= 0: raise ValueError("'eps' must be a positive rational") if steps is not None: steps = int(steps) elif eps is None: steps = 1 if hasattr(f.rep, 'refine_root'): S, T = f.rep.refine_root(s, t, eps=eps, steps=steps, fast=fast) else: # pragma: no cover raise OperationNotSupported(f, 'refine_root') return QQ.to_sympy(S), QQ.to_sympy(T) def count_roots(f, inf=None, sup=None): """ Return the number of roots of ``f`` in ``[inf, sup]`` interval. Examples ======== >>> from sympy import Poly, I >>> from sympy.abc import x >>> Poly(x**4 - 4, x).count_roots(-3, 3) 2 >>> Poly(x**4 - 4, x).count_roots(0, 1 + 3*I) 1 """ inf_real, sup_real = True, True if inf is not None: inf = sympify(inf) if inf is S.NegativeInfinity: inf = None else: re, im = inf.as_real_imag() if not im: inf = QQ.convert(inf) else: inf, inf_real = list(map(QQ.convert, (re, im))), False if sup is not None: sup = sympify(sup) if sup is S.Infinity: sup = None else: re, im = sup.as_real_imag() if not im: sup = QQ.convert(sup) else: sup, sup_real = list(map(QQ.convert, (re, im))), False if inf_real and sup_real: if hasattr(f.rep, 'count_real_roots'): count = f.rep.count_real_roots(inf=inf, sup=sup) else: # pragma: no cover raise OperationNotSupported(f, 'count_real_roots') else: if inf_real and inf is not None: inf = (inf, QQ.zero) if sup_real and sup is not None: sup = (sup, QQ.zero) if hasattr(f.rep, 'count_complex_roots'): count = f.rep.count_complex_roots(inf=inf, sup=sup) else: # pragma: no cover raise OperationNotSupported(f, 'count_complex_roots') return Integer(count) def root(f, index, radicals=True): """ Get an indexed root of a polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(2*x**3 - 7*x**2 + 4*x + 4) >>> f.root(0) -1/2 >>> f.root(1) 2 >>> f.root(2) 2 >>> f.root(3) Traceback (most recent call last): ... IndexError: root index out of [-3, 2] range, got 3 >>> Poly(x**5 + x + 1).root(0) CRootOf(x**3 - x**2 + 1, 0) """ return sympy.polys.rootoftools.rootof(f, index, radicals=radicals) def real_roots(f, multiple=True, radicals=True): """ Return a list of real roots with multiplicities. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**3 - 7*x**2 + 4*x + 4).real_roots() [-1/2, 2, 2] >>> Poly(x**3 + x + 1).real_roots() [CRootOf(x**3 + x + 1, 0)] """ reals = sympy.polys.rootoftools.CRootOf.real_roots(f, radicals=radicals) if multiple: return reals else: return group(reals, multiple=False) def all_roots(f, multiple=True, radicals=True): """ Return a list of real and complex roots with multiplicities. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**3 - 7*x**2 + 4*x + 4).all_roots() [-1/2, 2, 2] >>> Poly(x**3 + x + 1).all_roots() [CRootOf(x**3 + x + 1, 0), CRootOf(x**3 + x + 1, 1), CRootOf(x**3 + x + 1, 2)] """ roots = sympy.polys.rootoftools.CRootOf.all_roots(f, radicals=radicals) if multiple: return roots else: return group(roots, multiple=False) def nroots(f, n=15, maxsteps=50, cleanup=True): """ Compute numerical approximations of roots of ``f``. Parameters ========== n ... the number of digits to calculate maxsteps ... the maximum number of iterations to do If the accuracy `n` cannot be reached in `maxsteps`, it will raise an exception. You need to rerun with higher maxsteps. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 3).nroots(n=15) [-1.73205080756888, 1.73205080756888] >>> Poly(x**2 - 3).nroots(n=30) [-1.73205080756887729352744634151, 1.73205080756887729352744634151] """ if f.is_multivariate: raise MultivariatePolynomialError( "Cannot compute numerical roots of %s" % f) if f.degree() <= 0: return [] # For integer and rational coefficients, convert them to integers only # (for accuracy). Otherwise just try to convert the coefficients to # mpmath.mpc and raise an exception if the conversion fails. if f.rep.dom is ZZ: coeffs = [int(coeff) for coeff in f.all_coeffs()] elif f.rep.dom is QQ: denoms = [coeff.q for coeff in f.all_coeffs()] fac = ilcm(*denoms) coeffs = [int(coeff*fac) for coeff in f.all_coeffs()] else: coeffs = [coeff.evalf(n=n).as_real_imag() for coeff in f.all_coeffs()] try: coeffs = [mpmath.mpc(*coeff) for coeff in coeffs] except TypeError: raise DomainError("Numerical domain expected, got %s" % \ f.rep.dom) dps = mpmath.mp.dps mpmath.mp.dps = n from sympy.functions.elementary.complexes import sign try: # We need to add extra precision to guard against losing accuracy. # 10 times the degree of the polynomial seems to work well. roots = mpmath.polyroots(coeffs, maxsteps=maxsteps, cleanup=cleanup, error=False, extraprec=f.degree()*10) # Mpmath puts real roots first, then complex ones (as does all_roots) # so we make sure this convention holds here, too. roots = list(map(sympify, sorted(roots, key=lambda r: (1 if r.imag else 0, r.real, abs(r.imag), sign(r.imag))))) except NoConvergence: try: # If roots did not converge try again with more extra precision. roots = mpmath.polyroots(coeffs, maxsteps=maxsteps, cleanup=cleanup, error=False, extraprec=f.degree()*15) roots = list(map(sympify, sorted(roots, key=lambda r: (1 if r.imag else 0, r.real, abs(r.imag), sign(r.imag))))) except NoConvergence: raise NoConvergence( 'convergence to root failed; try n < %s or maxsteps > %s' % ( n, maxsteps)) finally: mpmath.mp.dps = dps return roots def ground_roots(f): """ Compute roots of ``f`` by factorization in the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**6 - 4*x**4 + 4*x**3 - x**2).ground_roots() {0: 2, 1: 2} """ if f.is_multivariate: raise MultivariatePolynomialError( "Cannot compute ground roots of %s" % f) roots = {} for factor, k in f.factor_list()[1]: if factor.is_linear: a, b = factor.all_coeffs() roots[-b/a] = k return roots def nth_power_roots_poly(f, n): """ Construct a polynomial with n-th powers of roots of ``f``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = Poly(x**4 - x**2 + 1) >>> f.nth_power_roots_poly(2) Poly(x**4 - 2*x**3 + 3*x**2 - 2*x + 1, x, domain='ZZ') >>> f.nth_power_roots_poly(3) Poly(x**4 + 2*x**2 + 1, x, domain='ZZ') >>> f.nth_power_roots_poly(4) Poly(x**4 + 2*x**3 + 3*x**2 + 2*x + 1, x, domain='ZZ') >>> f.nth_power_roots_poly(12) Poly(x**4 - 4*x**3 + 6*x**2 - 4*x + 1, x, domain='ZZ') """ if f.is_multivariate: raise MultivariatePolynomialError( "must be a univariate polynomial") N = sympify(n) if N.is_Integer and N >= 1: n = int(N) else: raise ValueError("'n' must an integer and n >= 1, got %s" % n) x = f.gen t = Dummy('t') r = f.resultant(f.__class__.from_expr(x**n - t, x, t)) return r.replace(t, x) def same_root(f, a, b): """ Decide whether two roots of this polynomial are equal. Examples ======== >>> from sympy import Poly, cyclotomic_poly, exp, I, pi >>> f = Poly(cyclotomic_poly(5)) >>> r0 = exp(2*I*pi/5) >>> indices = [i for i, r in enumerate(f.all_roots()) if f.same_root(r, r0)] >>> print(indices) [3] Raises ====== DomainError If the domain of the polynomial is not :ref:`ZZ`, :ref:`QQ`, :ref:`RR`, or :ref:`CC`. MultivariatePolynomialError If the polynomial is not univariate. PolynomialError If the polynomial is of degree < 2. """ if f.is_multivariate: raise MultivariatePolynomialError( "Must be a univariate polynomial") dom_delta_sq = f.rep.mignotte_sep_bound_squared() delta_sq = f.domain.get_field().to_sympy(dom_delta_sq) # We have delta_sq = delta**2, where delta is a lower bound on the # minimum separation between any two roots of this polynomial. # Let eps = delta/3, and define eps_sq = eps**2 = delta**2/9. eps_sq = delta_sq / 9 r, _, _, _ = evalf(1/eps_sq, 1, {}) n = fastlog(r) # Then 2^n > 1/eps**2. m = (n // 2) + (n % 2) # Then 2^(-m) < eps. ev = lambda x: quad_to_mpmath(_evalf_with_bounded_error(x, m=m)) # Then for any complex numbers a, b we will have # |a - ev(a)| < eps and |b - ev(b)| < eps. # So if |ev(a) - ev(b)|**2 < eps**2, then # |ev(a) - ev(b)| < eps, hence |a - b| < 3*eps = delta. A, B = ev(a), ev(b) return (A.real - B.real)**2 + (A.imag - B.imag)**2 < eps_sq def cancel(f, g, include=False): """ Cancel common factors in a rational function ``f/g``. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x)) (1, Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ')) >>> Poly(2*x**2 - 2, x).cancel(Poly(x**2 - 2*x + 1, x), include=True) (Poly(2*x + 2, x, domain='ZZ'), Poly(x - 1, x, domain='ZZ')) """ dom, per, F, G = f._unify(g) if hasattr(F, 'cancel'): result = F.cancel(G, include=include) else: # pragma: no cover raise OperationNotSupported(f, 'cancel') if not include: if dom.has_assoc_Ring: dom = dom.get_ring() cp, cq, p, q = result cp = dom.to_sympy(cp) cq = dom.to_sympy(cq) return cp/cq, per(p), per(q) else: return tuple(map(per, result)) @property def is_zero(f): """ Returns ``True`` if ``f`` is a zero polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(0, x).is_zero True >>> Poly(1, x).is_zero False """ return f.rep.is_zero @property def is_one(f): """ Returns ``True`` if ``f`` is a unit polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(0, x).is_one False >>> Poly(1, x).is_one True """ return f.rep.is_one @property def is_sqf(f): """ Returns ``True`` if ``f`` is a square-free polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 - 2*x + 1, x).is_sqf False >>> Poly(x**2 - 1, x).is_sqf True """ return f.rep.is_sqf @property def is_monic(f): """ Returns ``True`` if the leading coefficient of ``f`` is one. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x + 2, x).is_monic True >>> Poly(2*x + 2, x).is_monic False """ return f.rep.is_monic @property def is_primitive(f): """ Returns ``True`` if GCD of the coefficients of ``f`` is one. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(2*x**2 + 6*x + 12, x).is_primitive False >>> Poly(x**2 + 3*x + 6, x).is_primitive True """ return f.rep.is_primitive @property def is_ground(f): """ Returns ``True`` if ``f`` is an element of the ground domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x, x).is_ground False >>> Poly(2, x).is_ground True >>> Poly(y, x).is_ground True """ return f.rep.is_ground @property def is_linear(f): """ Returns ``True`` if ``f`` is linear in all its variables. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x + y + 2, x, y).is_linear True >>> Poly(x*y + 2, x, y).is_linear False """ return f.rep.is_linear @property def is_quadratic(f): """ Returns ``True`` if ``f`` is quadratic in all its variables. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x*y + 2, x, y).is_quadratic True >>> Poly(x*y**2 + 2, x, y).is_quadratic False """ return f.rep.is_quadratic @property def is_monomial(f): """ Returns ``True`` if ``f`` is zero or has only one term. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(3*x**2, x).is_monomial True >>> Poly(3*x**2 + 1, x).is_monomial False """ return f.rep.is_monomial @property def is_homogeneous(f): """ Returns ``True`` if ``f`` is a homogeneous polynomial. A homogeneous polynomial is a polynomial whose all monomials with non-zero coefficients have the same total degree. If you want not only to check if a polynomial is homogeneous but also compute its homogeneous order, then use :func:`Poly.homogeneous_order`. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x*y, x, y).is_homogeneous True >>> Poly(x**3 + x*y, x, y).is_homogeneous False """ return f.rep.is_homogeneous @property def is_irreducible(f): """ Returns ``True`` if ``f`` has no factors over its domain. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> Poly(x**2 + x + 1, x, modulus=2).is_irreducible True >>> Poly(x**2 + 1, x, modulus=2).is_irreducible False """ return f.rep.is_irreducible @property def is_univariate(f): """ Returns ``True`` if ``f`` is a univariate polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x + 1, x).is_univariate True >>> Poly(x*y**2 + x*y + 1, x, y).is_univariate False >>> Poly(x*y**2 + x*y + 1, x).is_univariate True >>> Poly(x**2 + x + 1, x, y).is_univariate False """ return len(f.gens) == 1 @property def is_multivariate(f): """ Returns ``True`` if ``f`` is a multivariate polynomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x, y >>> Poly(x**2 + x + 1, x).is_multivariate False >>> Poly(x*y**2 + x*y + 1, x, y).is_multivariate True >>> Poly(x*y**2 + x*y + 1, x).is_multivariate False >>> Poly(x**2 + x + 1, x, y).is_multivariate True """ return len(f.gens) != 1 @property def is_cyclotomic(f): """ Returns ``True`` if ``f`` is a cyclotomic polnomial. Examples ======== >>> from sympy import Poly >>> from sympy.abc import x >>> f = x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1 >>> Poly(f).is_cyclotomic False >>> g = x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1 >>> Poly(g).is_cyclotomic True """ return f.rep.is_cyclotomic def __abs__(f): return f.abs() def __neg__(f): return f.neg() @_polifyit def __add__(f, g): return f.add(g) @_polifyit def __radd__(f, g): return g.add(f) @_polifyit def __sub__(f, g): return f.sub(g) @_polifyit def __rsub__(f, g): return g.sub(f) @_polifyit def __mul__(f, g): return f.mul(g) @_polifyit def __rmul__(f, g): return g.mul(f) @_sympifyit('n', NotImplemented) def __pow__(f, n): if n.is_Integer and n >= 0: return f.pow(n) else: return NotImplemented @_polifyit def __divmod__(f, g): return f.div(g) @_polifyit def __rdivmod__(f, g): return g.div(f) @_polifyit def __mod__(f, g): return f.rem(g) @_polifyit def __rmod__(f, g): return g.rem(f) @_polifyit def __floordiv__(f, g): return f.quo(g) @_polifyit def __rfloordiv__(f, g): return g.quo(f) @_sympifyit('g', NotImplemented) def __truediv__(f, g): return f.as_expr()/g.as_expr() @_sympifyit('g', NotImplemented) def __rtruediv__(f, g): return g.as_expr()/f.as_expr() @_sympifyit('other', NotImplemented) def __eq__(self, other): f, g = self, other if not g.is_Poly: try: g = f.__class__(g, f.gens, domain=f.get_domain()) except (PolynomialError, DomainError, CoercionFailed): return False if f.gens != g.gens: return False if f.rep.dom != g.rep.dom: return False return f.rep == g.rep @_sympifyit('g', NotImplemented) def __ne__(f, g): return not f == g def __bool__(f): return not f.is_zero def eq(f, g, strict=False): if not strict: return f == g else: return f._strict_eq(sympify(g)) def ne(f, g, strict=False): return not f.eq(g, strict=strict) def _strict_eq(f, g): return isinstance(g, f.__class__) and f.gens == g.gens and f.rep.eq(g.rep, strict=True) @public class PurePoly(Poly): """Class for representing pure polynomials. """ def _hashable_content(self): """Allow SymPy to hash Poly instances. """ return (self.rep,) def __hash__(self): return super().__hash__() @property def free_symbols(self): """ Free symbols of a polynomial. Examples ======== >>> from sympy import PurePoly >>> from sympy.abc import x, y >>> PurePoly(x**2 + 1).free_symbols set() >>> PurePoly(x**2 + y).free_symbols set() >>> PurePoly(x**2 + y, x).free_symbols {y} """ return self.free_symbols_in_domain @_sympifyit('other', NotImplemented) def __eq__(self, other): f, g = self, other if not g.is_Poly: try: g = f.__class__(g, f.gens, domain=f.get_domain()) except (PolynomialError, DomainError, CoercionFailed): return False if len(f.gens) != len(g.gens): return False if f.rep.dom != g.rep.dom: try: dom = f.rep.dom.unify(g.rep.dom, f.gens) except UnificationFailed: return False f = f.set_domain(dom) g = g.set_domain(dom) return f.rep == g.rep def _strict_eq(f, g): return isinstance(g, f.__class__) and f.rep.eq(g.rep, strict=True) def _unify(f, g): g = sympify(g) if not g.is_Poly: try: return f.rep.dom, f.per, f.rep, f.rep.per(f.rep.dom.from_sympy(g)) except CoercionFailed: raise UnificationFailed("Cannot unify %s with %s" % (f, g)) if len(f.gens) != len(g.gens): raise UnificationFailed("Cannot unify %s with %s" % (f, g)) if not (isinstance(f.rep, DMP) and isinstance(g.rep, DMP)): raise UnificationFailed("Cannot unify %s with %s" % (f, g)) cls = f.__class__ gens = f.gens dom = f.rep.dom.unify(g.rep.dom, gens) F = f.rep.convert(dom) G = g.rep.convert(dom) def per(rep, dom=dom, gens=gens, remove=None): if remove is not None: gens = gens[:remove] + gens[remove + 1:] if not gens: return dom.to_sympy(rep) return cls.new(rep, *gens) return dom, per, F, G @public def poly_from_expr(expr, *gens, **args): """Construct a polynomial from an expression. """ opt = options.build_options(gens, args) return _poly_from_expr(expr, opt) def _poly_from_expr(expr, opt): """Construct a polynomial from an expression. """ orig, expr = expr, sympify(expr) if not isinstance(expr, Basic): raise PolificationFailed(opt, orig, expr) elif expr.is_Poly: poly = expr.__class__._from_poly(expr, opt) opt.gens = poly.gens opt.domain = poly.domain if opt.polys is None: opt.polys = True return poly, opt elif opt.expand: expr = expr.expand() rep, opt = _dict_from_expr(expr, opt) if not opt.gens: raise PolificationFailed(opt, orig, expr) monoms, coeffs = list(zip(*list(rep.items()))) domain = opt.domain if domain is None: opt.domain, coeffs = construct_domain(coeffs, opt=opt) else: coeffs = list(map(domain.from_sympy, coeffs)) rep = dict(list(zip(monoms, coeffs))) poly = Poly._from_dict(rep, opt) if opt.polys is None: opt.polys = False return poly, opt @public def parallel_poly_from_expr(exprs, *gens, **args): """Construct polynomials from expressions. """ opt = options.build_options(gens, args) return _parallel_poly_from_expr(exprs, opt) def _parallel_poly_from_expr(exprs, opt): """Construct polynomials from expressions. """ if len(exprs) == 2: f, g = exprs if isinstance(f, Poly) and isinstance(g, Poly): f = f.__class__._from_poly(f, opt) g = g.__class__._from_poly(g, opt) f, g = f.unify(g) opt.gens = f.gens opt.domain = f.domain if opt.polys is None: opt.polys = True return [f, g], opt origs, exprs = list(exprs), [] _exprs, _polys = [], [] failed = False for i, expr in enumerate(origs): expr = sympify(expr) if isinstance(expr, Basic): if expr.is_Poly: _polys.append(i) else: _exprs.append(i) if opt.expand: expr = expr.expand() else: failed = True exprs.append(expr) if failed: raise PolificationFailed(opt, origs, exprs, True) if _polys: # XXX: this is a temporary solution for i in _polys: exprs[i] = exprs[i].as_expr() reps, opt = _parallel_dict_from_expr(exprs, opt) if not opt.gens: raise PolificationFailed(opt, origs, exprs, True) from sympy.functions.elementary.piecewise import Piecewise for k in opt.gens: if isinstance(k, Piecewise): raise PolynomialError("Piecewise generators do not make sense") coeffs_list, lengths = [], [] all_monoms = [] all_coeffs = [] for rep in reps: monoms, coeffs = list(zip(*list(rep.items()))) coeffs_list.extend(coeffs) all_monoms.append(monoms) lengths.append(len(coeffs)) domain = opt.domain if domain is None: opt.domain, coeffs_list = construct_domain(coeffs_list, opt=opt) else: coeffs_list = list(map(domain.from_sympy, coeffs_list)) for k in lengths: all_coeffs.append(coeffs_list[:k]) coeffs_list = coeffs_list[k:] polys = [] for monoms, coeffs in zip(all_monoms, all_coeffs): rep = dict(list(zip(monoms, coeffs))) poly = Poly._from_dict(rep, opt) polys.append(poly) if opt.polys is None: opt.polys = bool(_polys) return polys, opt def _update_args(args, key, value): """Add a new ``(key, value)`` pair to arguments ``dict``. """ args = dict(args) if key not in args: args[key] = value return args @public def degree(f, gen=0): """ Return the degree of ``f`` in the given variable. The degree of 0 is negative infinity. Examples ======== >>> from sympy import degree >>> from sympy.abc import x, y >>> degree(x**2 + y*x + 1, gen=x) 2 >>> degree(x**2 + y*x + 1, gen=y) 1 >>> degree(0, x) -oo See also ======== sympy.polys.polytools.Poly.total_degree degree_list """ f = sympify(f, strict=True) gen_is_Num = sympify(gen, strict=True).is_Number if f.is_Poly: p = f isNum = p.as_expr().is_Number else: isNum = f.is_Number if not isNum: if gen_is_Num: p, _ = poly_from_expr(f) else: p, _ = poly_from_expr(f, gen) if isNum: return S.Zero if f else S.NegativeInfinity if not gen_is_Num: if f.is_Poly and gen not in p.gens: # try recast without explicit gens p, _ = poly_from_expr(f.as_expr()) if gen not in p.gens: return S.Zero elif not f.is_Poly and len(f.free_symbols) > 1: raise TypeError(filldedent(''' A symbolic generator of interest is required for a multivariate expression like func = %s, e.g. degree(func, gen = %s) instead of degree(func, gen = %s). ''' % (f, next(ordered(f.free_symbols)), gen))) result = p.degree(gen) return Integer(result) if isinstance(result, int) else S.NegativeInfinity @public def total_degree(f, *gens): """ Return the total_degree of ``f`` in the given variables. Examples ======== >>> from sympy import total_degree, Poly >>> from sympy.abc import x, y >>> total_degree(1) 0 >>> total_degree(x + x*y) 2 >>> total_degree(x + x*y, x) 1 If the expression is a Poly and no variables are given then the generators of the Poly will be used: >>> p = Poly(x + x*y, y) >>> total_degree(p) 1 To deal with the underlying expression of the Poly, convert it to an Expr: >>> total_degree(p.as_expr()) 2 This is done automatically if any variables are given: >>> total_degree(p, x) 1 See also ======== degree """ p = sympify(f) if p.is_Poly: p = p.as_expr() if p.is_Number: rv = 0 else: if f.is_Poly: gens = gens or f.gens rv = Poly(p, gens).total_degree() return Integer(rv) @public def degree_list(f, *gens, **args): """ Return a list of degrees of ``f`` in all variables. Examples ======== >>> from sympy import degree_list >>> from sympy.abc import x, y >>> degree_list(x**2 + y*x + 1) (2, 1) """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('degree_list', 1, exc) degrees = F.degree_list() return tuple(map(Integer, degrees)) @public def LC(f, *gens, **args): """ Return the leading coefficient of ``f``. Examples ======== >>> from sympy import LC >>> from sympy.abc import x, y >>> LC(4*x**2 + 2*x*y**2 + x*y + 3*y) 4 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('LC', 1, exc) return F.LC(order=opt.order) @public def LM(f, *gens, **args): """ Return the leading monomial of ``f``. Examples ======== >>> from sympy import LM >>> from sympy.abc import x, y >>> LM(4*x**2 + 2*x*y**2 + x*y + 3*y) x**2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('LM', 1, exc) monom = F.LM(order=opt.order) return monom.as_expr() @public def LT(f, *gens, **args): """ Return the leading term of ``f``. Examples ======== >>> from sympy import LT >>> from sympy.abc import x, y >>> LT(4*x**2 + 2*x*y**2 + x*y + 3*y) 4*x**2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('LT', 1, exc) monom, coeff = F.LT(order=opt.order) return coeff*monom.as_expr() @public def pdiv(f, g, *gens, **args): """ Compute polynomial pseudo-division of ``f`` and ``g``. Examples ======== >>> from sympy import pdiv >>> from sympy.abc import x >>> pdiv(x**2 + 1, 2*x - 4) (2*x + 4, 20) """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('pdiv', 2, exc) q, r = F.pdiv(G) if not opt.polys: return q.as_expr(), r.as_expr() else: return q, r @public def prem(f, g, *gens, **args): """ Compute polynomial pseudo-remainder of ``f`` and ``g``. Examples ======== >>> from sympy import prem >>> from sympy.abc import x >>> prem(x**2 + 1, 2*x - 4) 20 """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('prem', 2, exc) r = F.prem(G) if not opt.polys: return r.as_expr() else: return r @public def pquo(f, g, *gens, **args): """ Compute polynomial pseudo-quotient of ``f`` and ``g``. Examples ======== >>> from sympy import pquo >>> from sympy.abc import x >>> pquo(x**2 + 1, 2*x - 4) 2*x + 4 >>> pquo(x**2 - 1, 2*x - 1) 2*x + 1 """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('pquo', 2, exc) try: q = F.pquo(G) except ExactQuotientFailed: raise ExactQuotientFailed(f, g) if not opt.polys: return q.as_expr() else: return q @public def pexquo(f, g, *gens, **args): """ Compute polynomial exact pseudo-quotient of ``f`` and ``g``. Examples ======== >>> from sympy import pexquo >>> from sympy.abc import x >>> pexquo(x**2 - 1, 2*x - 2) 2*x + 2 >>> pexquo(x**2 + 1, 2*x - 4) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('pexquo', 2, exc) q = F.pexquo(G) if not opt.polys: return q.as_expr() else: return q @public def div(f, g, *gens, **args): """ Compute polynomial division of ``f`` and ``g``. Examples ======== >>> from sympy import div, ZZ, QQ >>> from sympy.abc import x >>> div(x**2 + 1, 2*x - 4, domain=ZZ) (0, x**2 + 1) >>> div(x**2 + 1, 2*x - 4, domain=QQ) (x/2 + 1, 5) """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('div', 2, exc) q, r = F.div(G, auto=opt.auto) if not opt.polys: return q.as_expr(), r.as_expr() else: return q, r @public def rem(f, g, *gens, **args): """ Compute polynomial remainder of ``f`` and ``g``. Examples ======== >>> from sympy import rem, ZZ, QQ >>> from sympy.abc import x >>> rem(x**2 + 1, 2*x - 4, domain=ZZ) x**2 + 1 >>> rem(x**2 + 1, 2*x - 4, domain=QQ) 5 """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('rem', 2, exc) r = F.rem(G, auto=opt.auto) if not opt.polys: return r.as_expr() else: return r @public def quo(f, g, *gens, **args): """ Compute polynomial quotient of ``f`` and ``g``. Examples ======== >>> from sympy import quo >>> from sympy.abc import x >>> quo(x**2 + 1, 2*x - 4) x/2 + 1 >>> quo(x**2 - 1, x - 1) x + 1 """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('quo', 2, exc) q = F.quo(G, auto=opt.auto) if not opt.polys: return q.as_expr() else: return q @public def exquo(f, g, *gens, **args): """ Compute polynomial exact quotient of ``f`` and ``g``. Examples ======== >>> from sympy import exquo >>> from sympy.abc import x >>> exquo(x**2 - 1, x - 1) x + 1 >>> exquo(x**2 + 1, 2*x - 4) Traceback (most recent call last): ... ExactQuotientFailed: 2*x - 4 does not divide x**2 + 1 """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('exquo', 2, exc) q = F.exquo(G, auto=opt.auto) if not opt.polys: return q.as_expr() else: return q @public def half_gcdex(f, g, *gens, **args): """ Half extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, h)`` such that ``h = gcd(f, g)`` and ``s*f = h (mod g)``. Examples ======== >>> from sympy import half_gcdex >>> from sympy.abc import x >>> half_gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4) (3/5 - x/5, x + 1) """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: domain, (a, b) = construct_domain(exc.exprs) try: s, h = domain.half_gcdex(a, b) except NotImplementedError: raise ComputationFailed('half_gcdex', 2, exc) else: return domain.to_sympy(s), domain.to_sympy(h) s, h = F.half_gcdex(G, auto=opt.auto) if not opt.polys: return s.as_expr(), h.as_expr() else: return s, h @public def gcdex(f, g, *gens, **args): """ Extended Euclidean algorithm of ``f`` and ``g``. Returns ``(s, t, h)`` such that ``h = gcd(f, g)`` and ``s*f + t*g = h``. Examples ======== >>> from sympy import gcdex >>> from sympy.abc import x >>> gcdex(x**4 - 2*x**3 - 6*x**2 + 12*x + 15, x**3 + x**2 - 4*x - 4) (3/5 - x/5, x**2/5 - 6*x/5 + 2, x + 1) """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: domain, (a, b) = construct_domain(exc.exprs) try: s, t, h = domain.gcdex(a, b) except NotImplementedError: raise ComputationFailed('gcdex', 2, exc) else: return domain.to_sympy(s), domain.to_sympy(t), domain.to_sympy(h) s, t, h = F.gcdex(G, auto=opt.auto) if not opt.polys: return s.as_expr(), t.as_expr(), h.as_expr() else: return s, t, h @public def invert(f, g, *gens, **args): """ Invert ``f`` modulo ``g`` when possible. Examples ======== >>> from sympy import invert, S, mod_inverse >>> from sympy.abc import x >>> invert(x**2 - 1, 2*x - 1) -4/3 >>> invert(x**2 - 1, x - 1) Traceback (most recent call last): ... NotInvertible: zero divisor For more efficient inversion of Rationals, use the :obj:`~.mod_inverse` function: >>> mod_inverse(3, 5) 2 >>> (S(2)/5).invert(S(7)/3) 5/2 See Also ======== sympy.core.numbers.mod_inverse """ options.allowed_flags(args, ['auto', 'polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: domain, (a, b) = construct_domain(exc.exprs) try: return domain.to_sympy(domain.invert(a, b)) except NotImplementedError: raise ComputationFailed('invert', 2, exc) h = F.invert(G, auto=opt.auto) if not opt.polys: return h.as_expr() else: return h @public def subresultants(f, g, *gens, **args): """ Compute subresultant PRS of ``f`` and ``g``. Examples ======== >>> from sympy import subresultants >>> from sympy.abc import x >>> subresultants(x**2 + 1, x**2 - 1) [x**2 + 1, x**2 - 1, -2] """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('subresultants', 2, exc) result = F.subresultants(G) if not opt.polys: return [r.as_expr() for r in result] else: return result @public def resultant(f, g, *gens, includePRS=False, **args): """ Compute resultant of ``f`` and ``g``. Examples ======== >>> from sympy import resultant >>> from sympy.abc import x >>> resultant(x**2 + 1, x**2 - 1) 4 """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('resultant', 2, exc) if includePRS: result, R = F.resultant(G, includePRS=includePRS) else: result = F.resultant(G) if not opt.polys: if includePRS: return result.as_expr(), [r.as_expr() for r in R] return result.as_expr() else: if includePRS: return result, R return result @public def discriminant(f, *gens, **args): """ Compute discriminant of ``f``. Examples ======== >>> from sympy import discriminant >>> from sympy.abc import x >>> discriminant(x**2 + 2*x + 3) -8 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('discriminant', 1, exc) result = F.discriminant() if not opt.polys: return result.as_expr() else: return result @public def cofactors(f, g, *gens, **args): """ Compute GCD and cofactors of ``f`` and ``g``. Returns polynomials ``(h, cff, cfg)`` such that ``h = gcd(f, g)``, and ``cff = quo(f, h)`` and ``cfg = quo(g, h)`` are, so called, cofactors of ``f`` and ``g``. Examples ======== >>> from sympy import cofactors >>> from sympy.abc import x >>> cofactors(x**2 - 1, x**2 - 3*x + 2) (x - 1, x + 1, x - 2) """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: domain, (a, b) = construct_domain(exc.exprs) try: h, cff, cfg = domain.cofactors(a, b) except NotImplementedError: raise ComputationFailed('cofactors', 2, exc) else: return domain.to_sympy(h), domain.to_sympy(cff), domain.to_sympy(cfg) h, cff, cfg = F.cofactors(G) if not opt.polys: return h.as_expr(), cff.as_expr(), cfg.as_expr() else: return h, cff, cfg @public def gcd_list(seq, *gens, **args): """ Compute GCD of a list of polynomials. Examples ======== >>> from sympy import gcd_list >>> from sympy.abc import x >>> gcd_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2]) x - 1 """ seq = sympify(seq) def try_non_polynomial_gcd(seq): if not gens and not args: domain, numbers = construct_domain(seq) if not numbers: return domain.zero elif domain.is_Numerical: result, numbers = numbers[0], numbers[1:] for number in numbers: result = domain.gcd(result, number) if domain.is_one(result): break return domain.to_sympy(result) return None result = try_non_polynomial_gcd(seq) if result is not None: return result options.allowed_flags(args, ['polys']) try: polys, opt = parallel_poly_from_expr(seq, *gens, **args) # gcd for domain Q[irrational] (purely algebraic irrational) if len(seq) > 1 and all(elt.is_algebraic and elt.is_irrational for elt in seq): a = seq[-1] lst = [ (a/elt).ratsimp() for elt in seq[:-1] ] if all(frc.is_rational for frc in lst): lc = 1 for frc in lst: lc = lcm(lc, frc.as_numer_denom()[0]) # abs ensures that the gcd is always non-negative return abs(a/lc) except PolificationFailed as exc: result = try_non_polynomial_gcd(exc.exprs) if result is not None: return result else: raise ComputationFailed('gcd_list', len(seq), exc) if not polys: if not opt.polys: return S.Zero else: return Poly(0, opt=opt) result, polys = polys[0], polys[1:] for poly in polys: result = result.gcd(poly) if result.is_one: break if not opt.polys: return result.as_expr() else: return result @public def gcd(f, g=None, *gens, **args): """ Compute GCD of ``f`` and ``g``. Examples ======== >>> from sympy import gcd >>> from sympy.abc import x >>> gcd(x**2 - 1, x**2 - 3*x + 2) x - 1 """ if hasattr(f, '__iter__'): if g is not None: gens = (g,) + gens return gcd_list(f, *gens, **args) elif g is None: raise TypeError("gcd() takes 2 arguments or a sequence of arguments") options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) # gcd for domain Q[irrational] (purely algebraic irrational) a, b = map(sympify, (f, g)) if a.is_algebraic and a.is_irrational and b.is_algebraic and b.is_irrational: frc = (a/b).ratsimp() if frc.is_rational: # abs ensures that the returned gcd is always non-negative return abs(a/frc.as_numer_denom()[0]) except PolificationFailed as exc: domain, (a, b) = construct_domain(exc.exprs) try: return domain.to_sympy(domain.gcd(a, b)) except NotImplementedError: raise ComputationFailed('gcd', 2, exc) result = F.gcd(G) if not opt.polys: return result.as_expr() else: return result @public def lcm_list(seq, *gens, **args): """ Compute LCM of a list of polynomials. Examples ======== >>> from sympy import lcm_list >>> from sympy.abc import x >>> lcm_list([x**3 - 1, x**2 - 1, x**2 - 3*x + 2]) x**5 - x**4 - 2*x**3 - x**2 + x + 2 """ seq = sympify(seq) def try_non_polynomial_lcm(seq) -> Optional[Expr]: if not gens and not args: domain, numbers = construct_domain(seq) if not numbers: return domain.to_sympy(domain.one) elif domain.is_Numerical: result, numbers = numbers[0], numbers[1:] for number in numbers: result = domain.lcm(result, number) return domain.to_sympy(result) return None result = try_non_polynomial_lcm(seq) if result is not None: return result options.allowed_flags(args, ['polys']) try: polys, opt = parallel_poly_from_expr(seq, *gens, **args) # lcm for domain Q[irrational] (purely algebraic irrational) if len(seq) > 1 and all(elt.is_algebraic and elt.is_irrational for elt in seq): a = seq[-1] lst = [ (a/elt).ratsimp() for elt in seq[:-1] ] if all(frc.is_rational for frc in lst): lc = 1 for frc in lst: lc = lcm(lc, frc.as_numer_denom()[1]) return a*lc except PolificationFailed as exc: result = try_non_polynomial_lcm(exc.exprs) if result is not None: return result else: raise ComputationFailed('lcm_list', len(seq), exc) if not polys: if not opt.polys: return S.One else: return Poly(1, opt=opt) result, polys = polys[0], polys[1:] for poly in polys: result = result.lcm(poly) if not opt.polys: return result.as_expr() else: return result @public def lcm(f, g=None, *gens, **args): """ Compute LCM of ``f`` and ``g``. Examples ======== >>> from sympy import lcm >>> from sympy.abc import x >>> lcm(x**2 - 1, x**2 - 3*x + 2) x**3 - 2*x**2 - x + 2 """ if hasattr(f, '__iter__'): if g is not None: gens = (g,) + gens return lcm_list(f, *gens, **args) elif g is None: raise TypeError("lcm() takes 2 arguments or a sequence of arguments") options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) # lcm for domain Q[irrational] (purely algebraic irrational) a, b = map(sympify, (f, g)) if a.is_algebraic and a.is_irrational and b.is_algebraic and b.is_irrational: frc = (a/b).ratsimp() if frc.is_rational: return a*frc.as_numer_denom()[1] except PolificationFailed as exc: domain, (a, b) = construct_domain(exc.exprs) try: return domain.to_sympy(domain.lcm(a, b)) except NotImplementedError: raise ComputationFailed('lcm', 2, exc) result = F.lcm(G) if not opt.polys: return result.as_expr() else: return result @public def terms_gcd(f, *gens, **args): """ Remove GCD of terms from ``f``. If the ``deep`` flag is True, then the arguments of ``f`` will have terms_gcd applied to them. If a fraction is factored out of ``f`` and ``f`` is an Add, then an unevaluated Mul will be returned so that automatic simplification does not redistribute it. The hint ``clear``, when set to False, can be used to prevent such factoring when all coefficients are not fractions. Examples ======== >>> from sympy import terms_gcd, cos >>> from sympy.abc import x, y >>> terms_gcd(x**6*y**2 + x**3*y, x, y) x**3*y*(x**3*y + 1) The default action of polys routines is to expand the expression given to them. terms_gcd follows this behavior: >>> terms_gcd((3+3*x)*(x+x*y)) 3*x*(x*y + x + y + 1) If this is not desired then the hint ``expand`` can be set to False. In this case the expression will be treated as though it were comprised of one or more terms: >>> terms_gcd((3+3*x)*(x+x*y), expand=False) (3*x + 3)*(x*y + x) In order to traverse factors of a Mul or the arguments of other functions, the ``deep`` hint can be used: >>> terms_gcd((3 + 3*x)*(x + x*y), expand=False, deep=True) 3*x*(x + 1)*(y + 1) >>> terms_gcd(cos(x + x*y), deep=True) cos(x*(y + 1)) Rationals are factored out by default: >>> terms_gcd(x + y/2) (2*x + y)/2 Only the y-term had a coefficient that was a fraction; if one does not want to factor out the 1/2 in cases like this, the flag ``clear`` can be set to False: >>> terms_gcd(x + y/2, clear=False) x + y/2 >>> terms_gcd(x*y/2 + y**2, clear=False) y*(x/2 + y) The ``clear`` flag is ignored if all coefficients are fractions: >>> terms_gcd(x/3 + y/2, clear=False) (2*x + 3*y)/6 See Also ======== sympy.core.exprtools.gcd_terms, sympy.core.exprtools.factor_terms """ orig = sympify(f) if isinstance(f, Equality): return Equality(*(terms_gcd(s, *gens, **args) for s in [f.lhs, f.rhs])) elif isinstance(f, Relational): raise TypeError("Inequalities cannot be used with terms_gcd. Found: %s" %(f,)) if not isinstance(f, Expr) or f.is_Atom: return orig if args.get('deep', False): new = f.func(*[terms_gcd(a, *gens, **args) for a in f.args]) args.pop('deep') args['expand'] = False return terms_gcd(new, *gens, **args) clear = args.pop('clear', True) options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: return exc.expr J, f = F.terms_gcd() if opt.domain.is_Ring: if opt.domain.is_Field: denom, f = f.clear_denoms(convert=True) coeff, f = f.primitive() if opt.domain.is_Field: coeff /= denom else: coeff = S.One term = Mul(*[x**j for x, j in zip(f.gens, J)]) if equal_valued(coeff, 1): coeff = S.One if term == 1: return orig if clear: return _keep_coeff(coeff, term*f.as_expr()) # base the clearing on the form of the original expression, not # the (perhaps) Mul that we have now coeff, f = _keep_coeff(coeff, f.as_expr(), clear=False).as_coeff_Mul() return _keep_coeff(coeff, term*f, clear=False) @public def trunc(f, p, *gens, **args): """ Reduce ``f`` modulo a constant ``p``. Examples ======== >>> from sympy import trunc >>> from sympy.abc import x >>> trunc(2*x**3 + 3*x**2 + 5*x + 7, 3) -x**3 - x + 1 """ options.allowed_flags(args, ['auto', 'polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('trunc', 1, exc) result = F.trunc(sympify(p)) if not opt.polys: return result.as_expr() else: return result @public def monic(f, *gens, **args): """ Divide all coefficients of ``f`` by ``LC(f)``. Examples ======== >>> from sympy import monic >>> from sympy.abc import x >>> monic(3*x**2 + 4*x + 2) x**2 + 4*x/3 + 2/3 """ options.allowed_flags(args, ['auto', 'polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('monic', 1, exc) result = F.monic(auto=opt.auto) if not opt.polys: return result.as_expr() else: return result @public def content(f, *gens, **args): """ Compute GCD of coefficients of ``f``. Examples ======== >>> from sympy import content >>> from sympy.abc import x >>> content(6*x**2 + 8*x + 12) 2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('content', 1, exc) return F.content() @public def primitive(f, *gens, **args): """ Compute content and the primitive form of ``f``. Examples ======== >>> from sympy.polys.polytools import primitive >>> from sympy.abc import x >>> primitive(6*x**2 + 8*x + 12) (2, 3*x**2 + 4*x + 6) >>> eq = (2 + 2*x)*x + 2 Expansion is performed by default: >>> primitive(eq) (2, x**2 + x + 1) Set ``expand`` to False to shut this off. Note that the extraction will not be recursive; use the as_content_primitive method for recursive, non-destructive Rational extraction. >>> primitive(eq, expand=False) (1, x*(2*x + 2) + 2) >>> eq.as_content_primitive() (2, x*(x + 1) + 1) """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('primitive', 1, exc) cont, result = F.primitive() if not opt.polys: return cont, result.as_expr() else: return cont, result @public def compose(f, g, *gens, **args): """ Compute functional composition ``f(g)``. Examples ======== >>> from sympy import compose >>> from sympy.abc import x >>> compose(x**2 + x, x - 1) x**2 - x """ options.allowed_flags(args, ['polys']) try: (F, G), opt = parallel_poly_from_expr((f, g), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('compose', 2, exc) result = F.compose(G) if not opt.polys: return result.as_expr() else: return result @public def decompose(f, *gens, **args): """ Compute functional decomposition of ``f``. Examples ======== >>> from sympy import decompose >>> from sympy.abc import x >>> decompose(x**4 + 2*x**3 - x - 1) [x**2 - x - 1, x**2 + x] """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('decompose', 1, exc) result = F.decompose() if not opt.polys: return [r.as_expr() for r in result] else: return result @public def sturm(f, *gens, **args): """ Compute Sturm sequence of ``f``. Examples ======== >>> from sympy import sturm >>> from sympy.abc import x >>> sturm(x**3 - 2*x**2 + x - 3) [x**3 - 2*x**2 + x - 3, 3*x**2 - 4*x + 1, 2*x/9 + 25/9, -2079/4] """ options.allowed_flags(args, ['auto', 'polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('sturm', 1, exc) result = F.sturm(auto=opt.auto) if not opt.polys: return [r.as_expr() for r in result] else: return result @public def gff_list(f, *gens, **args): """ Compute a list of greatest factorial factors of ``f``. Note that the input to ff() and rf() should be Poly instances to use the definitions here. Examples ======== >>> from sympy import gff_list, ff, Poly >>> from sympy.abc import x >>> f = Poly(x**5 + 2*x**4 - x**3 - 2*x**2, x) >>> gff_list(f) [(Poly(x, x, domain='ZZ'), 1), (Poly(x + 2, x, domain='ZZ'), 4)] >>> (ff(Poly(x), 1)*ff(Poly(x + 2), 4)) == f True >>> f = Poly(x**12 + 6*x**11 - 11*x**10 - 56*x**9 + 220*x**8 + 208*x**7 - \ 1401*x**6 + 1090*x**5 + 2715*x**4 - 6720*x**3 - 1092*x**2 + 5040*x, x) >>> gff_list(f) [(Poly(x**3 + 7, x, domain='ZZ'), 2), (Poly(x**2 + 5*x, x, domain='ZZ'), 3)] >>> ff(Poly(x**3 + 7, x), 2)*ff(Poly(x**2 + 5*x, x), 3) == f True """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('gff_list', 1, exc) factors = F.gff_list() if not opt.polys: return [(g.as_expr(), k) for g, k in factors] else: return factors @public def gff(f, *gens, **args): """Compute greatest factorial factorization of ``f``. """ raise NotImplementedError('symbolic falling factorial') @public def sqf_norm(f, *gens, **args): """ Compute square-free norm of ``f``. Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and ``r(x) = Norm(g(x))`` is a square-free polynomial over ``K``, where ``a`` is the algebraic extension of the ground domain. Examples ======== >>> from sympy import sqf_norm, sqrt >>> from sympy.abc import x >>> sqf_norm(x**2 + 1, extension=[sqrt(3)]) (1, x**2 - 2*sqrt(3)*x + 4, x**4 - 4*x**2 + 16) """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('sqf_norm', 1, exc) s, g, r = F.sqf_norm() if not opt.polys: return Integer(s), g.as_expr(), r.as_expr() else: return Integer(s), g, r @public def sqf_part(f, *gens, **args): """ Compute square-free part of ``f``. Examples ======== >>> from sympy import sqf_part >>> from sympy.abc import x >>> sqf_part(x**3 - 3*x - 2) x**2 - x - 2 """ options.allowed_flags(args, ['polys']) try: F, opt = poly_from_expr(f, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('sqf_part', 1, exc) result = F.sqf_part() if not opt.polys: return result.as_expr() else: return result def _sorted_factors(factors, method): """Sort a list of ``(expr, exp)`` pairs. """ if method == 'sqf': def key(obj): poly, exp = obj rep = poly.rep.rep return (exp, len(rep), len(poly.gens), str(poly.domain), rep) else: def key(obj): poly, exp = obj rep = poly.rep.rep return (len(rep), len(poly.gens), exp, str(poly.domain), rep) return sorted(factors, key=key) def _factors_product(factors): """Multiply a list of ``(expr, exp)`` pairs. """ return Mul(*[f.as_expr()**k for f, k in factors]) def _symbolic_factor_list(expr, opt, method): """Helper function for :func:`_symbolic_factor`. """ coeff, factors = S.One, [] args = [i._eval_factor() if hasattr(i, '_eval_factor') else i for i in Mul.make_args(expr)] for arg in args: if arg.is_Number or (isinstance(arg, Expr) and pure_complex(arg)): coeff *= arg continue elif arg.is_Pow and arg.base != S.Exp1: base, exp = arg.args if base.is_Number and exp.is_Number: coeff *= arg continue if base.is_Number: factors.append((base, exp)) continue else: base, exp = arg, S.One try: poly, _ = _poly_from_expr(base, opt) except PolificationFailed as exc: factors.append((exc.expr, exp)) else: func = getattr(poly, method + '_list') _coeff, _factors = func() if _coeff is not S.One: if exp.is_Integer: coeff *= _coeff**exp elif _coeff.is_positive: factors.append((_coeff, exp)) else: _factors.append((_coeff, S.One)) if exp is S.One: factors.extend(_factors) elif exp.is_integer: factors.extend([(f, k*exp) for f, k in _factors]) else: other = [] for f, k in _factors: if f.as_expr().is_positive: factors.append((f, k*exp)) else: other.append((f, k)) factors.append((_factors_product(other), exp)) if method == 'sqf': factors = [(reduce(mul, (f for f, _ in factors if _ == k)), k) for k in {i for _, i in factors}] return coeff, factors def _symbolic_factor(expr, opt, method): """Helper function for :func:`_factor`. """ if isinstance(expr, Expr): if hasattr(expr,'_eval_factor'): return expr._eval_factor() coeff, factors = _symbolic_factor_list(together(expr, fraction=opt['fraction']), opt, method) return _keep_coeff(coeff, _factors_product(factors)) elif hasattr(expr, 'args'): return expr.func(*[_symbolic_factor(arg, opt, method) for arg in expr.args]) elif hasattr(expr, '__iter__'): return expr.__class__([_symbolic_factor(arg, opt, method) for arg in expr]) else: return expr def _generic_factor_list(expr, gens, args, method): """Helper function for :func:`sqf_list` and :func:`factor_list`. """ options.allowed_flags(args, ['frac', 'polys']) opt = options.build_options(gens, args) expr = sympify(expr) if isinstance(expr, (Expr, Poly)): if isinstance(expr, Poly): numer, denom = expr, 1 else: numer, denom = together(expr).as_numer_denom() cp, fp = _symbolic_factor_list(numer, opt, method) cq, fq = _symbolic_factor_list(denom, opt, method) if fq and not opt.frac: raise PolynomialError("a polynomial expected, got %s" % expr) _opt = opt.clone(dict(expand=True)) for factors in (fp, fq): for i, (f, k) in enumerate(factors): if not f.is_Poly: f, _ = _poly_from_expr(f, _opt) factors[i] = (f, k) fp = _sorted_factors(fp, method) fq = _sorted_factors(fq, method) if not opt.polys: fp = [(f.as_expr(), k) for f, k in fp] fq = [(f.as_expr(), k) for f, k in fq] coeff = cp/cq if not opt.frac: return coeff, fp else: return coeff, fp, fq else: raise PolynomialError("a polynomial expected, got %s" % expr) def _generic_factor(expr, gens, args, method): """Helper function for :func:`sqf` and :func:`factor`. """ fraction = args.pop('fraction', True) options.allowed_flags(args, []) opt = options.build_options(gens, args) opt['fraction'] = fraction return _symbolic_factor(sympify(expr), opt, method) def to_rational_coeffs(f): """ try to transform a polynomial to have rational coefficients try to find a transformation ``x = alpha*y`` ``f(x) = lc*alpha**n * g(y)`` where ``g`` is a polynomial with rational coefficients, ``lc`` the leading coefficient. If this fails, try ``x = y + beta`` ``f(x) = g(y)`` Returns ``None`` if ``g`` not found; ``(lc, alpha, None, g)`` in case of rescaling ``(None, None, beta, g)`` in case of translation Notes ===== Currently it transforms only polynomials without roots larger than 2. Examples ======== >>> from sympy import sqrt, Poly, simplify >>> from sympy.polys.polytools import to_rational_coeffs >>> from sympy.abc import x >>> p = Poly(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))}), x, domain='EX') >>> lc, r, _, g = to_rational_coeffs(p) >>> lc, r (7 + 5*sqrt(2), 2 - 2*sqrt(2)) >>> g Poly(x**3 + x**2 - 1/4*x - 1/4, x, domain='QQ') >>> r1 = simplify(1/r) >>> Poly(lc*r**3*(g.as_expr()).subs({x:x*r1}), x, domain='EX') == p True """ from sympy.simplify.simplify import simplify def _try_rescale(f, f1=None): """ try rescaling ``x -> alpha*x`` to convert f to a polynomial with rational coefficients. Returns ``alpha, f``; if the rescaling is successful, ``alpha`` is the rescaling factor, and ``f`` is the rescaled polynomial; else ``alpha`` is ``None``. """ if not len(f.gens) == 1 or not (f.gens[0]).is_Atom: return None, f n = f.degree() lc = f.LC() f1 = f1 or f1.monic() coeffs = f1.all_coeffs()[1:] coeffs = [simplify(coeffx) for coeffx in coeffs] if len(coeffs) > 1 and coeffs[-2]: rescale1_x = simplify(coeffs[-2]/coeffs[-1]) coeffs1 = [] for i in range(len(coeffs)): coeffx = simplify(coeffs[i]*rescale1_x**(i + 1)) if not coeffx.is_rational: break coeffs1.append(coeffx) else: rescale_x = simplify(1/rescale1_x) x = f.gens[0] v = [x**n] for i in range(1, n + 1): v.append(coeffs1[i - 1]*x**(n - i)) f = Add(*v) f = Poly(f) return lc, rescale_x, f return None def _try_translate(f, f1=None): """ try translating ``x -> x + alpha`` to convert f to a polynomial with rational coefficients. Returns ``alpha, f``; if the translating is successful, ``alpha`` is the translating factor, and ``f`` is the shifted polynomial; else ``alpha`` is ``None``. """ if not len(f.gens) == 1 or not (f.gens[0]).is_Atom: return None, f n = f.degree() f1 = f1 or f1.monic() coeffs = f1.all_coeffs()[1:] c = simplify(coeffs[0]) if c.is_Add and not c.is_rational: rat, nonrat = sift(c.args, lambda z: z.is_rational is True, binary=True) alpha = -c.func(*nonrat)/n f2 = f1.shift(alpha) return alpha, f2 return None def _has_square_roots(p): """ Return True if ``f`` is a sum with square roots but no other root """ coeffs = p.coeffs() has_sq = False for y in coeffs: for x in Add.make_args(y): f = Factors(x).factors r = [wx.q for b, wx in f.items() if b.is_number and wx.is_Rational and wx.q >= 2] if not r: continue if min(r) == 2: has_sq = True if max(r) > 2: return False return has_sq if f.get_domain().is_EX and _has_square_roots(f): f1 = f.monic() r = _try_rescale(f, f1) if r: return r[0], r[1], None, r[2] else: r = _try_translate(f, f1) if r: return None, None, r[0], r[1] return None def _torational_factor_list(p, x): """ helper function to factor polynomial using to_rational_coeffs Examples ======== >>> from sympy.polys.polytools import _torational_factor_list >>> from sympy.abc import x >>> from sympy import sqrt, expand, Mul >>> p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))})) >>> factors = _torational_factor_list(p, x); factors (-2, [(-x*(1 + sqrt(2))/2 + 1, 1), (-x*(1 + sqrt(2)) - 1, 1), (-x*(1 + sqrt(2)) + 1, 1)]) >>> expand(factors[0]*Mul(*[z[0] for z in factors[1]])) == p True >>> p = expand(((x**2-1)*(x-2)).subs({x:x + sqrt(2)})) >>> factors = _torational_factor_list(p, x); factors (1, [(x - 2 + sqrt(2), 1), (x - 1 + sqrt(2), 1), (x + 1 + sqrt(2), 1)]) >>> expand(factors[0]*Mul(*[z[0] for z in factors[1]])) == p True """ from sympy.simplify.simplify import simplify p1 = Poly(p, x, domain='EX') n = p1.degree() res = to_rational_coeffs(p1) if not res: return None lc, r, t, g = res factors = factor_list(g.as_expr()) if lc: c = simplify(factors[0]*lc*r**n) r1 = simplify(1/r) a = [] for z in factors[1:][0]: a.append((simplify(z[0].subs({x: x*r1})), z[1])) else: c = factors[0] a = [] for z in factors[1:][0]: a.append((z[0].subs({x: x - t}), z[1])) return (c, a) @public def sqf_list(f, *gens, **args): """ Compute a list of square-free factors of ``f``. Examples ======== >>> from sympy import sqf_list >>> from sympy.abc import x >>> sqf_list(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16) (2, [(x + 1, 2), (x + 2, 3)]) """ return _generic_factor_list(f, gens, args, method='sqf') @public def sqf(f, *gens, **args): """ Compute square-free factorization of ``f``. Examples ======== >>> from sympy import sqf >>> from sympy.abc import x >>> sqf(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16) 2*(x + 1)**2*(x + 2)**3 """ return _generic_factor(f, gens, args, method='sqf') @public def factor_list(f, *gens, **args): """ Compute a list of irreducible factors of ``f``. Examples ======== >>> from sympy import factor_list >>> from sympy.abc import x, y >>> factor_list(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y) (2, [(x + y, 1), (x**2 + 1, 2)]) """ return _generic_factor_list(f, gens, args, method='factor') @public def factor(f, *gens, deep=False, **args): """ Compute the factorization of expression, ``f``, into irreducibles. (To factor an integer into primes, use ``factorint``.) There two modes implemented: symbolic and formal. If ``f`` is not an instance of :class:`Poly` and generators are not specified, then the former mode is used. Otherwise, the formal mode is used. In symbolic mode, :func:`factor` will traverse the expression tree and factor its components without any prior expansion, unless an instance of :class:`~.Add` is encountered (in this case formal factorization is used). This way :func:`factor` can handle large or symbolic exponents. By default, the factorization is computed over the rationals. To factor over other domain, e.g. an algebraic or finite field, use appropriate options: ``extension``, ``modulus`` or ``domain``. Examples ======== >>> from sympy import factor, sqrt, exp >>> from sympy.abc import x, y >>> factor(2*x**5 + 2*x**4*y + 4*x**3 + 4*x**2*y + 2*x + 2*y) 2*(x + y)*(x**2 + 1)**2 >>> factor(x**2 + 1) x**2 + 1 >>> factor(x**2 + 1, modulus=2) (x + 1)**2 >>> factor(x**2 + 1, gaussian=True) (x - I)*(x + I) >>> factor(x**2 - 2, extension=sqrt(2)) (x - sqrt(2))*(x + sqrt(2)) >>> factor((x**2 - 1)/(x**2 + 4*x + 4)) (x - 1)*(x + 1)/(x + 2)**2 >>> factor((x**2 + 4*x + 4)**10000000*(x**2 + 1)) (x + 2)**20000000*(x**2 + 1) By default, factor deals with an expression as a whole: >>> eq = 2**(x**2 + 2*x + 1) >>> factor(eq) 2**(x**2 + 2*x + 1) If the ``deep`` flag is True then subexpressions will be factored: >>> factor(eq, deep=True) 2**((x + 1)**2) If the ``fraction`` flag is False then rational expressions will not be combined. By default it is True. >>> factor(5*x + 3*exp(2 - 7*x), deep=True) (5*x*exp(7*x) + 3*exp(2))*exp(-7*x) >>> factor(5*x + 3*exp(2 - 7*x), deep=True, fraction=False) 5*x + 3*exp(2)*exp(-7*x) See Also ======== sympy.ntheory.factor_.factorint """ f = sympify(f) if deep: def _try_factor(expr): """ Factor, but avoid changing the expression when unable to. """ fac = factor(expr, *gens, **args) if fac.is_Mul or fac.is_Pow: return fac return expr f = bottom_up(f, _try_factor) # clean up any subexpressions that may have been expanded # while factoring out a larger expression partials = {} muladd = f.atoms(Mul, Add) for p in muladd: fac = factor(p, *gens, **args) if (fac.is_Mul or fac.is_Pow) and fac != p: partials[p] = fac return f.xreplace(partials) try: return _generic_factor(f, gens, args, method='factor') except PolynomialError as msg: if not f.is_commutative: return factor_nc(f) else: raise PolynomialError(msg) @public def intervals(F, all=False, eps=None, inf=None, sup=None, strict=False, fast=False, sqf=False): """ Compute isolating intervals for roots of ``f``. Examples ======== >>> from sympy import intervals >>> from sympy.abc import x >>> intervals(x**2 - 3) [((-2, -1), 1), ((1, 2), 1)] >>> intervals(x**2 - 3, eps=1e-2) [((-26/15, -19/11), 1), ((19/11, 26/15), 1)] """ if not hasattr(F, '__iter__'): try: F = Poly(F) except GeneratorsNeeded: return [] return F.intervals(all=all, eps=eps, inf=inf, sup=sup, fast=fast, sqf=sqf) else: polys, opt = parallel_poly_from_expr(F, domain='QQ') if len(opt.gens) > 1: raise MultivariatePolynomialError for i, poly in enumerate(polys): polys[i] = poly.rep.rep if eps is not None: eps = opt.domain.convert(eps) if eps <= 0: raise ValueError("'eps' must be a positive rational") if inf is not None: inf = opt.domain.convert(inf) if sup is not None: sup = opt.domain.convert(sup) intervals = dup_isolate_real_roots_list(polys, opt.domain, eps=eps, inf=inf, sup=sup, strict=strict, fast=fast) result = [] for (s, t), indices in intervals: s, t = opt.domain.to_sympy(s), opt.domain.to_sympy(t) result.append(((s, t), indices)) return result @public def refine_root(f, s, t, eps=None, steps=None, fast=False, check_sqf=False): """ Refine an isolating interval of a root to the given precision. Examples ======== >>> from sympy import refine_root >>> from sympy.abc import x >>> refine_root(x**2 - 3, 1, 2, eps=1e-2) (19/11, 26/15) """ try: F = Poly(f) if not isinstance(f, Poly) and not F.gen.is_Symbol: # root of sin(x) + 1 is -1 but when someone # passes an Expr instead of Poly they may not expect # that the generator will be sin(x), not x raise PolynomialError("generator must be a Symbol") except GeneratorsNeeded: raise PolynomialError( "Cannot refine a root of %s, not a polynomial" % f) return F.refine_root(s, t, eps=eps, steps=steps, fast=fast, check_sqf=check_sqf) @public def count_roots(f, inf=None, sup=None): """ Return the number of roots of ``f`` in ``[inf, sup]`` interval. If one of ``inf`` or ``sup`` is complex, it will return the number of roots in the complex rectangle with corners at ``inf`` and ``sup``. Examples ======== >>> from sympy import count_roots, I >>> from sympy.abc import x >>> count_roots(x**4 - 4, -3, 3) 2 >>> count_roots(x**4 - 4, 0, 1 + 3*I) 1 """ try: F = Poly(f, greedy=False) if not isinstance(f, Poly) and not F.gen.is_Symbol: # root of sin(x) + 1 is -1 but when someone # passes an Expr instead of Poly they may not expect # that the generator will be sin(x), not x raise PolynomialError("generator must be a Symbol") except GeneratorsNeeded: raise PolynomialError("Cannot count roots of %s, not a polynomial" % f) return F.count_roots(inf=inf, sup=sup) @public def real_roots(f, multiple=True): """ Return a list of real roots with multiplicities of ``f``. Examples ======== >>> from sympy import real_roots >>> from sympy.abc import x >>> real_roots(2*x**3 - 7*x**2 + 4*x + 4) [-1/2, 2, 2] """ try: F = Poly(f, greedy=False) if not isinstance(f, Poly) and not F.gen.is_Symbol: # root of sin(x) + 1 is -1 but when someone # passes an Expr instead of Poly they may not expect # that the generator will be sin(x), not x raise PolynomialError("generator must be a Symbol") except GeneratorsNeeded: raise PolynomialError( "Cannot compute real roots of %s, not a polynomial" % f) return F.real_roots(multiple=multiple) @public def nroots(f, n=15, maxsteps=50, cleanup=True): """ Compute numerical approximations of roots of ``f``. Examples ======== >>> from sympy import nroots >>> from sympy.abc import x >>> nroots(x**2 - 3, n=15) [-1.73205080756888, 1.73205080756888] >>> nroots(x**2 - 3, n=30) [-1.73205080756887729352744634151, 1.73205080756887729352744634151] """ try: F = Poly(f, greedy=False) if not isinstance(f, Poly) and not F.gen.is_Symbol: # root of sin(x) + 1 is -1 but when someone # passes an Expr instead of Poly they may not expect # that the generator will be sin(x), not x raise PolynomialError("generator must be a Symbol") except GeneratorsNeeded: raise PolynomialError( "Cannot compute numerical roots of %s, not a polynomial" % f) return F.nroots(n=n, maxsteps=maxsteps, cleanup=cleanup) @public def ground_roots(f, *gens, **args): """ Compute roots of ``f`` by factorization in the ground domain. Examples ======== >>> from sympy import ground_roots >>> from sympy.abc import x >>> ground_roots(x**6 - 4*x**4 + 4*x**3 - x**2) {0: 2, 1: 2} """ options.allowed_flags(args, []) try: F, opt = poly_from_expr(f, *gens, **args) if not isinstance(f, Poly) and not F.gen.is_Symbol: # root of sin(x) + 1 is -1 but when someone # passes an Expr instead of Poly they may not expect # that the generator will be sin(x), not x raise PolynomialError("generator must be a Symbol") except PolificationFailed as exc: raise ComputationFailed('ground_roots', 1, exc) return F.ground_roots() @public def nth_power_roots_poly(f, n, *gens, **args): """ Construct a polynomial with n-th powers of roots of ``f``. Examples ======== >>> from sympy import nth_power_roots_poly, factor, roots >>> from sympy.abc import x >>> f = x**4 - x**2 + 1 >>> g = factor(nth_power_roots_poly(f, 2)) >>> g (x**2 - x + 1)**2 >>> R_f = [ (r**2).expand() for r in roots(f) ] >>> R_g = roots(g).keys() >>> set(R_f) == set(R_g) True """ options.allowed_flags(args, []) try: F, opt = poly_from_expr(f, *gens, **args) if not isinstance(f, Poly) and not F.gen.is_Symbol: # root of sin(x) + 1 is -1 but when someone # passes an Expr instead of Poly they may not expect # that the generator will be sin(x), not x raise PolynomialError("generator must be a Symbol") except PolificationFailed as exc: raise ComputationFailed('nth_power_roots_poly', 1, exc) result = F.nth_power_roots_poly(n) if not opt.polys: return result.as_expr() else: return result @public def cancel(f, *gens, _signsimp=True, **args): """ Cancel common factors in a rational function ``f``. Examples ======== >>> from sympy import cancel, sqrt, Symbol, together >>> from sympy.abc import x >>> A = Symbol('A', commutative=False) >>> cancel((2*x**2 - 2)/(x**2 - 2*x + 1)) (2*x + 2)/(x - 1) >>> cancel((sqrt(3) + sqrt(15)*A)/(sqrt(2) + sqrt(10)*A)) sqrt(6)/2 Note: due to automatic distribution of Rationals, a sum divided by an integer will appear as a sum. To recover a rational form use `together` on the result: >>> cancel(x/2 + 1) x/2 + 1 >>> together(_) (x + 2)/2 """ from sympy.simplify.simplify import signsimp from sympy.polys.rings import sring options.allowed_flags(args, ['polys']) f = sympify(f) if _signsimp: f = signsimp(f) opt = {} if 'polys' in args: opt['polys'] = args['polys'] if not isinstance(f, (tuple, Tuple)): if f.is_Number or isinstance(f, Relational) or not isinstance(f, Expr): return f f = factor_terms(f, radical=True) p, q = f.as_numer_denom() elif len(f) == 2: p, q = f if isinstance(p, Poly) and isinstance(q, Poly): opt['gens'] = p.gens opt['domain'] = p.domain opt['polys'] = opt.get('polys', True) p, q = p.as_expr(), q.as_expr() elif isinstance(f, Tuple): return factor_terms(f) else: raise ValueError('unexpected argument: %s' % f) from sympy.functions.elementary.piecewise import Piecewise try: if f.has(Piecewise): raise PolynomialError() R, (F, G) = sring((p, q), *gens, **args) if not R.ngens: if not isinstance(f, (tuple, Tuple)): return f.expand() else: return S.One, p, q except PolynomialError as msg: if f.is_commutative and not f.has(Piecewise): raise PolynomialError(msg) # Handling of noncommutative and/or piecewise expressions if f.is_Add or f.is_Mul: c, nc = sift(f.args, lambda x: x.is_commutative is True and not x.has(Piecewise), binary=True) nc = [cancel(i) for i in nc] return f.func(cancel(f.func(*c)), *nc) else: reps = [] pot = preorder_traversal(f) next(pot) for e in pot: # XXX: This should really skip anything that's not Expr. if isinstance(e, (tuple, Tuple, BooleanAtom)): continue try: reps.append((e, cancel(e))) pot.skip() # this was handled successfully except NotImplementedError: pass return f.xreplace(dict(reps)) c, (P, Q) = 1, F.cancel(G) if opt.get('polys', False) and 'gens' not in opt: opt['gens'] = R.symbols if not isinstance(f, (tuple, Tuple)): return c*(P.as_expr()/Q.as_expr()) else: P, Q = P.as_expr(), Q.as_expr() if not opt.get('polys', False): return c, P, Q else: return c, Poly(P, *gens, **opt), Poly(Q, *gens, **opt) @public def reduced(f, G, *gens, **args): """ Reduces a polynomial ``f`` modulo a set of polynomials ``G``. Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``, computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r`` such that ``f = q_1*g_1 + ... + q_n*g_n + r``, where ``r`` vanishes or ``r`` is a completely reduced polynomial with respect to ``G``. Examples ======== >>> from sympy import reduced >>> from sympy.abc import x, y >>> reduced(2*x**4 + y**2 - x**2 + y**3, [x**3 - x, y**3 - y]) ([2*x, 1], x**2 + y**2 + y) """ options.allowed_flags(args, ['polys', 'auto']) try: polys, opt = parallel_poly_from_expr([f] + list(G), *gens, **args) except PolificationFailed as exc: raise ComputationFailed('reduced', 0, exc) domain = opt.domain retract = False if opt.auto and domain.is_Ring and not domain.is_Field: opt = opt.clone(dict(domain=domain.get_field())) retract = True from sympy.polys.rings import xring _ring, _ = xring(opt.gens, opt.domain, opt.order) for i, poly in enumerate(polys): poly = poly.set_domain(opt.domain).rep.to_dict() polys[i] = _ring.from_dict(poly) Q, r = polys[0].div(polys[1:]) Q = [Poly._from_dict(dict(q), opt) for q in Q] r = Poly._from_dict(dict(r), opt) if retract: try: _Q, _r = [q.to_ring() for q in Q], r.to_ring() except CoercionFailed: pass else: Q, r = _Q, _r if not opt.polys: return [q.as_expr() for q in Q], r.as_expr() else: return Q, r @public def groebner(F, *gens, **args): """ Computes the reduced Groebner basis for a set of polynomials. Use the ``order`` argument to set the monomial ordering that will be used to compute the basis. Allowed orders are ``lex``, ``grlex`` and ``grevlex``. If no order is specified, it defaults to ``lex``. For more information on Groebner bases, see the references and the docstring of :func:`~.solve_poly_system`. Examples ======== Example taken from [1]. >>> from sympy import groebner >>> from sympy.abc import x, y >>> F = [x*y - 2*y, 2*y**2 - x**2] >>> groebner(F, x, y, order='lex') GroebnerBasis([x**2 - 2*y**2, x*y - 2*y, y**3 - 2*y], x, y, domain='ZZ', order='lex') >>> groebner(F, x, y, order='grlex') GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y, domain='ZZ', order='grlex') >>> groebner(F, x, y, order='grevlex') GroebnerBasis([y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y], x, y, domain='ZZ', order='grevlex') By default, an improved implementation of the Buchberger algorithm is used. Optionally, an implementation of the F5B algorithm can be used. The algorithm can be set using the ``method`` flag or with the :func:`sympy.polys.polyconfig.setup` function. >>> F = [x**2 - x - 1, (2*x - 1) * y - (x**10 - (1 - x)**10)] >>> groebner(F, x, y, method='buchberger') GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex') >>> groebner(F, x, y, method='f5b') GroebnerBasis([x**2 - x - 1, y - 55], x, y, domain='ZZ', order='lex') References ========== 1. [Buchberger01]_ 2. [Cox97]_ """ return GroebnerBasis(F, *gens, **args) @public def is_zero_dimensional(F, *gens, **args): """ Checks if the ideal generated by a Groebner basis is zero-dimensional. The algorithm checks if the set of monomials not divisible by the leading monomial of any element of ``F`` is bounded. References ========== David A. Cox, John B. Little, Donal O'Shea. Ideals, Varieties and Algorithms, 3rd edition, p. 230 """ return GroebnerBasis(F, *gens, **args).is_zero_dimensional @public class GroebnerBasis(Basic): """Represents a reduced Groebner basis. """ def __new__(cls, F, *gens, **args): """Compute a reduced Groebner basis for a system of polynomials. """ options.allowed_flags(args, ['polys', 'method']) try: polys, opt = parallel_poly_from_expr(F, *gens, **args) except PolificationFailed as exc: raise ComputationFailed('groebner', len(F), exc) from sympy.polys.rings import PolyRing ring = PolyRing(opt.gens, opt.domain, opt.order) polys = [ring.from_dict(poly.rep.to_dict()) for poly in polys if poly] G = _groebner(polys, ring, method=opt.method) G = [Poly._from_dict(g, opt) for g in G] return cls._new(G, opt) @classmethod def _new(cls, basis, options): obj = Basic.__new__(cls) obj._basis = tuple(basis) obj._options = options return obj @property def args(self): basis = (p.as_expr() for p in self._basis) return (Tuple(*basis), Tuple(*self._options.gens)) @property def exprs(self): return [poly.as_expr() for poly in self._basis] @property def polys(self): return list(self._basis) @property def gens(self): return self._options.gens @property def domain(self): return self._options.domain @property def order(self): return self._options.order def __len__(self): return len(self._basis) def __iter__(self): if self._options.polys: return iter(self.polys) else: return iter(self.exprs) def __getitem__(self, item): if self._options.polys: basis = self.polys else: basis = self.exprs return basis[item] def __hash__(self): return hash((self._basis, tuple(self._options.items()))) def __eq__(self, other): if isinstance(other, self.__class__): return self._basis == other._basis and self._options == other._options elif iterable(other): return self.polys == list(other) or self.exprs == list(other) else: return False def __ne__(self, other): return not self == other @property def is_zero_dimensional(self): """ Checks if the ideal generated by a Groebner basis is zero-dimensional. The algorithm checks if the set of monomials not divisible by the leading monomial of any element of ``F`` is bounded. References ========== David A. Cox, John B. Little, Donal O'Shea. Ideals, Varieties and Algorithms, 3rd edition, p. 230 """ def single_var(monomial): return sum(map(bool, monomial)) == 1 exponents = Monomial([0]*len(self.gens)) order = self._options.order for poly in self.polys: monomial = poly.LM(order=order) if single_var(monomial): exponents *= monomial # If any element of the exponents vector is zero, then there's # a variable for which there's no degree bound and the ideal # generated by this Groebner basis isn't zero-dimensional. return all(exponents) def fglm(self, order): """ Convert a Groebner basis from one ordering to another. The FGLM algorithm converts reduced Groebner bases of zero-dimensional ideals from one ordering to another. This method is often used when it is infeasible to compute a Groebner basis with respect to a particular ordering directly. Examples ======== >>> from sympy.abc import x, y >>> from sympy import groebner >>> F = [x**2 - 3*y - x + 1, y**2 - 2*x + y - 1] >>> G = groebner(F, x, y, order='grlex') >>> list(G.fglm('lex')) [2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7] >>> list(groebner(F, x, y, order='lex')) [2*x - y**2 - y + 1, y**4 + 2*y**3 - 3*y**2 - 16*y + 7] References ========== .. [1] J.C. Faugere, P. Gianni, D. Lazard, T. Mora (1994). Efficient Computation of Zero-dimensional Groebner Bases by Change of Ordering """ opt = self._options src_order = opt.order dst_order = monomial_key(order) if src_order == dst_order: return self if not self.is_zero_dimensional: raise NotImplementedError("Cannot convert Groebner bases of ideals with positive dimension") polys = list(self._basis) domain = opt.domain opt = opt.clone(dict( domain=domain.get_field(), order=dst_order, )) from sympy.polys.rings import xring _ring, _ = xring(opt.gens, opt.domain, src_order) for i, poly in enumerate(polys): poly = poly.set_domain(opt.domain).rep.to_dict() polys[i] = _ring.from_dict(poly) G = matrix_fglm(polys, _ring, dst_order) G = [Poly._from_dict(dict(g), opt) for g in G] if not domain.is_Field: G = [g.clear_denoms(convert=True)[1] for g in G] opt.domain = domain return self._new(G, opt) def reduce(self, expr, auto=True): """ Reduces a polynomial modulo a Groebner basis. Given a polynomial ``f`` and a set of polynomials ``G = (g_1, ..., g_n)``, computes a set of quotients ``q = (q_1, ..., q_n)`` and the remainder ``r`` such that ``f = q_1*f_1 + ... + q_n*f_n + r``, where ``r`` vanishes or ``r`` is a completely reduced polynomial with respect to ``G``. Examples ======== >>> from sympy import groebner, expand >>> from sympy.abc import x, y >>> f = 2*x**4 - x**2 + y**3 + y**2 >>> G = groebner([x**3 - x, y**3 - y]) >>> G.reduce(f) ([2*x, 1], x**2 + y**2 + y) >>> Q, r = _ >>> expand(sum(q*g for q, g in zip(Q, G)) + r) 2*x**4 - x**2 + y**3 + y**2 >>> _ == f True """ poly = Poly._from_expr(expr, self._options) polys = [poly] + list(self._basis) opt = self._options domain = opt.domain retract = False if auto and domain.is_Ring and not domain.is_Field: opt = opt.clone(dict(domain=domain.get_field())) retract = True from sympy.polys.rings import xring _ring, _ = xring(opt.gens, opt.domain, opt.order) for i, poly in enumerate(polys): poly = poly.set_domain(opt.domain).rep.to_dict() polys[i] = _ring.from_dict(poly) Q, r = polys[0].div(polys[1:]) Q = [Poly._from_dict(dict(q), opt) for q in Q] r = Poly._from_dict(dict(r), opt) if retract: try: _Q, _r = [q.to_ring() for q in Q], r.to_ring() except CoercionFailed: pass else: Q, r = _Q, _r if not opt.polys: return [q.as_expr() for q in Q], r.as_expr() else: return Q, r def contains(self, poly): """ Check if ``poly`` belongs the ideal generated by ``self``. Examples ======== >>> from sympy import groebner >>> from sympy.abc import x, y >>> f = 2*x**3 + y**3 + 3*y >>> G = groebner([x**2 + y**2 - 1, x*y - 2]) >>> G.contains(f) True >>> G.contains(f + 1) False """ return self.reduce(poly)[1] == 0 @public def poly(expr, *gens, **args): """ Efficiently transform an expression into a polynomial. Examples ======== >>> from sympy import poly >>> from sympy.abc import x >>> poly(x*(x**2 + x - 1)**2) Poly(x**5 + 2*x**4 - x**3 - 2*x**2 + x, x, domain='ZZ') """ options.allowed_flags(args, []) def _poly(expr, opt): terms, poly_terms = [], [] for term in Add.make_args(expr): factors, poly_factors = [], [] for factor in Mul.make_args(term): if factor.is_Add: poly_factors.append(_poly(factor, opt)) elif factor.is_Pow and factor.base.is_Add and \ factor.exp.is_Integer and factor.exp >= 0: poly_factors.append( _poly(factor.base, opt).pow(factor.exp)) else: factors.append(factor) if not poly_factors: terms.append(term) else: product = poly_factors[0] for factor in poly_factors[1:]: product = product.mul(factor) if factors: factor = Mul(*factors) if factor.is_Number: product = product.mul(factor) else: product = product.mul(Poly._from_expr(factor, opt)) poly_terms.append(product) if not poly_terms: result = Poly._from_expr(expr, opt) else: result = poly_terms[0] for term in poly_terms[1:]: result = result.add(term) if terms: term = Add(*terms) if term.is_Number: result = result.add(term) else: result = result.add(Poly._from_expr(term, opt)) return result.reorder(*opt.get('gens', ()), **args) expr = sympify(expr) if expr.is_Poly: return Poly(expr, *gens, **args) if 'expand' not in args: args['expand'] = False opt = options.build_options(gens, args) return _poly(expr, opt) def named_poly(n, f, K, name, x, polys): r"""Common interface to the low-level polynomial generating functions in orthopolys and appellseqs. Parameters ========== n : int Index of the polynomial, which may or may not equal its degree. f : callable Low-level generating function to use. K : Domain or None Domain in which to perform the computations. If None, use the smallest field containing the rationals and the extra parameters of x (see below). name : str Name of an arbitrary individual polynomial in the sequence generated by f, only used in the error message for invalid n. x : seq The first element of this argument is the main variable of all polynomials in this sequence. Any further elements are extra parameters required by f. polys : bool, optional If True, return a Poly, otherwise (default) return an expression. """ if n < 0: raise ValueError("Cannot generate %s of index %s" % (name, n)) head, tail = x[0], x[1:] if K is None: K, tail = construct_domain(tail, field=True) poly = DMP(f(int(n), *tail, K), K) if head is None: poly = PurePoly.new(poly, Dummy('x')) else: poly = Poly.new(poly, head) return poly if polys else poly.as_expr()
0ab9fe91e99d82241dcab0952834a7ce5eed102540e0b613c32d37e20b4e9c16
"""Algorithms for computing symbolic roots of polynomials. """ import math from functools import reduce from sympy.core import S, I, pi from sympy.core.exprtools import factor_terms from sympy.core.function import _mexpand from sympy.core.logic import fuzzy_not from sympy.core.mul import expand_2arg, Mul from sympy.core.numbers import Rational, igcd, comp from sympy.core.power import Pow from sympy.core.relational import Eq from sympy.core.sorting import ordered from sympy.core.symbol import Dummy, Symbol, symbols from sympy.core.sympify import sympify from sympy.functions import exp, im, cos, acos, Piecewise from sympy.functions.elementary.miscellaneous import root, sqrt from sympy.ntheory import divisors, isprime, nextprime from sympy.polys.domains import EX from sympy.polys.polyerrors import (PolynomialError, GeneratorsNeeded, DomainError, UnsolvableFactorError) from sympy.polys.polyquinticconst import PolyQuintic from sympy.polys.polytools import Poly, cancel, factor, gcd_list, discriminant from sympy.polys.rationaltools import together from sympy.polys.specialpolys import cyclotomic_poly from sympy.utilities import public from sympy.utilities.misc import filldedent z = Symbol('z') # importing from abc cause O to be lost as clashing symbol def roots_linear(f): """Returns a list of roots of a linear polynomial.""" r = -f.nth(0)/f.nth(1) dom = f.get_domain() if not dom.is_Numerical: if dom.is_Composite: r = factor(r) else: from sympy.simplify.simplify import simplify r = simplify(r) return [r] def roots_quadratic(f): """Returns a list of roots of a quadratic polynomial. If the domain is ZZ then the roots will be sorted with negatives coming before positives. The ordering will be the same for any numerical coefficients as long as the assumptions tested are correct, otherwise the ordering will not be sorted (but will be canonical). """ a, b, c = f.all_coeffs() dom = f.get_domain() def _sqrt(d): # remove squares from square root since both will be represented # in the results; a similar thing is happening in roots() but # must be duplicated here because not all quadratics are binomials co = [] other = [] for di in Mul.make_args(d): if di.is_Pow and di.exp.is_Integer and di.exp % 2 == 0: co.append(Pow(di.base, di.exp//2)) else: other.append(di) if co: d = Mul(*other) co = Mul(*co) return co*sqrt(d) return sqrt(d) def _simplify(expr): if dom.is_Composite: return factor(expr) else: from sympy.simplify.simplify import simplify return simplify(expr) if c is S.Zero: r0, r1 = S.Zero, -b/a if not dom.is_Numerical: r1 = _simplify(r1) elif r1.is_negative: r0, r1 = r1, r0 elif b is S.Zero: r = -c/a if not dom.is_Numerical: r = _simplify(r) R = _sqrt(r) r0 = -R r1 = R else: d = b**2 - 4*a*c A = 2*a B = -b/A if not dom.is_Numerical: d = _simplify(d) B = _simplify(B) D = factor_terms(_sqrt(d)/A) r0 = B - D r1 = B + D if a.is_negative: r0, r1 = r1, r0 elif not dom.is_Numerical: r0, r1 = [expand_2arg(i) for i in (r0, r1)] return [r0, r1] def roots_cubic(f, trig=False): """Returns a list of roots of a cubic polynomial. References ========== [1] https://en.wikipedia.org/wiki/Cubic_function, General formula for roots, (accessed November 17, 2014). """ if trig: a, b, c, d = f.all_coeffs() p = (3*a*c - b**2)/(3*a**2) q = (2*b**3 - 9*a*b*c + 27*a**2*d)/(27*a**3) D = 18*a*b*c*d - 4*b**3*d + b**2*c**2 - 4*a*c**3 - 27*a**2*d**2 if (D > 0) == True: rv = [] for k in range(3): rv.append(2*sqrt(-p/3)*cos(acos(q/p*sqrt(-3/p)*Rational(3, 2))/3 - k*pi*Rational(2, 3))) return [i - b/3/a for i in rv] # a*x**3 + b*x**2 + c*x + d -> x**3 + a*x**2 + b*x + c _, a, b, c = f.monic().all_coeffs() if c is S.Zero: x1, x2 = roots([1, a, b], multiple=True) return [x1, S.Zero, x2] # x**3 + a*x**2 + b*x + c -> u**3 + p*u + q p = b - a**2/3 q = c - a*b/3 + 2*a**3/27 pon3 = p/3 aon3 = a/3 u1 = None if p is S.Zero: if q is S.Zero: return [-aon3]*3 u1 = -root(q, 3) if q.is_positive else root(-q, 3) elif q is S.Zero: y1, y2 = roots([1, 0, p], multiple=True) return [tmp - aon3 for tmp in [y1, S.Zero, y2]] elif q.is_real and q.is_negative: u1 = -root(-q/2 + sqrt(q**2/4 + pon3**3), 3) coeff = I*sqrt(3)/2 if u1 is None: u1 = S.One u2 = Rational(-1, 2) + coeff u3 = Rational(-1, 2) - coeff b, c, d = a, b, c # a, b, c, d = S.One, a, b, c D0 = b**2 - 3*c # b**2 - 3*a*c D1 = 2*b**3 - 9*b*c + 27*d # 2*b**3 - 9*a*b*c + 27*a**2*d C = root((D1 + sqrt(D1**2 - 4*D0**3))/2, 3) return [-(b + uk*C + D0/C/uk)/3 for uk in [u1, u2, u3]] # -(b + uk*C + D0/C/uk)/3/a u2 = u1*(Rational(-1, 2) + coeff) u3 = u1*(Rational(-1, 2) - coeff) if p is S.Zero: return [u1 - aon3, u2 - aon3, u3 - aon3] soln = [ -u1 + pon3/u1 - aon3, -u2 + pon3/u2 - aon3, -u3 + pon3/u3 - aon3 ] return soln def _roots_quartic_euler(p, q, r, a): """ Descartes-Euler solution of the quartic equation Parameters ========== p, q, r: coefficients of ``x**4 + p*x**2 + q*x + r`` a: shift of the roots Notes ===== This is a helper function for ``roots_quartic``. Look for solutions of the form :: ``x1 = sqrt(R) - sqrt(A + B*sqrt(R))`` ``x2 = -sqrt(R) - sqrt(A - B*sqrt(R))`` ``x3 = -sqrt(R) + sqrt(A - B*sqrt(R))`` ``x4 = sqrt(R) + sqrt(A + B*sqrt(R))`` To satisfy the quartic equation one must have ``p = -2*(R + A); q = -4*B*R; r = (R - A)**2 - B**2*R`` so that ``R`` must satisfy the Descartes-Euler resolvent equation ``64*R**3 + 32*p*R**2 + (4*p**2 - 16*r)*R - q**2 = 0`` If the resolvent does not have a rational solution, return None; in that case it is likely that the Ferrari method gives a simpler solution. Examples ======== >>> from sympy import S >>> from sympy.polys.polyroots import _roots_quartic_euler >>> p, q, r = -S(64)/5, -S(512)/125, -S(1024)/3125 >>> _roots_quartic_euler(p, q, r, S(0))[0] -sqrt(32*sqrt(5)/125 + 16/5) + 4*sqrt(5)/5 """ # solve the resolvent equation x = Dummy('x') eq = 64*x**3 + 32*p*x**2 + (4*p**2 - 16*r)*x - q**2 xsols = list(roots(Poly(eq, x), cubics=False).keys()) xsols = [sol for sol in xsols if sol.is_rational and sol.is_nonzero] if not xsols: return None R = max(xsols) c1 = sqrt(R) B = -q*c1/(4*R) A = -R - p/2 c2 = sqrt(A + B) c3 = sqrt(A - B) return [c1 - c2 - a, -c1 - c3 - a, -c1 + c3 - a, c1 + c2 - a] def roots_quartic(f): r""" Returns a list of roots of a quartic polynomial. There are many references for solving quartic expressions available [1-5]. This reviewer has found that many of them require one to select from among 2 or more possible sets of solutions and that some solutions work when one is searching for real roots but do not work when searching for complex roots (though this is not always stated clearly). The following routine has been tested and found to be correct for 0, 2 or 4 complex roots. The quasisymmetric case solution [6] looks for quartics that have the form `x**4 + A*x**3 + B*x**2 + C*x + D = 0` where `(C/A)**2 = D`. Although no general solution that is always applicable for all coefficients is known to this reviewer, certain conditions are tested to determine the simplest 4 expressions that can be returned: 1) `f = c + a*(a**2/8 - b/2) == 0` 2) `g = d - a*(a*(3*a**2/256 - b/16) + c/4) = 0` 3) if `f != 0` and `g != 0` and `p = -d + a*c/4 - b**2/12` then a) `p == 0` b) `p != 0` Examples ======== >>> from sympy import Poly >>> from sympy.polys.polyroots import roots_quartic >>> r = roots_quartic(Poly('x**4-6*x**3+17*x**2-26*x+20')) >>> # 4 complex roots: 1+-I*sqrt(3), 2+-I >>> sorted(str(tmp.evalf(n=2)) for tmp in r) ['1.0 + 1.7*I', '1.0 - 1.7*I', '2.0 + 1.0*I', '2.0 - 1.0*I'] References ========== 1. http://mathforum.org/dr.math/faq/faq.cubic.equations.html 2. https://en.wikipedia.org/wiki/Quartic_function#Summary_of_Ferrari.27s_method 3. http://planetmath.org/encyclopedia/GaloisTheoreticDerivationOfTheQuarticFormula.html 4. http://staff.bath.ac.uk/masjhd/JHD-CA.pdf 5. http://www.albmath.org/files/Math_5713.pdf 6. http://www.statemaster.com/encyclopedia/Quartic-equation 7. eqworld.ipmnet.ru/en/solutions/ae/ae0108.pdf """ _, a, b, c, d = f.monic().all_coeffs() if not d: return [S.Zero] + roots([1, a, b, c], multiple=True) elif (c/a)**2 == d: x, m = f.gen, c/a g = Poly(x**2 + a*x + b - 2*m, x) z1, z2 = roots_quadratic(g) h1 = Poly(x**2 - z1*x + m, x) h2 = Poly(x**2 - z2*x + m, x) r1 = roots_quadratic(h1) r2 = roots_quadratic(h2) return r1 + r2 else: a2 = a**2 e = b - 3*a2/8 f = _mexpand(c + a*(a2/8 - b/2)) aon4 = a/4 g = _mexpand(d - aon4*(a*(3*a2/64 - b/4) + c)) if f.is_zero: y1, y2 = [sqrt(tmp) for tmp in roots([1, e, g], multiple=True)] return [tmp - aon4 for tmp in [-y1, -y2, y1, y2]] if g.is_zero: y = [S.Zero] + roots([1, 0, e, f], multiple=True) return [tmp - aon4 for tmp in y] else: # Descartes-Euler method, see [7] sols = _roots_quartic_euler(e, f, g, aon4) if sols: return sols # Ferrari method, see [1, 2] p = -e**2/12 - g q = -e**3/108 + e*g/3 - f**2/8 TH = Rational(1, 3) def _ans(y): w = sqrt(e + 2*y) arg1 = 3*e + 2*y arg2 = 2*f/w ans = [] for s in [-1, 1]: root = sqrt(-(arg1 + s*arg2)) for t in [-1, 1]: ans.append((s*w - t*root)/2 - aon4) return ans # whether a Piecewise is returned or not # depends on knowing p, so try to put # in a simple form p = _mexpand(p) # p == 0 case y1 = e*Rational(-5, 6) - q**TH if p.is_zero: return _ans(y1) # if p != 0 then u below is not 0 root = sqrt(q**2/4 + p**3/27) r = -q/2 + root # or -q/2 - root u = r**TH # primary root of solve(x**3 - r, x) y2 = e*Rational(-5, 6) + u - p/u/3 if fuzzy_not(p.is_zero): return _ans(y2) # sort it out once they know the values of the coefficients return [Piecewise((a1, Eq(p, 0)), (a2, True)) for a1, a2 in zip(_ans(y1), _ans(y2))] def roots_binomial(f): """Returns a list of roots of a binomial polynomial. If the domain is ZZ then the roots will be sorted with negatives coming before positives. The ordering will be the same for any numerical coefficients as long as the assumptions tested are correct, otherwise the ordering will not be sorted (but will be canonical). """ n = f.degree() a, b = f.nth(n), f.nth(0) base = -cancel(b/a) alpha = root(base, n) if alpha.is_number: alpha = alpha.expand(complex=True) # define some parameters that will allow us to order the roots. # If the domain is ZZ this is guaranteed to return roots sorted # with reals before non-real roots and non-real sorted according # to real part and imaginary part, e.g. -1, 1, -1 + I, 2 - I neg = base.is_negative even = n % 2 == 0 if neg: if even == True and (base + 1).is_positive: big = True else: big = False # get the indices in the right order so the computed # roots will be sorted when the domain is ZZ ks = [] imax = n//2 if even: ks.append(imax) imax -= 1 if not neg: ks.append(0) for i in range(imax, 0, -1): if neg: ks.extend([i, -i]) else: ks.extend([-i, i]) if neg: ks.append(0) if big: for i in range(0, len(ks), 2): pair = ks[i: i + 2] pair = list(reversed(pair)) # compute the roots roots, d = [], 2*I*pi/n for k in ks: zeta = exp(k*d).expand(complex=True) roots.append((alpha*zeta).expand(power_base=False)) return roots def _inv_totient_estimate(m): """ Find ``(L, U)`` such that ``L <= phi^-1(m) <= U``. Examples ======== >>> from sympy.polys.polyroots import _inv_totient_estimate >>> _inv_totient_estimate(192) (192, 840) >>> _inv_totient_estimate(400) (400, 1750) """ primes = [ d + 1 for d in divisors(m) if isprime(d + 1) ] a, b = 1, 1 for p in primes: a *= p b *= p - 1 L = m U = int(math.ceil(m*(float(a)/b))) P = p = 2 primes = [] while P <= U: p = nextprime(p) primes.append(p) P *= p P //= p b = 1 for p in primes[:-1]: b *= p - 1 U = int(math.ceil(m*(float(P)/b))) return L, U def roots_cyclotomic(f, factor=False): """Compute roots of cyclotomic polynomials. """ L, U = _inv_totient_estimate(f.degree()) for n in range(L, U + 1): g = cyclotomic_poly(n, f.gen, polys=True) if f.expr == g.expr: break else: # pragma: no cover raise RuntimeError("failed to find index of a cyclotomic polynomial") roots = [] if not factor: # get the indices in the right order so the computed # roots will be sorted h = n//2 ks = [i for i in range(1, n + 1) if igcd(i, n) == 1] ks.sort(key=lambda x: (x, -1) if x <= h else (abs(x - n), 1)) d = 2*I*pi/n for k in reversed(ks): roots.append(exp(k*d).expand(complex=True)) else: g = Poly(f, extension=root(-1, n)) for h, _ in ordered(g.factor_list()[1]): roots.append(-h.TC()) return roots def roots_quintic(f): """ Calculate exact roots of a solvable irreducible quintic with rational coefficients. Return an empty list if the quintic is reducible or not solvable. """ result = [] coeff_5, coeff_4, p_, q_, r_, s_ = f.all_coeffs() if not all(coeff.is_Rational for coeff in (coeff_5, coeff_4, p_, q_, r_, s_)): return result if coeff_5 != 1: f = Poly(f / coeff_5) _, coeff_4, p_, q_, r_, s_ = f.all_coeffs() # Cancel coeff_4 to form x^5 + px^3 + qx^2 + rx + s if coeff_4: p = p_ - 2*coeff_4*coeff_4/5 q = q_ - 3*coeff_4*p_/5 + 4*coeff_4**3/25 r = r_ - 2*coeff_4*q_/5 + 3*coeff_4**2*p_/25 - 3*coeff_4**4/125 s = s_ - coeff_4*r_/5 + coeff_4**2*q_/25 - coeff_4**3*p_/125 + 4*coeff_4**5/3125 x = f.gen f = Poly(x**5 + p*x**3 + q*x**2 + r*x + s) else: p, q, r, s = p_, q_, r_, s_ quintic = PolyQuintic(f) # Eqn standardized. Algo for solving starts here if not f.is_irreducible: return result f20 = quintic.f20 # Check if f20 has linear factors over domain Z if f20.is_irreducible: return result # Now, we know that f is solvable for _factor in f20.factor_list()[1]: if _factor[0].is_linear: theta = _factor[0].root(0) break d = discriminant(f) delta = sqrt(d) # zeta = a fifth root of unity zeta1, zeta2, zeta3, zeta4 = quintic.zeta T = quintic.T(theta, d) tol = S(1e-10) alpha = T[1] + T[2]*delta alpha_bar = T[1] - T[2]*delta beta = T[3] + T[4]*delta beta_bar = T[3] - T[4]*delta disc = alpha**2 - 4*beta disc_bar = alpha_bar**2 - 4*beta_bar l0 = quintic.l0(theta) Stwo = S(2) l1 = _quintic_simplify((-alpha + sqrt(disc)) / Stwo) l4 = _quintic_simplify((-alpha - sqrt(disc)) / Stwo) l2 = _quintic_simplify((-alpha_bar + sqrt(disc_bar)) / Stwo) l3 = _quintic_simplify((-alpha_bar - sqrt(disc_bar)) / Stwo) order = quintic.order(theta, d) test = (order*delta.n()) - ( (l1.n() - l4.n())*(l2.n() - l3.n()) ) # Comparing floats if not comp(test, 0, tol): l2, l3 = l3, l2 # Now we have correct order of l's R1 = l0 + l1*zeta1 + l2*zeta2 + l3*zeta3 + l4*zeta4 R2 = l0 + l3*zeta1 + l1*zeta2 + l4*zeta3 + l2*zeta4 R3 = l0 + l2*zeta1 + l4*zeta2 + l1*zeta3 + l3*zeta4 R4 = l0 + l4*zeta1 + l3*zeta2 + l2*zeta3 + l1*zeta4 Res = [None, [None]*5, [None]*5, [None]*5, [None]*5] Res_n = [None, [None]*5, [None]*5, [None]*5, [None]*5] # Simplifying improves performance a lot for exact expressions R1 = _quintic_simplify(R1) R2 = _quintic_simplify(R2) R3 = _quintic_simplify(R3) R4 = _quintic_simplify(R4) # hard-coded results for [factor(i) for i in _vsolve(x**5 - a - I*b, x)] x0 = z**(S(1)/5) x1 = sqrt(2) x2 = sqrt(5) x3 = sqrt(5 - x2) x4 = I*x2 x5 = x4 + I x6 = I*x0/4 x7 = x1*sqrt(x2 + 5) sol = [x0, -x6*(x1*x3 - x5), x6*(x1*x3 + x5), -x6*(x4 + x7 - I), x6*(-x4 + x7 + I)] R1 = R1.as_real_imag() R2 = R2.as_real_imag() R3 = R3.as_real_imag() R4 = R4.as_real_imag() for i, s in enumerate(sol): Res[1][i] = _quintic_simplify(s.xreplace({z: R1[0] + I*R1[1]})) Res[2][i] = _quintic_simplify(s.xreplace({z: R2[0] + I*R2[1]})) Res[3][i] = _quintic_simplify(s.xreplace({z: R3[0] + I*R3[1]})) Res[4][i] = _quintic_simplify(s.xreplace({z: R4[0] + I*R4[1]})) for i in range(1, 5): for j in range(5): Res_n[i][j] = Res[i][j].n() Res[i][j] = _quintic_simplify(Res[i][j]) r1 = Res[1][0] r1_n = Res_n[1][0] for i in range(5): if comp(im(r1_n*Res_n[4][i]), 0, tol): r4 = Res[4][i] break # Now we have various Res values. Each will be a list of five # values. We have to pick one r value from those five for each Res u, v = quintic.uv(theta, d) testplus = (u + v*delta*sqrt(5)).n() testminus = (u - v*delta*sqrt(5)).n() # Evaluated numbers suffixed with _n # We will use evaluated numbers for calculation. Much faster. r4_n = r4.n() r2 = r3 = None for i in range(5): r2temp_n = Res_n[2][i] for j in range(5): # Again storing away the exact number and using # evaluated numbers in computations r3temp_n = Res_n[3][j] if (comp((r1_n*r2temp_n**2 + r4_n*r3temp_n**2 - testplus).n(), 0, tol) and comp((r3temp_n*r1_n**2 + r2temp_n*r4_n**2 - testminus).n(), 0, tol)): r2 = Res[2][i] r3 = Res[3][j] break if r2 is not None: break else: return [] # fall back to normal solve # Now, we have r's so we can get roots x1 = (r1 + r2 + r3 + r4)/5 x2 = (r1*zeta4 + r2*zeta3 + r3*zeta2 + r4*zeta1)/5 x3 = (r1*zeta3 + r2*zeta1 + r3*zeta4 + r4*zeta2)/5 x4 = (r1*zeta2 + r2*zeta4 + r3*zeta1 + r4*zeta3)/5 x5 = (r1*zeta1 + r2*zeta2 + r3*zeta3 + r4*zeta4)/5 result = [x1, x2, x3, x4, x5] # Now check if solutions are distinct saw = set() for r in result: r = r.n(2) if r in saw: # Roots were identical. Abort, return [] # and fall back to usual solve return [] saw.add(r) # Restore to original equation where coeff_4 is nonzero if coeff_4: result = [x - coeff_4 / 5 for x in result] return result def _quintic_simplify(expr): from sympy.simplify.simplify import powsimp expr = powsimp(expr) expr = cancel(expr) return together(expr) def _integer_basis(poly): """Compute coefficient basis for a polynomial over integers. Returns the integer ``div`` such that substituting ``x = div*y`` ``p(x) = m*q(y)`` where the coefficients of ``q`` are smaller than those of ``p``. For example ``x**5 + 512*x + 1024 = 0`` with ``div = 4`` becomes ``y**5 + 2*y + 1 = 0`` Returns the integer ``div`` or ``None`` if there is no possible scaling. Examples ======== >>> from sympy.polys import Poly >>> from sympy.abc import x >>> from sympy.polys.polyroots import _integer_basis >>> p = Poly(x**5 + 512*x + 1024, x, domain='ZZ') >>> _integer_basis(p) 4 """ monoms, coeffs = list(zip(*poly.terms())) monoms, = list(zip(*monoms)) coeffs = list(map(abs, coeffs)) if coeffs[0] < coeffs[-1]: coeffs = list(reversed(coeffs)) n = monoms[0] monoms = [n - i for i in reversed(monoms)] else: return None monoms = monoms[:-1] coeffs = coeffs[:-1] # Special case for two-term polynominals if len(monoms) == 1: r = Pow(coeffs[0], S.One/monoms[0]) if r.is_Integer: return int(r) else: return None divs = reversed(divisors(gcd_list(coeffs))[1:]) try: div = next(divs) except StopIteration: return None while True: for monom, coeff in zip(monoms, coeffs): if coeff % div**monom != 0: try: div = next(divs) except StopIteration: return None else: break else: return div def preprocess_roots(poly): """Try to get rid of symbolic coefficients from ``poly``. """ coeff = S.One poly_func = poly.func try: _, poly = poly.clear_denoms(convert=True) except DomainError: return coeff, poly poly = poly.primitive()[1] poly = poly.retract() # TODO: This is fragile. Figure out how to make this independent of construct_domain(). if poly.get_domain().is_Poly and all(c.is_term for c in poly.rep.coeffs()): poly = poly.inject() strips = list(zip(*poly.monoms())) gens = list(poly.gens[1:]) base, strips = strips[0], strips[1:] for gen, strip in zip(list(gens), strips): reverse = False if strip[0] < strip[-1]: strip = reversed(strip) reverse = True ratio = None for a, b in zip(base, strip): if not a and not b: continue elif not a or not b: break elif b % a != 0: break else: _ratio = b // a if ratio is None: ratio = _ratio elif ratio != _ratio: break else: if reverse: ratio = -ratio poly = poly.eval(gen, 1) coeff *= gen**(-ratio) gens.remove(gen) if gens: poly = poly.eject(*gens) if poly.is_univariate and poly.get_domain().is_ZZ: basis = _integer_basis(poly) if basis is not None: n = poly.degree() def func(k, coeff): return coeff//basis**(n - k[0]) poly = poly.termwise(func) coeff *= basis if not isinstance(poly, poly_func): poly = poly_func(poly) return coeff, poly @public def roots(f, *gens, auto=True, cubics=True, trig=False, quartics=True, quintics=False, multiple=False, filter=None, predicate=None, strict=False, **flags): """ Computes symbolic roots of a univariate polynomial. Given a univariate polynomial f with symbolic coefficients (or a list of the polynomial's coefficients), returns a dictionary with its roots and their multiplicities. Only roots expressible via radicals will be returned. To get a complete set of roots use RootOf class or numerical methods instead. By default cubic and quartic formulas are used in the algorithm. To disable them because of unreadable output set ``cubics=False`` or ``quartics=False`` respectively. If cubic roots are real but are expressed in terms of complex numbers (casus irreducibilis [1]) the ``trig`` flag can be set to True to have the solutions returned in terms of cosine and inverse cosine functions. To get roots from a specific domain set the ``filter`` flag with one of the following specifiers: Z, Q, R, I, C. By default all roots are returned (this is equivalent to setting ``filter='C'``). By default a dictionary is returned giving a compact result in case of multiple roots. However to get a list containing all those roots set the ``multiple`` flag to True; the list will have identical roots appearing next to each other in the result. (For a given Poly, the all_roots method will give the roots in sorted numerical order.) If the ``strict`` flag is True, ``UnsolvableFactorError`` will be raised if the roots found are known to be incomplete (because some roots are not expressible in radicals). Examples ======== >>> from sympy import Poly, roots, degree >>> from sympy.abc import x, y >>> roots(x**2 - 1, x) {-1: 1, 1: 1} >>> p = Poly(x**2-1, x) >>> roots(p) {-1: 1, 1: 1} >>> p = Poly(x**2-y, x, y) >>> roots(Poly(p, x)) {-sqrt(y): 1, sqrt(y): 1} >>> roots(x**2 - y, x) {-sqrt(y): 1, sqrt(y): 1} >>> roots([1, 0, -1]) {-1: 1, 1: 1} ``roots`` will only return roots expressible in radicals. If the given polynomial has some or all of its roots inexpressible in radicals, the result of ``roots`` will be incomplete or empty respectively. Example where result is incomplete: >>> roots((x-1)*(x**5-x+1), x) {1: 1} In this case, the polynomial has an unsolvable quintic factor whose roots cannot be expressed by radicals. The polynomial has a rational root (due to the factor `(x-1)`), which is returned since ``roots`` always finds all rational roots. Example where result is empty: >>> roots(x**7-3*x**2+1, x) {} Here, the polynomial has no roots expressible in radicals, so ``roots`` returns an empty dictionary. The result produced by ``roots`` is complete if and only if the sum of the multiplicity of each root is equal to the degree of the polynomial. If strict=True, UnsolvableFactorError will be raised if the result is incomplete. The result can be be checked for completeness as follows: >>> f = x**3-2*x**2+1 >>> sum(roots(f, x).values()) == degree(f, x) True >>> f = (x-1)*(x**5-x+1) >>> sum(roots(f, x).values()) == degree(f, x) False References ========== .. [1] https://en.wikipedia.org/wiki/Cubic_equation#Trigonometric_and_hyperbolic_solutions """ from sympy.polys.polytools import to_rational_coeffs flags = dict(flags) if isinstance(f, list): if gens: raise ValueError('redundant generators given') x = Dummy('x') poly, i = {}, len(f) - 1 for coeff in f: poly[i], i = sympify(coeff), i - 1 f = Poly(poly, x, field=True) else: try: F = Poly(f, *gens, **flags) if not isinstance(f, Poly) and not F.gen.is_Symbol: raise PolynomialError("generator must be a Symbol") f = F except GeneratorsNeeded: if multiple: return [] else: return {} else: n = f.degree() if f.length() == 2 and n > 2: # check for foo**n in constant if dep is c*gen**m con, dep = f.as_expr().as_independent(*f.gens) fcon = -(-con).factor() if fcon != con: con = fcon bases = [] for i in Mul.make_args(con): if i.is_Pow: b, e = i.as_base_exp() if e.is_Integer and b.is_Add: bases.append((b, Dummy(positive=True))) if bases: rv = roots(Poly((dep + con).xreplace(dict(bases)), *f.gens), *F.gens, auto=auto, cubics=cubics, trig=trig, quartics=quartics, quintics=quintics, multiple=multiple, filter=filter, predicate=predicate, **flags) return {factor_terms(k.xreplace( {v: k for k, v in bases}) ): v for k, v in rv.items()} if f.is_multivariate: raise PolynomialError('multivariate polynomials are not supported') def _update_dict(result, zeros, currentroot, k): if currentroot == S.Zero: if S.Zero in zeros: zeros[S.Zero] += k else: zeros[S.Zero] = k if currentroot in result: result[currentroot] += k else: result[currentroot] = k def _try_decompose(f): """Find roots using functional decomposition. """ factors, roots = f.decompose(), [] for currentroot in _try_heuristics(factors[0]): roots.append(currentroot) for currentfactor in factors[1:]: previous, roots = list(roots), [] for currentroot in previous: g = currentfactor - Poly(currentroot, f.gen) for currentroot in _try_heuristics(g): roots.append(currentroot) return roots def _try_heuristics(f): """Find roots using formulas and some tricks. """ if f.is_ground: return [] if f.is_monomial: return [S.Zero]*f.degree() if f.length() == 2: if f.degree() == 1: return list(map(cancel, roots_linear(f))) else: return roots_binomial(f) result = [] for i in [-1, 1]: if not f.eval(i): f = f.quo(Poly(f.gen - i, f.gen)) result.append(i) break n = f.degree() if n == 1: result += list(map(cancel, roots_linear(f))) elif n == 2: result += list(map(cancel, roots_quadratic(f))) elif f.is_cyclotomic: result += roots_cyclotomic(f) elif n == 3 and cubics: result += roots_cubic(f, trig=trig) elif n == 4 and quartics: result += roots_quartic(f) elif n == 5 and quintics: result += roots_quintic(f) return result # Convert the generators to symbols dumgens = symbols('x:%d' % len(f.gens), cls=Dummy) f = f.per(f.rep, dumgens) (k,), f = f.terms_gcd() if not k: zeros = {} else: zeros = {S.Zero: k} coeff, f = preprocess_roots(f) if auto and f.get_domain().is_Ring: f = f.to_field() # Use EX instead of ZZ_I or QQ_I if f.get_domain().is_QQ_I: f = f.per(f.rep.convert(EX)) rescale_x = None translate_x = None result = {} if not f.is_ground: dom = f.get_domain() if not dom.is_Exact and dom.is_Numerical: for r in f.nroots(): _update_dict(result, zeros, r, 1) elif f.degree() == 1: _update_dict(result, zeros, roots_linear(f)[0], 1) elif f.length() == 2: roots_fun = roots_quadratic if f.degree() == 2 else roots_binomial for r in roots_fun(f): _update_dict(result, zeros, r, 1) else: _, factors = Poly(f.as_expr()).factor_list() if len(factors) == 1 and f.degree() == 2: for r in roots_quadratic(f): _update_dict(result, zeros, r, 1) else: if len(factors) == 1 and factors[0][1] == 1: if f.get_domain().is_EX: res = to_rational_coeffs(f) if res: if res[0] is None: translate_x, f = res[2:] else: rescale_x, f = res[1], res[-1] result = roots(f) if not result: for currentroot in _try_decompose(f): _update_dict(result, zeros, currentroot, 1) else: for r in _try_heuristics(f): _update_dict(result, zeros, r, 1) else: for currentroot in _try_decompose(f): _update_dict(result, zeros, currentroot, 1) else: for currentfactor, k in factors: for r in _try_heuristics(Poly(currentfactor, f.gen, field=True)): _update_dict(result, zeros, r, k) if coeff is not S.One: _result, result, = result, {} for currentroot, k in _result.items(): result[coeff*currentroot] = k if filter not in [None, 'C']: handlers = { 'Z': lambda r: r.is_Integer, 'Q': lambda r: r.is_Rational, 'R': lambda r: all(a.is_real for a in r.as_numer_denom()), 'I': lambda r: r.is_imaginary, } try: query = handlers[filter] except KeyError: raise ValueError("Invalid filter: %s" % filter) for zero in dict(result).keys(): if not query(zero): del result[zero] if predicate is not None: for zero in dict(result).keys(): if not predicate(zero): del result[zero] if rescale_x: result1 = {} for k, v in result.items(): result1[k*rescale_x] = v result = result1 if translate_x: result1 = {} for k, v in result.items(): result1[k + translate_x] = v result = result1 # adding zero roots after non-trivial roots have been translated result.update(zeros) if strict and sum(result.values()) < f.degree(): raise UnsolvableFactorError(filldedent(''' Strict mode: some factors cannot be solved in radicals, so a complete list of solutions cannot be returned. Call roots with strict=False to get solutions expressible in radicals (if there are any). ''')) if not multiple: return result else: zeros = [] for zero in ordered(result): zeros.extend([zero]*result[zero]) return zeros def root_factors(f, *gens, filter=None, **args): """ Returns all factors of a univariate polynomial. Examples ======== >>> from sympy.abc import x, y >>> from sympy.polys.polyroots import root_factors >>> root_factors(x**2 - y, x) [x - sqrt(y), x + sqrt(y)] """ args = dict(args) F = Poly(f, *gens, **args) if not F.is_Poly: return [f] if F.is_multivariate: raise ValueError('multivariate polynomials are not supported') x = F.gens[0] zeros = roots(F, filter=filter) if not zeros: factors = [F] else: factors, N = [], 0 for r, n in ordered(zeros.items()): factors, N = factors + [Poly(x - r, x)]*n, N + n if N < F.degree(): G = reduce(lambda p, q: p*q, factors) factors.append(F.quo(G)) if not isinstance(f, Poly): factors = [ f.as_expr() for f in factors ] return factors
68999af8ab6b2a0bac50bd63cf92000f3eeaeaf73bd2bb1f6d3f4db71243795e
import re import fnmatch message_unicode_B = \ "File contains a unicode character : %s, line %s. " \ "But not in the whitelist. " \ "Add the file to the whitelist in " + __file__ message_unicode_D = \ "File does not contain a unicode character : %s." \ "but is in the whitelist. " \ "Remove the file from the whitelist in " + __file__ encoding_header_re = re.compile( r'^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)') # Whitelist pattern for files which can have unicode. unicode_whitelist = [ # Author names can include non-ASCII characters r'*/bin/authors_update.py', r'*/bin/mailmap_check.py', # These files have functions and test functions for unicode input and # output. r'*/sympy/testing/tests/test_code_quality.py', r'*/sympy/physics/vector/tests/test_printing.py', r'*/physics/quantum/tests/test_printing.py', r'*/sympy/vector/tests/test_printing.py', r'*/sympy/parsing/tests/test_sympy_parser.py', r'*/sympy/printing/pretty/tests/test_pretty.py', r'*/sympy/printing/tests/test_conventions.py', r'*/sympy/printing/tests/test_preview.py', r'*/liealgebras/type_g.py', r'*/liealgebras/weyl_group.py', r'*/liealgebras/tests/test_type_G.py', # wigner.py and polarization.py have unicode doctests. These probably # don't need to be there but some of the examples that are there are # pretty ugly without use_unicode (matrices need to be wrapped across # multiple lines etc) r'*/sympy/physics/wigner.py', r'*/sympy/physics/optics/polarization.py', # joint.py uses some unicode for variable names in the docstrings r'*/sympy/physics/mechanics/joint.py', # lll method has unicode in docstring references and author name r'*/sympy/polys/matrices/domainmatrix.py', ] unicode_strict_whitelist = [ r'*/sympy/parsing/latex/_antlr/__init__.py', # test_mathematica.py uses some unicode for testing Greek characters are working #24055 r'*/sympy/parsing/tests/test_mathematica.py', ] def _test_this_file_encoding( fname, test_file, unicode_whitelist=unicode_whitelist, unicode_strict_whitelist=unicode_strict_whitelist): """Test helper function for unicode test The test may have to operate on filewise manner, so it had moved to a separate process. """ has_unicode = False is_in_whitelist = False is_in_strict_whitelist = False for patt in unicode_whitelist: if fnmatch.fnmatch(fname, patt): is_in_whitelist = True break for patt in unicode_strict_whitelist: if fnmatch.fnmatch(fname, patt): is_in_strict_whitelist = True is_in_whitelist = True break if is_in_whitelist: for idx, line in enumerate(test_file): try: line.encode(encoding='ascii') except (UnicodeEncodeError, UnicodeDecodeError): has_unicode = True if not has_unicode and not is_in_strict_whitelist: assert False, message_unicode_D % fname else: for idx, line in enumerate(test_file): try: line.encode(encoding='ascii') except (UnicodeEncodeError, UnicodeDecodeError): assert False, message_unicode_B % (fname, idx + 1)
dedfcdbbddbfaf4089cebbc894261221b69b6270483becf6af79e350ab2c349d
from __future__ import annotations from typing import TYPE_CHECKING from sympy.simplify import simplify as simp, trigsimp as tsimp # type: ignore from sympy.core.decorators import call_highest_priority, _sympifyit from sympy.core.assumptions import StdFactKB from sympy.core.function import diff as df from sympy.integrals.integrals import Integral from sympy.polys.polytools import factor as fctr from sympy.core import S, Add, Mul from sympy.core.expr import Expr if TYPE_CHECKING: from sympy.vector.vector import BaseVector class BasisDependent(Expr): """ Super class containing functionality common to vectors and dyadics. Named so because the representation of these quantities in sympy.vector is dependent on the basis they are expressed in. """ zero: BasisDependentZero @call_highest_priority('__radd__') def __add__(self, other): return self._add_func(self, other) @call_highest_priority('__add__') def __radd__(self, other): return self._add_func(other, self) @call_highest_priority('__rsub__') def __sub__(self, other): return self._add_func(self, -other) @call_highest_priority('__sub__') def __rsub__(self, other): return self._add_func(other, -self) @_sympifyit('other', NotImplemented) @call_highest_priority('__rmul__') def __mul__(self, other): return self._mul_func(self, other) @_sympifyit('other', NotImplemented) @call_highest_priority('__mul__') def __rmul__(self, other): return self._mul_func(other, self) def __neg__(self): return self._mul_func(S.NegativeOne, self) @_sympifyit('other', NotImplemented) @call_highest_priority('__rtruediv__') def __truediv__(self, other): return self._div_helper(other) @call_highest_priority('__truediv__') def __rtruediv__(self, other): return TypeError("Invalid divisor for division") def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False): """ Implements the SymPy evalf routine for this quantity. evalf's documentation ===================== """ options = {'subs':subs, 'maxn':maxn, 'chop':chop, 'strict':strict, 'quad':quad, 'verbose':verbose} vec = self.zero for k, v in self.components.items(): vec += v.evalf(n, **options) * k return vec evalf.__doc__ += Expr.evalf.__doc__ # type: ignore n = evalf def simplify(self, **kwargs): """ Implements the SymPy simplify routine for this quantity. simplify's documentation ======================== """ simp_components = [simp(v, **kwargs) * k for k, v in self.components.items()] return self._add_func(*simp_components) simplify.__doc__ += simp.__doc__ # type: ignore def trigsimp(self, **opts): """ Implements the SymPy trigsimp routine, for this quantity. trigsimp's documentation ======================== """ trig_components = [tsimp(v, **opts) * k for k, v in self.components.items()] return self._add_func(*trig_components) trigsimp.__doc__ += tsimp.__doc__ # type: ignore def _eval_simplify(self, **kwargs): return self.simplify(**kwargs) def _eval_trigsimp(self, **opts): return self.trigsimp(**opts) def _eval_derivative(self, wrt): return self.diff(wrt) def _eval_Integral(self, *symbols, **assumptions): integral_components = [Integral(v, *symbols, **assumptions) * k for k, v in self.components.items()] return self._add_func(*integral_components) def as_numer_denom(self): """ Returns the expression as a tuple wrt the following transformation - expression -> a/b -> a, b """ return self, S.One def factor(self, *args, **kwargs): """ Implements the SymPy factor routine, on the scalar parts of a basis-dependent expression. factor's documentation ======================== """ fctr_components = [fctr(v, *args, **kwargs) * k for k, v in self.components.items()] return self._add_func(*fctr_components) factor.__doc__ += fctr.__doc__ # type: ignore def as_coeff_Mul(self, rational=False): """Efficiently extract the coefficient of a product.""" return (S.One, self) def as_coeff_add(self, *deps): """Efficiently extract the coefficient of a summation.""" l = [x * self.components[x] for x in self.components] return 0, tuple(l) def diff(self, *args, **kwargs): """ Implements the SymPy diff routine, for vectors. diff's documentation ======================== """ for x in args: if isinstance(x, BasisDependent): raise TypeError("Invalid arg for differentiation") diff_components = [df(v, *args, **kwargs) * k for k, v in self.components.items()] return self._add_func(*diff_components) diff.__doc__ += df.__doc__ # type: ignore def doit(self, **hints): """Calls .doit() on each term in the Dyadic""" doit_components = [self.components[x].doit(**hints) * x for x in self.components] return self._add_func(*doit_components) class BasisDependentAdd(BasisDependent, Add): """ Denotes sum of basis dependent quantities such that they cannot be expressed as base or Mul instances. """ def __new__(cls, *args, **options): components = {} # Check each arg and simultaneously learn the components for i, arg in enumerate(args): if not isinstance(arg, cls._expr_type): if isinstance(arg, Mul): arg = cls._mul_func(*(arg.args)) elif isinstance(arg, Add): arg = cls._add_func(*(arg.args)) else: raise TypeError(str(arg) + " cannot be interpreted correctly") # If argument is zero, ignore if arg == cls.zero: continue # Else, update components accordingly if hasattr(arg, "components"): for x in arg.components: components[x] = components.get(x, 0) + arg.components[x] temp = list(components.keys()) for x in temp: if components[x] == 0: del components[x] # Handle case of zero vector if len(components) == 0: return cls.zero # Build object newargs = [x * components[x] for x in components] obj = super().__new__(cls, *newargs, **options) if isinstance(obj, Mul): return cls._mul_func(*obj.args) assumptions = {'commutative': True} obj._assumptions = StdFactKB(assumptions) obj._components = components obj._sys = (list(components.keys()))[0]._sys return obj class BasisDependentMul(BasisDependent, Mul): """ Denotes product of base- basis dependent quantity with a scalar. """ def __new__(cls, *args, **options): from sympy.vector import Cross, Dot, Curl, Gradient count = 0 measure_number = S.One zeroflag = False extra_args = [] # Determine the component and check arguments # Also keep a count to ensure two vectors aren't # being multiplied for arg in args: if isinstance(arg, cls._zero_func): count += 1 zeroflag = True elif arg == S.Zero: zeroflag = True elif isinstance(arg, (cls._base_func, cls._mul_func)): count += 1 expr = arg._base_instance measure_number *= arg._measure_number elif isinstance(arg, cls._add_func): count += 1 expr = arg elif isinstance(arg, (Cross, Dot, Curl, Gradient)): extra_args.append(arg) else: measure_number *= arg # Make sure incompatible types weren't multiplied if count > 1: raise ValueError("Invalid multiplication") elif count == 0: return Mul(*args, **options) # Handle zero vector case if zeroflag: return cls.zero # If one of the args was a VectorAdd, return an # appropriate VectorAdd instance if isinstance(expr, cls._add_func): newargs = [cls._mul_func(measure_number, x) for x in expr.args] return cls._add_func(*newargs) obj = super().__new__(cls, measure_number, expr._base_instance, *extra_args, **options) if isinstance(obj, Add): return cls._add_func(*obj.args) obj._base_instance = expr._base_instance obj._measure_number = measure_number assumptions = {'commutative': True} obj._assumptions = StdFactKB(assumptions) obj._components = {expr._base_instance: measure_number} obj._sys = expr._base_instance._sys return obj def _sympystr(self, printer): measure_str = printer._print(self._measure_number) if ('(' in measure_str or '-' in measure_str or '+' in measure_str): measure_str = '(' + measure_str + ')' return measure_str + '*' + printer._print(self._base_instance) class BasisDependentZero(BasisDependent): """ Class to denote a zero basis dependent instance. """ components: dict['BaseVector', Expr] = {} _latex_form: str def __new__(cls): obj = super().__new__(cls) # Pre-compute a specific hash value for the zero vector # Use the same one always obj._hash = tuple([S.Zero, cls]).__hash__() return obj def __hash__(self): return self._hash @call_highest_priority('__req__') def __eq__(self, other): return isinstance(other, self._zero_func) __req__ = __eq__ @call_highest_priority('__radd__') def __add__(self, other): if isinstance(other, self._expr_type): return other else: raise TypeError("Invalid argument types for addition") @call_highest_priority('__add__') def __radd__(self, other): if isinstance(other, self._expr_type): return other else: raise TypeError("Invalid argument types for addition") @call_highest_priority('__rsub__') def __sub__(self, other): if isinstance(other, self._expr_type): return -other else: raise TypeError("Invalid argument types for subtraction") @call_highest_priority('__sub__') def __rsub__(self, other): if isinstance(other, self._expr_type): return other else: raise TypeError("Invalid argument types for subtraction") def __neg__(self): return self def normalize(self): """ Returns the normalized version of this vector. """ return self def _sympystr(self, printer): return '0'
f03b46921414ca5795222e567e9b59384936ce7d24c15019bf969e348e3df2d8
"""Geometrical Points. Contains ======== Point Point2D Point3D When methods of Point require 1 or more points as arguments, they can be passed as a sequence of coordinates or Points: >>> from sympy import Point >>> Point(1, 1).is_collinear((2, 2), (3, 4)) False >>> Point(1, 1).is_collinear(Point(2, 2), Point(3, 4)) False """ import warnings from sympy.core import S, sympify, Expr from sympy.core.add import Add from sympy.core.containers import Tuple from sympy.core.numbers import Float from sympy.core.parameters import global_parameters from sympy.simplify import nsimplify, simplify from sympy.geometry.exceptions import GeometryError from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.complexes import im from sympy.functions.elementary.trigonometric import cos, sin from sympy.matrices import Matrix from sympy.matrices.expressions import Transpose from sympy.utilities.iterables import uniq, is_sequence from sympy.utilities.misc import filldedent, func_name, Undecidable from .entity import GeometryEntity from mpmath.libmp.libmpf import prec_to_dps class Point(GeometryEntity): """A point in a n-dimensional Euclidean space. Parameters ========== coords : sequence of n-coordinate values. In the special case where n=2 or 3, a Point2D or Point3D will be created as appropriate. evaluate : if `True` (default), all floats are turn into exact types. dim : number of coordinates the point should have. If coordinates are unspecified, they are padded with zeros. on_morph : indicates what should happen when the number of coordinates of a point need to be changed by adding or removing zeros. Possible values are `'warn'`, `'error'`, or `ignore` (default). No warning or error is given when `*args` is empty and `dim` is given. An error is always raised when trying to remove nonzero coordinates. Attributes ========== length origin: A `Point` representing the origin of the appropriately-dimensioned space. Raises ====== TypeError : When instantiating with anything but a Point or sequence ValueError : when instantiating with a sequence with length < 2 or when trying to reduce dimensions if keyword `on_morph='error'` is set. See Also ======== sympy.geometry.line.Segment : Connects two Points Examples ======== >>> from sympy import Point >>> from sympy.abc import x >>> Point(1, 2, 3) Point3D(1, 2, 3) >>> Point([1, 2]) Point2D(1, 2) >>> Point(0, x) Point2D(0, x) >>> Point(dim=4) Point(0, 0, 0, 0) Floats are automatically converted to Rational unless the evaluate flag is False: >>> Point(0.5, 0.25) Point2D(1/2, 1/4) >>> Point(0.5, 0.25, evaluate=False) Point2D(0.5, 0.25) """ is_Point = True def __new__(cls, *args, **kwargs): evaluate = kwargs.get('evaluate', global_parameters.evaluate) on_morph = kwargs.get('on_morph', 'ignore') # unpack into coords coords = args[0] if len(args) == 1 else args # check args and handle quickly handle Point instances if isinstance(coords, Point): # even if we're mutating the dimension of a point, we # don't reevaluate its coordinates evaluate = False if len(coords) == kwargs.get('dim', len(coords)): return coords if not is_sequence(coords): raise TypeError(filldedent(''' Expecting sequence of coordinates, not `{}`''' .format(func_name(coords)))) # A point where only `dim` is specified is initialized # to zeros. if len(coords) == 0 and kwargs.get('dim', None): coords = (S.Zero,)*kwargs.get('dim') coords = Tuple(*coords) dim = kwargs.get('dim', len(coords)) if len(coords) < 2: raise ValueError(filldedent(''' Point requires 2 or more coordinates or keyword `dim` > 1.''')) if len(coords) != dim: message = ("Dimension of {} needs to be changed " "from {} to {}.").format(coords, len(coords), dim) if on_morph == 'ignore': pass elif on_morph == "error": raise ValueError(message) elif on_morph == 'warn': warnings.warn(message, stacklevel=2) else: raise ValueError(filldedent(''' on_morph value should be 'error', 'warn' or 'ignore'.''')) if any(coords[dim:]): raise ValueError('Nonzero coordinates cannot be removed.') if any(a.is_number and im(a).is_zero is False for a in coords): raise ValueError('Imaginary coordinates are not permitted.') if not all(isinstance(a, Expr) for a in coords): raise TypeError('Coordinates must be valid SymPy expressions.') # pad with zeros appropriately coords = coords[:dim] + (S.Zero,)*(dim - len(coords)) # Turn any Floats into rationals and simplify # any expressions before we instantiate if evaluate: coords = coords.xreplace({ f: simplify(nsimplify(f, rational=True)) for f in coords.atoms(Float)}) # return 2D or 3D instances if len(coords) == 2: kwargs['_nocheck'] = True return Point2D(*coords, **kwargs) elif len(coords) == 3: kwargs['_nocheck'] = True return Point3D(*coords, **kwargs) # the general Point return GeometryEntity.__new__(cls, *coords) def __abs__(self): """Returns the distance between this point and the origin.""" origin = Point([0]*len(self)) return Point.distance(origin, self) def __add__(self, other): """Add other to self by incrementing self's coordinates by those of other. Notes ===== >>> from sympy import Point When sequences of coordinates are passed to Point methods, they are converted to a Point internally. This __add__ method does not do that so if floating point values are used, a floating point result (in terms of SymPy Floats) will be returned. >>> Point(1, 2) + (.1, .2) Point2D(1.1, 2.2) If this is not desired, the `translate` method can be used or another Point can be added: >>> Point(1, 2).translate(.1, .2) Point2D(11/10, 11/5) >>> Point(1, 2) + Point(.1, .2) Point2D(11/10, 11/5) See Also ======== sympy.geometry.point.Point.translate """ try: s, o = Point._normalize_dimension(self, Point(other, evaluate=False)) except TypeError: raise GeometryError("Don't know how to add {} and a Point object".format(other)) coords = [simplify(a + b) for a, b in zip(s, o)] return Point(coords, evaluate=False) def __contains__(self, item): return item in self.args def __truediv__(self, divisor): """Divide point's coordinates by a factor.""" divisor = sympify(divisor) coords = [simplify(x/divisor) for x in self.args] return Point(coords, evaluate=False) def __eq__(self, other): if not isinstance(other, Point) or len(self.args) != len(other.args): return False return self.args == other.args def __getitem__(self, key): return self.args[key] def __hash__(self): return hash(self.args) def __iter__(self): return self.args.__iter__() def __len__(self): return len(self.args) def __mul__(self, factor): """Multiply point's coordinates by a factor. Notes ===== >>> from sympy import Point When multiplying a Point by a floating point number, the coordinates of the Point will be changed to Floats: >>> Point(1, 2)*0.1 Point2D(0.1, 0.2) If this is not desired, the `scale` method can be used or else only multiply or divide by integers: >>> Point(1, 2).scale(1.1, 1.1) Point2D(11/10, 11/5) >>> Point(1, 2)*11/10 Point2D(11/10, 11/5) See Also ======== sympy.geometry.point.Point.scale """ factor = sympify(factor) coords = [simplify(x*factor) for x in self.args] return Point(coords, evaluate=False) def __rmul__(self, factor): """Multiply a factor by point's coordinates.""" return self.__mul__(factor) def __neg__(self): """Negate the point.""" coords = [-x for x in self.args] return Point(coords, evaluate=False) def __sub__(self, other): """Subtract two points, or subtract a factor from this point's coordinates.""" return self + [-x for x in other] @classmethod def _normalize_dimension(cls, *points, **kwargs): """Ensure that points have the same dimension. By default `on_morph='warn'` is passed to the `Point` constructor.""" # if we have a built-in ambient dimension, use it dim = getattr(cls, '_ambient_dimension', None) # override if we specified it dim = kwargs.get('dim', dim) # if no dim was given, use the highest dimensional point if dim is None: dim = max(i.ambient_dimension for i in points) if all(i.ambient_dimension == dim for i in points): return list(points) kwargs['dim'] = dim kwargs['on_morph'] = kwargs.get('on_morph', 'warn') return [Point(i, **kwargs) for i in points] @staticmethod def affine_rank(*args): """The affine rank of a set of points is the dimension of the smallest affine space containing all the points. For example, if the points lie on a line (and are not all the same) their affine rank is 1. If the points lie on a plane but not a line, their affine rank is 2. By convention, the empty set has affine rank -1.""" if len(args) == 0: return -1 # make sure we're genuinely points # and translate every point to the origin points = Point._normalize_dimension(*[Point(i) for i in args]) origin = points[0] points = [i - origin for i in points[1:]] m = Matrix([i.args for i in points]) # XXX fragile -- what is a better way? return m.rank(iszerofunc = lambda x: abs(x.n(2)) < 1e-12 if x.is_number else x.is_zero) @property def ambient_dimension(self): """Number of components this point has.""" return getattr(self, '_ambient_dimension', len(self)) @classmethod def are_coplanar(cls, *points): """Return True if there exists a plane in which all the points lie. A trivial True value is returned if `len(points) < 3` or all Points are 2-dimensional. Parameters ========== A set of points Raises ====== ValueError : if less than 3 unique points are given Returns ======= boolean Examples ======== >>> from sympy import Point3D >>> p1 = Point3D(1, 2, 2) >>> p2 = Point3D(2, 7, 2) >>> p3 = Point3D(0, 0, 2) >>> p4 = Point3D(1, 1, 2) >>> Point3D.are_coplanar(p1, p2, p3, p4) True >>> p5 = Point3D(0, 1, 3) >>> Point3D.are_coplanar(p1, p2, p3, p5) False """ if len(points) <= 1: return True points = cls._normalize_dimension(*[Point(i) for i in points]) # quick exit if we are in 2D if points[0].ambient_dimension == 2: return True points = list(uniq(points)) return Point.affine_rank(*points) <= 2 def distance(self, other): """The Euclidean distance between self and another GeometricEntity. Returns ======= distance : number or symbolic expression. Raises ====== TypeError : if other is not recognized as a GeometricEntity or is a GeometricEntity for which distance is not defined. See Also ======== sympy.geometry.line.Segment.length sympy.geometry.point.Point.taxicab_distance Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(1, 1), Point(4, 5) >>> l = Line((3, 1), (2, 2)) >>> p1.distance(p2) 5 >>> p1.distance(l) sqrt(2) The computed distance may be symbolic, too: >>> from sympy.abc import x, y >>> p3 = Point(x, y) >>> p3.distance((0, 0)) sqrt(x**2 + y**2) """ if not isinstance(other, GeometryEntity): try: other = Point(other, dim=self.ambient_dimension) except TypeError: raise TypeError("not recognized as a GeometricEntity: %s" % type(other)) if isinstance(other, Point): s, p = Point._normalize_dimension(self, Point(other)) return sqrt(Add(*((a - b)**2 for a, b in zip(s, p)))) distance = getattr(other, 'distance', None) if distance is None: raise TypeError("distance between Point and %s is not defined" % type(other)) return distance(self) def dot(self, p): """Return dot product of self with another Point.""" if not is_sequence(p): p = Point(p) # raise the error via Point return Add(*(a*b for a, b in zip(self, p))) def equals(self, other): """Returns whether the coordinates of self and other agree.""" # a point is equal to another point if all its components are equal if not isinstance(other, Point) or len(self) != len(other): return False return all(a.equals(b) for a, b in zip(self, other)) def _eval_evalf(self, prec=15, **options): """Evaluate the coordinates of the point. This method will, where possible, create and return a new Point where the coordinates are evaluated as floating point numbers to the precision indicated (default=15). Parameters ========== prec : int Returns ======= point : Point Examples ======== >>> from sympy import Point, Rational >>> p1 = Point(Rational(1, 2), Rational(3, 2)) >>> p1 Point2D(1/2, 3/2) >>> p1.evalf() Point2D(0.5, 1.5) """ dps = prec_to_dps(prec) coords = [x.evalf(n=dps, **options) for x in self.args] return Point(*coords, evaluate=False) def intersection(self, other): """The intersection between this point and another GeometryEntity. Parameters ========== other : GeometryEntity or sequence of coordinates Returns ======= intersection : list of Points Notes ===== The return value will either be an empty list if there is no intersection, otherwise it will contain this point. Examples ======== >>> from sympy import Point >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, 0) >>> p1.intersection(p2) [] >>> p1.intersection(p3) [Point2D(0, 0)] """ if not isinstance(other, GeometryEntity): other = Point(other) if isinstance(other, Point): if self == other: return [self] p1, p2 = Point._normalize_dimension(self, other) if p1 == self and p1 == p2: return [self] return [] return other.intersection(self) def is_collinear(self, *args): """Returns `True` if there exists a line that contains `self` and `points`. Returns `False` otherwise. A trivially True value is returned if no points are given. Parameters ========== args : sequence of Points Returns ======= is_collinear : boolean See Also ======== sympy.geometry.line.Line Examples ======== >>> from sympy import Point >>> from sympy.abc import x >>> p1, p2 = Point(0, 0), Point(1, 1) >>> p3, p4, p5 = Point(2, 2), Point(x, x), Point(1, 2) >>> Point.is_collinear(p1, p2, p3, p4) True >>> Point.is_collinear(p1, p2, p3, p5) False """ points = (self,) + args points = Point._normalize_dimension(*[Point(i) for i in points]) points = list(uniq(points)) return Point.affine_rank(*points) <= 1 def is_concyclic(self, *args): """Do `self` and the given sequence of points lie in a circle? Returns True if the set of points are concyclic and False otherwise. A trivial value of True is returned if there are fewer than 2 other points. Parameters ========== args : sequence of Points Returns ======= is_concyclic : boolean Examples ======== >>> from sympy import Point Define 4 points that are on the unit circle: >>> p1, p2, p3, p4 = Point(1, 0), (0, 1), (-1, 0), (0, -1) >>> p1.is_concyclic() == p1.is_concyclic(p2, p3, p4) == True True Define a point not on that circle: >>> p = Point(1, 1) >>> p.is_concyclic(p1, p2, p3) False """ points = (self,) + args points = Point._normalize_dimension(*[Point(i) for i in points]) points = list(uniq(points)) if not Point.affine_rank(*points) <= 2: return False origin = points[0] points = [p - origin for p in points] # points are concyclic if they are coplanar and # there is a point c so that ||p_i-c|| == ||p_j-c|| for all # i and j. Rearranging this equation gives us the following # condition: the matrix `mat` must not a pivot in the last # column. mat = Matrix([list(i) + [i.dot(i)] for i in points]) rref, pivots = mat.rref() if len(origin) not in pivots: return True return False @property def is_nonzero(self): """True if any coordinate is nonzero, False if every coordinate is zero, and None if it cannot be determined.""" is_zero = self.is_zero if is_zero is None: return None return not is_zero def is_scalar_multiple(self, p): """Returns whether each coordinate of `self` is a scalar multiple of the corresponding coordinate in point p. """ s, o = Point._normalize_dimension(self, Point(p)) # 2d points happen a lot, so optimize this function call if s.ambient_dimension == 2: (x1, y1), (x2, y2) = s.args, o.args rv = (x1*y2 - x2*y1).equals(0) if rv is None: raise Undecidable(filldedent( '''Cannot determine if %s is a scalar multiple of %s''' % (s, o))) # if the vectors p1 and p2 are linearly dependent, then they must # be scalar multiples of each other m = Matrix([s.args, o.args]) return m.rank() < 2 @property def is_zero(self): """True if every coordinate is zero, False if any coordinate is not zero, and None if it cannot be determined.""" nonzero = [x.is_nonzero for x in self.args] if any(nonzero): return False if any(x is None for x in nonzero): return None return True @property def length(self): """ Treating a Point as a Line, this returns 0 for the length of a Point. Examples ======== >>> from sympy import Point >>> p = Point(0, 1) >>> p.length 0 """ return S.Zero def midpoint(self, p): """The midpoint between self and point p. Parameters ========== p : Point Returns ======= midpoint : Point See Also ======== sympy.geometry.line.Segment.midpoint Examples ======== >>> from sympy import Point >>> p1, p2 = Point(1, 1), Point(13, 5) >>> p1.midpoint(p2) Point2D(7, 3) """ s, p = Point._normalize_dimension(self, Point(p)) return Point([simplify((a + b)*S.Half) for a, b in zip(s, p)]) @property def origin(self): """A point of all zeros of the same ambient dimension as the current point""" return Point([0]*len(self), evaluate=False) @property def orthogonal_direction(self): """Returns a non-zero point that is orthogonal to the line containing `self` and the origin. Examples ======== >>> from sympy import Line, Point >>> a = Point(1, 2, 3) >>> a.orthogonal_direction Point3D(-2, 1, 0) >>> b = _ >>> Line(b, b.origin).is_perpendicular(Line(a, a.origin)) True """ dim = self.ambient_dimension # if a coordinate is zero, we can put a 1 there and zeros elsewhere if self[0].is_zero: return Point([1] + (dim - 1)*[0]) if self[1].is_zero: return Point([0,1] + (dim - 2)*[0]) # if the first two coordinates aren't zero, we can create a non-zero # orthogonal vector by swapping them, negating one, and padding with zeros return Point([-self[1], self[0]] + (dim - 2)*[0]) @staticmethod def project(a, b): """Project the point `a` onto the line between the origin and point `b` along the normal direction. Parameters ========== a : Point b : Point Returns ======= p : Point See Also ======== sympy.geometry.line.LinearEntity.projection Examples ======== >>> from sympy import Line, Point >>> a = Point(1, 2) >>> b = Point(2, 5) >>> z = a.origin >>> p = Point.project(a, b) >>> Line(p, a).is_perpendicular(Line(p, b)) True >>> Point.is_collinear(z, p, b) True """ a, b = Point._normalize_dimension(Point(a), Point(b)) if b.is_zero: raise ValueError("Cannot project to the zero vector.") return b*(a.dot(b) / b.dot(b)) def taxicab_distance(self, p): """The Taxicab Distance from self to point p. Returns the sum of the horizontal and vertical distances to point p. Parameters ========== p : Point Returns ======= taxicab_distance : The sum of the horizontal and vertical distances to point p. See Also ======== sympy.geometry.point.Point.distance Examples ======== >>> from sympy import Point >>> p1, p2 = Point(1, 1), Point(4, 5) >>> p1.taxicab_distance(p2) 7 """ s, p = Point._normalize_dimension(self, Point(p)) return Add(*(abs(a - b) for a, b in zip(s, p))) def canberra_distance(self, p): """The Canberra Distance from self to point p. Returns the weighted sum of horizontal and vertical distances to point p. Parameters ========== p : Point Returns ======= canberra_distance : The weighted sum of horizontal and vertical distances to point p. The weight used is the sum of absolute values of the coordinates. Examples ======== >>> from sympy import Point >>> p1, p2 = Point(1, 1), Point(3, 3) >>> p1.canberra_distance(p2) 1 >>> p1, p2 = Point(0, 0), Point(3, 3) >>> p1.canberra_distance(p2) 2 Raises ====== ValueError when both vectors are zero. See Also ======== sympy.geometry.point.Point.distance """ s, p = Point._normalize_dimension(self, Point(p)) if self.is_zero and p.is_zero: raise ValueError("Cannot project to the zero vector.") return Add(*((abs(a - b)/(abs(a) + abs(b))) for a, b in zip(s, p))) @property def unit(self): """Return the Point that is in the same direction as `self` and a distance of 1 from the origin""" return self / abs(self) class Point2D(Point): """A point in a 2-dimensional Euclidean space. Parameters ========== coords A sequence of 2 coordinate values. Attributes ========== x y length Raises ====== TypeError When trying to add or subtract points with different dimensions. When trying to create a point with more than two dimensions. When `intersection` is called with object other than a Point. See Also ======== sympy.geometry.line.Segment : Connects two Points Examples ======== >>> from sympy import Point2D >>> from sympy.abc import x >>> Point2D(1, 2) Point2D(1, 2) >>> Point2D([1, 2]) Point2D(1, 2) >>> Point2D(0, x) Point2D(0, x) Floats are automatically converted to Rational unless the evaluate flag is False: >>> Point2D(0.5, 0.25) Point2D(1/2, 1/4) >>> Point2D(0.5, 0.25, evaluate=False) Point2D(0.5, 0.25) """ _ambient_dimension = 2 def __new__(cls, *args, _nocheck=False, **kwargs): if not _nocheck: kwargs['dim'] = 2 args = Point(*args, **kwargs) return GeometryEntity.__new__(cls, *args) def __contains__(self, item): return item == self @property def bounds(self): """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding rectangle for the geometric figure. """ return (self.x, self.y, self.x, self.y) def rotate(self, angle, pt=None): """Rotate ``angle`` radians counterclockwise about Point ``pt``. See Also ======== translate, scale Examples ======== >>> from sympy import Point2D, pi >>> t = Point2D(1, 0) >>> t.rotate(pi/2) Point2D(0, 1) >>> t.rotate(pi/2, (2, 0)) Point2D(2, -1) """ c = cos(angle) s = sin(angle) rv = self if pt is not None: pt = Point(pt, dim=2) rv -= pt x, y = rv.args rv = Point(c*x - s*y, s*x + c*y) if pt is not None: rv += pt return rv def scale(self, x=1, y=1, pt=None): """Scale the coordinates of the Point by multiplying by ``x`` and ``y`` after subtracting ``pt`` -- default is (0, 0) -- and then adding ``pt`` back again (i.e. ``pt`` is the point of reference for the scaling). See Also ======== rotate, translate Examples ======== >>> from sympy import Point2D >>> t = Point2D(1, 1) >>> t.scale(2) Point2D(2, 1) >>> t.scale(2, 2) Point2D(2, 2) """ if pt: pt = Point(pt, dim=2) return self.translate(*(-pt).args).scale(x, y).translate(*pt.args) return Point(self.x*x, self.y*y) def transform(self, matrix): """Return the point after applying the transformation described by the 3x3 Matrix, ``matrix``. See Also ======== sympy.geometry.point.Point2D.rotate sympy.geometry.point.Point2D.scale sympy.geometry.point.Point2D.translate """ if not (matrix.is_Matrix and matrix.shape == (3, 3)): raise ValueError("matrix must be a 3x3 matrix") x, y = self.args return Point(*(Matrix(1, 3, [x, y, 1])*matrix).tolist()[0][:2]) def translate(self, x=0, y=0): """Shift the Point by adding x and y to the coordinates of the Point. See Also ======== sympy.geometry.point.Point2D.rotate, scale Examples ======== >>> from sympy import Point2D >>> t = Point2D(0, 1) >>> t.translate(2) Point2D(2, 1) >>> t.translate(2, 2) Point2D(2, 3) >>> t + Point2D(2, 2) Point2D(2, 3) """ return Point(self.x + x, self.y + y) @property def coordinates(self): """ Returns the two coordinates of the Point. Examples ======== >>> from sympy import Point2D >>> p = Point2D(0, 1) >>> p.coordinates (0, 1) """ return self.args @property def x(self): """ Returns the X coordinate of the Point. Examples ======== >>> from sympy import Point2D >>> p = Point2D(0, 1) >>> p.x 0 """ return self.args[0] @property def y(self): """ Returns the Y coordinate of the Point. Examples ======== >>> from sympy import Point2D >>> p = Point2D(0, 1) >>> p.y 1 """ return self.args[1] class Point3D(Point): """A point in a 3-dimensional Euclidean space. Parameters ========== coords A sequence of 3 coordinate values. Attributes ========== x y z length Raises ====== TypeError When trying to add or subtract points with different dimensions. When `intersection` is called with object other than a Point. Examples ======== >>> from sympy import Point3D >>> from sympy.abc import x >>> Point3D(1, 2, 3) Point3D(1, 2, 3) >>> Point3D([1, 2, 3]) Point3D(1, 2, 3) >>> Point3D(0, x, 3) Point3D(0, x, 3) Floats are automatically converted to Rational unless the evaluate flag is False: >>> Point3D(0.5, 0.25, 2) Point3D(1/2, 1/4, 2) >>> Point3D(0.5, 0.25, 3, evaluate=False) Point3D(0.5, 0.25, 3) """ _ambient_dimension = 3 def __new__(cls, *args, _nocheck=False, **kwargs): if not _nocheck: kwargs['dim'] = 3 args = Point(*args, **kwargs) return GeometryEntity.__new__(cls, *args) def __contains__(self, item): return item == self @staticmethod def are_collinear(*points): """Is a sequence of points collinear? Test whether or not a set of points are collinear. Returns True if the set of points are collinear, or False otherwise. Parameters ========== points : sequence of Point Returns ======= are_collinear : boolean See Also ======== sympy.geometry.line.Line3D Examples ======== >>> from sympy import Point3D >>> from sympy.abc import x >>> p1, p2 = Point3D(0, 0, 0), Point3D(1, 1, 1) >>> p3, p4, p5 = Point3D(2, 2, 2), Point3D(x, x, x), Point3D(1, 2, 6) >>> Point3D.are_collinear(p1, p2, p3, p4) True >>> Point3D.are_collinear(p1, p2, p3, p5) False """ return Point.is_collinear(*points) def direction_cosine(self, point): """ Gives the direction cosine between 2 points Parameters ========== p : Point3D Returns ======= list Examples ======== >>> from sympy import Point3D >>> p1 = Point3D(1, 2, 3) >>> p1.direction_cosine(Point3D(2, 3, 5)) [sqrt(6)/6, sqrt(6)/6, sqrt(6)/3] """ a = self.direction_ratio(point) b = sqrt(Add(*(i**2 for i in a))) return [(point.x - self.x) / b,(point.y - self.y) / b, (point.z - self.z) / b] def direction_ratio(self, point): """ Gives the direction ratio between 2 points Parameters ========== p : Point3D Returns ======= list Examples ======== >>> from sympy import Point3D >>> p1 = Point3D(1, 2, 3) >>> p1.direction_ratio(Point3D(2, 3, 5)) [1, 1, 2] """ return [(point.x - self.x),(point.y - self.y),(point.z - self.z)] def intersection(self, other): """The intersection between this point and another GeometryEntity. Parameters ========== other : GeometryEntity or sequence of coordinates Returns ======= intersection : list of Points Notes ===== The return value will either be an empty list if there is no intersection, otherwise it will contain this point. Examples ======== >>> from sympy import Point3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, 0, 0) >>> p1.intersection(p2) [] >>> p1.intersection(p3) [Point3D(0, 0, 0)] """ if not isinstance(other, GeometryEntity): other = Point(other, dim=3) if isinstance(other, Point3D): if self == other: return [self] return [] return other.intersection(self) def scale(self, x=1, y=1, z=1, pt=None): """Scale the coordinates of the Point by multiplying by ``x`` and ``y`` after subtracting ``pt`` -- default is (0, 0) -- and then adding ``pt`` back again (i.e. ``pt`` is the point of reference for the scaling). See Also ======== translate Examples ======== >>> from sympy import Point3D >>> t = Point3D(1, 1, 1) >>> t.scale(2) Point3D(2, 1, 1) >>> t.scale(2, 2) Point3D(2, 2, 1) """ if pt: pt = Point3D(pt) return self.translate(*(-pt).args).scale(x, y, z).translate(*pt.args) return Point3D(self.x*x, self.y*y, self.z*z) def transform(self, matrix): """Return the point after applying the transformation described by the 4x4 Matrix, ``matrix``. See Also ======== sympy.geometry.point.Point3D.scale sympy.geometry.point.Point3D.translate """ if not (matrix.is_Matrix and matrix.shape == (4, 4)): raise ValueError("matrix must be a 4x4 matrix") x, y, z = self.args m = Transpose(matrix) return Point3D(*(Matrix(1, 4, [x, y, z, 1])*m).tolist()[0][:3]) def translate(self, x=0, y=0, z=0): """Shift the Point by adding x and y to the coordinates of the Point. See Also ======== scale Examples ======== >>> from sympy import Point3D >>> t = Point3D(0, 1, 1) >>> t.translate(2) Point3D(2, 1, 1) >>> t.translate(2, 2) Point3D(2, 3, 1) >>> t + Point3D(2, 2, 2) Point3D(2, 3, 3) """ return Point3D(self.x + x, self.y + y, self.z + z) @property def coordinates(self): """ Returns the three coordinates of the Point. Examples ======== >>> from sympy import Point3D >>> p = Point3D(0, 1, 2) >>> p.coordinates (0, 1, 2) """ return self.args @property def x(self): """ Returns the X coordinate of the Point. Examples ======== >>> from sympy import Point3D >>> p = Point3D(0, 1, 3) >>> p.x 0 """ return self.args[0] @property def y(self): """ Returns the Y coordinate of the Point. Examples ======== >>> from sympy import Point3D >>> p = Point3D(0, 1, 2) >>> p.y 1 """ return self.args[1] @property def z(self): """ Returns the Z coordinate of the Point. Examples ======== >>> from sympy import Point3D >>> p = Point3D(0, 1, 1) >>> p.z 1 """ return self.args[2]
03e0a058b8c50bd93f3a3caa2456aaee40c076c4aa998113e1a665fde1f6535d
"""Geometrical Planes. Contains ======== Plane """ from sympy.core import Dummy, Rational, S, Symbol from sympy.core.symbol import _symbol from sympy.functions.elementary.trigonometric import cos, sin, acos, asin, sqrt from .entity import GeometryEntity from .line import (Line, Ray, Segment, Line3D, LinearEntity, LinearEntity3D, Ray3D, Segment3D) from .point import Point, Point3D from sympy.matrices import Matrix from sympy.polys.polytools import cancel from sympy.solvers import solve, linsolve from sympy.utilities.iterables import uniq, is_sequence from sympy.utilities.misc import filldedent, func_name, Undecidable from mpmath.libmp.libmpf import prec_to_dps import random x, y, z, t = [Dummy('plane_dummy') for i in range(4)] class Plane(GeometryEntity): """ A plane is a flat, two-dimensional surface. A plane is the two-dimensional analogue of a point (zero-dimensions), a line (one-dimension) and a solid (three-dimensions). A plane can generally be constructed by two types of inputs. They are three non-collinear points and a point and the plane's normal vector. Attributes ========== p1 normal_vector Examples ======== >>> from sympy import Plane, Point3D >>> Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2)) Plane(Point3D(1, 1, 1), (-1, 2, -1)) >>> Plane((1, 1, 1), (2, 3, 4), (2, 2, 2)) Plane(Point3D(1, 1, 1), (-1, 2, -1)) >>> Plane(Point3D(1, 1, 1), normal_vector=(1,4,7)) Plane(Point3D(1, 1, 1), (1, 4, 7)) """ def __new__(cls, p1, a=None, b=None, **kwargs): p1 = Point3D(p1, dim=3) if a and b: p2 = Point(a, dim=3) p3 = Point(b, dim=3) if Point3D.are_collinear(p1, p2, p3): raise ValueError('Enter three non-collinear points') a = p1.direction_ratio(p2) b = p1.direction_ratio(p3) normal_vector = tuple(Matrix(a).cross(Matrix(b))) else: a = kwargs.pop('normal_vector', a) evaluate = kwargs.get('evaluate', True) if is_sequence(a) and len(a) == 3: normal_vector = Point3D(a).args if evaluate else a else: raise ValueError(filldedent(''' Either provide 3 3D points or a point with a normal vector expressed as a sequence of length 3''')) if all(coord.is_zero for coord in normal_vector): raise ValueError('Normal vector cannot be zero vector') return GeometryEntity.__new__(cls, p1, normal_vector, **kwargs) def __contains__(self, o): k = self.equation(x, y, z) if isinstance(o, (LinearEntity, LinearEntity3D)): d = Point3D(o.arbitrary_point(t)) e = k.subs([(x, d.x), (y, d.y), (z, d.z)]) return e.equals(0) try: o = Point(o, dim=3, strict=True) d = k.xreplace(dict(zip((x, y, z), o.args))) return d.equals(0) except TypeError: return False def _eval_evalf(self, prec=15, **options): pt, tup = self.args dps = prec_to_dps(prec) pt = pt.evalf(n=dps, **options) tup = tuple([i.evalf(n=dps, **options) for i in tup]) return self.func(pt, normal_vector=tup, evaluate=False) def angle_between(self, o): """Angle between the plane and other geometric entity. Parameters ========== LinearEntity3D, Plane. Returns ======= angle : angle in radians Notes ===== This method accepts only 3D entities as it's parameter, but if you want to calculate the angle between a 2D entity and a plane you should first convert to a 3D entity by projecting onto a desired plane and then proceed to calculate the angle. Examples ======== >>> from sympy import Point3D, Line3D, Plane >>> a = Plane(Point3D(1, 2, 2), normal_vector=(1, 2, 3)) >>> b = Line3D(Point3D(1, 3, 4), Point3D(2, 2, 2)) >>> a.angle_between(b) -asin(sqrt(21)/6) """ if isinstance(o, LinearEntity3D): a = Matrix(self.normal_vector) b = Matrix(o.direction_ratio) c = a.dot(b) d = sqrt(sum([i**2 for i in self.normal_vector])) e = sqrt(sum([i**2 for i in o.direction_ratio])) return asin(c/(d*e)) if isinstance(o, Plane): a = Matrix(self.normal_vector) b = Matrix(o.normal_vector) c = a.dot(b) d = sqrt(sum([i**2 for i in self.normal_vector])) e = sqrt(sum([i**2 for i in o.normal_vector])) return acos(c/(d*e)) def arbitrary_point(self, u=None, v=None): """ Returns an arbitrary point on the Plane. If given two parameters, the point ranges over the entire plane. If given 1 or no parameters, returns a point with one parameter which, when varying from 0 to 2*pi, moves the point in a circle of radius 1 about p1 of the Plane. Examples ======== >>> from sympy import Plane, Ray >>> from sympy.abc import u, v, t, r >>> p = Plane((1, 1, 1), normal_vector=(1, 0, 0)) >>> p.arbitrary_point(u, v) Point3D(1, u + 1, v + 1) >>> p.arbitrary_point(t) Point3D(1, cos(t) + 1, sin(t) + 1) While arbitrary values of u and v can move the point anywhere in the plane, the single-parameter point can be used to construct a ray whose arbitrary point can be located at angle t and radius r from p.p1: >>> Ray(p.p1, _).arbitrary_point(r) Point3D(1, r*cos(t) + 1, r*sin(t) + 1) Returns ======= Point3D """ circle = v is None if circle: u = _symbol(u or 't', real=True) else: u = _symbol(u or 'u', real=True) v = _symbol(v or 'v', real=True) x, y, z = self.normal_vector a, b, c = self.p1.args # x1, y1, z1 is a nonzero vector parallel to the plane if x.is_zero and y.is_zero: x1, y1, z1 = S.One, S.Zero, S.Zero else: x1, y1, z1 = -y, x, S.Zero # x2, y2, z2 is also parallel to the plane, and orthogonal to x1, y1, z1 x2, y2, z2 = tuple(Matrix((x, y, z)).cross(Matrix((x1, y1, z1)))) if circle: x1, y1, z1 = (w/sqrt(x1**2 + y1**2 + z1**2) for w in (x1, y1, z1)) x2, y2, z2 = (w/sqrt(x2**2 + y2**2 + z2**2) for w in (x2, y2, z2)) p = Point3D(a + x1*cos(u) + x2*sin(u), \ b + y1*cos(u) + y2*sin(u), \ c + z1*cos(u) + z2*sin(u)) else: p = Point3D(a + x1*u + x2*v, b + y1*u + y2*v, c + z1*u + z2*v) return p @staticmethod def are_concurrent(*planes): """Is a sequence of Planes concurrent? Two or more Planes are concurrent if their intersections are a common line. Parameters ========== planes: list Returns ======= Boolean Examples ======== >>> from sympy import Plane, Point3D >>> a = Plane(Point3D(5, 0, 0), normal_vector=(1, -1, 1)) >>> b = Plane(Point3D(0, -2, 0), normal_vector=(3, 1, 1)) >>> c = Plane(Point3D(0, -1, 0), normal_vector=(5, -1, 9)) >>> Plane.are_concurrent(a, b) True >>> Plane.are_concurrent(a, b, c) False """ planes = list(uniq(planes)) for i in planes: if not isinstance(i, Plane): raise ValueError('All objects should be Planes but got %s' % i.func) if len(planes) < 2: return False planes = list(planes) first = planes.pop(0) sol = first.intersection(planes[0]) if sol == []: return False else: line = sol[0] for i in planes[1:]: l = first.intersection(i) if not l or l[0] not in line: return False return True def distance(self, o): """Distance between the plane and another geometric entity. Parameters ========== Point3D, LinearEntity3D, Plane. Returns ======= distance Notes ===== This method accepts only 3D entities as it's parameter, but if you want to calculate the distance between a 2D entity and a plane you should first convert to a 3D entity by projecting onto a desired plane and then proceed to calculate the distance. Examples ======== >>> from sympy import Point3D, Line3D, Plane >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 1, 1)) >>> b = Point3D(1, 2, 3) >>> a.distance(b) sqrt(3) >>> c = Line3D(Point3D(2, 3, 1), Point3D(1, 2, 2)) >>> a.distance(c) 0 """ if self.intersection(o) != []: return S.Zero if isinstance(o, (Segment3D, Ray3D)): a, b = o.p1, o.p2 pi, = self.intersection(Line3D(a, b)) if pi in o: return self.distance(pi) elif a in Segment3D(pi, b): return self.distance(a) else: assert isinstance(o, Segment3D) is True return self.distance(b) # following code handles `Point3D`, `LinearEntity3D`, `Plane` a = o if isinstance(o, Point3D) else o.p1 n = Point3D(self.normal_vector).unit d = (a - self.p1).dot(n) return abs(d) def equals(self, o): """ Returns True if self and o are the same mathematical entities. Examples ======== >>> from sympy import Plane, Point3D >>> a = Plane(Point3D(1, 2, 3), normal_vector=(1, 1, 1)) >>> b = Plane(Point3D(1, 2, 3), normal_vector=(2, 2, 2)) >>> c = Plane(Point3D(1, 2, 3), normal_vector=(-1, 4, 6)) >>> a.equals(a) True >>> a.equals(b) True >>> a.equals(c) False """ if isinstance(o, Plane): a = self.equation() b = o.equation() return cancel(a/b).is_constant() else: return False def equation(self, x=None, y=None, z=None): """The equation of the Plane. Examples ======== >>> from sympy import Point3D, Plane >>> a = Plane(Point3D(1, 1, 2), Point3D(2, 4, 7), Point3D(3, 5, 1)) >>> a.equation() -23*x + 11*y - 2*z + 16 >>> a = Plane(Point3D(1, 4, 2), normal_vector=(6, 6, 6)) >>> a.equation() 6*x + 6*y + 6*z - 42 """ x, y, z = [i if i else Symbol(j, real=True) for i, j in zip((x, y, z), 'xyz')] a = Point3D(x, y, z) b = self.p1.direction_ratio(a) c = self.normal_vector return (sum(i*j for i, j in zip(b, c))) def intersection(self, o): """ The intersection with other geometrical entity. Parameters ========== Point, Point3D, LinearEntity, LinearEntity3D, Plane Returns ======= List Examples ======== >>> from sympy import Point3D, Line3D, Plane >>> a = Plane(Point3D(1, 2, 3), normal_vector=(1, 1, 1)) >>> b = Point3D(1, 2, 3) >>> a.intersection(b) [Point3D(1, 2, 3)] >>> c = Line3D(Point3D(1, 4, 7), Point3D(2, 2, 2)) >>> a.intersection(c) [Point3D(2, 2, 2)] >>> d = Plane(Point3D(6, 0, 0), normal_vector=(2, -5, 3)) >>> e = Plane(Point3D(2, 0, 0), normal_vector=(3, 4, -3)) >>> d.intersection(e) [Line3D(Point3D(78/23, -24/23, 0), Point3D(147/23, 321/23, 23))] """ if not isinstance(o, GeometryEntity): o = Point(o, dim=3) if isinstance(o, Point): if o in self: return [o] else: return [] if isinstance(o, (LinearEntity, LinearEntity3D)): # recast to 3D p1, p2 = o.p1, o.p2 if isinstance(o, Segment): o = Segment3D(p1, p2) elif isinstance(o, Ray): o = Ray3D(p1, p2) elif isinstance(o, Line): o = Line3D(p1, p2) else: raise ValueError('unhandled linear entity: %s' % o.func) if o in self: return [o] else: a = Point3D(o.arbitrary_point(t)) p1, n = self.p1, Point3D(self.normal_vector) # TODO: Replace solve with solveset, when this line is tested c = solve((a - p1).dot(n), t) if not c: return [] else: c = [i for i in c if i.is_real is not False] if len(c) > 1: c = [i for i in c if i.is_real] if len(c) != 1: raise Undecidable("not sure which point is real") p = a.subs(t, c[0]) if p not in o: return [] # e.g. a segment might not intersect a plane return [p] if isinstance(o, Plane): if self.equals(o): return [self] if self.is_parallel(o): return [] else: x, y, z = map(Dummy, 'xyz') a, b = Matrix([self.normal_vector]), Matrix([o.normal_vector]) c = list(a.cross(b)) d = self.equation(x, y, z) e = o.equation(x, y, z) result = list(linsolve([d, e], x, y, z))[0] for i in (x, y, z): result = result.subs(i, 0) return [Line3D(Point3D(result), direction_ratio=c)] def is_coplanar(self, o): """ Returns True if `o` is coplanar with self, else False. Examples ======== >>> from sympy import Plane >>> o = (0, 0, 0) >>> p = Plane(o, (1, 1, 1)) >>> p2 = Plane(o, (2, 2, 2)) >>> p == p2 False >>> p.is_coplanar(p2) True """ if isinstance(o, Plane): return not cancel(self.equation(x, y, z)/o.equation(x, y, z)).has(x, y, z) if isinstance(o, Point3D): return o in self elif isinstance(o, LinearEntity3D): return all(i in self for i in self) elif isinstance(o, GeometryEntity): # XXX should only be handling 2D objects now return all(i == 0 for i in self.normal_vector[:2]) def is_parallel(self, l): """Is the given geometric entity parallel to the plane? Parameters ========== LinearEntity3D or Plane Returns ======= Boolean Examples ======== >>> from sympy import Plane, Point3D >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6)) >>> b = Plane(Point3D(3,1,3), normal_vector=(4, 8, 12)) >>> a.is_parallel(b) True """ if isinstance(l, LinearEntity3D): a = l.direction_ratio b = self.normal_vector c = sum([i*j for i, j in zip(a, b)]) if c == 0: return True else: return False elif isinstance(l, Plane): a = Matrix(l.normal_vector) b = Matrix(self.normal_vector) if a.cross(b).is_zero_matrix: return True else: return False def is_perpendicular(self, l): """Is the given geometric entity perpendicualar to the given plane? Parameters ========== LinearEntity3D or Plane Returns ======= Boolean Examples ======== >>> from sympy import Plane, Point3D >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6)) >>> b = Plane(Point3D(2, 2, 2), normal_vector=(-1, 2, -1)) >>> a.is_perpendicular(b) True """ if isinstance(l, LinearEntity3D): a = Matrix(l.direction_ratio) b = Matrix(self.normal_vector) if a.cross(b).is_zero_matrix: return True else: return False elif isinstance(l, Plane): a = Matrix(l.normal_vector) b = Matrix(self.normal_vector) if a.dot(b) == 0: return True else: return False else: return False @property def normal_vector(self): """Normal vector of the given plane. Examples ======== >>> from sympy import Point3D, Plane >>> a = Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2)) >>> a.normal_vector (-1, 2, -1) >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 4, 7)) >>> a.normal_vector (1, 4, 7) """ return self.args[1] @property def p1(self): """The only defining point of the plane. Others can be obtained from the arbitrary_point method. See Also ======== sympy.geometry.point.Point3D Examples ======== >>> from sympy import Point3D, Plane >>> a = Plane(Point3D(1, 1, 1), Point3D(2, 3, 4), Point3D(2, 2, 2)) >>> a.p1 Point3D(1, 1, 1) """ return self.args[0] def parallel_plane(self, pt): """ Plane parallel to the given plane and passing through the point pt. Parameters ========== pt: Point3D Returns ======= Plane Examples ======== >>> from sympy import Plane, Point3D >>> a = Plane(Point3D(1, 4, 6), normal_vector=(2, 4, 6)) >>> a.parallel_plane(Point3D(2, 3, 5)) Plane(Point3D(2, 3, 5), (2, 4, 6)) """ a = self.normal_vector return Plane(pt, normal_vector=a) def perpendicular_line(self, pt): """A line perpendicular to the given plane. Parameters ========== pt: Point3D Returns ======= Line3D Examples ======== >>> from sympy import Plane, Point3D >>> a = Plane(Point3D(1,4,6), normal_vector=(2, 4, 6)) >>> a.perpendicular_line(Point3D(9, 8, 7)) Line3D(Point3D(9, 8, 7), Point3D(11, 12, 13)) """ a = self.normal_vector return Line3D(pt, direction_ratio=a) def perpendicular_plane(self, *pts): """ Return a perpendicular passing through the given points. If the direction ratio between the points is the same as the Plane's normal vector then, to select from the infinite number of possible planes, a third point will be chosen on the z-axis (or the y-axis if the normal vector is already parallel to the z-axis). If less than two points are given they will be supplied as follows: if no point is given then pt1 will be self.p1; if a second point is not given it will be a point through pt1 on a line parallel to the z-axis (if the normal is not already the z-axis, otherwise on the line parallel to the y-axis). Parameters ========== pts: 0, 1 or 2 Point3D Returns ======= Plane Examples ======== >>> from sympy import Plane, Point3D >>> a, b = Point3D(0, 0, 0), Point3D(0, 1, 0) >>> Z = (0, 0, 1) >>> p = Plane(a, normal_vector=Z) >>> p.perpendicular_plane(a, b) Plane(Point3D(0, 0, 0), (1, 0, 0)) """ if len(pts) > 2: raise ValueError('No more than 2 pts should be provided.') pts = list(pts) if len(pts) == 0: pts.append(self.p1) if len(pts) == 1: x, y, z = self.normal_vector if x == y == 0: dir = (0, 1, 0) else: dir = (0, 0, 1) pts.append(pts[0] + Point3D(*dir)) p1, p2 = [Point(i, dim=3) for i in pts] l = Line3D(p1, p2) n = Line3D(p1, direction_ratio=self.normal_vector) if l in n: # XXX should an error be raised instead? # there are infinitely many perpendicular planes; x, y, z = self.normal_vector if x == y == 0: # the z axis is the normal so pick a pt on the y-axis p3 = Point3D(0, 1, 0) # case 1 else: # else pick a pt on the z axis p3 = Point3D(0, 0, 1) # case 2 # in case that point is already given, move it a bit if p3 in l: p3 *= 2 # case 3 else: p3 = p1 + Point3D(*self.normal_vector) # case 4 return Plane(p1, p2, p3) def projection_line(self, line): """Project the given line onto the plane through the normal plane containing the line. Parameters ========== LinearEntity or LinearEntity3D Returns ======= Point3D, Line3D, Ray3D or Segment3D Notes ===== For the interaction between 2D and 3D lines(segments, rays), you should convert the line to 3D by using this method. For example for finding the intersection between a 2D and a 3D line, convert the 2D line to a 3D line by projecting it on a required plane and then proceed to find the intersection between those lines. Examples ======== >>> from sympy import Plane, Line, Line3D, Point3D >>> a = Plane(Point3D(1, 1, 1), normal_vector=(1, 1, 1)) >>> b = Line(Point3D(1, 1), Point3D(2, 2)) >>> a.projection_line(b) Line3D(Point3D(4/3, 4/3, 1/3), Point3D(5/3, 5/3, -1/3)) >>> c = Line3D(Point3D(1, 1, 1), Point3D(2, 2, 2)) >>> a.projection_line(c) Point3D(1, 1, 1) """ if not isinstance(line, (LinearEntity, LinearEntity3D)): raise NotImplementedError('Enter a linear entity only') a, b = self.projection(line.p1), self.projection(line.p2) if a == b: # projection does not imply intersection so for # this case (line parallel to plane's normal) we # return the projection point return a if isinstance(line, (Line, Line3D)): return Line3D(a, b) if isinstance(line, (Ray, Ray3D)): return Ray3D(a, b) if isinstance(line, (Segment, Segment3D)): return Segment3D(a, b) def projection(self, pt): """Project the given point onto the plane along the plane normal. Parameters ========== Point or Point3D Returns ======= Point3D Examples ======== >>> from sympy import Plane, Point3D >>> A = Plane(Point3D(1, 1, 2), normal_vector=(1, 1, 1)) The projection is along the normal vector direction, not the z axis, so (1, 1) does not project to (1, 1, 2) on the plane A: >>> b = Point3D(1, 1) >>> A.projection(b) Point3D(5/3, 5/3, 2/3) >>> _ in A True But the point (1, 1, 2) projects to (1, 1) on the XY-plane: >>> XY = Plane((0, 0, 0), (0, 0, 1)) >>> XY.projection((1, 1, 2)) Point3D(1, 1, 0) """ rv = Point(pt, dim=3) if rv in self: return rv return self.intersection(Line3D(rv, rv + Point3D(self.normal_vector)))[0] def random_point(self, seed=None): """ Returns a random point on the Plane. Returns ======= Point3D Examples ======== >>> from sympy import Plane >>> p = Plane((1, 0, 0), normal_vector=(0, 1, 0)) >>> r = p.random_point(seed=42) # seed value is optional >>> r.n(3) Point3D(2.29, 0, -1.35) The random point can be moved to lie on the circle of radius 1 centered on p1: >>> c = p.p1 + (r - p.p1).unit >>> c.distance(p.p1).equals(1) True """ if seed is not None: rng = random.Random(seed) else: rng = random params = { x: 2*Rational(rng.gauss(0, 1)) - 1, y: 2*Rational(rng.gauss(0, 1)) - 1} return self.arbitrary_point(x, y).subs(params) def parameter_value(self, other, u, v=None): """Return the parameter(s) corresponding to the given point. Examples ======== >>> from sympy import pi, Plane >>> from sympy.abc import t, u, v >>> p = Plane((2, 0, 0), (0, 0, 1), (0, 1, 0)) By default, the parameter value returned defines a point that is a distance of 1 from the Plane's p1 value and in line with the given point: >>> on_circle = p.arbitrary_point(t).subs(t, pi/4) >>> on_circle.distance(p.p1) 1 >>> p.parameter_value(on_circle, t) {t: pi/4} Moving the point twice as far from p1 does not change the parameter value: >>> off_circle = p.p1 + (on_circle - p.p1)*2 >>> off_circle.distance(p.p1) 2 >>> p.parameter_value(off_circle, t) {t: pi/4} If the 2-value parameter is desired, supply the two parameter symbols and a replacement dictionary will be returned: >>> p.parameter_value(on_circle, u, v) {u: sqrt(10)/10, v: sqrt(10)/30} >>> p.parameter_value(off_circle, u, v) {u: sqrt(10)/5, v: sqrt(10)/15} """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if not isinstance(other, Point): raise ValueError("other must be a point") if other == self.p1: return other if isinstance(u, Symbol) and v is None: delta = self.arbitrary_point(u) - self.p1 eq = delta - (other - self.p1).unit sol = solve(eq, u, dict=True) elif isinstance(u, Symbol) and isinstance(v, Symbol): pt = self.arbitrary_point(u, v) sol = solve(pt - other, (u, v), dict=True) else: raise ValueError('expecting 1 or 2 symbols') if not sol: raise ValueError("Given point is not on %s" % func_name(self)) return sol[0] # {t: tval} or {u: uval, v: vval} @property def ambient_dimension(self): return self.p1.ambient_dimension
2ce508b1c9eadcf683f4b6b9434bcf184985ff6a55fd12d635795469c644171d
"""Elliptical geometrical entities. Contains * Ellipse * Circle """ from sympy.core.expr import Expr from sympy.core.relational import Eq from sympy.core import S, pi, sympify from sympy.core.evalf import N from sympy.core.parameters import global_parameters from sympy.core.logic import fuzzy_bool from sympy.core.numbers import Rational, oo from sympy.core.sorting import ordered from sympy.core.symbol import Dummy, uniquely_named_symbol, _symbol from sympy.simplify import simplify, trigsimp from sympy.functions.elementary.miscellaneous import sqrt, Max from sympy.functions.elementary.trigonometric import cos, sin from sympy.functions.special.elliptic_integrals import elliptic_e from .entity import GeometryEntity, GeometrySet from .exceptions import GeometryError from .line import Line, Segment, Ray2D, Segment2D, Line2D, LinearEntity3D from .point import Point, Point2D, Point3D from .util import idiff, find from sympy.polys import DomainError, Poly, PolynomialError from sympy.polys.polyutils import _not_a_coeff, _nsort from sympy.solvers import solve from sympy.solvers.solveset import linear_coeffs from sympy.utilities.misc import filldedent, func_name from mpmath.libmp.libmpf import prec_to_dps import random x, y = [Dummy('ellipse_dummy', real=True) for i in range(2)] class Ellipse(GeometrySet): """An elliptical GeometryEntity. Parameters ========== center : Point, optional Default value is Point(0, 0) hradius : number or SymPy expression, optional vradius : number or SymPy expression, optional eccentricity : number or SymPy expression, optional Two of `hradius`, `vradius` and `eccentricity` must be supplied to create an Ellipse. The third is derived from the two supplied. Attributes ========== center hradius vradius area circumference eccentricity periapsis apoapsis focus_distance foci Raises ====== GeometryError When `hradius`, `vradius` and `eccentricity` are incorrectly supplied as parameters. TypeError When `center` is not a Point. See Also ======== Circle Notes ----- Constructed from a center and two radii, the first being the horizontal radius (along the x-axis) and the second being the vertical radius (along the y-axis). When symbolic value for hradius and vradius are used, any calculation that refers to the foci or the major or minor axis will assume that the ellipse has its major radius on the x-axis. If this is not true then a manual rotation is necessary. Examples ======== >>> from sympy import Ellipse, Point, Rational >>> e1 = Ellipse(Point(0, 0), 5, 1) >>> e1.hradius, e1.vradius (5, 1) >>> e2 = Ellipse(Point(3, 1), hradius=3, eccentricity=Rational(4, 5)) >>> e2 Ellipse(Point2D(3, 1), 3, 9/5) """ def __contains__(self, o): if isinstance(o, Point): res = self.equation(x, y).subs({x: o.x, y: o.y}) return trigsimp(simplify(res)) is S.Zero elif isinstance(o, Ellipse): return self == o return False def __eq__(self, o): """Is the other GeometryEntity the same as this ellipse?""" return isinstance(o, Ellipse) and (self.center == o.center and self.hradius == o.hradius and self.vradius == o.vradius) def __hash__(self): return super().__hash__() def __new__( cls, center=None, hradius=None, vradius=None, eccentricity=None, **kwargs): hradius = sympify(hradius) vradius = sympify(vradius) if center is None: center = Point(0, 0) else: if len(center) != 2: raise ValueError('The center of "{}" must be a two dimensional point'.format(cls)) center = Point(center, dim=2) if len(list(filter(lambda x: x is not None, (hradius, vradius, eccentricity)))) != 2: raise ValueError(filldedent(''' Exactly two arguments of "hradius", "vradius", and "eccentricity" must not be None.''')) if eccentricity is not None: eccentricity = sympify(eccentricity) if eccentricity.is_negative: raise GeometryError("Eccentricity of ellipse/circle should lie between [0, 1)") elif hradius is None: hradius = vradius / sqrt(1 - eccentricity**2) elif vradius is None: vradius = hradius * sqrt(1 - eccentricity**2) if hradius == vradius: return Circle(center, hradius, **kwargs) if S.Zero in (hradius, vradius): return Segment(Point(center[0] - hradius, center[1] - vradius), Point(center[0] + hradius, center[1] + vradius)) if hradius.is_real is False or vradius.is_real is False: raise GeometryError("Invalid value encountered when computing hradius / vradius.") return GeometryEntity.__new__(cls, center, hradius, vradius, **kwargs) def _svg(self, scale_factor=1., fill_color="#66cc99"): """Returns SVG ellipse element for the Ellipse. Parameters ========== scale_factor : float Multiplication factor for the SVG stroke-width. Default is 1. fill_color : str, optional Hex string for fill color. Default is "#66cc99". """ c = N(self.center) h, v = N(self.hradius), N(self.vradius) return ( '<ellipse fill="{1}" stroke="#555555" ' 'stroke-width="{0}" opacity="0.6" cx="{2}" cy="{3}" rx="{4}" ry="{5}"/>' ).format(2. * scale_factor, fill_color, c.x, c.y, h, v) @property def ambient_dimension(self): return 2 @property def apoapsis(self): """The apoapsis of the ellipse. The greatest distance between the focus and the contour. Returns ======= apoapsis : number See Also ======== periapsis : Returns shortest distance between foci and contour Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.apoapsis 2*sqrt(2) + 3 """ return self.major * (1 + self.eccentricity) def arbitrary_point(self, parameter='t'): """A parameterized point on the ellipse. Parameters ========== parameter : str, optional Default value is 't'. Returns ======= arbitrary_point : Point Raises ====== ValueError When `parameter` already appears in the functions. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Ellipse >>> e1 = Ellipse(Point(0, 0), 3, 2) >>> e1.arbitrary_point() Point2D(3*cos(t), 2*sin(t)) """ t = _symbol(parameter, real=True) if t.name in (f.name for f in self.free_symbols): raise ValueError(filldedent('Symbol %s already appears in object ' 'and cannot be used as a parameter.' % t.name)) return Point(self.center.x + self.hradius*cos(t), self.center.y + self.vradius*sin(t)) @property def area(self): """The area of the ellipse. Returns ======= area : number Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.area 3*pi """ return simplify(S.Pi * self.hradius * self.vradius) @property def bounds(self): """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding rectangle for the geometric figure. """ h, v = self.hradius, self.vradius return (self.center.x - h, self.center.y - v, self.center.x + h, self.center.y + v) @property def center(self): """The center of the ellipse. Returns ======= center : number See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.center Point2D(0, 0) """ return self.args[0] @property def circumference(self): """The circumference of the ellipse. Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.circumference 12*elliptic_e(8/9) """ if self.eccentricity == 1: # degenerate return 4*self.major elif self.eccentricity == 0: # circle return 2*pi*self.hradius else: return 4*self.major*elliptic_e(self.eccentricity**2) @property def eccentricity(self): """The eccentricity of the ellipse. Returns ======= eccentricity : number Examples ======== >>> from sympy import Point, Ellipse, sqrt >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, sqrt(2)) >>> e1.eccentricity sqrt(7)/3 """ return self.focus_distance / self.major def encloses_point(self, p): """ Return True if p is enclosed by (is inside of) self. Notes ----- Being on the border of self is considered False. Parameters ========== p : Point Returns ======= encloses_point : True, False or None See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Ellipse, S >>> from sympy.abc import t >>> e = Ellipse((0, 0), 3, 2) >>> e.encloses_point((0, 0)) True >>> e.encloses_point(e.arbitrary_point(t).subs(t, S.Half)) False >>> e.encloses_point((4, 0)) False """ p = Point(p, dim=2) if p in self: return False if len(self.foci) == 2: # if the combined distance from the foci to p (h1 + h2) is less # than the combined distance from the foci to the minor axis # (which is the same as the major axis length) then p is inside # the ellipse h1, h2 = [f.distance(p) for f in self.foci] test = 2*self.major - (h1 + h2) else: test = self.radius - self.center.distance(p) return fuzzy_bool(test.is_positive) def equation(self, x='x', y='y', _slope=None): """ Returns the equation of an ellipse aligned with the x and y axes; when slope is given, the equation returned corresponds to an ellipse with a major axis having that slope. Parameters ========== x : str, optional Label for the x-axis. Default value is 'x'. y : str, optional Label for the y-axis. Default value is 'y'. _slope : Expr, optional The slope of the major axis. Ignored when 'None'. Returns ======= equation : SymPy expression See Also ======== arbitrary_point : Returns parameterized point on ellipse Examples ======== >>> from sympy import Point, Ellipse, pi >>> from sympy.abc import x, y >>> e1 = Ellipse(Point(1, 0), 3, 2) >>> eq1 = e1.equation(x, y); eq1 y**2/4 + (x/3 - 1/3)**2 - 1 >>> eq2 = e1.equation(x, y, _slope=1); eq2 (-x + y + 1)**2/8 + (x + y - 1)**2/18 - 1 A point on e1 satisfies eq1. Let's use one on the x-axis: >>> p1 = e1.center + Point(e1.major, 0) >>> assert eq1.subs(x, p1.x).subs(y, p1.y) == 0 When rotated the same as the rotated ellipse, about the center point of the ellipse, it will satisfy the rotated ellipse's equation, too: >>> r1 = p1.rotate(pi/4, e1.center) >>> assert eq2.subs(x, r1.x).subs(y, r1.y) == 0 References ========== .. [1] https://math.stackexchange.com/questions/108270/what-is-the-equation-of-an-ellipse-that-is-not-aligned-with-the-axis .. [2] https://en.wikipedia.org/wiki/Ellipse#Shifted_ellipse """ x = _symbol(x, real=True) y = _symbol(y, real=True) dx = x - self.center.x dy = y - self.center.y if _slope is not None: L = (dy - _slope*dx)**2 l = (_slope*dy + dx)**2 h = 1 + _slope**2 b = h*self.major**2 a = h*self.minor**2 return l/b + L/a - 1 else: t1 = (dx/self.hradius)**2 t2 = (dy/self.vradius)**2 return t1 + t2 - 1 def evolute(self, x='x', y='y'): """The equation of evolute of the ellipse. Parameters ========== x : str, optional Label for the x-axis. Default value is 'x'. y : str, optional Label for the y-axis. Default value is 'y'. Returns ======= equation : SymPy expression Examples ======== >>> from sympy import Point, Ellipse >>> e1 = Ellipse(Point(1, 0), 3, 2) >>> e1.evolute() 2**(2/3)*y**(2/3) + (3*x - 3)**(2/3) - 5**(2/3) """ if len(self.args) != 3: raise NotImplementedError('Evolute of arbitrary Ellipse is not supported.') x = _symbol(x, real=True) y = _symbol(y, real=True) t1 = (self.hradius*(x - self.center.x))**Rational(2, 3) t2 = (self.vradius*(y - self.center.y))**Rational(2, 3) return t1 + t2 - (self.hradius**2 - self.vradius**2)**Rational(2, 3) @property def foci(self): """The foci of the ellipse. Notes ----- The foci can only be calculated if the major/minor axes are known. Raises ====== ValueError When the major and minor axis cannot be determined. See Also ======== sympy.geometry.point.Point focus_distance : Returns the distance between focus and center Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.foci (Point2D(-2*sqrt(2), 0), Point2D(2*sqrt(2), 0)) """ c = self.center hr, vr = self.hradius, self.vradius if hr == vr: return (c, c) # calculate focus distance manually, since focus_distance calls this # routine fd = sqrt(self.major**2 - self.minor**2) if hr == self.minor: # foci on the y-axis return (c + Point(0, -fd), c + Point(0, fd)) elif hr == self.major: # foci on the x-axis return (c + Point(-fd, 0), c + Point(fd, 0)) @property def focus_distance(self): """The focal distance of the ellipse. The distance between the center and one focus. Returns ======= focus_distance : number See Also ======== foci Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.focus_distance 2*sqrt(2) """ return Point.distance(self.center, self.foci[0]) @property def hradius(self): """The horizontal radius of the ellipse. Returns ======= hradius : number See Also ======== vradius, major, minor Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.hradius 3 """ return self.args[1] def intersection(self, o): """The intersection of this ellipse and another geometrical entity `o`. Parameters ========== o : GeometryEntity Returns ======= intersection : list of GeometryEntity objects Notes ----- Currently supports intersections with Point, Line, Segment, Ray, Circle and Ellipse types. See Also ======== sympy.geometry.entity.GeometryEntity Examples ======== >>> from sympy import Ellipse, Point, Line >>> e = Ellipse(Point(0, 0), 5, 7) >>> e.intersection(Point(0, 0)) [] >>> e.intersection(Point(5, 0)) [Point2D(5, 0)] >>> e.intersection(Line(Point(0,0), Point(0, 1))) [Point2D(0, -7), Point2D(0, 7)] >>> e.intersection(Line(Point(5,0), Point(5, 1))) [Point2D(5, 0)] >>> e.intersection(Line(Point(6,0), Point(6, 1))) [] >>> e = Ellipse(Point(-1, 0), 4, 3) >>> e.intersection(Ellipse(Point(1, 0), 4, 3)) [Point2D(0, -3*sqrt(15)/4), Point2D(0, 3*sqrt(15)/4)] >>> e.intersection(Ellipse(Point(5, 0), 4, 3)) [Point2D(2, -3*sqrt(7)/4), Point2D(2, 3*sqrt(7)/4)] >>> e.intersection(Ellipse(Point(100500, 0), 4, 3)) [] >>> e.intersection(Ellipse(Point(0, 0), 3, 4)) [Point2D(3, 0), Point2D(-363/175, -48*sqrt(111)/175), Point2D(-363/175, 48*sqrt(111)/175)] >>> e.intersection(Ellipse(Point(-1, 0), 3, 4)) [Point2D(-17/5, -12/5), Point2D(-17/5, 12/5), Point2D(7/5, -12/5), Point2D(7/5, 12/5)] """ # TODO: Replace solve with nonlinsolve, when nonlinsolve will be able to solve in real domain if isinstance(o, Point): if o in self: return [o] else: return [] elif isinstance(o, (Segment2D, Ray2D)): ellipse_equation = self.equation(x, y) result = solve([ellipse_equation, Line( o.points[0], o.points[1]).equation(x, y)], [x, y], set=True)[1] return list(ordered([Point(i) for i in result if i in o])) elif isinstance(o, Polygon): return o.intersection(self) elif isinstance(o, (Ellipse, Line2D)): if o == self: return self else: ellipse_equation = self.equation(x, y) return list(ordered([Point(i) for i in solve( [ellipse_equation, o.equation(x, y)], [x, y], set=True)[1]])) elif isinstance(o, LinearEntity3D): raise TypeError('Entity must be two dimensional, not three dimensional') else: raise TypeError('Intersection not handled for %s' % func_name(o)) def is_tangent(self, o): """Is `o` tangent to the ellipse? Parameters ========== o : GeometryEntity An Ellipse, LinearEntity or Polygon Raises ====== NotImplementedError When the wrong type of argument is supplied. Returns ======= is_tangent: boolean True if o is tangent to the ellipse, False otherwise. See Also ======== tangent_lines Examples ======== >>> from sympy import Point, Ellipse, Line >>> p0, p1, p2 = Point(0, 0), Point(3, 0), Point(3, 3) >>> e1 = Ellipse(p0, 3, 2) >>> l1 = Line(p1, p2) >>> e1.is_tangent(l1) True """ if isinstance(o, Point2D): return False elif isinstance(o, Ellipse): intersect = self.intersection(o) if isinstance(intersect, Ellipse): return True elif intersect: return all((self.tangent_lines(i)[0]).equals(o.tangent_lines(i)[0]) for i in intersect) else: return False elif isinstance(o, Line2D): hit = self.intersection(o) if not hit: return False if len(hit) == 1: return True # might return None if it can't decide return hit[0].equals(hit[1]) elif isinstance(o, Ray2D): intersect = self.intersection(o) if len(intersect) == 1: return intersect[0] != o.source and not self.encloses_point(o.source) else: return False elif isinstance(o, (Segment2D, Polygon)): all_tangents = False segments = o.sides if isinstance(o, Polygon) else [o] for segment in segments: intersect = self.intersection(segment) if len(intersect) == 1: if not any(intersect[0] in i for i in segment.points) \ and not any(self.encloses_point(i) for i in segment.points): all_tangents = True continue else: return False else: return all_tangents return all_tangents elif isinstance(o, (LinearEntity3D, Point3D)): raise TypeError('Entity must be two dimensional, not three dimensional') else: raise TypeError('Is_tangent not handled for %s' % func_name(o)) @property def major(self): """Longer axis of the ellipse (if it can be determined) else hradius. Returns ======= major : number or expression See Also ======== hradius, vradius, minor Examples ======== >>> from sympy import Point, Ellipse, Symbol >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.major 3 >>> a = Symbol('a') >>> b = Symbol('b') >>> Ellipse(p1, a, b).major a >>> Ellipse(p1, b, a).major b >>> m = Symbol('m') >>> M = m + 1 >>> Ellipse(p1, m, M).major m + 1 """ ab = self.args[1:3] if len(ab) == 1: return ab[0] a, b = ab o = b - a < 0 if o == True: return a elif o == False: return b return self.hradius @property def minor(self): """Shorter axis of the ellipse (if it can be determined) else vradius. Returns ======= minor : number or expression See Also ======== hradius, vradius, major Examples ======== >>> from sympy import Point, Ellipse, Symbol >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.minor 1 >>> a = Symbol('a') >>> b = Symbol('b') >>> Ellipse(p1, a, b).minor b >>> Ellipse(p1, b, a).minor a >>> m = Symbol('m') >>> M = m + 1 >>> Ellipse(p1, m, M).minor m """ ab = self.args[1:3] if len(ab) == 1: return ab[0] a, b = ab o = a - b < 0 if o == True: return a elif o == False: return b return self.vradius def normal_lines(self, p, prec=None): """Normal lines between `p` and the ellipse. Parameters ========== p : Point Returns ======= normal_lines : list with 1, 2 or 4 Lines Examples ======== >>> from sympy import Point, Ellipse >>> e = Ellipse((0, 0), 2, 3) >>> c = e.center >>> e.normal_lines(c + Point(1, 0)) [Line2D(Point2D(0, 0), Point2D(1, 0))] >>> e.normal_lines(c) [Line2D(Point2D(0, 0), Point2D(0, 1)), Line2D(Point2D(0, 0), Point2D(1, 0))] Off-axis points require the solution of a quartic equation. This often leads to very large expressions that may be of little practical use. An approximate solution of `prec` digits can be obtained by passing in the desired value: >>> e.normal_lines((3, 3), prec=2) [Line2D(Point2D(-0.81, -2.7), Point2D(0.19, -1.2)), Line2D(Point2D(1.5, -2.0), Point2D(2.5, -2.7))] Whereas the above solution has an operation count of 12, the exact solution has an operation count of 2020. """ p = Point(p, dim=2) # XXX change True to something like self.angle == 0 if the arbitrarily # rotated ellipse is introduced. # https://github.com/sympy/sympy/issues/2815) if True: rv = [] if p.x == self.center.x: rv.append(Line(self.center, slope=oo)) if p.y == self.center.y: rv.append(Line(self.center, slope=0)) if rv: # at these special orientations of p either 1 or 2 normals # exist and we are done return rv # find the 4 normal points and construct lines through them with # the corresponding slope eq = self.equation(x, y) dydx = idiff(eq, y, x) norm = -1/dydx slope = Line(p, (x, y)).slope seq = slope - norm # TODO: Replace solve with solveset, when this line is tested yis = solve(seq, y)[0] xeq = eq.subs(y, yis).as_numer_denom()[0].expand() if len(xeq.free_symbols) == 1: try: # this is so much faster, it's worth a try xsol = Poly(xeq, x).real_roots() except (DomainError, PolynomialError, NotImplementedError): # TODO: Replace solve with solveset, when these lines are tested xsol = _nsort(solve(xeq, x), separated=True)[0] points = [Point(i, solve(eq.subs(x, i), y)[0]) for i in xsol] else: raise NotImplementedError( 'intersections for the general ellipse are not supported') slopes = [norm.subs(zip((x, y), pt.args)) for pt in points] if prec is not None: points = [pt.n(prec) for pt in points] slopes = [i if _not_a_coeff(i) else i.n(prec) for i in slopes] return [Line(pt, slope=s) for pt, s in zip(points, slopes)] @property def periapsis(self): """The periapsis of the ellipse. The shortest distance between the focus and the contour. Returns ======= periapsis : number See Also ======== apoapsis : Returns greatest distance between focus and contour Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.periapsis 3 - 2*sqrt(2) """ return self.major * (1 - self.eccentricity) @property def semilatus_rectum(self): """ Calculates the semi-latus rectum of the Ellipse. Semi-latus rectum is defined as one half of the chord through a focus parallel to the conic section directrix of a conic section. Returns ======= semilatus_rectum : number See Also ======== apoapsis : Returns greatest distance between focus and contour periapsis : The shortest distance between the focus and the contour Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.semilatus_rectum 1/3 References ========== .. [1] http://mathworld.wolfram.com/SemilatusRectum.html .. [2] https://en.wikipedia.org/wiki/Ellipse#Semi-latus_rectum """ return self.major * (1 - self.eccentricity ** 2) def auxiliary_circle(self): """Returns a Circle whose diameter is the major axis of the ellipse. Examples ======== >>> from sympy import Ellipse, Point, symbols >>> c = Point(1, 2) >>> Ellipse(c, 8, 7).auxiliary_circle() Circle(Point2D(1, 2), 8) >>> a, b = symbols('a b') >>> Ellipse(c, a, b).auxiliary_circle() Circle(Point2D(1, 2), Max(a, b)) """ return Circle(self.center, Max(self.hradius, self.vradius)) def director_circle(self): """ Returns a Circle consisting of all points where two perpendicular tangent lines to the ellipse cross each other. Returns ======= Circle A director circle returned as a geometric object. Examples ======== >>> from sympy import Ellipse, Point, symbols >>> c = Point(3,8) >>> Ellipse(c, 7, 9).director_circle() Circle(Point2D(3, 8), sqrt(130)) >>> a, b = symbols('a b') >>> Ellipse(c, a, b).director_circle() Circle(Point2D(3, 8), sqrt(a**2 + b**2)) References ========== .. [1] https://en.wikipedia.org/wiki/Director_circle """ return Circle(self.center, sqrt(self.hradius**2 + self.vradius**2)) def plot_interval(self, parameter='t'): """The plot interval for the default geometric plot of the Ellipse. Parameters ========== parameter : str, optional Default value is 't'. Returns ======= plot_interval : list [parameter, lower_bound, upper_bound] Examples ======== >>> from sympy import Point, Ellipse >>> e1 = Ellipse(Point(0, 0), 3, 2) >>> e1.plot_interval() [t, -pi, pi] """ t = _symbol(parameter, real=True) return [t, -S.Pi, S.Pi] def random_point(self, seed=None): """A random point on the ellipse. Returns ======= point : Point Examples ======== >>> from sympy import Point, Ellipse >>> e1 = Ellipse(Point(0, 0), 3, 2) >>> e1.random_point() # gives some random point Point2D(...) >>> p1 = e1.random_point(seed=0); p1.n(2) Point2D(2.1, 1.4) Notes ===== When creating a random point, one may simply replace the parameter with a random number. When doing so, however, the random number should be made a Rational or else the point may not test as being in the ellipse: >>> from sympy.abc import t >>> from sympy import Rational >>> arb = e1.arbitrary_point(t); arb Point2D(3*cos(t), 2*sin(t)) >>> arb.subs(t, .1) in e1 False >>> arb.subs(t, Rational(.1)) in e1 True >>> arb.subs(t, Rational('.1')) in e1 True See Also ======== sympy.geometry.point.Point arbitrary_point : Returns parameterized point on ellipse """ t = _symbol('t', real=True) x, y = self.arbitrary_point(t).args # get a random value in [-1, 1) corresponding to cos(t) # and confirm that it will test as being in the ellipse if seed is not None: rng = random.Random(seed) else: rng = random # simplify this now or else the Float will turn s into a Float r = Rational(rng.random()) c = 2*r - 1 s = sqrt(1 - c**2) return Point(x.subs(cos(t), c), y.subs(sin(t), s)) def reflect(self, line): """Override GeometryEntity.reflect since the radius is not a GeometryEntity. Examples ======== >>> from sympy import Circle, Line >>> Circle((0, 1), 1).reflect(Line((0, 0), (1, 1))) Circle(Point2D(1, 0), -1) >>> from sympy import Ellipse, Line, Point >>> Ellipse(Point(3, 4), 1, 3).reflect(Line(Point(0, -4), Point(5, 0))) Traceback (most recent call last): ... NotImplementedError: General Ellipse is not supported but the equation of the reflected Ellipse is given by the zeros of: f(x, y) = (9*x/41 + 40*y/41 + 37/41)**2 + (40*x/123 - 3*y/41 - 364/123)**2 - 1 Notes ===== Until the general ellipse (with no axis parallel to the x-axis) is supported a NotImplemented error is raised and the equation whose zeros define the rotated ellipse is given. """ if line.slope in (0, oo): c = self.center c = c.reflect(line) return self.func(c, -self.hradius, self.vradius) else: x, y = [uniquely_named_symbol( name, (self, line), modify=lambda s: '_' + s, real=True) for name in 'xy'] expr = self.equation(x, y) p = Point(x, y).reflect(line) result = expr.subs(zip((x, y), p.args ), simultaneous=True) raise NotImplementedError(filldedent( 'General Ellipse is not supported but the equation ' 'of the reflected Ellipse is given by the zeros of: ' + "f(%s, %s) = %s" % (str(x), str(y), str(result)))) def rotate(self, angle=0, pt=None): """Rotate ``angle`` radians counterclockwise about Point ``pt``. Note: since the general ellipse is not supported, only rotations that are integer multiples of pi/2 are allowed. Examples ======== >>> from sympy import Ellipse, pi >>> Ellipse((1, 0), 2, 1).rotate(pi/2) Ellipse(Point2D(0, 1), 1, 2) >>> Ellipse((1, 0), 2, 1).rotate(pi) Ellipse(Point2D(-1, 0), 2, 1) """ if self.hradius == self.vradius: return self.func(self.center.rotate(angle, pt), self.hradius) if (angle/S.Pi).is_integer: return super().rotate(angle, pt) if (2*angle/S.Pi).is_integer: return self.func(self.center.rotate(angle, pt), self.vradius, self.hradius) # XXX see https://github.com/sympy/sympy/issues/2815 for general ellipes raise NotImplementedError('Only rotations of pi/2 are currently supported for Ellipse.') def scale(self, x=1, y=1, pt=None): """Override GeometryEntity.scale since it is the major and minor axes which must be scaled and they are not GeometryEntities. Examples ======== >>> from sympy import Ellipse >>> Ellipse((0, 0), 2, 1).scale(2, 4) Circle(Point2D(0, 0), 4) >>> Ellipse((0, 0), 2, 1).scale(2) Ellipse(Point2D(0, 0), 4, 1) """ c = self.center if pt: pt = Point(pt, dim=2) return self.translate(*(-pt).args).scale(x, y).translate(*pt.args) h = self.hradius v = self.vradius return self.func(c.scale(x, y), hradius=h*x, vradius=v*y) def tangent_lines(self, p): """Tangent lines between `p` and the ellipse. If `p` is on the ellipse, returns the tangent line through point `p`. Otherwise, returns the tangent line(s) from `p` to the ellipse, or None if no tangent line is possible (e.g., `p` inside ellipse). Parameters ========== p : Point Returns ======= tangent_lines : list with 1 or 2 Lines Raises ====== NotImplementedError Can only find tangent lines for a point, `p`, on the ellipse. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Line Examples ======== >>> from sympy import Point, Ellipse >>> e1 = Ellipse(Point(0, 0), 3, 2) >>> e1.tangent_lines(Point(3, 0)) [Line2D(Point2D(3, 0), Point2D(3, -12))] """ p = Point(p, dim=2) if self.encloses_point(p): return [] if p in self: delta = self.center - p rise = (self.vradius**2)*delta.x run = -(self.hradius**2)*delta.y p2 = Point(simplify(p.x + run), simplify(p.y + rise)) return [Line(p, p2)] else: if len(self.foci) == 2: f1, f2 = self.foci maj = self.hradius test = (2*maj - Point.distance(f1, p) - Point.distance(f2, p)) else: test = self.radius - Point.distance(self.center, p) if test.is_number and test.is_positive: return [] # else p is outside the ellipse or we can't tell. In case of the # latter, the solutions returned will only be valid if # the point is not inside the ellipse; if it is, nan will result. eq = self.equation(x, y) dydx = idiff(eq, y, x) slope = Line(p, Point(x, y)).slope # TODO: Replace solve with solveset, when this line is tested tangent_points = solve([slope - dydx, eq], [x, y]) # handle horizontal and vertical tangent lines if len(tangent_points) == 1: if tangent_points[0][ 0] == p.x or tangent_points[0][1] == p.y: return [Line(p, p + Point(1, 0)), Line(p, p + Point(0, 1))] else: return [Line(p, p + Point(0, 1)), Line(p, tangent_points[0])] # others return [Line(p, tangent_points[0]), Line(p, tangent_points[1])] @property def vradius(self): """The vertical radius of the ellipse. Returns ======= vradius : number See Also ======== hradius, major, minor Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.vradius 1 """ return self.args[2] def second_moment_of_area(self, point=None): """Returns the second moment and product moment area of an ellipse. Parameters ========== point : Point, two-tuple of sympifiable objects, or None(default=None) point is the point about which second moment of area is to be found. If "point=None" it will be calculated about the axis passing through the centroid of the ellipse. Returns ======= I_xx, I_yy, I_xy : number or SymPy expression I_xx, I_yy are second moment of area of an ellise. I_xy is product moment of area of an ellipse. Examples ======== >>> from sympy import Point, Ellipse >>> p1 = Point(0, 0) >>> e1 = Ellipse(p1, 3, 1) >>> e1.second_moment_of_area() (3*pi/4, 27*pi/4, 0) References ========== .. [1] https://en.wikipedia.org/wiki/List_of_second_moments_of_area """ I_xx = (S.Pi*(self.hradius)*(self.vradius**3))/4 I_yy = (S.Pi*(self.hradius**3)*(self.vradius))/4 I_xy = 0 if point is None: return I_xx, I_yy, I_xy # parallel axis theorem I_xx = I_xx + self.area*((point[1] - self.center.y)**2) I_yy = I_yy + self.area*((point[0] - self.center.x)**2) I_xy = I_xy + self.area*(point[0] - self.center.x)*(point[1] - self.center.y) return I_xx, I_yy, I_xy def polar_second_moment_of_area(self): """Returns the polar second moment of area of an Ellipse It is a constituent of the second moment of area, linked through the perpendicular axis theorem. While the planar second moment of area describes an object's resistance to deflection (bending) when subjected to a force applied to a plane parallel to the central axis, the polar second moment of area describes an object's resistance to deflection when subjected to a moment applied in a plane perpendicular to the object's central axis (i.e. parallel to the cross-section) Examples ======== >>> from sympy import symbols, Circle, Ellipse >>> c = Circle((5, 5), 4) >>> c.polar_second_moment_of_area() 128*pi >>> a, b = symbols('a, b') >>> e = Ellipse((0, 0), a, b) >>> e.polar_second_moment_of_area() pi*a**3*b/4 + pi*a*b**3/4 References ========== .. [1] https://en.wikipedia.org/wiki/Polar_moment_of_inertia """ second_moment = self.second_moment_of_area() return second_moment[0] + second_moment[1] def section_modulus(self, point=None): """Returns a tuple with the section modulus of an ellipse Section modulus is a geometric property of an ellipse defined as the ratio of second moment of area to the distance of the extreme end of the ellipse from the centroidal axis. Parameters ========== point : Point, two-tuple of sympifyable objects, or None(default=None) point is the point at which section modulus is to be found. If "point=None" section modulus will be calculated for the point farthest from the centroidal axis of the ellipse. Returns ======= S_x, S_y: numbers or SymPy expressions S_x is the section modulus with respect to the x-axis S_y is the section modulus with respect to the y-axis A negative sign indicates that the section modulus is determined for a point below the centroidal axis. Examples ======== >>> from sympy import Symbol, Ellipse, Circle, Point2D >>> d = Symbol('d', positive=True) >>> c = Circle((0, 0), d/2) >>> c.section_modulus() (pi*d**3/32, pi*d**3/32) >>> e = Ellipse(Point2D(0, 0), 2, 4) >>> e.section_modulus() (8*pi, 4*pi) >>> e.section_modulus((2, 2)) (16*pi, 4*pi) References ========== .. [1] https://en.wikipedia.org/wiki/Section_modulus """ x_c, y_c = self.center if point is None: # taking x and y as maximum distances from centroid x_min, y_min, x_max, y_max = self.bounds y = max(y_c - y_min, y_max - y_c) x = max(x_c - x_min, x_max - x_c) else: # taking x and y as distances of the given point from the center point = Point2D(point) y = point.y - y_c x = point.x - x_c second_moment = self.second_moment_of_area() S_x = second_moment[0]/y S_y = second_moment[1]/x return S_x, S_y class Circle(Ellipse): """A circle in space. Constructed simply from a center and a radius, from three non-collinear points, or the equation of a circle. Parameters ========== center : Point radius : number or SymPy expression points : sequence of three Points equation : equation of a circle Attributes ========== radius (synonymous with hradius, vradius, major and minor) circumference equation Raises ====== GeometryError When the given equation is not that of a circle. When trying to construct circle from incorrect parameters. See Also ======== Ellipse, sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Circle, Eq >>> from sympy.abc import x, y, a, b A circle constructed from a center and radius: >>> c1 = Circle(Point(0, 0), 5) >>> c1.hradius, c1.vradius, c1.radius (5, 5, 5) A circle constructed from three points: >>> c2 = Circle(Point(0, 0), Point(1, 1), Point(1, 0)) >>> c2.hradius, c2.vradius, c2.radius, c2.center (sqrt(2)/2, sqrt(2)/2, sqrt(2)/2, Point2D(1/2, 1/2)) A circle can be constructed from an equation in the form `a*x**2 + by**2 + gx + hy + c = 0`, too: >>> Circle(x**2 + y**2 - 25) Circle(Point2D(0, 0), 5) If the variables corresponding to x and y are named something else, their name or symbol can be supplied: >>> Circle(Eq(a**2 + b**2, 25), x='a', y=b) Circle(Point2D(0, 0), 5) """ def __new__(cls, *args, **kwargs): evaluate = kwargs.get('evaluate', global_parameters.evaluate) if len(args) == 1 and isinstance(args[0], (Expr, Eq)): x = kwargs.get('x', 'x') y = kwargs.get('y', 'y') equation = args[0].expand() if isinstance(equation, Eq): equation = equation.lhs - equation.rhs x = find(x, equation) y = find(y, equation) try: a, b, c, d, e = linear_coeffs(equation, x**2, y**2, x, y) except ValueError: raise GeometryError("The given equation is not that of a circle.") if S.Zero in (a, b) or a != b: raise GeometryError("The given equation is not that of a circle.") center_x = -c/a/2 center_y = -d/b/2 r2 = (center_x**2) + (center_y**2) - e/a return Circle((center_x, center_y), sqrt(r2), evaluate=evaluate) else: c, r = None, None if len(args) == 3: args = [Point(a, dim=2, evaluate=evaluate) for a in args] t = Triangle(*args) if not isinstance(t, Triangle): return t c = t.circumcenter r = t.circumradius elif len(args) == 2: # Assume (center, radius) pair c = Point(args[0], dim=2, evaluate=evaluate) r = args[1] # this will prohibit imaginary radius try: r = Point(r, 0, evaluate=evaluate).x except ValueError: raise GeometryError("Circle with imaginary radius is not permitted") if not (c is None or r is None): if r == 0: return c return GeometryEntity.__new__(cls, c, r, **kwargs) raise GeometryError("Circle.__new__ received unknown arguments") def _eval_evalf(self, prec=15, **options): pt, r = self.args dps = prec_to_dps(prec) pt = pt.evalf(n=dps, **options) r = r.evalf(n=dps, **options) return self.func(pt, r, evaluate=False) @property def circumference(self): """The circumference of the circle. Returns ======= circumference : number or SymPy expression Examples ======== >>> from sympy import Point, Circle >>> c1 = Circle(Point(3, 4), 6) >>> c1.circumference 12*pi """ return 2 * S.Pi * self.radius def equation(self, x='x', y='y'): """The equation of the circle. Parameters ========== x : str or Symbol, optional Default value is 'x'. y : str or Symbol, optional Default value is 'y'. Returns ======= equation : SymPy expression Examples ======== >>> from sympy import Point, Circle >>> c1 = Circle(Point(0, 0), 5) >>> c1.equation() x**2 + y**2 - 25 """ x = _symbol(x, real=True) y = _symbol(y, real=True) t1 = (x - self.center.x)**2 t2 = (y - self.center.y)**2 return t1 + t2 - self.major**2 def intersection(self, o): """The intersection of this circle with another geometrical entity. Parameters ========== o : GeometryEntity Returns ======= intersection : list of GeometryEntities Examples ======== >>> from sympy import Point, Circle, Line, Ray >>> p1, p2, p3 = Point(0, 0), Point(5, 5), Point(6, 0) >>> p4 = Point(5, 0) >>> c1 = Circle(p1, 5) >>> c1.intersection(p2) [] >>> c1.intersection(p4) [Point2D(5, 0)] >>> c1.intersection(Ray(p1, p2)) [Point2D(5*sqrt(2)/2, 5*sqrt(2)/2)] >>> c1.intersection(Line(p2, p3)) [] """ return Ellipse.intersection(self, o) @property def radius(self): """The radius of the circle. Returns ======= radius : number or SymPy expression See Also ======== Ellipse.major, Ellipse.minor, Ellipse.hradius, Ellipse.vradius Examples ======== >>> from sympy import Point, Circle >>> c1 = Circle(Point(3, 4), 6) >>> c1.radius 6 """ return self.args[1] def reflect(self, line): """Override GeometryEntity.reflect since the radius is not a GeometryEntity. Examples ======== >>> from sympy import Circle, Line >>> Circle((0, 1), 1).reflect(Line((0, 0), (1, 1))) Circle(Point2D(1, 0), -1) """ c = self.center c = c.reflect(line) return self.func(c, -self.radius) def scale(self, x=1, y=1, pt=None): """Override GeometryEntity.scale since the radius is not a GeometryEntity. Examples ======== >>> from sympy import Circle >>> Circle((0, 0), 1).scale(2, 2) Circle(Point2D(0, 0), 2) >>> Circle((0, 0), 1).scale(2, 4) Ellipse(Point2D(0, 0), 2, 4) """ c = self.center if pt: pt = Point(pt, dim=2) return self.translate(*(-pt).args).scale(x, y).translate(*pt.args) c = c.scale(x, y) x, y = [abs(i) for i in (x, y)] if x == y: return self.func(c, x*self.radius) h = v = self.radius return Ellipse(c, hradius=h*x, vradius=v*y) @property def vradius(self): """ This Ellipse property is an alias for the Circle's radius. Whereas hradius, major and minor can use Ellipse's conventions, the vradius does not exist for a circle. It is always a positive value in order that the Circle, like Polygons, will have an area that can be positive or negative as determined by the sign of the hradius. Examples ======== >>> from sympy import Point, Circle >>> c1 = Circle(Point(3, 4), 6) >>> c1.vradius 6 """ return abs(self.radius) from .polygon import Polygon, Triangle
7ef1e1b526fa46f13abfef3233208dbe6d1e90b3e83bb10ef49f1312c1b24065
"""The definition of the base geometrical entity with attributes common to all derived geometrical entities. Contains ======== GeometryEntity GeometricSet Notes ===== A GeometryEntity is any object that has special geometric properties. A GeometrySet is a superclass of any GeometryEntity that can also be viewed as a sympy.sets.Set. In particular, points are the only GeometryEntity not considered a Set. Rn is a GeometrySet representing n-dimensional Euclidean space. R2 and R3 are currently the only ambient spaces implemented. """ from __future__ import annotations from sympy.core.basic import Basic from sympy.core.containers import Tuple from sympy.core.evalf import EvalfMixin, N from sympy.core.numbers import oo from sympy.core.symbol import Dummy from sympy.core.sympify import sympify from sympy.functions.elementary.trigonometric import cos, sin, atan from sympy.matrices import eye from sympy.multipledispatch import dispatch from sympy.printing import sstr from sympy.sets import Set, Union, FiniteSet from sympy.sets.handlers.intersection import intersection_sets from sympy.sets.handlers.union import union_sets from sympy.solvers.solvers import solve from sympy.utilities.misc import func_name from sympy.utilities.iterables import is_sequence # How entities are ordered; used by __cmp__ in GeometryEntity ordering_of_classes = [ "Point2D", "Point3D", "Point", "Segment2D", "Ray2D", "Line2D", "Segment3D", "Line3D", "Ray3D", "Segment", "Ray", "Line", "Plane", "Triangle", "RegularPolygon", "Polygon", "Circle", "Ellipse", "Curve", "Parabola" ] x, y = [Dummy('entity_dummy') for i in range(2)] T = Dummy('entity_dummy', real=True) class GeometryEntity(Basic, EvalfMixin): """The base class for all geometrical entities. This class does not represent any particular geometric entity, it only provides the implementation of some methods common to all subclasses. """ __slots__: tuple[str, ...] = () def __cmp__(self, other): """Comparison of two GeometryEntities.""" n1 = self.__class__.__name__ n2 = other.__class__.__name__ c = (n1 > n2) - (n1 < n2) if not c: return 0 i1 = -1 for cls in self.__class__.__mro__: try: i1 = ordering_of_classes.index(cls.__name__) break except ValueError: i1 = -1 if i1 == -1: return c i2 = -1 for cls in other.__class__.__mro__: try: i2 = ordering_of_classes.index(cls.__name__) break except ValueError: i2 = -1 if i2 == -1: return c return (i1 > i2) - (i1 < i2) def __contains__(self, other): """Subclasses should implement this method for anything more complex than equality.""" if type(self) is type(other): return self == other raise NotImplementedError() def __getnewargs__(self): """Returns a tuple that will be passed to __new__ on unpickling.""" return tuple(self.args) def __ne__(self, o): """Test inequality of two geometrical entities.""" return not self == o def __new__(cls, *args, **kwargs): # Points are sequences, but they should not # be converted to Tuples, so use this detection function instead. def is_seq_and_not_point(a): # we cannot use isinstance(a, Point) since we cannot import Point if hasattr(a, 'is_Point') and a.is_Point: return False return is_sequence(a) args = [Tuple(*a) if is_seq_and_not_point(a) else sympify(a) for a in args] return Basic.__new__(cls, *args) def __radd__(self, a): """Implementation of reverse add method.""" return a.__add__(self) def __rtruediv__(self, a): """Implementation of reverse division method.""" return a.__truediv__(self) def __repr__(self): """String representation of a GeometryEntity that can be evaluated by sympy.""" return type(self).__name__ + repr(self.args) def __rmul__(self, a): """Implementation of reverse multiplication method.""" return a.__mul__(self) def __rsub__(self, a): """Implementation of reverse subtraction method.""" return a.__sub__(self) def __str__(self): """String representation of a GeometryEntity.""" return type(self).__name__ + sstr(self.args) def _eval_subs(self, old, new): from sympy.geometry.point import Point, Point3D if is_sequence(old) or is_sequence(new): if isinstance(self, Point3D): old = Point3D(old) new = Point3D(new) else: old = Point(old) new = Point(new) return self._subs(old, new) def _repr_svg_(self): """SVG representation of a GeometryEntity suitable for IPython""" try: bounds = self.bounds except (NotImplementedError, TypeError): # if we have no SVG representation, return None so IPython # will fall back to the next representation return None if not all(x.is_number and x.is_finite for x in bounds): return None svg_top = '''<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="{1}" height="{2}" viewBox="{0}" preserveAspectRatio="xMinYMin meet"> <defs> <marker id="markerCircle" markerWidth="8" markerHeight="8" refx="5" refy="5" markerUnits="strokeWidth"> <circle cx="5" cy="5" r="1.5" style="stroke: none; fill:#000000;"/> </marker> <marker id="markerArrow" markerWidth="13" markerHeight="13" refx="2" refy="4" orient="auto" markerUnits="strokeWidth"> <path d="M2,2 L2,6 L6,4" style="fill: #000000;" /> </marker> <marker id="markerReverseArrow" markerWidth="13" markerHeight="13" refx="6" refy="4" orient="auto" markerUnits="strokeWidth"> <path d="M6,2 L6,6 L2,4" style="fill: #000000;" /> </marker> </defs>''' # Establish SVG canvas that will fit all the data + small space xmin, ymin, xmax, ymax = map(N, bounds) if xmin == xmax and ymin == ymax: # This is a point; buffer using an arbitrary size xmin, ymin, xmax, ymax = xmin - .5, ymin -.5, xmax + .5, ymax + .5 else: # Expand bounds by a fraction of the data ranges expand = 0.1 # or 10%; this keeps arrowheads in view (R plots use 4%) widest_part = max([xmax - xmin, ymax - ymin]) expand_amount = widest_part * expand xmin -= expand_amount ymin -= expand_amount xmax += expand_amount ymax += expand_amount dx = xmax - xmin dy = ymax - ymin width = min([max([100., dx]), 300]) height = min([max([100., dy]), 300]) scale_factor = 1. if max(width, height) == 0 else max(dx, dy) / max(width, height) try: svg = self._svg(scale_factor) except (NotImplementedError, TypeError): # if we have no SVG representation, return None so IPython # will fall back to the next representation return None view_box = "{} {} {} {}".format(xmin, ymin, dx, dy) transform = "matrix(1,0,0,-1,0,{})".format(ymax + ymin) svg_top = svg_top.format(view_box, width, height) return svg_top + ( '<g transform="{}">{}</g></svg>' ).format(transform, svg) def _svg(self, scale_factor=1., fill_color="#66cc99"): """Returns SVG path element for the GeometryEntity. Parameters ========== scale_factor : float Multiplication factor for the SVG stroke-width. Default is 1. fill_color : str, optional Hex string for fill color. Default is "#66cc99". """ raise NotImplementedError() def _sympy_(self): return self @property def ambient_dimension(self): """What is the dimension of the space that the object is contained in?""" raise NotImplementedError() @property def bounds(self): """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding rectangle for the geometric figure. """ raise NotImplementedError() def encloses(self, o): """ Return True if o is inside (not on or outside) the boundaries of self. The object will be decomposed into Points and individual Entities need only define an encloses_point method for their class. See Also ======== sympy.geometry.ellipse.Ellipse.encloses_point sympy.geometry.polygon.Polygon.encloses_point Examples ======== >>> from sympy import RegularPolygon, Point, Polygon >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices) >>> t2 = Polygon(*RegularPolygon(Point(0, 0), 2, 3).vertices) >>> t2.encloses(t) True >>> t.encloses(t2) False """ from sympy.geometry.point import Point from sympy.geometry.line import Segment, Ray, Line from sympy.geometry.ellipse import Ellipse from sympy.geometry.polygon import Polygon, RegularPolygon if isinstance(o, Point): return self.encloses_point(o) elif isinstance(o, Segment): return all(self.encloses_point(x) for x in o.points) elif isinstance(o, (Ray, Line)): return False elif isinstance(o, Ellipse): return self.encloses_point(o.center) and \ self.encloses_point( Point(o.center.x + o.hradius, o.center.y)) and \ not self.intersection(o) elif isinstance(o, Polygon): if isinstance(o, RegularPolygon): if not self.encloses_point(o.center): return False return all(self.encloses_point(v) for v in o.vertices) raise NotImplementedError() def equals(self, o): return self == o def intersection(self, o): """ Returns a list of all of the intersections of self with o. Notes ===== An entity is not required to implement this method. If two different types of entities can intersect, the item with higher index in ordering_of_classes should implement intersections with anything having a lower index. See Also ======== sympy.geometry.util.intersection """ raise NotImplementedError() def is_similar(self, other): """Is this geometrical entity similar to another geometrical entity? Two entities are similar if a uniform scaling (enlarging or shrinking) of one of the entities will allow one to obtain the other. Notes ===== This method is not intended to be used directly but rather through the `are_similar` function found in util.py. An entity is not required to implement this method. If two different types of entities can be similar, it is only required that one of them be able to determine this. See Also ======== scale """ raise NotImplementedError() def reflect(self, line): """ Reflects an object across a line. Parameters ========== line: Line Examples ======== >>> from sympy import pi, sqrt, Line, RegularPolygon >>> l = Line((0, pi), slope=sqrt(2)) >>> pent = RegularPolygon((1, 2), 1, 5) >>> rpent = pent.reflect(l) >>> rpent RegularPolygon(Point2D(-2*sqrt(2)*pi/3 - 1/3 + 4*sqrt(2)/3, 2/3 + 2*sqrt(2)/3 + 2*pi/3), -1, 5, -atan(2*sqrt(2)) + 3*pi/5) >>> from sympy import pi, Line, Circle, Point >>> l = Line((0, pi), slope=1) >>> circ = Circle(Point(0, 0), 5) >>> rcirc = circ.reflect(l) >>> rcirc Circle(Point2D(-pi, pi), -5) """ from sympy.geometry.point import Point g = self l = line o = Point(0, 0) if l.slope.is_zero: v = l.args[0].y if not v: # x-axis return g.scale(y=-1) reps = [(p, p.translate(y=2*(v - p.y))) for p in g.atoms(Point)] elif l.slope is oo: v = l.args[0].x if not v: # y-axis return g.scale(x=-1) reps = [(p, p.translate(x=2*(v - p.x))) for p in g.atoms(Point)] else: if not hasattr(g, 'reflect') and not all( isinstance(arg, Point) for arg in g.args): raise NotImplementedError( 'reflect undefined or non-Point args in %s' % g) a = atan(l.slope) c = l.coefficients d = -c[-1]/c[1] # y-intercept # apply the transform to a single point xf = Point(x, y) xf = xf.translate(y=-d).rotate(-a, o).scale(y=-1 ).rotate(a, o).translate(y=d) # replace every point using that transform reps = [(p, xf.xreplace({x: p.x, y: p.y})) for p in g.atoms(Point)] return g.xreplace(dict(reps)) def rotate(self, angle, pt=None): """Rotate ``angle`` radians counterclockwise about Point ``pt``. The default pt is the origin, Point(0, 0) See Also ======== scale, translate Examples ======== >>> from sympy import Point, RegularPolygon, Polygon, pi >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices) >>> t # vertex on x axis Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2)) >>> t.rotate(pi/2) # vertex on y axis now Triangle(Point2D(0, 1), Point2D(-sqrt(3)/2, -1/2), Point2D(sqrt(3)/2, -1/2)) """ newargs = [] for a in self.args: if isinstance(a, GeometryEntity): newargs.append(a.rotate(angle, pt)) else: newargs.append(a) return type(self)(*newargs) def scale(self, x=1, y=1, pt=None): """Scale the object by multiplying the x,y-coordinates by x and y. If pt is given, the scaling is done relative to that point; the object is shifted by -pt, scaled, and shifted by pt. See Also ======== rotate, translate Examples ======== >>> from sympy import RegularPolygon, Point, Polygon >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices) >>> t Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2)) >>> t.scale(2) Triangle(Point2D(2, 0), Point2D(-1, sqrt(3)/2), Point2D(-1, -sqrt(3)/2)) >>> t.scale(2, 2) Triangle(Point2D(2, 0), Point2D(-1, sqrt(3)), Point2D(-1, -sqrt(3))) """ from sympy.geometry.point import Point if pt: pt = Point(pt, dim=2) return self.translate(*(-pt).args).scale(x, y).translate(*pt.args) return type(self)(*[a.scale(x, y) for a in self.args]) # if this fails, override this class def translate(self, x=0, y=0): """Shift the object by adding to the x,y-coordinates the values x and y. See Also ======== rotate, scale Examples ======== >>> from sympy import RegularPolygon, Point, Polygon >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices) >>> t Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2)) >>> t.translate(2) Triangle(Point2D(3, 0), Point2D(3/2, sqrt(3)/2), Point2D(3/2, -sqrt(3)/2)) >>> t.translate(2, 2) Triangle(Point2D(3, 2), Point2D(3/2, sqrt(3)/2 + 2), Point2D(3/2, 2 - sqrt(3)/2)) """ newargs = [] for a in self.args: if isinstance(a, GeometryEntity): newargs.append(a.translate(x, y)) else: newargs.append(a) return self.func(*newargs) def parameter_value(self, other, t): """Return the parameter corresponding to the given point. Evaluating an arbitrary point of the entity at this parameter value will return the given point. Examples ======== >>> from sympy import Line, Point >>> from sympy.abc import t >>> a = Point(0, 0) >>> b = Point(2, 2) >>> Line(a, b).parameter_value((1, 1), t) {t: 1/2} >>> Line(a, b).arbitrary_point(t).subs(_) Point2D(1, 1) """ from sympy.geometry.point import Point if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if not isinstance(other, Point): raise ValueError("other must be a point") sol = solve(self.arbitrary_point(T) - other, T, dict=True) if not sol: raise ValueError("Given point is not on %s" % func_name(self)) return {t: sol[0][T]} class GeometrySet(GeometryEntity, Set): """Parent class of all GeometryEntity that are also Sets (compatible with sympy.sets) """ __slots__ = () def _contains(self, other): """sympy.sets uses the _contains method, so include it for compatibility.""" if isinstance(other, Set) and other.is_FiniteSet: return all(self.__contains__(i) for i in other) return self.__contains__(other) @dispatch(GeometrySet, Set) # type:ignore # noqa:F811 def union_sets(self, o): # noqa:F811 """ Returns the union of self and o for use with sympy.sets.Set, if possible. """ # if its a FiniteSet, merge any points # we contain and return a union with the rest if o.is_FiniteSet: other_points = [p for p in o if not self._contains(p)] if len(other_points) == len(o): return None return Union(self, FiniteSet(*other_points)) if self._contains(o): return self return None @dispatch(GeometrySet, Set) # type: ignore # noqa:F811 def intersection_sets(self, o): # noqa:F811 """ Returns a sympy.sets.Set of intersection objects, if possible. """ from sympy.geometry.point import Point try: # if o is a FiniteSet, find the intersection directly # to avoid infinite recursion if o.is_FiniteSet: inter = FiniteSet(*(p for p in o if self.contains(p))) else: inter = self.intersection(o) except NotImplementedError: # sympy.sets.Set.reduce expects None if an object # doesn't know how to simplify return None # put the points in a FiniteSet points = FiniteSet(*[p for p in inter if isinstance(p, Point)]) non_points = [p for p in inter if not isinstance(p, Point)] return Union(*(non_points + [points])) def translate(x, y): """Return the matrix to translate a 2-D point by x and y.""" rv = eye(3) rv[2, 0] = x rv[2, 1] = y return rv def scale(x, y, pt=None): """Return the matrix to multiply a 2-D point's coordinates by x and y. If pt is given, the scaling is done relative to that point.""" rv = eye(3) rv[0, 0] = x rv[1, 1] = y if pt: from sympy.geometry.point import Point pt = Point(pt, dim=2) tr1 = translate(*(-pt).args) tr2 = translate(*pt.args) return tr1*rv*tr2 return rv def rotate(th): """Return the matrix to rotate a 2-D point about the origin by ``angle``. The angle is measured in radians. To Point a point about a point other then the origin, translate the Point, do the rotation, and translate it back: >>> from sympy.geometry.entity import rotate, translate >>> from sympy import Point, pi >>> rot_about_11 = translate(-1, -1)*rotate(pi/2)*translate(1, 1) >>> Point(1, 1).transform(rot_about_11) Point2D(1, 1) >>> Point(0, 0).transform(rot_about_11) Point2D(2, 0) """ s = sin(th) rv = eye(3)*cos(th) rv[0, 1] = s rv[1, 0] = -s rv[2, 2] = 1 return rv
a092f886ef8cc5fd6d53aee0ba55e58fff52b7c8e8e866a773b79e1b01bba581
"""Utility functions for geometrical entities. Contains ======== intersection convex_hull closest_points farthest_points are_coplanar are_similar """ from collections import deque from math import sqrt as _sqrt from .entity import GeometryEntity from .exceptions import GeometryError from .point import Point, Point2D, Point3D from sympy.core.containers import OrderedSet from sympy.core.exprtools import factor_terms from sympy.core.function import Function, expand_mul from sympy.core.sorting import ordered from sympy.core.symbol import Symbol from sympy.core.singleton import S from sympy.polys.polytools import cancel from sympy.functions.elementary.miscellaneous import sqrt from sympy.utilities.iterables import is_sequence def find(x, equation): """ Checks whether a Symbol matching ``x`` is present in ``equation`` or not. If present, the matching symbol is returned, else a ValueError is raised. If ``x`` is a string the matching symbol will have the same name; if ``x`` is a Symbol then it will be returned if found. Examples ======== >>> from sympy.geometry.util import find >>> from sympy import Dummy >>> from sympy.abc import x >>> find('x', x) x >>> find('x', Dummy('x')) _x The dummy symbol is returned since it has a matching name: >>> _.name == 'x' True >>> find(x, Dummy('x')) Traceback (most recent call last): ... ValueError: could not find x """ free = equation.free_symbols xs = [i for i in free if (i.name if isinstance(x, str) else i) == x] if not xs: raise ValueError('could not find %s' % x) if len(xs) != 1: raise ValueError('ambiguous %s' % x) return xs[0] def _ordered_points(p): """Return the tuple of points sorted numerically according to args""" return tuple(sorted(p, key=lambda x: x.args)) def are_coplanar(*e): """ Returns True if the given entities are coplanar otherwise False Parameters ========== e: entities to be checked for being coplanar Returns ======= Boolean Examples ======== >>> from sympy import Point3D, Line3D >>> from sympy.geometry.util import are_coplanar >>> a = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1)) >>> b = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1)) >>> c = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9)) >>> are_coplanar(a, b, c) False """ from .line import LinearEntity3D from .plane import Plane # XXX update tests for coverage e = set(e) # first work with a Plane if present for i in list(e): if isinstance(i, Plane): e.remove(i) return all(p.is_coplanar(i) for p in e) if all(isinstance(i, Point3D) for i in e): if len(e) < 3: return False # remove pts that are collinear with 2 pts a, b = e.pop(), e.pop() for i in list(e): if Point3D.are_collinear(a, b, i): e.remove(i) if not e: return False else: # define a plane p = Plane(a, b, e.pop()) for i in e: if i not in p: return False return True else: pt3d = [] for i in e: if isinstance(i, Point3D): pt3d.append(i) elif isinstance(i, LinearEntity3D): pt3d.extend(i.args) elif isinstance(i, GeometryEntity): # XXX we should have a GeometryEntity3D class so we can tell the difference between 2D and 3D -- here we just want to deal with 2D objects; if new 3D objects are encountered that we didn't handle above, an error should be raised # all 2D objects have some Point that defines them; so convert those points to 3D pts by making z=0 for p in i.args: if isinstance(p, Point): pt3d.append(Point3D(*(p.args + (0,)))) return are_coplanar(*pt3d) def are_similar(e1, e2): """Are two geometrical entities similar. Can one geometrical entity be uniformly scaled to the other? Parameters ========== e1 : GeometryEntity e2 : GeometryEntity Returns ======= are_similar : boolean Raises ====== GeometryError When `e1` and `e2` cannot be compared. Notes ===== If the two objects are equal then they are similar. See Also ======== sympy.geometry.entity.GeometryEntity.is_similar Examples ======== >>> from sympy import Point, Circle, Triangle, are_similar >>> c1, c2 = Circle(Point(0, 0), 4), Circle(Point(1, 4), 3) >>> t1 = Triangle(Point(0, 0), Point(1, 0), Point(0, 1)) >>> t2 = Triangle(Point(0, 0), Point(2, 0), Point(0, 2)) >>> t3 = Triangle(Point(0, 0), Point(3, 0), Point(0, 1)) >>> are_similar(t1, t2) True >>> are_similar(t1, t3) False """ if e1 == e2: return True is_similar1 = getattr(e1, 'is_similar', None) if is_similar1: return is_similar1(e2) is_similar2 = getattr(e2, 'is_similar', None) if is_similar2: return is_similar2(e1) n1 = e1.__class__.__name__ n2 = e2.__class__.__name__ raise GeometryError( "Cannot test similarity between %s and %s" % (n1, n2)) def centroid(*args): """Find the centroid (center of mass) of the collection containing only Points, Segments or Polygons. The centroid is the weighted average of the individual centroid where the weights are the lengths (of segments) or areas (of polygons). Overlapping regions will add to the weight of that region. If there are no objects (or a mixture of objects) then None is returned. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Segment, sympy.geometry.polygon.Polygon Examples ======== >>> from sympy import Point, Segment, Polygon >>> from sympy.geometry.util import centroid >>> p = Polygon((0, 0), (10, 0), (10, 10)) >>> q = p.translate(0, 20) >>> p.centroid, q.centroid (Point2D(20/3, 10/3), Point2D(20/3, 70/3)) >>> centroid(p, q) Point2D(20/3, 40/3) >>> p, q = Segment((0, 0), (2, 0)), Segment((0, 0), (2, 2)) >>> centroid(p, q) Point2D(1, 2 - sqrt(2)) >>> centroid(Point(0, 0), Point(2, 0)) Point2D(1, 0) Stacking 3 polygons on top of each other effectively triples the weight of that polygon: >>> p = Polygon((0, 0), (1, 0), (1, 1), (0, 1)) >>> q = Polygon((1, 0), (3, 0), (3, 1), (1, 1)) >>> centroid(p, q) Point2D(3/2, 1/2) >>> centroid(p, p, p, q) # centroid x-coord shifts left Point2D(11/10, 1/2) Stacking the squares vertically above and below p has the same effect: >>> centroid(p, p.translate(0, 1), p.translate(0, -1), q) Point2D(11/10, 1/2) """ from .line import Segment from .polygon import Polygon if args: if all(isinstance(g, Point) for g in args): c = Point(0, 0) for g in args: c += g den = len(args) elif all(isinstance(g, Segment) for g in args): c = Point(0, 0) L = 0 for g in args: l = g.length c += g.midpoint*l L += l den = L elif all(isinstance(g, Polygon) for g in args): c = Point(0, 0) A = 0 for g in args: a = g.area c += g.centroid*a A += a den = A c /= den return c.func(*[i.simplify() for i in c.args]) def closest_points(*args): """Return the subset of points from a set of points that were the closest to each other in the 2D plane. Parameters ========== args A collection of Points on 2D plane. Notes ===== This can only be performed on a set of points whose coordinates can be ordered on the number line. If there are no ties then a single pair of Points will be in the set. Examples ======== >>> from sympy import closest_points, Triangle >>> Triangle(sss=(3, 4, 5)).args (Point2D(0, 0), Point2D(3, 0), Point2D(3, 4)) >>> closest_points(*_) {(Point2D(0, 0), Point2D(3, 0))} References ========== .. [1] http://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairPS.html .. [2] Sweep line algorithm https://en.wikipedia.org/wiki/Sweep_line_algorithm """ p = [Point2D(i) for i in set(args)] if len(p) < 2: raise ValueError('At least 2 distinct points must be given.') try: p.sort(key=lambda x: x.args) except TypeError: raise ValueError("The points could not be sorted.") if not all(i.is_Rational for j in p for i in j.args): def hypot(x, y): arg = x*x + y*y if arg.is_Rational: return _sqrt(arg) return sqrt(arg) else: from math import hypot rv = [(0, 1)] best_dist = hypot(p[1].x - p[0].x, p[1].y - p[0].y) i = 2 left = 0 box = deque([0, 1]) while i < len(p): while left < i and p[i][0] - p[left][0] > best_dist: box.popleft() left += 1 for j in box: d = hypot(p[i].x - p[j].x, p[i].y - p[j].y) if d < best_dist: rv = [(j, i)] elif d == best_dist: rv.append((j, i)) else: continue best_dist = d box.append(i) i += 1 return {tuple([p[i] for i in pair]) for pair in rv} def convex_hull(*args, polygon=True): """The convex hull surrounding the Points contained in the list of entities. Parameters ========== args : a collection of Points, Segments and/or Polygons Optional parameters =================== polygon : Boolean. If True, returns a Polygon, if false a tuple, see below. Default is True. Returns ======= convex_hull : Polygon if ``polygon`` is True else as a tuple `(U, L)` where ``L`` and ``U`` are the lower and upper hulls, respectively. Notes ===== This can only be performed on a set of points whose coordinates can be ordered on the number line. See Also ======== sympy.geometry.point.Point, sympy.geometry.polygon.Polygon Examples ======== >>> from sympy import convex_hull >>> points = [(1, 1), (1, 2), (3, 1), (-5, 2), (15, 4)] >>> convex_hull(*points) Polygon(Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4)) >>> convex_hull(*points, **dict(polygon=False)) ([Point2D(-5, 2), Point2D(15, 4)], [Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4)]) References ========== .. [1] https://en.wikipedia.org/wiki/Graham_scan .. [2] Andrew's Monotone Chain Algorithm (A.M. Andrew, "Another Efficient Algorithm for Convex Hulls in Two Dimensions", 1979) http://geomalgorithms.com/a10-_hull-1.html """ from .line import Segment from .polygon import Polygon p = OrderedSet() for e in args: if not isinstance(e, GeometryEntity): try: e = Point(e) except NotImplementedError: raise ValueError('%s is not a GeometryEntity and cannot be made into Point' % str(e)) if isinstance(e, Point): p.add(e) elif isinstance(e, Segment): p.update(e.points) elif isinstance(e, Polygon): p.update(e.vertices) else: raise NotImplementedError( 'Convex hull for %s not implemented.' % type(e)) # make sure all our points are of the same dimension if any(len(x) != 2 for x in p): raise ValueError('Can only compute the convex hull in two dimensions') p = list(p) if len(p) == 1: return p[0] if polygon else (p[0], None) elif len(p) == 2: s = Segment(p[0], p[1]) return s if polygon else (s, None) def _orientation(p, q, r): '''Return positive if p-q-r are clockwise, neg if ccw, zero if collinear.''' return (q.y - p.y)*(r.x - p.x) - (q.x - p.x)*(r.y - p.y) # scan to find upper and lower convex hulls of a set of 2d points. U = [] L = [] try: p.sort(key=lambda x: x.args) except TypeError: raise ValueError("The points could not be sorted.") for p_i in p: while len(U) > 1 and _orientation(U[-2], U[-1], p_i) <= 0: U.pop() while len(L) > 1 and _orientation(L[-2], L[-1], p_i) >= 0: L.pop() U.append(p_i) L.append(p_i) U.reverse() convexHull = tuple(L + U[1:-1]) if len(convexHull) == 2: s = Segment(convexHull[0], convexHull[1]) return s if polygon else (s, None) if polygon: return Polygon(*convexHull) else: U.reverse() return (U, L) def farthest_points(*args): """Return the subset of points from a set of points that were the furthest apart from each other in the 2D plane. Parameters ========== args A collection of Points on 2D plane. Notes ===== This can only be performed on a set of points whose coordinates can be ordered on the number line. If there are no ties then a single pair of Points will be in the set. Examples ======== >>> from sympy.geometry import farthest_points, Triangle >>> Triangle(sss=(3, 4, 5)).args (Point2D(0, 0), Point2D(3, 0), Point2D(3, 4)) >>> farthest_points(*_) {(Point2D(0, 0), Point2D(3, 4))} References ========== .. [1] http://code.activestate.com/recipes/117225-convex-hull-and-diameter-of-2d-point-sets/ .. [2] Rotating Callipers Technique https://en.wikipedia.org/wiki/Rotating_calipers """ def rotatingCalipers(Points): U, L = convex_hull(*Points, **dict(polygon=False)) if L is None: if isinstance(U, Point): raise ValueError('At least two distinct points must be given.') yield U.args else: i = 0 j = len(L) - 1 while i < len(U) - 1 or j > 0: yield U[i], L[j] # if all the way through one side of hull, advance the other side if i == len(U) - 1: j -= 1 elif j == 0: i += 1 # still points left on both lists, compare slopes of next hull edges # being careful to avoid divide-by-zero in slope calculation elif (U[i+1].y - U[i].y) * (L[j].x - L[j-1].x) > \ (L[j].y - L[j-1].y) * (U[i+1].x - U[i].x): i += 1 else: j -= 1 p = [Point2D(i) for i in set(args)] if not all(i.is_Rational for j in p for i in j.args): def hypot(x, y): arg = x*x + y*y if arg.is_Rational: return _sqrt(arg) return sqrt(arg) else: from math import hypot rv = [] diam = 0 for pair in rotatingCalipers(args): h, q = _ordered_points(pair) d = hypot(h.x - q.x, h.y - q.y) if d > diam: rv = [(h, q)] elif d == diam: rv.append((h, q)) else: continue diam = d return set(rv) def idiff(eq, y, x, n=1): """Return ``dy/dx`` assuming that ``eq == 0``. Parameters ========== y : the dependent variable or a list of dependent variables (with y first) x : the variable that the derivative is being taken with respect to n : the order of the derivative (default is 1) Examples ======== >>> from sympy.abc import x, y, a >>> from sympy.geometry.util import idiff >>> circ = x**2 + y**2 - 4 >>> idiff(circ, y, x) -x/y >>> idiff(circ, y, x, 2).simplify() (-x**2 - y**2)/y**3 Here, ``a`` is assumed to be independent of ``x``: >>> idiff(x + a + y, y, x) -1 Now the x-dependence of ``a`` is made explicit by listing ``a`` after ``y`` in a list. >>> idiff(x + a + y, [y, a], x) -Derivative(a, x) - 1 See Also ======== sympy.core.function.Derivative: represents unevaluated derivatives sympy.core.function.diff: explicitly differentiates wrt symbols """ if is_sequence(y): dep = set(y) y = y[0] elif isinstance(y, Symbol): dep = {y} elif isinstance(y, Function): pass else: raise ValueError("expecting x-dependent symbol(s) or function(s) but got: %s" % y) f = {s: Function(s.name)(x) for s in eq.free_symbols if s != x and s in dep} if isinstance(y, Symbol): dydx = Function(y.name)(x).diff(x) else: dydx = y.diff(x) eq = eq.subs(f) derivs = {} for i in range(n): # equation will be linear in dydx, a*dydx + b, so dydx = -b/a deq = eq.diff(x) b = deq.xreplace({dydx: S.Zero}) a = (deq - b).xreplace({dydx: S.One}) yp = factor_terms(expand_mul(cancel((-b/a).subs(derivs)), deep=False)) if i == n - 1: return yp.subs([(v, k) for k, v in f.items()]) derivs[dydx] = yp eq = dydx - yp dydx = dydx.diff(x) def intersection(*entities, pairwise=False, **kwargs): """The intersection of a collection of GeometryEntity instances. Parameters ========== entities : sequence of GeometryEntity pairwise (keyword argument) : Can be either True or False Returns ======= intersection : list of GeometryEntity Raises ====== NotImplementedError When unable to calculate intersection. Notes ===== The intersection of any geometrical entity with itself should return a list with one item: the entity in question. An intersection requires two or more entities. If only a single entity is given then the function will return an empty list. It is possible for `intersection` to miss intersections that one knows exists because the required quantities were not fully simplified internally. Reals should be converted to Rationals, e.g. Rational(str(real_num)) or else failures due to floating point issues may result. Case 1: When the keyword argument 'pairwise' is False (default value): In this case, the function returns a list of intersections common to all entities. Case 2: When the keyword argument 'pairwise' is True: In this case, the functions returns a list intersections that occur between any pair of entities. See Also ======== sympy.geometry.entity.GeometryEntity.intersection Examples ======== >>> from sympy import Ray, Circle, intersection >>> c = Circle((0, 1), 1) >>> intersection(c, c.center) [] >>> right = Ray((0, 0), (1, 0)) >>> up = Ray((0, 0), (0, 1)) >>> intersection(c, right, up) [Point2D(0, 0)] >>> intersection(c, right, up, pairwise=True) [Point2D(0, 0), Point2D(0, 2)] >>> left = Ray((1, 0), (0, 0)) >>> intersection(right, left) [Segment2D(Point2D(0, 0), Point2D(1, 0))] """ if len(entities) <= 1: return [] # entities may be an immutable tuple entities = list(entities) for i, e in enumerate(entities): if not isinstance(e, GeometryEntity): entities[i] = Point(e) if not pairwise: # find the intersection common to all objects res = entities[0].intersection(entities[1]) for entity in entities[2:]: newres = [] for x in res: newres.extend(x.intersection(entity)) res = newres return res # find all pairwise intersections ans = [] for j in range(len(entities)): for k in range(j + 1, len(entities)): ans.extend(intersection(entities[j], entities[k])) return list(ordered(set(ans)))
25273475c8ca5769b547a6fbb4868f8df7e1746cf765db6314abec1fbd8bbaaa
"""Line-like geometrical entities. Contains ======== LinearEntity Line Ray Segment LinearEntity2D Line2D Ray2D Segment2D LinearEntity3D Line3D Ray3D Segment3D """ from sympy.core.containers import Tuple from sympy.core.evalf import N from sympy.core.expr import Expr from sympy.core.numbers import Rational, oo, Float from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.sorting import ordered from sympy.core.symbol import _symbol, Dummy, uniquely_named_symbol from sympy.core.sympify import sympify from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (_pi_coeff, acos, tan, atan2) from .entity import GeometryEntity, GeometrySet from .exceptions import GeometryError from .point import Point, Point3D from .util import find, intersection from sympy.logic.boolalg import And from sympy.matrices import Matrix from sympy.sets.sets import Intersection from sympy.simplify.simplify import simplify from sympy.solvers.solvers import solve from sympy.solvers.solveset import linear_coeffs from sympy.utilities.misc import Undecidable, filldedent import random t, u = [Dummy('line_dummy') for i in range(2)] class LinearEntity(GeometrySet): """A base class for all linear entities (Line, Ray and Segment) in n-dimensional Euclidean space. Attributes ========== ambient_dimension direction length p1 p2 points Notes ===== This is an abstract class and is not meant to be instantiated. See Also ======== sympy.geometry.entity.GeometryEntity """ def __new__(cls, p1, p2=None, **kwargs): p1, p2 = Point._normalize_dimension(p1, p2) if p1 == p2: # sometimes we return a single point if we are not given two unique # points. This is done in the specific subclass raise ValueError( "%s.__new__ requires two unique Points." % cls.__name__) if len(p1) != len(p2): raise ValueError( "%s.__new__ requires two Points of equal dimension." % cls.__name__) return GeometryEntity.__new__(cls, p1, p2, **kwargs) def __contains__(self, other): """Return a definitive answer or else raise an error if it cannot be determined that other is on the boundaries of self.""" result = self.contains(other) if result is not None: return result else: raise Undecidable( "Cannot decide whether '%s' contains '%s'" % (self, other)) def _span_test(self, other): """Test whether the point `other` lies in the positive span of `self`. A point x is 'in front' of a point y if x.dot(y) >= 0. Return -1 if `other` is behind `self.p1`, 0 if `other` is `self.p1` and and 1 if `other` is in front of `self.p1`.""" if self.p1 == other: return 0 rel_pos = other - self.p1 d = self.direction if d.dot(rel_pos) > 0: return 1 return -1 @property def ambient_dimension(self): """A property method that returns the dimension of LinearEntity object. Parameters ========== p1 : LinearEntity Returns ======= dimension : integer Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(1, 1) >>> l1 = Line(p1, p2) >>> l1.ambient_dimension 2 >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0, 0), Point(1, 1, 1) >>> l1 = Line(p1, p2) >>> l1.ambient_dimension 3 """ return len(self.p1) def angle_between(l1, l2): """Return the non-reflex angle formed by rays emanating from the origin with directions the same as the direction vectors of the linear entities. Parameters ========== l1 : LinearEntity l2 : LinearEntity Returns ======= angle : angle in radians Notes ===== From the dot product of vectors v1 and v2 it is known that: ``dot(v1, v2) = |v1|*|v2|*cos(A)`` where A is the angle formed between the two vectors. We can get the directional vectors of the two lines and readily find the angle between the two using the above formula. See Also ======== is_perpendicular, Ray2D.closing_angle Examples ======== >>> from sympy import Line >>> e = Line((0, 0), (1, 0)) >>> ne = Line((0, 0), (1, 1)) >>> sw = Line((1, 1), (0, 0)) >>> ne.angle_between(e) pi/4 >>> sw.angle_between(e) 3*pi/4 To obtain the non-obtuse angle at the intersection of lines, use the ``smallest_angle_between`` method: >>> sw.smallest_angle_between(e) pi/4 >>> from sympy import Point3D, Line3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(-1, 2, 0) >>> l1, l2 = Line3D(p1, p2), Line3D(p2, p3) >>> l1.angle_between(l2) acos(-sqrt(2)/3) >>> l1.smallest_angle_between(l2) acos(sqrt(2)/3) """ if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity): raise TypeError('Must pass only LinearEntity objects') v1, v2 = l1.direction, l2.direction return acos(v1.dot(v2)/(abs(v1)*abs(v2))) def smallest_angle_between(l1, l2): """Return the smallest angle formed at the intersection of the lines containing the linear entities. Parameters ========== l1 : LinearEntity l2 : LinearEntity Returns ======= angle : angle in radians Examples ======== >>> from sympy import Point, Line >>> p1, p2, p3 = Point(0, 0), Point(0, 4), Point(2, -2) >>> l1, l2 = Line(p1, p2), Line(p1, p3) >>> l1.smallest_angle_between(l2) pi/4 See Also ======== angle_between, is_perpendicular, Ray2D.closing_angle """ if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity): raise TypeError('Must pass only LinearEntity objects') v1, v2 = l1.direction, l2.direction return acos(abs(v1.dot(v2))/(abs(v1)*abs(v2))) def arbitrary_point(self, parameter='t'): """A parameterized point on the Line. Parameters ========== parameter : str, optional The name of the parameter which will be used for the parametric point. The default value is 't'. When this parameter is 0, the first point used to define the line will be returned, and when it is 1 the second point will be returned. Returns ======= point : Point Raises ====== ValueError When ``parameter`` already appears in the Line's definition. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(1, 0), Point(5, 3) >>> l1 = Line(p1, p2) >>> l1.arbitrary_point() Point2D(4*t + 1, 3*t) >>> from sympy import Point3D, Line3D >>> p1, p2 = Point3D(1, 0, 0), Point3D(5, 3, 1) >>> l1 = Line3D(p1, p2) >>> l1.arbitrary_point() Point3D(4*t + 1, 3*t, t) """ t = _symbol(parameter, real=True) if t.name in (f.name for f in self.free_symbols): raise ValueError(filldedent(''' Symbol %s already appears in object and cannot be used as a parameter. ''' % t.name)) # multiply on the right so the variable gets # combined with the coordinates of the point return self.p1 + (self.p2 - self.p1)*t @staticmethod def are_concurrent(*lines): """Is a sequence of linear entities concurrent? Two or more linear entities are concurrent if they all intersect at a single point. Parameters ========== lines A sequence of linear entities. Returns ======= True : if the set of linear entities intersect in one point False : otherwise. See Also ======== sympy.geometry.util.intersection Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(3, 5) >>> p3, p4 = Point(-2, -2), Point(0, 2) >>> l1, l2, l3 = Line(p1, p2), Line(p1, p3), Line(p1, p4) >>> Line.are_concurrent(l1, l2, l3) True >>> l4 = Line(p2, p3) >>> Line.are_concurrent(l2, l3, l4) False >>> from sympy import Point3D, Line3D >>> p1, p2 = Point3D(0, 0, 0), Point3D(3, 5, 2) >>> p3, p4 = Point3D(-2, -2, -2), Point3D(0, 2, 1) >>> l1, l2, l3 = Line3D(p1, p2), Line3D(p1, p3), Line3D(p1, p4) >>> Line3D.are_concurrent(l1, l2, l3) True >>> l4 = Line3D(p2, p3) >>> Line3D.are_concurrent(l2, l3, l4) False """ common_points = Intersection(*lines) if common_points.is_FiniteSet and len(common_points) == 1: return True return False def contains(self, other): """Subclasses should implement this method and should return True if other is on the boundaries of self; False if not on the boundaries of self; None if a determination cannot be made.""" raise NotImplementedError() @property def direction(self): """The direction vector of the LinearEntity. Returns ======= p : a Point; the ray from the origin to this point is the direction of `self` Examples ======== >>> from sympy import Line >>> a, b = (1, 1), (1, 3) >>> Line(a, b).direction Point2D(0, 2) >>> Line(b, a).direction Point2D(0, -2) This can be reported so the distance from the origin is 1: >>> Line(b, a).direction.unit Point2D(0, -1) See Also ======== sympy.geometry.point.Point.unit """ return self.p2 - self.p1 def intersection(self, other): """The intersection with another geometrical entity. Parameters ========== o : Point or LinearEntity Returns ======= intersection : list of geometrical entities See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Line, Segment >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7) >>> l1 = Line(p1, p2) >>> l1.intersection(p3) [Point2D(7, 7)] >>> p4, p5 = Point(5, 0), Point(0, 3) >>> l2 = Line(p4, p5) >>> l1.intersection(l2) [Point2D(15/8, 15/8)] >>> p6, p7 = Point(0, 5), Point(2, 6) >>> s1 = Segment(p6, p7) >>> l1.intersection(s1) [] >>> from sympy import Point3D, Line3D, Segment3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(7, 7, 7) >>> l1 = Line3D(p1, p2) >>> l1.intersection(p3) [Point3D(7, 7, 7)] >>> l1 = Line3D(Point3D(4,19,12), Point3D(5,25,17)) >>> l2 = Line3D(Point3D(-3, -15, -19), direction_ratio=[2,8,8]) >>> l1.intersection(l2) [Point3D(1, 1, -3)] >>> p6, p7 = Point3D(0, 5, 2), Point3D(2, 6, 3) >>> s1 = Segment3D(p6, p7) >>> l1.intersection(s1) [] """ def intersect_parallel_rays(ray1, ray2): if ray1.direction.dot(ray2.direction) > 0: # rays point in the same direction # so return the one that is "in front" return [ray2] if ray1._span_test(ray2.p1) >= 0 else [ray1] else: # rays point in opposite directions st = ray1._span_test(ray2.p1) if st < 0: return [] elif st == 0: return [ray2.p1] return [Segment(ray1.p1, ray2.p1)] def intersect_parallel_ray_and_segment(ray, seg): st1, st2 = ray._span_test(seg.p1), ray._span_test(seg.p2) if st1 < 0 and st2 < 0: return [] elif st1 >= 0 and st2 >= 0: return [seg] elif st1 >= 0: # st2 < 0: return [Segment(ray.p1, seg.p1)] else: # st1 < 0 and st2 >= 0: return [Segment(ray.p1, seg.p2)] def intersect_parallel_segments(seg1, seg2): if seg1.contains(seg2): return [seg2] if seg2.contains(seg1): return [seg1] # direct the segments so they're oriented the same way if seg1.direction.dot(seg2.direction) < 0: seg2 = Segment(seg2.p2, seg2.p1) # order the segments so seg1 is "behind" seg2 if seg1._span_test(seg2.p1) < 0: seg1, seg2 = seg2, seg1 if seg2._span_test(seg1.p2) < 0: return [] return [Segment(seg2.p1, seg1.p2)] if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if other.is_Point: if self.contains(other): return [other] else: return [] elif isinstance(other, LinearEntity): # break into cases based on whether # the lines are parallel, non-parallel intersecting, or skew pts = Point._normalize_dimension(self.p1, self.p2, other.p1, other.p2) rank = Point.affine_rank(*pts) if rank == 1: # we're collinear if isinstance(self, Line): return [other] if isinstance(other, Line): return [self] if isinstance(self, Ray) and isinstance(other, Ray): return intersect_parallel_rays(self, other) if isinstance(self, Ray) and isinstance(other, Segment): return intersect_parallel_ray_and_segment(self, other) if isinstance(self, Segment) and isinstance(other, Ray): return intersect_parallel_ray_and_segment(other, self) if isinstance(self, Segment) and isinstance(other, Segment): return intersect_parallel_segments(self, other) elif rank == 2: # we're in the same plane l1 = Line(*pts[:2]) l2 = Line(*pts[2:]) # check to see if we're parallel. If we are, we can't # be intersecting, since the collinear case was already # handled if l1.direction.is_scalar_multiple(l2.direction): return [] # find the intersection as if everything were lines # by solving the equation t*d + p1 == s*d' + p1' m = Matrix([l1.direction, -l2.direction]).transpose() v = Matrix([l2.p1 - l1.p1]).transpose() # we cannot use m.solve(v) because that only works for square matrices m_rref, pivots = m.col_insert(2, v).rref(simplify=True) # rank == 2 ensures we have 2 pivots, but let's check anyway if len(pivots) != 2: raise GeometryError("Failed when solving Mx=b when M={} and b={}".format(m, v)) coeff = m_rref[0, 2] line_intersection = l1.direction*coeff + self.p1 # if both are lines, skip a containment check if isinstance(self, Line) and isinstance(other, Line): return [line_intersection] if ((isinstance(self, Line) or self.contains(line_intersection)) and other.contains(line_intersection)): return [line_intersection] if not self.atoms(Float) and not other.atoms(Float): # if it can fail when there are no Floats then # maybe the following parametric check should be # done return [] # floats may fail exact containment so check that the # arbitrary points, when equal, both give a # non-negative parameter when the arbitrary point # coordinates are equated tu = solve(self.arbitrary_point(t) - other.arbitrary_point(u), t, u, dict=True)[0] def ok(p, l): if isinstance(l, Line): # p > -oo return True if isinstance(l, Ray): # p >= 0 return p.is_nonnegative if isinstance(l, Segment): # 0 <= p <= 1 return p.is_nonnegative and (1 - p).is_nonnegative raise ValueError("unexpected line type") if ok(tu[t], self) and ok(tu[u], other): return [line_intersection] return [] else: # we're skew return [] return other.intersection(self) def is_parallel(l1, l2): """Are two linear entities parallel? Parameters ========== l1 : LinearEntity l2 : LinearEntity Returns ======= True : if l1 and l2 are parallel, False : otherwise. See Also ======== coefficients Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(1, 1) >>> p3, p4 = Point(3, 4), Point(6, 7) >>> l1, l2 = Line(p1, p2), Line(p3, p4) >>> Line.is_parallel(l1, l2) True >>> p5 = Point(6, 6) >>> l3 = Line(p3, p5) >>> Line.is_parallel(l1, l3) False >>> from sympy import Point3D, Line3D >>> p1, p2 = Point3D(0, 0, 0), Point3D(3, 4, 5) >>> p3, p4 = Point3D(2, 1, 1), Point3D(8, 9, 11) >>> l1, l2 = Line3D(p1, p2), Line3D(p3, p4) >>> Line3D.is_parallel(l1, l2) True >>> p5 = Point3D(6, 6, 6) >>> l3 = Line3D(p3, p5) >>> Line3D.is_parallel(l1, l3) False """ if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity): raise TypeError('Must pass only LinearEntity objects') return l1.direction.is_scalar_multiple(l2.direction) def is_perpendicular(l1, l2): """Are two linear entities perpendicular? Parameters ========== l1 : LinearEntity l2 : LinearEntity Returns ======= True : if l1 and l2 are perpendicular, False : otherwise. See Also ======== coefficients Examples ======== >>> from sympy import Point, Line >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(-1, 1) >>> l1, l2 = Line(p1, p2), Line(p1, p3) >>> l1.is_perpendicular(l2) True >>> p4 = Point(5, 3) >>> l3 = Line(p1, p4) >>> l1.is_perpendicular(l3) False >>> from sympy import Point3D, Line3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(-1, 2, 0) >>> l1, l2 = Line3D(p1, p2), Line3D(p2, p3) >>> l1.is_perpendicular(l2) False >>> p4 = Point3D(5, 3, 7) >>> l3 = Line3D(p1, p4) >>> l1.is_perpendicular(l3) False """ if not isinstance(l1, LinearEntity) and not isinstance(l2, LinearEntity): raise TypeError('Must pass only LinearEntity objects') return S.Zero.equals(l1.direction.dot(l2.direction)) def is_similar(self, other): """ Return True if self and other are contained in the same line. Examples ======== >>> from sympy import Point, Line >>> p1, p2, p3 = Point(0, 1), Point(3, 4), Point(2, 3) >>> l1 = Line(p1, p2) >>> l2 = Line(p1, p3) >>> l1.is_similar(l2) True """ l = Line(self.p1, self.p2) return l.contains(other) @property def length(self): """ The length of the line. Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(3, 5) >>> l1 = Line(p1, p2) >>> l1.length oo """ return S.Infinity @property def p1(self): """The first defining point of a linear entity. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(5, 3) >>> l = Line(p1, p2) >>> l.p1 Point2D(0, 0) """ return self.args[0] @property def p2(self): """The second defining point of a linear entity. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(5, 3) >>> l = Line(p1, p2) >>> l.p2 Point2D(5, 3) """ return self.args[1] def parallel_line(self, p): """Create a new Line parallel to this linear entity which passes through the point `p`. Parameters ========== p : Point Returns ======= line : Line See Also ======== is_parallel Examples ======== >>> from sympy import Point, Line >>> p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2) >>> l1 = Line(p1, p2) >>> l2 = l1.parallel_line(p3) >>> p3 in l2 True >>> l1.is_parallel(l2) True >>> from sympy import Point3D, Line3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(2, 3, 4), Point3D(-2, 2, 0) >>> l1 = Line3D(p1, p2) >>> l2 = l1.parallel_line(p3) >>> p3 in l2 True >>> l1.is_parallel(l2) True """ p = Point(p, dim=self.ambient_dimension) return Line(p, p + self.direction) def perpendicular_line(self, p): """Create a new Line perpendicular to this linear entity which passes through the point `p`. Parameters ========== p : Point Returns ======= line : Line See Also ======== sympy.geometry.line.LinearEntity.is_perpendicular, perpendicular_segment Examples ======== >>> from sympy import Point3D, Line3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(2, 3, 4), Point3D(-2, 2, 0) >>> L = Line3D(p1, p2) >>> P = L.perpendicular_line(p3); P Line3D(Point3D(-2, 2, 0), Point3D(4/29, 6/29, 8/29)) >>> L.is_perpendicular(P) True In 3D the, the first point used to define the line is the point through which the perpendicular was required to pass; the second point is (arbitrarily) contained in the given line: >>> P.p2 in L True """ p = Point(p, dim=self.ambient_dimension) if p in self: p = p + self.direction.orthogonal_direction return Line(p, self.projection(p)) def perpendicular_segment(self, p): """Create a perpendicular line segment from `p` to this line. The endpoints of the segment are ``p`` and the closest point in the line containing self. (If self is not a line, the point might not be in self.) Parameters ========== p : Point Returns ======= segment : Segment Notes ===== Returns `p` itself if `p` is on this linear entity. See Also ======== perpendicular_line Examples ======== >>> from sympy import Point, Line >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, 2) >>> l1 = Line(p1, p2) >>> s1 = l1.perpendicular_segment(p3) >>> l1.is_perpendicular(s1) True >>> p3 in s1 True >>> l1.perpendicular_segment(Point(4, 0)) Segment2D(Point2D(4, 0), Point2D(2, 2)) >>> from sympy import Point3D, Line3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, 2, 0) >>> l1 = Line3D(p1, p2) >>> s1 = l1.perpendicular_segment(p3) >>> l1.is_perpendicular(s1) True >>> p3 in s1 True >>> l1.perpendicular_segment(Point3D(4, 0, 0)) Segment3D(Point3D(4, 0, 0), Point3D(4/3, 4/3, 4/3)) """ p = Point(p, dim=self.ambient_dimension) if p in self: return p l = self.perpendicular_line(p) # The intersection should be unique, so unpack the singleton p2, = Intersection(Line(self.p1, self.p2), l) return Segment(p, p2) @property def points(self): """The two points used to define this linear entity. Returns ======= points : tuple of Points See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(5, 11) >>> l1 = Line(p1, p2) >>> l1.points (Point2D(0, 0), Point2D(5, 11)) """ return (self.p1, self.p2) def projection(self, other): """Project a point, line, ray, or segment onto this linear entity. Parameters ========== other : Point or LinearEntity (Line, Ray, Segment) Returns ======= projection : Point or LinearEntity (Line, Ray, Segment) The return type matches the type of the parameter ``other``. Raises ====== GeometryError When method is unable to perform projection. Notes ===== A projection involves taking the two points that define the linear entity and projecting those points onto a Line and then reforming the linear entity using these projections. A point P is projected onto a line L by finding the point on L that is closest to P. This point is the intersection of L and the line perpendicular to L that passes through P. See Also ======== sympy.geometry.point.Point, perpendicular_line Examples ======== >>> from sympy import Point, Line, Segment, Rational >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(Rational(1, 2), 0) >>> l1 = Line(p1, p2) >>> l1.projection(p3) Point2D(1/4, 1/4) >>> p4, p5 = Point(10, 0), Point(12, 1) >>> s1 = Segment(p4, p5) >>> l1.projection(s1) Segment2D(Point2D(5, 5), Point2D(13/2, 13/2)) >>> p1, p2, p3 = Point(0, 0, 1), Point(1, 1, 2), Point(2, 0, 1) >>> l1 = Line(p1, p2) >>> l1.projection(p3) Point3D(2/3, 2/3, 5/3) >>> p4, p5 = Point(10, 0, 1), Point(12, 1, 3) >>> s1 = Segment(p4, p5) >>> l1.projection(s1) Segment3D(Point3D(10/3, 10/3, 13/3), Point3D(5, 5, 6)) """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) def proj_point(p): return Point.project(p - self.p1, self.direction) + self.p1 if isinstance(other, Point): return proj_point(other) elif isinstance(other, LinearEntity): p1, p2 = proj_point(other.p1), proj_point(other.p2) # test to see if we're degenerate if p1 == p2: return p1 projected = other.__class__(p1, p2) projected = Intersection(self, projected) if projected.is_empty: return projected # if we happen to have intersected in only a point, return that if projected.is_FiniteSet and len(projected) == 1: # projected is a set of size 1, so unpack it in `a` a, = projected return a # order args so projection is in the same direction as self if self.direction.dot(projected.direction) < 0: p1, p2 = projected.args projected = projected.func(p2, p1) return projected raise GeometryError( "Do not know how to project %s onto %s" % (other, self)) def random_point(self, seed=None): """A random point on a LinearEntity. Returns ======= point : Point See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Line, Ray, Segment >>> p1, p2 = Point(0, 0), Point(5, 3) >>> line = Line(p1, p2) >>> r = line.random_point(seed=42) # seed value is optional >>> r.n(3) Point2D(-0.72, -0.432) >>> r in line True >>> Ray(p1, p2).random_point(seed=42).n(3) Point2D(0.72, 0.432) >>> Segment(p1, p2).random_point(seed=42).n(3) Point2D(3.2, 1.92) """ if seed is not None: rng = random.Random(seed) else: rng = random pt = self.arbitrary_point(t) if isinstance(self, Ray): v = abs(rng.gauss(0, 1)) elif isinstance(self, Segment): v = rng.random() elif isinstance(self, Line): v = rng.gauss(0, 1) else: raise NotImplementedError('unhandled line type') return pt.subs(t, Rational(v)) def bisectors(self, other): """Returns the perpendicular lines which pass through the intersections of self and other that are in the same plane. Parameters ========== line : Line3D Returns ======= list: two Line instances Examples ======== >>> from sympy import Point3D, Line3D >>> r1 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)) >>> r2 = Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0)) >>> r1.bisectors(r2) [Line3D(Point3D(0, 0, 0), Point3D(1, 1, 0)), Line3D(Point3D(0, 0, 0), Point3D(1, -1, 0))] """ if not isinstance(other, LinearEntity): raise GeometryError("Expecting LinearEntity, not %s" % other) l1, l2 = self, other # make sure dimensions match or else a warning will rise from # intersection calculation if l1.p1.ambient_dimension != l2.p1.ambient_dimension: if isinstance(l1, Line2D): l1, l2 = l2, l1 _, p1 = Point._normalize_dimension(l1.p1, l2.p1, on_morph='ignore') _, p2 = Point._normalize_dimension(l1.p2, l2.p2, on_morph='ignore') l2 = Line(p1, p2) point = intersection(l1, l2) # Three cases: Lines may intersect in a point, may be equal or may not intersect. if not point: raise GeometryError("The lines do not intersect") else: pt = point[0] if isinstance(pt, Line): # Intersection is a line because both lines are coincident return [self] d1 = l1.direction.unit d2 = l2.direction.unit bis1 = Line(pt, pt + d1 + d2) bis2 = Line(pt, pt + d1 - d2) return [bis1, bis2] class Line(LinearEntity): """An infinite line in space. A 2D line is declared with two distinct points, point and slope, or an equation. A 3D line may be defined with a point and a direction ratio. Parameters ========== p1 : Point p2 : Point slope : SymPy expression direction_ratio : list equation : equation of a line Notes ===== `Line` will automatically subclass to `Line2D` or `Line3D` based on the dimension of `p1`. The `slope` argument is only relevant for `Line2D` and the `direction_ratio` argument is only relevant for `Line3D`. The order of the points will define the direction of the line which is used when calculating the angle between lines. See Also ======== sympy.geometry.point.Point sympy.geometry.line.Line2D sympy.geometry.line.Line3D Examples ======== >>> from sympy import Line, Segment, Point, Eq >>> from sympy.abc import x, y, a, b >>> L = Line(Point(2,3), Point(3,5)) >>> L Line2D(Point2D(2, 3), Point2D(3, 5)) >>> L.points (Point2D(2, 3), Point2D(3, 5)) >>> L.equation() -2*x + y + 1 >>> L.coefficients (-2, 1, 1) Instantiate with keyword ``slope``: >>> Line(Point(0, 0), slope=0) Line2D(Point2D(0, 0), Point2D(1, 0)) Instantiate with another linear object >>> s = Segment((0, 0), (0, 1)) >>> Line(s).equation() x The line corresponding to an equation in the for `ax + by + c = 0`, can be entered: >>> Line(3*x + y + 18) Line2D(Point2D(0, -18), Point2D(1, -21)) If `x` or `y` has a different name, then they can be specified, too, as a string (to match the name) or symbol: >>> Line(Eq(3*a + b, -18), x='a', y=b) Line2D(Point2D(0, -18), Point2D(1, -21)) """ def __new__(cls, *args, **kwargs): if len(args) == 1 and isinstance(args[0], (Expr, Eq)): missing = uniquely_named_symbol('?', args) if not kwargs: x = 'x' y = 'y' else: x = kwargs.pop('x', missing) y = kwargs.pop('y', missing) if kwargs: raise ValueError('expecting only x and y as keywords') equation = args[0] if isinstance(equation, Eq): equation = equation.lhs - equation.rhs def find_or_missing(x): try: return find(x, equation) except ValueError: return missing x = find_or_missing(x) y = find_or_missing(y) a, b, c = linear_coeffs(equation, x, y) if b: return Line((0, -c/b), slope=-a/b) if a: return Line((-c/a, 0), slope=oo) raise ValueError('not found in equation: %s' % (set('xy') - {x, y})) else: if len(args) > 0: p1 = args[0] if len(args) > 1: p2 = args[1] else: p2 = None if isinstance(p1, LinearEntity): if p2: raise ValueError('If p1 is a LinearEntity, p2 must be None.') dim = len(p1.p1) else: p1 = Point(p1) dim = len(p1) if p2 is not None or isinstance(p2, Point) and p2.ambient_dimension != dim: p2 = Point(p2) if dim == 2: return Line2D(p1, p2, **kwargs) elif dim == 3: return Line3D(p1, p2, **kwargs) return LinearEntity.__new__(cls, p1, p2, **kwargs) def contains(self, other): """ Return True if `other` is on this Line, or False otherwise. Examples ======== >>> from sympy import Line,Point >>> p1, p2 = Point(0, 1), Point(3, 4) >>> l = Line(p1, p2) >>> l.contains(p1) True >>> l.contains((0, 1)) True >>> l.contains((0, 0)) False >>> a = (0, 0, 0) >>> b = (1, 1, 1) >>> c = (2, 2, 2) >>> l1 = Line(a, b) >>> l2 = Line(b, a) >>> l1 == l2 False >>> l1 in l2 True """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if isinstance(other, Point): return Point.is_collinear(other, self.p1, self.p2) if isinstance(other, LinearEntity): return Point.is_collinear(self.p1, self.p2, other.p1, other.p2) return False def distance(self, other): """ Finds the shortest distance between a line and a point. Raises ====== NotImplementedError is raised if `other` is not a Point Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(1, 1) >>> s = Line(p1, p2) >>> s.distance(Point(-1, 1)) sqrt(2) >>> s.distance((-1, 2)) 3*sqrt(2)/2 >>> p1, p2 = Point(0, 0, 0), Point(1, 1, 1) >>> s = Line(p1, p2) >>> s.distance(Point(-1, 1, 1)) 2*sqrt(6)/3 >>> s.distance((-1, 1, 1)) 2*sqrt(6)/3 """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if self.contains(other): return S.Zero return self.perpendicular_segment(other).length def equals(self, other): """Returns True if self and other are the same mathematical entities""" if not isinstance(other, Line): return False return Point.is_collinear(self.p1, other.p1, self.p2, other.p2) def plot_interval(self, parameter='t'): """The plot interval for the default geometric plot of line. Gives values that will produce a line that is +/- 5 units long (where a unit is the distance between the two points that define the line). Parameters ========== parameter : str, optional Default value is 't'. Returns ======= plot_interval : list (plot interval) [parameter, lower_bound, upper_bound] Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(5, 3) >>> l1 = Line(p1, p2) >>> l1.plot_interval() [t, -5, 5] """ t = _symbol(parameter, real=True) return [t, -5, 5] class Ray(LinearEntity): """A Ray is a semi-line in the space with a source point and a direction. Parameters ========== p1 : Point The source of the Ray p2 : Point or radian value This point determines the direction in which the Ray propagates. If given as an angle it is interpreted in radians with the positive direction being ccw. Attributes ========== source See Also ======== sympy.geometry.line.Ray2D sympy.geometry.line.Ray3D sympy.geometry.point.Point sympy.geometry.line.Line Notes ===== `Ray` will automatically subclass to `Ray2D` or `Ray3D` based on the dimension of `p1`. Examples ======== >>> from sympy import Ray, Point, pi >>> r = Ray(Point(2, 3), Point(3, 5)) >>> r Ray2D(Point2D(2, 3), Point2D(3, 5)) >>> r.points (Point2D(2, 3), Point2D(3, 5)) >>> r.source Point2D(2, 3) >>> r.xdirection oo >>> r.ydirection oo >>> r.slope 2 >>> Ray(Point(0, 0), angle=pi/4).slope 1 """ def __new__(cls, p1, p2=None, **kwargs): p1 = Point(p1) if p2 is not None: p1, p2 = Point._normalize_dimension(p1, Point(p2)) dim = len(p1) if dim == 2: return Ray2D(p1, p2, **kwargs) elif dim == 3: return Ray3D(p1, p2, **kwargs) return LinearEntity.__new__(cls, p1, p2, **kwargs) def _svg(self, scale_factor=1., fill_color="#66cc99"): """Returns SVG path element for the LinearEntity. Parameters ========== scale_factor : float Multiplication factor for the SVG stroke-width. Default is 1. fill_color : str, optional Hex string for fill color. Default is "#66cc99". """ verts = (N(self.p1), N(self.p2)) coords = ["{},{}".format(p.x, p.y) for p in verts] path = "M {} L {}".format(coords[0], " L ".join(coords[1:])) return ( '<path fill-rule="evenodd" fill="{2}" stroke="#555555" ' 'stroke-width="{0}" opacity="0.6" d="{1}" ' 'marker-start="url(#markerCircle)" marker-end="url(#markerArrow)"/>' ).format(2.*scale_factor, path, fill_color) def contains(self, other): """ Is other GeometryEntity contained in this Ray? Examples ======== >>> from sympy import Ray,Point,Segment >>> p1, p2 = Point(0, 0), Point(4, 4) >>> r = Ray(p1, p2) >>> r.contains(p1) True >>> r.contains((1, 1)) True >>> r.contains((1, 3)) False >>> s = Segment((1, 1), (2, 2)) >>> r.contains(s) True >>> s = Segment((1, 2), (2, 5)) >>> r.contains(s) False >>> r1 = Ray((2, 2), (3, 3)) >>> r.contains(r1) True >>> r1 = Ray((2, 2), (3, 5)) >>> r.contains(r1) False """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if isinstance(other, Point): if Point.is_collinear(self.p1, self.p2, other): # if we're in the direction of the ray, our # direction vector dot the ray's direction vector # should be non-negative return bool((self.p2 - self.p1).dot(other - self.p1) >= S.Zero) return False elif isinstance(other, Ray): if Point.is_collinear(self.p1, self.p2, other.p1, other.p2): return bool((self.p2 - self.p1).dot(other.p2 - other.p1) > S.Zero) return False elif isinstance(other, Segment): return other.p1 in self and other.p2 in self # No other known entity can be contained in a Ray return False def distance(self, other): """ Finds the shortest distance between the ray and a point. Raises ====== NotImplementedError is raised if `other` is not a Point Examples ======== >>> from sympy import Point, Ray >>> p1, p2 = Point(0, 0), Point(1, 1) >>> s = Ray(p1, p2) >>> s.distance(Point(-1, -1)) sqrt(2) >>> s.distance((-1, 2)) 3*sqrt(2)/2 >>> p1, p2 = Point(0, 0, 0), Point(1, 1, 2) >>> s = Ray(p1, p2) >>> s Ray3D(Point3D(0, 0, 0), Point3D(1, 1, 2)) >>> s.distance(Point(-1, -1, 2)) 4*sqrt(3)/3 >>> s.distance((-1, -1, 2)) 4*sqrt(3)/3 """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if self.contains(other): return S.Zero proj = Line(self.p1, self.p2).projection(other) if self.contains(proj): return abs(other - proj) else: return abs(other - self.source) def equals(self, other): """Returns True if self and other are the same mathematical entities""" if not isinstance(other, Ray): return False return self.source == other.source and other.p2 in self def plot_interval(self, parameter='t'): """The plot interval for the default geometric plot of the Ray. Gives values that will produce a ray that is 10 units long (where a unit is the distance between the two points that define the ray). Parameters ========== parameter : str, optional Default value is 't'. Returns ======= plot_interval : list [parameter, lower_bound, upper_bound] Examples ======== >>> from sympy import Ray, pi >>> r = Ray((0, 0), angle=pi/4) >>> r.plot_interval() [t, 0, 10] """ t = _symbol(parameter, real=True) return [t, 0, 10] @property def source(self): """The point from which the ray emanates. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Ray >>> p1, p2 = Point(0, 0), Point(4, 1) >>> r1 = Ray(p1, p2) >>> r1.source Point2D(0, 0) >>> p1, p2 = Point(0, 0, 0), Point(4, 1, 5) >>> r1 = Ray(p2, p1) >>> r1.source Point3D(4, 1, 5) """ return self.p1 class Segment(LinearEntity): """A line segment in space. Parameters ========== p1 : Point p2 : Point Attributes ========== length : number or SymPy expression midpoint : Point See Also ======== sympy.geometry.line.Segment2D sympy.geometry.line.Segment3D sympy.geometry.point.Point sympy.geometry.line.Line Notes ===== If 2D or 3D points are used to define `Segment`, it will be automatically subclassed to `Segment2D` or `Segment3D`. Examples ======== >>> from sympy import Point, Segment >>> Segment((1, 0), (1, 1)) # tuples are interpreted as pts Segment2D(Point2D(1, 0), Point2D(1, 1)) >>> s = Segment(Point(4, 3), Point(1, 1)) >>> s.points (Point2D(4, 3), Point2D(1, 1)) >>> s.slope 2/3 >>> s.length sqrt(13) >>> s.midpoint Point2D(5/2, 2) >>> Segment((1, 0, 0), (1, 1, 1)) # tuples are interpreted as pts Segment3D(Point3D(1, 0, 0), Point3D(1, 1, 1)) >>> s = Segment(Point(4, 3, 9), Point(1, 1, 7)); s Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7)) >>> s.points (Point3D(4, 3, 9), Point3D(1, 1, 7)) >>> s.length sqrt(17) >>> s.midpoint Point3D(5/2, 2, 8) """ def __new__(cls, p1, p2, **kwargs): p1, p2 = Point._normalize_dimension(Point(p1), Point(p2)) dim = len(p1) if dim == 2: return Segment2D(p1, p2, **kwargs) elif dim == 3: return Segment3D(p1, p2, **kwargs) return LinearEntity.__new__(cls, p1, p2, **kwargs) def contains(self, other): """ Is the other GeometryEntity contained within this Segment? Examples ======== >>> from sympy import Point, Segment >>> p1, p2 = Point(0, 1), Point(3, 4) >>> s = Segment(p1, p2) >>> s2 = Segment(p2, p1) >>> s.contains(s2) True >>> from sympy import Point3D, Segment3D >>> p1, p2 = Point3D(0, 1, 1), Point3D(3, 4, 5) >>> s = Segment3D(p1, p2) >>> s2 = Segment3D(p2, p1) >>> s.contains(s2) True >>> s.contains((p1 + p2)/2) True """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if isinstance(other, Point): if Point.is_collinear(other, self.p1, self.p2): if isinstance(self, Segment2D): # if it is collinear and is in the bounding box of the # segment then it must be on the segment vert = (1/self.slope).equals(0) if vert is False: isin = (self.p1.x - other.x)*(self.p2.x - other.x) <= 0 if isin in (True, False): return isin if vert is True: isin = (self.p1.y - other.y)*(self.p2.y - other.y) <= 0 if isin in (True, False): return isin # use the triangle inequality d1, d2 = other - self.p1, other - self.p2 d = self.p2 - self.p1 # without the call to simplify, SymPy cannot tell that an expression # like (a+b)*(a/2+b/2) is always non-negative. If it cannot be # determined, raise an Undecidable error try: # the triangle inequality says that |d1|+|d2| >= |d| and is strict # only if other lies in the line segment return bool(simplify(Eq(abs(d1) + abs(d2) - abs(d), 0))) except TypeError: raise Undecidable("Cannot determine if {} is in {}".format(other, self)) if isinstance(other, Segment): return other.p1 in self and other.p2 in self return False def equals(self, other): """Returns True if self and other are the same mathematical entities""" return isinstance(other, self.func) and list( ordered(self.args)) == list(ordered(other.args)) def distance(self, other): """ Finds the shortest distance between a line segment and a point. Raises ====== NotImplementedError is raised if `other` is not a Point Examples ======== >>> from sympy import Point, Segment >>> p1, p2 = Point(0, 1), Point(3, 4) >>> s = Segment(p1, p2) >>> s.distance(Point(10, 15)) sqrt(170) >>> s.distance((0, 12)) sqrt(73) >>> from sympy import Point3D, Segment3D >>> p1, p2 = Point3D(0, 0, 3), Point3D(1, 1, 4) >>> s = Segment3D(p1, p2) >>> s.distance(Point3D(10, 15, 12)) sqrt(341) >>> s.distance((10, 15, 12)) sqrt(341) """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if isinstance(other, Point): vp1 = other - self.p1 vp2 = other - self.p2 dot_prod_sign_1 = self.direction.dot(vp1) >= 0 dot_prod_sign_2 = self.direction.dot(vp2) <= 0 if dot_prod_sign_1 and dot_prod_sign_2: return Line(self.p1, self.p2).distance(other) if dot_prod_sign_1 and not dot_prod_sign_2: return abs(vp2) if not dot_prod_sign_1 and dot_prod_sign_2: return abs(vp1) raise NotImplementedError() @property def length(self): """The length of the line segment. See Also ======== sympy.geometry.point.Point.distance Examples ======== >>> from sympy import Point, Segment >>> p1, p2 = Point(0, 0), Point(4, 3) >>> s1 = Segment(p1, p2) >>> s1.length 5 >>> from sympy import Point3D, Segment3D >>> p1, p2 = Point3D(0, 0, 0), Point3D(4, 3, 3) >>> s1 = Segment3D(p1, p2) >>> s1.length sqrt(34) """ return Point.distance(self.p1, self.p2) @property def midpoint(self): """The midpoint of the line segment. See Also ======== sympy.geometry.point.Point.midpoint Examples ======== >>> from sympy import Point, Segment >>> p1, p2 = Point(0, 0), Point(4, 3) >>> s1 = Segment(p1, p2) >>> s1.midpoint Point2D(2, 3/2) >>> from sympy import Point3D, Segment3D >>> p1, p2 = Point3D(0, 0, 0), Point3D(4, 3, 3) >>> s1 = Segment3D(p1, p2) >>> s1.midpoint Point3D(2, 3/2, 3/2) """ return Point.midpoint(self.p1, self.p2) def perpendicular_bisector(self, p=None): """The perpendicular bisector of this segment. If no point is specified or the point specified is not on the bisector then the bisector is returned as a Line. Otherwise a Segment is returned that joins the point specified and the intersection of the bisector and the segment. Parameters ========== p : Point Returns ======= bisector : Line or Segment See Also ======== LinearEntity.perpendicular_segment Examples ======== >>> from sympy import Point, Segment >>> p1, p2, p3 = Point(0, 0), Point(6, 6), Point(5, 1) >>> s1 = Segment(p1, p2) >>> s1.perpendicular_bisector() Line2D(Point2D(3, 3), Point2D(-3, 9)) >>> s1.perpendicular_bisector(p3) Segment2D(Point2D(5, 1), Point2D(3, 3)) """ l = self.perpendicular_line(self.midpoint) if p is not None: p2 = Point(p, dim=self.ambient_dimension) if p2 in l: return Segment(p2, self.midpoint) return l def plot_interval(self, parameter='t'): """The plot interval for the default geometric plot of the Segment gives values that will produce the full segment in a plot. Parameters ========== parameter : str, optional Default value is 't'. Returns ======= plot_interval : list [parameter, lower_bound, upper_bound] Examples ======== >>> from sympy import Point, Segment >>> p1, p2 = Point(0, 0), Point(5, 3) >>> s1 = Segment(p1, p2) >>> s1.plot_interval() [t, 0, 1] """ t = _symbol(parameter, real=True) return [t, 0, 1] class LinearEntity2D(LinearEntity): """A base class for all linear entities (line, ray and segment) in a 2-dimensional Euclidean space. Attributes ========== p1 p2 coefficients slope points Notes ===== This is an abstract class and is not meant to be instantiated. See Also ======== sympy.geometry.entity.GeometryEntity """ @property def bounds(self): """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding rectangle for the geometric figure. """ verts = self.points xs = [p.x for p in verts] ys = [p.y for p in verts] return (min(xs), min(ys), max(xs), max(ys)) def perpendicular_line(self, p): """Create a new Line perpendicular to this linear entity which passes through the point `p`. Parameters ========== p : Point Returns ======= line : Line See Also ======== sympy.geometry.line.LinearEntity.is_perpendicular, perpendicular_segment Examples ======== >>> from sympy import Point, Line >>> p1, p2, p3 = Point(0, 0), Point(2, 3), Point(-2, 2) >>> L = Line(p1, p2) >>> P = L.perpendicular_line(p3); P Line2D(Point2D(-2, 2), Point2D(-5, 4)) >>> L.is_perpendicular(P) True In 2D, the first point of the perpendicular line is the point through which was required to pass; the second point is arbitrarily chosen. To get a line that explicitly uses a point in the line, create a line from the perpendicular segment from the line to the point: >>> Line(L.perpendicular_segment(p3)) Line2D(Point2D(-2, 2), Point2D(4/13, 6/13)) """ p = Point(p, dim=self.ambient_dimension) # any two lines in R^2 intersect, so blindly making # a line through p in an orthogonal direction will work # and is faster than finding the projection point as in 3D return Line(p, p + self.direction.orthogonal_direction) @property def slope(self): """The slope of this linear entity, or infinity if vertical. Returns ======= slope : number or SymPy expression See Also ======== coefficients Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(3, 5) >>> l1 = Line(p1, p2) >>> l1.slope 5/3 >>> p3 = Point(0, 4) >>> l2 = Line(p1, p3) >>> l2.slope oo """ d1, d2 = (self.p1 - self.p2).args if d1 == 0: return S.Infinity return simplify(d2/d1) class Line2D(LinearEntity2D, Line): """An infinite line in space 2D. A line is declared with two distinct points or a point and slope as defined using keyword `slope`. Parameters ========== p1 : Point pt : Point slope : SymPy expression See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Line, Segment, Point >>> L = Line(Point(2,3), Point(3,5)) >>> L Line2D(Point2D(2, 3), Point2D(3, 5)) >>> L.points (Point2D(2, 3), Point2D(3, 5)) >>> L.equation() -2*x + y + 1 >>> L.coefficients (-2, 1, 1) Instantiate with keyword ``slope``: >>> Line(Point(0, 0), slope=0) Line2D(Point2D(0, 0), Point2D(1, 0)) Instantiate with another linear object >>> s = Segment((0, 0), (0, 1)) >>> Line(s).equation() x """ def __new__(cls, p1, pt=None, slope=None, **kwargs): if isinstance(p1, LinearEntity): if pt is not None: raise ValueError('When p1 is a LinearEntity, pt should be None') p1, pt = Point._normalize_dimension(*p1.args, dim=2) else: p1 = Point(p1, dim=2) if pt is not None and slope is None: try: p2 = Point(pt, dim=2) except (NotImplementedError, TypeError, ValueError): raise ValueError(filldedent(''' The 2nd argument was not a valid Point. If it was a slope, enter it with keyword "slope". ''')) elif slope is not None and pt is None: slope = sympify(slope) if slope.is_finite is False: # when infinite slope, don't change x dx = 0 dy = 1 else: # go over 1 up slope dx = 1 dy = slope # XXX avoiding simplification by adding to coords directly p2 = Point(p1.x + dx, p1.y + dy, evaluate=False) else: raise ValueError('A 2nd Point or keyword "slope" must be used.') return LinearEntity2D.__new__(cls, p1, p2, **kwargs) def _svg(self, scale_factor=1., fill_color="#66cc99"): """Returns SVG path element for the LinearEntity. Parameters ========== scale_factor : float Multiplication factor for the SVG stroke-width. Default is 1. fill_color : str, optional Hex string for fill color. Default is "#66cc99". """ verts = (N(self.p1), N(self.p2)) coords = ["{},{}".format(p.x, p.y) for p in verts] path = "M {} L {}".format(coords[0], " L ".join(coords[1:])) return ( '<path fill-rule="evenodd" fill="{2}" stroke="#555555" ' 'stroke-width="{0}" opacity="0.6" d="{1}" ' 'marker-start="url(#markerReverseArrow)" marker-end="url(#markerArrow)"/>' ).format(2.*scale_factor, path, fill_color) @property def coefficients(self): """The coefficients (`a`, `b`, `c`) for `ax + by + c = 0`. See Also ======== sympy.geometry.line.Line2D.equation Examples ======== >>> from sympy import Point, Line >>> from sympy.abc import x, y >>> p1, p2 = Point(0, 0), Point(5, 3) >>> l = Line(p1, p2) >>> l.coefficients (-3, 5, 0) >>> p3 = Point(x, y) >>> l2 = Line(p1, p3) >>> l2.coefficients (-y, x, 0) """ p1, p2 = self.points if p1.x == p2.x: return (S.One, S.Zero, -p1.x) elif p1.y == p2.y: return (S.Zero, S.One, -p1.y) return tuple([simplify(i) for i in (self.p1.y - self.p2.y, self.p2.x - self.p1.x, self.p1.x*self.p2.y - self.p1.y*self.p2.x)]) def equation(self, x='x', y='y'): """The equation of the line: ax + by + c. Parameters ========== x : str, optional The name to use for the x-axis, default value is 'x'. y : str, optional The name to use for the y-axis, default value is 'y'. Returns ======= equation : SymPy expression See Also ======== sympy.geometry.line.Line2D.coefficients Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(1, 0), Point(5, 3) >>> l1 = Line(p1, p2) >>> l1.equation() -3*x + 4*y + 3 """ x = _symbol(x, real=True) y = _symbol(y, real=True) p1, p2 = self.points if p1.x == p2.x: return x - p1.x elif p1.y == p2.y: return y - p1.y a, b, c = self.coefficients return a*x + b*y + c class Ray2D(LinearEntity2D, Ray): """ A Ray is a semi-line in the space with a source point and a direction. Parameters ========== p1 : Point The source of the Ray p2 : Point or radian value This point determines the direction in which the Ray propagates. If given as an angle it is interpreted in radians with the positive direction being ccw. Attributes ========== source xdirection ydirection See Also ======== sympy.geometry.point.Point, Line Examples ======== >>> from sympy import Point, pi, Ray >>> r = Ray(Point(2, 3), Point(3, 5)) >>> r Ray2D(Point2D(2, 3), Point2D(3, 5)) >>> r.points (Point2D(2, 3), Point2D(3, 5)) >>> r.source Point2D(2, 3) >>> r.xdirection oo >>> r.ydirection oo >>> r.slope 2 >>> Ray(Point(0, 0), angle=pi/4).slope 1 """ def __new__(cls, p1, pt=None, angle=None, **kwargs): p1 = Point(p1, dim=2) if pt is not None and angle is None: try: p2 = Point(pt, dim=2) except (NotImplementedError, TypeError, ValueError): raise ValueError(filldedent(''' The 2nd argument was not a valid Point; if it was meant to be an angle it should be given with keyword "angle".''')) if p1 == p2: raise ValueError('A Ray requires two distinct points.') elif angle is not None and pt is None: # we need to know if the angle is an odd multiple of pi/2 angle = sympify(angle) c = _pi_coeff(angle) p2 = None if c is not None: if c.is_Rational: if c.q == 2: if c.p == 1: p2 = p1 + Point(0, 1) elif c.p == 3: p2 = p1 + Point(0, -1) elif c.q == 1: if c.p == 0: p2 = p1 + Point(1, 0) elif c.p == 1: p2 = p1 + Point(-1, 0) if p2 is None: c *= S.Pi else: c = angle % (2*S.Pi) if not p2: m = 2*c/S.Pi left = And(1 < m, m < 3) # is it in quadrant 2 or 3? x = Piecewise((-1, left), (Piecewise((0, Eq(m % 1, 0)), (1, True)), True)) y = Piecewise((-tan(c), left), (Piecewise((1, Eq(m, 1)), (-1, Eq(m, 3)), (tan(c), True)), True)) p2 = p1 + Point(x, y) else: raise ValueError('A 2nd point or keyword "angle" must be used.') return LinearEntity2D.__new__(cls, p1, p2, **kwargs) @property def xdirection(self): """The x direction of the ray. Positive infinity if the ray points in the positive x direction, negative infinity if the ray points in the negative x direction, or 0 if the ray is vertical. See Also ======== ydirection Examples ======== >>> from sympy import Point, Ray >>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(0, -1) >>> r1, r2 = Ray(p1, p2), Ray(p1, p3) >>> r1.xdirection oo >>> r2.xdirection 0 """ if self.p1.x < self.p2.x: return S.Infinity elif self.p1.x == self.p2.x: return S.Zero else: return S.NegativeInfinity @property def ydirection(self): """The y direction of the ray. Positive infinity if the ray points in the positive y direction, negative infinity if the ray points in the negative y direction, or 0 if the ray is horizontal. See Also ======== xdirection Examples ======== >>> from sympy import Point, Ray >>> p1, p2, p3 = Point(0, 0), Point(-1, -1), Point(-1, 0) >>> r1, r2 = Ray(p1, p2), Ray(p1, p3) >>> r1.ydirection -oo >>> r2.ydirection 0 """ if self.p1.y < self.p2.y: return S.Infinity elif self.p1.y == self.p2.y: return S.Zero else: return S.NegativeInfinity def closing_angle(r1, r2): """Return the angle by which r2 must be rotated so it faces the same direction as r1. Parameters ========== r1 : Ray2D r2 : Ray2D Returns ======= angle : angle in radians (ccw angle is positive) See Also ======== LinearEntity.angle_between Examples ======== >>> from sympy import Ray, pi >>> r1 = Ray((0, 0), (1, 0)) >>> r2 = r1.rotate(-pi/2) >>> angle = r1.closing_angle(r2); angle pi/2 >>> r2.rotate(angle).direction.unit == r1.direction.unit True >>> r2.closing_angle(r1) -pi/2 """ if not all(isinstance(r, Ray2D) for r in (r1, r2)): # although the direction property is defined for # all linear entities, only the Ray is truly a # directed object raise TypeError('Both arguments must be Ray2D objects.') a1 = atan2(*list(reversed(r1.direction.args))) a2 = atan2(*list(reversed(r2.direction.args))) if a1*a2 < 0: a1 = 2*S.Pi + a1 if a1 < 0 else a1 a2 = 2*S.Pi + a2 if a2 < 0 else a2 return a1 - a2 class Segment2D(LinearEntity2D, Segment): """A line segment in 2D space. Parameters ========== p1 : Point p2 : Point Attributes ========== length : number or SymPy expression midpoint : Point See Also ======== sympy.geometry.point.Point, Line Examples ======== >>> from sympy import Point, Segment >>> Segment((1, 0), (1, 1)) # tuples are interpreted as pts Segment2D(Point2D(1, 0), Point2D(1, 1)) >>> s = Segment(Point(4, 3), Point(1, 1)); s Segment2D(Point2D(4, 3), Point2D(1, 1)) >>> s.points (Point2D(4, 3), Point2D(1, 1)) >>> s.slope 2/3 >>> s.length sqrt(13) >>> s.midpoint Point2D(5/2, 2) """ def __new__(cls, p1, p2, **kwargs): p1 = Point(p1, dim=2) p2 = Point(p2, dim=2) if p1 == p2: return p1 return LinearEntity2D.__new__(cls, p1, p2, **kwargs) def _svg(self, scale_factor=1., fill_color="#66cc99"): """Returns SVG path element for the LinearEntity. Parameters ========== scale_factor : float Multiplication factor for the SVG stroke-width. Default is 1. fill_color : str, optional Hex string for fill color. Default is "#66cc99". """ verts = (N(self.p1), N(self.p2)) coords = ["{},{}".format(p.x, p.y) for p in verts] path = "M {} L {}".format(coords[0], " L ".join(coords[1:])) return ( '<path fill-rule="evenodd" fill="{2}" stroke="#555555" ' 'stroke-width="{0}" opacity="0.6" d="{1}" />' ).format(2.*scale_factor, path, fill_color) class LinearEntity3D(LinearEntity): """An base class for all linear entities (line, ray and segment) in a 3-dimensional Euclidean space. Attributes ========== p1 p2 direction_ratio direction_cosine points Notes ===== This is a base class and is not meant to be instantiated. """ def __new__(cls, p1, p2, **kwargs): p1 = Point3D(p1, dim=3) p2 = Point3D(p2, dim=3) if p1 == p2: # if it makes sense to return a Point, handle in subclass raise ValueError( "%s.__new__ requires two unique Points." % cls.__name__) return GeometryEntity.__new__(cls, p1, p2, **kwargs) ambient_dimension = 3 @property def direction_ratio(self): """The direction ratio of a given line in 3D. See Also ======== sympy.geometry.line.Line3D.equation Examples ======== >>> from sympy import Point3D, Line3D >>> p1, p2 = Point3D(0, 0, 0), Point3D(5, 3, 1) >>> l = Line3D(p1, p2) >>> l.direction_ratio [5, 3, 1] """ p1, p2 = self.points return p1.direction_ratio(p2) @property def direction_cosine(self): """The normalized direction ratio of a given line in 3D. See Also ======== sympy.geometry.line.Line3D.equation Examples ======== >>> from sympy import Point3D, Line3D >>> p1, p2 = Point3D(0, 0, 0), Point3D(5, 3, 1) >>> l = Line3D(p1, p2) >>> l.direction_cosine [sqrt(35)/7, 3*sqrt(35)/35, sqrt(35)/35] >>> sum(i**2 for i in _) 1 """ p1, p2 = self.points return p1.direction_cosine(p2) class Line3D(LinearEntity3D, Line): """An infinite 3D line in space. A line is declared with two distinct points or a point and direction_ratio as defined using keyword `direction_ratio`. Parameters ========== p1 : Point3D pt : Point3D direction_ratio : list See Also ======== sympy.geometry.point.Point3D sympy.geometry.line.Line sympy.geometry.line.Line2D Examples ======== >>> from sympy import Line3D, Point3D >>> L = Line3D(Point3D(2, 3, 4), Point3D(3, 5, 1)) >>> L Line3D(Point3D(2, 3, 4), Point3D(3, 5, 1)) >>> L.points (Point3D(2, 3, 4), Point3D(3, 5, 1)) """ def __new__(cls, p1, pt=None, direction_ratio=(), **kwargs): if isinstance(p1, LinearEntity3D): if pt is not None: raise ValueError('if p1 is a LinearEntity, pt must be None.') p1, pt = p1.args else: p1 = Point(p1, dim=3) if pt is not None and len(direction_ratio) == 0: pt = Point(pt, dim=3) elif len(direction_ratio) == 3 and pt is None: pt = Point3D(p1.x + direction_ratio[0], p1.y + direction_ratio[1], p1.z + direction_ratio[2]) else: raise ValueError('A 2nd Point or keyword "direction_ratio" must ' 'be used.') return LinearEntity3D.__new__(cls, p1, pt, **kwargs) def equation(self, x='x', y='y', z='z'): """Return the equations that define the line in 3D. Parameters ========== x : str, optional The name to use for the x-axis, default value is 'x'. y : str, optional The name to use for the y-axis, default value is 'y'. z : str, optional The name to use for the z-axis, default value is 'z'. Returns ======= equation : Tuple of simultaneous equations Examples ======== >>> from sympy import Point3D, Line3D, solve >>> from sympy.abc import x, y, z >>> p1, p2 = Point3D(1, 0, 0), Point3D(5, 3, 0) >>> l1 = Line3D(p1, p2) >>> eq = l1.equation(x, y, z); eq (-3*x + 4*y + 3, z) >>> solve(eq.subs(z, 0), (x, y, z)) {x: 4*y/3 + 1} """ x, y, z, k = [_symbol(i, real=True) for i in (x, y, z, 'k')] p1, p2 = self.points d1, d2, d3 = p1.direction_ratio(p2) x1, y1, z1 = p1 eqs = [-d1*k + x - x1, -d2*k + y - y1, -d3*k + z - z1] # eliminate k from equations by solving first eq with k for k for i, e in enumerate(eqs): if e.has(k): kk = solve(eqs[i], k)[0] eqs.pop(i) break return Tuple(*[i.subs(k, kk).as_numer_denom()[0] for i in eqs]) class Ray3D(LinearEntity3D, Ray): """ A Ray is a semi-line in the space with a source point and a direction. Parameters ========== p1 : Point3D The source of the Ray p2 : Point or a direction vector direction_ratio: Determines the direction in which the Ray propagates. Attributes ========== source xdirection ydirection zdirection See Also ======== sympy.geometry.point.Point3D, Line3D Examples ======== >>> from sympy import Point3D, Ray3D >>> r = Ray3D(Point3D(2, 3, 4), Point3D(3, 5, 0)) >>> r Ray3D(Point3D(2, 3, 4), Point3D(3, 5, 0)) >>> r.points (Point3D(2, 3, 4), Point3D(3, 5, 0)) >>> r.source Point3D(2, 3, 4) >>> r.xdirection oo >>> r.ydirection oo >>> r.direction_ratio [1, 2, -4] """ def __new__(cls, p1, pt=None, direction_ratio=(), **kwargs): if isinstance(p1, LinearEntity3D): if pt is not None: raise ValueError('If p1 is a LinearEntity, pt must be None') p1, pt = p1.args else: p1 = Point(p1, dim=3) if pt is not None and len(direction_ratio) == 0: pt = Point(pt, dim=3) elif len(direction_ratio) == 3 and pt is None: pt = Point3D(p1.x + direction_ratio[0], p1.y + direction_ratio[1], p1.z + direction_ratio[2]) else: raise ValueError(filldedent(''' A 2nd Point or keyword "direction_ratio" must be used. ''')) return LinearEntity3D.__new__(cls, p1, pt, **kwargs) @property def xdirection(self): """The x direction of the ray. Positive infinity if the ray points in the positive x direction, negative infinity if the ray points in the negative x direction, or 0 if the ray is vertical. See Also ======== ydirection Examples ======== >>> from sympy import Point3D, Ray3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(1, 1, 1), Point3D(0, -1, 0) >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3) >>> r1.xdirection oo >>> r2.xdirection 0 """ if self.p1.x < self.p2.x: return S.Infinity elif self.p1.x == self.p2.x: return S.Zero else: return S.NegativeInfinity @property def ydirection(self): """The y direction of the ray. Positive infinity if the ray points in the positive y direction, negative infinity if the ray points in the negative y direction, or 0 if the ray is horizontal. See Also ======== xdirection Examples ======== >>> from sympy import Point3D, Ray3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(-1, -1, -1), Point3D(-1, 0, 0) >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3) >>> r1.ydirection -oo >>> r2.ydirection 0 """ if self.p1.y < self.p2.y: return S.Infinity elif self.p1.y == self.p2.y: return S.Zero else: return S.NegativeInfinity @property def zdirection(self): """The z direction of the ray. Positive infinity if the ray points in the positive z direction, negative infinity if the ray points in the negative z direction, or 0 if the ray is horizontal. See Also ======== xdirection Examples ======== >>> from sympy import Point3D, Ray3D >>> p1, p2, p3 = Point3D(0, 0, 0), Point3D(-1, -1, -1), Point3D(-1, 0, 0) >>> r1, r2 = Ray3D(p1, p2), Ray3D(p1, p3) >>> r1.ydirection -oo >>> r2.ydirection 0 >>> r2.zdirection 0 """ if self.p1.z < self.p2.z: return S.Infinity elif self.p1.z == self.p2.z: return S.Zero else: return S.NegativeInfinity class Segment3D(LinearEntity3D, Segment): """A line segment in a 3D space. Parameters ========== p1 : Point3D p2 : Point3D Attributes ========== length : number or SymPy expression midpoint : Point3D See Also ======== sympy.geometry.point.Point3D, Line3D Examples ======== >>> from sympy import Point3D, Segment3D >>> Segment3D((1, 0, 0), (1, 1, 1)) # tuples are interpreted as pts Segment3D(Point3D(1, 0, 0), Point3D(1, 1, 1)) >>> s = Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7)); s Segment3D(Point3D(4, 3, 9), Point3D(1, 1, 7)) >>> s.points (Point3D(4, 3, 9), Point3D(1, 1, 7)) >>> s.length sqrt(17) >>> s.midpoint Point3D(5/2, 2, 8) """ def __new__(cls, p1, p2, **kwargs): p1 = Point(p1, dim=3) p2 = Point(p2, dim=3) if p1 == p2: return p1 return LinearEntity3D.__new__(cls, p1, p2, **kwargs)
47a201b04e722a7d2a453db4763ee81bfd6aacabf4005b12de7d9aafd3ff3552
from sympy.core import Expr, S, oo, pi, sympify from sympy.core.evalf import N from sympy.core.sorting import default_sort_key, ordered from sympy.core.symbol import _symbol, Dummy, Symbol from sympy.functions.elementary.complexes import sign from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import cos, sin, tan from .ellipse import Circle from .entity import GeometryEntity, GeometrySet from .exceptions import GeometryError from .line import Line, Segment, Ray from .point import Point from sympy.logic import And from sympy.matrices import Matrix from sympy.simplify.simplify import simplify from sympy.solvers.solvers import solve from sympy.utilities.iterables import has_dups, has_variety, uniq, rotate_left, least_rotation from sympy.utilities.misc import as_int, func_name from mpmath.libmp.libmpf import prec_to_dps import warnings x, y, T = [Dummy('polygon_dummy', real=True) for i in range(3)] class Polygon(GeometrySet): """A two-dimensional polygon. A simple polygon in space. Can be constructed from a sequence of points or from a center, radius, number of sides and rotation angle. Parameters ========== vertices A sequence of points. n : int, optional If $> 0$, an n-sided RegularPolygon is created. Default value is $0$. Attributes ========== area angles perimeter vertices centroid sides Raises ====== GeometryError If all parameters are not Points. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Segment, Triangle Notes ===== Polygons are treated as closed paths rather than 2D areas so some calculations can be be negative or positive (e.g., area) based on the orientation of the points. Any consecutive identical points are reduced to a single point and any points collinear and between two points will be removed unless they are needed to define an explicit intersection (see examples). A Triangle, Segment or Point will be returned when there are 3 or fewer points provided. Examples ======== >>> from sympy import Polygon, pi >>> p1, p2, p3, p4, p5 = [(0, 0), (1, 0), (5, 1), (0, 1), (3, 0)] >>> Polygon(p1, p2, p3, p4) Polygon(Point2D(0, 0), Point2D(1, 0), Point2D(5, 1), Point2D(0, 1)) >>> Polygon(p1, p2) Segment2D(Point2D(0, 0), Point2D(1, 0)) >>> Polygon(p1, p2, p5) Segment2D(Point2D(0, 0), Point2D(3, 0)) The area of a polygon is calculated as positive when vertices are traversed in a ccw direction. When the sides of a polygon cross the area will have positive and negative contributions. The following defines a Z shape where the bottom right connects back to the top left. >>> Polygon((0, 2), (2, 2), (0, 0), (2, 0)).area 0 When the keyword `n` is used to define the number of sides of the Polygon then a RegularPolygon is created and the other arguments are interpreted as center, radius and rotation. The unrotated RegularPolygon will always have a vertex at Point(r, 0) where `r` is the radius of the circle that circumscribes the RegularPolygon. Its method `spin` can be used to increment that angle. >>> p = Polygon((0,0), 1, n=3) >>> p RegularPolygon(Point2D(0, 0), 1, 3, 0) >>> p.vertices[0] Point2D(1, 0) >>> p.args[0] Point2D(0, 0) >>> p.spin(pi/2) >>> p.vertices[0] Point2D(0, 1) """ __slots__ = () def __new__(cls, *args, n = 0, **kwargs): if n: args = list(args) # return a virtual polygon with n sides if len(args) == 2: # center, radius args.append(n) elif len(args) == 3: # center, radius, rotation args.insert(2, n) return RegularPolygon(*args, **kwargs) vertices = [Point(a, dim=2, **kwargs) for a in args] # remove consecutive duplicates nodup = [] for p in vertices: if nodup and p == nodup[-1]: continue nodup.append(p) if len(nodup) > 1 and nodup[-1] == nodup[0]: nodup.pop() # last point was same as first # remove collinear points i = -3 while i < len(nodup) - 3 and len(nodup) > 2: a, b, c = nodup[i], nodup[i + 1], nodup[i + 2] if Point.is_collinear(a, b, c): nodup.pop(i + 1) if a == c: nodup.pop(i) else: i += 1 vertices = list(nodup) if len(vertices) > 3: return GeometryEntity.__new__(cls, *vertices, **kwargs) elif len(vertices) == 3: return Triangle(*vertices, **kwargs) elif len(vertices) == 2: return Segment(*vertices, **kwargs) else: return Point(*vertices, **kwargs) @property def area(self): """ The area of the polygon. Notes ===== The area calculation can be positive or negative based on the orientation of the points. If any side of the polygon crosses any other side, there will be areas having opposite signs. See Also ======== sympy.geometry.ellipse.Ellipse.area Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.area 3 In the Z shaped polygon (with the lower right connecting back to the upper left) the areas cancel out: >>> Z = Polygon((0, 1), (1, 1), (0, 0), (1, 0)) >>> Z.area 0 In the M shaped polygon, areas do not cancel because no side crosses any other (though there is a point of contact). >>> M = Polygon((0, 0), (0, 1), (2, 0), (3, 1), (3, 0)) >>> M.area -3/2 """ area = 0 args = self.args for i in range(len(args)): x1, y1 = args[i - 1].args x2, y2 = args[i].args area += x1*y2 - x2*y1 return simplify(area) / 2 @staticmethod def _isright(a, b, c): """Return True/False for cw/ccw orientation. Examples ======== >>> from sympy import Point, Polygon >>> a, b, c = [Point(i) for i in [(0, 0), (1, 1), (1, 0)]] >>> Polygon._isright(a, b, c) True >>> Polygon._isright(a, c, b) False """ ba = b - a ca = c - a t_area = simplify(ba.x*ca.y - ca.x*ba.y) res = t_area.is_nonpositive if res is None: raise ValueError("Can't determine orientation") return res @property def angles(self): """The internal angle at each vertex. Returns ======= angles : dict A dictionary where each key is a vertex and each value is the internal angle at that vertex. The vertices are represented as Points. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.LinearEntity.angle_between Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.angles[p1] pi/2 >>> poly.angles[p2] acos(-4*sqrt(17)/17) """ # Determine orientation of points args = self.vertices cw = self._isright(args[-1], args[0], args[1]) ret = {} for i in range(len(args)): a, b, c = args[i - 2], args[i - 1], args[i] ang = Ray(b, a).angle_between(Ray(b, c)) if cw ^ self._isright(a, b, c): ret[b] = 2*S.Pi - ang else: ret[b] = ang return ret @property def ambient_dimension(self): return self.vertices[0].ambient_dimension @property def perimeter(self): """The perimeter of the polygon. Returns ======= perimeter : number or Basic instance See Also ======== sympy.geometry.line.Segment.length Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.perimeter sqrt(17) + 7 """ p = 0 args = self.vertices for i in range(len(args)): p += args[i - 1].distance(args[i]) return simplify(p) @property def vertices(self): """The vertices of the polygon. Returns ======= vertices : list of Points Notes ===== When iterating over the vertices, it is more efficient to index self rather than to request the vertices and index them. Only use the vertices when you want to process all of them at once. This is even more important with RegularPolygons that calculate each vertex. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.vertices [Point2D(0, 0), Point2D(1, 0), Point2D(5, 1), Point2D(0, 1)] >>> poly.vertices[0] Point2D(0, 0) """ return list(self.args) @property def centroid(self): """The centroid of the polygon. Returns ======= centroid : Point See Also ======== sympy.geometry.point.Point, sympy.geometry.util.centroid Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.centroid Point2D(31/18, 11/18) """ A = 1/(6*self.area) cx, cy = 0, 0 args = self.args for i in range(len(args)): x1, y1 = args[i - 1].args x2, y2 = args[i].args v = x1*y2 - x2*y1 cx += v*(x1 + x2) cy += v*(y1 + y2) return Point(simplify(A*cx), simplify(A*cy)) def second_moment_of_area(self, point=None): """Returns the second moment and product moment of area of a two dimensional polygon. Parameters ========== point : Point, two-tuple of sympifyable objects, or None(default=None) point is the point about which second moment of area is to be found. If "point=None" it will be calculated about the axis passing through the centroid of the polygon. Returns ======= I_xx, I_yy, I_xy : number or SymPy expression I_xx, I_yy are second moment of area of a two dimensional polygon. I_xy is product moment of area of a two dimensional polygon. Examples ======== >>> from sympy import Polygon, symbols >>> a, b = symbols('a, b') >>> p1, p2, p3, p4, p5 = [(0, 0), (a, 0), (a, b), (0, b), (a/3, b/3)] >>> rectangle = Polygon(p1, p2, p3, p4) >>> rectangle.second_moment_of_area() (a*b**3/12, a**3*b/12, 0) >>> rectangle.second_moment_of_area(p5) (a*b**3/9, a**3*b/9, a**2*b**2/36) References ========== .. [1] https://en.wikipedia.org/wiki/Second_moment_of_area """ I_xx, I_yy, I_xy = 0, 0, 0 args = self.vertices for i in range(len(args)): x1, y1 = args[i-1].args x2, y2 = args[i].args v = x1*y2 - x2*y1 I_xx += (y1**2 + y1*y2 + y2**2)*v I_yy += (x1**2 + x1*x2 + x2**2)*v I_xy += (x1*y2 + 2*x1*y1 + 2*x2*y2 + x2*y1)*v A = self.area c_x = self.centroid[0] c_y = self.centroid[1] # parallel axis theorem I_xx_c = (I_xx/12) - (A*(c_y**2)) I_yy_c = (I_yy/12) - (A*(c_x**2)) I_xy_c = (I_xy/24) - (A*(c_x*c_y)) if point is None: return I_xx_c, I_yy_c, I_xy_c I_xx = (I_xx_c + A*((point[1]-c_y)**2)) I_yy = (I_yy_c + A*((point[0]-c_x)**2)) I_xy = (I_xy_c + A*((point[0]-c_x)*(point[1]-c_y))) return I_xx, I_yy, I_xy def first_moment_of_area(self, point=None): """ Returns the first moment of area of a two-dimensional polygon with respect to a certain point of interest. First moment of area is a measure of the distribution of the area of a polygon in relation to an axis. The first moment of area of the entire polygon about its own centroid is always zero. Therefore, here it is calculated for an area, above or below a certain point of interest, that makes up a smaller portion of the polygon. This area is bounded by the point of interest and the extreme end (top or bottom) of the polygon. The first moment for this area is is then determined about the centroidal axis of the initial polygon. References ========== .. [1] https://skyciv.com/docs/tutorials/section-tutorials/calculating-the-statical-or-first-moment-of-area-of-beam-sections/?cc=BMD .. [2] https://mechanicalc.com/reference/cross-sections Parameters ========== point: Point, two-tuple of sympifyable objects, or None (default=None) point is the point above or below which the area of interest lies If ``point=None`` then the centroid acts as the point of interest. Returns ======= Q_x, Q_y: number or SymPy expressions Q_x is the first moment of area about the x-axis Q_y is the first moment of area about the y-axis A negative sign indicates that the section modulus is determined for a section below (or left of) the centroidal axis Examples ======== >>> from sympy import Point, Polygon >>> a, b = 50, 10 >>> p1, p2, p3, p4 = [(0, b), (0, 0), (a, 0), (a, b)] >>> p = Polygon(p1, p2, p3, p4) >>> p.first_moment_of_area() (625, 3125) >>> p.first_moment_of_area(point=Point(30, 7)) (525, 3000) """ if point: xc, yc = self.centroid else: point = self.centroid xc, yc = point h_line = Line(point, slope=0) v_line = Line(point, slope=S.Infinity) h_poly = self.cut_section(h_line) v_poly = self.cut_section(v_line) poly_1 = h_poly[0] if h_poly[0].area <= h_poly[1].area else h_poly[1] poly_2 = v_poly[0] if v_poly[0].area <= v_poly[1].area else v_poly[1] Q_x = (poly_1.centroid.y - yc)*poly_1.area Q_y = (poly_2.centroid.x - xc)*poly_2.area return Q_x, Q_y def polar_second_moment_of_area(self): """Returns the polar modulus of a two-dimensional polygon It is a constituent of the second moment of area, linked through the perpendicular axis theorem. While the planar second moment of area describes an object's resistance to deflection (bending) when subjected to a force applied to a plane parallel to the central axis, the polar second moment of area describes an object's resistance to deflection when subjected to a moment applied in a plane perpendicular to the object's central axis (i.e. parallel to the cross-section) Examples ======== >>> from sympy import Polygon, symbols >>> a, b = symbols('a, b') >>> rectangle = Polygon((0, 0), (a, 0), (a, b), (0, b)) >>> rectangle.polar_second_moment_of_area() a**3*b/12 + a*b**3/12 References ========== .. [1] https://en.wikipedia.org/wiki/Polar_moment_of_inertia """ second_moment = self.second_moment_of_area() return second_moment[0] + second_moment[1] def section_modulus(self, point=None): """Returns a tuple with the section modulus of a two-dimensional polygon. Section modulus is a geometric property of a polygon defined as the ratio of second moment of area to the distance of the extreme end of the polygon from the centroidal axis. Parameters ========== point : Point, two-tuple of sympifyable objects, or None(default=None) point is the point at which section modulus is to be found. If "point=None" it will be calculated for the point farthest from the centroidal axis of the polygon. Returns ======= S_x, S_y: numbers or SymPy expressions S_x is the section modulus with respect to the x-axis S_y is the section modulus with respect to the y-axis A negative sign indicates that the section modulus is determined for a point below the centroidal axis Examples ======== >>> from sympy import symbols, Polygon, Point >>> a, b = symbols('a, b', positive=True) >>> rectangle = Polygon((0, 0), (a, 0), (a, b), (0, b)) >>> rectangle.section_modulus() (a*b**2/6, a**2*b/6) >>> rectangle.section_modulus(Point(a/4, b/4)) (-a*b**2/3, -a**2*b/3) References ========== .. [1] https://en.wikipedia.org/wiki/Section_modulus """ x_c, y_c = self.centroid if point is None: # taking x and y as maximum distances from centroid x_min, y_min, x_max, y_max = self.bounds y = max(y_c - y_min, y_max - y_c) x = max(x_c - x_min, x_max - x_c) else: # taking x and y as distances of the given point from the centroid y = point.y - y_c x = point.x - x_c second_moment= self.second_moment_of_area() S_x = second_moment[0]/y S_y = second_moment[1]/x return S_x, S_y @property def sides(self): """The directed line segments that form the sides of the polygon. Returns ======= sides : list of sides Each side is a directed Segment. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Segment Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.sides [Segment2D(Point2D(0, 0), Point2D(1, 0)), Segment2D(Point2D(1, 0), Point2D(5, 1)), Segment2D(Point2D(5, 1), Point2D(0, 1)), Segment2D(Point2D(0, 1), Point2D(0, 0))] """ res = [] args = self.vertices for i in range(-len(args), 0): res.append(Segment(args[i], args[i + 1])) return res @property def bounds(self): """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding rectangle for the geometric figure. """ verts = self.vertices xs = [p.x for p in verts] ys = [p.y for p in verts] return (min(xs), min(ys), max(xs), max(ys)) def is_convex(self): """Is the polygon convex? A polygon is convex if all its interior angles are less than 180 degrees and there are no intersections between sides. Returns ======= is_convex : boolean True if this polygon is convex, False otherwise. See Also ======== sympy.geometry.util.convex_hull Examples ======== >>> from sympy import Point, Polygon >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly = Polygon(p1, p2, p3, p4) >>> poly.is_convex() True """ # Determine orientation of points args = self.vertices cw = self._isright(args[-2], args[-1], args[0]) for i in range(1, len(args)): if cw ^ self._isright(args[i - 2], args[i - 1], args[i]): return False # check for intersecting sides sides = self.sides for i, si in enumerate(sides): pts = si.args # exclude the sides connected to si for j in range(1 if i == len(sides) - 1 else 0, i - 1): sj = sides[j] if sj.p1 not in pts and sj.p2 not in pts: hit = si.intersection(sj) if hit: return False return True def encloses_point(self, p): """ Return True if p is enclosed by (is inside of) self. Notes ===== Being on the border of self is considered False. Parameters ========== p : Point Returns ======= encloses_point : True, False or None See Also ======== sympy.geometry.point.Point, sympy.geometry.ellipse.Ellipse.encloses_point Examples ======== >>> from sympy import Polygon, Point >>> p = Polygon((0, 0), (4, 0), (4, 4)) >>> p.encloses_point(Point(2, 1)) True >>> p.encloses_point(Point(2, 2)) False >>> p.encloses_point(Point(5, 5)) False References ========== .. [1] http://paulbourke.net/geometry/polygonmesh/#insidepoly """ p = Point(p, dim=2) if p in self.vertices or any(p in s for s in self.sides): return False # move to p, checking that the result is numeric lit = [] for v in self.vertices: lit.append(v - p) # the difference is simplified if lit[-1].free_symbols: return None poly = Polygon(*lit) # polygon closure is assumed in the following test but Polygon removes duplicate pts so # the last point has to be added so all sides are computed. Using Polygon.sides is # not good since Segments are unordered. args = poly.args indices = list(range(-len(args), 1)) if poly.is_convex(): orientation = None for i in indices: a = args[i] b = args[i + 1] test = ((-a.y)*(b.x - a.x) - (-a.x)*(b.y - a.y)).is_negative if orientation is None: orientation = test elif test is not orientation: return False return True hit_odd = False p1x, p1y = args[0].args for i in indices[1:]: p2x, p2y = args[i].args if 0 > min(p1y, p2y): if 0 <= max(p1y, p2y): if 0 <= max(p1x, p2x): if p1y != p2y: xinters = (-p1y)*(p2x - p1x)/(p2y - p1y) + p1x if p1x == p2x or 0 <= xinters: hit_odd = not hit_odd p1x, p1y = p2x, p2y return hit_odd def arbitrary_point(self, parameter='t'): """A parameterized point on the polygon. The parameter, varying from 0 to 1, assigns points to the position on the perimeter that is that fraction of the total perimeter. So the point evaluated at t=1/2 would return the point from the first vertex that is 1/2 way around the polygon. Parameters ========== parameter : str, optional Default value is 't'. Returns ======= arbitrary_point : Point Raises ====== ValueError When `parameter` already appears in the Polygon's definition. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Polygon, Symbol >>> t = Symbol('t', real=True) >>> tri = Polygon((0, 0), (1, 0), (1, 1)) >>> p = tri.arbitrary_point('t') >>> perimeter = tri.perimeter >>> s1, s2 = [s.length for s in tri.sides[:2]] >>> p.subs(t, (s1 + s2/2)/perimeter) Point2D(1, 1/2) """ t = _symbol(parameter, real=True) if t.name in (f.name for f in self.free_symbols): raise ValueError('Symbol %s already appears in object and cannot be used as a parameter.' % t.name) sides = [] perimeter = self.perimeter perim_fraction_start = 0 for s in self.sides: side_perim_fraction = s.length/perimeter perim_fraction_end = perim_fraction_start + side_perim_fraction pt = s.arbitrary_point(parameter).subs( t, (t - perim_fraction_start)/side_perim_fraction) sides.append( (pt, (And(perim_fraction_start <= t, t < perim_fraction_end)))) perim_fraction_start = perim_fraction_end return Piecewise(*sides) def parameter_value(self, other, t): if not isinstance(other,GeometryEntity): other = Point(other, dim=self.ambient_dimension) if not isinstance(other,Point): raise ValueError("other must be a point") if other.free_symbols: raise NotImplementedError('non-numeric coordinates') unknown = False p = self.arbitrary_point(T) for pt, cond in p.args: sol = solve(pt - other, T, dict=True) if not sol: continue value = sol[0][T] if simplify(cond.subs(T, value)) == True: return {t: value} unknown = True if unknown: raise ValueError("Given point may not be on %s" % func_name(self)) raise ValueError("Given point is not on %s" % func_name(self)) def plot_interval(self, parameter='t'): """The plot interval for the default geometric plot of the polygon. Parameters ========== parameter : str, optional Default value is 't'. Returns ======= plot_interval : list (plot interval) [parameter, lower_bound, upper_bound] Examples ======== >>> from sympy import Polygon >>> p = Polygon((0, 0), (1, 0), (1, 1)) >>> p.plot_interval() [t, 0, 1] """ t = Symbol(parameter, real=True) return [t, 0, 1] def intersection(self, o): """The intersection of polygon and geometry entity. The intersection may be empty and can contain individual Points and complete Line Segments. Parameters ========== other: GeometryEntity Returns ======= intersection : list The list of Segments and Points See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Segment Examples ======== >>> from sympy import Point, Polygon, Line >>> p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) >>> poly1 = Polygon(p1, p2, p3, p4) >>> p5, p6, p7 = map(Point, [(3, 2), (1, -1), (0, 2)]) >>> poly2 = Polygon(p5, p6, p7) >>> poly1.intersection(poly2) [Point2D(1/3, 1), Point2D(2/3, 0), Point2D(9/5, 1/5), Point2D(7/3, 1)] >>> poly1.intersection(Line(p1, p2)) [Segment2D(Point2D(0, 0), Point2D(1, 0))] >>> poly1.intersection(p1) [Point2D(0, 0)] """ intersection_result = [] k = o.sides if isinstance(o, Polygon) else [o] for side in self.sides: for side1 in k: intersection_result.extend(side.intersection(side1)) intersection_result = list(uniq(intersection_result)) points = [entity for entity in intersection_result if isinstance(entity, Point)] segments = [entity for entity in intersection_result if isinstance(entity, Segment)] if points and segments: points_in_segments = list(uniq([point for point in points for segment in segments if point in segment])) if points_in_segments: for i in points_in_segments: points.remove(i) return list(ordered(segments + points)) else: return list(ordered(intersection_result)) def cut_section(self, line): """ Returns a tuple of two polygon segments that lie above and below the intersecting line respectively. Parameters ========== line: Line object of geometry module line which cuts the Polygon. The part of the Polygon that lies above and below this line is returned. Returns ======= upper_polygon, lower_polygon: Polygon objects or None upper_polygon is the polygon that lies above the given line. lower_polygon is the polygon that lies below the given line. upper_polygon and lower polygon are ``None`` when no polygon exists above the line or below the line. Raises ====== ValueError: When the line does not intersect the polygon Examples ======== >>> from sympy import Polygon, Line >>> a, b = 20, 10 >>> p1, p2, p3, p4 = [(0, b), (0, 0), (a, 0), (a, b)] >>> rectangle = Polygon(p1, p2, p3, p4) >>> t = rectangle.cut_section(Line((0, 5), slope=0)) >>> t (Polygon(Point2D(0, 10), Point2D(0, 5), Point2D(20, 5), Point2D(20, 10)), Polygon(Point2D(0, 5), Point2D(0, 0), Point2D(20, 0), Point2D(20, 5))) >>> upper_segment, lower_segment = t >>> upper_segment.area 100 >>> upper_segment.centroid Point2D(10, 15/2) >>> lower_segment.centroid Point2D(10, 5/2) References ========== .. [1] https://github.com/sympy/sympy/wiki/A-method-to-return-a-cut-section-of-any-polygon-geometry """ intersection_points = self.intersection(line) if not intersection_points: raise ValueError("This line does not intersect the polygon") points = list(self.vertices) points.append(points[0]) eq = line.equation(x, y) # considering equation of line to be `ax +by + c` a = eq.coeff(x) b = eq.coeff(y) upper_vertices = [] lower_vertices = [] # prev is true when previous point is above the line prev = True prev_point = None for point in points: # when coefficient of y is 0, right side of the line is # considered compare = eq.subs({x: point.x, y: point.y})/b if b \ else eq.subs(x, point.x)/a # if point lies above line if compare > 0: if not prev: # if previous point lies below the line, the intersection # point of the polygon edge and the line has to be included edge = Line(point, prev_point) new_point = edge.intersection(line) upper_vertices.append(new_point[0]) lower_vertices.append(new_point[0]) upper_vertices.append(point) prev = True else: if prev and prev_point: edge = Line(point, prev_point) new_point = edge.intersection(line) upper_vertices.append(new_point[0]) lower_vertices.append(new_point[0]) lower_vertices.append(point) prev = False prev_point = point upper_polygon, lower_polygon = None, None if upper_vertices and isinstance(Polygon(*upper_vertices), Polygon): upper_polygon = Polygon(*upper_vertices) if lower_vertices and isinstance(Polygon(*lower_vertices), Polygon): lower_polygon = Polygon(*lower_vertices) return upper_polygon, lower_polygon def distance(self, o): """ Returns the shortest distance between self and o. If o is a point, then self does not need to be convex. If o is another polygon self and o must be convex. Examples ======== >>> from sympy import Point, Polygon, RegularPolygon >>> p1, p2 = map(Point, [(0, 0), (7, 5)]) >>> poly = Polygon(*RegularPolygon(p1, 1, 3).vertices) >>> poly.distance(p2) sqrt(61) """ if isinstance(o, Point): dist = oo for side in self.sides: current = side.distance(o) if current == 0: return S.Zero elif current < dist: dist = current return dist elif isinstance(o, Polygon) and self.is_convex() and o.is_convex(): return self._do_poly_distance(o) raise NotImplementedError() def _do_poly_distance(self, e2): """ Calculates the least distance between the exteriors of two convex polygons e1 and e2. Does not check for the convexity of the polygons as this is checked by Polygon.distance. Notes ===== - Prints a warning if the two polygons possibly intersect as the return value will not be valid in such a case. For a more through test of intersection use intersection(). See Also ======== sympy.geometry.point.Point.distance Examples ======== >>> from sympy import Point, Polygon >>> square = Polygon(Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0)) >>> triangle = Polygon(Point(1, 2), Point(2, 2), Point(2, 1)) >>> square._do_poly_distance(triangle) sqrt(2)/2 Description of method used ========================== Method: [1] http://cgm.cs.mcgill.ca/~orm/mind2p.html Uses rotating calipers: [2] https://en.wikipedia.org/wiki/Rotating_calipers and antipodal points: [3] https://en.wikipedia.org/wiki/Antipodal_point """ e1 = self '''Tests for a possible intersection between the polygons and outputs a warning''' e1_center = e1.centroid e2_center = e2.centroid e1_max_radius = S.Zero e2_max_radius = S.Zero for vertex in e1.vertices: r = Point.distance(e1_center, vertex) if e1_max_radius < r: e1_max_radius = r for vertex in e2.vertices: r = Point.distance(e2_center, vertex) if e2_max_radius < r: e2_max_radius = r center_dist = Point.distance(e1_center, e2_center) if center_dist <= e1_max_radius + e2_max_radius: warnings.warn("Polygons may intersect producing erroneous output", stacklevel=3) ''' Find the upper rightmost vertex of e1 and the lowest leftmost vertex of e2 ''' e1_ymax = Point(0, -oo) e2_ymin = Point(0, oo) for vertex in e1.vertices: if vertex.y > e1_ymax.y or (vertex.y == e1_ymax.y and vertex.x > e1_ymax.x): e1_ymax = vertex for vertex in e2.vertices: if vertex.y < e2_ymin.y or (vertex.y == e2_ymin.y and vertex.x < e2_ymin.x): e2_ymin = vertex min_dist = Point.distance(e1_ymax, e2_ymin) ''' Produce a dictionary with vertices of e1 as the keys and, for each vertex, the points to which the vertex is connected as its value. The same is then done for e2. ''' e1_connections = {} e2_connections = {} for side in e1.sides: if side.p1 in e1_connections: e1_connections[side.p1].append(side.p2) else: e1_connections[side.p1] = [side.p2] if side.p2 in e1_connections: e1_connections[side.p2].append(side.p1) else: e1_connections[side.p2] = [side.p1] for side in e2.sides: if side.p1 in e2_connections: e2_connections[side.p1].append(side.p2) else: e2_connections[side.p1] = [side.p2] if side.p2 in e2_connections: e2_connections[side.p2].append(side.p1) else: e2_connections[side.p2] = [side.p1] e1_current = e1_ymax e2_current = e2_ymin support_line = Line(Point(S.Zero, S.Zero), Point(S.One, S.Zero)) ''' Determine which point in e1 and e2 will be selected after e2_ymin and e1_ymax, this information combined with the above produced dictionaries determines the path that will be taken around the polygons ''' point1 = e1_connections[e1_ymax][0] point2 = e1_connections[e1_ymax][1] angle1 = support_line.angle_between(Line(e1_ymax, point1)) angle2 = support_line.angle_between(Line(e1_ymax, point2)) if angle1 < angle2: e1_next = point1 elif angle2 < angle1: e1_next = point2 elif Point.distance(e1_ymax, point1) > Point.distance(e1_ymax, point2): e1_next = point2 else: e1_next = point1 point1 = e2_connections[e2_ymin][0] point2 = e2_connections[e2_ymin][1] angle1 = support_line.angle_between(Line(e2_ymin, point1)) angle2 = support_line.angle_between(Line(e2_ymin, point2)) if angle1 > angle2: e2_next = point1 elif angle2 > angle1: e2_next = point2 elif Point.distance(e2_ymin, point1) > Point.distance(e2_ymin, point2): e2_next = point2 else: e2_next = point1 ''' Loop which determines the distance between anti-podal pairs and updates the minimum distance accordingly. It repeats until it reaches the starting position. ''' while True: e1_angle = support_line.angle_between(Line(e1_current, e1_next)) e2_angle = pi - support_line.angle_between(Line( e2_current, e2_next)) if (e1_angle < e2_angle) is True: support_line = Line(e1_current, e1_next) e1_segment = Segment(e1_current, e1_next) min_dist_current = e1_segment.distance(e2_current) if min_dist_current.evalf() < min_dist.evalf(): min_dist = min_dist_current if e1_connections[e1_next][0] != e1_current: e1_current = e1_next e1_next = e1_connections[e1_next][0] else: e1_current = e1_next e1_next = e1_connections[e1_next][1] elif (e1_angle > e2_angle) is True: support_line = Line(e2_next, e2_current) e2_segment = Segment(e2_current, e2_next) min_dist_current = e2_segment.distance(e1_current) if min_dist_current.evalf() < min_dist.evalf(): min_dist = min_dist_current if e2_connections[e2_next][0] != e2_current: e2_current = e2_next e2_next = e2_connections[e2_next][0] else: e2_current = e2_next e2_next = e2_connections[e2_next][1] else: support_line = Line(e1_current, e1_next) e1_segment = Segment(e1_current, e1_next) e2_segment = Segment(e2_current, e2_next) min1 = e1_segment.distance(e2_next) min2 = e2_segment.distance(e1_next) min_dist_current = min(min1, min2) if min_dist_current.evalf() < min_dist.evalf(): min_dist = min_dist_current if e1_connections[e1_next][0] != e1_current: e1_current = e1_next e1_next = e1_connections[e1_next][0] else: e1_current = e1_next e1_next = e1_connections[e1_next][1] if e2_connections[e2_next][0] != e2_current: e2_current = e2_next e2_next = e2_connections[e2_next][0] else: e2_current = e2_next e2_next = e2_connections[e2_next][1] if e1_current == e1_ymax and e2_current == e2_ymin: break return min_dist def _svg(self, scale_factor=1., fill_color="#66cc99"): """Returns SVG path element for the Polygon. Parameters ========== scale_factor : float Multiplication factor for the SVG stroke-width. Default is 1. fill_color : str, optional Hex string for fill color. Default is "#66cc99". """ verts = map(N, self.vertices) coords = ["{},{}".format(p.x, p.y) for p in verts] path = "M {} L {} z".format(coords[0], " L ".join(coords[1:])) return ( '<path fill-rule="evenodd" fill="{2}" stroke="#555555" ' 'stroke-width="{0}" opacity="0.6" d="{1}" />' ).format(2. * scale_factor, path, fill_color) def _hashable_content(self): D = {} def ref_list(point_list): kee = {} for i, p in enumerate(ordered(set(point_list))): kee[p] = i D[i] = p return [kee[p] for p in point_list] S1 = ref_list(self.args) r_nor = rotate_left(S1, least_rotation(S1)) S2 = ref_list(list(reversed(self.args))) r_rev = rotate_left(S2, least_rotation(S2)) if r_nor < r_rev: r = r_nor else: r = r_rev canonical_args = [ D[order] for order in r ] return tuple(canonical_args) def __contains__(self, o): """ Return True if o is contained within the boundary lines of self.altitudes Parameters ========== other : GeometryEntity Returns ======= contained in : bool The points (and sides, if applicable) are contained in self. See Also ======== sympy.geometry.entity.GeometryEntity.encloses Examples ======== >>> from sympy import Line, Segment, Point >>> p = Point(0, 0) >>> q = Point(1, 1) >>> s = Segment(p, q*2) >>> l = Line(p, q) >>> p in q False >>> p in s True >>> q*3 in s False >>> s in l True """ if isinstance(o, Polygon): return self == o elif isinstance(o, Segment): return any(o in s for s in self.sides) elif isinstance(o, Point): if o in self.vertices: return True for side in self.sides: if o in side: return True return False def bisectors(p, prec=None): """Returns angle bisectors of a polygon. If prec is given then approximate the point defining the ray to that precision. The distance between the points defining the bisector ray is 1. Examples ======== >>> from sympy import Polygon, Point >>> p = Polygon(Point(0, 0), Point(2, 0), Point(1, 1), Point(0, 3)) >>> p.bisectors(2) {Point2D(0, 0): Ray2D(Point2D(0, 0), Point2D(0.71, 0.71)), Point2D(0, 3): Ray2D(Point2D(0, 3), Point2D(0.23, 2.0)), Point2D(1, 1): Ray2D(Point2D(1, 1), Point2D(0.19, 0.42)), Point2D(2, 0): Ray2D(Point2D(2, 0), Point2D(1.1, 0.38))} """ b = {} pts = list(p.args) pts.append(pts[0]) # close it cw = Polygon._isright(*pts[:3]) if cw: pts = list(reversed(pts)) for v, a in p.angles.items(): i = pts.index(v) p1, p2 = Point._normalize_dimension(pts[i], pts[i + 1]) ray = Ray(p1, p2).rotate(a/2, v) dir = ray.direction ray = Ray(ray.p1, ray.p1 + dir/dir.distance((0, 0))) if prec is not None: ray = Ray(ray.p1, ray.p2.n(prec)) b[v] = ray return b class RegularPolygon(Polygon): """ A regular polygon. Such a polygon has all internal angles equal and all sides the same length. Parameters ========== center : Point radius : number or Basic instance The distance from the center to a vertex n : int The number of sides Attributes ========== vertices center radius rotation apothem interior_angle exterior_angle circumcircle incircle angles Raises ====== GeometryError If the `center` is not a Point, or the `radius` is not a number or Basic instance, or the number of sides, `n`, is less than three. Notes ===== A RegularPolygon can be instantiated with Polygon with the kwarg n. Regular polygons are instantiated with a center, radius, number of sides and a rotation angle. Whereas the arguments of a Polygon are vertices, the vertices of the RegularPolygon must be obtained with the vertices method. See Also ======== sympy.geometry.point.Point, Polygon Examples ======== >>> from sympy import RegularPolygon, Point >>> r = RegularPolygon(Point(0, 0), 5, 3) >>> r RegularPolygon(Point2D(0, 0), 5, 3, 0) >>> r.vertices[0] Point2D(5, 0) """ __slots__ = ('_n', '_center', '_radius', '_rot') def __new__(self, c, r, n, rot=0, **kwargs): r, n, rot = map(sympify, (r, n, rot)) c = Point(c, dim=2, **kwargs) if not isinstance(r, Expr): raise GeometryError("r must be an Expr object, not %s" % r) if n.is_Number: as_int(n) # let an error raise if necessary if n < 3: raise GeometryError("n must be a >= 3, not %s" % n) obj = GeometryEntity.__new__(self, c, r, n, **kwargs) obj._n = n obj._center = c obj._radius = r obj._rot = rot % (2*S.Pi/n) if rot.is_number else rot return obj def _eval_evalf(self, prec=15, **options): c, r, n, a = self.args dps = prec_to_dps(prec) c, r, a = [i.evalf(n=dps, **options) for i in (c, r, a)] return self.func(c, r, n, a) @property def args(self): """ Returns the center point, the radius, the number of sides, and the orientation angle. Examples ======== >>> from sympy import RegularPolygon, Point >>> r = RegularPolygon(Point(0, 0), 5, 3) >>> r.args (Point2D(0, 0), 5, 3, 0) """ return self._center, self._radius, self._n, self._rot def __str__(self): return 'RegularPolygon(%s, %s, %s, %s)' % tuple(self.args) def __repr__(self): return 'RegularPolygon(%s, %s, %s, %s)' % tuple(self.args) @property def area(self): """Returns the area. Examples ======== >>> from sympy import RegularPolygon >>> square = RegularPolygon((0, 0), 1, 4) >>> square.area 2 >>> _ == square.length**2 True """ c, r, n, rot = self.args return sign(r)*n*self.length**2/(4*tan(pi/n)) @property def length(self): """Returns the length of the sides. The half-length of the side and the apothem form two legs of a right triangle whose hypotenuse is the radius of the regular polygon. Examples ======== >>> from sympy import RegularPolygon >>> from sympy import sqrt >>> s = square_in_unit_circle = RegularPolygon((0, 0), 1, 4) >>> s.length sqrt(2) >>> sqrt((_/2)**2 + s.apothem**2) == s.radius True """ return self.radius*2*sin(pi/self._n) @property def center(self): """The center of the RegularPolygon This is also the center of the circumscribing circle. Returns ======= center : Point See Also ======== sympy.geometry.point.Point, sympy.geometry.ellipse.Ellipse.center Examples ======== >>> from sympy import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 5, 4) >>> rp.center Point2D(0, 0) """ return self._center centroid = center @property def circumcenter(self): """ Alias for center. Examples ======== >>> from sympy import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 5, 4) >>> rp.circumcenter Point2D(0, 0) """ return self.center @property def radius(self): """Radius of the RegularPolygon This is also the radius of the circumscribing circle. Returns ======= radius : number or instance of Basic See Also ======== sympy.geometry.line.Segment.length, sympy.geometry.ellipse.Circle.radius Examples ======== >>> from sympy import Symbol >>> from sympy import RegularPolygon, Point >>> radius = Symbol('r') >>> rp = RegularPolygon(Point(0, 0), radius, 4) >>> rp.radius r """ return self._radius @property def circumradius(self): """ Alias for radius. Examples ======== >>> from sympy import Symbol >>> from sympy import RegularPolygon, Point >>> radius = Symbol('r') >>> rp = RegularPolygon(Point(0, 0), radius, 4) >>> rp.circumradius r """ return self.radius @property def rotation(self): """CCW angle by which the RegularPolygon is rotated Returns ======= rotation : number or instance of Basic Examples ======== >>> from sympy import pi >>> from sympy.abc import a >>> from sympy import RegularPolygon, Point >>> RegularPolygon(Point(0, 0), 3, 4, pi/4).rotation pi/4 Numerical rotation angles are made canonical: >>> RegularPolygon(Point(0, 0), 3, 4, a).rotation a >>> RegularPolygon(Point(0, 0), 3, 4, pi).rotation 0 """ return self._rot @property def apothem(self): """The inradius of the RegularPolygon. The apothem/inradius is the radius of the inscribed circle. Returns ======= apothem : number or instance of Basic See Also ======== sympy.geometry.line.Segment.length, sympy.geometry.ellipse.Circle.radius Examples ======== >>> from sympy import Symbol >>> from sympy import RegularPolygon, Point >>> radius = Symbol('r') >>> rp = RegularPolygon(Point(0, 0), radius, 4) >>> rp.apothem sqrt(2)*r/2 """ return self.radius * cos(S.Pi/self._n) @property def inradius(self): """ Alias for apothem. Examples ======== >>> from sympy import Symbol >>> from sympy import RegularPolygon, Point >>> radius = Symbol('r') >>> rp = RegularPolygon(Point(0, 0), radius, 4) >>> rp.inradius sqrt(2)*r/2 """ return self.apothem @property def interior_angle(self): """Measure of the interior angles. Returns ======= interior_angle : number See Also ======== sympy.geometry.line.LinearEntity.angle_between Examples ======== >>> from sympy import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 4, 8) >>> rp.interior_angle 3*pi/4 """ return (self._n - 2)*S.Pi/self._n @property def exterior_angle(self): """Measure of the exterior angles. Returns ======= exterior_angle : number See Also ======== sympy.geometry.line.LinearEntity.angle_between Examples ======== >>> from sympy import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 4, 8) >>> rp.exterior_angle pi/4 """ return 2*S.Pi/self._n @property def circumcircle(self): """The circumcircle of the RegularPolygon. Returns ======= circumcircle : Circle See Also ======== circumcenter, sympy.geometry.ellipse.Circle Examples ======== >>> from sympy import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 4, 8) >>> rp.circumcircle Circle(Point2D(0, 0), 4) """ return Circle(self.center, self.radius) @property def incircle(self): """The incircle of the RegularPolygon. Returns ======= incircle : Circle See Also ======== inradius, sympy.geometry.ellipse.Circle Examples ======== >>> from sympy import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 4, 7) >>> rp.incircle Circle(Point2D(0, 0), 4*cos(pi/7)) """ return Circle(self.center, self.apothem) @property def angles(self): """ Returns a dictionary with keys, the vertices of the Polygon, and values, the interior angle at each vertex. Examples ======== >>> from sympy import RegularPolygon, Point >>> r = RegularPolygon(Point(0, 0), 5, 3) >>> r.angles {Point2D(-5/2, -5*sqrt(3)/2): pi/3, Point2D(-5/2, 5*sqrt(3)/2): pi/3, Point2D(5, 0): pi/3} """ ret = {} ang = self.interior_angle for v in self.vertices: ret[v] = ang return ret def encloses_point(self, p): """ Return True if p is enclosed by (is inside of) self. Notes ===== Being on the border of self is considered False. The general Polygon.encloses_point method is called only if a point is not within or beyond the incircle or circumcircle, respectively. Parameters ========== p : Point Returns ======= encloses_point : True, False or None See Also ======== sympy.geometry.ellipse.Ellipse.encloses_point Examples ======== >>> from sympy import RegularPolygon, S, Point, Symbol >>> p = RegularPolygon((0, 0), 3, 4) >>> p.encloses_point(Point(0, 0)) True >>> r, R = p.inradius, p.circumradius >>> p.encloses_point(Point((r + R)/2, 0)) True >>> p.encloses_point(Point(R/2, R/2 + (R - r)/10)) False >>> t = Symbol('t', real=True) >>> p.encloses_point(p.arbitrary_point().subs(t, S.Half)) False >>> p.encloses_point(Point(5, 5)) False """ c = self.center d = Segment(c, p).length if d >= self.radius: return False elif d < self.inradius: return True else: # now enumerate the RegularPolygon like a general polygon. return Polygon.encloses_point(self, p) def spin(self, angle): """Increment *in place* the virtual Polygon's rotation by ccw angle. See also: rotate method which moves the center. >>> from sympy import Polygon, Point, pi >>> r = Polygon(Point(0,0), 1, n=3) >>> r.vertices[0] Point2D(1, 0) >>> r.spin(pi/6) >>> r.vertices[0] Point2D(sqrt(3)/2, 1/2) See Also ======== rotation rotate : Creates a copy of the RegularPolygon rotated about a Point """ self._rot += angle def rotate(self, angle, pt=None): """Override GeometryEntity.rotate to first rotate the RegularPolygon about its center. >>> from sympy import Point, RegularPolygon, pi >>> t = RegularPolygon(Point(1, 0), 1, 3) >>> t.vertices[0] # vertex on x-axis Point2D(2, 0) >>> t.rotate(pi/2).vertices[0] # vertex on y axis now Point2D(0, 2) See Also ======== rotation spin : Rotates a RegularPolygon in place """ r = type(self)(*self.args) # need a copy or else changes are in-place r._rot += angle return GeometryEntity.rotate(r, angle, pt) def scale(self, x=1, y=1, pt=None): """Override GeometryEntity.scale since it is the radius that must be scaled (if x == y) or else a new Polygon must be returned. >>> from sympy import RegularPolygon Symmetric scaling returns a RegularPolygon: >>> RegularPolygon((0, 0), 1, 4).scale(2, 2) RegularPolygon(Point2D(0, 0), 2, 4, 0) Asymmetric scaling returns a kite as a Polygon: >>> RegularPolygon((0, 0), 1, 4).scale(2, 1) Polygon(Point2D(2, 0), Point2D(0, 1), Point2D(-2, 0), Point2D(0, -1)) """ if pt: pt = Point(pt, dim=2) return self.translate(*(-pt).args).scale(x, y).translate(*pt.args) if x != y: return Polygon(*self.vertices).scale(x, y) c, r, n, rot = self.args r *= x return self.func(c, r, n, rot) def reflect(self, line): """Override GeometryEntity.reflect since this is not made of only points. Examples ======== >>> from sympy import RegularPolygon, Line >>> RegularPolygon((0, 0), 1, 4).reflect(Line((0, 1), slope=-2)) RegularPolygon(Point2D(4/5, 2/5), -1, 4, atan(4/3)) """ c, r, n, rot = self.args v = self.vertices[0] d = v - c cc = c.reflect(line) vv = v.reflect(line) dd = vv - cc # calculate rotation about the new center # which will align the vertices l1 = Ray((0, 0), dd) l2 = Ray((0, 0), d) ang = l1.closing_angle(l2) rot += ang # change sign of radius as point traversal is reversed return self.func(cc, -r, n, rot) @property def vertices(self): """The vertices of the RegularPolygon. Returns ======= vertices : list Each vertex is a Point. See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import RegularPolygon, Point >>> rp = RegularPolygon(Point(0, 0), 5, 4) >>> rp.vertices [Point2D(5, 0), Point2D(0, 5), Point2D(-5, 0), Point2D(0, -5)] """ c = self._center r = abs(self._radius) rot = self._rot v = 2*S.Pi/self._n return [Point(c.x + r*cos(k*v + rot), c.y + r*sin(k*v + rot)) for k in range(self._n)] def __eq__(self, o): if not isinstance(o, Polygon): return False elif not isinstance(o, RegularPolygon): return Polygon.__eq__(o, self) return self.args == o.args def __hash__(self): return super().__hash__() class Triangle(Polygon): """ A polygon with three vertices and three sides. Parameters ========== points : sequence of Points keyword: asa, sas, or sss to specify sides/angles of the triangle Attributes ========== vertices altitudes orthocenter circumcenter circumradius circumcircle inradius incircle exradii medians medial nine_point_circle Raises ====== GeometryError If the number of vertices is not equal to three, or one of the vertices is not a Point, or a valid keyword is not given. See Also ======== sympy.geometry.point.Point, Polygon Examples ======== >>> from sympy import Triangle, Point >>> Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) Triangle(Point2D(0, 0), Point2D(4, 0), Point2D(4, 3)) Keywords sss, sas, or asa can be used to give the desired side lengths (in order) and interior angles (in degrees) that define the triangle: >>> Triangle(sss=(3, 4, 5)) Triangle(Point2D(0, 0), Point2D(3, 0), Point2D(3, 4)) >>> Triangle(asa=(30, 1, 30)) Triangle(Point2D(0, 0), Point2D(1, 0), Point2D(1/2, sqrt(3)/6)) >>> Triangle(sas=(1, 45, 2)) Triangle(Point2D(0, 0), Point2D(2, 0), Point2D(sqrt(2)/2, sqrt(2)/2)) """ def __new__(cls, *args, **kwargs): if len(args) != 3: if 'sss' in kwargs: return _sss(*[simplify(a) for a in kwargs['sss']]) if 'asa' in kwargs: return _asa(*[simplify(a) for a in kwargs['asa']]) if 'sas' in kwargs: return _sas(*[simplify(a) for a in kwargs['sas']]) msg = "Triangle instantiates with three points or a valid keyword." raise GeometryError(msg) vertices = [Point(a, dim=2, **kwargs) for a in args] # remove consecutive duplicates nodup = [] for p in vertices: if nodup and p == nodup[-1]: continue nodup.append(p) if len(nodup) > 1 and nodup[-1] == nodup[0]: nodup.pop() # last point was same as first # remove collinear points i = -3 while i < len(nodup) - 3 and len(nodup) > 2: a, b, c = sorted( [nodup[i], nodup[i + 1], nodup[i + 2]], key=default_sort_key) if Point.is_collinear(a, b, c): nodup[i] = a nodup[i + 1] = None nodup.pop(i + 1) i += 1 vertices = list(filter(lambda x: x is not None, nodup)) if len(vertices) == 3: return GeometryEntity.__new__(cls, *vertices, **kwargs) elif len(vertices) == 2: return Segment(*vertices, **kwargs) else: return Point(*vertices, **kwargs) @property def vertices(self): """The triangle's vertices Returns ======= vertices : tuple Each element in the tuple is a Point See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Triangle, Point >>> t = Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) >>> t.vertices (Point2D(0, 0), Point2D(4, 0), Point2D(4, 3)) """ return self.args def is_similar(t1, t2): """Is another triangle similar to this one. Two triangles are similar if one can be uniformly scaled to the other. Parameters ========== other: Triangle Returns ======= is_similar : boolean See Also ======== sympy.geometry.entity.GeometryEntity.is_similar Examples ======== >>> from sympy import Triangle, Point >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) >>> t2 = Triangle(Point(0, 0), Point(-4, 0), Point(-4, -3)) >>> t1.is_similar(t2) True >>> t2 = Triangle(Point(0, 0), Point(-4, 0), Point(-4, -4)) >>> t1.is_similar(t2) False """ if not isinstance(t2, Polygon): return False s1_1, s1_2, s1_3 = [side.length for side in t1.sides] s2 = [side.length for side in t2.sides] def _are_similar(u1, u2, u3, v1, v2, v3): e1 = simplify(u1/v1) e2 = simplify(u2/v2) e3 = simplify(u3/v3) return bool(e1 == e2) and bool(e2 == e3) # There's only 6 permutations, so write them out return _are_similar(s1_1, s1_2, s1_3, *s2) or \ _are_similar(s1_1, s1_3, s1_2, *s2) or \ _are_similar(s1_2, s1_1, s1_3, *s2) or \ _are_similar(s1_2, s1_3, s1_1, *s2) or \ _are_similar(s1_3, s1_1, s1_2, *s2) or \ _are_similar(s1_3, s1_2, s1_1, *s2) def is_equilateral(self): """Are all the sides the same length? Returns ======= is_equilateral : boolean See Also ======== sympy.geometry.entity.GeometryEntity.is_similar, RegularPolygon is_isosceles, is_right, is_scalene Examples ======== >>> from sympy import Triangle, Point >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) >>> t1.is_equilateral() False >>> from sympy import sqrt >>> t2 = Triangle(Point(0, 0), Point(10, 0), Point(5, 5*sqrt(3))) >>> t2.is_equilateral() True """ return not has_variety(s.length for s in self.sides) def is_isosceles(self): """Are two or more of the sides the same length? Returns ======= is_isosceles : boolean See Also ======== is_equilateral, is_right, is_scalene Examples ======== >>> from sympy import Triangle, Point >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(2, 4)) >>> t1.is_isosceles() True """ return has_dups(s.length for s in self.sides) def is_scalene(self): """Are all the sides of the triangle of different lengths? Returns ======= is_scalene : boolean See Also ======== is_equilateral, is_isosceles, is_right Examples ======== >>> from sympy import Triangle, Point >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(1, 4)) >>> t1.is_scalene() True """ return not has_dups(s.length for s in self.sides) def is_right(self): """Is the triangle right-angled. Returns ======= is_right : boolean See Also ======== sympy.geometry.line.LinearEntity.is_perpendicular is_equilateral, is_isosceles, is_scalene Examples ======== >>> from sympy import Triangle, Point >>> t1 = Triangle(Point(0, 0), Point(4, 0), Point(4, 3)) >>> t1.is_right() True """ s = self.sides return Segment.is_perpendicular(s[0], s[1]) or \ Segment.is_perpendicular(s[1], s[2]) or \ Segment.is_perpendicular(s[0], s[2]) @property def altitudes(self): """The altitudes of the triangle. An altitude of a triangle is a segment through a vertex, perpendicular to the opposite side, with length being the height of the vertex measured from the line containing the side. Returns ======= altitudes : dict The dictionary consists of keys which are vertices and values which are Segments. See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Segment.length Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.altitudes[p1] Segment2D(Point2D(0, 0), Point2D(1/2, 1/2)) """ s = self.sides v = self.vertices return {v[0]: s[1].perpendicular_segment(v[0]), v[1]: s[2].perpendicular_segment(v[1]), v[2]: s[0].perpendicular_segment(v[2])} @property def orthocenter(self): """The orthocenter of the triangle. The orthocenter is the intersection of the altitudes of a triangle. It may lie inside, outside or on the triangle. Returns ======= orthocenter : Point See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.orthocenter Point2D(0, 0) """ a = self.altitudes v = self.vertices return Line(a[v[0]]).intersection(Line(a[v[1]]))[0] @property def circumcenter(self): """The circumcenter of the triangle The circumcenter is the center of the circumcircle. Returns ======= circumcenter : Point See Also ======== sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.circumcenter Point2D(1/2, 1/2) """ a, b, c = [x.perpendicular_bisector() for x in self.sides] return a.intersection(b)[0] @property def circumradius(self): """The radius of the circumcircle of the triangle. Returns ======= circumradius : number of Basic instance See Also ======== sympy.geometry.ellipse.Circle.radius Examples ======== >>> from sympy import Symbol >>> from sympy import Point, Triangle >>> a = Symbol('a') >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, a) >>> t = Triangle(p1, p2, p3) >>> t.circumradius sqrt(a**2/4 + 1/4) """ return Point.distance(self.circumcenter, self.vertices[0]) @property def circumcircle(self): """The circle which passes through the three vertices of the triangle. Returns ======= circumcircle : Circle See Also ======== sympy.geometry.ellipse.Circle Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.circumcircle Circle(Point2D(1/2, 1/2), sqrt(2)/2) """ return Circle(self.circumcenter, self.circumradius) def bisectors(self): """The angle bisectors of the triangle. An angle bisector of a triangle is a straight line through a vertex which cuts the corresponding angle in half. Returns ======= bisectors : dict Each key is a vertex (Point) and each value is the corresponding bisector (Segment). See Also ======== sympy.geometry.point.Point, sympy.geometry.line.Segment Examples ======== >>> from sympy import Point, Triangle, Segment >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> from sympy import sqrt >>> t.bisectors()[p2] == Segment(Point(1, 0), Point(0, sqrt(2) - 1)) True """ # use lines containing sides so containment check during # intersection calculation can be avoided, thus reducing # the processing time for calculating the bisectors s = [Line(l) for l in self.sides] v = self.vertices c = self.incenter l1 = Segment(v[0], Line(v[0], c).intersection(s[1])[0]) l2 = Segment(v[1], Line(v[1], c).intersection(s[2])[0]) l3 = Segment(v[2], Line(v[2], c).intersection(s[0])[0]) return {v[0]: l1, v[1]: l2, v[2]: l3} @property def incenter(self): """The center of the incircle. The incircle is the circle which lies inside the triangle and touches all three sides. Returns ======= incenter : Point See Also ======== incircle, sympy.geometry.point.Point Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.incenter Point2D(1 - sqrt(2)/2, 1 - sqrt(2)/2) """ s = self.sides l = Matrix([s[i].length for i in [1, 2, 0]]) p = sum(l) v = self.vertices x = simplify(l.dot(Matrix([vi.x for vi in v]))/p) y = simplify(l.dot(Matrix([vi.y for vi in v]))/p) return Point(x, y) @property def inradius(self): """The radius of the incircle. Returns ======= inradius : number of Basic instance See Also ======== incircle, sympy.geometry.ellipse.Circle.radius Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(4, 0), Point(0, 3) >>> t = Triangle(p1, p2, p3) >>> t.inradius 1 """ return simplify(2 * self.area / self.perimeter) @property def incircle(self): """The incircle of the triangle. The incircle is the circle which lies inside the triangle and touches all three sides. Returns ======= incircle : Circle See Also ======== sympy.geometry.ellipse.Circle Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(2, 0), Point(0, 2) >>> t = Triangle(p1, p2, p3) >>> t.incircle Circle(Point2D(2 - sqrt(2), 2 - sqrt(2)), 2 - sqrt(2)) """ return Circle(self.incenter, self.inradius) @property def exradii(self): """The radius of excircles of a triangle. An excircle of the triangle is a circle lying outside the triangle, tangent to one of its sides and tangent to the extensions of the other two. Returns ======= exradii : dict See Also ======== sympy.geometry.polygon.Triangle.inradius Examples ======== The exradius touches the side of the triangle to which it is keyed, e.g. the exradius touching side 2 is: >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(6, 0), Point(0, 2) >>> t = Triangle(p1, p2, p3) >>> t.exradii[t.sides[2]] -2 + sqrt(10) References ========== .. [1] http://mathworld.wolfram.com/Exradius.html .. [2] http://mathworld.wolfram.com/Excircles.html """ side = self.sides a = side[0].length b = side[1].length c = side[2].length s = (a+b+c)/2 area = self.area exradii = {self.sides[0]: simplify(area/(s-a)), self.sides[1]: simplify(area/(s-b)), self.sides[2]: simplify(area/(s-c))} return exradii @property def excenters(self): """Excenters of the triangle. An excenter is the center of a circle that is tangent to a side of the triangle and the extensions of the other two sides. Returns ======= excenters : dict Examples ======== The excenters are keyed to the side of the triangle to which their corresponding excircle is tangent: The center is keyed, e.g. the excenter of a circle touching side 0 is: >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(6, 0), Point(0, 2) >>> t = Triangle(p1, p2, p3) >>> t.excenters[t.sides[0]] Point2D(12*sqrt(10), 2/3 + sqrt(10)/3) See Also ======== sympy.geometry.polygon.Triangle.exradii References ========== .. [1] http://mathworld.wolfram.com/Excircles.html """ s = self.sides v = self.vertices a = s[0].length b = s[1].length c = s[2].length x = [v[0].x, v[1].x, v[2].x] y = [v[0].y, v[1].y, v[2].y] exc_coords = { "x1": simplify(-a*x[0]+b*x[1]+c*x[2]/(-a+b+c)), "x2": simplify(a*x[0]-b*x[1]+c*x[2]/(a-b+c)), "x3": simplify(a*x[0]+b*x[1]-c*x[2]/(a+b-c)), "y1": simplify(-a*y[0]+b*y[1]+c*y[2]/(-a+b+c)), "y2": simplify(a*y[0]-b*y[1]+c*y[2]/(a-b+c)), "y3": simplify(a*y[0]+b*y[1]-c*y[2]/(a+b-c)) } excenters = { s[0]: Point(exc_coords["x1"], exc_coords["y1"]), s[1]: Point(exc_coords["x2"], exc_coords["y2"]), s[2]: Point(exc_coords["x3"], exc_coords["y3"]) } return excenters @property def medians(self): """The medians of the triangle. A median of a triangle is a straight line through a vertex and the midpoint of the opposite side, and divides the triangle into two equal areas. Returns ======= medians : dict Each key is a vertex (Point) and each value is the median (Segment) at that point. See Also ======== sympy.geometry.point.Point.midpoint, sympy.geometry.line.Segment.midpoint Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.medians[p1] Segment2D(Point2D(0, 0), Point2D(1/2, 1/2)) """ s = self.sides v = self.vertices return {v[0]: Segment(v[0], s[1].midpoint), v[1]: Segment(v[1], s[2].midpoint), v[2]: Segment(v[2], s[0].midpoint)} @property def medial(self): """The medial triangle of the triangle. The triangle which is formed from the midpoints of the three sides. Returns ======= medial : Triangle See Also ======== sympy.geometry.line.Segment.midpoint Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.medial Triangle(Point2D(1/2, 0), Point2D(1/2, 1/2), Point2D(0, 1/2)) """ s = self.sides return Triangle(s[0].midpoint, s[1].midpoint, s[2].midpoint) @property def nine_point_circle(self): """The nine-point circle of the triangle. Nine-point circle is the circumcircle of the medial triangle, which passes through the feet of altitudes and the middle points of segments connecting the vertices and the orthocenter. Returns ======= nine_point_circle : Circle See also ======== sympy.geometry.line.Segment.midpoint sympy.geometry.polygon.Triangle.medial sympy.geometry.polygon.Triangle.orthocenter Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.nine_point_circle Circle(Point2D(1/4, 1/4), sqrt(2)/4) """ return Circle(*self.medial.vertices) @property def eulerline(self): """The Euler line of the triangle. The line which passes through circumcenter, centroid and orthocenter. Returns ======= eulerline : Line (or Point for equilateral triangles in which case all centers coincide) Examples ======== >>> from sympy import Point, Triangle >>> p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) >>> t = Triangle(p1, p2, p3) >>> t.eulerline Line2D(Point2D(0, 0), Point2D(1/2, 1/2)) """ if self.is_equilateral(): return self.orthocenter return Line(self.orthocenter, self.circumcenter) def rad(d): """Return the radian value for the given degrees (pi = 180 degrees).""" return d*pi/180 def deg(r): """Return the degree value for the given radians (pi = 180 degrees).""" return r/pi*180 def _slope(d): rv = tan(rad(d)) return rv def _asa(d1, l, d2): """Return triangle having side with length l on the x-axis.""" xy = Line((0, 0), slope=_slope(d1)).intersection( Line((l, 0), slope=_slope(180 - d2)))[0] return Triangle((0, 0), (l, 0), xy) def _sss(l1, l2, l3): """Return triangle having side of length l1 on the x-axis.""" c1 = Circle((0, 0), l3) c2 = Circle((l1, 0), l2) inter = [a for a in c1.intersection(c2) if a.y.is_nonnegative] if not inter: return None pt = inter[0] return Triangle((0, 0), (l1, 0), pt) def _sas(l1, d, l2): """Return triangle having side with length l2 on the x-axis.""" p1 = Point(0, 0) p2 = Point(l2, 0) p3 = Point(cos(rad(d))*l1, sin(rad(d))*l1) return Triangle(p1, p2, p3)
0e4a05aa80a71eccdb3074a8f09de55c024460e65f5a4ae955d93f1a47d74303
""" This module implements Holonomic Functions and various operations on them. """ from sympy.core import Add, Mul, Pow from sympy.core.numbers import (NaN, Infinity, NegativeInfinity, Float, I, pi, equal_valued) from sympy.core.singleton import S from sympy.core.sorting import ordered from sympy.core.symbol import Dummy, Symbol from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import binomial, factorial, rf from sympy.functions.elementary.exponential import exp_polar, exp, log from sympy.functions.elementary.hyperbolic import (cosh, sinh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin, sinc) from sympy.functions.special.error_functions import (Ci, Shi, Si, erf, erfc, erfi) from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import hyper, meijerg from sympy.integrals import meijerint from sympy.matrices import Matrix from sympy.polys.rings import PolyElement from sympy.polys.fields import FracElement from sympy.polys.domains import QQ, RR from sympy.polys.polyclasses import DMF from sympy.polys.polyroots import roots from sympy.polys.polytools import Poly from sympy.polys.matrices import DomainMatrix from sympy.printing import sstr from sympy.series.limits import limit from sympy.series.order import Order from sympy.simplify.hyperexpand import hyperexpand from sympy.simplify.simplify import nsimplify from sympy.solvers.solvers import solve from .recurrence import HolonomicSequence, RecurrenceOperator, RecurrenceOperators from .holonomicerrors import (NotPowerSeriesError, NotHyperSeriesError, SingularityError, NotHolonomicError) def _find_nonzero_solution(r, homosys): ones = lambda shape: DomainMatrix.ones(shape, r.domain) particular, nullspace = r._solve(homosys) nullity = nullspace.shape[0] nullpart = ones((1, nullity)) * nullspace sol = (particular + nullpart).transpose() return sol def DifferentialOperators(base, generator): r""" This function is used to create annihilators using ``Dx``. Explanation =========== Returns an Algebra of Differential Operators also called Weyl Algebra and the operator for differentiation i.e. the ``Dx`` operator. Parameters ========== base: Base polynomial ring for the algebra. The base polynomial ring is the ring of polynomials in :math:`x` that will appear as coefficients in the operators. generator: Generator of the algebra which can be either a noncommutative ``Symbol`` or a string. e.g. "Dx" or "D". Examples ======== >>> from sympy import ZZ >>> from sympy.abc import x >>> from sympy.holonomic.holonomic import DifferentialOperators >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') >>> R Univariate Differential Operator Algebra in intermediate Dx over the base ring ZZ[x] >>> Dx*x (1) + (x)*Dx """ ring = DifferentialOperatorAlgebra(base, generator) return (ring, ring.derivative_operator) class DifferentialOperatorAlgebra: r""" An Ore Algebra is a set of noncommutative polynomials in the intermediate ``Dx`` and coefficients in a base polynomial ring :math:`A`. It follows the commutation rule: .. math :: Dxa = \sigma(a)Dx + \delta(a) for :math:`a \subset A`. Where :math:`\sigma: A \Rightarrow A` is an endomorphism and :math:`\delta: A \rightarrow A` is a skew-derivation i.e. :math:`\delta(ab) = \delta(a) b + \sigma(a) \delta(b)`. If one takes the sigma as identity map and delta as the standard derivation then it becomes the algebra of Differential Operators also called a Weyl Algebra i.e. an algebra whose elements are Differential Operators. This class represents a Weyl Algebra and serves as the parent ring for Differential Operators. Examples ======== >>> from sympy import ZZ >>> from sympy import symbols >>> from sympy.holonomic.holonomic import DifferentialOperators >>> x = symbols('x') >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') >>> R Univariate Differential Operator Algebra in intermediate Dx over the base ring ZZ[x] See Also ======== DifferentialOperator """ def __init__(self, base, generator): # the base polynomial ring for the algebra self.base = base # the operator representing differentiation i.e. `Dx` self.derivative_operator = DifferentialOperator( [base.zero, base.one], self) if generator is None: self.gen_symbol = Symbol('Dx', commutative=False) else: if isinstance(generator, str): self.gen_symbol = Symbol(generator, commutative=False) elif isinstance(generator, Symbol): self.gen_symbol = generator def __str__(self): string = 'Univariate Differential Operator Algebra in intermediate '\ + sstr(self.gen_symbol) + ' over the base ring ' + \ (self.base).__str__() return string __repr__ = __str__ def __eq__(self, other): if self.base == other.base and self.gen_symbol == other.gen_symbol: return True else: return False class DifferentialOperator: """ Differential Operators are elements of Weyl Algebra. The Operators are defined by a list of polynomials in the base ring and the parent ring of the Operator i.e. the algebra it belongs to. Explanation =========== Takes a list of polynomials for each power of ``Dx`` and the parent ring which must be an instance of DifferentialOperatorAlgebra. A Differential Operator can be created easily using the operator ``Dx``. See examples below. Examples ======== >>> from sympy.holonomic.holonomic import DifferentialOperator, DifferentialOperators >>> from sympy import ZZ >>> from sympy import symbols >>> x = symbols('x') >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx') >>> DifferentialOperator([0, 1, x**2], R) (1)*Dx + (x**2)*Dx**2 >>> (x*Dx*x + 1 - Dx**2)**2 (2*x**2 + 2*x + 1) + (4*x**3 + 2*x**2 - 4)*Dx + (x**4 - 6*x - 2)*Dx**2 + (-2*x**2)*Dx**3 + (1)*Dx**4 See Also ======== DifferentialOperatorAlgebra """ _op_priority = 20 def __init__(self, list_of_poly, parent): """ Parameters ========== list_of_poly: List of polynomials belonging to the base ring of the algebra. parent: Parent algebra of the operator. """ # the parent ring for this operator # must be an DifferentialOperatorAlgebra object self.parent = parent base = self.parent.base self.x = base.gens[0] if isinstance(base.gens[0], Symbol) else base.gens[0][0] # sequence of polynomials in x for each power of Dx # the list should not have trailing zeroes # represents the operator # convert the expressions into ring elements using from_sympy for i, j in enumerate(list_of_poly): if not isinstance(j, base.dtype): list_of_poly[i] = base.from_sympy(sympify(j)) else: list_of_poly[i] = base.from_sympy(base.to_sympy(j)) self.listofpoly = list_of_poly # highest power of `Dx` self.order = len(self.listofpoly) - 1 def __mul__(self, other): """ Multiplies two DifferentialOperator and returns another DifferentialOperator instance using the commutation rule Dx*a = a*Dx + a' """ listofself = self.listofpoly if not isinstance(other, DifferentialOperator): if not isinstance(other, self.parent.base.dtype): listofother = [self.parent.base.from_sympy(sympify(other))] else: listofother = [other] else: listofother = other.listofpoly # multiplies a polynomial `b` with a list of polynomials def _mul_dmp_diffop(b, listofother): if isinstance(listofother, list): sol = [] for i in listofother: sol.append(i * b) return sol else: return [b * listofother] sol = _mul_dmp_diffop(listofself[0], listofother) # compute Dx^i * b def _mul_Dxi_b(b): sol1 = [self.parent.base.zero] sol2 = [] if isinstance(b, list): for i in b: sol1.append(i) sol2.append(i.diff()) else: sol1.append(self.parent.base.from_sympy(b)) sol2.append(self.parent.base.from_sympy(b).diff()) return _add_lists(sol1, sol2) for i in range(1, len(listofself)): # find Dx^i * b in ith iteration listofother = _mul_Dxi_b(listofother) # solution = solution + listofself[i] * (Dx^i * b) sol = _add_lists(sol, _mul_dmp_diffop(listofself[i], listofother)) return DifferentialOperator(sol, self.parent) def __rmul__(self, other): if not isinstance(other, DifferentialOperator): if not isinstance(other, self.parent.base.dtype): other = (self.parent.base).from_sympy(sympify(other)) sol = [] for j in self.listofpoly: sol.append(other * j) return DifferentialOperator(sol, self.parent) def __add__(self, other): if isinstance(other, DifferentialOperator): sol = _add_lists(self.listofpoly, other.listofpoly) return DifferentialOperator(sol, self.parent) else: list_self = self.listofpoly if not isinstance(other, self.parent.base.dtype): list_other = [((self.parent).base).from_sympy(sympify(other))] else: list_other = [other] sol = [] sol.append(list_self[0] + list_other[0]) sol += list_self[1:] return DifferentialOperator(sol, self.parent) __radd__ = __add__ def __sub__(self, other): return self + (-1) * other def __rsub__(self, other): return (-1) * self + other def __neg__(self): return -1 * self def __truediv__(self, other): return self * (S.One / other) def __pow__(self, n): if n == 1: return self if n == 0: return DifferentialOperator([self.parent.base.one], self.parent) # if self is `Dx` if self.listofpoly == self.parent.derivative_operator.listofpoly: sol = [self.parent.base.zero]*n sol.append(self.parent.base.one) return DifferentialOperator(sol, self.parent) # the general case else: if n % 2 == 1: powreduce = self**(n - 1) return powreduce * self elif n % 2 == 0: powreduce = self**(n / 2) return powreduce * powreduce def __str__(self): listofpoly = self.listofpoly print_str = '' for i, j in enumerate(listofpoly): if j == self.parent.base.zero: continue if i == 0: print_str += '(' + sstr(j) + ')' continue if print_str: print_str += ' + ' if i == 1: print_str += '(' + sstr(j) + ')*%s' %(self.parent.gen_symbol) continue print_str += '(' + sstr(j) + ')' + '*%s**' %(self.parent.gen_symbol) + sstr(i) return print_str __repr__ = __str__ def __eq__(self, other): if isinstance(other, DifferentialOperator): if self.listofpoly == other.listofpoly and self.parent == other.parent: return True else: return False else: if self.listofpoly[0] == other: for i in self.listofpoly[1:]: if i is not self.parent.base.zero: return False return True else: return False def is_singular(self, x0): """ Checks if the differential equation is singular at x0. """ base = self.parent.base return x0 in roots(base.to_sympy(self.listofpoly[-1]), self.x) class HolonomicFunction: r""" A Holonomic Function is a solution to a linear homogeneous ordinary differential equation with polynomial coefficients. This differential equation can also be represented by an annihilator i.e. a Differential Operator ``L`` such that :math:`L.f = 0`. For uniqueness of these functions, initial conditions can also be provided along with the annihilator. Explanation =========== Holonomic functions have closure properties and thus forms a ring. Given two Holonomic Functions f and g, their sum, product, integral and derivative is also a Holonomic Function. For ordinary points initial condition should be a vector of values of the derivatives i.e. :math:`[y(x_0), y'(x_0), y''(x_0) ... ]`. For regular singular points initial conditions can also be provided in this format: :math:`{s0: [C_0, C_1, ...], s1: [C^1_0, C^1_1, ...], ...}` where s0, s1, ... are the roots of indicial equation and vectors :math:`[C_0, C_1, ...], [C^0_0, C^0_1, ...], ...` are the corresponding initial terms of the associated power series. See Examples below. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import QQ >>> from sympy import symbols, S >>> x = symbols('x') >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') >>> p = HolonomicFunction(Dx - 1, x, 0, [1]) # e^x >>> q = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]) # sin(x) >>> p + q # annihilator of e^x + sin(x) HolonomicFunction((-1) + (1)*Dx + (-1)*Dx**2 + (1)*Dx**3, x, 0, [1, 2, 1]) >>> p * q # annihilator of e^x * sin(x) HolonomicFunction((2) + (-2)*Dx + (1)*Dx**2, x, 0, [0, 1]) An example of initial conditions for regular singular points, the indicial equation has only one root `1/2`. >>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}) HolonomicFunction((-1/2) + (x)*Dx, x, 0, {1/2: [1]}) >>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}).to_expr() sqrt(x) To plot a Holonomic Function, one can use `.evalf()` for numerical computation. Here's an example on `sin(x)**2/x` using numpy and matplotlib. >>> import sympy.holonomic # doctest: +SKIP >>> from sympy import var, sin # doctest: +SKIP >>> import matplotlib.pyplot as plt # doctest: +SKIP >>> import numpy as np # doctest: +SKIP >>> var("x") # doctest: +SKIP >>> r = np.linspace(1, 5, 100) # doctest: +SKIP >>> y = sympy.holonomic.expr_to_holonomic(sin(x)**2/x, x0=1).evalf(r) # doctest: +SKIP >>> plt.plot(r, y, label="holonomic function") # doctest: +SKIP >>> plt.show() # doctest: +SKIP """ _op_priority = 20 def __init__(self, annihilator, x, x0=0, y0=None): """ Parameters ========== annihilator: Annihilator of the Holonomic Function, represented by a `DifferentialOperator` object. x: Variable of the function. x0: The point at which initial conditions are stored. Generally an integer. y0: The initial condition. The proper format for the initial condition is described in class docstring. To make the function unique, length of the vector `y0` should be equal to or greater than the order of differential equation. """ # initial condition self.y0 = y0 # the point for initial conditions, default is zero. self.x0 = x0 # differential operator L such that L.f = 0 self.annihilator = annihilator self.x = x def __str__(self): if self._have_init_cond(): str_sol = 'HolonomicFunction(%s, %s, %s, %s)' % (str(self.annihilator),\ sstr(self.x), sstr(self.x0), sstr(self.y0)) else: str_sol = 'HolonomicFunction(%s, %s)' % (str(self.annihilator),\ sstr(self.x)) return str_sol __repr__ = __str__ def unify(self, other): """ Unifies the base polynomial ring of a given two Holonomic Functions. """ R1 = self.annihilator.parent.base R2 = other.annihilator.parent.base dom1 = R1.dom dom2 = R2.dom if R1 == R2: return (self, other) R = (dom1.unify(dom2)).old_poly_ring(self.x) newparent, _ = DifferentialOperators(R, str(self.annihilator.parent.gen_symbol)) sol1 = [R1.to_sympy(i) for i in self.annihilator.listofpoly] sol2 = [R2.to_sympy(i) for i in other.annihilator.listofpoly] sol1 = DifferentialOperator(sol1, newparent) sol2 = DifferentialOperator(sol2, newparent) sol1 = HolonomicFunction(sol1, self.x, self.x0, self.y0) sol2 = HolonomicFunction(sol2, other.x, other.x0, other.y0) return (sol1, sol2) def is_singularics(self): """ Returns True if the function have singular initial condition in the dictionary format. Returns False if the function have ordinary initial condition in the list format. Returns None for all other cases. """ if isinstance(self.y0, dict): return True elif isinstance(self.y0, list): return False def _have_init_cond(self): """ Checks if the function have initial condition. """ return bool(self.y0) def _singularics_to_ord(self): """ Converts a singular initial condition to ordinary if possible. """ a = list(self.y0)[0] b = self.y0[a] if len(self.y0) == 1 and a == int(a) and a > 0: y0 = [] a = int(a) for i in range(a): y0.append(S.Zero) y0 += [j * factorial(a + i) for i, j in enumerate(b)] return HolonomicFunction(self.annihilator, self.x, self.x0, y0) def __add__(self, other): # if the ground domains are different if self.annihilator.parent.base != other.annihilator.parent.base: a, b = self.unify(other) return a + b deg1 = self.annihilator.order deg2 = other.annihilator.order dim = max(deg1, deg2) R = self.annihilator.parent.base K = R.get_field() rowsself = [self.annihilator] rowsother = [other.annihilator] gen = self.annihilator.parent.derivative_operator # constructing annihilators up to order dim for i in range(dim - deg1): diff1 = (gen * rowsself[-1]) rowsself.append(diff1) for i in range(dim - deg2): diff2 = (gen * rowsother[-1]) rowsother.append(diff2) row = rowsself + rowsother # constructing the matrix of the ansatz r = [] for expr in row: p = [] for i in range(dim + 1): if i >= len(expr.listofpoly): p.append(K.zero) else: p.append(K.new(expr.listofpoly[i].rep)) r.append(p) # solving the linear system using gauss jordan solver r = DomainMatrix(r, (len(row), dim+1), K).transpose() homosys = DomainMatrix.zeros((dim+1, 1), K) sol = _find_nonzero_solution(r, homosys) # if a solution is not obtained then increasing the order by 1 in each # iteration while sol.is_zero_matrix: dim += 1 diff1 = (gen * rowsself[-1]) rowsself.append(diff1) diff2 = (gen * rowsother[-1]) rowsother.append(diff2) row = rowsself + rowsother r = [] for expr in row: p = [] for i in range(dim + 1): if i >= len(expr.listofpoly): p.append(K.zero) else: p.append(K.new(expr.listofpoly[i].rep)) r.append(p) # solving the linear system using gauss jordan solver r = DomainMatrix(r, (len(row), dim+1), K).transpose() homosys = DomainMatrix.zeros((dim+1, 1), K) sol = _find_nonzero_solution(r, homosys) # taking only the coefficients needed to multiply with `self` # can be also be done the other way by taking R.H.S and multiplying with # `other` sol = sol.flat()[:dim + 1 - deg1] sol1 = _normalize(sol, self.annihilator.parent) # annihilator of the solution sol = sol1 * (self.annihilator) sol = _normalize(sol.listofpoly, self.annihilator.parent, negative=False) if not (self._have_init_cond() and other._have_init_cond()): return HolonomicFunction(sol, self.x) # both the functions have ordinary initial conditions if self.is_singularics() == False and other.is_singularics() == False: # directly add the corresponding value if self.x0 == other.x0: # try to extended the initial conditions # using the annihilator y1 = _extend_y0(self, sol.order) y2 = _extend_y0(other, sol.order) y0 = [a + b for a, b in zip(y1, y2)] return HolonomicFunction(sol, self.x, self.x0, y0) else: # change the initial conditions to a same point selfat0 = self.annihilator.is_singular(0) otherat0 = other.annihilator.is_singular(0) if self.x0 == 0 and not selfat0 and not otherat0: return self + other.change_ics(0) elif other.x0 == 0 and not selfat0 and not otherat0: return self.change_ics(0) + other else: selfatx0 = self.annihilator.is_singular(self.x0) otheratx0 = other.annihilator.is_singular(self.x0) if not selfatx0 and not otheratx0: return self + other.change_ics(self.x0) else: return self.change_ics(other.x0) + other if self.x0 != other.x0: return HolonomicFunction(sol, self.x) # if the functions have singular_ics y1 = None y2 = None if self.is_singularics() == False and other.is_singularics() == True: # convert the ordinary initial condition to singular. _y0 = [j / factorial(i) for i, j in enumerate(self.y0)] y1 = {S.Zero: _y0} y2 = other.y0 elif self.is_singularics() == True and other.is_singularics() == False: _y0 = [j / factorial(i) for i, j in enumerate(other.y0)] y1 = self.y0 y2 = {S.Zero: _y0} elif self.is_singularics() == True and other.is_singularics() == True: y1 = self.y0 y2 = other.y0 # computing singular initial condition for the result # taking union of the series terms of both functions y0 = {} for i in y1: # add corresponding initial terms if the power # on `x` is same if i in y2: y0[i] = [a + b for a, b in zip(y1[i], y2[i])] else: y0[i] = y1[i] for i in y2: if i not in y1: y0[i] = y2[i] return HolonomicFunction(sol, self.x, self.x0, y0) def integrate(self, limits, initcond=False): """ Integrates the given holonomic function. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import QQ >>> from sympy import symbols >>> x = symbols('x') >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') >>> HolonomicFunction(Dx - 1, x, 0, [1]).integrate((x, 0, x)) # e^x - 1 HolonomicFunction((-1)*Dx + (1)*Dx**2, x, 0, [0, 1]) >>> HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]).integrate((x, 0, x)) HolonomicFunction((1)*Dx + (1)*Dx**3, x, 0, [0, 1, 0]) """ # to get the annihilator, just multiply by Dx from right D = self.annihilator.parent.derivative_operator # if the function have initial conditions of the series format if self.is_singularics() == True: r = self._singularics_to_ord() if r: return r.integrate(limits, initcond=initcond) # computing singular initial condition for the function # produced after integration. y0 = {} for i in self.y0: c = self.y0[i] c2 = [] for j, cj in enumerate(c): if cj == 0: c2.append(S.Zero) # if power on `x` is -1, the integration becomes log(x) # TODO: Implement this case elif i + j + 1 == 0: raise NotImplementedError("logarithmic terms in the series are not supported") else: c2.append(cj / S(i + j + 1)) y0[i + 1] = c2 if hasattr(limits, "__iter__"): raise NotImplementedError("Definite integration for singular initial conditions") return HolonomicFunction(self.annihilator * D, self.x, self.x0, y0) # if no initial conditions are available for the function if not self._have_init_cond(): if initcond: return HolonomicFunction(self.annihilator * D, self.x, self.x0, [S.Zero]) return HolonomicFunction(self.annihilator * D, self.x) # definite integral # initial conditions for the answer will be stored at point `a`, # where `a` is the lower limit of the integrand if hasattr(limits, "__iter__"): if len(limits) == 3 and limits[0] == self.x: x0 = self.x0 a = limits[1] b = limits[2] definite = True else: definite = False y0 = [S.Zero] y0 += self.y0 indefinite_integral = HolonomicFunction(self.annihilator * D, self.x, self.x0, y0) if not definite: return indefinite_integral # use evalf to get the values at `a` if x0 != a: try: indefinite_expr = indefinite_integral.to_expr() except (NotHyperSeriesError, NotPowerSeriesError): indefinite_expr = None if indefinite_expr: lower = indefinite_expr.subs(self.x, a) if isinstance(lower, NaN): lower = indefinite_expr.limit(self.x, a) else: lower = indefinite_integral.evalf(a) if b == self.x: y0[0] = y0[0] - lower return HolonomicFunction(self.annihilator * D, self.x, x0, y0) elif S(b).is_Number: if indefinite_expr: upper = indefinite_expr.subs(self.x, b) if isinstance(upper, NaN): upper = indefinite_expr.limit(self.x, b) else: upper = indefinite_integral.evalf(b) return upper - lower # if the upper limit is `x`, the answer will be a function if b == self.x: return HolonomicFunction(self.annihilator * D, self.x, a, y0) # if the upper limits is a Number, a numerical value will be returned elif S(b).is_Number: try: s = HolonomicFunction(self.annihilator * D, self.x, a,\ y0).to_expr() indefinite = s.subs(self.x, b) if not isinstance(indefinite, NaN): return indefinite else: return s.limit(self.x, b) except (NotHyperSeriesError, NotPowerSeriesError): return HolonomicFunction(self.annihilator * D, self.x, a, y0).evalf(b) return HolonomicFunction(self.annihilator * D, self.x) def diff(self, *args, **kwargs): r""" Differentiation of the given Holonomic function. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import ZZ >>> from sympy import symbols >>> x = symbols('x') >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx') >>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).diff().to_expr() cos(x) >>> HolonomicFunction(Dx - 2, x, 0, [1]).diff().to_expr() 2*exp(2*x) See Also ======== integrate """ kwargs.setdefault('evaluate', True) if args: if args[0] != self.x: return S.Zero elif len(args) == 2: sol = self for i in range(args[1]): sol = sol.diff(args[0]) return sol ann = self.annihilator # if the function is constant. if ann.listofpoly[0] == ann.parent.base.zero and ann.order == 1: return S.Zero # if the coefficient of y in the differential equation is zero. # a shifting is done to compute the answer in this case. elif ann.listofpoly[0] == ann.parent.base.zero: sol = DifferentialOperator(ann.listofpoly[1:], ann.parent) if self._have_init_cond(): # if ordinary initial condition if self.is_singularics() == False: return HolonomicFunction(sol, self.x, self.x0, self.y0[1:]) # TODO: support for singular initial condition return HolonomicFunction(sol, self.x) else: return HolonomicFunction(sol, self.x) # the general algorithm R = ann.parent.base K = R.get_field() seq_dmf = [K.new(i.rep) for i in ann.listofpoly] # -y = a1*y'/a0 + a2*y''/a0 ... + an*y^n/a0 rhs = [i / seq_dmf[0] for i in seq_dmf[1:]] rhs.insert(0, K.zero) # differentiate both lhs and rhs sol = _derivate_diff_eq(rhs) # add the term y' in lhs to rhs sol = _add_lists(sol, [K.zero, K.one]) sol = _normalize(sol[1:], self.annihilator.parent, negative=False) if not self._have_init_cond() or self.is_singularics() == True: return HolonomicFunction(sol, self.x) y0 = _extend_y0(self, sol.order + 1)[1:] return HolonomicFunction(sol, self.x, self.x0, y0) def __eq__(self, other): if self.annihilator == other.annihilator: if self.x == other.x: if self._have_init_cond() and other._have_init_cond(): if self.x0 == other.x0 and self.y0 == other.y0: return True else: return False else: return True else: return False else: return False def __mul__(self, other): ann_self = self.annihilator if not isinstance(other, HolonomicFunction): other = sympify(other) if other.has(self.x): raise NotImplementedError(" Can't multiply a HolonomicFunction and expressions/functions.") if not self._have_init_cond(): return self else: y0 = _extend_y0(self, ann_self.order) y1 = [] for j in y0: y1.append((Poly.new(j, self.x) * other).rep) return HolonomicFunction(ann_self, self.x, self.x0, y1) if self.annihilator.parent.base != other.annihilator.parent.base: a, b = self.unify(other) return a * b ann_other = other.annihilator list_self = [] list_other = [] a = ann_self.order b = ann_other.order R = ann_self.parent.base K = R.get_field() for j in ann_self.listofpoly: list_self.append(K.new(j.rep)) for j in ann_other.listofpoly: list_other.append(K.new(j.rep)) # will be used to reduce the degree self_red = [-list_self[i] / list_self[a] for i in range(a)] other_red = [-list_other[i] / list_other[b] for i in range(b)] # coeff_mull[i][j] is the coefficient of Dx^i(f).Dx^j(g) coeff_mul = [[K.zero for i in range(b + 1)] for j in range(a + 1)] coeff_mul[0][0] = K.one # making the ansatz lin_sys_elements = [[coeff_mul[i][j] for i in range(a) for j in range(b)]] lin_sys = DomainMatrix(lin_sys_elements, (1, a*b), K).transpose() homo_sys = DomainMatrix.zeros((a*b, 1), K) sol = _find_nonzero_solution(lin_sys, homo_sys) # until a non trivial solution is found while sol.is_zero_matrix: # updating the coefficients Dx^i(f).Dx^j(g) for next degree for i in range(a - 1, -1, -1): for j in range(b - 1, -1, -1): coeff_mul[i][j + 1] += coeff_mul[i][j] coeff_mul[i + 1][j] += coeff_mul[i][j] if isinstance(coeff_mul[i][j], K.dtype): coeff_mul[i][j] = DMFdiff(coeff_mul[i][j]) else: coeff_mul[i][j] = coeff_mul[i][j].diff(self.x) # reduce the terms to lower power using annihilators of f, g for i in range(a + 1): if not coeff_mul[i][b].is_zero: for j in range(b): coeff_mul[i][j] += other_red[j] * \ coeff_mul[i][b] coeff_mul[i][b] = K.zero # not d2 + 1, as that is already covered in previous loop for j in range(b): if not coeff_mul[a][j] == 0: for i in range(a): coeff_mul[i][j] += self_red[i] * \ coeff_mul[a][j] coeff_mul[a][j] = K.zero lin_sys_elements.append([coeff_mul[i][j] for i in range(a) for j in range(b)]) lin_sys = DomainMatrix(lin_sys_elements, (len(lin_sys_elements), a*b), K).transpose() sol = _find_nonzero_solution(lin_sys, homo_sys) sol_ann = _normalize(sol.flat(), self.annihilator.parent, negative=False) if not (self._have_init_cond() and other._have_init_cond()): return HolonomicFunction(sol_ann, self.x) if self.is_singularics() == False and other.is_singularics() == False: # if both the conditions are at same point if self.x0 == other.x0: # try to find more initial conditions y0_self = _extend_y0(self, sol_ann.order) y0_other = _extend_y0(other, sol_ann.order) # h(x0) = f(x0) * g(x0) y0 = [y0_self[0] * y0_other[0]] # coefficient of Dx^j(f)*Dx^i(g) in Dx^i(fg) for i in range(1, min(len(y0_self), len(y0_other))): coeff = [[0 for i in range(i + 1)] for j in range(i + 1)] for j in range(i + 1): for k in range(i + 1): if j + k == i: coeff[j][k] = binomial(i, j) sol = 0 for j in range(i + 1): for k in range(i + 1): sol += coeff[j][k]* y0_self[j] * y0_other[k] y0.append(sol) return HolonomicFunction(sol_ann, self.x, self.x0, y0) # if the points are different, consider one else: selfat0 = self.annihilator.is_singular(0) otherat0 = other.annihilator.is_singular(0) if self.x0 == 0 and not selfat0 and not otherat0: return self * other.change_ics(0) elif other.x0 == 0 and not selfat0 and not otherat0: return self.change_ics(0) * other else: selfatx0 = self.annihilator.is_singular(self.x0) otheratx0 = other.annihilator.is_singular(self.x0) if not selfatx0 and not otheratx0: return self * other.change_ics(self.x0) else: return self.change_ics(other.x0) * other if self.x0 != other.x0: return HolonomicFunction(sol_ann, self.x) # if the functions have singular_ics y1 = None y2 = None if self.is_singularics() == False and other.is_singularics() == True: _y0 = [j / factorial(i) for i, j in enumerate(self.y0)] y1 = {S.Zero: _y0} y2 = other.y0 elif self.is_singularics() == True and other.is_singularics() == False: _y0 = [j / factorial(i) for i, j in enumerate(other.y0)] y1 = self.y0 y2 = {S.Zero: _y0} elif self.is_singularics() == True and other.is_singularics() == True: y1 = self.y0 y2 = other.y0 y0 = {} # multiply every possible pair of the series terms for i in y1: for j in y2: k = min(len(y1[i]), len(y2[j])) c = [] for a in range(k): s = S.Zero for b in range(a + 1): s += y1[i][b] * y2[j][a - b] c.append(s) if not i + j in y0: y0[i + j] = c else: y0[i + j] = [a + b for a, b in zip(c, y0[i + j])] return HolonomicFunction(sol_ann, self.x, self.x0, y0) __rmul__ = __mul__ def __sub__(self, other): return self + other * -1 def __rsub__(self, other): return self * -1 + other def __neg__(self): return -1 * self def __truediv__(self, other): return self * (S.One / other) def __pow__(self, n): if self.annihilator.order <= 1: ann = self.annihilator parent = ann.parent if self.y0 is None: y0 = None else: y0 = [list(self.y0)[0] ** n] p0 = ann.listofpoly[0] p1 = ann.listofpoly[1] p0 = (Poly.new(p0, self.x) * n).rep sol = [parent.base.to_sympy(i) for i in [p0, p1]] dd = DifferentialOperator(sol, parent) return HolonomicFunction(dd, self.x, self.x0, y0) if n < 0: raise NotHolonomicError("Negative Power on a Holonomic Function") if n == 0: Dx = self.annihilator.parent.derivative_operator return HolonomicFunction(Dx, self.x, S.Zero, [S.One]) if n == 1: return self else: if n % 2 == 1: powreduce = self**(n - 1) return powreduce * self elif n % 2 == 0: powreduce = self**(n / 2) return powreduce * powreduce def degree(self): """ Returns the highest power of `x` in the annihilator. """ sol = [i.degree() for i in self.annihilator.listofpoly] return max(sol) def composition(self, expr, *args, **kwargs): """ Returns function after composition of a holonomic function with an algebraic function. The method cannot compute initial conditions for the result by itself, so they can be also be provided. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import QQ >>> from sympy import symbols >>> x = symbols('x') >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') >>> HolonomicFunction(Dx - 1, x).composition(x**2, 0, [1]) # e^(x**2) HolonomicFunction((-2*x) + (1)*Dx, x, 0, [1]) >>> HolonomicFunction(Dx**2 + 1, x).composition(x**2 - 1, 1, [1, 0]) HolonomicFunction((4*x**3) + (-1)*Dx + (x)*Dx**2, x, 1, [1, 0]) See Also ======== from_hyper """ R = self.annihilator.parent a = self.annihilator.order diff = expr.diff(self.x) listofpoly = self.annihilator.listofpoly for i, j in enumerate(listofpoly): if isinstance(j, self.annihilator.parent.base.dtype): listofpoly[i] = self.annihilator.parent.base.to_sympy(j) r = listofpoly[a].subs({self.x:expr}) subs = [-listofpoly[i].subs({self.x:expr}) / r for i in range (a)] coeffs = [S.Zero for i in range(a)] # coeffs[i] == coeff of (D^i f)(a) in D^k (f(a)) coeffs[0] = S.One system = [coeffs] homogeneous = Matrix([[S.Zero for i in range(a)]]).transpose() while True: coeffs_next = [p.diff(self.x) for p in coeffs] for i in range(a - 1): coeffs_next[i + 1] += (coeffs[i] * diff) for i in range(a): coeffs_next[i] += (coeffs[-1] * subs[i] * diff) coeffs = coeffs_next # check for linear relations system.append(coeffs) sol, taus = (Matrix(system).transpose() ).gauss_jordan_solve(homogeneous) if sol.is_zero_matrix is not True: break tau = list(taus)[0] sol = sol.subs(tau, 1) sol = _normalize(sol[0:], R, negative=False) # if initial conditions are given for the resulting function if args: return HolonomicFunction(sol, self.x, args[0], args[1]) return HolonomicFunction(sol, self.x) def to_sequence(self, lb=True): r""" Finds recurrence relation for the coefficients in the series expansion of the function about :math:`x_0`, where :math:`x_0` is the point at which the initial condition is stored. Explanation =========== If the point :math:`x_0` is ordinary, solution of the form :math:`[(R, n_0)]` is returned. Where :math:`R` is the recurrence relation and :math:`n_0` is the smallest ``n`` for which the recurrence holds true. If the point :math:`x_0` is regular singular, a list of solutions in the format :math:`(R, p, n_0)` is returned, i.e. `[(R, p, n_0), ... ]`. Each tuple in this vector represents a recurrence relation :math:`R` associated with a root of the indicial equation ``p``. Conditions of a different format can also be provided in this case, see the docstring of HolonomicFunction class. If it's not possible to numerically compute a initial condition, it is returned as a symbol :math:`C_j`, denoting the coefficient of :math:`(x - x_0)^j` in the power series about :math:`x_0`. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import QQ >>> from sympy import symbols, S >>> x = symbols('x') >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') >>> HolonomicFunction(Dx - 1, x, 0, [1]).to_sequence() [(HolonomicSequence((-1) + (n + 1)Sn, n), u(0) = 1, 0)] >>> HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]).to_sequence() [(HolonomicSequence((n**2) + (n**2 + n)Sn, n), u(0) = 0, u(1) = 1, u(2) = -1/2, 2)] >>> HolonomicFunction(-S(1)/2 + x*Dx, x, 0, {S(1)/2: [1]}).to_sequence() [(HolonomicSequence((n), n), u(0) = 1, 1/2, 1)] See Also ======== HolonomicFunction.series References ========== .. [1] https://hal.inria.fr/inria-00070025/document .. [2] http://www.risc.jku.at/publications/download/risc_2244/DIPLFORM.pdf """ if self.x0 != 0: return self.shift_x(self.x0).to_sequence() # check whether a power series exists if the point is singular if self.annihilator.is_singular(self.x0): return self._frobenius(lb=lb) dict1 = {} n = Symbol('n', integer=True) dom = self.annihilator.parent.base.dom R, _ = RecurrenceOperators(dom.old_poly_ring(n), 'Sn') # substituting each term of the form `x^k Dx^j` in the # annihilator, according to the formula below: # x^k Dx^j = Sum(rf(n + 1 - k, j) * a(n + j - k) * x^n, (n, k, oo)) # for explanation see [2]. for i, j in enumerate(self.annihilator.listofpoly): listofdmp = j.all_coeffs() degree = len(listofdmp) - 1 for k in range(degree + 1): coeff = listofdmp[degree - k] if coeff == 0: continue if (i - k, k) in dict1: dict1[(i - k, k)] += (dom.to_sympy(coeff) * rf(n - k + 1, i)) else: dict1[(i - k, k)] = (dom.to_sympy(coeff) * rf(n - k + 1, i)) sol = [] keylist = [i[0] for i in dict1] lower = min(keylist) upper = max(keylist) degree = self.degree() # the recurrence relation holds for all values of # n greater than smallest_n, i.e. n >= smallest_n smallest_n = lower + degree dummys = {} eqs = [] unknowns = [] # an appropriate shift of the recurrence for j in range(lower, upper + 1): if j in keylist: temp = S.Zero for k in dict1.keys(): if k[0] == j: temp += dict1[k].subs(n, n - lower) sol.append(temp) else: sol.append(S.Zero) # the recurrence relation sol = RecurrenceOperator(sol, R) # computing the initial conditions for recurrence order = sol.order all_roots = roots(R.base.to_sympy(sol.listofpoly[-1]), n, filter='Z') all_roots = all_roots.keys() if all_roots: max_root = max(all_roots) + 1 smallest_n = max(max_root, smallest_n) order += smallest_n y0 = _extend_y0(self, order) u0 = [] # u(n) = y^n(0)/factorial(n) for i, j in enumerate(y0): u0.append(j / factorial(i)) # if sufficient conditions can't be computed then # try to use the series method i.e. # equate the coefficients of x^k in the equation formed by # substituting the series in differential equation, to zero. if len(u0) < order: for i in range(degree): eq = S.Zero for j in dict1: if i + j[0] < 0: dummys[i + j[0]] = S.Zero elif i + j[0] < len(u0): dummys[i + j[0]] = u0[i + j[0]] elif not i + j[0] in dummys: dummys[i + j[0]] = Symbol('C_%s' %(i + j[0])) unknowns.append(dummys[i + j[0]]) if j[1] <= i: eq += dict1[j].subs(n, i) * dummys[i + j[0]] eqs.append(eq) # solve the system of equations formed soleqs = solve(eqs, *unknowns) if isinstance(soleqs, dict): for i in range(len(u0), order): if i not in dummys: dummys[i] = Symbol('C_%s' %i) if dummys[i] in soleqs: u0.append(soleqs[dummys[i]]) else: u0.append(dummys[i]) if lb: return [(HolonomicSequence(sol, u0), smallest_n)] return [HolonomicSequence(sol, u0)] for i in range(len(u0), order): if i not in dummys: dummys[i] = Symbol('C_%s' %i) s = False for j in soleqs: if dummys[i] in j: u0.append(j[dummys[i]]) s = True if not s: u0.append(dummys[i]) if lb: return [(HolonomicSequence(sol, u0), smallest_n)] return [HolonomicSequence(sol, u0)] def _frobenius(self, lb=True): # compute the roots of indicial equation indicialroots = self._indicial() reals = [] compl = [] for i in ordered(indicialroots.keys()): if i.is_real: reals.extend([i] * indicialroots[i]) else: a, b = i.as_real_imag() compl.extend([(i, a, b)] * indicialroots[i]) # sort the roots for a fixed ordering of solution compl.sort(key=lambda x : x[1]) compl.sort(key=lambda x : x[2]) reals.sort() # grouping the roots, roots differ by an integer are put in the same group. grp = [] for i in reals: intdiff = False if len(grp) == 0: grp.append([i]) continue for j in grp: if int(j[0] - i) == j[0] - i: j.append(i) intdiff = True break if not intdiff: grp.append([i]) # True if none of the roots differ by an integer i.e. # each element in group have only one member independent = True if all(len(i) == 1 for i in grp) else False allpos = all(i >= 0 for i in reals) allint = all(int(i) == i for i in reals) # if initial conditions are provided # then use them. if self.is_singularics() == True: rootstoconsider = [] for i in ordered(self.y0.keys()): for j in ordered(indicialroots.keys()): if equal_valued(j, i): rootstoconsider.append(i) elif allpos and allint: rootstoconsider = [min(reals)] elif independent: rootstoconsider = [i[0] for i in grp] + [j[0] for j in compl] elif not allint: rootstoconsider = [] for i in reals: if not int(i) == i: rootstoconsider.append(i) elif not allpos: if not self._have_init_cond() or S(self.y0[0]).is_finite == False: rootstoconsider = [min(reals)] else: posroots = [] for i in reals: if i >= 0: posroots.append(i) rootstoconsider = [min(posroots)] n = Symbol('n', integer=True) dom = self.annihilator.parent.base.dom R, _ = RecurrenceOperators(dom.old_poly_ring(n), 'Sn') finalsol = [] char = ord('C') for p in rootstoconsider: dict1 = {} for i, j in enumerate(self.annihilator.listofpoly): listofdmp = j.all_coeffs() degree = len(listofdmp) - 1 for k in range(degree + 1): coeff = listofdmp[degree - k] if coeff == 0: continue if (i - k, k - i) in dict1: dict1[(i - k, k - i)] += (dom.to_sympy(coeff) * rf(n - k + 1 + p, i)) else: dict1[(i - k, k - i)] = (dom.to_sympy(coeff) * rf(n - k + 1 + p, i)) sol = [] keylist = [i[0] for i in dict1] lower = min(keylist) upper = max(keylist) degree = max([i[1] for i in dict1]) degree2 = min([i[1] for i in dict1]) smallest_n = lower + degree dummys = {} eqs = [] unknowns = [] for j in range(lower, upper + 1): if j in keylist: temp = S.Zero for k in dict1.keys(): if k[0] == j: temp += dict1[k].subs(n, n - lower) sol.append(temp) else: sol.append(S.Zero) # the recurrence relation sol = RecurrenceOperator(sol, R) # computing the initial conditions for recurrence order = sol.order all_roots = roots(R.base.to_sympy(sol.listofpoly[-1]), n, filter='Z') all_roots = all_roots.keys() if all_roots: max_root = max(all_roots) + 1 smallest_n = max(max_root, smallest_n) order += smallest_n u0 = [] if self.is_singularics() == True: u0 = self.y0[p] elif self.is_singularics() == False and p >= 0 and int(p) == p and len(rootstoconsider) == 1: y0 = _extend_y0(self, order + int(p)) # u(n) = y^n(0)/factorial(n) if len(y0) > int(p): for i in range(int(p), len(y0)): u0.append(y0[i] / factorial(i)) if len(u0) < order: for i in range(degree2, degree): eq = S.Zero for j in dict1: if i + j[0] < 0: dummys[i + j[0]] = S.Zero elif i + j[0] < len(u0): dummys[i + j[0]] = u0[i + j[0]] elif not i + j[0] in dummys: letter = chr(char) + '_%s' %(i + j[0]) dummys[i + j[0]] = Symbol(letter) unknowns.append(dummys[i + j[0]]) if j[1] <= i: eq += dict1[j].subs(n, i) * dummys[i + j[0]] eqs.append(eq) # solve the system of equations formed soleqs = solve(eqs, *unknowns) if isinstance(soleqs, dict): for i in range(len(u0), order): if i not in dummys: letter = chr(char) + '_%s' %i dummys[i] = Symbol(letter) if dummys[i] in soleqs: u0.append(soleqs[dummys[i]]) else: u0.append(dummys[i]) if lb: finalsol.append((HolonomicSequence(sol, u0), p, smallest_n)) continue else: finalsol.append((HolonomicSequence(sol, u0), p)) continue for i in range(len(u0), order): if i not in dummys: letter = chr(char) + '_%s' %i dummys[i] = Symbol(letter) s = False for j in soleqs: if dummys[i] in j: u0.append(j[dummys[i]]) s = True if not s: u0.append(dummys[i]) if lb: finalsol.append((HolonomicSequence(sol, u0), p, smallest_n)) else: finalsol.append((HolonomicSequence(sol, u0), p)) char += 1 return finalsol def series(self, n=6, coefficient=False, order=True, _recur=None): r""" Finds the power series expansion of given holonomic function about :math:`x_0`. Explanation =========== A list of series might be returned if :math:`x_0` is a regular point with multiple roots of the indicial equation. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import QQ >>> from sympy import symbols >>> x = symbols('x') >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') >>> HolonomicFunction(Dx - 1, x, 0, [1]).series() # e^x 1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + O(x**6) >>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).series(n=8) # sin(x) x - x**3/6 + x**5/120 - x**7/5040 + O(x**8) See Also ======== HolonomicFunction.to_sequence """ if _recur is None: recurrence = self.to_sequence() else: recurrence = _recur if isinstance(recurrence, tuple) and len(recurrence) == 2: recurrence = recurrence[0] constantpower = 0 elif isinstance(recurrence, tuple) and len(recurrence) == 3: constantpower = recurrence[1] recurrence = recurrence[0] elif len(recurrence) == 1 and len(recurrence[0]) == 2: recurrence = recurrence[0][0] constantpower = 0 elif len(recurrence) == 1 and len(recurrence[0]) == 3: constantpower = recurrence[0][1] recurrence = recurrence[0][0] else: sol = [] for i in recurrence: sol.append(self.series(_recur=i)) return sol n = n - int(constantpower) l = len(recurrence.u0) - 1 k = recurrence.recurrence.order x = self.x x0 = self.x0 seq_dmp = recurrence.recurrence.listofpoly R = recurrence.recurrence.parent.base K = R.get_field() seq = [] for i, j in enumerate(seq_dmp): seq.append(K.new(j.rep)) sub = [-seq[i] / seq[k] for i in range(k)] sol = [i for i in recurrence.u0] if l + 1 >= n: pass else: # use the initial conditions to find the next term for i in range(l + 1 - k, n - k): coeff = S.Zero for j in range(k): if i + j >= 0: coeff += DMFsubs(sub[j], i) * sol[i + j] sol.append(coeff) if coefficient: return sol ser = S.Zero for i, j in enumerate(sol): ser += x**(i + constantpower) * j if order: ser += Order(x**(n + int(constantpower)), x) if x0 != 0: return ser.subs(x, x - x0) return ser def _indicial(self): """ Computes roots of the Indicial equation. """ if self.x0 != 0: return self.shift_x(self.x0)._indicial() list_coeff = self.annihilator.listofpoly R = self.annihilator.parent.base x = self.x s = R.zero y = R.one def _pole_degree(poly): root_all = roots(R.to_sympy(poly), x, filter='Z') if 0 in root_all.keys(): return root_all[0] else: return 0 degree = [j.degree() for j in list_coeff] degree = max(degree) inf = 10 * (max(1, degree) + max(1, self.annihilator.order)) deg = lambda q: inf if q.is_zero else _pole_degree(q) b = deg(list_coeff[0]) for j in range(1, len(list_coeff)): b = min(b, deg(list_coeff[j]) - j) for i, j in enumerate(list_coeff): listofdmp = j.all_coeffs() degree = len(listofdmp) - 1 if - i - b <= 0 and degree - i - b >= 0: s = s + listofdmp[degree - i - b] * y y *= x - i return roots(R.to_sympy(s), x) def evalf(self, points, method='RK4', h=0.05, derivatives=False): r""" Finds numerical value of a holonomic function using numerical methods. (RK4 by default). A set of points (real or complex) must be provided which will be the path for the numerical integration. Explanation =========== The path should be given as a list :math:`[x_1, x_2, \dots x_n]`. The numerical values will be computed at each point in this order :math:`x_1 \rightarrow x_2 \rightarrow x_3 \dots \rightarrow x_n`. Returns values of the function at :math:`x_1, x_2, \dots x_n` in a list. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import QQ >>> from sympy import symbols >>> x = symbols('x') >>> R, Dx = DifferentialOperators(QQ.old_poly_ring(x),'Dx') A straight line on the real axis from (0 to 1) >>> r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1] Runge-Kutta 4th order on e^x from 0.1 to 1. Exact solution at 1 is 2.71828182845905 >>> HolonomicFunction(Dx - 1, x, 0, [1]).evalf(r) [1.10517083333333, 1.22140257085069, 1.34985849706254, 1.49182424008069, 1.64872063859684, 1.82211796209193, 2.01375162659678, 2.22553956329232, 2.45960141378007, 2.71827974413517] Euler's method for the same >>> HolonomicFunction(Dx - 1, x, 0, [1]).evalf(r, method='Euler') [1.1, 1.21, 1.331, 1.4641, 1.61051, 1.771561, 1.9487171, 2.14358881, 2.357947691, 2.5937424601] One can also observe that the value obtained using Runge-Kutta 4th order is much more accurate than Euler's method. """ from sympy.holonomic.numerical import _evalf lp = False # if a point `b` is given instead of a mesh if not hasattr(points, "__iter__"): lp = True b = S(points) if self.x0 == b: return _evalf(self, [b], method=method, derivatives=derivatives)[-1] if not b.is_Number: raise NotImplementedError a = self.x0 if a > b: h = -h n = int((b - a) / h) points = [a + h] for i in range(n - 1): points.append(points[-1] + h) for i in roots(self.annihilator.parent.base.to_sympy(self.annihilator.listofpoly[-1]), self.x): if i == self.x0 or i in points: raise SingularityError(self, i) if lp: return _evalf(self, points, method=method, derivatives=derivatives)[-1] return _evalf(self, points, method=method, derivatives=derivatives) def change_x(self, z): """ Changes only the variable of Holonomic Function, for internal purposes. For composition use HolonomicFunction.composition() """ dom = self.annihilator.parent.base.dom R = dom.old_poly_ring(z) parent, _ = DifferentialOperators(R, 'Dx') sol = [] for j in self.annihilator.listofpoly: sol.append(R(j.rep)) sol = DifferentialOperator(sol, parent) return HolonomicFunction(sol, z, self.x0, self.y0) def shift_x(self, a): """ Substitute `x + a` for `x`. """ x = self.x listaftershift = self.annihilator.listofpoly base = self.annihilator.parent.base sol = [base.from_sympy(base.to_sympy(i).subs(x, x + a)) for i in listaftershift] sol = DifferentialOperator(sol, self.annihilator.parent) x0 = self.x0 - a if not self._have_init_cond(): return HolonomicFunction(sol, x) return HolonomicFunction(sol, x, x0, self.y0) def to_hyper(self, as_list=False, _recur=None): r""" Returns a hypergeometric function (or linear combination of them) representing the given holonomic function. Explanation =========== Returns an answer of the form: `a_1 \cdot x^{b_1} \cdot{hyper()} + a_2 \cdot x^{b_2} \cdot{hyper()} \dots` This is very useful as one can now use ``hyperexpand`` to find the symbolic expressions/functions. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import ZZ >>> from sympy import symbols >>> x = symbols('x') >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx') >>> # sin(x) >>> HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).to_hyper() x*hyper((), (3/2,), -x**2/4) >>> # exp(x) >>> HolonomicFunction(Dx - 1, x, 0, [1]).to_hyper() hyper((), (), x) See Also ======== from_hyper, from_meijerg """ if _recur is None: recurrence = self.to_sequence() else: recurrence = _recur if isinstance(recurrence, tuple) and len(recurrence) == 2: smallest_n = recurrence[1] recurrence = recurrence[0] constantpower = 0 elif isinstance(recurrence, tuple) and len(recurrence) == 3: smallest_n = recurrence[2] constantpower = recurrence[1] recurrence = recurrence[0] elif len(recurrence) == 1 and len(recurrence[0]) == 2: smallest_n = recurrence[0][1] recurrence = recurrence[0][0] constantpower = 0 elif len(recurrence) == 1 and len(recurrence[0]) == 3: smallest_n = recurrence[0][2] constantpower = recurrence[0][1] recurrence = recurrence[0][0] else: sol = self.to_hyper(as_list=as_list, _recur=recurrence[0]) for i in recurrence[1:]: sol += self.to_hyper(as_list=as_list, _recur=i) return sol u0 = recurrence.u0 r = recurrence.recurrence x = self.x x0 = self.x0 # order of the recurrence relation m = r.order # when no recurrence exists, and the power series have finite terms if m == 0: nonzeroterms = roots(r.parent.base.to_sympy(r.listofpoly[0]), recurrence.n, filter='R') sol = S.Zero for j, i in enumerate(nonzeroterms): if i < 0 or int(i) != i: continue i = int(i) if i < len(u0): if isinstance(u0[i], (PolyElement, FracElement)): u0[i] = u0[i].as_expr() sol += u0[i] * x**i else: sol += Symbol('C_%s' %j) * x**i if isinstance(sol, (PolyElement, FracElement)): sol = sol.as_expr() * x**constantpower else: sol = sol * x**constantpower if as_list: if x0 != 0: return [(sol.subs(x, x - x0), )] return [(sol, )] if x0 != 0: return sol.subs(x, x - x0) return sol if smallest_n + m > len(u0): raise NotImplementedError("Can't compute sufficient Initial Conditions") # check if the recurrence represents a hypergeometric series is_hyper = True for i in range(1, len(r.listofpoly)-1): if r.listofpoly[i] != r.parent.base.zero: is_hyper = False break if not is_hyper: raise NotHyperSeriesError(self, self.x0) a = r.listofpoly[0] b = r.listofpoly[-1] # the constant multiple of argument of hypergeometric function if isinstance(a.rep[0], (PolyElement, FracElement)): c = - (S(a.rep[0].as_expr()) * m**(a.degree())) / (S(b.rep[0].as_expr()) * m**(b.degree())) else: c = - (S(a.rep[0]) * m**(a.degree())) / (S(b.rep[0]) * m**(b.degree())) sol = 0 arg1 = roots(r.parent.base.to_sympy(a), recurrence.n) arg2 = roots(r.parent.base.to_sympy(b), recurrence.n) # iterate through the initial conditions to find # the hypergeometric representation of the given # function. # The answer will be a linear combination # of different hypergeometric series which satisfies # the recurrence. if as_list: listofsol = [] for i in range(smallest_n + m): # if the recurrence relation doesn't hold for `n = i`, # then a Hypergeometric representation doesn't exist. # add the algebraic term a * x**i to the solution, # where a is u0[i] if i < smallest_n: if as_list: listofsol.append(((S(u0[i]) * x**(i+constantpower)).subs(x, x-x0), )) else: sol += S(u0[i]) * x**i continue # if the coefficient u0[i] is zero, then the # independent hypergeomtric series starting with # x**i is not a part of the answer. if S(u0[i]) == 0: continue ap = [] bq = [] # substitute m * n + i for n for k in ordered(arg1.keys()): ap.extend([nsimplify((i - k) / m)] * arg1[k]) for k in ordered(arg2.keys()): bq.extend([nsimplify((i - k) / m)] * arg2[k]) # convention of (k + 1) in the denominator if 1 in bq: bq.remove(1) else: ap.append(1) if as_list: listofsol.append(((S(u0[i])*x**(i+constantpower)).subs(x, x-x0), (hyper(ap, bq, c*x**m)).subs(x, x-x0))) else: sol += S(u0[i]) * hyper(ap, bq, c * x**m) * x**i if as_list: return listofsol sol = sol * x**constantpower if x0 != 0: return sol.subs(x, x - x0) return sol def to_expr(self): """ Converts a Holonomic Function back to elementary functions. Examples ======== >>> from sympy.holonomic.holonomic import HolonomicFunction, DifferentialOperators >>> from sympy import ZZ >>> from sympy import symbols, S >>> x = symbols('x') >>> R, Dx = DifferentialOperators(ZZ.old_poly_ring(x),'Dx') >>> HolonomicFunction(x**2*Dx**2 + x*Dx + (x**2 - 1), x, 0, [0, S(1)/2]).to_expr() besselj(1, x) >>> HolonomicFunction((1 + x)*Dx**3 + Dx**2, x, 0, [1, 1, 1]).to_expr() x*log(x + 1) + log(x + 1) + 1 """ return hyperexpand(self.to_hyper()).simplify() def change_ics(self, b, lenics=None): """ Changes the point `x0` to ``b`` for initial conditions. Examples ======== >>> from sympy.holonomic import expr_to_holonomic >>> from sympy import symbols, sin, exp >>> x = symbols('x') >>> expr_to_holonomic(sin(x)).change_ics(1) HolonomicFunction((1) + (1)*Dx**2, x, 1, [sin(1), cos(1)]) >>> expr_to_holonomic(exp(x)).change_ics(2) HolonomicFunction((-1) + (1)*Dx, x, 2, [exp(2)]) """ symbolic = True if lenics is None and len(self.y0) > self.annihilator.order: lenics = len(self.y0) dom = self.annihilator.parent.base.domain try: sol = expr_to_holonomic(self.to_expr(), x=self.x, x0=b, lenics=lenics, domain=dom) except (NotPowerSeriesError, NotHyperSeriesError): symbolic = False if symbolic and sol.x0 == b: return sol y0 = self.evalf(b, derivatives=True) return HolonomicFunction(self.annihilator, self.x, b, y0) def to_meijerg(self): """ Returns a linear combination of Meijer G-functions. Examples ======== >>> from sympy.holonomic import expr_to_holonomic >>> from sympy import sin, cos, hyperexpand, log, symbols >>> x = symbols('x') >>> hyperexpand(expr_to_holonomic(cos(x) + sin(x)).to_meijerg()) sin(x) + cos(x) >>> hyperexpand(expr_to_holonomic(log(x)).to_meijerg()).simplify() log(x) See Also ======== to_hyper """ # convert to hypergeometric first rep = self.to_hyper(as_list=True) sol = S.Zero for i in rep: if len(i) == 1: sol += i[0] elif len(i) == 2: sol += i[0] * _hyper_to_meijerg(i[1]) return sol def from_hyper(func, x0=0, evalf=False): r""" Converts a hypergeometric function to holonomic. ``func`` is the Hypergeometric Function and ``x0`` is the point at which initial conditions are required. Examples ======== >>> from sympy.holonomic.holonomic import from_hyper >>> from sympy import symbols, hyper, S >>> x = symbols('x') >>> from_hyper(hyper([], [S(3)/2], x**2/4)) HolonomicFunction((-x) + (2)*Dx + (x)*Dx**2, x, 1, [sinh(1), -sinh(1) + cosh(1)]) """ a = func.ap b = func.bq z = func.args[2] x = z.atoms(Symbol).pop() R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') # generalized hypergeometric differential equation xDx = x*Dx r1 = 1 for ai in a: # XXX gives sympify error if Mul is used with list of all factors r1 *= xDx + ai xDx_1 = xDx - 1 # r2 = Mul(*([Dx] + [xDx_1 + bi for bi in b])) # XXX gives sympify error r2 = Dx for bi in b: r2 *= xDx_1 + bi sol = r1 - r2 simp = hyperexpand(func) if simp in (Infinity, NegativeInfinity): return HolonomicFunction(sol, x).composition(z) def _find_conditions(simp, x, x0, order, evalf=False): y0 = [] for i in range(order): if evalf: val = simp.subs(x, x0).evalf() else: val = simp.subs(x, x0) # return None if it is Infinite or NaN if val.is_finite is False or isinstance(val, NaN): return None y0.append(val) simp = simp.diff(x) return y0 # if the function is known symbolically if not isinstance(simp, hyper): y0 = _find_conditions(simp, x, x0, sol.order) while not y0: # if values don't exist at 0, then try to find initial # conditions at 1. If it doesn't exist at 1 too then # try 2 and so on. x0 += 1 y0 = _find_conditions(simp, x, x0, sol.order) return HolonomicFunction(sol, x).composition(z, x0, y0) if isinstance(simp, hyper): x0 = 1 # use evalf if the function can't be simplified y0 = _find_conditions(simp, x, x0, sol.order, evalf) while not y0: x0 += 1 y0 = _find_conditions(simp, x, x0, sol.order, evalf) return HolonomicFunction(sol, x).composition(z, x0, y0) return HolonomicFunction(sol, x).composition(z) def from_meijerg(func, x0=0, evalf=False, initcond=True, domain=QQ): """ Converts a Meijer G-function to Holonomic. ``func`` is the G-Function and ``x0`` is the point at which initial conditions are required. Examples ======== >>> from sympy.holonomic.holonomic import from_meijerg >>> from sympy import symbols, meijerg, S >>> x = symbols('x') >>> from_meijerg(meijerg(([], []), ([S(1)/2], [0]), x**2/4)) HolonomicFunction((1) + (1)*Dx**2, x, 0, [0, 1/sqrt(pi)]) """ a = func.ap b = func.bq n = len(func.an) m = len(func.bm) p = len(a) z = func.args[2] x = z.atoms(Symbol).pop() R, Dx = DifferentialOperators(domain.old_poly_ring(x), 'Dx') # compute the differential equation satisfied by the # Meijer G-function. xDx = x*Dx xDx1 = xDx + 1 r1 = x*(-1)**(m + n - p) for ai in a: # XXX gives sympify error if args given in list r1 *= xDx1 - ai # r2 = Mul(*[xDx - bi for bi in b]) # gives sympify error r2 = 1 for bi in b: r2 *= xDx - bi sol = r1 - r2 if not initcond: return HolonomicFunction(sol, x).composition(z) simp = hyperexpand(func) if simp in (Infinity, NegativeInfinity): return HolonomicFunction(sol, x).composition(z) def _find_conditions(simp, x, x0, order, evalf=False): y0 = [] for i in range(order): if evalf: val = simp.subs(x, x0).evalf() else: val = simp.subs(x, x0) if val.is_finite is False or isinstance(val, NaN): return None y0.append(val) simp = simp.diff(x) return y0 # computing initial conditions if not isinstance(simp, meijerg): y0 = _find_conditions(simp, x, x0, sol.order) while not y0: x0 += 1 y0 = _find_conditions(simp, x, x0, sol.order) return HolonomicFunction(sol, x).composition(z, x0, y0) if isinstance(simp, meijerg): x0 = 1 y0 = _find_conditions(simp, x, x0, sol.order, evalf) while not y0: x0 += 1 y0 = _find_conditions(simp, x, x0, sol.order, evalf) return HolonomicFunction(sol, x).composition(z, x0, y0) return HolonomicFunction(sol, x).composition(z) x_1 = Dummy('x_1') _lookup_table = None domain_for_table = None from sympy.integrals.meijerint import _mytype def expr_to_holonomic(func, x=None, x0=0, y0=None, lenics=None, domain=None, initcond=True): """ Converts a function or an expression to a holonomic function. Parameters ========== func: The expression to be converted. x: variable for the function. x0: point at which initial condition must be computed. y0: One can optionally provide initial condition if the method is not able to do it automatically. lenics: Number of terms in the initial condition. By default it is equal to the order of the annihilator. domain: Ground domain for the polynomials in ``x`` appearing as coefficients in the annihilator. initcond: Set it false if you do not want the initial conditions to be computed. Examples ======== >>> from sympy.holonomic.holonomic import expr_to_holonomic >>> from sympy import sin, exp, symbols >>> x = symbols('x') >>> expr_to_holonomic(sin(x)) HolonomicFunction((1) + (1)*Dx**2, x, 0, [0, 1]) >>> expr_to_holonomic(exp(x)) HolonomicFunction((-1) + (1)*Dx, x, 0, [1]) See Also ======== sympy.integrals.meijerint._rewrite1, _convert_poly_rat_alg, _create_table """ func = sympify(func) syms = func.free_symbols if not x: if len(syms) == 1: x= syms.pop() else: raise ValueError("Specify the variable for the function") elif x in syms: syms.remove(x) extra_syms = list(syms) if domain is None: if func.has(Float): domain = RR else: domain = QQ if len(extra_syms) != 0: domain = domain[extra_syms].get_field() # try to convert if the function is polynomial or rational solpoly = _convert_poly_rat_alg(func, x, x0=x0, y0=y0, lenics=lenics, domain=domain, initcond=initcond) if solpoly: return solpoly # create the lookup table global _lookup_table, domain_for_table if not _lookup_table: domain_for_table = domain _lookup_table = {} _create_table(_lookup_table, domain=domain) elif domain != domain_for_table: domain_for_table = domain _lookup_table = {} _create_table(_lookup_table, domain=domain) # use the table directly to convert to Holonomic if func.is_Function: f = func.subs(x, x_1) t = _mytype(f, x_1) if t in _lookup_table: l = _lookup_table[t] sol = l[0][1].change_x(x) else: sol = _convert_meijerint(func, x, initcond=False, domain=domain) if not sol: raise NotImplementedError if y0: sol.y0 = y0 if y0 or not initcond: sol.x0 = x0 return sol if not lenics: lenics = sol.annihilator.order _y0 = _find_conditions(func, x, x0, lenics) while not _y0: x0 += 1 _y0 = _find_conditions(func, x, x0, lenics) return HolonomicFunction(sol.annihilator, x, x0, _y0) if y0 or not initcond: sol = sol.composition(func.args[0]) if y0: sol.y0 = y0 sol.x0 = x0 return sol if not lenics: lenics = sol.annihilator.order _y0 = _find_conditions(func, x, x0, lenics) while not _y0: x0 += 1 _y0 = _find_conditions(func, x, x0, lenics) return sol.composition(func.args[0], x0, _y0) # iterate through the expression recursively args = func.args f = func.func sol = expr_to_holonomic(args[0], x=x, initcond=False, domain=domain) if f is Add: for i in range(1, len(args)): sol += expr_to_holonomic(args[i], x=x, initcond=False, domain=domain) elif f is Mul: for i in range(1, len(args)): sol *= expr_to_holonomic(args[i], x=x, initcond=False, domain=domain) elif f is Pow: sol = sol**args[1] sol.x0 = x0 if not sol: raise NotImplementedError if y0: sol.y0 = y0 if y0 or not initcond: return sol if sol.y0: return sol if not lenics: lenics = sol.annihilator.order if sol.annihilator.is_singular(x0): r = sol._indicial() l = list(r) if len(r) == 1 and r[l[0]] == S.One: r = l[0] g = func / (x - x0)**r singular_ics = _find_conditions(g, x, x0, lenics) singular_ics = [j / factorial(i) for i, j in enumerate(singular_ics)] y0 = {r:singular_ics} return HolonomicFunction(sol.annihilator, x, x0, y0) _y0 = _find_conditions(func, x, x0, lenics) while not _y0: x0 += 1 _y0 = _find_conditions(func, x, x0, lenics) return HolonomicFunction(sol.annihilator, x, x0, _y0) ## Some helper functions ## def _normalize(list_of, parent, negative=True): """ Normalize a given annihilator """ num = [] denom = [] base = parent.base K = base.get_field() lcm_denom = base.from_sympy(S.One) list_of_coeff = [] # convert polynomials to the elements of associated # fraction field for i, j in enumerate(list_of): if isinstance(j, base.dtype): list_of_coeff.append(K.new(j.rep)) elif not isinstance(j, K.dtype): list_of_coeff.append(K.from_sympy(sympify(j))) else: list_of_coeff.append(j) # corresponding numerators of the sequence of polynomials num.append(list_of_coeff[i].numer()) # corresponding denominators denom.append(list_of_coeff[i].denom()) # lcm of denominators in the coefficients for i in denom: lcm_denom = i.lcm(lcm_denom) if negative: lcm_denom = -lcm_denom lcm_denom = K.new(lcm_denom.rep) # multiply the coefficients with lcm for i, j in enumerate(list_of_coeff): list_of_coeff[i] = j * lcm_denom gcd_numer = base((list_of_coeff[-1].numer() / list_of_coeff[-1].denom()).rep) # gcd of numerators in the coefficients for i in num: gcd_numer = i.gcd(gcd_numer) gcd_numer = K.new(gcd_numer.rep) # divide all the coefficients by the gcd for i, j in enumerate(list_of_coeff): frac_ans = j / gcd_numer list_of_coeff[i] = base((frac_ans.numer() / frac_ans.denom()).rep) return DifferentialOperator(list_of_coeff, parent) def _derivate_diff_eq(listofpoly): """ Let a differential equation a0(x)y(x) + a1(x)y'(x) + ... = 0 where a0, a1,... are polynomials or rational functions. The function returns b0, b1, b2... such that the differential equation b0(x)y(x) + b1(x)y'(x) +... = 0 is formed after differentiating the former equation. """ sol = [] a = len(listofpoly) - 1 sol.append(DMFdiff(listofpoly[0])) for i, j in enumerate(listofpoly[1:]): sol.append(DMFdiff(j) + listofpoly[i]) sol.append(listofpoly[a]) return sol def _hyper_to_meijerg(func): """ Converts a `hyper` to meijerg. """ ap = func.ap bq = func.bq ispoly = any(i <= 0 and int(i) == i for i in ap) if ispoly: return hyperexpand(func) z = func.args[2] # parameters of the `meijerg` function. an = (1 - i for i in ap) anp = () bm = (S.Zero, ) bmq = (1 - i for i in bq) k = S.One for i in bq: k = k * gamma(i) for i in ap: k = k / gamma(i) return k * meijerg(an, anp, bm, bmq, -z) def _add_lists(list1, list2): """Takes polynomial sequences of two annihilators a and b and returns the list of polynomials of sum of a and b. """ if len(list1) <= len(list2): sol = [a + b for a, b in zip(list1, list2)] + list2[len(list1):] else: sol = [a + b for a, b in zip(list1, list2)] + list1[len(list2):] return sol def _extend_y0(Holonomic, n): """ Tries to find more initial conditions by substituting the initial value point in the differential equation. """ if Holonomic.annihilator.is_singular(Holonomic.x0) or Holonomic.is_singularics() == True: return Holonomic.y0 annihilator = Holonomic.annihilator a = annihilator.order listofpoly = [] y0 = Holonomic.y0 R = annihilator.parent.base K = R.get_field() for i, j in enumerate(annihilator.listofpoly): if isinstance(j, annihilator.parent.base.dtype): listofpoly.append(K.new(j.rep)) if len(y0) < a or n <= len(y0): return y0 else: list_red = [-listofpoly[i] / listofpoly[a] for i in range(a)] if len(y0) > a: y1 = [y0[i] for i in range(a)] else: y1 = [i for i in y0] for i in range(n - a): sol = 0 for a, b in zip(y1, list_red): r = DMFsubs(b, Holonomic.x0) if not getattr(r, 'is_finite', True): return y0 if isinstance(r, (PolyElement, FracElement)): r = r.as_expr() sol += a * r y1.append(sol) list_red = _derivate_diff_eq(list_red) return y0 + y1[len(y0):] def DMFdiff(frac): # differentiate a DMF object represented as p/q if not isinstance(frac, DMF): return frac.diff() K = frac.ring p = K.numer(frac) q = K.denom(frac) sol_num = - p * q.diff() + q * p.diff() sol_denom = q**2 return K((sol_num.rep, sol_denom.rep)) def DMFsubs(frac, x0, mpm=False): # substitute the point x0 in DMF object of the form p/q if not isinstance(frac, DMF): return frac p = frac.num q = frac.den sol_p = S.Zero sol_q = S.Zero if mpm: from mpmath import mp for i, j in enumerate(reversed(p)): if mpm: j = sympify(j)._to_mpmath(mp.prec) sol_p += j * x0**i for i, j in enumerate(reversed(q)): if mpm: j = sympify(j)._to_mpmath(mp.prec) sol_q += j * x0**i if isinstance(sol_p, (PolyElement, FracElement)): sol_p = sol_p.as_expr() if isinstance(sol_q, (PolyElement, FracElement)): sol_q = sol_q.as_expr() return sol_p / sol_q def _convert_poly_rat_alg(func, x, x0=0, y0=None, lenics=None, domain=QQ, initcond=True): """ Converts polynomials, rationals and algebraic functions to holonomic. """ ispoly = func.is_polynomial() if not ispoly: israt = func.is_rational_function() else: israt = True if not (ispoly or israt): basepoly, ratexp = func.as_base_exp() if basepoly.is_polynomial() and ratexp.is_Number: if isinstance(ratexp, Float): ratexp = nsimplify(ratexp) m, n = ratexp.p, ratexp.q is_alg = True else: is_alg = False else: is_alg = True if not (ispoly or israt or is_alg): return None R = domain.old_poly_ring(x) _, Dx = DifferentialOperators(R, 'Dx') # if the function is constant if not func.has(x): return HolonomicFunction(Dx, x, 0, [func]) if ispoly: # differential equation satisfied by polynomial sol = func * Dx - func.diff(x) sol = _normalize(sol.listofpoly, sol.parent, negative=False) is_singular = sol.is_singular(x0) # try to compute the conditions for singular points if y0 is None and x0 == 0 and is_singular: rep = R.from_sympy(func).rep for i, j in enumerate(reversed(rep)): if j == 0: continue else: coeff = list(reversed(rep))[i:] indicial = i break for i, j in enumerate(coeff): if isinstance(j, (PolyElement, FracElement)): coeff[i] = j.as_expr() y0 = {indicial: S(coeff)} elif israt: p, q = func.as_numer_denom() # differential equation satisfied by rational sol = p * q * Dx + p * q.diff(x) - q * p.diff(x) sol = _normalize(sol.listofpoly, sol.parent, negative=False) elif is_alg: sol = n * (x / m) * Dx - 1 sol = HolonomicFunction(sol, x).composition(basepoly).annihilator is_singular = sol.is_singular(x0) # try to compute the conditions for singular points if y0 is None and x0 == 0 and is_singular and \ (lenics is None or lenics <= 1): rep = R.from_sympy(basepoly).rep for i, j in enumerate(reversed(rep)): if j == 0: continue if isinstance(j, (PolyElement, FracElement)): j = j.as_expr() coeff = S(j)**ratexp indicial = S(i) * ratexp break if isinstance(coeff, (PolyElement, FracElement)): coeff = coeff.as_expr() y0 = {indicial: S([coeff])} if y0 or not initcond: return HolonomicFunction(sol, x, x0, y0) if not lenics: lenics = sol.order if sol.is_singular(x0): r = HolonomicFunction(sol, x, x0)._indicial() l = list(r) if len(r) == 1 and r[l[0]] == S.One: r = l[0] g = func / (x - x0)**r singular_ics = _find_conditions(g, x, x0, lenics) singular_ics = [j / factorial(i) for i, j in enumerate(singular_ics)] y0 = {r:singular_ics} return HolonomicFunction(sol, x, x0, y0) y0 = _find_conditions(func, x, x0, lenics) while not y0: x0 += 1 y0 = _find_conditions(func, x, x0, lenics) return HolonomicFunction(sol, x, x0, y0) def _convert_meijerint(func, x, initcond=True, domain=QQ): args = meijerint._rewrite1(func, x) if args: fac, po, g, _ = args else: return None # lists for sum of meijerg functions fac_list = [fac * i[0] for i in g] t = po.as_base_exp() s = t[1] if t[0] == x else S.Zero po_list = [s + i[1] for i in g] G_list = [i[2] for i in g] # finds meijerg representation of x**s * meijerg(a1 ... ap, b1 ... bq, z) def _shift(func, s): z = func.args[-1] if z.has(I): z = z.subs(exp_polar, exp) d = z.collect(x, evaluate=False) b = list(d)[0] a = d[b] t = b.as_base_exp() b = t[1] if t[0] == x else S.Zero r = s / b an = (i + r for i in func.args[0][0]) ap = (i + r for i in func.args[0][1]) bm = (i + r for i in func.args[1][0]) bq = (i + r for i in func.args[1][1]) return a**-r, meijerg((an, ap), (bm, bq), z) coeff, m = _shift(G_list[0], po_list[0]) sol = fac_list[0] * coeff * from_meijerg(m, initcond=initcond, domain=domain) # add all the meijerg functions after converting to holonomic for i in range(1, len(G_list)): coeff, m = _shift(G_list[i], po_list[i]) sol += fac_list[i] * coeff * from_meijerg(m, initcond=initcond, domain=domain) return sol def _create_table(table, domain=QQ): """ Creates the look-up table. For a similar implementation see meijerint._create_lookup_table. """ def add(formula, annihilator, arg, x0=0, y0=()): """ Adds a formula in the dictionary """ table.setdefault(_mytype(formula, x_1), []).append((formula, HolonomicFunction(annihilator, arg, x0, y0))) R = domain.old_poly_ring(x_1) _, Dx = DifferentialOperators(R, 'Dx') # add some basic functions add(sin(x_1), Dx**2 + 1, x_1, 0, [0, 1]) add(cos(x_1), Dx**2 + 1, x_1, 0, [1, 0]) add(exp(x_1), Dx - 1, x_1, 0, 1) add(log(x_1), Dx + x_1*Dx**2, x_1, 1, [0, 1]) add(erf(x_1), 2*x_1*Dx + Dx**2, x_1, 0, [0, 2/sqrt(pi)]) add(erfc(x_1), 2*x_1*Dx + Dx**2, x_1, 0, [1, -2/sqrt(pi)]) add(erfi(x_1), -2*x_1*Dx + Dx**2, x_1, 0, [0, 2/sqrt(pi)]) add(sinh(x_1), Dx**2 - 1, x_1, 0, [0, 1]) add(cosh(x_1), Dx**2 - 1, x_1, 0, [1, 0]) add(sinc(x_1), x_1 + 2*Dx + x_1*Dx**2, x_1) add(Si(x_1), x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1) add(Ci(x_1), x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1) add(Shi(x_1), -x_1*Dx + 2*Dx**2 + x_1*Dx**3, x_1) def _find_conditions(func, x, x0, order): y0 = [] for i in range(order): val = func.subs(x, x0) if isinstance(val, NaN): val = limit(func, x, x0) if val.is_finite is False or isinstance(val, NaN): return None y0.append(val) func = func.diff(x) return y0
c2ec4309f24aa4c6dd9785a3ccf9d985eebf3202f12d4abe8d8f58e3dde14170
"""Transform a string with Python-like source code into SymPy expression. """ from tokenize import (generate_tokens, untokenize, TokenError, NUMBER, STRING, NAME, OP, ENDMARKER, ERRORTOKEN, NEWLINE) from keyword import iskeyword import ast import unicodedata from io import StringIO import builtins import types from typing import Tuple as tTuple, Dict as tDict, Any, Callable, \ List, Optional, Union as tUnion from sympy.assumptions.ask import AssumptionKeys from sympy.core.basic import Basic from sympy.core import Symbol from sympy.core.function import Function from sympy.utilities.misc import func_name from sympy.functions.elementary.miscellaneous import Max, Min null = '' TOKEN = tTuple[int, str] DICT = tDict[str, Any] TRANS = Callable[[List[TOKEN], DICT, DICT], List[TOKEN]] def _token_splittable(token_name: str) -> bool: """ Predicate for whether a token name can be split into multiple tokens. A token is splittable if it does not contain an underscore character and it is not the name of a Greek letter. This is used to implicitly convert expressions like 'xyz' into 'x*y*z'. """ if '_' in token_name: return False try: return not unicodedata.lookup('GREEK SMALL LETTER ' + token_name) except KeyError: return len(token_name) > 1 def _token_callable(token: TOKEN, local_dict: DICT, global_dict: DICT, nextToken=None): """ Predicate for whether a token name represents a callable function. Essentially wraps ``callable``, but looks up the token name in the locals and globals. """ func = local_dict.get(token[1]) if not func: func = global_dict.get(token[1]) return callable(func) and not isinstance(func, Symbol) def _add_factorial_tokens(name: str, result: List[TOKEN]) -> List[TOKEN]: if result == [] or result[-1][1] == '(': raise TokenError() beginning = [(NAME, name), (OP, '(')] end = [(OP, ')')] diff = 0 length = len(result) for index, token in enumerate(result[::-1]): toknum, tokval = token i = length - index - 1 if tokval == ')': diff += 1 elif tokval == '(': diff -= 1 if diff == 0: if i - 1 >= 0 and result[i - 1][0] == NAME: return result[:i - 1] + beginning + result[i - 1:] + end else: return result[:i] + beginning + result[i:] + end return result class ParenthesisGroup(List[TOKEN]): """List of tokens representing an expression in parentheses.""" pass class AppliedFunction: """ A group of tokens representing a function and its arguments. `exponent` is for handling the shorthand sin^2, ln^2, etc. """ def __init__(self, function: TOKEN, args: ParenthesisGroup, exponent=None): if exponent is None: exponent = [] self.function = function self.args = args self.exponent = exponent self.items = ['function', 'args', 'exponent'] def expand(self) -> List[TOKEN]: """Return a list of tokens representing the function""" return [self.function, *self.args] def __getitem__(self, index): return getattr(self, self.items[index]) def __repr__(self): return "AppliedFunction(%s, %s, %s)" % (self.function, self.args, self.exponent) def _flatten(result: List[tUnion[TOKEN, AppliedFunction]]): result2: List[TOKEN] = [] for tok in result: if isinstance(tok, AppliedFunction): result2.extend(tok.expand()) else: result2.append(tok) return result2 def _group_parentheses(recursor: TRANS): def _inner(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Group tokens between parentheses with ParenthesisGroup. Also processes those tokens recursively. """ result: List[tUnion[TOKEN, ParenthesisGroup]] = [] stacks: List[ParenthesisGroup] = [] stacklevel = 0 for token in tokens: if token[0] == OP: if token[1] == '(': stacks.append(ParenthesisGroup([])) stacklevel += 1 elif token[1] == ')': stacks[-1].append(token) stack = stacks.pop() if len(stacks) > 0: # We don't recurse here since the upper-level stack # would reprocess these tokens stacks[-1].extend(stack) else: # Recurse here to handle nested parentheses # Strip off the outer parentheses to avoid an infinite loop inner = stack[1:-1] inner = recursor(inner, local_dict, global_dict) parenGroup = [stack[0]] + inner + [stack[-1]] result.append(ParenthesisGroup(parenGroup)) stacklevel -= 1 continue if stacklevel: stacks[-1].append(token) else: result.append(token) if stacklevel: raise TokenError("Mismatched parentheses") return result return _inner def _apply_functions(tokens: List[tUnion[TOKEN, ParenthesisGroup]], local_dict: DICT, global_dict: DICT): """Convert a NAME token + ParenthesisGroup into an AppliedFunction. Note that ParenthesisGroups, if not applied to any function, are converted back into lists of tokens. """ result: List[tUnion[TOKEN, AppliedFunction]] = [] symbol = None for tok in tokens: if isinstance(tok, ParenthesisGroup): if symbol and _token_callable(symbol, local_dict, global_dict): result[-1] = AppliedFunction(symbol, tok) symbol = None else: result.extend(tok) elif tok[0] == NAME: symbol = tok result.append(tok) else: symbol = None result.append(tok) return result def _implicit_multiplication(tokens: List[tUnion[TOKEN, AppliedFunction]], local_dict: DICT, global_dict: DICT): """Implicitly adds '*' tokens. Cases: - Two AppliedFunctions next to each other ("sin(x)cos(x)") - AppliedFunction next to an open parenthesis ("sin x (cos x + 1)") - A close parenthesis next to an AppliedFunction ("(x+2)sin x")\ - A close parenthesis next to an open parenthesis ("(x+2)(x+3)") - AppliedFunction next to an implicitly applied function ("sin(x)cos x") """ result: List[tUnion[TOKEN, AppliedFunction]] = [] skip = False for tok, nextTok in zip(tokens, tokens[1:]): result.append(tok) if skip: skip = False continue if tok[0] == OP and tok[1] == '.' and nextTok[0] == NAME: # Dotted name. Do not do implicit multiplication skip = True continue if isinstance(tok, AppliedFunction): if isinstance(nextTok, AppliedFunction): result.append((OP, '*')) elif nextTok == (OP, '('): # Applied function followed by an open parenthesis if tok.function[1] == "Function": tok.function = (tok.function[0], 'Symbol') result.append((OP, '*')) elif nextTok[0] == NAME: # Applied function followed by implicitly applied function result.append((OP, '*')) else: if tok == (OP, ')'): if isinstance(nextTok, AppliedFunction): # Close parenthesis followed by an applied function result.append((OP, '*')) elif nextTok[0] == NAME: # Close parenthesis followed by an implicitly applied function result.append((OP, '*')) elif nextTok == (OP, '('): # Close parenthesis followed by an open parenthesis result.append((OP, '*')) elif tok[0] == NAME and not _token_callable(tok, local_dict, global_dict): if isinstance(nextTok, AppliedFunction) or \ (nextTok[0] == NAME and _token_callable(nextTok, local_dict, global_dict)): # Constant followed by (implicitly applied) function result.append((OP, '*')) elif nextTok == (OP, '('): # Constant followed by parenthesis result.append((OP, '*')) elif nextTok[0] == NAME: # Constant followed by constant result.append((OP, '*')) if tokens: result.append(tokens[-1]) return result def _implicit_application(tokens: List[tUnion[TOKEN, AppliedFunction]], local_dict: DICT, global_dict: DICT): """Adds parentheses as needed after functions.""" result: List[tUnion[TOKEN, AppliedFunction]] = [] appendParen = 0 # number of closing parentheses to add skip = 0 # number of tokens to delay before adding a ')' (to # capture **, ^, etc.) exponentSkip = False # skipping tokens before inserting parentheses to # work with function exponentiation for tok, nextTok in zip(tokens, tokens[1:]): result.append(tok) if (tok[0] == NAME and nextTok[0] not in [OP, ENDMARKER, NEWLINE]): if _token_callable(tok, local_dict, global_dict, nextTok): # type: ignore result.append((OP, '(')) appendParen += 1 # name followed by exponent - function exponentiation elif (tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**'): if _token_callable(tok, local_dict, global_dict): # type: ignore exponentSkip = True elif exponentSkip: # if the last token added was an applied function (i.e. the # power of the function exponent) OR a multiplication (as # implicit multiplication would have added an extraneous # multiplication) if (isinstance(tok, AppliedFunction) or (tok[0] == OP and tok[1] == '*')): # don't add anything if the next token is a multiplication # or if there's already a parenthesis (if parenthesis, still # stop skipping tokens) if not (nextTok[0] == OP and nextTok[1] == '*'): if not(nextTok[0] == OP and nextTok[1] == '('): result.append((OP, '(')) appendParen += 1 exponentSkip = False elif appendParen: if nextTok[0] == OP and nextTok[1] in ('^', '**', '*'): skip = 1 continue if skip: skip -= 1 continue result.append((OP, ')')) appendParen -= 1 if tokens: result.append(tokens[-1]) if appendParen: result.extend([(OP, ')')] * appendParen) return result def function_exponentiation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Allows functions to be exponentiated, e.g. ``cos**2(x)``. Examples ======== >>> from sympy.parsing.sympy_parser import (parse_expr, ... standard_transformations, function_exponentiation) >>> transformations = standard_transformations + (function_exponentiation,) >>> parse_expr('sin**4(x)', transformations=transformations) sin(x)**4 """ result: List[TOKEN] = [] exponent: List[TOKEN] = [] consuming_exponent = False level = 0 for tok, nextTok in zip(tokens, tokens[1:]): if tok[0] == NAME and nextTok[0] == OP and nextTok[1] == '**': if _token_callable(tok, local_dict, global_dict): consuming_exponent = True elif consuming_exponent: if tok[0] == NAME and tok[1] == 'Function': tok = (NAME, 'Symbol') exponent.append(tok) # only want to stop after hitting ) if tok[0] == nextTok[0] == OP and tok[1] == ')' and nextTok[1] == '(': consuming_exponent = False # if implicit multiplication was used, we may have )*( instead if tok[0] == nextTok[0] == OP and tok[1] == '*' and nextTok[1] == '(': consuming_exponent = False del exponent[-1] continue elif exponent and not consuming_exponent: if tok[0] == OP: if tok[1] == '(': level += 1 elif tok[1] == ')': level -= 1 if level == 0: result.append(tok) result.extend(exponent) exponent = [] continue result.append(tok) if tokens: result.append(tokens[-1]) if exponent: result.extend(exponent) return result def split_symbols_custom(predicate: Callable[[str], bool]): """Creates a transformation that splits symbol names. ``predicate`` should return True if the symbol name is to be split. For instance, to retain the default behavior but avoid splitting certain symbol names, a predicate like this would work: >>> from sympy.parsing.sympy_parser import (parse_expr, _token_splittable, ... standard_transformations, implicit_multiplication, ... split_symbols_custom) >>> def can_split(symbol): ... if symbol not in ('list', 'of', 'unsplittable', 'names'): ... return _token_splittable(symbol) ... return False ... >>> transformation = split_symbols_custom(can_split) >>> parse_expr('unsplittable', transformations=standard_transformations + ... (transformation, implicit_multiplication)) unsplittable """ def _split_symbols(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): result: List[TOKEN] = [] split = False split_previous=False for tok in tokens: if split_previous: # throw out closing parenthesis of Symbol that was split split_previous=False continue split_previous=False if tok[0] == NAME and tok[1] in ['Symbol', 'Function']: split = True elif split and tok[0] == NAME: symbol = tok[1][1:-1] if predicate(symbol): tok_type = result[-2][1] # Symbol or Function del result[-2:] # Get rid of the call to Symbol i = 0 while i < len(symbol): char = symbol[i] if char in local_dict or char in global_dict: result.append((NAME, "%s" % char)) elif char.isdigit(): chars = [char] for i in range(i + 1, len(symbol)): if not symbol[i].isdigit(): i -= 1 break chars.append(symbol[i]) char = ''.join(chars) result.extend([(NAME, 'Number'), (OP, '('), (NAME, "'%s'" % char), (OP, ')')]) else: use = tok_type if i == len(symbol) else 'Symbol' result.extend([(NAME, use), (OP, '('), (NAME, "'%s'" % char), (OP, ')')]) i += 1 # Set split_previous=True so will skip # the closing parenthesis of the original Symbol split = False split_previous = True continue else: split = False result.append(tok) return result return _split_symbols #: Splits symbol names for implicit multiplication. #: #: Intended to let expressions like ``xyz`` be parsed as ``x*y*z``. Does not #: split Greek character names, so ``theta`` will *not* become #: ``t*h*e*t*a``. Generally this should be used with #: ``implicit_multiplication``. split_symbols = split_symbols_custom(_token_splittable) def implicit_multiplication(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT) -> List[TOKEN]: """Makes the multiplication operator optional in most cases. Use this before :func:`implicit_application`, otherwise expressions like ``sin 2x`` will be parsed as ``x * sin(2)`` rather than ``sin(2*x)``. Examples ======== >>> from sympy.parsing.sympy_parser import (parse_expr, ... standard_transformations, implicit_multiplication) >>> transformations = standard_transformations + (implicit_multiplication,) >>> parse_expr('3 x y', transformations=transformations) 3*x*y """ # These are interdependent steps, so we don't expose them separately res1 = _group_parentheses(implicit_multiplication)(tokens, local_dict, global_dict) res2 = _apply_functions(res1, local_dict, global_dict) res3 = _implicit_multiplication(res2, local_dict, global_dict) result = _flatten(res3) return result def implicit_application(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT) -> List[TOKEN]: """Makes parentheses optional in some cases for function calls. Use this after :func:`implicit_multiplication`, otherwise expressions like ``sin 2x`` will be parsed as ``x * sin(2)`` rather than ``sin(2*x)``. Examples ======== >>> from sympy.parsing.sympy_parser import (parse_expr, ... standard_transformations, implicit_application) >>> transformations = standard_transformations + (implicit_application,) >>> parse_expr('cot z + csc z', transformations=transformations) cot(z) + csc(z) """ res1 = _group_parentheses(implicit_application)(tokens, local_dict, global_dict) res2 = _apply_functions(res1, local_dict, global_dict) res3 = _implicit_application(res2, local_dict, global_dict) result = _flatten(res3) return result def implicit_multiplication_application(result: List[TOKEN], local_dict: DICT, global_dict: DICT) -> List[TOKEN]: """Allows a slightly relaxed syntax. - Parentheses for single-argument method calls are optional. - Multiplication is implicit. - Symbol names can be split (i.e. spaces are not needed between symbols). - Functions can be exponentiated. Examples ======== >>> from sympy.parsing.sympy_parser import (parse_expr, ... standard_transformations, implicit_multiplication_application) >>> parse_expr("10sin**2 x**2 + 3xyz + tan theta", ... transformations=(standard_transformations + ... (implicit_multiplication_application,))) 3*x*y*z + 10*sin(x**2)**2 + tan(theta) """ for step in (split_symbols, implicit_multiplication, implicit_application, function_exponentiation): result = step(result, local_dict, global_dict) return result def auto_symbol(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Inserts calls to ``Symbol``/``Function`` for undefined variables.""" result: List[TOKEN] = [] prevTok = (-1, '') tokens.append((-1, '')) # so zip traverses all tokens for tok, nextTok in zip(tokens, tokens[1:]): tokNum, tokVal = tok nextTokNum, nextTokVal = nextTok if tokNum == NAME: name = tokVal if (name in ['True', 'False', 'None'] or iskeyword(name) # Don't convert attribute access or (prevTok[0] == OP and prevTok[1] == '.') # Don't convert keyword arguments or (prevTok[0] == OP and prevTok[1] in ('(', ',') and nextTokNum == OP and nextTokVal == '=') # the name has already been defined or name in local_dict and local_dict[name] is not null): result.append((NAME, name)) continue elif name in local_dict: local_dict.setdefault(null, set()).add(name) if nextTokVal == '(': local_dict[name] = Function(name) else: local_dict[name] = Symbol(name) result.append((NAME, name)) continue elif name in global_dict: obj = global_dict[name] if isinstance(obj, (AssumptionKeys, Basic, type)) or callable(obj): result.append((NAME, name)) continue result.extend([ (NAME, 'Symbol' if nextTokVal != '(' else 'Function'), (OP, '('), (NAME, repr(str(name))), (OP, ')'), ]) else: result.append((tokNum, tokVal)) prevTok = (tokNum, tokVal) return result def lambda_notation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Substitutes "lambda" with its SymPy equivalent Lambda(). However, the conversion does not take place if only "lambda" is passed because that is a syntax error. """ result: List[TOKEN] = [] flag = False toknum, tokval = tokens[0] tokLen = len(tokens) if toknum == NAME and tokval == 'lambda': if tokLen == 2 or tokLen == 3 and tokens[1][0] == NEWLINE: # In Python 3.6.7+, inputs without a newline get NEWLINE added to # the tokens result.extend(tokens) elif tokLen > 2: result.extend([ (NAME, 'Lambda'), (OP, '('), (OP, '('), (OP, ')'), (OP, ')'), ]) for tokNum, tokVal in tokens[1:]: if tokNum == OP and tokVal == ':': tokVal = ',' flag = True if not flag and tokNum == OP and tokVal in ('*', '**'): raise TokenError("Starred arguments in lambda not supported") if flag: result.insert(-1, (tokNum, tokVal)) else: result.insert(-2, (tokNum, tokVal)) else: result.extend(tokens) return result def factorial_notation(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Allows standard notation for factorial.""" result: List[TOKEN] = [] nfactorial = 0 for toknum, tokval in tokens: if toknum == ERRORTOKEN: op = tokval if op == '!': nfactorial += 1 else: nfactorial = 0 result.append((OP, op)) else: if nfactorial == 1: result = _add_factorial_tokens('factorial', result) elif nfactorial == 2: result = _add_factorial_tokens('factorial2', result) elif nfactorial > 2: raise TokenError nfactorial = 0 result.append((toknum, tokval)) return result def convert_xor(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Treats XOR, ``^``, as exponentiation, ``**``.""" result: List[TOKEN] = [] for toknum, tokval in tokens: if toknum == OP: if tokval == '^': result.append((OP, '**')) else: result.append((toknum, tokval)) else: result.append((toknum, tokval)) return result def repeated_decimals(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """ Allows 0.2[1] notation to represent the repeated decimal 0.2111... (19/90) Run this before auto_number. """ result: List[TOKEN] = [] def is_digit(s): return all(i in '0123456789_' for i in s) # num will running match any DECIMAL [ INTEGER ] num: List[TOKEN] = [] for toknum, tokval in tokens: if toknum == NUMBER: if (not num and '.' in tokval and 'e' not in tokval.lower() and 'j' not in tokval.lower()): num.append((toknum, tokval)) elif is_digit(tokval)and len(num) == 2: num.append((toknum, tokval)) elif is_digit(tokval) and len(num) == 3 and is_digit(num[-1][1]): # Python 2 tokenizes 00123 as '00', '123' # Python 3 tokenizes 01289 as '012', '89' num.append((toknum, tokval)) else: num = [] elif toknum == OP: if tokval == '[' and len(num) == 1: num.append((OP, tokval)) elif tokval == ']' and len(num) >= 3: num.append((OP, tokval)) elif tokval == '.' and not num: # handle .[1] num.append((NUMBER, '0.')) else: num = [] else: num = [] result.append((toknum, tokval)) if num and num[-1][1] == ']': # pre.post[repetend] = a + b/c + d/e where a = pre, b/c = post, # and d/e = repetend result = result[:-len(num)] pre, post = num[0][1].split('.') repetend = num[2][1] if len(num) == 5: repetend += num[3][1] pre = pre.replace('_', '') post = post.replace('_', '') repetend = repetend.replace('_', '') zeros = '0'*len(post) post, repetends = [w.lstrip('0') for w in [post, repetend]] # or else interpreted as octal a = pre or '0' b, c = post or '0', '1' + zeros d, e = repetends, ('9'*len(repetend)) + zeros seq = [ (OP, '('), (NAME, 'Integer'), (OP, '('), (NUMBER, a), (OP, ')'), (OP, '+'), (NAME, 'Rational'), (OP, '('), (NUMBER, b), (OP, ','), (NUMBER, c), (OP, ')'), (OP, '+'), (NAME, 'Rational'), (OP, '('), (NUMBER, d), (OP, ','), (NUMBER, e), (OP, ')'), (OP, ')'), ] result.extend(seq) num = [] return result def auto_number(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """ Converts numeric literals to use SymPy equivalents. Complex numbers use ``I``, integer literals use ``Integer``, and float literals use ``Float``. """ result: List[TOKEN] = [] for toknum, tokval in tokens: if toknum == NUMBER: number = tokval postfix = [] if number.endswith('j') or number.endswith('J'): number = number[:-1] postfix = [(OP, '*'), (NAME, 'I')] if '.' in number or (('e' in number or 'E' in number) and not (number.startswith('0x') or number.startswith('0X'))): seq = [(NAME, 'Float'), (OP, '('), (NUMBER, repr(str(number))), (OP, ')')] else: seq = [(NAME, 'Integer'), (OP, '('), ( NUMBER, number), (OP, ')')] result.extend(seq + postfix) else: result.append((toknum, tokval)) return result def rationalize(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Converts floats into ``Rational``. Run AFTER ``auto_number``.""" result: List[TOKEN] = [] passed_float = False for toknum, tokval in tokens: if toknum == NAME: if tokval == 'Float': passed_float = True tokval = 'Rational' result.append((toknum, tokval)) elif passed_float == True and toknum == NUMBER: passed_float = False result.append((STRING, tokval)) else: result.append((toknum, tokval)) return result def _transform_equals_sign(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT): """Transforms the equals sign ``=`` to instances of Eq. This is a helper function for ``convert_equals_signs``. Works with expressions containing one equals sign and no nesting. Expressions like ``(1=2)=False`` will not work with this and should be used with ``convert_equals_signs``. Examples: 1=2 to Eq(1,2) 1*2=x to Eq(1*2, x) This does not deal with function arguments yet. """ result: List[TOKEN] = [] if (OP, "=") in tokens: result.append((NAME, "Eq")) result.append((OP, "(")) for token in tokens: if token == (OP, "="): result.append((OP, ",")) continue result.append(token) result.append((OP, ")")) else: result = tokens return result def convert_equals_signs(tokens: List[TOKEN], local_dict: DICT, global_dict: DICT) -> List[TOKEN]: """ Transforms all the equals signs ``=`` to instances of Eq. Parses the equals signs in the expression and replaces them with appropriate Eq instances. Also works with nested equals signs. Does not yet play well with function arguments. For example, the expression ``(x=y)`` is ambiguous and can be interpreted as x being an argument to a function and ``convert_equals_signs`` will not work for this. See also ======== convert_equality_operators Examples ======== >>> from sympy.parsing.sympy_parser import (parse_expr, ... standard_transformations, convert_equals_signs) >>> parse_expr("1*2=x", transformations=( ... standard_transformations + (convert_equals_signs,))) Eq(2, x) >>> parse_expr("(1*2=x)=False", transformations=( ... standard_transformations + (convert_equals_signs,))) Eq(Eq(2, x), False) """ res1 = _group_parentheses(convert_equals_signs)(tokens, local_dict, global_dict) res2 = _apply_functions(res1, local_dict, global_dict) res3 = _transform_equals_sign(res2, local_dict, global_dict) result = _flatten(res3) return result #: Standard transformations for :func:`parse_expr`. #: Inserts calls to :class:`~.Symbol`, :class:`~.Integer`, and other SymPy #: datatypes and allows the use of standard factorial notation (e.g. ``x!``). standard_transformations: tTuple[TRANS, ...] \ = (lambda_notation, auto_symbol, repeated_decimals, auto_number, factorial_notation) def stringify_expr(s: str, local_dict: DICT, global_dict: DICT, transformations: tTuple[TRANS, ...]) -> str: """ Converts the string ``s`` to Python code, in ``local_dict`` Generally, ``parse_expr`` should be used. """ tokens = [] input_code = StringIO(s.strip()) for toknum, tokval, _, _, _ in generate_tokens(input_code.readline): tokens.append((toknum, tokval)) for transform in transformations: tokens = transform(tokens, local_dict, global_dict) return untokenize(tokens) def eval_expr(code, local_dict: DICT, global_dict: DICT): """ Evaluate Python code generated by ``stringify_expr``. Generally, ``parse_expr`` should be used. """ expr = eval( code, global_dict, local_dict) # take local objects in preference return expr def parse_expr(s: str, local_dict: Optional[DICT] = None, transformations: tUnion[tTuple[TRANS, ...], str] \ = standard_transformations, global_dict: Optional[DICT] = None, evaluate=True): """Converts the string ``s`` to a SymPy expression, in ``local_dict``. Parameters ========== s : str The string to parse. local_dict : dict, optional A dictionary of local variables to use when parsing. global_dict : dict, optional A dictionary of global variables. By default, this is initialized with ``from sympy import *``; provide this parameter to override this behavior (for instance, to parse ``"Q & S"``). transformations : tuple or str A tuple of transformation functions used to modify the tokens of the parsed expression before evaluation. The default transformations convert numeric literals into their SymPy equivalents, convert undefined variables into SymPy symbols, and allow the use of standard mathematical factorial notation (e.g. ``x!``). Selection via string is available (see below). evaluate : bool, optional When False, the order of the arguments will remain as they were in the string and automatic simplification that would normally occur is suppressed. (see examples) Examples ======== >>> from sympy.parsing.sympy_parser import parse_expr >>> parse_expr("1/2") 1/2 >>> type(_) <class 'sympy.core.numbers.Half'> >>> from sympy.parsing.sympy_parser import standard_transformations,\\ ... implicit_multiplication_application >>> transformations = (standard_transformations + ... (implicit_multiplication_application,)) >>> parse_expr("2x", transformations=transformations) 2*x When evaluate=False, some automatic simplifications will not occur: >>> parse_expr("2**3"), parse_expr("2**3", evaluate=False) (8, 2**3) In addition the order of the arguments will not be made canonical. This feature allows one to tell exactly how the expression was entered: >>> a = parse_expr('1 + x', evaluate=False) >>> b = parse_expr('x + 1', evaluate=0) >>> a == b False >>> a.args (1, x) >>> b.args (x, 1) Note, however, that when these expressions are printed they will appear the same: >>> assert str(a) == str(b) As a convenience, transformations can be seen by printing ``transformations``: >>> from sympy.parsing.sympy_parser import transformations >>> print(transformations) 0: lambda_notation 1: auto_symbol 2: repeated_decimals 3: auto_number 4: factorial_notation 5: implicit_multiplication_application 6: convert_xor 7: implicit_application 8: implicit_multiplication 9: convert_equals_signs 10: function_exponentiation 11: rationalize The ``T`` object provides a way to select these transformations: >>> from sympy.parsing.sympy_parser import T If you print it, you will see the same list as shown above. >>> str(T) == str(transformations) True Standard slicing will return a tuple of transformations: >>> T[:5] == standard_transformations True So ``T`` can be used to specify the parsing transformations: >>> parse_expr("2x", transformations=T[:5]) Traceback (most recent call last): ... SyntaxError: invalid syntax >>> parse_expr("2x", transformations=T[:6]) 2*x >>> parse_expr('.3', transformations=T[3, 11]) 3/10 >>> parse_expr('.3x', transformations=T[:]) 3*x/10 As a further convenience, strings 'implicit' and 'all' can be used to select 0-5 and all the transformations, respectively. >>> parse_expr('.3x', transformations='all') 3*x/10 See Also ======== stringify_expr, eval_expr, standard_transformations, implicit_multiplication_application """ if local_dict is None: local_dict = {} elif not isinstance(local_dict, dict): raise TypeError('expecting local_dict to be a dict') elif null in local_dict: raise ValueError('cannot use "" in local_dict') if global_dict is None: global_dict = {} exec('from sympy import *', global_dict) builtins_dict = vars(builtins) for name, obj in builtins_dict.items(): if isinstance(obj, types.BuiltinFunctionType): global_dict[name] = obj global_dict['max'] = Max global_dict['min'] = Min elif not isinstance(global_dict, dict): raise TypeError('expecting global_dict to be a dict') transformations = transformations or () if isinstance(transformations, str): if transformations == 'all': _transformations = T[:] elif transformations == 'implicit': _transformations = T[:6] else: raise ValueError('unknown transformation group name') else: _transformations = transformations code = stringify_expr(s, local_dict, global_dict, _transformations) if not evaluate: code = compile(evaluateFalse(code), '<string>', 'eval') try: rv = eval_expr(code, local_dict, global_dict) # restore neutral definitions for names for i in local_dict.pop(null, ()): local_dict[i] = null return rv except Exception as e: # restore neutral definitions for names for i in local_dict.pop(null, ()): local_dict[i] = null raise e from ValueError(f"Error from parse_expr with transformed code: {code!r}") def evaluateFalse(s: str): """ Replaces operators with the SymPy equivalent and sets evaluate=False. """ node = ast.parse(s) transformed_node = EvaluateFalseTransformer().visit(node) # node is a Module, we want an Expression transformed_node = ast.Expression(transformed_node.body[0].value) return ast.fix_missing_locations(transformed_node) class EvaluateFalseTransformer(ast.NodeTransformer): operators = { ast.Add: 'Add', ast.Mult: 'Mul', ast.Pow: 'Pow', ast.Sub: 'Add', ast.Div: 'Mul', ast.BitOr: 'Or', ast.BitAnd: 'And', ast.BitXor: 'Not', } functions = ( 'Abs', 'im', 're', 'sign', 'arg', 'conjugate', 'acos', 'acot', 'acsc', 'asec', 'asin', 'atan', 'acosh', 'acoth', 'acsch', 'asech', 'asinh', 'atanh', 'cos', 'cot', 'csc', 'sec', 'sin', 'tan', 'cosh', 'coth', 'csch', 'sech', 'sinh', 'tanh', 'exp', 'ln', 'log', 'sqrt', 'cbrt', ) def flatten(self, args, func): result = [] for arg in args: if isinstance(arg, ast.Call): arg_func = arg.func if isinstance(arg_func, ast.Call): arg_func = arg_func.func if arg_func.id == func: result.extend(self.flatten(arg.args, func)) else: result.append(arg) else: result.append(arg) return result def visit_BinOp(self, node): if node.op.__class__ in self.operators: sympy_class = self.operators[node.op.__class__] right = self.visit(node.right) left = self.visit(node.left) rev = False if isinstance(node.op, ast.Sub): right = ast.Call( func=ast.Name(id='Mul', ctx=ast.Load()), args=[ast.UnaryOp(op=ast.USub(), operand=ast.Num(1)), right], keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))], starargs=None, kwargs=None ) elif isinstance(node.op, ast.Div): if isinstance(node.left, ast.UnaryOp): left, right = right, left rev = True left = ast.Call( func=ast.Name(id='Pow', ctx=ast.Load()), args=[left, ast.UnaryOp(op=ast.USub(), operand=ast.Num(1))], keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))], starargs=None, kwargs=None ) else: right = ast.Call( func=ast.Name(id='Pow', ctx=ast.Load()), args=[right, ast.UnaryOp(op=ast.USub(), operand=ast.Num(1))], keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))], starargs=None, kwargs=None ) if rev: # undo reversal left, right = right, left new_node = ast.Call( func=ast.Name(id=sympy_class, ctx=ast.Load()), args=[left, right], keywords=[ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))], starargs=None, kwargs=None ) if sympy_class in ('Add', 'Mul'): # Denest Add or Mul as appropriate new_node.args = self.flatten(new_node.args, sympy_class) return new_node return node def visit_Call(self, node): new_node = self.generic_visit(node) if isinstance(node.func, ast.Name) and node.func.id in self.functions: new_node.keywords.append(ast.keyword(arg='evaluate', value=ast.NameConstant(value=False, ctx=ast.Load()))) return new_node _transformation = { # items can be added but never re-ordered 0: lambda_notation, 1: auto_symbol, 2: repeated_decimals, 3: auto_number, 4: factorial_notation, 5: implicit_multiplication_application, 6: convert_xor, 7: implicit_application, 8: implicit_multiplication, 9: convert_equals_signs, 10: function_exponentiation, 11: rationalize} transformations = '\n'.join('%s: %s' % (i, func_name(f)) for i, f in _transformation.items()) class _T(): """class to retrieve transformations from a given slice EXAMPLES ======== >>> from sympy.parsing.sympy_parser import T, standard_transformations >>> assert T[:5] == standard_transformations """ def __init__(self): self.N = len(_transformation) def __str__(self): return transformations def __getitem__(self, t): if not type(t) is tuple: t = (t,) i = [] for ti in t: if type(ti) is int: i.append(range(self.N)[ti]) elif type(ti) is slice: i.extend(range(*ti.indices(self.N))) else: raise TypeError('unexpected slice arg') return tuple([_transformation[_] for _ in i]) T = _T()
986b1f943069650eb923dac620e2481757ed80920f810cd55ed134de1a8b6770
""" This module defines tensors with abstract index notation. The abstract index notation has been first formalized by Penrose. Tensor indices are formal objects, with a tensor type; there is no notion of index range, it is only possible to assign the dimension, used to trace the Kronecker delta; the dimension can be a Symbol. The Einstein summation convention is used. The covariant indices are indicated with a minus sign in front of the index. For instance the tensor ``t = p(a)*A(b,c)*q(-c)`` has the index ``c`` contracted. A tensor expression ``t`` can be called; called with its indices in sorted order it is equal to itself: in the above example ``t(a, b) == t``; one can call ``t`` with different indices; ``t(c, d) == p(c)*A(d,a)*q(-a)``. The contracted indices are dummy indices, internally they have no name, the indices being represented by a graph-like structure. Tensors are put in canonical form using ``canon_bp``, which uses the Butler-Portugal algorithm for canonicalization using the monoterm symmetries of the tensors. If there is a (anti)symmetric metric, the indices can be raised and lowered when the tensor is put in canonical form. """ from __future__ import annotations from typing import Any from functools import reduce from math import prod from abc import abstractmethod, ABCMeta from collections import defaultdict import operator import itertools from sympy.core.numbers import (Integer, Rational) from sympy.combinatorics import Permutation from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, \ bsgs_direct_product, canonicalize, riemann_bsgs from sympy.core import Basic, Expr, sympify, Add, Mul, S from sympy.core.assumptions import ManagedProperties from sympy.core.containers import Tuple, Dict from sympy.core.sorting import default_sort_key from sympy.core.symbol import Symbol, symbols from sympy.core.sympify import CantSympify, _sympify from sympy.core.operations import AssocOp from sympy.external.gmpy import SYMPY_INTS from sympy.matrices import eye from sympy.utilities.exceptions import (sympy_deprecation_warning, SymPyDeprecationWarning, ignore_warnings) from sympy.utilities.decorator import memoize_property, deprecated from sympy.utilities.iterables import sift def deprecate_data(): sympy_deprecation_warning( """ The data attribute of TensorIndexType is deprecated. Use The replace_with_arrays() method instead. """, deprecated_since_version="1.4", active_deprecations_target="deprecated-tensorindextype-attrs", stacklevel=4, ) def deprecate_fun_eval(): sympy_deprecation_warning( """ The Tensor.fun_eval() method is deprecated. Use Tensor.substitute_indices() instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensor-fun-eval", stacklevel=4, ) def deprecate_call(): sympy_deprecation_warning( """ Calling a tensor like Tensor(*indices) is deprecated. Use Tensor.substitute_indices() instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensor-fun-eval", stacklevel=4, ) class _IndexStructure(CantSympify): """ This class handles the indices (free and dummy ones). It contains the algorithms to manage the dummy indices replacements and contractions of free indices under multiplications of tensor expressions, as well as stuff related to canonicalization sorting, getting the permutation of the expression and so on. It also includes tools to get the ``TensorIndex`` objects corresponding to the given index structure. """ def __init__(self, free, dum, index_types, indices, canon_bp=False): self.free = free self.dum = dum self.index_types = index_types self.indices = indices self._ext_rank = len(self.free) + 2*len(self.dum) self.dum.sort(key=lambda x: x[0]) @staticmethod def from_indices(*indices): """ Create a new ``_IndexStructure`` object from a list of ``indices``. Explanation =========== ``indices`` ``TensorIndex`` objects, the indices. Contractions are detected upon construction. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, _IndexStructure >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2, m3 = tensor_indices('m0,m1,m2,m3', Lorentz) >>> _IndexStructure.from_indices(m0, m1, -m1, m3) _IndexStructure([(m0, 0), (m3, 3)], [(1, 2)], [Lorentz, Lorentz, Lorentz, Lorentz]) """ free, dum = _IndexStructure._free_dum_from_indices(*indices) index_types = [i.tensor_index_type for i in indices] indices = _IndexStructure._replace_dummy_names(indices, free, dum) return _IndexStructure(free, dum, index_types, indices) @staticmethod def from_components_free_dum(components, free, dum): index_types = [] for component in components: index_types.extend(component.index_types) indices = _IndexStructure.generate_indices_from_free_dum_index_types(free, dum, index_types) return _IndexStructure(free, dum, index_types, indices) @staticmethod def _free_dum_from_indices(*indices): """ Convert ``indices`` into ``free``, ``dum`` for single component tensor. Explanation =========== ``free`` list of tuples ``(index, pos, 0)``, where ``pos`` is the position of index in the list of indices formed by the component tensors ``dum`` list of tuples ``(pos_contr, pos_cov, 0, 0)`` Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, \ _IndexStructure >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2, m3 = tensor_indices('m0,m1,m2,m3', Lorentz) >>> _IndexStructure._free_dum_from_indices(m0, m1, -m1, m3) ([(m0, 0), (m3, 3)], [(1, 2)]) """ n = len(indices) if n == 1: return [(indices[0], 0)], [] # find the positions of the free indices and of the dummy indices free = [True]*len(indices) index_dict = {} dum = [] for i, index in enumerate(indices): name = index.name typ = index.tensor_index_type contr = index.is_up if (name, typ) in index_dict: # found a pair of dummy indices is_contr, pos = index_dict[(name, typ)] # check consistency and update free if is_contr: if contr: raise ValueError('two equal contravariant indices in slots %d and %d' %(pos, i)) else: free[pos] = False free[i] = False else: if contr: free[pos] = False free[i] = False else: raise ValueError('two equal covariant indices in slots %d and %d' %(pos, i)) if contr: dum.append((i, pos)) else: dum.append((pos, i)) else: index_dict[(name, typ)] = index.is_up, i free = [(index, i) for i, index in enumerate(indices) if free[i]] free.sort() return free, dum def get_indices(self): """ Get a list of indices, creating new tensor indices to complete dummy indices. """ return self.indices[:] @staticmethod def generate_indices_from_free_dum_index_types(free, dum, index_types): indices = [None]*(len(free)+2*len(dum)) for idx, pos in free: indices[pos] = idx generate_dummy_name = _IndexStructure._get_generator_for_dummy_indices(free) for pos1, pos2 in dum: typ1 = index_types[pos1] indname = generate_dummy_name(typ1) indices[pos1] = TensorIndex(indname, typ1, True) indices[pos2] = TensorIndex(indname, typ1, False) return _IndexStructure._replace_dummy_names(indices, free, dum) @staticmethod def _get_generator_for_dummy_indices(free): cdt = defaultdict(int) # if the free indices have names with dummy_name, start with an # index higher than those for the dummy indices # to avoid name collisions for indx, ipos in free: if indx.name.split('_')[0] == indx.tensor_index_type.dummy_name: cdt[indx.tensor_index_type] = max(cdt[indx.tensor_index_type], int(indx.name.split('_')[1]) + 1) def dummy_name_gen(tensor_index_type): nd = str(cdt[tensor_index_type]) cdt[tensor_index_type] += 1 return tensor_index_type.dummy_name + '_' + nd return dummy_name_gen @staticmethod def _replace_dummy_names(indices, free, dum): dum.sort(key=lambda x: x[0]) new_indices = [ind for ind in indices] assert len(indices) == len(free) + 2*len(dum) generate_dummy_name = _IndexStructure._get_generator_for_dummy_indices(free) for ipos1, ipos2 in dum: typ1 = new_indices[ipos1].tensor_index_type indname = generate_dummy_name(typ1) new_indices[ipos1] = TensorIndex(indname, typ1, True) new_indices[ipos2] = TensorIndex(indname, typ1, False) return new_indices def get_free_indices(self) -> list[TensorIndex]: """ Get a list of free indices. """ # get sorted indices according to their position: free = sorted(self.free, key=lambda x: x[1]) return [i[0] for i in free] def __str__(self): return "_IndexStructure({}, {}, {})".format(self.free, self.dum, self.index_types) def __repr__(self): return self.__str__() def _get_sorted_free_indices_for_canon(self): sorted_free = self.free[:] sorted_free.sort(key=lambda x: x[0]) return sorted_free def _get_sorted_dum_indices_for_canon(self): return sorted(self.dum, key=lambda x: x[0]) def _get_lexicographically_sorted_index_types(self): permutation = self.indices_canon_args()[0] index_types = [None]*self._ext_rank for i, it in enumerate(self.index_types): index_types[permutation(i)] = it return index_types def _get_lexicographically_sorted_indices(self): permutation = self.indices_canon_args()[0] indices = [None]*self._ext_rank for i, it in enumerate(self.indices): indices[permutation(i)] = it return indices def perm2tensor(self, g, is_canon_bp=False): """ Returns a ``_IndexStructure`` instance corresponding to the permutation ``g``. Explanation =========== ``g`` permutation corresponding to the tensor in the representation used in canonicalization ``is_canon_bp`` if True, then ``g`` is the permutation corresponding to the canonical form of the tensor """ sorted_free = [i[0] for i in self._get_sorted_free_indices_for_canon()] lex_index_types = self._get_lexicographically_sorted_index_types() lex_indices = self._get_lexicographically_sorted_indices() nfree = len(sorted_free) rank = self._ext_rank dum = [[None]*2 for i in range((rank - nfree)//2)] free = [] index_types = [None]*rank indices = [None]*rank for i in range(rank): gi = g[i] index_types[i] = lex_index_types[gi] indices[i] = lex_indices[gi] if gi < nfree: ind = sorted_free[gi] assert index_types[i] == sorted_free[gi].tensor_index_type free.append((ind, i)) else: j = gi - nfree idum, cov = divmod(j, 2) if cov: dum[idum][1] = i else: dum[idum][0] = i dum = [tuple(x) for x in dum] return _IndexStructure(free, dum, index_types, indices) def indices_canon_args(self): """ Returns ``(g, dummies, msym, v)``, the entries of ``canonicalize`` See ``canonicalize`` in ``tensor_can.py`` in combinatorics module. """ # to be called after sorted_components from sympy.combinatorics.permutations import _af_new n = self._ext_rank g = [None]*n + [n, n+1] # Converts the symmetry of the metric into msym from .canonicalize() # method in the combinatorics module def metric_symmetry_to_msym(metric): if metric is None: return None sym = metric.symmetry if sym == TensorSymmetry.fully_symmetric(2): return 0 if sym == TensorSymmetry.fully_symmetric(-2): return 1 return None # ordered indices: first the free indices, ordered by types # then the dummy indices, ordered by types and contravariant before # covariant # g[position in tensor] = position in ordered indices for i, (indx, ipos) in enumerate(self._get_sorted_free_indices_for_canon()): g[ipos] = i pos = len(self.free) j = len(self.free) dummies = [] prev = None a = [] msym = [] for ipos1, ipos2 in self._get_sorted_dum_indices_for_canon(): g[ipos1] = j g[ipos2] = j + 1 j += 2 typ = self.index_types[ipos1] if typ != prev: if a: dummies.append(a) a = [pos, pos + 1] prev = typ msym.append(metric_symmetry_to_msym(typ.metric)) else: a.extend([pos, pos + 1]) pos += 2 if a: dummies.append(a) return _af_new(g), dummies, msym def components_canon_args(components): numtyp = [] prev = None for t in components: if t == prev: numtyp[-1][1] += 1 else: prev = t numtyp.append([prev, 1]) v = [] for h, n in numtyp: if h.comm in (0, 1): comm = h.comm else: comm = TensorManager.get_comm(h.comm, h.comm) v.append((h.symmetry.base, h.symmetry.generators, n, comm)) return v class _TensorDataLazyEvaluator(CantSympify): """ EXPERIMENTAL: do not rely on this class, it may change without deprecation warnings in future versions of SymPy. Explanation =========== This object contains the logic to associate components data to a tensor expression. Components data are set via the ``.data`` property of tensor expressions, is stored inside this class as a mapping between the tensor expression and the ``ndarray``. Computations are executed lazily: whereas the tensor expressions can have contractions, tensor products, and additions, components data are not computed until they are accessed by reading the ``.data`` property associated to the tensor expression. """ _substitutions_dict: dict[Any, Any] = {} _substitutions_dict_tensmul: dict[Any, Any] = {} def __getitem__(self, key): dat = self._get(key) if dat is None: return None from .array import NDimArray if not isinstance(dat, NDimArray): return dat if dat.rank() == 0: return dat[()] elif dat.rank() == 1 and len(dat) == 1: return dat[0] return dat def _get(self, key): """ Retrieve ``data`` associated with ``key``. Explanation =========== This algorithm looks into ``self._substitutions_dict`` for all ``TensorHead`` in the ``TensExpr`` (or just ``TensorHead`` if key is a TensorHead instance). It reconstructs the components data that the tensor expression should have by performing on components data the operations that correspond to the abstract tensor operations applied. Metric tensor is handled in a different manner: it is pre-computed in ``self._substitutions_dict_tensmul``. """ if key in self._substitutions_dict: return self._substitutions_dict[key] if isinstance(key, TensorHead): return None if isinstance(key, Tensor): # special case to handle metrics. Metric tensors cannot be # constructed through contraction by the metric, their # components show if they are a matrix or its inverse. signature = tuple([i.is_up for i in key.get_indices()]) srch = (key.component,) + signature if srch in self._substitutions_dict_tensmul: return self._substitutions_dict_tensmul[srch] array_list = [self.data_from_tensor(key)] return self.data_contract_dum(array_list, key.dum, key.ext_rank) if isinstance(key, TensMul): tensmul_args = key.args if len(tensmul_args) == 1 and len(tensmul_args[0].components) == 1: # special case to handle metrics. Metric tensors cannot be # constructed through contraction by the metric, their # components show if they are a matrix or its inverse. signature = tuple([i.is_up for i in tensmul_args[0].get_indices()]) srch = (tensmul_args[0].components[0],) + signature if srch in self._substitutions_dict_tensmul: return self._substitutions_dict_tensmul[srch] #data_list = [self.data_from_tensor(i) for i in tensmul_args if isinstance(i, TensExpr)] data_list = [self.data_from_tensor(i) if isinstance(i, Tensor) else i.data for i in tensmul_args if isinstance(i, TensExpr)] coeff = prod([i for i in tensmul_args if not isinstance(i, TensExpr)]) if all(i is None for i in data_list): return None if any(i is None for i in data_list): raise ValueError("Mixing tensors with associated components "\ "data with tensors without components data") data_result = self.data_contract_dum(data_list, key.dum, key.ext_rank) return coeff*data_result if isinstance(key, TensAdd): data_list = [] free_args_list = [] for arg in key.args: if isinstance(arg, TensExpr): data_list.append(arg.data) free_args_list.append([x[0] for x in arg.free]) else: data_list.append(arg) free_args_list.append([]) if all(i is None for i in data_list): return None if any(i is None for i in data_list): raise ValueError("Mixing tensors with associated components "\ "data with tensors without components data") sum_list = [] from .array import permutedims for data, free_args in zip(data_list, free_args_list): if len(free_args) < 2: sum_list.append(data) else: free_args_pos = {y: x for x, y in enumerate(free_args)} axes = [free_args_pos[arg] for arg in key.free_args] sum_list.append(permutedims(data, axes)) return reduce(lambda x, y: x+y, sum_list) return None @staticmethod def data_contract_dum(ndarray_list, dum, ext_rank): from .array import tensorproduct, tensorcontraction, MutableDenseNDimArray arrays = list(map(MutableDenseNDimArray, ndarray_list)) prodarr = tensorproduct(*arrays) return tensorcontraction(prodarr, *dum) def data_tensorhead_from_tensmul(self, data, tensmul, tensorhead): """ This method is used when assigning components data to a ``TensMul`` object, it converts components data to a fully contravariant ndarray, which is then stored according to the ``TensorHead`` key. """ if data is None: return None return self._correct_signature_from_indices( data, tensmul.get_indices(), tensmul.free, tensmul.dum, True) def data_from_tensor(self, tensor): """ This method corrects the components data to the right signature (covariant/contravariant) using the metric associated with each ``TensorIndexType``. """ tensorhead = tensor.component if tensorhead.data is None: return None return self._correct_signature_from_indices( tensorhead.data, tensor.get_indices(), tensor.free, tensor.dum) def _assign_data_to_tensor_expr(self, key, data): if isinstance(key, TensAdd): raise ValueError('cannot assign data to TensAdd') # here it is assumed that `key` is a `TensMul` instance. if len(key.components) != 1: raise ValueError('cannot assign data to TensMul with multiple components') tensorhead = key.components[0] newdata = self.data_tensorhead_from_tensmul(data, key, tensorhead) return tensorhead, newdata def _check_permutations_on_data(self, tens, data): from .array import permutedims from .array.arrayop import Flatten if isinstance(tens, TensorHead): rank = tens.rank generators = tens.symmetry.generators elif isinstance(tens, Tensor): rank = tens.rank generators = tens.components[0].symmetry.generators elif isinstance(tens, TensorIndexType): rank = tens.metric.rank generators = tens.metric.symmetry.generators # Every generator is a permutation, check that by permuting the array # by that permutation, the array will be the same, except for a # possible sign change if the permutation admits it. for gener in generators: sign_change = +1 if (gener(rank) == rank) else -1 data_swapped = data last_data = data permute_axes = list(map(gener, range(rank))) # the order of a permutation is the number of times to get the # identity by applying that permutation. for i in range(gener.order()-1): data_swapped = permutedims(data_swapped, permute_axes) # if any value in the difference array is non-zero, raise an error: if any(Flatten(last_data - sign_change*data_swapped)): raise ValueError("Component data symmetry structure error") last_data = data_swapped def __setitem__(self, key, value): """ Set the components data of a tensor object/expression. Explanation =========== Components data are transformed to the all-contravariant form and stored with the corresponding ``TensorHead`` object. If a ``TensorHead`` object cannot be uniquely identified, it will raise an error. """ data = _TensorDataLazyEvaluator.parse_data(value) self._check_permutations_on_data(key, data) # TensorHead and TensorIndexType can be assigned data directly, while # TensMul must first convert data to a fully contravariant form, and # assign it to its corresponding TensorHead single component. if not isinstance(key, (TensorHead, TensorIndexType)): key, data = self._assign_data_to_tensor_expr(key, data) if isinstance(key, TensorHead): for dim, indextype in zip(data.shape, key.index_types): if indextype.data is None: raise ValueError("index type {} has no components data"\ " associated (needed to raise/lower index)".format(indextype)) if not indextype.dim.is_number: continue if dim != indextype.dim: raise ValueError("wrong dimension of ndarray") self._substitutions_dict[key] = data def __delitem__(self, key): del self._substitutions_dict[key] def __contains__(self, key): return key in self._substitutions_dict def add_metric_data(self, metric, data): """ Assign data to the ``metric`` tensor. The metric tensor behaves in an anomalous way when raising and lowering indices. Explanation =========== A fully covariant metric is the inverse transpose of the fully contravariant metric (it is meant matrix inverse). If the metric is symmetric, the transpose is not necessary and mixed covariant/contravariant metrics are Kronecker deltas. """ # hard assignment, data should not be added to `TensorHead` for metric: # the problem with `TensorHead` is that the metric is anomalous, i.e. # raising and lowering the index means considering the metric or its # inverse, this is not the case for other tensors. self._substitutions_dict_tensmul[metric, True, True] = data inverse_transpose = self.inverse_transpose_matrix(data) # in symmetric spaces, the transpose is the same as the original matrix, # the full covariant metric tensor is the inverse transpose, so this # code will be able to handle non-symmetric metrics. self._substitutions_dict_tensmul[metric, False, False] = inverse_transpose # now mixed cases, these are identical to the unit matrix if the metric # is symmetric. m = data.tomatrix() invt = inverse_transpose.tomatrix() self._substitutions_dict_tensmul[metric, True, False] = m * invt self._substitutions_dict_tensmul[metric, False, True] = invt * m @staticmethod def _flip_index_by_metric(data, metric, pos): from .array import tensorproduct, tensorcontraction mdim = metric.rank() ddim = data.rank() if pos == 0: data = tensorcontraction( tensorproduct( metric, data ), (1, mdim+pos) ) else: data = tensorcontraction( tensorproduct( data, metric ), (pos, ddim) ) return data @staticmethod def inverse_matrix(ndarray): m = ndarray.tomatrix().inv() return _TensorDataLazyEvaluator.parse_data(m) @staticmethod def inverse_transpose_matrix(ndarray): m = ndarray.tomatrix().inv().T return _TensorDataLazyEvaluator.parse_data(m) @staticmethod def _correct_signature_from_indices(data, indices, free, dum, inverse=False): """ Utility function to correct the values inside the components data ndarray according to whether indices are covariant or contravariant. It uses the metric matrix to lower values of covariant indices. """ # change the ndarray values according covariantness/contravariantness of the indices # use the metric for i, indx in enumerate(indices): if not indx.is_up and not inverse: data = _TensorDataLazyEvaluator._flip_index_by_metric(data, indx.tensor_index_type.data, i) elif not indx.is_up and inverse: data = _TensorDataLazyEvaluator._flip_index_by_metric( data, _TensorDataLazyEvaluator.inverse_matrix(indx.tensor_index_type.data), i ) return data @staticmethod def _sort_data_axes(old, new): from .array import permutedims new_data = old.data.copy() old_free = [i[0] for i in old.free] new_free = [i[0] for i in new.free] for i in range(len(new_free)): for j in range(i, len(old_free)): if old_free[j] == new_free[i]: old_free[i], old_free[j] = old_free[j], old_free[i] new_data = permutedims(new_data, (i, j)) break return new_data @staticmethod def add_rearrange_tensmul_parts(new_tensmul, old_tensmul): def sorted_compo(): return _TensorDataLazyEvaluator._sort_data_axes(old_tensmul, new_tensmul) _TensorDataLazyEvaluator._substitutions_dict[new_tensmul] = sorted_compo() @staticmethod def parse_data(data): """ Transform ``data`` to array. The parameter ``data`` may contain data in various formats, e.g. nested lists, SymPy ``Matrix``, and so on. Examples ======== >>> from sympy.tensor.tensor import _TensorDataLazyEvaluator >>> _TensorDataLazyEvaluator.parse_data([1, 3, -6, 12]) [1, 3, -6, 12] >>> _TensorDataLazyEvaluator.parse_data([[1, 2], [4, 7]]) [[1, 2], [4, 7]] """ from .array import MutableDenseNDimArray if not isinstance(data, MutableDenseNDimArray): if len(data) == 2 and hasattr(data[0], '__call__'): data = MutableDenseNDimArray(data[0], data[1]) else: data = MutableDenseNDimArray(data) return data _tensor_data_substitution_dict = _TensorDataLazyEvaluator() class _TensorManager: """ Class to manage tensor properties. Notes ===== Tensors belong to tensor commutation groups; each group has a label ``comm``; there are predefined labels: ``0`` tensors commuting with any other tensor ``1`` tensors anticommuting among themselves ``2`` tensors not commuting, apart with those with ``comm=0`` Other groups can be defined using ``set_comm``; tensors in those groups commute with those with ``comm=0``; by default they do not commute with any other group. """ def __init__(self): self._comm_init() def _comm_init(self): self._comm = [{} for i in range(3)] for i in range(3): self._comm[0][i] = 0 self._comm[i][0] = 0 self._comm[1][1] = 1 self._comm[2][1] = None self._comm[1][2] = None self._comm_symbols2i = {0:0, 1:1, 2:2} self._comm_i2symbol = {0:0, 1:1, 2:2} @property def comm(self): return self._comm def comm_symbols2i(self, i): """ Get the commutation group number corresponding to ``i``. ``i`` can be a symbol or a number or a string. If ``i`` is not already defined its commutation group number is set. """ if i not in self._comm_symbols2i: n = len(self._comm) self._comm.append({}) self._comm[n][0] = 0 self._comm[0][n] = 0 self._comm_symbols2i[i] = n self._comm_i2symbol[n] = i return n return self._comm_symbols2i[i] def comm_i2symbol(self, i): """ Returns the symbol corresponding to the commutation group number. """ return self._comm_i2symbol[i] def set_comm(self, i, j, c): """ Set the commutation parameter ``c`` for commutation groups ``i, j``. Parameters ========== i, j : symbols representing commutation groups c : group commutation number Notes ===== ``i, j`` can be symbols, strings or numbers, apart from ``0, 1`` and ``2`` which are reserved respectively for commuting, anticommuting tensors and tensors not commuting with any other group apart with the commuting tensors. For the remaining cases, use this method to set the commutation rules; by default ``c=None``. The group commutation number ``c`` is assigned in correspondence to the group commutation symbols; it can be 0 commuting 1 anticommuting None no commutation property Examples ======== ``G`` and ``GH`` do not commute with themselves and commute with each other; A is commuting. >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, TensorManager, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz') >>> i0,i1,i2,i3,i4 = tensor_indices('i0:5', Lorentz) >>> A = TensorHead('A', [Lorentz]) >>> G = TensorHead('G', [Lorentz], TensorSymmetry.no_symmetry(1), 'Gcomm') >>> GH = TensorHead('GH', [Lorentz], TensorSymmetry.no_symmetry(1), 'GHcomm') >>> TensorManager.set_comm('Gcomm', 'GHcomm', 0) >>> (GH(i1)*G(i0)).canon_bp() G(i0)*GH(i1) >>> (G(i1)*G(i0)).canon_bp() G(i1)*G(i0) >>> (G(i1)*A(i0)).canon_bp() A(i0)*G(i1) """ if c not in (0, 1, None): raise ValueError('`c` can assume only the values 0, 1 or None') if i not in self._comm_symbols2i: n = len(self._comm) self._comm.append({}) self._comm[n][0] = 0 self._comm[0][n] = 0 self._comm_symbols2i[i] = n self._comm_i2symbol[n] = i if j not in self._comm_symbols2i: n = len(self._comm) self._comm.append({}) self._comm[0][n] = 0 self._comm[n][0] = 0 self._comm_symbols2i[j] = n self._comm_i2symbol[n] = j ni = self._comm_symbols2i[i] nj = self._comm_symbols2i[j] self._comm[ni][nj] = c self._comm[nj][ni] = c def set_comms(self, *args): """ Set the commutation group numbers ``c`` for symbols ``i, j``. Parameters ========== args : sequence of ``(i, j, c)`` """ for i, j, c in args: self.set_comm(i, j, c) def get_comm(self, i, j): """ Return the commutation parameter for commutation group numbers ``i, j`` see ``_TensorManager.set_comm`` """ return self._comm[i].get(j, 0 if i == 0 or j == 0 else None) def clear(self): """ Clear the TensorManager. """ self._comm_init() TensorManager = _TensorManager() class TensorIndexType(Basic): """ A TensorIndexType is characterized by its name and its metric. Parameters ========== name : name of the tensor type dummy_name : name of the head of dummy indices dim : dimension, it can be a symbol or an integer or ``None`` eps_dim : dimension of the epsilon tensor metric_symmetry : integer that denotes metric symmetry or ``None`` for no metric metric_name : string with the name of the metric tensor Attributes ========== ``metric`` : the metric tensor ``delta`` : ``Kronecker delta`` ``epsilon`` : the ``Levi-Civita epsilon`` tensor ``data`` : (deprecated) a property to add ``ndarray`` values, to work in a specified basis. Notes ===== The possible values of the ``metric_symmetry`` parameter are: ``1`` : metric tensor is fully symmetric ``0`` : metric tensor possesses no index symmetry ``-1`` : metric tensor is fully antisymmetric ``None``: there is no metric tensor (metric equals to ``None``) The metric is assumed to be symmetric by default. It can also be set to a custom tensor by the ``.set_metric()`` method. If there is a metric the metric is used to raise and lower indices. In the case of non-symmetric metric, the following raising and lowering conventions will be adopted: ``psi(a) = g(a, b)*psi(-b); chi(-a) = chi(b)*g(-b, -a)`` From these it is easy to find: ``g(-a, b) = delta(-a, b)`` where ``delta(-a, b) = delta(b, -a)`` is the ``Kronecker delta`` (see ``TensorIndex`` for the conventions on indices). For antisymmetric metrics there is also the following equality: ``g(a, -b) = -delta(a, -b)`` If there is no metric it is not possible to raise or lower indices; e.g. the index of the defining representation of ``SU(N)`` is 'covariant' and the conjugate representation is 'contravariant'; for ``N > 2`` they are linearly independent. ``eps_dim`` is by default equal to ``dim``, if the latter is an integer; else it can be assigned (for use in naive dimensional regularization); if ``eps_dim`` is not an integer ``epsilon`` is ``None``. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> Lorentz.metric metric(Lorentz,Lorentz) """ def __new__(cls, name, dummy_name=None, dim=None, eps_dim=None, metric_symmetry=1, metric_name='metric', **kwargs): if 'dummy_fmt' in kwargs: dummy_fmt = kwargs['dummy_fmt'] sympy_deprecation_warning( f""" The dummy_fmt keyword to TensorIndexType is deprecated. Use dummy_name={dummy_fmt} instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorindextype-dummy-fmt", ) dummy_name = dummy_fmt if isinstance(name, str): name = Symbol(name) if dummy_name is None: dummy_name = str(name)[0] if isinstance(dummy_name, str): dummy_name = Symbol(dummy_name) if dim is None: dim = Symbol("dim_" + dummy_name.name) else: dim = sympify(dim) if eps_dim is None: eps_dim = dim else: eps_dim = sympify(eps_dim) metric_symmetry = sympify(metric_symmetry) if isinstance(metric_name, str): metric_name = Symbol(metric_name) if 'metric' in kwargs: SymPyDeprecationWarning( """ The 'metric' keyword argument to TensorIndexType is deprecated. Use the 'metric_symmetry' keyword argument or the TensorIndexType.set_metric() method instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorindextype-metric", ) metric = kwargs.get('metric') if metric is not None: if metric in (True, False, 0, 1): metric_name = 'metric' #metric_antisym = metric else: metric_name = metric.name #metric_antisym = metric.antisym if metric: metric_symmetry = -1 else: metric_symmetry = 1 obj = Basic.__new__(cls, name, dummy_name, dim, eps_dim, metric_symmetry, metric_name) obj._autogenerated = [] return obj @property def name(self): return self.args[0].name @property def dummy_name(self): return self.args[1].name @property def dim(self): return self.args[2] @property def eps_dim(self): return self.args[3] @memoize_property def metric(self): metric_symmetry = self.args[4] metric_name = self.args[5] if metric_symmetry is None: return None if metric_symmetry == 0: symmetry = TensorSymmetry.no_symmetry(2) elif metric_symmetry == 1: symmetry = TensorSymmetry.fully_symmetric(2) elif metric_symmetry == -1: symmetry = TensorSymmetry.fully_symmetric(-2) return TensorHead(metric_name, [self]*2, symmetry) @memoize_property def delta(self): return TensorHead('KD', [self]*2, TensorSymmetry.fully_symmetric(2)) @memoize_property def epsilon(self): if not isinstance(self.eps_dim, (SYMPY_INTS, Integer)): return None symmetry = TensorSymmetry.fully_symmetric(-self.eps_dim) return TensorHead('Eps', [self]*self.eps_dim, symmetry) def set_metric(self, tensor): self._metric = tensor def __lt__(self, other): return self.name < other.name def __str__(self): return self.name __repr__ = __str__ # Everything below this line is deprecated @property def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return _tensor_data_substitution_dict[self] @data.setter def data(self, data): deprecate_data() # This assignment is a bit controversial, should metric components be assigned # to the metric only or also to the TensorIndexType object? The advantage here # is the ability to assign a 1D array and transform it to a 2D diagonal array. from .array import MutableDenseNDimArray data = _TensorDataLazyEvaluator.parse_data(data) if data.rank() > 2: raise ValueError("data have to be of rank 1 (diagonal metric) or 2.") if data.rank() == 1: if self.dim.is_number: nda_dim = data.shape[0] if nda_dim != self.dim: raise ValueError("Dimension mismatch") dim = data.shape[0] newndarray = MutableDenseNDimArray.zeros(dim, dim) for i, val in enumerate(data): newndarray[i, i] = val data = newndarray dim1, dim2 = data.shape if dim1 != dim2: raise ValueError("Non-square matrix tensor.") if self.dim.is_number: if self.dim != dim1: raise ValueError("Dimension mismatch") _tensor_data_substitution_dict[self] = data _tensor_data_substitution_dict.add_metric_data(self.metric, data) with ignore_warnings(SymPyDeprecationWarning): delta = self.get_kronecker_delta() i1 = TensorIndex('i1', self) i2 = TensorIndex('i2', self) with ignore_warnings(SymPyDeprecationWarning): delta(i1, -i2).data = _TensorDataLazyEvaluator.parse_data(eye(dim1)) @data.deleter def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] if self.metric in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self.metric] @deprecated( """ The TensorIndexType.get_kronecker_delta() method is deprecated. Use the TensorIndexType.delta attribute instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorindextype-methods", ) def get_kronecker_delta(self): sym2 = TensorSymmetry(get_symmetric_group_sgs(2)) delta = TensorHead('KD', [self]*2, sym2) return delta @deprecated( """ The TensorIndexType.get_epsilon() method is deprecated. Use the TensorIndexType.epsilon attribute instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorindextype-methods", ) def get_epsilon(self): if not isinstance(self._eps_dim, (SYMPY_INTS, Integer)): return None sym = TensorSymmetry(get_symmetric_group_sgs(self._eps_dim, 1)) epsilon = TensorHead('Eps', [self]*self._eps_dim, sym) return epsilon def _components_data_full_destroy(self): """ EXPERIMENTAL: do not rely on this API method. This destroys components data associated to the ``TensorIndexType``, if any, specifically: * metric tensor data * Kronecker tensor data """ if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] def delete_tensmul_data(key): if key in _tensor_data_substitution_dict._substitutions_dict_tensmul: del _tensor_data_substitution_dict._substitutions_dict_tensmul[key] # delete metric data: delete_tensmul_data((self.metric, True, True)) delete_tensmul_data((self.metric, True, False)) delete_tensmul_data((self.metric, False, True)) delete_tensmul_data((self.metric, False, False)) # delete delta tensor data: delta = self.get_kronecker_delta() if delta in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[delta] class TensorIndex(Basic): """ Represents a tensor index Parameters ========== name : name of the index, or ``True`` if you want it to be automatically assigned tensor_index_type : ``TensorIndexType`` of the index is_up : flag for contravariant index (is_up=True by default) Attributes ========== ``name`` ``tensor_index_type`` ``is_up`` Notes ===== Tensor indices are contracted with the Einstein summation convention. An index can be in contravariant or in covariant form; in the latter case it is represented prepending a ``-`` to the index name. Adding ``-`` to a covariant (is_up=False) index makes it contravariant. Dummy indices have a name with head given by ``tensor_inde_type.dummy_name`` with underscore and a number. Similar to ``symbols`` multiple contravariant indices can be created at once using ``tensor_indices(s, typ)``, where ``s`` is a string of names. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, TensorIndex, TensorHead, tensor_indices >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> mu = TensorIndex('mu', Lorentz, is_up=False) >>> nu, rho = tensor_indices('nu, rho', Lorentz) >>> A = TensorHead('A', [Lorentz, Lorentz]) >>> A(mu, nu) A(-mu, nu) >>> A(-mu, -rho) A(mu, -rho) >>> A(mu, -mu) A(-L_0, L_0) """ def __new__(cls, name, tensor_index_type, is_up=True): if isinstance(name, str): name_symbol = Symbol(name) elif isinstance(name, Symbol): name_symbol = name elif name is True: name = "_i{}".format(len(tensor_index_type._autogenerated)) name_symbol = Symbol(name) tensor_index_type._autogenerated.append(name_symbol) else: raise ValueError("invalid name") is_up = sympify(is_up) return Basic.__new__(cls, name_symbol, tensor_index_type, is_up) @property def name(self): return self.args[0].name @property def tensor_index_type(self): return self.args[1] @property def is_up(self): return self.args[2] def _print(self): s = self.name if not self.is_up: s = '-%s' % s return s def __lt__(self, other): return ((self.tensor_index_type, self.name) < (other.tensor_index_type, other.name)) def __neg__(self): t1 = TensorIndex(self.name, self.tensor_index_type, (not self.is_up)) return t1 def tensor_indices(s, typ): """ Returns list of tensor indices given their names and their types. Parameters ========== s : string of comma separated names of indices typ : ``TensorIndexType`` of the indices Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> a, b, c, d = tensor_indices('a,b,c,d', Lorentz) """ if isinstance(s, str): a = [x.name for x in symbols(s, seq=True)] else: raise ValueError('expecting a string') tilist = [TensorIndex(i, typ) for i in a] if len(tilist) == 1: return tilist[0] return tilist class TensorSymmetry(Basic): """ Monoterm symmetry of a tensor (i.e. any symmetric or anti-symmetric index permutation). For the relevant terminology see ``tensor_can.py`` section of the combinatorics module. Parameters ========== bsgs : tuple ``(base, sgs)`` BSGS of the symmetry of the tensor Attributes ========== ``base`` : base of the BSGS ``generators`` : generators of the BSGS ``rank`` : rank of the tensor Notes ===== A tensor can have an arbitrary monoterm symmetry provided by its BSGS. Multiterm symmetries, like the cyclic symmetry of the Riemann tensor (i.e., Bianchi identity), are not covered. See combinatorics module for information on how to generate BSGS for a general index permutation group. Simple symmetries can be generated using built-in methods. See Also ======== sympy.combinatorics.tensor_can.get_symmetric_group_sgs Examples ======== Define a symmetric tensor of rank 2 >>> from sympy.tensor.tensor import TensorIndexType, TensorSymmetry, get_symmetric_group_sgs, TensorHead >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> sym = TensorSymmetry(get_symmetric_group_sgs(2)) >>> T = TensorHead('T', [Lorentz]*2, sym) Note, that the same can also be done using built-in TensorSymmetry methods >>> sym2 = TensorSymmetry.fully_symmetric(2) >>> sym == sym2 True """ def __new__(cls, *args, **kw_args): if len(args) == 1: base, generators = args[0] elif len(args) == 2: base, generators = args else: raise TypeError("bsgs required, either two separate parameters or one tuple") if not isinstance(base, Tuple): base = Tuple(*base) if not isinstance(generators, Tuple): generators = Tuple(*generators) return Basic.__new__(cls, base, generators, **kw_args) @property def base(self): return self.args[0] @property def generators(self): return self.args[1] @property def rank(self): return self.generators[0].size - 2 @classmethod def fully_symmetric(cls, rank): """ Returns a fully symmetric (antisymmetric if ``rank``<0) TensorSymmetry object for ``abs(rank)`` indices. """ if rank > 0: bsgs = get_symmetric_group_sgs(rank, False) elif rank < 0: bsgs = get_symmetric_group_sgs(-rank, True) elif rank == 0: bsgs = ([], [Permutation(1)]) return TensorSymmetry(bsgs) @classmethod def direct_product(cls, *args): """ Returns a TensorSymmetry object that is being a direct product of fully (anti-)symmetric index permutation groups. Notes ===== Some examples for different values of ``(*args)``: ``(1)`` vector, equivalent to ``TensorSymmetry.fully_symmetric(1)`` ``(2)`` tensor with 2 symmetric indices, equivalent to ``.fully_symmetric(2)`` ``(-2)`` tensor with 2 antisymmetric indices, equivalent to ``.fully_symmetric(-2)`` ``(2, -2)`` tensor with the first 2 indices commuting and the last 2 anticommuting ``(1, 1, 1)`` tensor with 3 indices without any symmetry """ base, sgs = [], [Permutation(1)] for arg in args: if arg > 0: bsgs2 = get_symmetric_group_sgs(arg, False) elif arg < 0: bsgs2 = get_symmetric_group_sgs(-arg, True) else: continue base, sgs = bsgs_direct_product(base, sgs, *bsgs2) return TensorSymmetry(base, sgs) @classmethod def riemann(cls): """ Returns a monotorem symmetry of the Riemann tensor """ return TensorSymmetry(riemann_bsgs) @classmethod def no_symmetry(cls, rank): """ TensorSymmetry object for ``rank`` indices with no symmetry """ return TensorSymmetry([], [Permutation(rank+1)]) @deprecated( """ The tensorsymmetry() function is deprecated. Use the TensorSymmetry constructor instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorsymmetry", ) def tensorsymmetry(*args): """ Returns a ``TensorSymmetry`` object. This method is deprecated, use ``TensorSymmetry.direct_product()`` or ``.riemann()`` instead. Explanation =========== One can represent a tensor with any monoterm slot symmetry group using a BSGS. ``args`` can be a BSGS ``args[0]`` base ``args[1]`` sgs Usually tensors are in (direct products of) representations of the symmetric group; ``args`` can be a list of lists representing the shapes of Young tableaux Notes ===== For instance: ``[[1]]`` vector ``[[1]*n]`` symmetric tensor of rank ``n`` ``[[n]]`` antisymmetric tensor of rank ``n`` ``[[2, 2]]`` monoterm slot symmetry of the Riemann tensor ``[[1],[1]]`` vector*vector ``[[2],[1],[1]`` (antisymmetric tensor)*vector*vector Notice that with the shape ``[2, 2]`` we associate only the monoterm symmetries of the Riemann tensor; this is an abuse of notation, since the shape ``[2, 2]`` corresponds usually to the irreducible representation characterized by the monoterm symmetries and by the cyclic symmetry. """ from sympy.combinatorics import Permutation def tableau2bsgs(a): if len(a) == 1: # antisymmetric vector n = a[0] bsgs = get_symmetric_group_sgs(n, 1) else: if all(x == 1 for x in a): # symmetric vector n = len(a) bsgs = get_symmetric_group_sgs(n) elif a == [2, 2]: bsgs = riemann_bsgs else: raise NotImplementedError return bsgs if not args: return TensorSymmetry(Tuple(), Tuple(Permutation(1))) if len(args) == 2 and isinstance(args[1][0], Permutation): return TensorSymmetry(args) base, sgs = tableau2bsgs(args[0]) for a in args[1:]: basex, sgsx = tableau2bsgs(a) base, sgs = bsgs_direct_product(base, sgs, basex, sgsx) return TensorSymmetry(Tuple(base, sgs)) @deprecated( "TensorType is deprecated. Use tensor_heads() instead.", deprecated_since_version="1.5", active_deprecations_target="deprecated-tensortype", ) class TensorType(Basic): """ Class of tensor types. Deprecated, use tensor_heads() instead. Parameters ========== index_types : list of ``TensorIndexType`` of the tensor indices symmetry : ``TensorSymmetry`` of the tensor Attributes ========== ``index_types`` ``symmetry`` ``types`` : list of ``TensorIndexType`` without repetitions """ is_commutative = False def __new__(cls, index_types, symmetry, **kw_args): assert symmetry.rank == len(index_types) obj = Basic.__new__(cls, Tuple(*index_types), symmetry, **kw_args) return obj @property def index_types(self): return self.args[0] @property def symmetry(self): return self.args[1] @property def types(self): return sorted(set(self.index_types), key=lambda x: x.name) def __str__(self): return 'TensorType(%s)' % ([str(x) for x in self.index_types]) def __call__(self, s, comm=0): """ Return a TensorHead object or a list of TensorHead objects. Parameters ========== s : name or string of names. comm : Commutation group. see ``_TensorManager.set_comm`` """ if isinstance(s, str): names = [x.name for x in symbols(s, seq=True)] else: raise ValueError('expecting a string') if len(names) == 1: return TensorHead(names[0], self.index_types, self.symmetry, comm) else: return [TensorHead(name, self.index_types, self.symmetry, comm) for name in names] @deprecated( """ The tensorhead() function is deprecated. Use tensor_heads() instead. """, deprecated_since_version="1.5", active_deprecations_target="deprecated-tensorhead", ) def tensorhead(name, typ, sym=None, comm=0): """ Function generating tensorhead(s). This method is deprecated, use TensorHead constructor or tensor_heads() instead. Parameters ========== name : name or sequence of names (as in ``symbols``) typ : index types sym : same as ``*args`` in ``tensorsymmetry`` comm : commutation group number see ``_TensorManager.set_comm`` """ if sym is None: sym = [[1] for i in range(len(typ))] with ignore_warnings(SymPyDeprecationWarning): sym = tensorsymmetry(*sym) return TensorHead(name, typ, sym, comm) class TensorHead(Basic): """ Tensor head of the tensor. Parameters ========== name : name of the tensor index_types : list of TensorIndexType symmetry : TensorSymmetry of the tensor comm : commutation group number Attributes ========== ``name`` ``index_types`` ``rank`` : total number of indices ``symmetry`` ``comm`` : commutation group Notes ===== Similar to ``symbols`` multiple TensorHeads can be created using ``tensorhead(s, typ, sym=None, comm=0)`` function, where ``s`` is the string of names and ``sym`` is the monoterm tensor symmetry (see ``tensorsymmetry``). A ``TensorHead`` belongs to a commutation group, defined by a symbol on number ``comm`` (see ``_TensorManager.set_comm``); tensors in a commutation group have the same commutation properties; by default ``comm`` is ``0``, the group of the commuting tensors. Examples ======== Define a fully antisymmetric tensor of rank 2: >>> from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> asym2 = TensorSymmetry.fully_symmetric(-2) >>> A = TensorHead('A', [Lorentz, Lorentz], asym2) Examples with ndarray values, the components data assigned to the ``TensorHead`` object are assumed to be in a fully-contravariant representation. In case it is necessary to assign components data which represents the values of a non-fully covariant tensor, see the other examples. >>> from sympy.tensor.tensor import tensor_indices >>> from sympy import diag >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> i0, i1 = tensor_indices('i0:2', Lorentz) Specify a replacement dictionary to keep track of the arrays to use for replacements in the tensorial expression. The ``TensorIndexType`` is associated to the metric used for contractions (in fully covariant form): >>> repl = {Lorentz: diag(1, -1, -1, -1)} Let's see some examples of working with components with the electromagnetic tensor: >>> from sympy import symbols >>> Ex, Ey, Ez, Bx, By, Bz = symbols('E_x E_y E_z B_x B_y B_z') >>> c = symbols('c', positive=True) Let's define `F`, an antisymmetric tensor: >>> F = TensorHead('F', [Lorentz, Lorentz], asym2) Let's update the dictionary to contain the matrix to use in the replacements: >>> repl.update({F(-i0, -i1): [ ... [0, Ex/c, Ey/c, Ez/c], ... [-Ex/c, 0, -Bz, By], ... [-Ey/c, Bz, 0, -Bx], ... [-Ez/c, -By, Bx, 0]]}) Now it is possible to retrieve the contravariant form of the Electromagnetic tensor: >>> F(i0, i1).replace_with_arrays(repl, [i0, i1]) [[0, -E_x/c, -E_y/c, -E_z/c], [E_x/c, 0, -B_z, B_y], [E_y/c, B_z, 0, -B_x], [E_z/c, -B_y, B_x, 0]] and the mixed contravariant-covariant form: >>> F(i0, -i1).replace_with_arrays(repl, [i0, -i1]) [[0, E_x/c, E_y/c, E_z/c], [E_x/c, 0, B_z, -B_y], [E_y/c, -B_z, 0, B_x], [E_z/c, B_y, -B_x, 0]] Energy-momentum of a particle may be represented as: >>> from sympy import symbols >>> P = TensorHead('P', [Lorentz], TensorSymmetry.no_symmetry(1)) >>> E, px, py, pz = symbols('E p_x p_y p_z', positive=True) >>> repl.update({P(i0): [E, px, py, pz]}) The contravariant and covariant components are, respectively: >>> P(i0).replace_with_arrays(repl, [i0]) [E, p_x, p_y, p_z] >>> P(-i0).replace_with_arrays(repl, [-i0]) [E, -p_x, -p_y, -p_z] The contraction of a 1-index tensor by itself: >>> expr = P(i0)*P(-i0) >>> expr.replace_with_arrays(repl, []) E**2 - p_x**2 - p_y**2 - p_z**2 """ is_commutative = False def __new__(cls, name, index_types, symmetry=None, comm=0): if isinstance(name, str): name_symbol = Symbol(name) elif isinstance(name, Symbol): name_symbol = name else: raise ValueError("invalid name") if symmetry is None: symmetry = TensorSymmetry.no_symmetry(len(index_types)) else: assert symmetry.rank == len(index_types) obj = Basic.__new__(cls, name_symbol, Tuple(*index_types), symmetry) obj.comm = TensorManager.comm_symbols2i(comm) return obj @property def name(self): return self.args[0].name @property def index_types(self): return list(self.args[1]) @property def symmetry(self): return self.args[2] @property def rank(self): return len(self.index_types) def __lt__(self, other): return (self.name, self.index_types) < (other.name, other.index_types) def commutes_with(self, other): """ Returns ``0`` if ``self`` and ``other`` commute, ``1`` if they anticommute. Returns ``None`` if ``self`` and ``other`` neither commute nor anticommute. """ r = TensorManager.get_comm(self.comm, other.comm) return r def _print(self): return '%s(%s)' %(self.name, ','.join([str(x) for x in self.index_types])) def __call__(self, *indices, **kw_args): """ Returns a tensor with indices. Explanation =========== There is a special behavior in case of indices denoted by ``True``, they are considered auto-matrix indices, their slots are automatically filled, and confer to the tensor the behavior of a matrix or vector upon multiplication with another tensor containing auto-matrix indices of the same ``TensorIndexType``. This means indices get summed over the same way as in matrix multiplication. For matrix behavior, define two auto-matrix indices, for vector behavior define just one. Indices can also be strings, in which case the attribute ``index_types`` is used to convert them to proper ``TensorIndex``. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorSymmetry, TensorHead >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> a, b = tensor_indices('a,b', Lorentz) >>> A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2)) >>> t = A(a, -b) >>> t A(a, -b) """ updated_indices = [] for idx, typ in zip(indices, self.index_types): if isinstance(idx, str): idx = idx.strip().replace(" ", "") if idx.startswith('-'): updated_indices.append(TensorIndex(idx[1:], typ, is_up=False)) else: updated_indices.append(TensorIndex(idx, typ)) else: updated_indices.append(idx) updated_indices += indices[len(updated_indices):] tensor = Tensor(self, updated_indices, **kw_args) return tensor.doit() # Everything below this line is deprecated def __pow__(self, other): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self.data is None: raise ValueError("No power on abstract tensors.") from .array import tensorproduct, tensorcontraction metrics = [_.data for _ in self.index_types] marray = self.data marraydim = marray.rank() for metric in metrics: marray = tensorproduct(marray, metric, marray) marray = tensorcontraction(marray, (0, marraydim), (marraydim+1, marraydim+2)) return marray ** (other * S.Half) @property def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return _tensor_data_substitution_dict[self] @data.setter def data(self, data): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): _tensor_data_substitution_dict[self] = data @data.deleter def data(self): deprecate_data() if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] def __iter__(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return self.data.__iter__() def _components_data_full_destroy(self): """ EXPERIMENTAL: do not rely on this API method. Destroy components data associated to the ``TensorHead`` object, this checks for attached components data, and destroys components data too. """ # do not garbage collect Kronecker tensor (it should be done by # ``TensorIndexType`` garbage collection) deprecate_data() if self.name == "KD": return # the data attached to a tensor must be deleted only by the TensorHead # destructor. If the TensorHead is deleted, it means that there are no # more instances of that tensor anywhere. if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] def tensor_heads(s, index_types, symmetry=None, comm=0): """ Returns a sequence of TensorHeads from a string `s` """ if isinstance(s, str): names = [x.name for x in symbols(s, seq=True)] else: raise ValueError('expecting a string') thlist = [TensorHead(name, index_types, symmetry, comm) for name in names] if len(thlist) == 1: return thlist[0] return thlist class _TensorMetaclass(ManagedProperties, ABCMeta): pass class TensExpr(Expr, metaclass=_TensorMetaclass): """ Abstract base class for tensor expressions Notes ===== A tensor expression is an expression formed by tensors; currently the sums of tensors are distributed. A ``TensExpr`` can be a ``TensAdd`` or a ``TensMul``. ``TensMul`` objects are formed by products of component tensors, and include a coefficient, which is a SymPy expression. In the internal representation contracted indices are represented by ``(ipos1, ipos2, icomp1, icomp2)``, where ``icomp1`` is the position of the component tensor with contravariant index, ``ipos1`` is the slot which the index occupies in that component tensor. Contracted indices are therefore nameless in the internal representation. """ _op_priority = 12.0 is_commutative = False def __neg__(self): return self*S.NegativeOne def __abs__(self): raise NotImplementedError def __add__(self, other): return TensAdd(self, other).doit() def __radd__(self, other): return TensAdd(other, self).doit() def __sub__(self, other): return TensAdd(self, -other).doit() def __rsub__(self, other): return TensAdd(other, -self).doit() def __mul__(self, other): """ Multiply two tensors using Einstein summation convention. Explanation =========== If the two tensors have an index in common, one contravariant and the other covariant, in their product the indices are summed Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) >>> g = Lorentz.metric >>> p, q = tensor_heads('p,q', [Lorentz]) >>> t1 = p(m0) >>> t2 = q(-m0) >>> t1*t2 p(L_0)*q(-L_0) """ return TensMul(self, other).doit() def __rmul__(self, other): return TensMul(other, self).doit() def __truediv__(self, other): other = _sympify(other) if isinstance(other, TensExpr): raise ValueError('cannot divide by a tensor') return TensMul(self, S.One/other).doit() def __rtruediv__(self, other): raise ValueError('cannot divide by a tensor') def __pow__(self, other): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self.data is None: raise ValueError("No power without ndarray data.") from .array import tensorproduct, tensorcontraction free = self.free marray = self.data mdim = marray.rank() for metric in free: marray = tensorcontraction( tensorproduct( marray, metric[0].tensor_index_type.data, marray), (0, mdim), (mdim+1, mdim+2) ) return marray ** (other * S.Half) def __rpow__(self, other): raise NotImplementedError @property @abstractmethod def nocoeff(self): raise NotImplementedError("abstract method") @property @abstractmethod def coeff(self): raise NotImplementedError("abstract method") @abstractmethod def get_indices(self): raise NotImplementedError("abstract method") @abstractmethod def get_free_indices(self) -> list[TensorIndex]: raise NotImplementedError("abstract method") @abstractmethod def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr: raise NotImplementedError("abstract method") def fun_eval(self, *index_tuples): deprecate_fun_eval() return self.substitute_indices(*index_tuples) def get_matrix(self): """ DEPRECATED: do not use. Returns ndarray components data as a matrix, if components data are available and ndarray dimension does not exceed 2. """ from sympy.matrices.dense import Matrix deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if 0 < self.rank <= 2: rows = self.data.shape[0] columns = self.data.shape[1] if self.rank == 2 else 1 if self.rank == 2: mat_list = [] * rows for i in range(rows): mat_list.append([]) for j in range(columns): mat_list[i].append(self[i, j]) else: mat_list = [None] * rows for i in range(rows): mat_list[i] = self[i] return Matrix(mat_list) else: raise NotImplementedError( "missing multidimensional reduction to matrix.") @staticmethod def _get_indices_permutation(indices1, indices2): return [indices1.index(i) for i in indices2] def expand(self, **hints): return _expand(self, **hints).doit() def _expand(self, **kwargs): return self def _get_free_indices_set(self): indset = set() for arg in self.args: if isinstance(arg, TensExpr): indset.update(arg._get_free_indices_set()) return indset def _get_dummy_indices_set(self): indset = set() for arg in self.args: if isinstance(arg, TensExpr): indset.update(arg._get_dummy_indices_set()) return indset def _get_indices_set(self): indset = set() for arg in self.args: if isinstance(arg, TensExpr): indset.update(arg._get_indices_set()) return indset @property def _iterate_dummy_indices(self): dummy_set = self._get_dummy_indices_set() def recursor(expr, pos): if isinstance(expr, TensorIndex): if expr in dummy_set: yield (expr, pos) elif isinstance(expr, (Tuple, TensExpr)): for p, arg in enumerate(expr.args): yield from recursor(arg, pos+(p,)) return recursor(self, ()) @property def _iterate_free_indices(self): free_set = self._get_free_indices_set() def recursor(expr, pos): if isinstance(expr, TensorIndex): if expr in free_set: yield (expr, pos) elif isinstance(expr, (Tuple, TensExpr)): for p, arg in enumerate(expr.args): yield from recursor(arg, pos+(p,)) return recursor(self, ()) @property def _iterate_indices(self): def recursor(expr, pos): if isinstance(expr, TensorIndex): yield (expr, pos) elif isinstance(expr, (Tuple, TensExpr)): for p, arg in enumerate(expr.args): yield from recursor(arg, pos+(p,)) return recursor(self, ()) @staticmethod def _contract_and_permute_with_metric(metric, array, pos, dim): # TODO: add possibility of metric after (spinors) from .array import tensorcontraction, tensorproduct, permutedims array = tensorcontraction(tensorproduct(metric, array), (1, 2+pos)) permu = list(range(dim)) permu[0], permu[pos] = permu[pos], permu[0] return permutedims(array, permu) @staticmethod def _match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict): from .array import permutedims index_types1 = [i.tensor_index_type for i in free_ind1] # Check if variance of indices needs to be fixed: pos2up = [] pos2down = [] free2remaining = free_ind2[:] for pos1, index1 in enumerate(free_ind1): if index1 in free2remaining: pos2 = free2remaining.index(index1) free2remaining[pos2] = None continue if -index1 in free2remaining: pos2 = free2remaining.index(-index1) free2remaining[pos2] = None free_ind2[pos2] = index1 if index1.is_up: pos2up.append(pos2) else: pos2down.append(pos2) else: index2 = free2remaining[pos1] if index2 is None: raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2)) free2remaining[pos1] = None free_ind2[pos1] = index1 if index1.is_up ^ index2.is_up: if index1.is_up: pos2up.append(pos1) else: pos2down.append(pos1) if len(set(free_ind1) & set(free_ind2)) < len(free_ind1): raise ValueError("incompatible indices: %s and %s" % (free_ind1, free_ind2)) # Raise indices: for pos in pos2up: index_type_pos = index_types1[pos] if index_type_pos not in replacement_dict: raise ValueError("No metric provided to lower index") metric = replacement_dict[index_type_pos] metric_inverse = _TensorDataLazyEvaluator.inverse_matrix(metric) array = TensExpr._contract_and_permute_with_metric(metric_inverse, array, pos, len(free_ind1)) # Lower indices: for pos in pos2down: index_type_pos = index_types1[pos] if index_type_pos not in replacement_dict: raise ValueError("No metric provided to lower index") metric = replacement_dict[index_type_pos] array = TensExpr._contract_and_permute_with_metric(metric, array, pos, len(free_ind1)) if free_ind1: permutation = TensExpr._get_indices_permutation(free_ind2, free_ind1) array = permutedims(array, permutation) if hasattr(array, "rank") and array.rank() == 0: array = array[()] return free_ind2, array def replace_with_arrays(self, replacement_dict, indices=None): """ Replace the tensorial expressions with arrays. The final array will correspond to the N-dimensional array with indices arranged according to ``indices``. Parameters ========== replacement_dict dictionary containing the replacement rules for tensors. indices the index order with respect to which the array is read. The original index order will be used if no value is passed. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices >>> from sympy.tensor.tensor import TensorHead >>> from sympy import symbols, diag >>> L = TensorIndexType("L") >>> i, j = tensor_indices("i j", L) >>> A = TensorHead("A", [L]) >>> A(i).replace_with_arrays({A(i): [1, 2]}, [i]) [1, 2] Since 'indices' is optional, we can also call replace_with_arrays by this way if no specific index order is needed: >>> A(i).replace_with_arrays({A(i): [1, 2]}) [1, 2] >>> expr = A(i)*A(j) >>> expr.replace_with_arrays({A(i): [1, 2]}) [[1, 2], [2, 4]] For contractions, specify the metric of the ``TensorIndexType``, which in this case is ``L``, in its covariant form: >>> expr = A(i)*A(-i) >>> expr.replace_with_arrays({A(i): [1, 2], L: diag(1, -1)}) -3 Symmetrization of an array: >>> H = TensorHead("H", [L, L]) >>> a, b, c, d = symbols("a b c d") >>> expr = H(i, j)/2 + H(j, i)/2 >>> expr.replace_with_arrays({H(i, j): [[a, b], [c, d]]}) [[a, b/2 + c/2], [b/2 + c/2, d]] Anti-symmetrization of an array: >>> expr = H(i, j)/2 - H(j, i)/2 >>> repl = {H(i, j): [[a, b], [c, d]]} >>> expr.replace_with_arrays(repl) [[0, b/2 - c/2], [-b/2 + c/2, 0]] The same expression can be read as the transpose by inverting ``i`` and ``j``: >>> expr.replace_with_arrays(repl, [j, i]) [[0, -b/2 + c/2], [b/2 - c/2, 0]] """ from .array import Array indices = indices or [] remap = {k.args[0] if k.is_up else -k.args[0]: k for k in self.get_free_indices()} for i, index in enumerate(indices): if isinstance(index, (Symbol, Mul)): if index in remap: indices[i] = remap[index] else: indices[i] = -remap[-index] replacement_dict = {tensor: Array(array) for tensor, array in replacement_dict.items()} # Check dimensions of replaced arrays: for tensor, array in replacement_dict.items(): if isinstance(tensor, TensorIndexType): expected_shape = [tensor.dim for i in range(2)] else: expected_shape = [index_type.dim for index_type in tensor.index_types] if len(expected_shape) != array.rank() or (not all(dim1 == dim2 if dim1.is_number else True for dim1, dim2 in zip(expected_shape, array.shape))): raise ValueError("shapes for tensor %s expected to be %s, "\ "replacement array shape is %s" % (tensor, expected_shape, array.shape)) ret_indices, array = self._extract_data(replacement_dict) last_indices, array = self._match_indices_with_other_tensor(array, indices, ret_indices, replacement_dict) return array def _check_add_Sum(self, expr, index_symbols): from sympy.concrete.summations import Sum indices = self.get_indices() dum = self.dum sum_indices = [ (index_symbols[i], 0, indices[i].tensor_index_type.dim-1) for i, j in dum] if sum_indices: expr = Sum(expr, *sum_indices) return expr def _expand_partial_derivative(self): # simply delegate the _expand_partial_derivative() to # its arguments to expand a possibly found PartialDerivative return self.func(*[ a._expand_partial_derivative() if isinstance(a, TensExpr) else a for a in self.args]) class TensAdd(TensExpr, AssocOp): """ Sum of tensors. Parameters ========== free_args : list of the free indices Attributes ========== ``args`` : tuple of addends ``rank`` : rank of the tensor ``free_args`` : list of the free indices in sorted order Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_heads, tensor_indices >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> a, b = tensor_indices('a,b', Lorentz) >>> p, q = tensor_heads('p,q', [Lorentz]) >>> t = p(a) + q(a); t p(a) + q(a) Examples with components data added to the tensor expression: >>> from sympy import symbols, diag >>> x, y, z, t = symbols("x y z t") >>> repl = {} >>> repl[Lorentz] = diag(1, -1, -1, -1) >>> repl[p(a)] = [1, 2, 3, 4] >>> repl[q(a)] = [x, y, z, t] The following are: 2**2 - 3**2 - 2**2 - 7**2 ==> -58 >>> expr = p(a) + q(a) >>> expr.replace_with_arrays(repl, [a]) [x + 1, y + 2, z + 3, t + 4] """ def __new__(cls, *args, **kw_args): args = [_sympify(x) for x in args if x] args = TensAdd._tensAdd_flatten(args) args.sort(key=default_sort_key) if not args: return S.Zero if len(args) == 1: return args[0] return Basic.__new__(cls, *args, **kw_args) @property def coeff(self): return S.One @property def nocoeff(self): return self def get_free_indices(self) -> list[TensorIndex]: return self.free_indices def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr: newargs = [arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg in self.args] return self.func(*newargs) @memoize_property def rank(self): if isinstance(self.args[0], TensExpr): return self.args[0].rank else: return 0 @memoize_property def free_args(self): if isinstance(self.args[0], TensExpr): return self.args[0].free_args else: return [] @memoize_property def free_indices(self): if isinstance(self.args[0], TensExpr): return self.args[0].get_free_indices() else: return set() def doit(self, **hints): deep = hints.get('deep', True) if deep: args = [arg.doit(**hints) for arg in self.args] else: args = self.args # if any of the args are zero (after doit), drop them. Otherwise, _tensAdd_check will complain about non-matching indices, even though the TensAdd is correctly formed. args = [arg for arg in args if arg != S.Zero] if len(args) == 0: return S.Zero elif len(args) == 1: return args[0] # now check that all addends have the same indices: TensAdd._tensAdd_check(args) # Collect terms appearing more than once, differing by their coefficients: args = TensAdd._tensAdd_collect_terms(args) # collect canonicalized terms def sort_key(t): if not isinstance(t, TensExpr): return [], [], [] if hasattr(t, "_index_structure") and hasattr(t, "components"): x = get_index_structure(t) return t.components, x.free, x.dum return [], [], [] args.sort(key=sort_key) if not args: return S.Zero # it there is only a component tensor return it if len(args) == 1: return args[0] obj = self.func(*args) return obj @staticmethod def _tensAdd_flatten(args): # flatten TensAdd, coerce terms which are not tensors to tensors a = [] for x in args: if isinstance(x, (Add, TensAdd)): a.extend(list(x.args)) else: a.append(x) args = [x for x in a if x.coeff] return args @staticmethod def _tensAdd_check(args): # check that all addends have the same free indices def get_indices_set(x: Expr) -> set[TensorIndex]: if isinstance(x, TensExpr): return set(x.get_free_indices()) return set() indices0 = get_indices_set(args[0]) list_indices = [get_indices_set(arg) for arg in args[1:]] if not all(x == indices0 for x in list_indices): raise ValueError('all tensors must have the same indices') @staticmethod def _tensAdd_collect_terms(args): # collect TensMul terms differing at most by their coefficient terms_dict = defaultdict(list) scalars = S.Zero if isinstance(args[0], TensExpr): free_indices = set(args[0].get_free_indices()) else: free_indices = set() for arg in args: if not isinstance(arg, TensExpr): if free_indices != set(): raise ValueError("wrong valence") scalars += arg continue if free_indices != set(arg.get_free_indices()): raise ValueError("wrong valence") # TODO: what is the part which is not a coeff? # needs an implementation similar to .as_coeff_Mul() terms_dict[arg.nocoeff].append(arg.coeff) new_args = [TensMul(Add(*coeff), t).doit() for t, coeff in terms_dict.items() if Add(*coeff) != 0] if isinstance(scalars, Add): new_args = list(scalars.args) + new_args elif scalars != 0: new_args = [scalars] + new_args return new_args def get_indices(self): indices = [] for arg in self.args: indices.extend([i for i in get_indices(arg) if i not in indices]) return indices def _expand(self, **hints): return TensAdd(*[_expand(i, **hints) for i in self.args]) def __call__(self, *indices): deprecate_call() free_args = self.free_args indices = list(indices) if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]: raise ValueError('incompatible types') if indices == free_args: return self index_tuples = list(zip(free_args, indices)) a = [x.func(*x.substitute_indices(*index_tuples).args) for x in self.args] res = TensAdd(*a).doit() return res def canon_bp(self): """ Canonicalize using the Butler-Portugal algorithm for canonicalization under monoterm symmetries. """ expr = self.expand() args = [canon_bp(x) for x in expr.args] res = TensAdd(*args).doit() return res def equals(self, other): other = _sympify(other) if isinstance(other, TensMul) and other.coeff == 0: return all(x.coeff == 0 for x in self.args) if isinstance(other, TensExpr): if self.rank != other.rank: return False if isinstance(other, TensAdd): if set(self.args) != set(other.args): return False else: return True t = self - other if not isinstance(t, TensExpr): return t == 0 else: if isinstance(t, TensMul): return t.coeff == 0 else: return all(x.coeff == 0 for x in t.args) def __getitem__(self, item): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return self.data[item] def contract_delta(self, delta): args = [x.contract_delta(delta) for x in self.args] t = TensAdd(*args).doit() return canon_bp(t) def contract_metric(self, g): """ Raise or lower indices with the metric ``g``. Parameters ========== g : metric contract_all : if True, eliminate all ``g`` which are contracted Notes ===== see the ``TensorIndexType`` docstring for the contraction conventions """ args = [contract_metric(x, g) for x in self.args] t = TensAdd(*args).doit() return canon_bp(t) def substitute_indices(self, *index_tuples): new_args = [] for arg in self.args: if isinstance(arg, TensExpr): arg = arg.substitute_indices(*index_tuples) new_args.append(arg) return TensAdd(*new_args).doit() def _print(self): a = [] args = self.args for x in args: a.append(str(x)) s = ' + '.join(a) s = s.replace('+ -', '- ') return s def _extract_data(self, replacement_dict): from sympy.tensor.array import Array, permutedims args_indices, arrays = zip(*[ arg._extract_data(replacement_dict) if isinstance(arg, TensExpr) else ([], arg) for arg in self.args ]) arrays = [Array(i) for i in arrays] ref_indices = args_indices[0] for i in range(1, len(args_indices)): indices = args_indices[i] array = arrays[i] permutation = TensMul._get_indices_permutation(indices, ref_indices) arrays[i] = permutedims(array, permutation) return ref_indices, sum(arrays, Array.zeros(*array.shape)) @property def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return _tensor_data_substitution_dict[self.expand()] @data.setter def data(self, data): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): _tensor_data_substitution_dict[self] = data @data.deleter def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] def __iter__(self): deprecate_data() if not self.data: raise ValueError("No iteration on abstract tensors") return self.data.flatten().__iter__() def _eval_rewrite_as_Indexed(self, *args): return Add.fromiter(args) def _eval_partial_derivative(self, s): # Evaluation like Add list_addends = [] for a in self.args: if isinstance(a, TensExpr): list_addends.append(a._eval_partial_derivative(s)) # do not call diff if s is no symbol elif s._diff_wrt: list_addends.append(a._eval_derivative(s)) return self.func(*list_addends) class Tensor(TensExpr): """ Base tensor class, i.e. this represents a tensor, the single unit to be put into an expression. Explanation =========== This object is usually created from a ``TensorHead``, by attaching indices to it. Indices preceded by a minus sign are considered contravariant, otherwise covariant. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead >>> Lorentz = TensorIndexType("Lorentz", dummy_name="L") >>> mu, nu = tensor_indices('mu nu', Lorentz) >>> A = TensorHead("A", [Lorentz, Lorentz]) >>> A(mu, -nu) A(mu, -nu) >>> A(mu, -mu) A(L_0, -L_0) It is also possible to use symbols instead of inidices (appropriate indices are then generated automatically). >>> from sympy import Symbol >>> x = Symbol('x') >>> A(x, mu) A(x, mu) >>> A(x, -x) A(L_0, -L_0) """ is_commutative = False _index_structure = None # type: _IndexStructure args: tuple[TensorHead, Tuple] def __new__(cls, tensor_head, indices, *, is_canon_bp=False, **kw_args): indices = cls._parse_indices(tensor_head, indices) obj = Basic.__new__(cls, tensor_head, Tuple(*indices), **kw_args) obj._index_structure = _IndexStructure.from_indices(*indices) obj._free = obj._index_structure.free[:] obj._dum = obj._index_structure.dum[:] obj._ext_rank = obj._index_structure._ext_rank obj._coeff = S.One obj._nocoeff = obj obj._component = tensor_head obj._components = [tensor_head] if tensor_head.rank != len(indices): raise ValueError("wrong number of indices") obj.is_canon_bp = is_canon_bp obj._index_map = Tensor._build_index_map(indices, obj._index_structure) return obj @property def free(self): return self._free @property def dum(self): return self._dum @property def ext_rank(self): return self._ext_rank @property def coeff(self): return self._coeff @property def nocoeff(self): return self._nocoeff @property def component(self): return self._component @property def components(self): return self._components @property def head(self): return self.args[0] @property def indices(self): return self.args[1] @property def free_indices(self): return set(self._index_structure.get_free_indices()) @property def index_types(self): return self.head.index_types @property def rank(self): return len(self.free_indices) @staticmethod def _build_index_map(indices, index_structure): index_map = {} for idx in indices: index_map[idx] = (indices.index(idx),) return index_map def doit(self, **hints): args, indices, free, dum = TensMul._tensMul_contract_indices([self]) return args[0] @staticmethod def _parse_indices(tensor_head, indices): if not isinstance(indices, (tuple, list, Tuple)): raise TypeError("indices should be an array, got %s" % type(indices)) indices = list(indices) for i, index in enumerate(indices): if isinstance(index, Symbol): indices[i] = TensorIndex(index, tensor_head.index_types[i], True) elif isinstance(index, Mul): c, e = index.as_coeff_Mul() if c == -1 and isinstance(e, Symbol): indices[i] = TensorIndex(e, tensor_head.index_types[i], False) else: raise ValueError("index not understood: %s" % index) elif not isinstance(index, TensorIndex): raise TypeError("wrong type for index: %s is %s" % (index, type(index))) return indices def _set_new_index_structure(self, im, is_canon_bp=False): indices = im.get_indices() return self._set_indices(*indices, is_canon_bp=is_canon_bp) def _set_indices(self, *indices, is_canon_bp=False, **kw_args): if len(indices) != self.ext_rank: raise ValueError("indices length mismatch") return self.func(self.args[0], indices, is_canon_bp=is_canon_bp).doit() def _get_free_indices_set(self): return {i[0] for i in self._index_structure.free} def _get_dummy_indices_set(self): dummy_pos = set(itertools.chain(*self._index_structure.dum)) return {idx for i, idx in enumerate(self.args[1]) if i in dummy_pos} def _get_indices_set(self): return set(self.args[1].args) @property def free_in_args(self): return [(ind, pos, 0) for ind, pos in self.free] @property def dum_in_args(self): return [(p1, p2, 0, 0) for p1, p2 in self.dum] @property def free_args(self): return sorted([x[0] for x in self.free]) def commutes_with(self, other): """ :param other: :return: 0 commute 1 anticommute None neither commute nor anticommute """ if not isinstance(other, TensExpr): return 0 elif isinstance(other, Tensor): return self.component.commutes_with(other.component) return NotImplementedError def perm2tensor(self, g, is_canon_bp=False): """ Returns the tensor corresponding to the permutation ``g``. For further details, see the method in ``TIDS`` with the same name. """ return perm2tensor(self, g, is_canon_bp) def canon_bp(self): if self.is_canon_bp: return self expr = self.expand() g, dummies, msym = expr._index_structure.indices_canon_args() v = components_canon_args([expr.component]) can = canonicalize(g, dummies, msym, *v) if can == 0: return S.Zero tensor = self.perm2tensor(can, True) return tensor def split(self): return [self] def _expand(self, **kwargs): return self def sorted_components(self): return self def get_indices(self) -> list[TensorIndex]: """ Get a list of indices, corresponding to those of the tensor. """ return list(self.args[1]) def get_free_indices(self) -> list[TensorIndex]: """ Get a list of free indices, corresponding to those of the tensor. """ return self._index_structure.get_free_indices() def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr: # TODO: this could be optimized by only swapping the indices # instead of visiting the whole expression tree: return self.xreplace(repl) def as_base_exp(self): return self, S.One def substitute_indices(self, *index_tuples): """ Return a tensor with free indices substituted according to ``index_tuples``. ``index_types`` list of tuples ``(old_index, new_index)``. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz) >>> A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) >>> t = A(i, k)*B(-k, -j); t A(i, L_0)*B(-L_0, -j) >>> t.substitute_indices((i, k),(-j, l)) A(k, L_0)*B(-L_0, l) """ indices = [] for index in self.indices: for ind_old, ind_new in index_tuples: if (index.name == ind_old.name and index.tensor_index_type == ind_old.tensor_index_type): if index.is_up == ind_old.is_up: indices.append(ind_new) else: indices.append(-ind_new) break else: indices.append(index) return self.head(*indices) def __call__(self, *indices): deprecate_call() free_args = self.free_args indices = list(indices) if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]: raise ValueError('incompatible types') if indices == free_args: return self t = self.substitute_indices(*list(zip(free_args, indices))) # object is rebuilt in order to make sure that all contracted indices # get recognized as dummies, but only if there are contracted indices. if len({i if i.is_up else -i for i in indices}) != len(indices): return t.func(*t.args) return t # TODO: put this into TensExpr? def __iter__(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return self.data.__iter__() # TODO: put this into TensExpr? def __getitem__(self, item): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return self.data[item] def _extract_data(self, replacement_dict): from .array import Array for k, v in replacement_dict.items(): if isinstance(k, Tensor) and k.args[0] == self.args[0]: other = k array = v break else: raise ValueError("%s not found in %s" % (self, replacement_dict)) # TODO: inefficient, this should be done at root level only: replacement_dict = {k: Array(v) for k, v in replacement_dict.items()} array = Array(array) dum1 = self.dum dum2 = other.dum if len(dum2) > 0: for pair in dum2: # allow `dum2` if the contained values are also in `dum1`. if pair not in dum1: raise NotImplementedError("%s with contractions is not implemented" % other) # Remove elements in `dum2` from `dum1`: dum1 = [pair for pair in dum1 if pair not in dum2] if len(dum1) > 0: indices1 = self.get_indices() indices2 = other.get_indices() repl = {} for p1, p2 in dum1: repl[indices2[p2]] = -indices2[p1] for pos in (p1, p2): if indices1[pos].is_up ^ indices2[pos].is_up: metric = replacement_dict[indices1[pos].tensor_index_type] if indices1[pos].is_up: metric = _TensorDataLazyEvaluator.inverse_matrix(metric) array = self._contract_and_permute_with_metric(metric, array, pos, len(indices2)) other = other.xreplace(repl).doit() array = _TensorDataLazyEvaluator.data_contract_dum([array], dum1, len(indices2)) free_ind1 = self.get_free_indices() free_ind2 = other.get_free_indices() return self._match_indices_with_other_tensor(array, free_ind1, free_ind2, replacement_dict) @property def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return _tensor_data_substitution_dict[self] @data.setter def data(self, data): deprecate_data() # TODO: check data compatibility with properties of tensor. with ignore_warnings(SymPyDeprecationWarning): _tensor_data_substitution_dict[self] = data @data.deleter def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self] if self.metric in _tensor_data_substitution_dict: del _tensor_data_substitution_dict[self.metric] def _print(self): indices = [str(ind) for ind in self.indices] component = self.component if component.rank > 0: return ('%s(%s)' % (component.name, ', '.join(indices))) else: return ('%s' % component.name) def equals(self, other): if other == 0: return self.coeff == 0 other = _sympify(other) if not isinstance(other, TensExpr): assert not self.components return S.One == other def _get_compar_comp(self): t = self.canon_bp() r = (t.coeff, tuple(t.components), \ tuple(sorted(t.free)), tuple(sorted(t.dum))) return r return _get_compar_comp(self) == _get_compar_comp(other) def contract_metric(self, g): # if metric is not the same, ignore this step: if self.component != g: return self # in case there are free components, do not perform anything: if len(self.free) != 0: return self #antisym = g.index_types[0].metric_antisym if g.symmetry == TensorSymmetry.fully_symmetric(-2): antisym = 1 elif g.symmetry == TensorSymmetry.fully_symmetric(2): antisym = 0 elif g.symmetry == TensorSymmetry.no_symmetry(2): antisym = None else: raise NotImplementedError sign = S.One typ = g.index_types[0] if not antisym: # g(i, -i) sign = sign*typ.dim else: # g(i, -i) sign = sign*typ.dim dp0, dp1 = self.dum[0] if dp0 < dp1: # g(i, -i) = -D with antisymmetric metric sign = -sign return sign def contract_delta(self, metric): return self.contract_metric(metric) def _eval_rewrite_as_Indexed(self, tens, indices): from sympy.tensor.indexed import Indexed # TODO: replace .args[0] with .name: index_symbols = [i.args[0] for i in self.get_indices()] expr = Indexed(tens.args[0], *index_symbols) return self._check_add_Sum(expr, index_symbols) def _eval_partial_derivative(self, s): # type: (Tensor) -> Expr if not isinstance(s, Tensor): return S.Zero else: # @a_i/@a_k = delta_i^k # @a_i/@a^k = g_ij delta^j_k # @a^i/@a^k = delta^i_k # @a^i/@a_k = g^ij delta_j^k # TODO: if there is no metric present, the derivative should be zero? if self.head != s.head: return S.Zero # if heads are the same, provide delta and/or metric products # for every free index pair in the appropriate tensor # assumed that the free indices are in proper order # A contravariante index in the derivative becomes covariant # after performing the derivative and vice versa kronecker_delta_list = [1] # not guarantee a correct index order for (count, (iself, iother)) in enumerate(zip(self.get_free_indices(), s.get_free_indices())): if iself.tensor_index_type != iother.tensor_index_type: raise ValueError("index types not compatible") else: tensor_index_type = iself.tensor_index_type tensor_metric = tensor_index_type.metric dummy = TensorIndex("d_" + str(count), tensor_index_type, is_up=iself.is_up) if iself.is_up == iother.is_up: kroneckerdelta = tensor_index_type.delta(iself, -iother) else: kroneckerdelta = ( TensMul(tensor_metric(iself, dummy), tensor_index_type.delta(-dummy, -iother)) ) kronecker_delta_list.append(kroneckerdelta) return TensMul.fromiter(kronecker_delta_list).doit() # doit necessary to rename dummy indices accordingly class TensMul(TensExpr, AssocOp): """ Product of tensors. Parameters ========== coeff : SymPy coefficient of the tensor args Attributes ========== ``components`` : list of ``TensorHead`` of the component tensors ``types`` : list of nonrepeated ``TensorIndexType`` ``free`` : list of ``(ind, ipos, icomp)``, see Notes ``dum`` : list of ``(ipos1, ipos2, icomp1, icomp2)``, see Notes ``ext_rank`` : rank of the tensor counting the dummy indices ``rank`` : rank of the tensor ``coeff`` : SymPy coefficient of the tensor ``free_args`` : list of the free indices in sorted order ``is_canon_bp`` : ``True`` if the tensor in in canonical form Notes ===== ``args[0]`` list of ``TensorHead`` of the component tensors. ``args[1]`` list of ``(ind, ipos, icomp)`` where ``ind`` is a free index, ``ipos`` is the slot position of ``ind`` in the ``icomp``-th component tensor. ``args[2]`` list of tuples representing dummy indices. ``(ipos1, ipos2, icomp1, icomp2)`` indicates that the contravariant dummy index is the ``ipos1``-th slot position in the ``icomp1``-th component tensor; the corresponding covariant index is in the ``ipos2`` slot position in the ``icomp2``-th component tensor. """ identity = S.One _index_structure = None # type: _IndexStructure def __new__(cls, *args, **kw_args): is_canon_bp = kw_args.get('is_canon_bp', False) args = list(map(_sympify, args)) """ If the internal dummy indices in one arg conflict with the free indices of the remaining args, we need to rename those internal dummy indices. """ free = [get_free_indices(arg) for arg in args] free = set(itertools.chain(*free)) #flatten free newargs = [] for arg in args: dum_this = set(get_dummy_indices(arg)) dum_other = [get_dummy_indices(a) for a in newargs] dum_other = set(itertools.chain(*dum_other)) #flatten dum_other free_this = set(get_free_indices(arg)) if len(dum_this.intersection(free)) > 0: exclude = free_this.union(free, dum_other) newarg = TensMul._dedupe_indices(arg, exclude) else: newarg = arg newargs.append(newarg) args = newargs # Flatten: args = [i for arg in args for i in (arg.args if isinstance(arg, (TensMul, Mul)) else [arg])] args, indices, free, dum = TensMul._tensMul_contract_indices(args, replace_indices=False) # Data for indices: index_types = [i.tensor_index_type for i in indices] index_structure = _IndexStructure(free, dum, index_types, indices, canon_bp=is_canon_bp) obj = TensExpr.__new__(cls, *args) obj._indices = indices obj._index_types = index_types[:] obj._index_structure = index_structure obj._free = index_structure.free[:] obj._dum = index_structure.dum[:] obj._free_indices = {x[0] for x in obj.free} obj._rank = len(obj.free) obj._ext_rank = len(obj._index_structure.free) + 2*len(obj._index_structure.dum) obj._coeff = S.One obj._is_canon_bp = is_canon_bp return obj index_types = property(lambda self: self._index_types) free = property(lambda self: self._free) dum = property(lambda self: self._dum) free_indices = property(lambda self: self._free_indices) rank = property(lambda self: self._rank) ext_rank = property(lambda self: self._ext_rank) @staticmethod def _indices_to_free_dum(args_indices): free2pos1 = {} free2pos2 = {} dummy_data = [] indices = [] # Notation for positions (to better understand the code): # `pos1`: position in the `args`. # `pos2`: position in the indices. # Example: # A(i, j)*B(k, m, n)*C(p) # `pos1` of `n` is 1 because it's in `B` (second `args` of TensMul). # `pos2` of `n` is 4 because it's the fifth overall index. # Counter for the index position wrt the whole expression: pos2 = 0 for pos1, arg_indices in enumerate(args_indices): for index_pos, index in enumerate(arg_indices): if not isinstance(index, TensorIndex): raise TypeError("expected TensorIndex") if -index in free2pos1: # Dummy index detected: other_pos1 = free2pos1.pop(-index) other_pos2 = free2pos2.pop(-index) if index.is_up: dummy_data.append((index, pos1, other_pos1, pos2, other_pos2)) else: dummy_data.append((-index, other_pos1, pos1, other_pos2, pos2)) indices.append(index) elif index in free2pos1: raise ValueError("Repeated index: %s" % index) else: free2pos1[index] = pos1 free2pos2[index] = pos2 indices.append(index) pos2 += 1 free = [(i, p) for (i, p) in free2pos2.items()] free_names = [i.name for i in free2pos2.keys()] dummy_data.sort(key=lambda x: x[3]) return indices, free, free_names, dummy_data @staticmethod def _dummy_data_to_dum(dummy_data): return [(p2a, p2b) for (i, p1a, p1b, p2a, p2b) in dummy_data] @staticmethod def _tensMul_contract_indices(args, replace_indices=True): replacements = [{} for _ in args] #_index_order = all(_has_index_order(arg) for arg in args) args_indices = [get_indices(arg) for arg in args] indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices) cdt = defaultdict(int) def dummy_name_gen(tensor_index_type): nd = str(cdt[tensor_index_type]) cdt[tensor_index_type] += 1 return tensor_index_type.dummy_name + '_' + nd if replace_indices: for old_index, pos1cov, pos1contra, pos2cov, pos2contra in dummy_data: index_type = old_index.tensor_index_type while True: dummy_name = dummy_name_gen(index_type) if dummy_name not in free_names: break dummy = TensorIndex(dummy_name, index_type, True) replacements[pos1cov][old_index] = dummy replacements[pos1contra][-old_index] = -dummy indices[pos2cov] = dummy indices[pos2contra] = -dummy args = [ arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg, repl in zip(args, replacements)] dum = TensMul._dummy_data_to_dum(dummy_data) return args, indices, free, dum @staticmethod def _get_components_from_args(args): """ Get a list of ``Tensor`` objects having the same ``TIDS`` if multiplied by one another. """ components = [] for arg in args: if not isinstance(arg, TensExpr): continue if isinstance(arg, TensAdd): continue components.extend(arg.components) return components @staticmethod def _rebuild_tensors_list(args, index_structure): indices = index_structure.get_indices() #tensors = [None for i in components] # pre-allocate list ind_pos = 0 for i, arg in enumerate(args): if not isinstance(arg, TensExpr): continue prev_pos = ind_pos ind_pos += arg.ext_rank args[i] = Tensor(arg.component, indices[prev_pos:ind_pos]) def doit(self, **hints): is_canon_bp = self._is_canon_bp deep = hints.get('deep', True) if deep: args = [arg.doit(**hints) for arg in self.args] """ There may now be conflicts between dummy indices of different args (each arg's doit method does not have any information about which dummy indices are already used in the other args), so we deduplicate them. """ rule = dict(zip(self.args, args)) rule = self._dedupe_indices_in_rule(rule) args = [rule[a] for a in self.args] else: args = self.args args = [arg for arg in args if arg != self.identity] # Extract non-tensor coefficients: coeff = reduce(lambda a, b: a*b, [arg for arg in args if not isinstance(arg, TensExpr)], S.One) args = [arg for arg in args if isinstance(arg, TensExpr)] if len(args) == 0: return coeff if coeff != self.identity: args = [coeff] + args if coeff == 0: return S.Zero if len(args) == 1: return args[0] args, indices, free, dum = TensMul._tensMul_contract_indices(args) # Data for indices: index_types = [i.tensor_index_type for i in indices] index_structure = _IndexStructure(free, dum, index_types, indices, canon_bp=is_canon_bp) obj = self.func(*args) obj._index_types = index_types obj._index_structure = index_structure obj._ext_rank = len(obj._index_structure.free) + 2*len(obj._index_structure.dum) obj._coeff = coeff obj._is_canon_bp = is_canon_bp return obj # TODO: this method should be private # TODO: should this method be renamed _from_components_free_dum ? @staticmethod def from_data(coeff, components, free, dum, **kw_args): return TensMul(coeff, *TensMul._get_tensors_from_components_free_dum(components, free, dum), **kw_args).doit() @staticmethod def _get_tensors_from_components_free_dum(components, free, dum): """ Get a list of ``Tensor`` objects by distributing ``free`` and ``dum`` indices on the ``components``. """ index_structure = _IndexStructure.from_components_free_dum(components, free, dum) indices = index_structure.get_indices() tensors = [None for i in components] # pre-allocate list # distribute indices on components to build a list of tensors: ind_pos = 0 for i, component in enumerate(components): prev_pos = ind_pos ind_pos += component.rank tensors[i] = Tensor(component, indices[prev_pos:ind_pos]) return tensors def _get_free_indices_set(self): return {i[0] for i in self.free} def _get_dummy_indices_set(self): dummy_pos = set(itertools.chain(*self.dum)) return {idx for i, idx in enumerate(self._index_structure.get_indices()) if i in dummy_pos} def _get_position_offset_for_indices(self): arg_offset = [None for i in range(self.ext_rank)] counter = 0 for i, arg in enumerate(self.args): if not isinstance(arg, TensExpr): continue for j in range(arg.ext_rank): arg_offset[j + counter] = counter counter += arg.ext_rank return arg_offset @property def free_args(self): return sorted([x[0] for x in self.free]) @property def components(self): return self._get_components_from_args(self.args) @property def free_in_args(self): arg_offset = self._get_position_offset_for_indices() argpos = self._get_indices_to_args_pos() return [(ind, pos-arg_offset[pos], argpos[pos]) for (ind, pos) in self.free] @property def coeff(self): # return Mul.fromiter([c for c in self.args if not isinstance(c, TensExpr)]) return self._coeff @property def nocoeff(self): return self.func(*[t for t in self.args if isinstance(t, TensExpr)]).doit() @property def dum_in_args(self): arg_offset = self._get_position_offset_for_indices() argpos = self._get_indices_to_args_pos() return [(p1-arg_offset[p1], p2-arg_offset[p2], argpos[p1], argpos[p2]) for p1, p2 in self.dum] def equals(self, other): if other == 0: return self.coeff == 0 other = _sympify(other) if not isinstance(other, TensExpr): assert not self.components return self.coeff == other return self.canon_bp() == other.canon_bp() def get_indices(self): """ Returns the list of indices of the tensor. Explanation =========== The indices are listed in the order in which they appear in the component tensors. The dummy indices are given a name which does not collide with the names of the free indices. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) >>> g = Lorentz.metric >>> p, q = tensor_heads('p,q', [Lorentz]) >>> t = p(m1)*g(m0,m2) >>> t.get_indices() [m1, m0, m2] >>> t2 = p(m1)*g(-m1, m2) >>> t2.get_indices() [L_0, -L_0, m2] """ return self._indices def get_free_indices(self) -> list[TensorIndex]: """ Returns the list of free indices of the tensor. Explanation =========== The indices are listed in the order in which they appear in the component tensors. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) >>> g = Lorentz.metric >>> p, q = tensor_heads('p,q', [Lorentz]) >>> t = p(m1)*g(m0,m2) >>> t.get_free_indices() [m1, m0, m2] >>> t2 = p(m1)*g(-m1, m2) >>> t2.get_free_indices() [m2] """ return self._index_structure.get_free_indices() def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr: return self.func(*[arg._replace_indices(repl) if isinstance(arg, TensExpr) else arg for arg in self.args]) def split(self): """ Returns a list of tensors, whose product is ``self``. Explanation =========== Dummy indices contracted among different tensor components become free indices with the same name as the one used to represent the dummy indices. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> a, b, c, d = tensor_indices('a,b,c,d', Lorentz) >>> A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2)) >>> t = A(a,b)*B(-b,c) >>> t A(a, L_0)*B(-L_0, c) >>> t.split() [A(a, L_0), B(-L_0, c)] """ if self.args == (): return [self] splitp = [] res = 1 for arg in self.args: if isinstance(arg, Tensor): splitp.append(res*arg) res = 1 else: res *= arg return splitp def _expand(self, **hints): # TODO: temporary solution, in the future this should be linked to # `Expr.expand`. args = [_expand(arg, **hints) for arg in self.args] args1 = [arg.args if isinstance(arg, (Add, TensAdd)) else (arg,) for arg in args] return TensAdd(*[ TensMul(*i) for i in itertools.product(*args1)] ) def __neg__(self): return TensMul(S.NegativeOne, self, is_canon_bp=self._is_canon_bp).doit() def __getitem__(self, item): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): return self.data[item] def _get_args_for_traditional_printer(self): args = list(self.args) if self.coeff.could_extract_minus_sign(): # expressions like "-A(a)" sign = "-" if args[0] == S.NegativeOne: args = args[1:] else: args[0] = -args[0] else: sign = "" return sign, args def _sort_args_for_sorted_components(self): """ Returns the ``args`` sorted according to the components commutation properties. Explanation =========== The sorting is done taking into account the commutation group of the component tensors. """ cv = [arg for arg in self.args if isinstance(arg, TensExpr)] sign = 1 n = len(cv) - 1 for i in range(n): for j in range(n, i, -1): c = cv[j-1].commutes_with(cv[j]) # if `c` is `None`, it does neither commute nor anticommute, skip: if c not in (0, 1): continue typ1 = sorted(set(cv[j-1].component.index_types), key=lambda x: x.name) typ2 = sorted(set(cv[j].component.index_types), key=lambda x: x.name) if (typ1, cv[j-1].component.name) > (typ2, cv[j].component.name): cv[j-1], cv[j] = cv[j], cv[j-1] # if `c` is 1, the anticommute, so change sign: if c: sign = -sign coeff = sign * self.coeff if coeff != 1: return [coeff] + cv return cv def sorted_components(self): """ Returns a tensor product with sorted components. """ return TensMul(*self._sort_args_for_sorted_components()).doit() def perm2tensor(self, g, is_canon_bp=False): """ Returns the tensor corresponding to the permutation ``g`` For further details, see the method in ``TIDS`` with the same name. """ return perm2tensor(self, g, is_canon_bp=is_canon_bp) def canon_bp(self): """ Canonicalize using the Butler-Portugal algorithm for canonicalization under monoterm symmetries. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) >>> A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2)) >>> t = A(m0,-m1)*A(m1,-m0) >>> t.canon_bp() -A(L_0, L_1)*A(-L_0, -L_1) >>> t = A(m0,-m1)*A(m1,-m2)*A(m2,-m0) >>> t.canon_bp() 0 """ if self._is_canon_bp: return self expr = self.expand() if isinstance(expr, TensAdd): return expr.canon_bp() if not expr.components: return expr t = expr.sorted_components() g, dummies, msym = t._index_structure.indices_canon_args() v = components_canon_args(t.components) can = canonicalize(g, dummies, msym, *v) if can == 0: return S.Zero tmul = t.perm2tensor(can, True) return tmul def contract_delta(self, delta): t = self.contract_metric(delta) return t def _get_indices_to_args_pos(self): """ Get a dict mapping the index position to TensMul's argument number. """ pos_map = {} pos_counter = 0 for arg_i, arg in enumerate(self.args): if not isinstance(arg, TensExpr): continue assert isinstance(arg, Tensor) for i in range(arg.ext_rank): pos_map[pos_counter] = arg_i pos_counter += 1 return pos_map def contract_metric(self, g): """ Raise or lower indices with the metric ``g``. Parameters ========== g : metric Notes ===== See the ``TensorIndexType`` docstring for the contraction conventions. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> m0, m1, m2 = tensor_indices('m0,m1,m2', Lorentz) >>> g = Lorentz.metric >>> p, q = tensor_heads('p,q', [Lorentz]) >>> t = p(m0)*q(m1)*g(-m0, -m1) >>> t.canon_bp() metric(L_0, L_1)*p(-L_0)*q(-L_1) >>> t.contract_metric(g).canon_bp() p(L_0)*q(-L_0) """ expr = self.expand() if self != expr: expr = canon_bp(expr) return contract_metric(expr, g) pos_map = self._get_indices_to_args_pos() args = list(self.args) #antisym = g.index_types[0].metric_antisym if g.symmetry == TensorSymmetry.fully_symmetric(-2): antisym = 1 elif g.symmetry == TensorSymmetry.fully_symmetric(2): antisym = 0 elif g.symmetry == TensorSymmetry.no_symmetry(2): antisym = None else: raise NotImplementedError # list of positions of the metric ``g`` inside ``args`` gpos = [i for i, x in enumerate(self.args) if isinstance(x, Tensor) and x.component == g] if not gpos: return self # Sign is either 1 or -1, to correct the sign after metric contraction # (for spinor indices). sign = 1 dum = self.dum[:] free = self.free[:] elim = set() for gposx in gpos: if gposx in elim: continue free1 = [x for x in free if pos_map[x[1]] == gposx] dum1 = [x for x in dum if pos_map[x[0]] == gposx or pos_map[x[1]] == gposx] if not dum1: continue elim.add(gposx) # subs with the multiplication neutral element, that is, remove it: args[gposx] = 1 if len(dum1) == 2: if not antisym: dum10, dum11 = dum1 if pos_map[dum10[1]] == gposx: # the index with pos p0 contravariant p0 = dum10[0] else: # the index with pos p0 is covariant p0 = dum10[1] if pos_map[dum11[1]] == gposx: # the index with pos p1 is contravariant p1 = dum11[0] else: # the index with pos p1 is covariant p1 = dum11[1] dum.append((p0, p1)) else: dum10, dum11 = dum1 # change the sign to bring the indices of the metric to contravariant # form; change the sign if dum10 has the metric index in position 0 if pos_map[dum10[1]] == gposx: # the index with pos p0 is contravariant p0 = dum10[0] if dum10[1] == 1: sign = -sign else: # the index with pos p0 is covariant p0 = dum10[1] if dum10[0] == 0: sign = -sign if pos_map[dum11[1]] == gposx: # the index with pos p1 is contravariant p1 = dum11[0] sign = -sign else: # the index with pos p1 is covariant p1 = dum11[1] dum.append((p0, p1)) elif len(dum1) == 1: if not antisym: dp0, dp1 = dum1[0] if pos_map[dp0] == pos_map[dp1]: # g(i, -i) typ = g.index_types[0] sign = sign*typ.dim else: # g(i0, i1)*p(-i1) if pos_map[dp0] == gposx: p1 = dp1 else: p1 = dp0 ind, p = free1[0] free.append((ind, p1)) else: dp0, dp1 = dum1[0] if pos_map[dp0] == pos_map[dp1]: # g(i, -i) typ = g.index_types[0] sign = sign*typ.dim if dp0 < dp1: # g(i, -i) = -D with antisymmetric metric sign = -sign else: # g(i0, i1)*p(-i1) if pos_map[dp0] == gposx: p1 = dp1 if dp0 == 0: sign = -sign else: p1 = dp0 ind, p = free1[0] free.append((ind, p1)) dum = [x for x in dum if x not in dum1] free = [x for x in free if x not in free1] # shift positions: shift = 0 shifts = [0]*len(args) for i in range(len(args)): if i in elim: shift += 2 continue shifts[i] = shift free = [(ind, p - shifts[pos_map[p]]) for (ind, p) in free if pos_map[p] not in elim] dum = [(p0 - shifts[pos_map[p0]], p1 - shifts[pos_map[p1]]) for i, (p0, p1) in enumerate(dum) if pos_map[p0] not in elim and pos_map[p1] not in elim] res = sign*TensMul(*args).doit() if not isinstance(res, TensExpr): return res im = _IndexStructure.from_components_free_dum(res.components, free, dum) return res._set_new_index_structure(im) def _set_new_index_structure(self, im, is_canon_bp=False): indices = im.get_indices() return self._set_indices(*indices, is_canon_bp=is_canon_bp) def _set_indices(self, *indices, is_canon_bp=False, **kw_args): if len(indices) != self.ext_rank: raise ValueError("indices length mismatch") args = list(self.args)[:] pos = 0 for i, arg in enumerate(args): if not isinstance(arg, TensExpr): continue assert isinstance(arg, Tensor) ext_rank = arg.ext_rank args[i] = arg._set_indices(*indices[pos:pos+ext_rank]) pos += ext_rank return TensMul(*args, is_canon_bp=is_canon_bp).doit() @staticmethod def _index_replacement_for_contract_metric(args, free, dum): for arg in args: if not isinstance(arg, TensExpr): continue assert isinstance(arg, Tensor) def substitute_indices(self, *index_tuples): new_args = [] for arg in self.args: if isinstance(arg, TensExpr): arg = arg.substitute_indices(*index_tuples) new_args.append(arg) return TensMul(*new_args).doit() def __call__(self, *indices): deprecate_call() free_args = self.free_args indices = list(indices) if [x.tensor_index_type for x in indices] != [x.tensor_index_type for x in free_args]: raise ValueError('incompatible types') if indices == free_args: return self t = self.substitute_indices(*list(zip(free_args, indices))) # object is rebuilt in order to make sure that all contracted indices # get recognized as dummies, but only if there are contracted indices. if len({i if i.is_up else -i for i in indices}) != len(indices): return t.func(*t.args) return t def _extract_data(self, replacement_dict): args_indices, arrays = zip(*[arg._extract_data(replacement_dict) for arg in self.args if isinstance(arg, TensExpr)]) coeff = reduce(operator.mul, [a for a in self.args if not isinstance(a, TensExpr)], S.One) indices, free, free_names, dummy_data = TensMul._indices_to_free_dum(args_indices) dum = TensMul._dummy_data_to_dum(dummy_data) ext_rank = self.ext_rank free.sort(key=lambda x: x[1]) free_indices = [i[0] for i in free] return free_indices, coeff*_TensorDataLazyEvaluator.data_contract_dum(arrays, dum, ext_rank) @property def data(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): dat = _tensor_data_substitution_dict[self.expand()] return dat @data.setter def data(self, data): deprecate_data() raise ValueError("Not possible to set component data to a tensor expression") @data.deleter def data(self): deprecate_data() raise ValueError("Not possible to delete component data to a tensor expression") def __iter__(self): deprecate_data() with ignore_warnings(SymPyDeprecationWarning): if self.data is None: raise ValueError("No iteration on abstract tensors") return self.data.__iter__() @staticmethod def _dedupe_indices(new, exclude): """ exclude: set new: TensExpr If ``new`` has any dummy indices that are in ``exclude``, return a version of new with those indices replaced. If no replacements are needed, return None """ exclude = set(exclude) dums_new = set(get_dummy_indices(new)) free_new = set(get_free_indices(new)) conflicts = dums_new.intersection(exclude) if len(conflicts) == 0: return None """ ``exclude_for_gen`` is to be passed to ``_IndexStructure._get_generator_for_dummy_indices()``. Since the latter does not use the index position for anything, we just set it as ``None`` here. """ exclude.update(dums_new) exclude.update(free_new) exclude_for_gen = [(i, None) for i in exclude] gen = _IndexStructure._get_generator_for_dummy_indices(exclude_for_gen) repl = {} for d in conflicts: if -d in repl.keys(): continue newname = gen(d.tensor_index_type) new_d = d.func(newname, *d.args[1:]) repl[d] = new_d repl[-d] = -new_d if len(repl) == 0: return None new_renamed = new._replace_indices(repl) return new_renamed def _dedupe_indices_in_rule(self, rule): """ rule: dict This applies TensMul._dedupe_indices on all values of rule. """ index_rules = {k:v for k,v in rule.items() if isinstance(k, TensorIndex)} other_rules = {k:v for k,v in rule.items() if k not in index_rules.keys()} exclude = set(self.get_indices()) newrule = {} newrule.update(index_rules) exclude.update(index_rules.keys()) exclude.update(index_rules.values()) for old, new in other_rules.items(): new_renamed = TensMul._dedupe_indices(new, exclude) if old == new or new_renamed is None: newrule[old] = new else: newrule[old] = new_renamed exclude.update(get_indices(new_renamed)) return newrule def _eval_rewrite_as_Indexed(self, *args): from sympy.concrete.summations import Sum index_symbols = [i.args[0] for i in self.get_indices()] args = [arg.args[0] if isinstance(arg, Sum) else arg for arg in args] expr = Mul.fromiter(args) return self._check_add_Sum(expr, index_symbols) def _eval_partial_derivative(self, s): # Evaluation like Mul terms = [] for i, arg in enumerate(self.args): # checking whether some tensor instance is differentiated # or some other thing is necessary, but ugly if isinstance(arg, TensExpr): d = arg._eval_partial_derivative(s) else: # do not call diff is s is no symbol if s._diff_wrt: d = arg._eval_derivative(s) else: d = S.Zero if d: terms.append(TensMul.fromiter(self.args[:i] + (d,) + self.args[i + 1:])) return TensAdd.fromiter(terms) class TensorElement(TensExpr): """ Tensor with evaluated components. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, TensorHead, TensorSymmetry >>> from sympy import symbols >>> L = TensorIndexType("L") >>> i, j, k = symbols("i j k") >>> A = TensorHead("A", [L, L], TensorSymmetry.fully_symmetric(2)) >>> A(i, j).get_free_indices() [i, j] If we want to set component ``i`` to a specific value, use the ``TensorElement`` class: >>> from sympy.tensor.tensor import TensorElement >>> te = TensorElement(A(i, j), {i: 2}) As index ``i`` has been accessed (``{i: 2}`` is the evaluation of its 3rd element), the free indices will only contain ``j``: >>> te.get_free_indices() [j] """ def __new__(cls, expr, index_map): if not isinstance(expr, Tensor): # remap if not isinstance(expr, TensExpr): raise TypeError("%s is not a tensor expression" % expr) return expr.func(*[TensorElement(arg, index_map) for arg in expr.args]) expr_free_indices = expr.get_free_indices() name_translation = {i.args[0]: i for i in expr_free_indices} index_map = {name_translation.get(index, index): value for index, value in index_map.items()} index_map = {index: value for index, value in index_map.items() if index in expr_free_indices} if len(index_map) == 0: return expr free_indices = [i for i in expr_free_indices if i not in index_map.keys()] index_map = Dict(index_map) obj = TensExpr.__new__(cls, expr, index_map) obj._free_indices = free_indices return obj @property def free(self): return [(index, i) for i, index in enumerate(self.get_free_indices())] @property def dum(self): # TODO: inherit dummies from expr return [] @property def expr(self): return self._args[0] @property def index_map(self): return self._args[1] @property def coeff(self): return S.One @property def nocoeff(self): return self def get_free_indices(self): return self._free_indices def _replace_indices(self, repl: dict[TensorIndex, TensorIndex]) -> TensExpr: # TODO: can be improved: return self.xreplace(repl) def get_indices(self): return self.get_free_indices() def _extract_data(self, replacement_dict): ret_indices, array = self.expr._extract_data(replacement_dict) index_map = self.index_map slice_tuple = tuple(index_map.get(i, slice(None)) for i in ret_indices) ret_indices = [i for i in ret_indices if i not in index_map] array = array.__getitem__(slice_tuple) return ret_indices, array class WildTensorHead(TensorHead): """ A wild object that is used to create ``WildTensor`` instances Explanation =========== Examples ======== >>> from sympy.tensor.tensor import TensorHead, TensorIndex, WildTensorHead, TensorIndexType >>> R3 = TensorIndexType('R3', dim=3) >>> p = TensorIndex('p', R3) >>> q = TensorIndex('q', R3) A WildTensorHead can be created without specifying a ``TensorIndexType`` >>> W = WildTensorHead("W") Calling it with a ``TensorIndex`` creates a ``WildTensor`` instance. >>> type(W(p)) <class 'sympy.tensor.tensor.WildTensor'> The ``TensorIndexType`` is automatically detected from the index that is passed >>> W(p).component W(R3) Calling it with no indices returns an object that can match tensors with any number of indices. >>> K = TensorHead('K', [R3]) >>> Q = TensorHead('Q', [R3, R3]) >>> W().matches(K(p)) {W: K(p)} >>> W().matches(Q(p,q)) {W: Q(p, q)} If you want to ignore the order of indices while matching, pass ``unordered_indices=True``. >>> U = WildTensorHead("U", unordered_indices=True) >>> W(p,q).matches(Q(q,p)) >>> U(p,q).matches(Q(q,p)) {U(R3,R3): _WildTensExpr(Q(q, p))} Parameters ========== name : name of the tensor unordered_indices : whether the order of the indices matters for matching (default: False) See also ======== ``WildTensor`` ``TensorHead`` """ def __new__(cls, name, index_types=None, symmetry=None, comm=0, unordered_indices=False): if isinstance(name, str): name_symbol = Symbol(name) elif isinstance(name, Symbol): name_symbol = name else: raise ValueError("invalid name") if index_types is None: index_types = [] if symmetry is None: symmetry = TensorSymmetry.no_symmetry(len(index_types)) else: assert symmetry.rank == len(index_types) if symmetry != TensorSymmetry.no_symmetry(len(index_types)): raise NotImplementedError("Wild matching based on symmetry is not implemented.") obj = Basic.__new__(cls, name_symbol, Tuple(*index_types), sympify(symmetry), sympify(comm), sympify(unordered_indices)) obj.comm = TensorManager.comm_symbols2i(comm) obj.unordered_indices = unordered_indices return obj def __call__(self, *indices, **kwargs): tensor = WildTensor(self, indices, **kwargs) return tensor.doit() class WildTensor(Tensor): """ A wild object which matches ``Tensor`` instances Explanation =========== This is instantiated by attaching indices to a ``WildTensorHead`` instance. Examples ======== >>> from sympy.tensor.tensor import TensorHead, TensorIndex, WildTensorHead, TensorIndexType >>> W = WildTensorHead("W") >>> R3 = TensorIndexType('R3', dim=3) >>> p = TensorIndex('p', R3) >>> q = TensorIndex('q', R3) >>> K = TensorHead('K', [R3]) >>> Q = TensorHead('Q', [R3, R3]) Matching also takes the indices into account >>> W(p).matches(K(p)) {W(R3): _WildTensExpr(K(p))} >>> W(p).matches(K(q)) >>> W(p).matches(K(-p)) If you want to match objects with any number of indices, just use a ``WildTensor`` with no indices. >>> W().matches(K(p)) {W: K(p)} >>> W().matches(Q(p,q)) {W: Q(p, q)} See Also ======== ``WildTensorHead`` ``Tensor`` """ def __new__(cls, tensor_head, indices, **kw_args): is_canon_bp = kw_args.pop("is_canon_bp", False) if tensor_head.func == TensorHead: """ If someone tried to call WildTensor by supplying a TensorHead (not a WildTensorHead), return a normal tensor instead. This is helpful when using subs on an expression to replace occurrences of a WildTensorHead with a TensorHead. """ return Tensor(tensor_head, indices, is_canon_bp=is_canon_bp, **kw_args) elif tensor_head.func == _WildTensExpr: return tensor_head(*indices) indices = cls._parse_indices(tensor_head, indices) index_types = [ind.tensor_index_type for ind in indices] tensor_head = tensor_head.func( tensor_head.name, index_types, symmetry=None, comm=tensor_head.comm, unordered_indices=tensor_head.unordered_indices, ) obj = Basic.__new__(cls, tensor_head, Tuple(*indices)) obj.name = tensor_head.name obj._index_structure = _IndexStructure.from_indices(*indices) obj._free = obj._index_structure.free[:] obj._dum = obj._index_structure.dum[:] obj._ext_rank = obj._index_structure._ext_rank obj._coeff = S.One obj._nocoeff = obj obj._component = tensor_head obj._components = [tensor_head] if tensor_head.rank != len(indices): raise ValueError("wrong number of indices") obj.is_canon_bp = is_canon_bp obj._index_map = obj._build_index_map(indices, obj._index_structure) return obj def matches(self, expr, repl_dict=None, old=False): if not isinstance(expr, TensExpr) and expr != S(1): return None if repl_dict is None: repl_dict = {} else: repl_dict = repl_dict.copy() if len(self.indices) > 0: if not hasattr(expr, "get_free_indices"): return None expr_indices = expr.get_free_indices() if len(expr_indices) != len(self.indices): return None if self._component.unordered_indices: m = self._match_indices_ignoring_order(expr) if m is None: return None else: repl_dict.update(m) else: for i in range(len(expr_indices)): m = self.indices[i].matches(expr_indices[i]) if m is None: return None else: repl_dict.update(m) repl_dict[self.component] = _WildTensExpr(expr) else: #If no indices were passed to the WildTensor, it may match tensors with any number of indices. repl_dict[self] = expr return repl_dict def _match_indices_ignoring_order(self, expr, repl_dict=None, old=False): """ Helper method for matches. Checks if the indices of self and expr match disregarding index ordering. """ if repl_dict is None: repl_dict = {} else: repl_dict = repl_dict.copy() def siftkey(ind): if isinstance(ind, WildTensorIndex): if ind.ignore_updown: return "wild, updown" else: return "wild" else: return "nonwild" indices_sifted = sift(self.indices, siftkey) matched_indices = [] expr_indices_remaining = expr.get_indices() for ind in indices_sifted["nonwild"]: matched_this_ind = False for e_ind in expr_indices_remaining: if e_ind in matched_indices: continue m = ind.matches(e_ind) if m is not None: matched_this_ind = True repl_dict.update(m) matched_indices.append(e_ind) break if not matched_this_ind: return None expr_indices_remaining = [i for i in expr_indices_remaining if i not in matched_indices] for ind in indices_sifted["wild"]: matched_this_ind = False for e_ind in expr_indices_remaining: m = ind.matches(e_ind) if m is not None: if -ind in repl_dict.keys() and -repl_dict[-ind] != m[ind]: return None matched_this_ind = True repl_dict.update(m) matched_indices.append(e_ind) break if not matched_this_ind: return None expr_indices_remaining = [i for i in expr_indices_remaining if i not in matched_indices] for ind in indices_sifted["wild, updown"]: matched_this_ind = False for e_ind in expr_indices_remaining: m = ind.matches(e_ind) if m is not None: if -ind in repl_dict.keys() and -repl_dict[-ind] != m[ind]: return None matched_this_ind = True repl_dict.update(m) matched_indices.append(e_ind) break if not matched_this_ind: return None if len(matched_indices) < len(self.indices): return None else: return repl_dict class WildTensorIndex(TensorIndex): """ A wild object that matches TensorIndex instances. Examples ======== >>> from sympy.tensor.tensor import TensorIndex, TensorIndexType, WildTensorIndex >>> R3 = TensorIndexType('R3', dim=3) >>> p = TensorIndex("p", R3) By default, covariant indices only match with covariant indices (and similarly for contravariant) >>> q = WildTensorIndex("q", R3) >>> (q).matches(p) {q: p} >>> (q).matches(-p) If you want matching to ignore whether the index is co/contra-variant, set ignore_updown=True >>> r = WildTensorIndex("r", R3, ignore_updown=True) >>> (r).matches(-p) {r: -p} >>> (r).matches(p) {r: p} Parameters ========== name : name of the index (string), or ``True`` if you want it to be automatically assigned tensor_index_type : ``TensorIndexType`` of the index is_up : flag for contravariant index (is_up=True by default) ignore_updown : bool, Whether this should match both co- and contra-variant indices (default:False) """ def __new__(cls, name, tensor_index_type, is_up=True, ignore_updown=False): if isinstance(name, str): name_symbol = Symbol(name) elif isinstance(name, Symbol): name_symbol = name elif name is True: name = "_i{}".format(len(tensor_index_type._autogenerated)) name_symbol = Symbol(name) tensor_index_type._autogenerated.append(name_symbol) else: raise ValueError("invalid name") is_up = sympify(is_up) ignore_updown = sympify(ignore_updown) return Basic.__new__(cls, name_symbol, tensor_index_type, is_up, ignore_updown) @property def ignore_updown(self): return self.args[3] def __neg__(self): t1 = WildTensorIndex(self.name, self.tensor_index_type, (not self.is_up), self.ignore_updown) return t1 def matches(self, expr, repl_dict=None, old=False): if not isinstance(expr, TensorIndex): return None if self.tensor_index_type != expr.tensor_index_type: return None if not self.ignore_updown: if self.is_up != expr.is_up: return None if repl_dict is None: repl_dict = {} else: repl_dict = repl_dict.copy() repl_dict[self] = expr return repl_dict class _WildTensExpr(Basic): """ INTERNAL USE ONLY This is an object that helps with replacement of WildTensors in expressions. When this object is set as the tensor_head of a WildTensor, it replaces the WildTensor by a TensExpr (passed when initializing this object). Examples ======== >>> from sympy.tensor.tensor import WildTensorHead, TensorIndex, TensorHead, TensorIndexType >>> W = WildTensorHead("W") >>> R3 = TensorIndexType('R3', dim=3) >>> p = TensorIndex('p', R3) >>> q = TensorIndex('q', R3) >>> K = TensorHead('K', [R3]) >>> print( ( K(p) ).replace( W(p), W(q)*W(-q)*W(p) ) ) K(R_0)*K(-R_0)*K(p) """ def __init__(self, expr): if not isinstance(expr, TensExpr): raise TypeError("_WildTensExpr expects a TensExpr as argument") self.expr = expr def __call__(self, *indices): return self.expr._replace_indices(dict(zip(self.expr.get_free_indices(), indices))) def __neg__(self): return self.func(self.expr*S.NegativeOne) def __abs__(self): raise NotImplementedError def __add__(self, other): if other.func != self.func: raise TypeError(f"Cannot add {self.func} to {other.func}") return self.func(self.expr+other.expr) def __radd__(self, other): if other.func != self.func: raise TypeError(f"Cannot add {self.func} to {other.func}") return self.func(other.expr+self.expr) def __sub__(self, other): return self + (-other) def __rsub__(self, other): return other + (-self) def __mul__(self, other): raise NotImplementedError def __rmul__(self, other): raise NotImplementedError def __truediv__(self, other): raise NotImplementedError def __rtruediv__(self, other): raise NotImplementedError def __pow__(self, other): raise NotImplementedError def __rpow__(self, other): raise NotImplementedError def canon_bp(p): """ Butler-Portugal canonicalization. See ``tensor_can.py`` from the combinatorics module for the details. """ if isinstance(p, TensExpr): return p.canon_bp() return p def tensor_mul(*a): """ product of tensors """ if not a: return TensMul.from_data(S.One, [], [], []) t = a[0] for tx in a[1:]: t = t*tx return t def riemann_cyclic_replace(t_r): """ replace Riemann tensor with an equivalent expression ``R(m,n,p,q) -> 2/3*R(m,n,p,q) - 1/3*R(m,q,n,p) + 1/3*R(m,p,n,q)`` """ free = sorted(t_r.free, key=lambda x: x[1]) m, n, p, q = [x[0] for x in free] t0 = t_r*Rational(2, 3) t1 = -t_r.substitute_indices((m,m),(n,q),(p,n),(q,p))*Rational(1, 3) t2 = t_r.substitute_indices((m,m),(n,p),(p,n),(q,q))*Rational(1, 3) t3 = t0 + t1 + t2 return t3 def riemann_cyclic(t2): """ Replace each Riemann tensor with an equivalent expression satisfying the cyclic identity. This trick is discussed in the reference guide to Cadabra. Examples ======== >>> from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorHead, riemann_cyclic, TensorSymmetry >>> Lorentz = TensorIndexType('Lorentz', dummy_name='L') >>> i, j, k, l = tensor_indices('i,j,k,l', Lorentz) >>> R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann()) >>> t = R(i,j,k,l)*(R(-i,-j,-k,-l) - 2*R(-i,-k,-j,-l)) >>> riemann_cyclic(t) 0 """ t2 = t2.expand() if isinstance(t2, (TensMul, Tensor)): args = [t2] else: args = t2.args a1 = [x.split() for x in args] a2 = [[riemann_cyclic_replace(tx) for tx in y] for y in a1] a3 = [tensor_mul(*v) for v in a2] t3 = TensAdd(*a3).doit() if not t3: return t3 else: return canon_bp(t3) def get_lines(ex, index_type): """ Returns ``(lines, traces, rest)`` for an index type, where ``lines`` is the list of list of positions of a matrix line, ``traces`` is the list of list of traced matrix lines, ``rest`` is the rest of the elements of the tensor. """ def _join_lines(a): i = 0 while i < len(a): x = a[i] xend = x[-1] xstart = x[0] hit = True while hit: hit = False for j in range(i + 1, len(a)): if j >= len(a): break if a[j][0] == xend: hit = True x.extend(a[j][1:]) xend = x[-1] a.pop(j) continue if a[j][0] == xstart: hit = True a[i] = reversed(a[j][1:]) + x x = a[i] xstart = a[i][0] a.pop(j) continue if a[j][-1] == xend: hit = True x.extend(reversed(a[j][:-1])) xend = x[-1] a.pop(j) continue if a[j][-1] == xstart: hit = True a[i] = a[j][:-1] + x x = a[i] xstart = x[0] a.pop(j) continue i += 1 return a arguments = ex.args dt = {} for c in ex.args: if not isinstance(c, TensExpr): continue if c in dt: continue index_types = c.index_types a = [] for i in range(len(index_types)): if index_types[i] is index_type: a.append(i) if len(a) > 2: raise ValueError('at most two indices of type %s allowed' % index_type) if len(a) == 2: dt[c] = a #dum = ex.dum lines = [] traces = [] traces1 = [] #indices_to_args_pos = ex._get_indices_to_args_pos() # TODO: add a dum_to_components_map ? for p0, p1, c0, c1 in ex.dum_in_args: if arguments[c0] not in dt: continue if c0 == c1: traces.append([c0]) continue ta0 = dt[arguments[c0]] ta1 = dt[arguments[c1]] if p0 not in ta0: continue if ta0.index(p0) == ta1.index(p1): # case gamma(i,s0,-s1) in c0, gamma(j,-s0,s2) in c1; # to deal with this case one could add to the position # a flag for transposition; # one could write [(c0, False), (c1, True)] raise NotImplementedError # if p0 == ta0[1] then G in pos c0 is mult on the right by G in c1 # if p0 == ta0[0] then G in pos c1 is mult on the right by G in c0 ta0 = dt[arguments[c0]] b0, b1 = (c0, c1) if p0 == ta0[1] else (c1, c0) lines1 = lines[:] for line in lines: if line[-1] == b0: if line[0] == b1: n = line.index(min(line)) traces1.append(line) traces.append(line[n:] + line[:n]) else: line.append(b1) break elif line[0] == b1: line.insert(0, b0) break else: lines1.append([b0, b1]) lines = [x for x in lines1 if x not in traces1] lines = _join_lines(lines) rest = [] for line in lines: for y in line: rest.append(y) for line in traces: for y in line: rest.append(y) rest = [x for x in range(len(arguments)) if x not in rest] return lines, traces, rest def get_free_indices(t): if not isinstance(t, TensExpr): return () return t.get_free_indices() def get_indices(t): if not isinstance(t, TensExpr): return () return t.get_indices() def get_dummy_indices(t): if not isinstance(t, TensExpr): return () inds = t.get_indices() free = t.get_free_indices() return [i for i in inds if i not in free] def get_index_structure(t): if isinstance(t, TensExpr): return t._index_structure return _IndexStructure([], [], [], []) def get_coeff(t): if isinstance(t, Tensor): return S.One if isinstance(t, TensMul): return t.coeff if isinstance(t, TensExpr): raise ValueError("no coefficient associated to this tensor expression") return t def contract_metric(t, g): if isinstance(t, TensExpr): return t.contract_metric(g) return t def perm2tensor(t, g, is_canon_bp=False): """ Returns the tensor corresponding to the permutation ``g`` For further details, see the method in ``TIDS`` with the same name. """ if not isinstance(t, TensExpr): return t elif isinstance(t, (Tensor, TensMul)): nim = get_index_structure(t).perm2tensor(g, is_canon_bp=is_canon_bp) res = t._set_new_index_structure(nim, is_canon_bp=is_canon_bp) if g[-1] != len(g) - 1: return -res return res raise NotImplementedError() def substitute_indices(t, *index_tuples): if not isinstance(t, TensExpr): return t return t.substitute_indices(*index_tuples) def _expand(expr, **kwargs): if isinstance(expr, TensExpr): return expr._expand(**kwargs) else: return expr.expand(**kwargs)
8c9dcb2d928149e52076d5bc62fe1b8bf95968d810c83c8ec52b9b88f356bf43
""" Boolean algebra module for SymPy """ from collections import defaultdict from itertools import chain, combinations, product, permutations from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.cache import cacheit from sympy.core.containers import Tuple from sympy.core.decorators import sympify_method_args, sympify_return from sympy.core.function import Application, Derivative from sympy.core.kind import BooleanKind, NumberKind from sympy.core.numbers import Number from sympy.core.operations import LatticeOp from sympy.core.singleton import Singleton, S from sympy.core.sorting import ordered from sympy.core.sympify import _sympy_converter, _sympify, sympify from sympy.utilities.iterables import sift, ibin from sympy.utilities.misc import filldedent def as_Boolean(e): """Like ``bool``, return the Boolean value of an expression, e, which can be any instance of :py:class:`~.Boolean` or ``bool``. Examples ======== >>> from sympy import true, false, nan >>> from sympy.logic.boolalg import as_Boolean >>> from sympy.abc import x >>> as_Boolean(0) is false True >>> as_Boolean(1) is true True >>> as_Boolean(x) x >>> as_Boolean(2) Traceback (most recent call last): ... TypeError: expecting bool or Boolean, not `2`. >>> as_Boolean(nan) Traceback (most recent call last): ... TypeError: expecting bool or Boolean, not `nan`. """ from sympy.core.symbol import Symbol if e == True: return true if e == False: return false if isinstance(e, Symbol): z = e.is_zero if z is None: return e return false if z else true if isinstance(e, Boolean): return e raise TypeError('expecting bool or Boolean, not `%s`.' % e) @sympify_method_args class Boolean(Basic): """A Boolean object is an object for which logic operations make sense.""" __slots__ = () kind = BooleanKind @sympify_return([('other', 'Boolean')], NotImplemented) def __and__(self, other): return And(self, other) __rand__ = __and__ @sympify_return([('other', 'Boolean')], NotImplemented) def __or__(self, other): return Or(self, other) __ror__ = __or__ def __invert__(self): """Overloading for ~""" return Not(self) @sympify_return([('other', 'Boolean')], NotImplemented) def __rshift__(self, other): return Implies(self, other) @sympify_return([('other', 'Boolean')], NotImplemented) def __lshift__(self, other): return Implies(other, self) __rrshift__ = __lshift__ __rlshift__ = __rshift__ @sympify_return([('other', 'Boolean')], NotImplemented) def __xor__(self, other): return Xor(self, other) __rxor__ = __xor__ def equals(self, other): """ Returns ``True`` if the given formulas have the same truth table. For two formulas to be equal they must have the same literals. Examples ======== >>> from sympy.abc import A, B, C >>> from sympy import And, Or, Not >>> (A >> B).equals(~B >> ~A) True >>> Not(And(A, B, C)).equals(And(Not(A), Not(B), Not(C))) False >>> Not(And(A, Not(A))).equals(Or(B, Not(B))) False """ from sympy.logic.inference import satisfiable from sympy.core.relational import Relational if self.has(Relational) or other.has(Relational): raise NotImplementedError('handling of relationals') return self.atoms() == other.atoms() and \ not satisfiable(Not(Equivalent(self, other))) def to_nnf(self, simplify=True): # override where necessary return self def as_set(self): """ Rewrites Boolean expression in terms of real sets. Examples ======== >>> from sympy import Symbol, Eq, Or, And >>> x = Symbol('x', real=True) >>> Eq(x, 0).as_set() {0} >>> (x > 0).as_set() Interval.open(0, oo) >>> And(-2 < x, x < 2).as_set() Interval.open(-2, 2) >>> Or(x < -2, 2 < x).as_set() Union(Interval.open(-oo, -2), Interval.open(2, oo)) """ from sympy.calculus.util import periodicity from sympy.core.relational import Relational free = self.free_symbols if len(free) == 1: x = free.pop() if x.kind is NumberKind: reps = {} for r in self.atoms(Relational): if periodicity(r, x) not in (0, None): s = r._eval_as_set() if s in (S.EmptySet, S.UniversalSet, S.Reals): reps[r] = s.as_relational(x) continue raise NotImplementedError(filldedent(''' as_set is not implemented for relationals with periodic solutions ''')) new = self.subs(reps) if new.func != self.func: return new.as_set() # restart with new obj else: return new._eval_as_set() return self._eval_as_set() else: raise NotImplementedError("Sorry, as_set has not yet been" " implemented for multivariate" " expressions") @property def binary_symbols(self): from sympy.core.relational import Eq, Ne return set().union(*[i.binary_symbols for i in self.args if i.is_Boolean or i.is_Symbol or isinstance(i, (Eq, Ne))]) def _eval_refine(self, assumptions): from sympy.assumptions import ask ret = ask(self, assumptions) if ret is True: return true elif ret is False: return false return None class BooleanAtom(Boolean): """ Base class of :py:class:`~.BooleanTrue` and :py:class:`~.BooleanFalse`. """ is_Boolean = True is_Atom = True _op_priority = 11 # higher than Expr def simplify(self, *a, **kw): return self def expand(self, *a, **kw): return self @property def canonical(self): return self def _noop(self, other=None): raise TypeError('BooleanAtom not allowed in this context.') __add__ = _noop __radd__ = _noop __sub__ = _noop __rsub__ = _noop __mul__ = _noop __rmul__ = _noop __pow__ = _noop __rpow__ = _noop __truediv__ = _noop __rtruediv__ = _noop __mod__ = _noop __rmod__ = _noop _eval_power = _noop # /// drop when Py2 is no longer supported def __lt__(self, other): raise TypeError(filldedent(''' A Boolean argument can only be used in Eq and Ne; all other relationals expect real expressions. ''')) __le__ = __lt__ __gt__ = __lt__ __ge__ = __lt__ # \\\ def _eval_simplify(self, **kwargs): return self class BooleanTrue(BooleanAtom, metaclass=Singleton): """ SymPy version of ``True``, a singleton that can be accessed via ``S.true``. This is the SymPy version of ``True``, for use in the logic module. The primary advantage of using ``true`` instead of ``True`` is that shorthand Boolean operations like ``~`` and ``>>`` will work as expected on this class, whereas with True they act bitwise on 1. Functions in the logic module will return this class when they evaluate to true. Notes ===== There is liable to be some confusion as to when ``True`` should be used and when ``S.true`` should be used in various contexts throughout SymPy. An important thing to remember is that ``sympify(True)`` returns ``S.true``. This means that for the most part, you can just use ``True`` and it will automatically be converted to ``S.true`` when necessary, similar to how you can generally use 1 instead of ``S.One``. The rule of thumb is: "If the boolean in question can be replaced by an arbitrary symbolic ``Boolean``, like ``Or(x, y)`` or ``x > 1``, use ``S.true``. Otherwise, use ``True``" In other words, use ``S.true`` only on those contexts where the boolean is being used as a symbolic representation of truth. For example, if the object ends up in the ``.args`` of any expression, then it must necessarily be ``S.true`` instead of ``True``, as elements of ``.args`` must be ``Basic``. On the other hand, ``==`` is not a symbolic operation in SymPy, since it always returns ``True`` or ``False``, and does so in terms of structural equality rather than mathematical, so it should return ``True``. The assumptions system should use ``True`` and ``False``. Aside from not satisfying the above rule of thumb, the assumptions system uses a three-valued logic (``True``, ``False``, ``None``), whereas ``S.true`` and ``S.false`` represent a two-valued logic. When in doubt, use ``True``. "``S.true == True is True``." While "``S.true is True``" is ``False``, "``S.true == True``" is ``True``, so if there is any doubt over whether a function or expression will return ``S.true`` or ``True``, just use ``==`` instead of ``is`` to do the comparison, and it will work in either case. Finally, for boolean flags, it's better to just use ``if x`` instead of ``if x is True``. To quote PEP 8: Do not compare boolean values to ``True`` or ``False`` using ``==``. * Yes: ``if greeting:`` * No: ``if greeting == True:`` * Worse: ``if greeting is True:`` Examples ======== >>> from sympy import sympify, true, false, Or >>> sympify(True) True >>> _ is True, _ is true (False, True) >>> Or(true, false) True >>> _ is true True Python operators give a boolean result for true but a bitwise result for True >>> ~true, ~True (False, -2) >>> true >> true, True >> True (True, 0) Python operators give a boolean result for true but a bitwise result for True >>> ~true, ~True (False, -2) >>> true >> true, True >> True (True, 0) See Also ======== sympy.logic.boolalg.BooleanFalse """ def __bool__(self): return True def __hash__(self): return hash(True) def __eq__(self, other): if other is True: return True if other is False: return False return super().__eq__(other) @property def negated(self): return false def as_set(self): """ Rewrite logic operators and relationals in terms of real sets. Examples ======== >>> from sympy import true >>> true.as_set() UniversalSet """ return S.UniversalSet class BooleanFalse(BooleanAtom, metaclass=Singleton): """ SymPy version of ``False``, a singleton that can be accessed via ``S.false``. This is the SymPy version of ``False``, for use in the logic module. The primary advantage of using ``false`` instead of ``False`` is that shorthand Boolean operations like ``~`` and ``>>`` will work as expected on this class, whereas with ``False`` they act bitwise on 0. Functions in the logic module will return this class when they evaluate to false. Notes ====== See the notes section in :py:class:`sympy.logic.boolalg.BooleanTrue` Examples ======== >>> from sympy import sympify, true, false, Or >>> sympify(False) False >>> _ is False, _ is false (False, True) >>> Or(true, false) True >>> _ is true True Python operators give a boolean result for false but a bitwise result for False >>> ~false, ~False (True, -1) >>> false >> false, False >> False (True, 0) See Also ======== sympy.logic.boolalg.BooleanTrue """ def __bool__(self): return False def __hash__(self): return hash(False) def __eq__(self, other): if other is True: return False if other is False: return True return super().__eq__(other) @property def negated(self): return true def as_set(self): """ Rewrite logic operators and relationals in terms of real sets. Examples ======== >>> from sympy import false >>> false.as_set() EmptySet """ return S.EmptySet true = BooleanTrue() false = BooleanFalse() # We want S.true and S.false to work, rather than S.BooleanTrue and # S.BooleanFalse, but making the class and instance names the same causes some # major issues (like the inability to import the class directly from this # file). S.true = true S.false = false _sympy_converter[bool] = lambda x: true if x else false class BooleanFunction(Application, Boolean): """Boolean function is a function that lives in a boolean space It is used as base class for :py:class:`~.And`, :py:class:`~.Or`, :py:class:`~.Not`, etc. """ is_Boolean = True def _eval_simplify(self, **kwargs): rv = simplify_univariate(self) if not isinstance(rv, BooleanFunction): return rv.simplify(**kwargs) rv = rv.func(*[a.simplify(**kwargs) for a in rv.args]) return simplify_logic(rv) def simplify(self, **kwargs): from sympy.simplify.simplify import simplify return simplify(self, **kwargs) def __lt__(self, other): raise TypeError(filldedent(''' A Boolean argument can only be used in Eq and Ne; all other relationals expect real expressions. ''')) __le__ = __lt__ __ge__ = __lt__ __gt__ = __lt__ @classmethod def binary_check_and_simplify(self, *args): from sympy.core.relational import Relational, Eq, Ne args = [as_Boolean(i) for i in args] bin_syms = set().union(*[i.binary_symbols for i in args]) rel = set().union(*[i.atoms(Relational) for i in args]) reps = {} for x in bin_syms: for r in rel: if x in bin_syms and x in r.free_symbols: if isinstance(r, (Eq, Ne)): if not ( true in r.args or false in r.args): reps[r] = false else: raise TypeError(filldedent(''' Incompatible use of binary symbol `%s` as a real variable in `%s` ''' % (x, r))) return [i.subs(reps) for i in args] def to_nnf(self, simplify=True): return self._to_nnf(*self.args, simplify=simplify) def to_anf(self, deep=True): return self._to_anf(*self.args, deep=deep) @classmethod def _to_nnf(cls, *args, **kwargs): simplify = kwargs.get('simplify', True) argset = set() for arg in args: if not is_literal(arg): arg = arg.to_nnf(simplify) if simplify: if isinstance(arg, cls): arg = arg.args else: arg = (arg,) for a in arg: if Not(a) in argset: return cls.zero argset.add(a) else: argset.add(arg) return cls(*argset) @classmethod def _to_anf(cls, *args, **kwargs): deep = kwargs.get('deep', True) argset = set() for arg in args: if deep: if not is_literal(arg) or isinstance(arg, Not): arg = arg.to_anf(deep=deep) argset.add(arg) else: argset.add(arg) return cls(*argset, remove_true=False) # the diff method below is copied from Expr class def diff(self, *symbols, **assumptions): assumptions.setdefault("evaluate", True) return Derivative(self, *symbols, **assumptions) def _eval_derivative(self, x): if x in self.binary_symbols: from sympy.core.relational import Eq from sympy.functions.elementary.piecewise import Piecewise return Piecewise( (0, Eq(self.subs(x, 0), self.subs(x, 1))), (1, True)) elif x in self.free_symbols: # not implemented, see https://www.encyclopediaofmath.org/ # index.php/Boolean_differential_calculus pass else: return S.Zero class And(LatticeOp, BooleanFunction): """ Logical AND function. It evaluates its arguments in order, returning false immediately when an argument is false and true if they are all true. Examples ======== >>> from sympy.abc import x, y >>> from sympy import And >>> x & y x & y Notes ===== The ``&`` operator is provided as a convenience, but note that its use here is different from its normal use in Python, which is bitwise and. Hence, ``And(a, b)`` and ``a & b`` will produce different results if ``a`` and ``b`` are integers. >>> And(x, y).subs(x, 1) y """ zero = false identity = true nargs = None @classmethod def _new_args_filter(cls, args): args = BooleanFunction.binary_check_and_simplify(*args) args = LatticeOp._new_args_filter(args, And) newargs = [] rel = set() for x in ordered(args): if x.is_Relational: c = x.canonical if c in rel: continue elif c.negated.canonical in rel: return [false] else: rel.add(c) newargs.append(x) return newargs def _eval_subs(self, old, new): args = [] bad = None for i in self.args: try: i = i.subs(old, new) except TypeError: # store TypeError if bad is None: bad = i continue if i == False: return false elif i != True: args.append(i) if bad is not None: # let it raise bad.subs(old, new) # If old is And, replace the parts of the arguments with new if all # are there if isinstance(old, And): old_set = set(old.args) if old_set.issubset(args): args = set(args) - old_set args.add(new) return self.func(*args) def _eval_simplify(self, **kwargs): from sympy.core.relational import Equality, Relational from sympy.solvers.solveset import linear_coeffs # standard simplify rv = super()._eval_simplify(**kwargs) if not isinstance(rv, And): return rv # simplify args that are equalities involving # symbols so x == 0 & x == y -> x==0 & y == 0 Rel, nonRel = sift(rv.args, lambda i: isinstance(i, Relational), binary=True) if not Rel: return rv eqs, other = sift(Rel, lambda i: isinstance(i, Equality), binary=True) measure = kwargs['measure'] if eqs: ratio = kwargs['ratio'] reps = {} sifted = {} # group by length of free symbols sifted = sift(ordered([ (i.free_symbols, i) for i in eqs]), lambda x: len(x[0])) eqs = [] nonlineqs = [] while 1 in sifted: for free, e in sifted.pop(1): x = free.pop() if (e.lhs != x or x in e.rhs.free_symbols) and x not in reps: try: m, b = linear_coeffs( e.rewrite(Add, evaluate=False), x) enew = e.func(x, -b/m) if measure(enew) <= ratio*measure(e): e = enew else: eqs.append(e) continue except ValueError: pass if x in reps: eqs.append(e.subs(x, reps[x])) elif e.lhs == x and x not in e.rhs.free_symbols: reps[x] = e.rhs eqs.append(e) else: # x is not yet identified, but may be later nonlineqs.append(e) resifted = defaultdict(list) for k in sifted: for f, e in sifted[k]: e = e.xreplace(reps) f = e.free_symbols resifted[len(f)].append((f, e)) sifted = resifted for k in sifted: eqs.extend([e for f, e in sifted[k]]) nonlineqs = [ei.subs(reps) for ei in nonlineqs] other = [ei.subs(reps) for ei in other] rv = rv.func(*([i.canonical for i in (eqs + nonlineqs + other)] + nonRel)) patterns = _simplify_patterns_and() threeterm_patterns = _simplify_patterns_and3() return _apply_patternbased_simplification(rv, patterns, measure, false, threeterm_patterns=threeterm_patterns) def _eval_as_set(self): from sympy.sets.sets import Intersection return Intersection(*[arg.as_set() for arg in self.args]) def _eval_rewrite_as_Nor(self, *args, **kwargs): return Nor(*[Not(arg) for arg in self.args]) def to_anf(self, deep=True): if deep: result = And._to_anf(*self.args, deep=deep) return distribute_xor_over_and(result) return self class Or(LatticeOp, BooleanFunction): """ Logical OR function It evaluates its arguments in order, returning true immediately when an argument is true, and false if they are all false. Examples ======== >>> from sympy.abc import x, y >>> from sympy import Or >>> x | y x | y Notes ===== The ``|`` operator is provided as a convenience, but note that its use here is different from its normal use in Python, which is bitwise or. Hence, ``Or(a, b)`` and ``a | b`` will return different things if ``a`` and ``b`` are integers. >>> Or(x, y).subs(x, 0) y """ zero = true identity = false @classmethod def _new_args_filter(cls, args): newargs = [] rel = [] args = BooleanFunction.binary_check_and_simplify(*args) for x in args: if x.is_Relational: c = x.canonical if c in rel: continue nc = c.negated.canonical if any(r == nc for r in rel): return [true] rel.append(c) newargs.append(x) return LatticeOp._new_args_filter(newargs, Or) def _eval_subs(self, old, new): args = [] bad = None for i in self.args: try: i = i.subs(old, new) except TypeError: # store TypeError if bad is None: bad = i continue if i == True: return true elif i != False: args.append(i) if bad is not None: # let it raise bad.subs(old, new) # If old is Or, replace the parts of the arguments with new if all # are there if isinstance(old, Or): old_set = set(old.args) if old_set.issubset(args): args = set(args) - old_set args.add(new) return self.func(*args) def _eval_as_set(self): from sympy.sets.sets import Union return Union(*[arg.as_set() for arg in self.args]) def _eval_rewrite_as_Nand(self, *args, **kwargs): return Nand(*[Not(arg) for arg in self.args]) def _eval_simplify(self, **kwargs): from sympy.core.relational import Le, Ge, Eq lege = self.atoms(Le, Ge) if lege: reps = {i: self.func( Eq(i.lhs, i.rhs), i.strict) for i in lege} return self.xreplace(reps)._eval_simplify(**kwargs) # standard simplify rv = super()._eval_simplify(**kwargs) if not isinstance(rv, Or): return rv patterns = _simplify_patterns_or() return _apply_patternbased_simplification(rv, patterns, kwargs['measure'], true) def to_anf(self, deep=True): args = range(1, len(self.args) + 1) args = (combinations(self.args, j) for j in args) args = chain.from_iterable(args) # powerset args = (And(*arg) for arg in args) args = map(lambda x: to_anf(x, deep=deep) if deep else x, args) return Xor(*list(args), remove_true=False) class Not(BooleanFunction): """ Logical Not function (negation) Returns ``true`` if the statement is ``false`` or ``False``. Returns ``false`` if the statement is ``true`` or ``True``. Examples ======== >>> from sympy import Not, And, Or >>> from sympy.abc import x, A, B >>> Not(True) False >>> Not(False) True >>> Not(And(True, False)) True >>> Not(Or(True, False)) False >>> Not(And(And(True, x), Or(x, False))) ~x >>> ~x ~x >>> Not(And(Or(A, B), Or(~A, ~B))) ~((A | B) & (~A | ~B)) Notes ===== - The ``~`` operator is provided as a convenience, but note that its use here is different from its normal use in Python, which is bitwise not. In particular, ``~a`` and ``Not(a)`` will be different if ``a`` is an integer. Furthermore, since bools in Python subclass from ``int``, ``~True`` is the same as ``~1`` which is ``-2``, which has a boolean value of True. To avoid this issue, use the SymPy boolean types ``true`` and ``false``. >>> from sympy import true >>> ~True -2 >>> ~true False """ is_Not = True @classmethod def eval(cls, arg): if isinstance(arg, Number) or arg in (True, False): return false if arg else true if arg.is_Not: return arg.args[0] # Simplify Relational objects. if arg.is_Relational: return arg.negated def _eval_as_set(self): """ Rewrite logic operators and relationals in terms of real sets. Examples ======== >>> from sympy import Not, Symbol >>> x = Symbol('x') >>> Not(x > 0).as_set() Interval(-oo, 0) """ return self.args[0].as_set().complement(S.Reals) def to_nnf(self, simplify=True): if is_literal(self): return self expr = self.args[0] func, args = expr.func, expr.args if func == And: return Or._to_nnf(*[Not(arg) for arg in args], simplify=simplify) if func == Or: return And._to_nnf(*[Not(arg) for arg in args], simplify=simplify) if func == Implies: a, b = args return And._to_nnf(a, Not(b), simplify=simplify) if func == Equivalent: return And._to_nnf(Or(*args), Or(*[Not(arg) for arg in args]), simplify=simplify) if func == Xor: result = [] for i in range(1, len(args)+1, 2): for neg in combinations(args, i): clause = [Not(s) if s in neg else s for s in args] result.append(Or(*clause)) return And._to_nnf(*result, simplify=simplify) if func == ITE: a, b, c = args return And._to_nnf(Or(a, Not(c)), Or(Not(a), Not(b)), simplify=simplify) raise ValueError("Illegal operator %s in expression" % func) def to_anf(self, deep=True): return Xor._to_anf(true, self.args[0], deep=deep) class Xor(BooleanFunction): """ Logical XOR (exclusive OR) function. Returns True if an odd number of the arguments are True and the rest are False. Returns False if an even number of the arguments are True and the rest are False. Examples ======== >>> from sympy.logic.boolalg import Xor >>> from sympy import symbols >>> x, y = symbols('x y') >>> Xor(True, False) True >>> Xor(True, True) False >>> Xor(True, False, True, True, False) True >>> Xor(True, False, True, False) False >>> x ^ y x ^ y Notes ===== The ``^`` operator is provided as a convenience, but note that its use here is different from its normal use in Python, which is bitwise xor. In particular, ``a ^ b`` and ``Xor(a, b)`` will be different if ``a`` and ``b`` are integers. >>> Xor(x, y).subs(y, 0) x """ def __new__(cls, *args, remove_true=True, **kwargs): argset = set() obj = super().__new__(cls, *args, **kwargs) for arg in obj._args: if isinstance(arg, Number) or arg in (True, False): if arg: arg = true else: continue if isinstance(arg, Xor): for a in arg.args: argset.remove(a) if a in argset else argset.add(a) elif arg in argset: argset.remove(arg) else: argset.add(arg) rel = [(r, r.canonical, r.negated.canonical) for r in argset if r.is_Relational] odd = False # is number of complimentary pairs odd? start 0 -> False remove = [] for i, (r, c, nc) in enumerate(rel): for j in range(i + 1, len(rel)): rj, cj = rel[j][:2] if cj == nc: odd = ~odd break elif cj == c: break else: continue remove.append((r, rj)) if odd: argset.remove(true) if true in argset else argset.add(true) for a, b in remove: argset.remove(a) argset.remove(b) if len(argset) == 0: return false elif len(argset) == 1: return argset.pop() elif True in argset and remove_true: argset.remove(True) return Not(Xor(*argset)) else: obj._args = tuple(ordered(argset)) obj._argset = frozenset(argset) return obj # XXX: This should be cached on the object rather than using cacheit # Maybe it can be computed in __new__? @property # type: ignore @cacheit def args(self): return tuple(ordered(self._argset)) def to_nnf(self, simplify=True): args = [] for i in range(0, len(self.args)+1, 2): for neg in combinations(self.args, i): clause = [Not(s) if s in neg else s for s in self.args] args.append(Or(*clause)) return And._to_nnf(*args, simplify=simplify) def _eval_rewrite_as_Or(self, *args, **kwargs): a = self.args return Or(*[_convert_to_varsSOP(x, self.args) for x in _get_odd_parity_terms(len(a))]) def _eval_rewrite_as_And(self, *args, **kwargs): a = self.args return And(*[_convert_to_varsPOS(x, self.args) for x in _get_even_parity_terms(len(a))]) def _eval_simplify(self, **kwargs): # as standard simplify uses simplify_logic which writes things as # And and Or, we only simplify the partial expressions before using # patterns rv = self.func(*[a.simplify(**kwargs) for a in self.args]) if not isinstance(rv, Xor): # This shouldn't really happen here return rv patterns = _simplify_patterns_xor() return _apply_patternbased_simplification(rv, patterns, kwargs['measure'], None) def _eval_subs(self, old, new): # If old is Xor, replace the parts of the arguments with new if all # are there if isinstance(old, Xor): old_set = set(old.args) if old_set.issubset(self.args): args = set(self.args) - old_set args.add(new) return self.func(*args) class Nand(BooleanFunction): """ Logical NAND function. It evaluates its arguments in order, giving True immediately if any of them are False, and False if they are all True. Returns True if any of the arguments are False Returns False if all arguments are True Examples ======== >>> from sympy.logic.boolalg import Nand >>> from sympy import symbols >>> x, y = symbols('x y') >>> Nand(False, True) True >>> Nand(True, True) False >>> Nand(x, y) ~(x & y) """ @classmethod def eval(cls, *args): return Not(And(*args)) class Nor(BooleanFunction): """ Logical NOR function. It evaluates its arguments in order, giving False immediately if any of them are True, and True if they are all False. Returns False if any argument is True Returns True if all arguments are False Examples ======== >>> from sympy.logic.boolalg import Nor >>> from sympy import symbols >>> x, y = symbols('x y') >>> Nor(True, False) False >>> Nor(True, True) False >>> Nor(False, True) False >>> Nor(False, False) True >>> Nor(x, y) ~(x | y) """ @classmethod def eval(cls, *args): return Not(Or(*args)) class Xnor(BooleanFunction): """ Logical XNOR function. Returns False if an odd number of the arguments are True and the rest are False. Returns True if an even number of the arguments are True and the rest are False. Examples ======== >>> from sympy.logic.boolalg import Xnor >>> from sympy import symbols >>> x, y = symbols('x y') >>> Xnor(True, False) False >>> Xnor(True, True) True >>> Xnor(True, False, True, True, False) False >>> Xnor(True, False, True, False) True """ @classmethod def eval(cls, *args): return Not(Xor(*args)) class Implies(BooleanFunction): r""" Logical implication. A implies B is equivalent to if A then B. Mathematically, it is written as `A \Rightarrow B` and is equivalent to `\neg A \vee B` or ``~A | B``. Accepts two Boolean arguments; A and B. Returns False if A is True and B is False Returns True otherwise. Examples ======== >>> from sympy.logic.boolalg import Implies >>> from sympy import symbols >>> x, y = symbols('x y') >>> Implies(True, False) False >>> Implies(False, False) True >>> Implies(True, True) True >>> Implies(False, True) True >>> x >> y Implies(x, y) >>> y << x Implies(x, y) Notes ===== The ``>>`` and ``<<`` operators are provided as a convenience, but note that their use here is different from their normal use in Python, which is bit shifts. Hence, ``Implies(a, b)`` and ``a >> b`` will return different things if ``a`` and ``b`` are integers. In particular, since Python considers ``True`` and ``False`` to be integers, ``True >> True`` will be the same as ``1 >> 1``, i.e., 0, which has a truth value of False. To avoid this issue, use the SymPy objects ``true`` and ``false``. >>> from sympy import true, false >>> True >> False 1 >>> true >> false False """ @classmethod def eval(cls, *args): try: newargs = [] for x in args: if isinstance(x, Number) or x in (0, 1): newargs.append(bool(x)) else: newargs.append(x) A, B = newargs except ValueError: raise ValueError( "%d operand(s) used for an Implies " "(pairs are required): %s" % (len(args), str(args))) if A in (True, False) or B in (True, False): return Or(Not(A), B) elif A == B: return true elif A.is_Relational and B.is_Relational: if A.canonical == B.canonical: return true if A.negated.canonical == B.canonical: return B else: return Basic.__new__(cls, *args) def to_nnf(self, simplify=True): a, b = self.args return Or._to_nnf(Not(a), b, simplify=simplify) def to_anf(self, deep=True): a, b = self.args return Xor._to_anf(true, a, And(a, b), deep=deep) class Equivalent(BooleanFunction): """ Equivalence relation. ``Equivalent(A, B)`` is True iff A and B are both True or both False. Returns True if all of the arguments are logically equivalent. Returns False otherwise. For two arguments, this is equivalent to :py:class:`~.Xnor`. Examples ======== >>> from sympy.logic.boolalg import Equivalent, And >>> from sympy.abc import x >>> Equivalent(False, False, False) True >>> Equivalent(True, False, False) False >>> Equivalent(x, And(x, True)) True """ def __new__(cls, *args, **options): from sympy.core.relational import Relational args = [_sympify(arg) for arg in args] argset = set(args) for x in args: if isinstance(x, Number) or x in [True, False]: # Includes 0, 1 argset.discard(x) argset.add(bool(x)) rel = [] for r in argset: if isinstance(r, Relational): rel.append((r, r.canonical, r.negated.canonical)) remove = [] for i, (r, c, nc) in enumerate(rel): for j in range(i + 1, len(rel)): rj, cj = rel[j][:2] if cj == nc: return false elif cj == c: remove.append((r, rj)) break for a, b in remove: argset.remove(a) argset.remove(b) argset.add(True) if len(argset) <= 1: return true if True in argset: argset.discard(True) return And(*argset) if False in argset: argset.discard(False) return And(*[Not(arg) for arg in argset]) _args = frozenset(argset) obj = super().__new__(cls, _args) obj._argset = _args return obj # XXX: This should be cached on the object rather than using cacheit # Maybe it can be computed in __new__? @property # type: ignore @cacheit def args(self): return tuple(ordered(self._argset)) def to_nnf(self, simplify=True): args = [] for a, b in zip(self.args, self.args[1:]): args.append(Or(Not(a), b)) args.append(Or(Not(self.args[-1]), self.args[0])) return And._to_nnf(*args, simplify=simplify) def to_anf(self, deep=True): a = And(*self.args) b = And(*[to_anf(Not(arg), deep=False) for arg in self.args]) b = distribute_xor_over_and(b) return Xor._to_anf(a, b, deep=deep) class ITE(BooleanFunction): """ If-then-else clause. ``ITE(A, B, C)`` evaluates and returns the result of B if A is true else it returns the result of C. All args must be Booleans. From a logic gate perspective, ITE corresponds to a 2-to-1 multiplexer, where A is the select signal. Examples ======== >>> from sympy.logic.boolalg import ITE, And, Xor, Or >>> from sympy.abc import x, y, z >>> ITE(True, False, True) False >>> ITE(Or(True, False), And(True, True), Xor(True, True)) True >>> ITE(x, y, z) ITE(x, y, z) >>> ITE(True, x, y) x >>> ITE(False, x, y) y >>> ITE(x, y, y) y Trying to use non-Boolean args will generate a TypeError: >>> ITE(True, [], ()) Traceback (most recent call last): ... TypeError: expecting bool, Boolean or ITE, not `[]` """ def __new__(cls, *args, **kwargs): from sympy.core.relational import Eq, Ne if len(args) != 3: raise ValueError('expecting exactly 3 args') a, b, c = args # check use of binary symbols if isinstance(a, (Eq, Ne)): # in this context, we can evaluate the Eq/Ne # if one arg is a binary symbol and the other # is true/false b, c = map(as_Boolean, (b, c)) bin_syms = set().union(*[i.binary_symbols for i in (b, c)]) if len(set(a.args) - bin_syms) == 1: # one arg is a binary_symbols _a = a if a.lhs is true: a = a.rhs elif a.rhs is true: a = a.lhs elif a.lhs is false: a = Not(a.rhs) elif a.rhs is false: a = Not(a.lhs) else: # binary can only equal True or False a = false if isinstance(_a, Ne): a = Not(a) else: a, b, c = BooleanFunction.binary_check_and_simplify( a, b, c) rv = None if kwargs.get('evaluate', True): rv = cls.eval(a, b, c) if rv is None: rv = BooleanFunction.__new__(cls, a, b, c, evaluate=False) return rv @classmethod def eval(cls, *args): from sympy.core.relational import Eq, Ne # do the args give a singular result? a, b, c = args if isinstance(a, (Ne, Eq)): _a = a if true in a.args: a = a.lhs if a.rhs is true else a.rhs elif false in a.args: a = Not(a.lhs) if a.rhs is false else Not(a.rhs) else: _a = None if _a is not None and isinstance(_a, Ne): a = Not(a) if a is true: return b if a is false: return c if b == c: return b else: # or maybe the results allow the answer to be expressed # in terms of the condition if b is true and c is false: return a if b is false and c is true: return Not(a) if [a, b, c] != args: return cls(a, b, c, evaluate=False) def to_nnf(self, simplify=True): a, b, c = self.args return And._to_nnf(Or(Not(a), b), Or(a, c), simplify=simplify) def _eval_as_set(self): return self.to_nnf().as_set() def _eval_rewrite_as_Piecewise(self, *args, **kwargs): from sympy.functions.elementary.piecewise import Piecewise return Piecewise((args[1], args[0]), (args[2], True)) class Exclusive(BooleanFunction): """ True if only one or no argument is true. ``Exclusive(A, B, C)`` is equivalent to ``~(A & B) & ~(A & C) & ~(B & C)``. For two arguments, this is equivalent to :py:class:`~.Xor`. Examples ======== >>> from sympy.logic.boolalg import Exclusive >>> Exclusive(False, False, False) True >>> Exclusive(False, True, False) True >>> Exclusive(False, True, True) False """ @classmethod def eval(cls, *args): and_args = [] for a, b in combinations(args, 2): and_args.append(Not(And(a, b))) return And(*and_args) # end class definitions. Some useful methods def conjuncts(expr): """Return a list of the conjuncts in ``expr``. Examples ======== >>> from sympy.logic.boolalg import conjuncts >>> from sympy.abc import A, B >>> conjuncts(A & B) frozenset({A, B}) >>> conjuncts(A | B) frozenset({A | B}) """ return And.make_args(expr) def disjuncts(expr): """Return a list of the disjuncts in ``expr``. Examples ======== >>> from sympy.logic.boolalg import disjuncts >>> from sympy.abc import A, B >>> disjuncts(A | B) frozenset({A, B}) >>> disjuncts(A & B) frozenset({A & B}) """ return Or.make_args(expr) def distribute_and_over_or(expr): """ Given a sentence ``expr`` consisting of conjunctions and disjunctions of literals, return an equivalent sentence in CNF. Examples ======== >>> from sympy.logic.boolalg import distribute_and_over_or, And, Or, Not >>> from sympy.abc import A, B, C >>> distribute_and_over_or(Or(A, And(Not(B), Not(C)))) (A | ~B) & (A | ~C) """ return _distribute((expr, And, Or)) def distribute_or_over_and(expr): """ Given a sentence ``expr`` consisting of conjunctions and disjunctions of literals, return an equivalent sentence in DNF. Note that the output is NOT simplified. Examples ======== >>> from sympy.logic.boolalg import distribute_or_over_and, And, Or, Not >>> from sympy.abc import A, B, C >>> distribute_or_over_and(And(Or(Not(A), B), C)) (B & C) | (C & ~A) """ return _distribute((expr, Or, And)) def distribute_xor_over_and(expr): """ Given a sentence ``expr`` consisting of conjunction and exclusive disjunctions of literals, return an equivalent exclusive disjunction. Note that the output is NOT simplified. Examples ======== >>> from sympy.logic.boolalg import distribute_xor_over_and, And, Xor, Not >>> from sympy.abc import A, B, C >>> distribute_xor_over_and(And(Xor(Not(A), B), C)) (B & C) ^ (C & ~A) """ return _distribute((expr, Xor, And)) def _distribute(info): """ Distributes ``info[1]`` over ``info[2]`` with respect to ``info[0]``. """ if isinstance(info[0], info[2]): for arg in info[0].args: if isinstance(arg, info[1]): conj = arg break else: return info[0] rest = info[2](*[a for a in info[0].args if a is not conj]) return info[1](*list(map(_distribute, [(info[2](c, rest), info[1], info[2]) for c in conj.args])), remove_true=False) elif isinstance(info[0], info[1]): return info[1](*list(map(_distribute, [(x, info[1], info[2]) for x in info[0].args])), remove_true=False) else: return info[0] def to_anf(expr, deep=True): r""" Converts expr to Algebraic Normal Form (ANF). ANF is a canonical normal form, which means that two equivalent formulas will convert to the same ANF. A logical expression is in ANF if it has the form .. math:: 1 \oplus a \oplus b \oplus ab \oplus abc i.e. it can be: - purely true, - purely false, - conjunction of variables, - exclusive disjunction. The exclusive disjunction can only contain true, variables or conjunction of variables. No negations are permitted. If ``deep`` is ``False``, arguments of the boolean expression are considered variables, i.e. only the top-level expression is converted to ANF. Examples ======== >>> from sympy.logic.boolalg import And, Or, Not, Implies, Equivalent >>> from sympy.logic.boolalg import to_anf >>> from sympy.abc import A, B, C >>> to_anf(Not(A)) A ^ True >>> to_anf(And(Or(A, B), Not(C))) A ^ B ^ (A & B) ^ (A & C) ^ (B & C) ^ (A & B & C) >>> to_anf(Implies(Not(A), Equivalent(B, C)), deep=False) True ^ ~A ^ (~A & (Equivalent(B, C))) """ expr = sympify(expr) if is_anf(expr): return expr return expr.to_anf(deep=deep) def to_nnf(expr, simplify=True): """ Converts ``expr`` to Negation Normal Form (NNF). A logical expression is in NNF if it contains only :py:class:`~.And`, :py:class:`~.Or` and :py:class:`~.Not`, and :py:class:`~.Not` is applied only to literals. If ``simplify`` is ``True``, the result contains no redundant clauses. Examples ======== >>> from sympy.abc import A, B, C, D >>> from sympy.logic.boolalg import Not, Equivalent, to_nnf >>> to_nnf(Not((~A & ~B) | (C & D))) (A | B) & (~C | ~D) >>> to_nnf(Equivalent(A >> B, B >> A)) (A | ~B | (A & ~B)) & (B | ~A | (B & ~A)) """ if is_nnf(expr, simplify): return expr return expr.to_nnf(simplify) def to_cnf(expr, simplify=False, force=False): """ Convert a propositional logical sentence ``expr`` to conjunctive normal form: ``((A | ~B | ...) & (B | C | ...) & ...)``. If ``simplify`` is ``True``, ``expr`` is evaluated to its simplest CNF form using the Quine-McCluskey algorithm; this may take a long time. If there are more than 8 variables the ``force`` flag must be set to ``True`` to simplify (default is ``False``). Examples ======== >>> from sympy.logic.boolalg import to_cnf >>> from sympy.abc import A, B, D >>> to_cnf(~(A | B) | D) (D | ~A) & (D | ~B) >>> to_cnf((A | B) & (A | ~A), True) A | B """ expr = sympify(expr) if not isinstance(expr, BooleanFunction): return expr if simplify: if not force and len(_find_predicates(expr)) > 8: raise ValueError(filldedent(''' To simplify a logical expression with more than 8 variables may take a long time and requires the use of `force=True`.''')) return simplify_logic(expr, 'cnf', True, force=force) # Don't convert unless we have to if is_cnf(expr): return expr expr = eliminate_implications(expr) res = distribute_and_over_or(expr) return res def to_dnf(expr, simplify=False, force=False): """ Convert a propositional logical sentence ``expr`` to disjunctive normal form: ``((A & ~B & ...) | (B & C & ...) | ...)``. If ``simplify`` is ``True``, ``expr`` is evaluated to its simplest DNF form using the Quine-McCluskey algorithm; this may take a long time. If there are more than 8 variables, the ``force`` flag must be set to ``True`` to simplify (default is ``False``). Examples ======== >>> from sympy.logic.boolalg import to_dnf >>> from sympy.abc import A, B, C >>> to_dnf(B & (A | C)) (A & B) | (B & C) >>> to_dnf((A & B) | (A & ~B) | (B & C) | (~B & C), True) A | C """ expr = sympify(expr) if not isinstance(expr, BooleanFunction): return expr if simplify: if not force and len(_find_predicates(expr)) > 8: raise ValueError(filldedent(''' To simplify a logical expression with more than 8 variables may take a long time and requires the use of `force=True`.''')) return simplify_logic(expr, 'dnf', True, force=force) # Don't convert unless we have to if is_dnf(expr): return expr expr = eliminate_implications(expr) return distribute_or_over_and(expr) def is_anf(expr): r""" Checks if ``expr`` is in Algebraic Normal Form (ANF). A logical expression is in ANF if it has the form .. math:: 1 \oplus a \oplus b \oplus ab \oplus abc i.e. it is purely true, purely false, conjunction of variables or exclusive disjunction. The exclusive disjunction can only contain true, variables or conjunction of variables. No negations are permitted. Examples ======== >>> from sympy.logic.boolalg import And, Not, Xor, true, is_anf >>> from sympy.abc import A, B, C >>> is_anf(true) True >>> is_anf(A) True >>> is_anf(And(A, B, C)) True >>> is_anf(Xor(A, Not(B))) False """ expr = sympify(expr) if is_literal(expr) and not isinstance(expr, Not): return True if isinstance(expr, And): for arg in expr.args: if not arg.is_Symbol: return False return True elif isinstance(expr, Xor): for arg in expr.args: if isinstance(arg, And): for a in arg.args: if not a.is_Symbol: return False elif is_literal(arg): if isinstance(arg, Not): return False else: return False return True else: return False def is_nnf(expr, simplified=True): """ Checks if ``expr`` is in Negation Normal Form (NNF). A logical expression is in NNF if it contains only :py:class:`~.And`, :py:class:`~.Or` and :py:class:`~.Not`, and :py:class:`~.Not` is applied only to literals. If ``simplified`` is ``True``, checks if result contains no redundant clauses. Examples ======== >>> from sympy.abc import A, B, C >>> from sympy.logic.boolalg import Not, is_nnf >>> is_nnf(A & B | ~C) True >>> is_nnf((A | ~A) & (B | C)) False >>> is_nnf((A | ~A) & (B | C), False) True >>> is_nnf(Not(A & B) | C) False >>> is_nnf((A >> B) & (B >> A)) False """ expr = sympify(expr) if is_literal(expr): return True stack = [expr] while stack: expr = stack.pop() if expr.func in (And, Or): if simplified: args = expr.args for arg in args: if Not(arg) in args: return False stack.extend(expr.args) elif not is_literal(expr): return False return True def is_cnf(expr): """ Test whether or not an expression is in conjunctive normal form. Examples ======== >>> from sympy.logic.boolalg import is_cnf >>> from sympy.abc import A, B, C >>> is_cnf(A | B | C) True >>> is_cnf(A & B & C) True >>> is_cnf((A & B) | C) False """ return _is_form(expr, And, Or) def is_dnf(expr): """ Test whether or not an expression is in disjunctive normal form. Examples ======== >>> from sympy.logic.boolalg import is_dnf >>> from sympy.abc import A, B, C >>> is_dnf(A | B | C) True >>> is_dnf(A & B & C) True >>> is_dnf((A & B) | C) True >>> is_dnf(A & (B | C)) False """ return _is_form(expr, Or, And) def _is_form(expr, function1, function2): """ Test whether or not an expression is of the required form. """ expr = sympify(expr) vals = function1.make_args(expr) if isinstance(expr, function1) else [expr] for lit in vals: if isinstance(lit, function2): vals2 = function2.make_args(lit) if isinstance(lit, function2) else [lit] for l in vals2: if is_literal(l) is False: return False elif is_literal(lit) is False: return False return True def eliminate_implications(expr): """ Change :py:class:`~.Implies` and :py:class:`~.Equivalent` into :py:class:`~.And`, :py:class:`~.Or`, and :py:class:`~.Not`. That is, return an expression that is equivalent to ``expr``, but has only ``&``, ``|``, and ``~`` as logical operators. Examples ======== >>> from sympy.logic.boolalg import Implies, Equivalent, \ eliminate_implications >>> from sympy.abc import A, B, C >>> eliminate_implications(Implies(A, B)) B | ~A >>> eliminate_implications(Equivalent(A, B)) (A | ~B) & (B | ~A) >>> eliminate_implications(Equivalent(A, B, C)) (A | ~C) & (B | ~A) & (C | ~B) """ return to_nnf(expr, simplify=False) def is_literal(expr): """ Returns True if expr is a literal, else False. Examples ======== >>> from sympy import Or, Q >>> from sympy.abc import A, B >>> from sympy.logic.boolalg import is_literal >>> is_literal(A) True >>> is_literal(~A) True >>> is_literal(Q.zero(A)) True >>> is_literal(A + B) True >>> is_literal(Or(A, B)) False """ from sympy.assumptions import AppliedPredicate if isinstance(expr, Not): return is_literal(expr.args[0]) elif expr in (True, False) or isinstance(expr, AppliedPredicate) or expr.is_Atom: return True elif not isinstance(expr, BooleanFunction) and all( (isinstance(expr, AppliedPredicate) or a.is_Atom) for a in expr.args): return True return False def to_int_repr(clauses, symbols): """ Takes clauses in CNF format and puts them into an integer representation. Examples ======== >>> from sympy.logic.boolalg import to_int_repr >>> from sympy.abc import x, y >>> to_int_repr([x | y, y], [x, y]) == [{1, 2}, {2}] True """ # Convert the symbol list into a dict symbols = dict(zip(symbols, range(1, len(symbols) + 1))) def append_symbol(arg, symbols): if isinstance(arg, Not): return -symbols[arg.args[0]] else: return symbols[arg] return [{append_symbol(arg, symbols) for arg in Or.make_args(c)} for c in clauses] def term_to_integer(term): """ Return an integer corresponding to the base-2 digits given by *term*. Parameters ========== term : a string or list of ones and zeros Examples ======== >>> from sympy.logic.boolalg import term_to_integer >>> term_to_integer([1, 0, 0]) 4 >>> term_to_integer('100') 4 """ return int(''.join(list(map(str, list(term)))), 2) integer_to_term = ibin # XXX could delete? def truth_table(expr, variables, input=True): """ Return a generator of all possible configurations of the input variables, and the result of the boolean expression for those values. Parameters ========== expr : Boolean expression variables : list of variables input : bool (default ``True``) Indicates whether to return the input combinations. Examples ======== >>> from sympy.logic.boolalg import truth_table >>> from sympy.abc import x,y >>> table = truth_table(x >> y, [x, y]) >>> for t in table: ... print('{0} -> {1}'.format(*t)) [0, 0] -> True [0, 1] -> True [1, 0] -> False [1, 1] -> True >>> table = truth_table(x | y, [x, y]) >>> list(table) [([0, 0], False), ([0, 1], True), ([1, 0], True), ([1, 1], True)] If ``input`` is ``False``, ``truth_table`` returns only a list of truth values. In this case, the corresponding input values of variables can be deduced from the index of a given output. >>> from sympy.utilities.iterables import ibin >>> vars = [y, x] >>> values = truth_table(x >> y, vars, input=False) >>> values = list(values) >>> values [True, False, True, True] >>> for i, value in enumerate(values): ... print('{0} -> {1}'.format(list(zip( ... vars, ibin(i, len(vars)))), value)) [(y, 0), (x, 0)] -> True [(y, 0), (x, 1)] -> False [(y, 1), (x, 0)] -> True [(y, 1), (x, 1)] -> True """ variables = [sympify(v) for v in variables] expr = sympify(expr) if not isinstance(expr, BooleanFunction) and not is_literal(expr): return table = product((0, 1), repeat=len(variables)) for term in table: value = expr.xreplace(dict(zip(variables, term))) if input: yield list(term), value else: yield value def _check_pair(minterm1, minterm2): """ Checks if a pair of minterms differs by only one bit. If yes, returns index, else returns `-1`. """ # Early termination seems to be faster than list comprehension, # at least for large examples. index = -1 for x, i in enumerate(minterm1): # zip(minterm1, minterm2) is slower if i != minterm2[x]: if index == -1: index = x else: return -1 return index def _convert_to_varsSOP(minterm, variables): """ Converts a term in the expansion of a function from binary to its variable form (for SOP). """ temp = [variables[n] if val == 1 else Not(variables[n]) for n, val in enumerate(minterm) if val != 3] return And(*temp) def _convert_to_varsPOS(maxterm, variables): """ Converts a term in the expansion of a function from binary to its variable form (for POS). """ temp = [variables[n] if val == 0 else Not(variables[n]) for n, val in enumerate(maxterm) if val != 3] return Or(*temp) def _convert_to_varsANF(term, variables): """ Converts a term in the expansion of a function from binary to its variable form (for ANF). Parameters ========== term : list of 1's and 0's (complementation pattern) variables : list of variables """ temp = [variables[n] for n, t in enumerate(term) if t == 1] if not temp: return true return And(*temp) def _get_odd_parity_terms(n): """ Returns a list of lists, with all possible combinations of n zeros and ones with an odd number of ones. """ return [e for e in [ibin(i, n) for i in range(2**n)] if sum(e) % 2 == 1] def _get_even_parity_terms(n): """ Returns a list of lists, with all possible combinations of n zeros and ones with an even number of ones. """ return [e for e in [ibin(i, n) for i in range(2**n)] if sum(e) % 2 == 0] def _simplified_pairs(terms): """ Reduces a set of minterms, if possible, to a simplified set of minterms with one less variable in the terms using QM method. """ if not terms: return [] simplified_terms = [] todo = list(range(len(terms))) # Count number of ones as _check_pair can only potentially match if there # is at most a difference of a single one termdict = defaultdict(list) for n, term in enumerate(terms): ones = sum([1 for t in term if t == 1]) termdict[ones].append(n) variables = len(terms[0]) for k in range(variables): for i in termdict[k]: for j in termdict[k+1]: index = _check_pair(terms[i], terms[j]) if index != -1: # Mark terms handled todo[i] = todo[j] = None # Copy old term newterm = terms[i][:] # Set differing position to don't care newterm[index] = 3 # Add if not already there if newterm not in simplified_terms: simplified_terms.append(newterm) if simplified_terms: # Further simplifications only among the new terms simplified_terms = _simplified_pairs(simplified_terms) # Add remaining, non-simplified, terms simplified_terms.extend([terms[i] for i in todo if i is not None]) return simplified_terms def _rem_redundancy(l1, terms): """ After the truth table has been sufficiently simplified, use the prime implicant table method to recognize and eliminate redundant pairs, and return the essential arguments. """ if not terms: return [] nterms = len(terms) nl1 = len(l1) # Create dominating matrix dommatrix = [[0]*nl1 for n in range(nterms)] colcount = [0]*nl1 rowcount = [0]*nterms for primei, prime in enumerate(l1): for termi, term in enumerate(terms): # Check prime implicant covering term if all(t == 3 or t == mt for t, mt in zip(prime, term)): dommatrix[termi][primei] = 1 colcount[primei] += 1 rowcount[termi] += 1 # Keep track if anything changed anythingchanged = True # Then, go again while anythingchanged: anythingchanged = False for rowi in range(nterms): # Still non-dominated? if rowcount[rowi]: row = dommatrix[rowi] for row2i in range(nterms): # Still non-dominated? if rowi != row2i and rowcount[rowi] and (rowcount[rowi] <= rowcount[row2i]): row2 = dommatrix[row2i] if all(row2[n] >= row[n] for n in range(nl1)): # row2 dominating row, remove row2 rowcount[row2i] = 0 anythingchanged = True for primei, prime in enumerate(row2): if prime: # Make corresponding entry 0 dommatrix[row2i][primei] = 0 colcount[primei] -= 1 colcache = {} for coli in range(nl1): # Still non-dominated? if colcount[coli]: if coli in colcache: col = colcache[coli] else: col = [dommatrix[i][coli] for i in range(nterms)] colcache[coli] = col for col2i in range(nl1): # Still non-dominated? if coli != col2i and colcount[col2i] and (colcount[coli] >= colcount[col2i]): if col2i in colcache: col2 = colcache[col2i] else: col2 = [dommatrix[i][col2i] for i in range(nterms)] colcache[col2i] = col2 if all(col[n] >= col2[n] for n in range(nterms)): # col dominating col2, remove col2 colcount[col2i] = 0 anythingchanged = True for termi, term in enumerate(col2): if term and dommatrix[termi][col2i]: # Make corresponding entry 0 dommatrix[termi][col2i] = 0 rowcount[termi] -= 1 if not anythingchanged: # Heuristically select the prime implicant covering most terms maxterms = 0 bestcolidx = -1 for coli in range(nl1): s = colcount[coli] if s > maxterms: bestcolidx = coli maxterms = s # In case we found a prime implicant covering at least two terms if bestcolidx != -1 and maxterms > 1: for primei, prime in enumerate(l1): if primei != bestcolidx: for termi, term in enumerate(colcache[bestcolidx]): if term and dommatrix[termi][primei]: # Make corresponding entry 0 dommatrix[termi][primei] = 0 anythingchanged = True rowcount[termi] -= 1 colcount[primei] -= 1 return [l1[i] for i in range(nl1) if colcount[i]] def _input_to_binlist(inputlist, variables): binlist = [] bits = len(variables) for val in inputlist: if isinstance(val, int): binlist.append(ibin(val, bits)) elif isinstance(val, dict): nonspecvars = list(variables) for key in val.keys(): nonspecvars.remove(key) for t in product((0, 1), repeat=len(nonspecvars)): d = dict(zip(nonspecvars, t)) d.update(val) binlist.append([d[v] for v in variables]) elif isinstance(val, (list, tuple)): if len(val) != bits: raise ValueError("Each term must contain {bits} bits as there are" "\n{bits} variables (or be an integer)." "".format(bits=bits)) binlist.append(list(val)) else: raise TypeError("A term list can only contain lists," " ints or dicts.") return binlist def SOPform(variables, minterms, dontcares=None): """ The SOPform function uses simplified_pairs and a redundant group- eliminating algorithm to convert the list of all input combos that generate '1' (the minterms) into the smallest sum-of-products form. The variables must be given as the first argument. Return a logical :py:class:`~.Or` function (i.e., the "sum of products" or "SOP" form) that gives the desired outcome. If there are inputs that can be ignored, pass them as a list, too. The result will be one of the (perhaps many) functions that satisfy the conditions. Examples ======== >>> from sympy.logic import SOPform >>> from sympy import symbols >>> w, x, y, z = symbols('w x y z') >>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1], ... [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1]] >>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]] >>> SOPform([w, x, y, z], minterms, dontcares) (y & z) | (~w & ~x) The terms can also be represented as integers: >>> minterms = [1, 3, 7, 11, 15] >>> dontcares = [0, 2, 5] >>> SOPform([w, x, y, z], minterms, dontcares) (y & z) | (~w & ~x) They can also be specified using dicts, which does not have to be fully specified: >>> minterms = [{w: 0, x: 1}, {y: 1, z: 1, x: 0}] >>> SOPform([w, x, y, z], minterms) (x & ~w) | (y & z & ~x) Or a combination: >>> minterms = [4, 7, 11, [1, 1, 1, 1]] >>> dontcares = [{w : 0, x : 0, y: 0}, 5] >>> SOPform([w, x, y, z], minterms, dontcares) (w & y & z) | (~w & ~y) | (x & z & ~w) See also ======== POSform References ========== .. [1] https://en.wikipedia.org/wiki/Quine-McCluskey_algorithm .. [2] https://en.wikipedia.org/wiki/Don%27t-care_term """ if not minterms: return false variables = tuple(map(sympify, variables)) minterms = _input_to_binlist(minterms, variables) dontcares = _input_to_binlist((dontcares or []), variables) for d in dontcares: if d in minterms: raise ValueError('%s in minterms is also in dontcares' % d) return _sop_form(variables, minterms, dontcares) def _sop_form(variables, minterms, dontcares): new = _simplified_pairs(minterms + dontcares) essential = _rem_redundancy(new, minterms) return Or(*[_convert_to_varsSOP(x, variables) for x in essential]) def POSform(variables, minterms, dontcares=None): """ The POSform function uses simplified_pairs and a redundant-group eliminating algorithm to convert the list of all input combinations that generate '1' (the minterms) into the smallest product-of-sums form. The variables must be given as the first argument. Return a logical :py:class:`~.And` function (i.e., the "product of sums" or "POS" form) that gives the desired outcome. If there are inputs that can be ignored, pass them as a list, too. The result will be one of the (perhaps many) functions that satisfy the conditions. Examples ======== >>> from sympy.logic import POSform >>> from sympy import symbols >>> w, x, y, z = symbols('w x y z') >>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], ... [1, 0, 1, 1], [1, 1, 1, 1]] >>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]] >>> POSform([w, x, y, z], minterms, dontcares) z & (y | ~w) The terms can also be represented as integers: >>> minterms = [1, 3, 7, 11, 15] >>> dontcares = [0, 2, 5] >>> POSform([w, x, y, z], minterms, dontcares) z & (y | ~w) They can also be specified using dicts, which does not have to be fully specified: >>> minterms = [{w: 0, x: 1}, {y: 1, z: 1, x: 0}] >>> POSform([w, x, y, z], minterms) (x | y) & (x | z) & (~w | ~x) Or a combination: >>> minterms = [4, 7, 11, [1, 1, 1, 1]] >>> dontcares = [{w : 0, x : 0, y: 0}, 5] >>> POSform([w, x, y, z], minterms, dontcares) (w | x) & (y | ~w) & (z | ~y) See also ======== SOPform References ========== .. [1] https://en.wikipedia.org/wiki/Quine-McCluskey_algorithm .. [2] https://en.wikipedia.org/wiki/Don%27t-care_term """ if not minterms: return false variables = tuple(map(sympify, variables)) minterms = _input_to_binlist(minterms, variables) dontcares = _input_to_binlist((dontcares or []), variables) for d in dontcares: if d in minterms: raise ValueError('%s in minterms is also in dontcares' % d) maxterms = [] for t in product((0, 1), repeat=len(variables)): t = list(t) if (t not in minterms) and (t not in dontcares): maxterms.append(t) new = _simplified_pairs(maxterms + dontcares) essential = _rem_redundancy(new, maxterms) return And(*[_convert_to_varsPOS(x, variables) for x in essential]) def ANFform(variables, truthvalues): """ The ANFform function converts the list of truth values to Algebraic Normal Form (ANF). The variables must be given as the first argument. Return True, False, logical :py:class:`~.And` function (i.e., the "Zhegalkin monomial") or logical :py:class:`~.Xor` function (i.e., the "Zhegalkin polynomial"). When True and False are represented by 1 and 0, respectively, then :py:class:`~.And` is multiplication and :py:class:`~.Xor` is addition. Formally a "Zhegalkin monomial" is the product (logical And) of a finite set of distinct variables, including the empty set whose product is denoted 1 (True). A "Zhegalkin polynomial" is the sum (logical Xor) of a set of Zhegalkin monomials, with the empty set denoted by 0 (False). Parameters ========== variables : list of variables truthvalues : list of 1's and 0's (result column of truth table) Examples ======== >>> from sympy.logic.boolalg import ANFform >>> from sympy.abc import x, y >>> ANFform([x], [1, 0]) x ^ True >>> ANFform([x, y], [0, 1, 1, 1]) x ^ y ^ (x & y) References ========== .. [1] https://en.wikipedia.org/wiki/Zhegalkin_polynomial """ n_vars = len(variables) n_values = len(truthvalues) if n_values != 2 ** n_vars: raise ValueError("The number of truth values must be equal to 2^%d, " "got %d" % (n_vars, n_values)) variables = tuple(map(sympify, variables)) coeffs = anf_coeffs(truthvalues) terms = [] for i, t in enumerate(product((0, 1), repeat=n_vars)): if coeffs[i] == 1: terms.append(t) return Xor(*[_convert_to_varsANF(x, variables) for x in terms], remove_true=False) def anf_coeffs(truthvalues): """ Convert a list of truth values of some boolean expression to the list of coefficients of the polynomial mod 2 (exclusive disjunction) representing the boolean expression in ANF (i.e., the "Zhegalkin polynomial"). There are `2^n` possible Zhegalkin monomials in `n` variables, since each monomial is fully specified by the presence or absence of each variable. We can enumerate all the monomials. For example, boolean function with four variables ``(a, b, c, d)`` can contain up to `2^4 = 16` monomials. The 13-th monomial is the product ``a & b & d``, because 13 in binary is 1, 1, 0, 1. A given monomial's presence or absence in a polynomial corresponds to that monomial's coefficient being 1 or 0 respectively. Examples ======== >>> from sympy.logic.boolalg import anf_coeffs, bool_monomial, Xor >>> from sympy.abc import a, b, c >>> truthvalues = [0, 1, 1, 0, 0, 1, 0, 1] >>> coeffs = anf_coeffs(truthvalues) >>> coeffs [0, 1, 1, 0, 0, 0, 1, 0] >>> polynomial = Xor(*[ ... bool_monomial(k, [a, b, c]) ... for k, coeff in enumerate(coeffs) if coeff == 1 ... ]) >>> polynomial b ^ c ^ (a & b) """ s = '{:b}'.format(len(truthvalues)) n = len(s) - 1 if len(truthvalues) != 2**n: raise ValueError("The number of truth values must be a power of two, " "got %d" % len(truthvalues)) coeffs = [[v] for v in truthvalues] for i in range(n): tmp = [] for j in range(2 ** (n-i-1)): tmp.append(coeffs[2*j] + list(map(lambda x, y: x^y, coeffs[2*j], coeffs[2*j+1]))) coeffs = tmp return coeffs[0] def bool_minterm(k, variables): """ Return the k-th minterm. Minterms are numbered by a binary encoding of the complementation pattern of the variables. This convention assigns the value 1 to the direct form and 0 to the complemented form. Parameters ========== k : int or list of 1's and 0's (complementation pattern) variables : list of variables Examples ======== >>> from sympy.logic.boolalg import bool_minterm >>> from sympy.abc import x, y, z >>> bool_minterm([1, 0, 1], [x, y, z]) x & z & ~y >>> bool_minterm(6, [x, y, z]) x & y & ~z References ========== .. [1] https://en.wikipedia.org/wiki/Canonical_normal_form#Indexing_minterms """ if isinstance(k, int): k = ibin(k, len(variables)) variables = tuple(map(sympify, variables)) return _convert_to_varsSOP(k, variables) def bool_maxterm(k, variables): """ Return the k-th maxterm. Each maxterm is assigned an index based on the opposite conventional binary encoding used for minterms. The maxterm convention assigns the value 0 to the direct form and 1 to the complemented form. Parameters ========== k : int or list of 1's and 0's (complementation pattern) variables : list of variables Examples ======== >>> from sympy.logic.boolalg import bool_maxterm >>> from sympy.abc import x, y, z >>> bool_maxterm([1, 0, 1], [x, y, z]) y | ~x | ~z >>> bool_maxterm(6, [x, y, z]) z | ~x | ~y References ========== .. [1] https://en.wikipedia.org/wiki/Canonical_normal_form#Indexing_maxterms """ if isinstance(k, int): k = ibin(k, len(variables)) variables = tuple(map(sympify, variables)) return _convert_to_varsPOS(k, variables) def bool_monomial(k, variables): """ Return the k-th monomial. Monomials are numbered by a binary encoding of the presence and absences of the variables. This convention assigns the value 1 to the presence of variable and 0 to the absence of variable. Each boolean function can be uniquely represented by a Zhegalkin Polynomial (Algebraic Normal Form). The Zhegalkin Polynomial of the boolean function with `n` variables can contain up to `2^n` monomials. We can enumerate all the monomials. Each monomial is fully specified by the presence or absence of each variable. For example, boolean function with four variables ``(a, b, c, d)`` can contain up to `2^4 = 16` monomials. The 13-th monomial is the product ``a & b & d``, because 13 in binary is 1, 1, 0, 1. Parameters ========== k : int or list of 1's and 0's variables : list of variables Examples ======== >>> from sympy.logic.boolalg import bool_monomial >>> from sympy.abc import x, y, z >>> bool_monomial([1, 0, 1], [x, y, z]) x & z >>> bool_monomial(6, [x, y, z]) x & y """ if isinstance(k, int): k = ibin(k, len(variables)) variables = tuple(map(sympify, variables)) return _convert_to_varsANF(k, variables) def _find_predicates(expr): """Helper to find logical predicates in BooleanFunctions. A logical predicate is defined here as anything within a BooleanFunction that is not a BooleanFunction itself. """ if not isinstance(expr, BooleanFunction): return {expr} return set().union(*(map(_find_predicates, expr.args))) def simplify_logic(expr, form=None, deep=True, force=False, dontcare=None): """ This function simplifies a boolean function to its simplified version in SOP or POS form. The return type is an :py:class:`~.Or` or :py:class:`~.And` object in SymPy. Parameters ========== expr : Boolean form : string (``'cnf'`` or ``'dnf'``) or ``None`` (default). If ``'cnf'`` or ``'dnf'``, the simplest expression in the corresponding normal form is returned; if ``None``, the answer is returned according to the form with fewest args (in CNF by default). deep : bool (default ``True``) Indicates whether to recursively simplify any non-boolean functions contained within the input. force : bool (default ``False``) As the simplifications require exponential time in the number of variables, there is by default a limit on expressions with 8 variables. When the expression has more than 8 variables only symbolical simplification (controlled by ``deep``) is made. By setting ``force`` to ``True``, this limit is removed. Be aware that this can lead to very long simplification times. dontcare : Boolean Optimize expression under the assumption that inputs where this expression is true are don't care. This is useful in e.g. Piecewise conditions, where later conditions do not need to consider inputs that are converted by previous conditions. For example, if a previous condition is ``And(A, B)``, the simplification of expr can be made with don't cares for ``And(A, B)``. Examples ======== >>> from sympy.logic import simplify_logic >>> from sympy.abc import x, y, z >>> b = (~x & ~y & ~z) | ( ~x & ~y & z) >>> simplify_logic(b) ~x & ~y >>> simplify_logic(x | y, dontcare=y) x References ========== .. [1] https://en.wikipedia.org/wiki/Don%27t-care_term """ if form not in (None, 'cnf', 'dnf'): raise ValueError("form can be cnf or dnf only") expr = sympify(expr) # check for quick exit if form is given: right form and all args are # literal and do not involve Not if form: form_ok = False if form == 'cnf': form_ok = is_cnf(expr) elif form == 'dnf': form_ok = is_dnf(expr) if form_ok and all(is_literal(a) for a in expr.args): return expr from sympy.core.relational import Relational if deep: variables = expr.atoms(Relational) from sympy.simplify.simplify import simplify s = tuple(map(simplify, variables)) expr = expr.xreplace(dict(zip(variables, s))) if not isinstance(expr, BooleanFunction): return expr # Replace Relationals with Dummys to possibly # reduce the number of variables repl = {} undo = {} from sympy.core.symbol import Dummy variables = expr.atoms(Relational) if dontcare is not None: dontcare = sympify(dontcare) variables.update(dontcare.atoms(Relational)) while variables: var = variables.pop() if var.is_Relational: d = Dummy() undo[d] = var repl[var] = d nvar = var.negated if nvar in variables: repl[nvar] = Not(d) variables.remove(nvar) expr = expr.xreplace(repl) if dontcare is not None: dontcare = dontcare.xreplace(repl) # Get new variables after replacing variables = _find_predicates(expr) if not force and len(variables) > 8: return expr.xreplace(undo) if dontcare is not None: # Add variables from dontcare dcvariables = _find_predicates(dontcare) variables.update(dcvariables) # if too many restore to variables only if not force and len(variables) > 8: variables = _find_predicates(expr) dontcare = None # group into constants and variable values c, v = sift(ordered(variables), lambda x: x in (True, False), binary=True) variables = c + v # standardize constants to be 1 or 0 in keeping with truthtable c = [1 if i == True else 0 for i in c] truthtable = _get_truthtable(v, expr, c) if dontcare is not None: dctruthtable = _get_truthtable(v, dontcare, c) truthtable = [t for t in truthtable if t not in dctruthtable] else: dctruthtable = [] big = len(truthtable) >= (2 ** (len(variables) - 1)) if form == 'dnf' or form is None and big: return _sop_form(variables, truthtable, dctruthtable).xreplace(undo) return POSform(variables, truthtable, dctruthtable).xreplace(undo) def _get_truthtable(variables, expr, const): """ Return a list of all combinations leading to a True result for ``expr``. """ _variables = variables.copy() def _get_tt(inputs): if _variables: v = _variables.pop() tab = [[i[0].xreplace({v: false}), [0] + i[1]] for i in inputs if i[0] is not false] tab.extend([[i[0].xreplace({v: true}), [1] + i[1]] for i in inputs if i[0] is not false]) return _get_tt(tab) return inputs res = [const + k[1] for k in _get_tt([[expr, []]]) if k[0]] if res == [[]]: return [] else: return res def _finger(eq): """ Assign a 5-item fingerprint to each symbol in the equation: [ # of times it appeared as a Symbol; # of times it appeared as a Not(symbol); # of times it appeared as a Symbol in an And or Or; # of times it appeared as a Not(Symbol) in an And or Or; a sorted tuple of tuples, (i, j, k), where i is the number of arguments in an And or Or with which it appeared as a Symbol, and j is the number of arguments that were Not(Symbol); k is the number of times that (i, j) was seen. ] Examples ======== >>> from sympy.logic.boolalg import _finger as finger >>> from sympy import And, Or, Not, Xor, to_cnf, symbols >>> from sympy.abc import a, b, x, y >>> eq = Or(And(Not(y), a), And(Not(y), b), And(x, y)) >>> dict(finger(eq)) {(0, 0, 1, 0, ((2, 0, 1),)): [x], (0, 0, 1, 0, ((2, 1, 1),)): [a, b], (0, 0, 1, 2, ((2, 0, 1),)): [y]} >>> dict(finger(x & ~y)) {(0, 1, 0, 0, ()): [y], (1, 0, 0, 0, ()): [x]} In the following, the (5, 2, 6) means that there were 6 Or functions in which a symbol appeared as itself amongst 5 arguments in which there were also 2 negated symbols, e.g. ``(a0 | a1 | a2 | ~a3 | ~a4)`` is counted once for a0, a1 and a2. >>> dict(finger(to_cnf(Xor(*symbols('a:5'))))) {(0, 0, 8, 8, ((5, 0, 1), (5, 2, 6), (5, 4, 1))): [a0, a1, a2, a3, a4]} The equation must not have more than one level of nesting: >>> dict(finger(And(Or(x, y), y))) {(0, 0, 1, 0, ((2, 0, 1),)): [x], (1, 0, 1, 0, ((2, 0, 1),)): [y]} >>> dict(finger(And(Or(x, And(a, x)), y))) Traceback (most recent call last): ... NotImplementedError: unexpected level of nesting So y and x have unique fingerprints, but a and b do not. """ f = eq.free_symbols d = dict(list(zip(f, [[0]*4 + [defaultdict(int)] for fi in f]))) for a in eq.args: if a.is_Symbol: d[a][0] += 1 elif a.is_Not: d[a.args[0]][1] += 1 else: o = len(a.args), sum(isinstance(ai, Not) for ai in a.args) for ai in a.args: if ai.is_Symbol: d[ai][2] += 1 d[ai][-1][o] += 1 elif ai.is_Not: d[ai.args[0]][3] += 1 else: raise NotImplementedError('unexpected level of nesting') inv = defaultdict(list) for k, v in ordered(iter(d.items())): v[-1] = tuple(sorted([i + (j,) for i, j in v[-1].items()])) inv[tuple(v)].append(k) return inv def bool_map(bool1, bool2): """ Return the simplified version of *bool1*, and the mapping of variables that makes the two expressions *bool1* and *bool2* represent the same logical behaviour for some correspondence between the variables of each. If more than one mappings of this sort exist, one of them is returned. For example, ``And(x, y)`` is logically equivalent to ``And(a, b)`` for the mapping ``{x: a, y: b}`` or ``{x: b, y: a}``. If no such mapping exists, return ``False``. Examples ======== >>> from sympy import SOPform, bool_map, Or, And, Not, Xor >>> from sympy.abc import w, x, y, z, a, b, c, d >>> function1 = SOPform([x, z, y],[[1, 0, 1], [0, 0, 1]]) >>> function2 = SOPform([a, b, c],[[1, 0, 1], [1, 0, 0]]) >>> bool_map(function1, function2) (y & ~z, {y: a, z: b}) The results are not necessarily unique, but they are canonical. Here, ``(w, z)`` could be ``(a, d)`` or ``(d, a)``: >>> eq = Or(And(Not(y), w), And(Not(y), z), And(x, y)) >>> eq2 = Or(And(Not(c), a), And(Not(c), d), And(b, c)) >>> bool_map(eq, eq2) ((x & y) | (w & ~y) | (z & ~y), {w: a, x: b, y: c, z: d}) >>> eq = And(Xor(a, b), c, And(c,d)) >>> bool_map(eq, eq.subs(c, x)) (c & d & (a | b) & (~a | ~b), {a: a, b: b, c: d, d: x}) """ def match(function1, function2): """Return the mapping that equates variables between two simplified boolean expressions if possible. By "simplified" we mean that a function has been denested and is either an And (or an Or) whose arguments are either symbols (x), negated symbols (Not(x)), or Or (or an And) whose arguments are only symbols or negated symbols. For example, ``And(x, Not(y), Or(w, Not(z)))``. Basic.match is not robust enough (see issue 4835) so this is a workaround that is valid for simplified boolean expressions """ # do some quick checks if function1.__class__ != function2.__class__: return None # maybe simplification makes them the same? if len(function1.args) != len(function2.args): return None # maybe simplification makes them the same? if function1.is_Symbol: return {function1: function2} # get the fingerprint dictionaries f1 = _finger(function1) f2 = _finger(function2) # more quick checks if len(f1) != len(f2): return False # assemble the match dictionary if possible matchdict = {} for k in f1.keys(): if k not in f2: return False if len(f1[k]) != len(f2[k]): return False for i, x in enumerate(f1[k]): matchdict[x] = f2[k][i] return matchdict a = simplify_logic(bool1) b = simplify_logic(bool2) m = match(a, b) if m: return a, m return m def _apply_patternbased_simplification(rv, patterns, measure, dominatingvalue, replacementvalue=None, threeterm_patterns=None): """ Replace patterns of Relational Parameters ========== rv : Expr Boolean expression patterns : tuple Tuple of tuples, with (pattern to simplify, simplified pattern) with two terms. measure : function Simplification measure. dominatingvalue : Boolean or ``None`` The dominating value for the function of consideration. For example, for :py:class:`~.And` ``S.false`` is dominating. As soon as one expression is ``S.false`` in :py:class:`~.And`, the whole expression is ``S.false``. replacementvalue : Boolean or ``None``, optional The resulting value for the whole expression if one argument evaluates to ``dominatingvalue``. For example, for :py:class:`~.Nand` ``S.false`` is dominating, but in this case the resulting value is ``S.true``. Default is ``None``. If ``replacementvalue`` is ``None`` and ``dominatingvalue`` is not ``None``, ``replacementvalue = dominatingvalue``. threeterm_patterns : tuple, optional Tuple of tuples, with (pattern to simplify, simplified pattern) with three terms. """ from sympy.core.relational import Relational, _canonical if replacementvalue is None and dominatingvalue is not None: replacementvalue = dominatingvalue # Use replacement patterns for Relationals Rel, nonRel = sift(rv.args, lambda i: isinstance(i, Relational), binary=True) if len(Rel) <= 1: return rv Rel, nonRealRel = sift(Rel, lambda i: not any(s.is_real is False for s in i.free_symbols), binary=True) Rel = [i.canonical for i in Rel] if threeterm_patterns and len(Rel) >= 3: Rel = _apply_patternbased_threeterm_simplification(Rel, threeterm_patterns, rv.func, dominatingvalue, replacementvalue, measure) Rel = _apply_patternbased_twoterm_simplification(Rel, patterns, rv.func, dominatingvalue, replacementvalue, measure) rv = rv.func(*([_canonical(i) for i in ordered(Rel)] + nonRel + nonRealRel)) return rv def _apply_patternbased_twoterm_simplification(Rel, patterns, func, dominatingvalue, replacementvalue, measure): """ Apply pattern-based two-term simplification.""" from sympy.functions.elementary.miscellaneous import Min, Max from sympy.core.relational import Ge, Gt, _Inequality changed = True while changed and len(Rel) >= 2: changed = False # Use only < or <= Rel = [r.reversed if isinstance(r, (Ge, Gt)) else r for r in Rel] # Sort based on ordered Rel = list(ordered(Rel)) # Eq and Ne must be tested reversed as well rtmp = [(r, ) if isinstance(r, _Inequality) else (r, r.reversed) for r in Rel] # Create a list of possible replacements results = [] # Try all combinations of possibly reversed relational for ((i, pi), (j, pj)) in combinations(enumerate(rtmp), 2): for pattern, simp in patterns: res = [] for p1, p2 in product(pi, pj): # use SymPy matching oldexpr = Tuple(p1, p2) tmpres = oldexpr.match(pattern) if tmpres: res.append((tmpres, oldexpr)) if res: for tmpres, oldexpr in res: # we have a matching, compute replacement np = simp.xreplace(tmpres) if np == dominatingvalue: # if dominatingvalue, the whole expression # will be replacementvalue return [replacementvalue] # add replacement if not isinstance(np, ITE) and not np.has(Min, Max): # We only want to use ITE and Min/Max replacements if # they simplify to a relational costsaving = measure(func(*oldexpr.args)) - measure(np) if costsaving > 0: results.append((costsaving, ([i, j], np))) if results: # Sort results based on complexity results = list(reversed(sorted(results, key=lambda pair: pair[0]))) # Replace the one providing most simplification replacement = results[0][1] idx, newrel = replacement idx.sort() # Remove the old relationals for index in reversed(idx): del Rel[index] if dominatingvalue is None or newrel != Not(dominatingvalue): # Insert the new one (no need to insert a value that will # not affect the result) if newrel.func == func: for a in newrel.args: Rel.append(a) else: Rel.append(newrel) # We did change something so try again changed = True return Rel def _apply_patternbased_threeterm_simplification(Rel, patterns, func, dominatingvalue, replacementvalue, measure): """ Apply pattern-based three-term simplification.""" from sympy.functions.elementary.miscellaneous import Min, Max from sympy.core.relational import Le, Lt, _Inequality changed = True while changed and len(Rel) >= 3: changed = False # Use only > or >= Rel = [r.reversed if isinstance(r, (Le, Lt)) else r for r in Rel] # Sort based on ordered Rel = list(ordered(Rel)) # Create a list of possible replacements results = [] # Eq and Ne must be tested reversed as well rtmp = [(r, ) if isinstance(r, _Inequality) else (r, r.reversed) for r in Rel] # Try all combinations of possibly reversed relational for ((i, pi), (j, pj), (k, pk)) in permutations(enumerate(rtmp), 3): for pattern, simp in patterns: res = [] for p1, p2, p3 in product(pi, pj, pk): # use SymPy matching oldexpr = Tuple(p1, p2, p3) tmpres = oldexpr.match(pattern) if tmpres: res.append((tmpres, oldexpr)) if res: for tmpres, oldexpr in res: # we have a matching, compute replacement np = simp.xreplace(tmpres) if np == dominatingvalue: # if dominatingvalue, the whole expression # will be replacementvalue return [replacementvalue] # add replacement if not isinstance(np, ITE) and not np.has(Min, Max): # We only want to use ITE and Min/Max replacements if # they simplify to a relational costsaving = measure(func(*oldexpr.args)) - measure(np) if costsaving > 0: results.append((costsaving, ([i, j, k], np))) if results: # Sort results based on complexity results = list(reversed(sorted(results, key=lambda pair: pair[0]))) # Replace the one providing most simplification replacement = results[0][1] idx, newrel = replacement idx.sort() # Remove the old relationals for index in reversed(idx): del Rel[index] if dominatingvalue is None or newrel != Not(dominatingvalue): # Insert the new one (no need to insert a value that will # not affect the result) if newrel.func == func: for a in newrel.args: Rel.append(a) else: Rel.append(newrel) # We did change something so try again changed = True return Rel @cacheit def _simplify_patterns_and(): """ Two-term patterns for And.""" from sympy.core import Wild from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.miscellaneous import Min, Max a = Wild('a') b = Wild('b') c = Wild('c') # Relationals patterns should be in alphabetical order # (pattern1, pattern2, simplified) # Do not use Ge, Gt _matchers_and = ((Tuple(Eq(a, b), Lt(a, b)), false), #(Tuple(Eq(a, b), Lt(b, a)), S.false), #(Tuple(Le(b, a), Lt(a, b)), S.false), #(Tuple(Lt(b, a), Le(a, b)), S.false), (Tuple(Lt(b, a), Lt(a, b)), false), (Tuple(Eq(a, b), Le(b, a)), Eq(a, b)), #(Tuple(Eq(a, b), Le(a, b)), Eq(a, b)), #(Tuple(Le(b, a), Lt(b, a)), Gt(a, b)), (Tuple(Le(b, a), Le(a, b)), Eq(a, b)), #(Tuple(Le(b, a), Ne(a, b)), Gt(a, b)), #(Tuple(Lt(b, a), Ne(a, b)), Gt(a, b)), (Tuple(Le(a, b), Lt(a, b)), Lt(a, b)), (Tuple(Le(a, b), Ne(a, b)), Lt(a, b)), (Tuple(Lt(a, b), Ne(a, b)), Lt(a, b)), # Sign (Tuple(Eq(a, b), Eq(a, -b)), And(Eq(a, S.Zero), Eq(b, S.Zero))), # Min/Max/ITE (Tuple(Le(b, a), Le(c, a)), Ge(a, Max(b, c))), (Tuple(Le(b, a), Lt(c, a)), ITE(b > c, Ge(a, b), Gt(a, c))), (Tuple(Lt(b, a), Lt(c, a)), Gt(a, Max(b, c))), (Tuple(Le(a, b), Le(a, c)), Le(a, Min(b, c))), (Tuple(Le(a, b), Lt(a, c)), ITE(b < c, Le(a, b), Lt(a, c))), (Tuple(Lt(a, b), Lt(a, c)), Lt(a, Min(b, c))), (Tuple(Le(a, b), Le(c, a)), ITE(Eq(b, c), Eq(a, b), ITE(b < c, false, And(Le(a, b), Ge(a, c))))), (Tuple(Le(c, a), Le(a, b)), ITE(Eq(b, c), Eq(a, b), ITE(b < c, false, And(Le(a, b), Ge(a, c))))), (Tuple(Lt(a, b), Lt(c, a)), ITE(b < c, false, And(Lt(a, b), Gt(a, c)))), (Tuple(Lt(c, a), Lt(a, b)), ITE(b < c, false, And(Lt(a, b), Gt(a, c)))), (Tuple(Le(a, b), Lt(c, a)), ITE(b <= c, false, And(Le(a, b), Gt(a, c)))), (Tuple(Le(c, a), Lt(a, b)), ITE(b <= c, false, And(Lt(a, b), Ge(a, c)))), (Tuple(Eq(a, b), Eq(a, c)), ITE(Eq(b, c), Eq(a, b), false)), (Tuple(Lt(a, b), Lt(-b, a)), ITE(b > 0, Lt(Abs(a), b), false)), (Tuple(Le(a, b), Le(-b, a)), ITE(b >= 0, Le(Abs(a), b), false)), ) return _matchers_and @cacheit def _simplify_patterns_and3(): """ Three-term patterns for And.""" from sympy.core import Wild from sympy.core.relational import Eq, Ge, Gt a = Wild('a') b = Wild('b') c = Wild('c') # Relationals patterns should be in alphabetical order # (pattern1, pattern2, pattern3, simplified) # Do not use Le, Lt _matchers_and = ((Tuple(Ge(a, b), Ge(b, c), Gt(c, a)), false), (Tuple(Ge(a, b), Gt(b, c), Gt(c, a)), false), (Tuple(Gt(a, b), Gt(b, c), Gt(c, a)), false), # (Tuple(Ge(c, a), Gt(a, b), Gt(b, c)), S.false), # Lower bound relations # Commented out combinations that does not simplify (Tuple(Ge(a, b), Ge(a, c), Ge(b, c)), And(Ge(a, b), Ge(b, c))), (Tuple(Ge(a, b), Ge(a, c), Gt(b, c)), And(Ge(a, b), Gt(b, c))), # (Tuple(Ge(a, b), Gt(a, c), Ge(b, c)), And(Ge(a, b), Ge(b, c))), (Tuple(Ge(a, b), Gt(a, c), Gt(b, c)), And(Ge(a, b), Gt(b, c))), # (Tuple(Gt(a, b), Ge(a, c), Ge(b, c)), And(Gt(a, b), Ge(b, c))), (Tuple(Ge(a, c), Gt(a, b), Gt(b, c)), And(Gt(a, b), Gt(b, c))), (Tuple(Ge(b, c), Gt(a, b), Gt(a, c)), And(Gt(a, b), Ge(b, c))), (Tuple(Gt(a, b), Gt(a, c), Gt(b, c)), And(Gt(a, b), Gt(b, c))), # Upper bound relations # Commented out combinations that does not simplify (Tuple(Ge(b, a), Ge(c, a), Ge(b, c)), And(Ge(c, a), Ge(b, c))), (Tuple(Ge(b, a), Ge(c, a), Gt(b, c)), And(Ge(c, a), Gt(b, c))), # (Tuple(Ge(b, a), Gt(c, a), Ge(b, c)), And(Gt(c, a), Ge(b, c))), (Tuple(Ge(b, a), Gt(c, a), Gt(b, c)), And(Gt(c, a), Gt(b, c))), # (Tuple(Gt(b, a), Ge(c, a), Ge(b, c)), And(Ge(c, a), Ge(b, c))), (Tuple(Ge(c, a), Gt(b, a), Gt(b, c)), And(Ge(c, a), Gt(b, c))), (Tuple(Ge(b, c), Gt(b, a), Gt(c, a)), And(Gt(c, a), Ge(b, c))), (Tuple(Gt(b, a), Gt(c, a), Gt(b, c)), And(Gt(c, a), Gt(b, c))), # Circular relation (Tuple(Ge(a, b), Ge(b, c), Ge(c, a)), And(Eq(a, b), Eq(b, c))), ) return _matchers_and @cacheit def _simplify_patterns_or(): """ Two-term patterns for Or.""" from sympy.core import Wild from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.miscellaneous import Min, Max a = Wild('a') b = Wild('b') c = Wild('c') # Relationals patterns should be in alphabetical order # (pattern1, pattern2, simplified) # Do not use Ge, Gt _matchers_or = ((Tuple(Le(b, a), Le(a, b)), true), #(Tuple(Le(b, a), Lt(a, b)), true), (Tuple(Le(b, a), Ne(a, b)), true), #(Tuple(Le(a, b), Lt(b, a)), true), #(Tuple(Le(a, b), Ne(a, b)), true), #(Tuple(Eq(a, b), Le(b, a)), Ge(a, b)), #(Tuple(Eq(a, b), Lt(b, a)), Ge(a, b)), (Tuple(Eq(a, b), Le(a, b)), Le(a, b)), (Tuple(Eq(a, b), Lt(a, b)), Le(a, b)), #(Tuple(Le(b, a), Lt(b, a)), Ge(a, b)), (Tuple(Lt(b, a), Lt(a, b)), Ne(a, b)), (Tuple(Lt(b, a), Ne(a, b)), Ne(a, b)), (Tuple(Le(a, b), Lt(a, b)), Le(a, b)), #(Tuple(Lt(a, b), Ne(a, b)), Ne(a, b)), (Tuple(Eq(a, b), Ne(a, c)), ITE(Eq(b, c), true, Ne(a, c))), (Tuple(Ne(a, b), Ne(a, c)), ITE(Eq(b, c), Ne(a, b), true)), # Min/Max/ITE (Tuple(Le(b, a), Le(c, a)), Ge(a, Min(b, c))), #(Tuple(Ge(b, a), Ge(c, a)), Ge(Min(b, c), a)), (Tuple(Le(b, a), Lt(c, a)), ITE(b > c, Lt(c, a), Le(b, a))), (Tuple(Lt(b, a), Lt(c, a)), Gt(a, Min(b, c))), #(Tuple(Gt(b, a), Gt(c, a)), Gt(Min(b, c), a)), (Tuple(Le(a, b), Le(a, c)), Le(a, Max(b, c))), #(Tuple(Le(b, a), Le(c, a)), Le(Max(b, c), a)), (Tuple(Le(a, b), Lt(a, c)), ITE(b >= c, Le(a, b), Lt(a, c))), (Tuple(Lt(a, b), Lt(a, c)), Lt(a, Max(b, c))), #(Tuple(Lt(b, a), Lt(c, a)), Lt(Max(b, c), a)), (Tuple(Le(a, b), Le(c, a)), ITE(b >= c, true, Or(Le(a, b), Ge(a, c)))), (Tuple(Le(c, a), Le(a, b)), ITE(b >= c, true, Or(Le(a, b), Ge(a, c)))), (Tuple(Lt(a, b), Lt(c, a)), ITE(b > c, true, Or(Lt(a, b), Gt(a, c)))), (Tuple(Lt(c, a), Lt(a, b)), ITE(b > c, true, Or(Lt(a, b), Gt(a, c)))), (Tuple(Le(a, b), Lt(c, a)), ITE(b >= c, true, Or(Le(a, b), Gt(a, c)))), (Tuple(Le(c, a), Lt(a, b)), ITE(b >= c, true, Or(Lt(a, b), Ge(a, c)))), (Tuple(Lt(b, a), Lt(a, -b)), ITE(b >= 0, Gt(Abs(a), b), true)), (Tuple(Le(b, a), Le(a, -b)), ITE(b > 0, Ge(Abs(a), b), true)), ) return _matchers_or @cacheit def _simplify_patterns_xor(): """ Two-term patterns for Xor.""" from sympy.functions.elementary.miscellaneous import Min, Max from sympy.core import Wild from sympy.core.relational import Eq, Ne, Ge, Gt, Le, Lt a = Wild('a') b = Wild('b') c = Wild('c') # Relationals patterns should be in alphabetical order # (pattern1, pattern2, simplified) # Do not use Ge, Gt _matchers_xor = (#(Tuple(Le(b, a), Lt(a, b)), true), #(Tuple(Lt(b, a), Le(a, b)), true), #(Tuple(Eq(a, b), Le(b, a)), Gt(a, b)), #(Tuple(Eq(a, b), Lt(b, a)), Ge(a, b)), (Tuple(Eq(a, b), Le(a, b)), Lt(a, b)), (Tuple(Eq(a, b), Lt(a, b)), Le(a, b)), (Tuple(Le(a, b), Lt(a, b)), Eq(a, b)), (Tuple(Le(a, b), Le(b, a)), Ne(a, b)), (Tuple(Le(b, a), Ne(a, b)), Le(a, b)), # (Tuple(Lt(b, a), Lt(a, b)), Ne(a, b)), (Tuple(Lt(b, a), Ne(a, b)), Lt(a, b)), # (Tuple(Le(a, b), Lt(a, b)), Eq(a, b)), # (Tuple(Le(a, b), Ne(a, b)), Ge(a, b)), # (Tuple(Lt(a, b), Ne(a, b)), Gt(a, b)), # Min/Max/ITE (Tuple(Le(b, a), Le(c, a)), And(Ge(a, Min(b, c)), Lt(a, Max(b, c)))), (Tuple(Le(b, a), Lt(c, a)), ITE(b > c, And(Gt(a, c), Lt(a, b)), And(Ge(a, b), Le(a, c)))), (Tuple(Lt(b, a), Lt(c, a)), And(Gt(a, Min(b, c)), Le(a, Max(b, c)))), (Tuple(Le(a, b), Le(a, c)), And(Le(a, Max(b, c)), Gt(a, Min(b, c)))), (Tuple(Le(a, b), Lt(a, c)), ITE(b < c, And(Lt(a, c), Gt(a, b)), And(Le(a, b), Ge(a, c)))), (Tuple(Lt(a, b), Lt(a, c)), And(Lt(a, Max(b, c)), Ge(a, Min(b, c)))), ) return _matchers_xor def simplify_univariate(expr): """return a simplified version of univariate boolean expression, else ``expr``""" from sympy.functions.elementary.piecewise import Piecewise from sympy.core.relational import Eq, Ne if not isinstance(expr, BooleanFunction): return expr if expr.atoms(Eq, Ne): return expr c = expr free = c.free_symbols if len(free) != 1: return c x = free.pop() ok, i = Piecewise((0, c), evaluate=False )._intervals(x, err_on_Eq=True) if not ok: return c if not i: return false args = [] for a, b, _, _ in i: if a is S.NegativeInfinity: if b is S.Infinity: c = true else: if c.subs(x, b) == True: c = (x <= b) else: c = (x < b) else: incl_a = (c.subs(x, a) == True) incl_b = (c.subs(x, b) == True) if incl_a and incl_b: if b.is_infinite: c = (x >= a) else: c = And(a <= x, x <= b) elif incl_a: c = And(a <= x, x < b) elif incl_b: if b.is_infinite: c = (x > a) else: c = And(a < x, x <= b) else: c = And(a < x, x < b) args.append(c) return Or(*args) # Classes corresponding to logic gates # Used in gateinputcount method BooleanGates = (And, Or, Xor, Nand, Nor, Not, Xnor, ITE) def gateinputcount(expr): """ Return the total number of inputs for the logic gates realizing the Boolean expression. Returns ======= int Number of gate inputs Note ==== Not all Boolean functions count as gate here, only those that are considered to be standard gates. These are: :py:class:`~.And`, :py:class:`~.Or`, :py:class:`~.Xor`, :py:class:`~.Not`, and :py:class:`~.ITE` (multiplexer). :py:class:`~.Nand`, :py:class:`~.Nor`, and :py:class:`~.Xnor` will be evaluated to ``Not(And())`` etc. Examples ======== >>> from sympy.logic import And, Or, Nand, Not, gateinputcount >>> from sympy.abc import x, y, z >>> expr = And(x, y) >>> gateinputcount(expr) 2 >>> gateinputcount(Or(expr, z)) 4 Note that ``Nand`` is automatically evaluated to ``Not(And())`` so >>> gateinputcount(Nand(x, y, z)) 4 >>> gateinputcount(Not(And(x, y, z))) 4 Although this can be avoided by using ``evaluate=False`` >>> gateinputcount(Nand(x, y, z, evaluate=False)) 3 Also note that a comparison will count as a Boolean variable: >>> gateinputcount(And(x > z, y >= 2)) 2 As will a symbol: >>> gateinputcount(x) 0 """ if not isinstance(expr, Boolean): raise TypeError("Expression must be Boolean") if isinstance(expr, BooleanGates): return len(expr.args) + sum(gateinputcount(x) for x in expr.args) return 0
f8e0ec96c4e9876e6d24979f787851dd2438eb60970fa76ac045598b854fec20
import copy from sympy.core import S from sympy.core.function import expand_mul from sympy.functions.elementary.miscellaneous import Min, sqrt from sympy.functions.elementary.complexes import sign from .common import NonSquareMatrixError, NonPositiveDefiniteMatrixError from .utilities import _get_intermediate_simp, _iszero from .determinant import _find_reasonable_pivot_naive def _rank_decomposition(M, iszerofunc=_iszero, simplify=False): r"""Returns a pair of matrices (`C`, `F`) with matching rank such that `A = C F`. Parameters ========== iszerofunc : Function, optional A function used for detecting whether an element can act as a pivot. ``lambda x: x.is_zero`` is used by default. simplify : Bool or Function, optional A function used to simplify elements when looking for a pivot. By default SymPy's ``simplify`` is used. Returns ======= (C, F) : Matrices `C` and `F` are full-rank matrices with rank as same as `A`, whose product gives `A`. See Notes for additional mathematical details. Examples ======== >>> from sympy import Matrix >>> A = Matrix([ ... [1, 3, 1, 4], ... [2, 7, 3, 9], ... [1, 5, 3, 1], ... [1, 2, 0, 8] ... ]) >>> C, F = A.rank_decomposition() >>> C Matrix([ [1, 3, 4], [2, 7, 9], [1, 5, 1], [1, 2, 8]]) >>> F Matrix([ [1, 0, -2, 0], [0, 1, 1, 0], [0, 0, 0, 1]]) >>> C * F == A True Notes ===== Obtaining `F`, an RREF of `A`, is equivalent to creating a product .. math:: E_n E_{n-1} ... E_1 A = F where `E_n, E_{n-1}, \dots, E_1` are the elimination matrices or permutation matrices equivalent to each row-reduction step. The inverse of the same product of elimination matrices gives `C`: .. math:: C = \left(E_n E_{n-1} \dots E_1\right)^{-1} It is not necessary, however, to actually compute the inverse: the columns of `C` are those from the original matrix with the same column indices as the indices of the pivot columns of `F`. References ========== .. [1] https://en.wikipedia.org/wiki/Rank_factorization .. [2] Piziak, R.; Odell, P. L. (1 June 1999). "Full Rank Factorization of Matrices". Mathematics Magazine. 72 (3): 193. doi:10.2307/2690882 See Also ======== sympy.matrices.matrices.MatrixReductions.rref """ F, pivot_cols = M.rref(simplify=simplify, iszerofunc=iszerofunc, pivots=True) rank = len(pivot_cols) C = M.extract(range(M.rows), pivot_cols) F = F[:rank, :] return C, F def _liupc(M): """Liu's algorithm, for pre-determination of the Elimination Tree of the given matrix, used in row-based symbolic Cholesky factorization. Examples ======== >>> from sympy import SparseMatrix >>> S = SparseMatrix([ ... [1, 0, 3, 2], ... [0, 0, 1, 0], ... [4, 0, 0, 5], ... [0, 6, 7, 0]]) >>> S.liupc() ([[0], [], [0], [1, 2]], [4, 3, 4, 4]) References ========== .. [1] Symbolic Sparse Cholesky Factorization using Elimination Trees, Jeroen Van Grondelle (1999) http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.39.7582 """ # Algorithm 2.4, p 17 of reference # get the indices of the elements that are non-zero on or below diag R = [[] for r in range(M.rows)] for r, c, _ in M.row_list(): if c <= r: R[r].append(c) inf = len(R) # nothing will be this large parent = [inf]*M.rows virtual = [inf]*M.rows for r in range(M.rows): for c in R[r][:-1]: while virtual[c] < r: t = virtual[c] virtual[c] = r c = t if virtual[c] == inf: parent[c] = virtual[c] = r return R, parent def _row_structure_symbolic_cholesky(M): """Symbolic cholesky factorization, for pre-determination of the non-zero structure of the Cholesky factororization. Examples ======== >>> from sympy import SparseMatrix >>> S = SparseMatrix([ ... [1, 0, 3, 2], ... [0, 0, 1, 0], ... [4, 0, 0, 5], ... [0, 6, 7, 0]]) >>> S.row_structure_symbolic_cholesky() [[0], [], [0], [1, 2]] References ========== .. [1] Symbolic Sparse Cholesky Factorization using Elimination Trees, Jeroen Van Grondelle (1999) http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.39.7582 """ R, parent = M.liupc() inf = len(R) # this acts as infinity Lrow = copy.deepcopy(R) for k in range(M.rows): for j in R[k]: while j != inf and j != k: Lrow[k].append(j) j = parent[j] Lrow[k] = list(sorted(set(Lrow[k]))) return Lrow def _cholesky(M, hermitian=True): """Returns the Cholesky-type decomposition L of a matrix A such that L * L.H == A if hermitian flag is True, or L * L.T == A if hermitian is False. A must be a Hermitian positive-definite matrix if hermitian is True, or a symmetric matrix if it is False. Examples ======== >>> from sympy import Matrix >>> A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) >>> A.cholesky() Matrix([ [ 5, 0, 0], [ 3, 3, 0], [-1, 1, 3]]) >>> A.cholesky() * A.cholesky().T Matrix([ [25, 15, -5], [15, 18, 0], [-5, 0, 11]]) The matrix can have complex entries: >>> from sympy import I >>> A = Matrix(((9, 3*I), (-3*I, 5))) >>> A.cholesky() Matrix([ [ 3, 0], [-I, 2]]) >>> A.cholesky() * A.cholesky().H Matrix([ [ 9, 3*I], [-3*I, 5]]) Non-hermitian Cholesky-type decomposition may be useful when the matrix is not positive-definite. >>> A = Matrix([[1, 2], [2, 1]]) >>> L = A.cholesky(hermitian=False) >>> L Matrix([ [1, 0], [2, sqrt(3)*I]]) >>> L*L.T == A True See Also ======== sympy.matrices.dense.DenseMatrix.LDLdecomposition sympy.matrices.matrices.MatrixBase.LUdecomposition QRdecomposition """ from .dense import MutableDenseMatrix if not M.is_square: raise NonSquareMatrixError("Matrix must be square.") if hermitian and not M.is_hermitian: raise ValueError("Matrix must be Hermitian.") if not hermitian and not M.is_symmetric(): raise ValueError("Matrix must be symmetric.") L = MutableDenseMatrix.zeros(M.rows, M.rows) if hermitian: for i in range(M.rows): for j in range(i): L[i, j] = ((1 / L[j, j])*(M[i, j] - sum(L[i, k]*L[j, k].conjugate() for k in range(j)))) Lii2 = (M[i, i] - sum(L[i, k]*L[i, k].conjugate() for k in range(i))) if Lii2.is_positive is False: raise NonPositiveDefiniteMatrixError( "Matrix must be positive-definite") L[i, i] = sqrt(Lii2) else: for i in range(M.rows): for j in range(i): L[i, j] = ((1 / L[j, j])*(M[i, j] - sum(L[i, k]*L[j, k] for k in range(j)))) L[i, i] = sqrt(M[i, i] - sum(L[i, k]**2 for k in range(i))) return M._new(L) def _cholesky_sparse(M, hermitian=True): """ Returns the Cholesky decomposition L of a matrix A such that L * L.T = A A must be a square, symmetric, positive-definite and non-singular matrix Examples ======== >>> from sympy import SparseMatrix >>> A = SparseMatrix(((25,15,-5),(15,18,0),(-5,0,11))) >>> A.cholesky() Matrix([ [ 5, 0, 0], [ 3, 3, 0], [-1, 1, 3]]) >>> A.cholesky() * A.cholesky().T == A True The matrix can have complex entries: >>> from sympy import I >>> A = SparseMatrix(((9, 3*I), (-3*I, 5))) >>> A.cholesky() Matrix([ [ 3, 0], [-I, 2]]) >>> A.cholesky() * A.cholesky().H Matrix([ [ 9, 3*I], [-3*I, 5]]) Non-hermitian Cholesky-type decomposition may be useful when the matrix is not positive-definite. >>> A = SparseMatrix([[1, 2], [2, 1]]) >>> L = A.cholesky(hermitian=False) >>> L Matrix([ [1, 0], [2, sqrt(3)*I]]) >>> L*L.T == A True See Also ======== sympy.matrices.sparse.SparseMatrix.LDLdecomposition sympy.matrices.matrices.MatrixBase.LUdecomposition QRdecomposition """ from .dense import MutableDenseMatrix if not M.is_square: raise NonSquareMatrixError("Matrix must be square.") if hermitian and not M.is_hermitian: raise ValueError("Matrix must be Hermitian.") if not hermitian and not M.is_symmetric(): raise ValueError("Matrix must be symmetric.") dps = _get_intermediate_simp(expand_mul, expand_mul) Crowstruc = M.row_structure_symbolic_cholesky() C = MutableDenseMatrix.zeros(M.rows) for i in range(len(Crowstruc)): for j in Crowstruc[i]: if i != j: C[i, j] = M[i, j] summ = 0 for p1 in Crowstruc[i]: if p1 < j: for p2 in Crowstruc[j]: if p2 < j: if p1 == p2: if hermitian: summ += C[i, p1]*C[j, p1].conjugate() else: summ += C[i, p1]*C[j, p1] else: break else: break C[i, j] = dps((C[i, j] - summ) / C[j, j]) else: # i == j C[j, j] = M[j, j] summ = 0 for k in Crowstruc[j]: if k < j: if hermitian: summ += C[j, k]*C[j, k].conjugate() else: summ += C[j, k]**2 else: break Cjj2 = dps(C[j, j] - summ) if hermitian and Cjj2.is_positive is False: raise NonPositiveDefiniteMatrixError( "Matrix must be positive-definite") C[j, j] = sqrt(Cjj2) return M._new(C) def _LDLdecomposition(M, hermitian=True): """Returns the LDL Decomposition (L, D) of matrix A, such that L * D * L.H == A if hermitian flag is True, or L * D * L.T == A if hermitian is False. This method eliminates the use of square root. Further this ensures that all the diagonal entries of L are 1. A must be a Hermitian positive-definite matrix if hermitian is True, or a symmetric matrix otherwise. Examples ======== >>> from sympy import Matrix, eye >>> A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) >>> L, D = A.LDLdecomposition() >>> L Matrix([ [ 1, 0, 0], [ 3/5, 1, 0], [-1/5, 1/3, 1]]) >>> D Matrix([ [25, 0, 0], [ 0, 9, 0], [ 0, 0, 9]]) >>> L * D * L.T * A.inv() == eye(A.rows) True The matrix can have complex entries: >>> from sympy import I >>> A = Matrix(((9, 3*I), (-3*I, 5))) >>> L, D = A.LDLdecomposition() >>> L Matrix([ [ 1, 0], [-I/3, 1]]) >>> D Matrix([ [9, 0], [0, 4]]) >>> L*D*L.H == A True See Also ======== sympy.matrices.dense.DenseMatrix.cholesky sympy.matrices.matrices.MatrixBase.LUdecomposition QRdecomposition """ from .dense import MutableDenseMatrix if not M.is_square: raise NonSquareMatrixError("Matrix must be square.") if hermitian and not M.is_hermitian: raise ValueError("Matrix must be Hermitian.") if not hermitian and not M.is_symmetric(): raise ValueError("Matrix must be symmetric.") D = MutableDenseMatrix.zeros(M.rows, M.rows) L = MutableDenseMatrix.eye(M.rows) if hermitian: for i in range(M.rows): for j in range(i): L[i, j] = (1 / D[j, j])*(M[i, j] - sum( L[i, k]*L[j, k].conjugate()*D[k, k] for k in range(j))) D[i, i] = (M[i, i] - sum(L[i, k]*L[i, k].conjugate()*D[k, k] for k in range(i))) if D[i, i].is_positive is False: raise NonPositiveDefiniteMatrixError( "Matrix must be positive-definite") else: for i in range(M.rows): for j in range(i): L[i, j] = (1 / D[j, j])*(M[i, j] - sum( L[i, k]*L[j, k]*D[k, k] for k in range(j))) D[i, i] = M[i, i] - sum(L[i, k]**2*D[k, k] for k in range(i)) return M._new(L), M._new(D) def _LDLdecomposition_sparse(M, hermitian=True): """ Returns the LDL Decomposition (matrices ``L`` and ``D``) of matrix ``A``, such that ``L * D * L.T == A``. ``A`` must be a square, symmetric, positive-definite and non-singular. This method eliminates the use of square root and ensures that all the diagonal entries of L are 1. Examples ======== >>> from sympy import SparseMatrix >>> A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11))) >>> L, D = A.LDLdecomposition() >>> L Matrix([ [ 1, 0, 0], [ 3/5, 1, 0], [-1/5, 1/3, 1]]) >>> D Matrix([ [25, 0, 0], [ 0, 9, 0], [ 0, 0, 9]]) >>> L * D * L.T == A True """ from .dense import MutableDenseMatrix if not M.is_square: raise NonSquareMatrixError("Matrix must be square.") if hermitian and not M.is_hermitian: raise ValueError("Matrix must be Hermitian.") if not hermitian and not M.is_symmetric(): raise ValueError("Matrix must be symmetric.") dps = _get_intermediate_simp(expand_mul, expand_mul) Lrowstruc = M.row_structure_symbolic_cholesky() L = MutableDenseMatrix.eye(M.rows) D = MutableDenseMatrix.zeros(M.rows, M.cols) for i in range(len(Lrowstruc)): for j in Lrowstruc[i]: if i != j: L[i, j] = M[i, j] summ = 0 for p1 in Lrowstruc[i]: if p1 < j: for p2 in Lrowstruc[j]: if p2 < j: if p1 == p2: if hermitian: summ += L[i, p1]*L[j, p1].conjugate()*D[p1, p1] else: summ += L[i, p1]*L[j, p1]*D[p1, p1] else: break else: break L[i, j] = dps((L[i, j] - summ) / D[j, j]) else: # i == j D[i, i] = M[i, i] summ = 0 for k in Lrowstruc[i]: if k < i: if hermitian: summ += L[i, k]*L[i, k].conjugate()*D[k, k] else: summ += L[i, k]**2*D[k, k] else: break D[i, i] = dps(D[i, i] - summ) if hermitian and D[i, i].is_positive is False: raise NonPositiveDefiniteMatrixError( "Matrix must be positive-definite") return M._new(L), M._new(D) def _LUdecomposition(M, iszerofunc=_iszero, simpfunc=None, rankcheck=False): """Returns (L, U, perm) where L is a lower triangular matrix with unit diagonal, U is an upper triangular matrix, and perm is a list of row swap index pairs. If A is the original matrix, then ``A = (L*U).permuteBkwd(perm)``, and the row permutation matrix P such that $P A = L U$ can be computed by ``P = eye(A.rows).permuteFwd(perm)``. See documentation for LUCombined for details about the keyword argument rankcheck, iszerofunc, and simpfunc. Parameters ========== rankcheck : bool, optional Determines if this function should detect the rank deficiency of the matrixis and should raise a ``ValueError``. iszerofunc : function, optional A function which determines if a given expression is zero. The function should be a callable that takes a single SymPy expression and returns a 3-valued boolean value ``True``, ``False``, or ``None``. It is internally used by the pivot searching algorithm. See the notes section for a more information about the pivot searching algorithm. simpfunc : function or None, optional A function that simplifies the input. If this is specified as a function, this function should be a callable that takes a single SymPy expression and returns an another SymPy expression that is algebraically equivalent. If ``None``, it indicates that the pivot search algorithm should not attempt to simplify any candidate pivots. It is internally used by the pivot searching algorithm. See the notes section for a more information about the pivot searching algorithm. Examples ======== >>> from sympy import Matrix >>> a = Matrix([[4, 3], [6, 3]]) >>> L, U, _ = a.LUdecomposition() >>> L Matrix([ [ 1, 0], [3/2, 1]]) >>> U Matrix([ [4, 3], [0, -3/2]]) See Also ======== sympy.matrices.dense.DenseMatrix.cholesky sympy.matrices.dense.DenseMatrix.LDLdecomposition QRdecomposition LUdecomposition_Simple LUdecompositionFF LUsolve """ combined, p = M.LUdecomposition_Simple(iszerofunc=iszerofunc, simpfunc=simpfunc, rankcheck=rankcheck) # L is lower triangular ``M.rows x M.rows`` # U is upper triangular ``M.rows x M.cols`` # L has unit diagonal. For each column in combined, the subcolumn # below the diagonal of combined is shared by L. # If L has more columns than combined, then the remaining subcolumns # below the diagonal of L are zero. # The upper triangular portion of L and combined are equal. def entry_L(i, j): if i < j: # Super diagonal entry return M.zero elif i == j: return M.one elif j < combined.cols: return combined[i, j] # Subdiagonal entry of L with no corresponding # entry in combined return M.zero def entry_U(i, j): return M.zero if i > j else combined[i, j] L = M._new(combined.rows, combined.rows, entry_L) U = M._new(combined.rows, combined.cols, entry_U) return L, U, p def _LUdecomposition_Simple(M, iszerofunc=_iszero, simpfunc=None, rankcheck=False): r"""Compute the PLU decomposition of the matrix. Parameters ========== rankcheck : bool, optional Determines if this function should detect the rank deficiency of the matrixis and should raise a ``ValueError``. iszerofunc : function, optional A function which determines if a given expression is zero. The function should be a callable that takes a single SymPy expression and returns a 3-valued boolean value ``True``, ``False``, or ``None``. It is internally used by the pivot searching algorithm. See the notes section for a more information about the pivot searching algorithm. simpfunc : function or None, optional A function that simplifies the input. If this is specified as a function, this function should be a callable that takes a single SymPy expression and returns an another SymPy expression that is algebraically equivalent. If ``None``, it indicates that the pivot search algorithm should not attempt to simplify any candidate pivots. It is internally used by the pivot searching algorithm. See the notes section for a more information about the pivot searching algorithm. Returns ======= (lu, row_swaps) : (Matrix, list) If the original matrix is a $m, n$ matrix: *lu* is a $m, n$ matrix, which contains result of the decomposition in a compressed form. See the notes section to see how the matrix is compressed. *row_swaps* is a $m$-element list where each element is a pair of row exchange indices. ``A = (L*U).permute_backward(perm)``, and the row permutation matrix $P$ from the formula $P A = L U$ can be computed by ``P=eye(A.row).permute_forward(perm)``. Raises ====== ValueError Raised if ``rankcheck=True`` and the matrix is found to be rank deficient during the computation. Notes ===== About the PLU decomposition: PLU decomposition is a generalization of a LU decomposition which can be extended for rank-deficient matrices. It can further be generalized for non-square matrices, and this is the notation that SymPy is using. PLU decomposition is a decomposition of a $m, n$ matrix $A$ in the form of $P A = L U$ where * $L$ is a $m, m$ lower triangular matrix with unit diagonal entries. * $U$ is a $m, n$ upper triangular matrix. * $P$ is a $m, m$ permutation matrix. So, for a square matrix, the decomposition would look like: .. math:: L = \begin{bmatrix} 1 & 0 & 0 & \cdots & 0 \\ L_{1, 0} & 1 & 0 & \cdots & 0 \\ L_{2, 0} & L_{2, 1} & 1 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots & 1 \end{bmatrix} .. math:: U = \begin{bmatrix} U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\ 0 & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\ 0 & 0 & U_{2, 2} & \cdots & U_{2, n-1} \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \cdots & U_{n-1, n-1} \end{bmatrix} And for a matrix with more rows than the columns, the decomposition would look like: .. math:: L = \begin{bmatrix} 1 & 0 & 0 & \cdots & 0 & 0 & \cdots & 0 \\ L_{1, 0} & 1 & 0 & \cdots & 0 & 0 & \cdots & 0 \\ L_{2, 0} & L_{2, 1} & 1 & \cdots & 0 & 0 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \ddots & \vdots \\ L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots & 1 & 0 & \cdots & 0 \\ L_{n, 0} & L_{n, 1} & L_{n, 2} & \cdots & L_{n, n-1} & 1 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots & \vdots & \ddots & \vdots \\ L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots & L_{m-1, n-1} & 0 & \cdots & 1 \\ \end{bmatrix} .. math:: U = \begin{bmatrix} U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\ 0 & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\ 0 & 0 & U_{2, 2} & \cdots & U_{2, n-1} \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \cdots & U_{n-1, n-1} \\ 0 & 0 & 0 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \cdots & 0 \end{bmatrix} Finally, for a matrix with more columns than the rows, the decomposition would look like: .. math:: L = \begin{bmatrix} 1 & 0 & 0 & \cdots & 0 \\ L_{1, 0} & 1 & 0 & \cdots & 0 \\ L_{2, 0} & L_{2, 1} & 1 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots & 1 \end{bmatrix} .. math:: U = \begin{bmatrix} U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, m-1} & \cdots & U_{0, n-1} \\ 0 & U_{1, 1} & U_{1, 2} & \cdots & U_{1, m-1} & \cdots & U_{1, n-1} \\ 0 & 0 & U_{2, 2} & \cdots & U_{2, m-1} & \cdots & U_{2, n-1} \\ \vdots & \vdots & \vdots & \ddots & \vdots & \cdots & \vdots \\ 0 & 0 & 0 & \cdots & U_{m-1, m-1} & \cdots & U_{m-1, n-1} \\ \end{bmatrix} About the compressed LU storage: The results of the decomposition are often stored in compressed forms rather than returning $L$ and $U$ matrices individually. It may be less intiuitive, but it is commonly used for a lot of numeric libraries because of the efficiency. The storage matrix is defined as following for this specific method: * The subdiagonal elements of $L$ are stored in the subdiagonal portion of $LU$, that is $LU_{i, j} = L_{i, j}$ whenever $i > j$. * The elements on the diagonal of $L$ are all 1, and are not explicitly stored. * $U$ is stored in the upper triangular portion of $LU$, that is $LU_{i, j} = U_{i, j}$ whenever $i <= j$. * For a case of $m > n$, the right side of the $L$ matrix is trivial to store. * For a case of $m < n$, the below side of the $U$ matrix is trivial to store. So, for a square matrix, the compressed output matrix would be: .. math:: LU = \begin{bmatrix} U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\ L_{1, 0} & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\ L_{2, 0} & L_{2, 1} & U_{2, 2} & \cdots & U_{2, n-1} \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots & U_{n-1, n-1} \end{bmatrix} For a matrix with more rows than the columns, the compressed output matrix would be: .. math:: LU = \begin{bmatrix} U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, n-1} \\ L_{1, 0} & U_{1, 1} & U_{1, 2} & \cdots & U_{1, n-1} \\ L_{2, 0} & L_{2, 1} & U_{2, 2} & \cdots & U_{2, n-1} \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ L_{n-1, 0} & L_{n-1, 1} & L_{n-1, 2} & \cdots & U_{n-1, n-1} \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots & L_{m-1, n-1} \\ \end{bmatrix} For a matrix with more columns than the rows, the compressed output matrix would be: .. math:: LU = \begin{bmatrix} U_{0, 0} & U_{0, 1} & U_{0, 2} & \cdots & U_{0, m-1} & \cdots & U_{0, n-1} \\ L_{1, 0} & U_{1, 1} & U_{1, 2} & \cdots & U_{1, m-1} & \cdots & U_{1, n-1} \\ L_{2, 0} & L_{2, 1} & U_{2, 2} & \cdots & U_{2, m-1} & \cdots & U_{2, n-1} \\ \vdots & \vdots & \vdots & \ddots & \vdots & \cdots & \vdots \\ L_{m-1, 0} & L_{m-1, 1} & L_{m-1, 2} & \cdots & U_{m-1, m-1} & \cdots & U_{m-1, n-1} \\ \end{bmatrix} About the pivot searching algorithm: When a matrix contains symbolic entries, the pivot search algorithm differs from the case where every entry can be categorized as zero or nonzero. The algorithm searches column by column through the submatrix whose top left entry coincides with the pivot position. If it exists, the pivot is the first entry in the current search column that iszerofunc guarantees is nonzero. If no such candidate exists, then each candidate pivot is simplified if simpfunc is not None. The search is repeated, with the difference that a candidate may be the pivot if ``iszerofunc()`` cannot guarantee that it is nonzero. In the second search the pivot is the first candidate that iszerofunc can guarantee is nonzero. If no such candidate exists, then the pivot is the first candidate for which iszerofunc returns None. If no such candidate exists, then the search is repeated in the next column to the right. The pivot search algorithm differs from the one in ``rref()``, which relies on ``_find_reasonable_pivot()``. Future versions of ``LUdecomposition_simple()`` may use ``_find_reasonable_pivot()``. See Also ======== sympy.matrices.matrices.MatrixBase.LUdecomposition LUdecompositionFF LUsolve """ if rankcheck: # https://github.com/sympy/sympy/issues/9796 pass if S.Zero in M.shape: # Define LU decomposition of a matrix with no entries as a matrix # of the same dimensions with all zero entries. return M.zeros(M.rows, M.cols), [] dps = _get_intermediate_simp() lu = M.as_mutable() row_swaps = [] pivot_col = 0 for pivot_row in range(0, lu.rows - 1): # Search for pivot. Prefer entry that iszeropivot determines # is nonzero, over entry that iszeropivot cannot guarantee # is zero. # XXX ``_find_reasonable_pivot`` uses slow zero testing. Blocked by bug #10279 # Future versions of LUdecomposition_simple can pass iszerofunc and simpfunc # to _find_reasonable_pivot(). # In pass 3 of _find_reasonable_pivot(), the predicate in ``if x.equals(S.Zero):`` # calls sympy.simplify(), and not the simplification function passed in via # the keyword argument simpfunc. iszeropivot = True while pivot_col != M.cols and iszeropivot: sub_col = (lu[r, pivot_col] for r in range(pivot_row, M.rows)) pivot_row_offset, pivot_value, is_assumed_non_zero, ind_simplified_pairs =\ _find_reasonable_pivot_naive(sub_col, iszerofunc, simpfunc) iszeropivot = pivot_value is None if iszeropivot: # All candidate pivots in this column are zero. # Proceed to next column. pivot_col += 1 if rankcheck and pivot_col != pivot_row: # All entries including and below the pivot position are # zero, which indicates that the rank of the matrix is # strictly less than min(num rows, num cols) # Mimic behavior of previous implementation, by throwing a # ValueError. raise ValueError("Rank of matrix is strictly less than" " number of rows or columns." " Pass keyword argument" " rankcheck=False to compute" " the LU decomposition of this matrix.") candidate_pivot_row = None if pivot_row_offset is None else pivot_row + pivot_row_offset if candidate_pivot_row is None and iszeropivot: # If candidate_pivot_row is None and iszeropivot is True # after pivot search has completed, then the submatrix # below and to the right of (pivot_row, pivot_col) is # all zeros, indicating that Gaussian elimination is # complete. return lu, row_swaps # Update entries simplified during pivot search. for offset, val in ind_simplified_pairs: lu[pivot_row + offset, pivot_col] = val if pivot_row != candidate_pivot_row: # Row swap book keeping: # Record which rows were swapped. # Update stored portion of L factor by multiplying L on the # left and right with the current permutation. # Swap rows of U. row_swaps.append([pivot_row, candidate_pivot_row]) # Update L. lu[pivot_row, 0:pivot_row], lu[candidate_pivot_row, 0:pivot_row] = \ lu[candidate_pivot_row, 0:pivot_row], lu[pivot_row, 0:pivot_row] # Swap pivot row of U with candidate pivot row. lu[pivot_row, pivot_col:lu.cols], lu[candidate_pivot_row, pivot_col:lu.cols] = \ lu[candidate_pivot_row, pivot_col:lu.cols], lu[pivot_row, pivot_col:lu.cols] # Introduce zeros below the pivot by adding a multiple of the # pivot row to a row under it, and store the result in the # row under it. # Only entries in the target row whose index is greater than # start_col may be nonzero. start_col = pivot_col + 1 for row in range(pivot_row + 1, lu.rows): # Store factors of L in the subcolumn below # (pivot_row, pivot_row). lu[row, pivot_row] = \ dps(lu[row, pivot_col]/lu[pivot_row, pivot_col]) # Form the linear combination of the pivot row and the current # row below the pivot row that zeros the entries below the pivot. # Employing slicing instead of a loop here raises # NotImplementedError: Cannot add Zero to MutableSparseMatrix # in sympy/matrices/tests/test_sparse.py. # c = pivot_row + 1 if pivot_row == pivot_col else pivot_col for c in range(start_col, lu.cols): lu[row, c] = dps(lu[row, c] - lu[row, pivot_row]*lu[pivot_row, c]) if pivot_row != pivot_col: # matrix rank < min(num rows, num cols), # so factors of L are not stored directly below the pivot. # These entries are zero by construction, so don't bother # computing them. for row in range(pivot_row + 1, lu.rows): lu[row, pivot_col] = M.zero pivot_col += 1 if pivot_col == lu.cols: # All candidate pivots are zero implies that Gaussian # elimination is complete. return lu, row_swaps if rankcheck: if iszerofunc( lu[Min(lu.rows, lu.cols) - 1, Min(lu.rows, lu.cols) - 1]): raise ValueError("Rank of matrix is strictly less than" " number of rows or columns." " Pass keyword argument" " rankcheck=False to compute" " the LU decomposition of this matrix.") return lu, row_swaps def _LUdecompositionFF(M): """Compute a fraction-free LU decomposition. Returns 4 matrices P, L, D, U such that PA = L D**-1 U. If the elements of the matrix belong to some integral domain I, then all elements of L, D and U are guaranteed to belong to I. See Also ======== sympy.matrices.matrices.MatrixBase.LUdecomposition LUdecomposition_Simple LUsolve References ========== .. [1] W. Zhou & D.J. Jeffrey, "Fraction-free matrix factors: new forms for LU and QR factors". Frontiers in Computer Science in China, Vol 2, no. 1, pp. 67-80, 2008. """ from sympy.matrices import SparseMatrix zeros = SparseMatrix.zeros eye = SparseMatrix.eye n, m = M.rows, M.cols U, L, P = M.as_mutable(), eye(n), eye(n) DD = zeros(n, n) oldpivot = 1 for k in range(n - 1): if U[k, k] == 0: for kpivot in range(k + 1, n): if U[kpivot, k]: break else: raise ValueError("Matrix is not full rank") U[k, k:], U[kpivot, k:] = U[kpivot, k:], U[k, k:] L[k, :k], L[kpivot, :k] = L[kpivot, :k], L[k, :k] P[k, :], P[kpivot, :] = P[kpivot, :], P[k, :] L [k, k] = Ukk = U[k, k] DD[k, k] = oldpivot * Ukk for i in range(k + 1, n): L[i, k] = Uik = U[i, k] for j in range(k + 1, m): U[i, j] = (Ukk * U[i, j] - U[k, j] * Uik) / oldpivot U[i, k] = 0 oldpivot = Ukk DD[n - 1, n - 1] = oldpivot return P, L, DD, U def _singular_value_decomposition(A): r"""Returns a Condensed Singular Value decomposition. Explanation =========== A Singular Value decomposition is a decomposition in the form $A = U \Sigma V$ where - $U, V$ are column orthogonal matrix. - $\Sigma$ is a diagonal matrix, where the main diagonal contains singular values of matrix A. A column orthogonal matrix satisfies $\mathbb{I} = U^H U$ while a full orthogonal matrix satisfies relation $\mathbb{I} = U U^H = U^H U$ where $\mathbb{I}$ is an identity matrix with matching dimensions. For matrices which are not square or are rank-deficient, it is sufficient to return a column orthogonal matrix because augmenting them may introduce redundant computations. In condensed Singular Value Decomposition we only return column orthogonal matrices because of this reason If you want to augment the results to return a full orthogonal decomposition, you should use the following procedures. - Augment the $U, V$ matrices with columns that are orthogonal to every other columns and make it square. - Augment the $\Sigma$ matrix with zero rows to make it have the same shape as the original matrix. The procedure will be illustrated in the examples section. Examples ======== we take a full rank matrix first: >>> from sympy import Matrix >>> A = Matrix([[1, 2],[2,1]]) >>> U, S, V = A.singular_value_decomposition() >>> U Matrix([ [ sqrt(2)/2, sqrt(2)/2], [-sqrt(2)/2, sqrt(2)/2]]) >>> S Matrix([ [1, 0], [0, 3]]) >>> V Matrix([ [-sqrt(2)/2, sqrt(2)/2], [ sqrt(2)/2, sqrt(2)/2]]) If a matrix if square and full rank both U, V are orthogonal in both directions >>> U * U.H Matrix([ [1, 0], [0, 1]]) >>> U.H * U Matrix([ [1, 0], [0, 1]]) >>> V * V.H Matrix([ [1, 0], [0, 1]]) >>> V.H * V Matrix([ [1, 0], [0, 1]]) >>> A == U * S * V.H True >>> C = Matrix([ ... [1, 0, 0, 0, 2], ... [0, 0, 3, 0, 0], ... [0, 0, 0, 0, 0], ... [0, 2, 0, 0, 0], ... ]) >>> U, S, V = C.singular_value_decomposition() >>> V.H * V Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> V * V.H Matrix([ [1/5, 0, 0, 0, 2/5], [ 0, 1, 0, 0, 0], [ 0, 0, 1, 0, 0], [ 0, 0, 0, 0, 0], [2/5, 0, 0, 0, 4/5]]) If you want to augment the results to be a full orthogonal decomposition, you should augment $V$ with an another orthogonal column. You are able to append an arbitrary standard basis that are linearly independent to every other columns and you can run the Gram-Schmidt process to make them augmented as orthogonal basis. >>> V_aug = V.row_join(Matrix([[0,0,0,0,1], ... [0,0,0,1,0]]).H) >>> V_aug = V_aug.QRdecomposition()[0] >>> V_aug Matrix([ [0, sqrt(5)/5, 0, -2*sqrt(5)/5, 0], [1, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 1], [0, 2*sqrt(5)/5, 0, sqrt(5)/5, 0]]) >>> V_aug.H * V_aug Matrix([ [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]) >>> V_aug * V_aug.H Matrix([ [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]) Similarly we augment U >>> U_aug = U.row_join(Matrix([0,0,1,0])) >>> U_aug = U_aug.QRdecomposition()[0] >>> U_aug Matrix([ [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0]]) >>> U_aug.H * U_aug Matrix([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) >>> U_aug * U_aug.H Matrix([ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) We add 2 zero columns and one row to S >>> S_aug = S.col_join(Matrix([[0,0,0]])) >>> S_aug = S_aug.row_join(Matrix([[0,0,0,0], ... [0,0,0,0]]).H) >>> S_aug Matrix([ [2, 0, 0, 0, 0], [0, sqrt(5), 0, 0, 0], [0, 0, 3, 0, 0], [0, 0, 0, 0, 0]]) >>> U_aug * S_aug * V_aug.H == C True """ AH = A.H m, n = A.shape if m >= n: V, S = (AH * A).diagonalize() ranked = [] for i, x in enumerate(S.diagonal()): if not x.is_zero: ranked.append(i) V = V[:, ranked] Singular_vals = [sqrt(S[i, i]) for i in range(S.rows) if i in ranked] S = S.zeros(len(Singular_vals)) for i, sv in enumerate(Singular_vals): S[i, i] = sv V, _ = V.QRdecomposition() U = A * V * S.inv() else: U, S = (A * AH).diagonalize() ranked = [] for i, x in enumerate(S.diagonal()): if not x.is_zero: ranked.append(i) U = U[:, ranked] Singular_vals = [sqrt(S[i, i]) for i in range(S.rows) if i in ranked] S = S.zeros(len(Singular_vals)) for i, sv in enumerate(Singular_vals): S[i, i] = sv U, _ = U.QRdecomposition() V = AH * U * S.inv() return U, S, V def _QRdecomposition_optional(M, normalize=True): def dot(u, v): return u.dot(v, hermitian=True) dps = _get_intermediate_simp(expand_mul, expand_mul) A = M.as_mutable() ranked = list() Q = A R = A.zeros(A.cols) for j in range(A.cols): for i in range(j): if Q[:, i].is_zero_matrix: continue R[i, j] = dot(Q[:, i], Q[:, j]) / dot(Q[:, i], Q[:, i]) R[i, j] = dps(R[i, j]) Q[:, j] -= Q[:, i] * R[i, j] Q[:, j] = dps(Q[:, j]) if Q[:, j].is_zero_matrix is not True: ranked.append(j) R[j, j] = M.one Q = Q.extract(range(Q.rows), ranked) R = R.extract(ranked, range(R.cols)) if normalize: # Normalization for i in range(Q.cols): norm = Q[:, i].norm() Q[:, i] /= norm R[i, :] *= norm return M.__class__(Q), M.__class__(R) def _QRdecomposition(M): r"""Returns a QR decomposition. Explanation =========== A QR decomposition is a decomposition in the form $A = Q R$ where - $Q$ is a column orthogonal matrix. - $R$ is a upper triangular (trapezoidal) matrix. A column orthogonal matrix satisfies $\mathbb{I} = Q^H Q$ while a full orthogonal matrix satisfies relation $\mathbb{I} = Q Q^H = Q^H Q$ where $I$ is an identity matrix with matching dimensions. For matrices which are not square or are rank-deficient, it is sufficient to return a column orthogonal matrix because augmenting them may introduce redundant computations. And an another advantage of this is that you can easily inspect the matrix rank by counting the number of columns of $Q$. If you want to augment the results to return a full orthogonal decomposition, you should use the following procedures. - Augment the $Q$ matrix with columns that are orthogonal to every other columns and make it square. - Augment the $R$ matrix with zero rows to make it have the same shape as the original matrix. The procedure will be illustrated in the examples section. Examples ======== A full rank matrix example: >>> from sympy import Matrix >>> A = Matrix([[12, -51, 4], [6, 167, -68], [-4, 24, -41]]) >>> Q, R = A.QRdecomposition() >>> Q Matrix([ [ 6/7, -69/175, -58/175], [ 3/7, 158/175, 6/175], [-2/7, 6/35, -33/35]]) >>> R Matrix([ [14, 21, -14], [ 0, 175, -70], [ 0, 0, 35]]) If the matrix is square and full rank, the $Q$ matrix becomes orthogonal in both directions, and needs no augmentation. >>> Q * Q.H Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> Q.H * Q Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> A == Q*R True A rank deficient matrix example: >>> A = Matrix([[12, -51, 0], [6, 167, 0], [-4, 24, 0]]) >>> Q, R = A.QRdecomposition() >>> Q Matrix([ [ 6/7, -69/175], [ 3/7, 158/175], [-2/7, 6/35]]) >>> R Matrix([ [14, 21, 0], [ 0, 175, 0]]) QRdecomposition might return a matrix Q that is rectangular. In this case the orthogonality condition might be satisfied as $\mathbb{I} = Q.H*Q$ but not in the reversed product $\mathbb{I} = Q * Q.H$. >>> Q.H * Q Matrix([ [1, 0], [0, 1]]) >>> Q * Q.H Matrix([ [27261/30625, 348/30625, -1914/6125], [ 348/30625, 30589/30625, 198/6125], [ -1914/6125, 198/6125, 136/1225]]) If you want to augment the results to be a full orthogonal decomposition, you should augment $Q$ with an another orthogonal column. You are able to append an arbitrary standard basis that are linearly independent to every other columns and you can run the Gram-Schmidt process to make them augmented as orthogonal basis. >>> Q_aug = Q.row_join(Matrix([0, 0, 1])) >>> Q_aug = Q_aug.QRdecomposition()[0] >>> Q_aug Matrix([ [ 6/7, -69/175, 58/175], [ 3/7, 158/175, -6/175], [-2/7, 6/35, 33/35]]) >>> Q_aug.H * Q_aug Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> Q_aug * Q_aug.H Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) Augmenting the $R$ matrix with zero row is straightforward. >>> R_aug = R.col_join(Matrix([[0, 0, 0]])) >>> R_aug Matrix([ [14, 21, 0], [ 0, 175, 0], [ 0, 0, 0]]) >>> Q_aug * R_aug == A True A zero matrix example: >>> from sympy import Matrix >>> A = Matrix.zeros(3, 4) >>> Q, R = A.QRdecomposition() They may return matrices with zero rows and columns. >>> Q Matrix(3, 0, []) >>> R Matrix(0, 4, []) >>> Q*R Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) As the same augmentation rule described above, $Q$ can be augmented with columns of an identity matrix and $R$ can be augmented with rows of a zero matrix. >>> Q_aug = Q.row_join(Matrix.eye(3)) >>> R_aug = R.col_join(Matrix.zeros(3, 4)) >>> Q_aug * Q_aug.T Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> R_aug Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]) >>> Q_aug * R_aug == A True See Also ======== sympy.matrices.dense.DenseMatrix.cholesky sympy.matrices.dense.DenseMatrix.LDLdecomposition sympy.matrices.matrices.MatrixBase.LUdecomposition QRsolve """ return _QRdecomposition_optional(M, normalize=True) def _upper_hessenberg_decomposition(A): """Converts a matrix into Hessenberg matrix H. Returns 2 matrices H, P s.t. $P H P^{T} = A$, where H is an upper hessenberg matrix and P is an orthogonal matrix Examples ======== >>> from sympy import Matrix >>> A = Matrix([ ... [1,2,3], ... [-3,5,6], ... [4,-8,9], ... ]) >>> H, P = A.upper_hessenberg_decomposition() >>> H Matrix([ [1, 6/5, 17/5], [5, 213/25, -134/25], [0, 216/25, 137/25]]) >>> P Matrix([ [1, 0, 0], [0, -3/5, 4/5], [0, 4/5, 3/5]]) >>> P * H * P.H == A True References ========== .. [#] https://mathworld.wolfram.com/HessenbergDecomposition.html """ M = A.as_mutable() if not M.is_square: raise NonSquareMatrixError("Matrix must be square.") n = M.cols P = M.eye(n) H = M for j in range(n - 2): u = H[j + 1:, j] if u[1:, :].is_zero_matrix: continue if sign(u[0]) != 0: u[0] = u[0] + sign(u[0]) * u.norm() else: u[0] = u[0] + u.norm() v = u / u.norm() H[j + 1:, :] = H[j + 1:, :] - 2 * v * (v.H * H[j + 1:, :]) H[:, j + 1:] = H[:, j + 1:] - (H[:, j + 1:] * (2 * v)) * v.H P[:, j + 1:] = P[:, j + 1:] - (P[:, j + 1:] * (2 * v)) * v.H return H, P
dc5e63c7af4260a8a02b49885b0368939579bdb8de37cc6c82a067c51a3af008
""" Basic methods common to all matrices to be used when creating more advanced matrices (e.g., matrices over rings, etc.). """ from collections import defaultdict from collections.abc import Iterable from inspect import isfunction from functools import reduce from sympy.assumptions.refine import refine from sympy.core import SympifyError, Add from sympy.core.basic import Atom from sympy.core.decorators import call_highest_priority from sympy.core.kind import Kind, NumberKind from sympy.core.logic import fuzzy_and, FuzzyBool from sympy.core.mod import Mod from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.functions.elementary.complexes import Abs, re, im from .utilities import _dotprodsimp, _simplify from sympy.polys.polytools import Poly from sympy.utilities.iterables import flatten, is_sequence from sympy.utilities.misc import as_int, 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 combination 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, entry) 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, entry) 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, entry) 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( "The matrices have incompatible number of rows ({} and {})" .format(self.rows, other.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( "The matrices have incompatible number of columns ({} and {})" .format(self.cols, other.cols)) 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 col_del col_join col_insert """ return self[:, j] def extract(self, rowsList, colsList): r"""Return a submatrix by specifying a list of rows and columns. Negative indices can be given. All indices must be in the range $-n \le 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 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( "The matrices have incompatible number of columns ({} and {})" .format(self.cols, other.cols)) 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( "The matrices have incompatible number of rows ({} and {})" .format(self.rows, other.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 """ 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 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 import zeros >>> M = zeros(2, 3) >>> M.shape (2, 3) >>> M.rows 2 >>> M.cols 3 """ return (self.rows, self.cols) def todok(self): """Return the matrix as dictionary of keys. Examples ======== >>> from sympy import Matrix >>> M = Matrix.eye(3) >>> M.todok() {(0, 0): 1, (1, 1): 1, (2, 2): 1} """ return self._eval_todok() def tolist(self): """Return the Matrix as a nested Python list. Examples ======== >>> from sympy import Matrix, ones >>> m = Matrix(3, 3, range(9)) >>> m Matrix([ [0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> m.tolist() [[0, 1, 2], [3, 4, 5], [6, 7, 8]] >>> ones(3, 0).tolist() [[], [], []] When there are no rows then it will not be possible to tell how many columns were in the original matrix: >>> ones(0, 3).tolist() [] """ if not self.rows: return [] if not self.cols: return [[] for i in range(self.rows)] return self._eval_tolist() def todod(M): """Returns matrix as dict of dicts containing non-zero elements of the Matrix Examples ======== >>> from sympy import Matrix >>> A = Matrix([[0, 1],[0, 3]]) >>> A Matrix([ [0, 1], [0, 3]]) >>> A.todod() {0: {1: 1}, 1: {1: 3}} """ rowsdict = {} Mlol = M.tolist() for i, Mi in enumerate(Mlol): row = {j: Mij for j, Mij in enumerate(Mi) if Mij} if row: rowsdict[i] = row return rowsdict def vec(self): """Return the Matrix converted into a one column matrix by stacking columns Examples ======== >>> from sympy import Matrix >>> m=Matrix([[1, 3], [2, 4]]) >>> m Matrix([ [1, 3], [2, 4]]) >>> m.vec() Matrix([ [1], [2], [3], [4]]) See Also ======== vech """ return self._eval_vec() def vech(self, diagonal=True, check_symmetry=True): """Reshapes the matrix into a column vector by stacking the elements in the lower triangle. Parameters ========== diagonal : bool, optional If ``True``, it includes the diagonal elements. check_symmetry : bool, optional If ``True``, it checks whether the matrix is symmetric. Examples ======== >>> from sympy import Matrix >>> m=Matrix([[1, 2], [2, 3]]) >>> m Matrix([ [1, 2], [2, 3]]) >>> m.vech() Matrix([ [1], [2], [3]]) >>> m.vech(diagonal=False) Matrix([[2]]) Notes ===== This should work for symmetric matrices and ``vech`` can represent symmetric matrices in vector form with less size than ``vec``. See Also ======== vec """ if not self.is_square: raise NonSquareMatrixError if check_symmetry and not self.is_symmetric(): raise ValueError("The matrix is not symmetric.") return self._eval_vech(diagonal) @classmethod def vstack(cls, *args): """Return a matrix formed by joining args vertically (i.e. by repeated application of col_join). Examples ======== >>> from sympy import Matrix, eye >>> Matrix.vstack(eye(2), 2*eye(2)) Matrix([ [1, 0], [0, 1], [2, 0], [0, 2]]) """ if len(args) == 0: return cls._new() kls = type(args[0]) return reduce(kls.col_join, args) class MatrixSpecial(MatrixRequired): """Construction of special matrices""" @classmethod def _eval_diag(cls, rows, cols, diag_dict): """diag_dict is a defaultdict containing all the entries of the diagonal matrix.""" def entry(i, j): return diag_dict[(i, j)] return cls._new(rows, cols, entry) @classmethod def _eval_eye(cls, rows, cols): vals = [cls.zero]*(rows*cols) vals[::cols+1] = [cls.one]*min(rows, cols) return cls._new(rows, cols, vals, copy=False) @classmethod def _eval_jordan_block(cls, size: int, 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(size, size, entry) @classmethod def _eval_ones(cls, rows, cols): def entry(i, j): return cls.one return cls._new(rows, cols, entry) @classmethod def _eval_zeros(cls, rows, cols): return cls._new(rows, cols, [cls.zero]*(rows*cols), copy=False) @classmethod def _eval_wilkinson(cls, n): def entry(i, j): return cls.one if i + 1 == j else cls.zero D = cls._new(2*n + 1, 2*n + 1, entry) wminus = cls.diag([i for i in range(-n, n + 1)], unpack=True) + D + D.T wplus = abs(cls.diag([i for i in range(-n, n + 1)], unpack=True)) + D + D.T return wminus, wplus @classmethod def diag(kls, *args, strict=False, unpack=True, rows=None, cols=None, **kwargs): """Returns a matrix with the specified diagonal. If matrices are passed, a block-diagonal matrix is created (i.e. the "direct sum" of the matrices). kwargs ====== rows : rows of the resulting matrix; computed if not given. cols : columns of the resulting matrix; computed if not given. cls : class for the resulting matrix unpack : bool which, when True (default), unpacks a single sequence rather than interpreting it as a Matrix. strict : bool which, when False (default), allows Matrices to have variable-length rows. Examples ======== >>> from sympy 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 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 .dense.diag .expressions.blockmatrix.BlockMatrix .sparsetools.banded """ from sympy.matrices.matrices import MatrixBase from sympy.matrices.dense import Matrix from sympy.matrices 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, mi in enumerate(m): for j, _ in enumerate(mi): 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. Parameters ========== rows : rows of the matrix cols : cols of the matrix (if None, cols=rows) kwargs ====== cls : class of the returned matrix """ if cols is None: cols = rows if rows < 0 or cols < 0: raise ValueError("Cannot create a {} x {} matrix. " "Both dimensions must be positive".format(rows, cols)) klass = kwargs.get('cls', kls) rows, cols = as_int(rows), as_int(cols) return klass._eval_eye(rows, cols) @classmethod def jordan_block(kls, size=None, eigenvalue=None, *, band='upper', **kwargs): """Returns a Jordan block Parameters ========== size : Integer, optional Specifies the shape of the Jordan block matrix. eigenvalue : Number or Symbol Specifies the value for the main diagonal of the matrix. .. note:: The keyword ``eigenval`` is also specified as an alias of this keyword, but it is not recommended to use. We may deprecate the alias in later release. band : 'upper' or 'lower', optional Specifies the position of the off-diagonal to put `1` s on. cls : Matrix, optional Specifies the matrix class of the output form. If it is not specified, the class type where the method is being executed on will be returned. 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]]) References ========== .. [1] https://en.wikipedia.org/wiki/Jordan_matrix """ klass = kwargs.pop('cls', kls) 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 is None: raise ValueError("Must supply a matrix size") size = as_int(size) return klass._eval_jordan_block(size, eigenvalue, band) @classmethod def ones(kls, rows, cols=None, **kwargs): """Returns a matrix of ones. Parameters ========== 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. Parameters ========== rows : rows of the matrix cols : cols of the matrix (if None, cols=rows) kwargs ====== cls : class of the returned matrix """ if cols is None: cols = rows if rows < 0 or cols < 0: raise ValueError("Cannot create a {} x {} matrix. " "Both dimensions must be positive".format(rows, cols)) klass = kwargs.get('cls', kls) rows, cols = as_int(rows), as_int(cols) return klass._eval_zeros(rows, cols) @classmethod def companion(kls, poly): """Returns a companion matrix of a polynomial. Examples ======== >>> from sympy import Matrix, Poly, Symbol, symbols >>> x = Symbol('x') >>> c0, c1, c2, c3, c4 = symbols('c0:5') >>> p = Poly(c0 + c1*x + c2*x**2 + c3*x**3 + c4*x**4 + x**5, x) >>> Matrix.companion(p) Matrix([ [0, 0, 0, 0, -c0], [1, 0, 0, 0, -c1], [0, 1, 0, 0, -c2], [0, 0, 1, 0, -c3], [0, 0, 0, 1, -c4]]) """ poly = kls._sympify(poly) if not isinstance(poly, Poly): raise ValueError("{} must be a Poly instance.".format(poly)) if not poly.is_monic: raise ValueError("{} must be a monic polynomial.".format(poly)) if not poly.is_univariate: raise ValueError( "{} must be a univariate polynomial.".format(poly)) size = poly.degree() if not size >= 1: raise ValueError( "{} must have degree not less than 1.".format(poly)) coeffs = poly.all_coeffs() def entry(i, j): if j == size - 1: return -coeffs[-1 - i] elif i == j + 1: return kls.one return kls.zero return kls._new(size, size, entry) @classmethod def wilkinson(kls, n, **kwargs): """Returns two square Wilkinson Matrix of size 2*n + 1 $W_{2n + 1}^-, W_{2n + 1}^+ =$ Wilkinson(n) Examples ======== >>> from sympy import Matrix >>> wminus, wplus = Matrix.wilkinson(3) >>> wminus Matrix([ [-3, 1, 0, 0, 0, 0, 0], [ 1, -2, 1, 0, 0, 0, 0], [ 0, 1, -1, 1, 0, 0, 0], [ 0, 0, 1, 0, 1, 0, 0], [ 0, 0, 0, 1, 1, 1, 0], [ 0, 0, 0, 0, 1, 2, 1], [ 0, 0, 0, 0, 0, 1, 3]]) >>> wplus Matrix([ [3, 1, 0, 0, 0, 0, 0], [1, 2, 1, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 1, 2, 1], [0, 0, 0, 0, 0, 1, 3]]) References ========== .. [1] https://blogs.mathworks.com/cleve/2013/04/15/wilkinsons-matrices-2/ .. [2] J. H. Wilkinson, The Algebraic Eigenvalue Problem, Claredon Press, Oxford, 1965, 662 pp. """ klass = kwargs.get('cls', kls) n = as_int(n) return klass._eval_wilkinson(n) class MatrixProperties(MatrixRequired): """Provides basic properties of a matrix.""" def _eval_atoms(self, *types): result = set() for i in self: result.update(i.atoms(*types)) return result def _eval_free_symbols(self): return set().union(*(i.free_symbols for i in self if i)) def _eval_has(self, *patterns): return any(a.has(*patterns) for a in self) def _eval_is_anti_symmetric(self, simpfunc): if not all(simpfunc(self[i, j] + self[j, i]).is_zero for i in range(self.rows) for j in range(self.cols)): return False return True def _eval_is_diagonal(self): for i in range(self.rows): for j in range(self.cols): if i != j and self[i, j]: return False return True # _eval_is_hermitian is called by some general SymPy # routines and has a different *args signature. Make # sure the names don't clash by adding `_matrix_` in name. def _eval_is_matrix_hermitian(self, simpfunc): mat = self._new(self.rows, self.cols, lambda i, j: simpfunc(self[i, j] - self[j, i].conjugate())) return mat.is_zero_matrix def _eval_is_Identity(self) -> FuzzyBool: def dirac(i, j): if i == j: return 1 return 0 return all(self[i, j] == dirac(i, j) for i in range(self.rows) for j in range(self.cols)) def _eval_is_lower_hessenberg(self): return all(self[i, j].is_zero for i in range(self.rows) for j in range(i + 2, self.cols)) def _eval_is_lower(self): return all(self[i, j].is_zero for i in range(self.rows) for j in range(i + 1, self.cols)) def _eval_is_symbolic(self): return self.has(Symbol) def _eval_is_symmetric(self, simpfunc): mat = self._new(self.rows, self.cols, lambda i, j: simpfunc(self[i, j] - self[j, i])) return mat.is_zero_matrix def _eval_is_zero_matrix(self): if any(i.is_zero == False for i in self): return False if any(i.is_zero is None for i in self): return None return True def _eval_is_upper_hessenberg(self): return all(self[i, j].is_zero for i in range(2, self.rows) for j in range(min(self.cols, (i - 1)))) def _eval_values(self): return [i for i in self if not i.is_zero] def _has_positive_diagonals(self): diagonal_entries = (self[i, i] for i in range(self.rows)) return fuzzy_and(x.is_positive for x in diagonal_entries) def _has_nonnegative_diagonals(self): diagonal_entries = (self[i, i] for i in range(self.rows)) return fuzzy_and(x.is_nonnegative for x in diagonal_entries) def atoms(self, *types): """Returns the atoms that form the current object. Examples ======== >>> from sympy.abc import x, y >>> from sympy 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 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 would not 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 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 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 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 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 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 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 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 import SparseMatrix, 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, **hints): return self.applyfunc(lambda x: x.doit(**hints)) 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 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 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 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 SparseMatrix, sin, cos >>> 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 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 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.trigsimp import trigsimp return self.applyfunc(lambda x: trigsimp(x, **opts)) def upper_triangular(self, k=0): """Return the elements on and above the kth diagonal of a matrix. If k is not specified then simply returns upper-triangular portion of a matrix Examples ======== >>> from sympy import ones >>> A = ones(4) >>> A.upper_triangular() Matrix([ [1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1], [0, 0, 0, 1]]) >>> A.upper_triangular(2) Matrix([ [0, 0, 1, 1], [0, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]]) >>> A.upper_triangular(-1) Matrix([ [1, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1]]) """ def entry(i, j): return self[i, j] if i + k <= j else self.zero return self._new(self.rows, self.cols, entry) def lower_triangular(self, k=0): """Return the elements on and below the kth diagonal of a matrix. If k is not specified then simply returns lower-triangular portion of a matrix Examples ======== >>> from sympy import ones >>> A = ones(4) >>> A.lower_triangular() Matrix([ [1, 0, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1]]) >>> A.lower_triangular(-2) Matrix([ [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0], [1, 1, 0, 0]]) >>> A.lower_triangular(1) Matrix([ [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1], [1, 1, 1, 1]]) """ def entry(i, j): return self[i, j] if i + k >= j else self.zero return self._new(self.rows, self.cols, entry) class MatrixArithmetic(MatrixRequired): """Provides basic matrix arithmetic operations. Should not be instantiated directly.""" _op_priority = 10.01 def _eval_Abs(self): return self._new(self.rows, self.cols, lambda i, j: Abs(self[i, j])) def _eval_add(self, other): return self._new(self.rows, self.cols, lambda i, j: self[i, j] + other[i, j]) def _eval_matrix_mul(self, other): def entry(i, j): vec = [self[i,k]*other[k,j] for k in range(self.cols)] try: return Add(*vec) except (TypeError, SympifyError): # Some matrices don't work with `sum` or `Add` # They don't work with `sum` because `sum` tries to add `0` # Fall back to a safe way to multiply if the `Add` fails. return reduce(lambda a, b: a + b, vec) return self._new(self.rows, other.cols, entry) def _eval_matrix_mul_elementwise(self, other): return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other[i,j]) def _eval_matrix_rmul(self, other): def entry(i, j): return sum(other[i,k]*self[k,j] for k in range(other.cols)) return self._new(other.rows, self.cols, entry) def _eval_pow_by_recursion(self, num): if num == 1: return self if num % 2 == 1: a, b = self, self._eval_pow_by_recursion(num - 1) else: a = b = self._eval_pow_by_recursion(num // 2) return a.multiply(b) def _eval_pow_by_cayley(self, exp): from sympy.discrete.recurrences import linrec_coeffs row = self.shape[0] p = self.charpoly() coeffs = (-p).all_coeffs()[1:] coeffs = linrec_coeffs(coeffs, exp) new_mat = self.eye(row) ans = self.zeros(row) for i in range(row): ans += coeffs[i]*new_mat new_mat *= self return ans def _eval_pow_by_recursion_dotprodsimp(self, num, prevsimp=None): if prevsimp is None: prevsimp = [True]*len(self) if num == 1: return self if num % 2 == 1: a, b = self, self._eval_pow_by_recursion_dotprodsimp(num - 1, prevsimp=prevsimp) else: a = b = self._eval_pow_by_recursion_dotprodsimp(num // 2, prevsimp=prevsimp) m = a.multiply(b, dotprodsimp=False) lenm = len(m) elems = [None]*lenm for i in range(lenm): if prevsimp[i]: elems[i], prevsimp[i] = _dotprodsimp(m[i], withsimp=True) else: elems[i] = m[i] return m._new(m.rows, m.cols, elems) def _eval_scalar_mul(self, other): return self._new(self.rows, self.cols, lambda i, j: self[i,j]*other) def _eval_scalar_rmul(self, other): return self._new(self.rows, self.cols, lambda i, j: other*self[i,j]) def _eval_Mod(self, other): 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 do not 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 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 import Matrix >>> A = Matrix([[0, 1, 2], [3, 4, 5]]) >>> B = Matrix([[1, 10, 100], [100, 10, 1]]) >>> A.multiply_elementwise(B) Matrix([ [ 0, 10, 200], [300, 40, 5]]) See Also ======== sympy.matrices.matrices.MatrixBase.cross sympy.matrices.matrices.MatrixBase.dot multiply """ if self.shape != other.shape: raise ShapeError("Matrix shapes must agree {} != {}".format(self.shape, other.shape)) return self._eval_matrix_mul_elementwise(other) def __neg__(self): return self._eval_scalar_mul(-1) @call_highest_priority('__rpow__') def __pow__(self, exp): """Return self**exp a scalar or symbol.""" return self.pow(exp) def pow(self, exp, method=None): r"""Return self**exp a scalar or symbol. Parameters ========== method : multiply, mulsimp, jordan, cayley If multiply then it returns exponentiation using recursion. If jordan then Jordan form exponentiation will be used. If cayley then the exponentiation is done using Cayley-Hamilton theorem. If mulsimp then the exponentiation is done using recursion with dotprodsimp. This specifies whether intermediate term algebraic simplification is used during naive matrix power to control expression blowup and thus speed up calculation. If None, then it heuristically decides which method to use. """ if method is not None and method not in ['multiply', 'mulsimp', 'jordan', 'cayley']: raise TypeError('No such method') if self.rows != self.cols: raise NonSquareMatrixError() a = self jordan_pow = getattr(a, '_matrix_pow_by_jordan_blocks', None) exp = sympify(exp) if exp.is_zero: return a._new(a.rows, a.cols, lambda i, j: int(i == j)) if exp == 1: return a diagonal = getattr(a, 'is_diagonal', None) if diagonal is not None and diagonal(): return a._new(a.rows, a.cols, lambda i, j: a[i,j]**exp if i == j else 0) if exp.is_Number and exp % 1 == 0: if a.rows == 1: return a._new([[a[0]**exp]]) if exp < 0: exp = -exp a = a.inv() # When certain conditions are met, # Jordan block algorithm is faster than # computation by recursion. if method == 'jordan': try: return jordan_pow(exp) except MatrixError: if method == 'jordan': raise elif method == 'cayley': if not exp.is_Number or exp % 1 != 0: raise ValueError("cayley method is only valid for integer powers") return a._eval_pow_by_cayley(exp) elif method == "mulsimp": if not exp.is_Number or exp % 1 != 0: raise ValueError("mulsimp method is only valid for integer powers") return a._eval_pow_by_recursion_dotprodsimp(exp) elif method == "multiply": if not exp.is_Number or exp % 1 != 0: raise ValueError("multiply method is only valid for integer powers") return a._eval_pow_by_recursion(exp) elif method is None and exp.is_Number and exp % 1 == 0: # Decide heuristically which method to apply if a.rows == 2 and exp > 100000: return jordan_pow(exp) elif _get_intermediate_simp_bool(True, None): return a._eval_pow_by_recursion_dotprodsimp(exp) elif exp > 10000: return a._eval_pow_by_cayley(exp) else: return a._eval_pow_by_recursion(exp) if jordan_pow: try: return jordan_pow(exp) except NonInvertibleMatrixError: # Raised by jordan_pow on zero determinant matrix unless exp is # definitely known to be a non-negative integer. # Here we raise if n is definitely not a non-negative integer # but otherwise we can leave this as an unevaluated MatPow. if exp.is_integer is False or exp.is_nonnegative is False: raise from sympy.matrices.expressions import MatPow return MatPow(a, exp) @call_highest_priority('__add__') def __radd__(self, other): return self + other @call_highest_priority('__matmul__') def __rmatmul__(self, other): other = _matrixify(other) if not getattr(other, 'is_Matrix', False) and not getattr(other, 'is_MatrixLike', False): return NotImplemented return self.__rmul__(other) @call_highest_priority('__mul__') def __rmul__(self, other): return self.rmultiply(other) def rmultiply(self, other, dotprodsimp=None): """Same as __rmul__() but with optional simplification. Parameters ========== dotprodsimp : bool, optional Specifies whether intermediate term algebraic simplification is used during matrix multiplications to control expression blowup and thus speed up calculation. Default is off. """ isimpbool = _get_intermediate_simp_bool(False, dotprodsimp) other = _matrixify(other) # matrix-like objects can have shapes. This is # our first sanity check. Double check other is not explicitly not a Matrix. if (hasattr(other, 'shape') and len(other.shape) == 2 and (getattr(other, 'is_Matrix', True) or getattr(other, 'is_MatrixLike', True))): if self.shape[0] != other.shape[1]: raise ShapeError("Matrix size mismatch.") # honest SymPy matrices defer to their class's routine if getattr(other, 'is_Matrix', False): m = self._eval_matrix_rmul(other) if isimpbool: return m._new(m.rows, m.cols, [_dotprodsimp(e) for e in m]) return m # Matrix-like objects can be passed to CommonMatrix routines directly. if getattr(other, 'is_MatrixLike', False): return MatrixArithmetic._eval_matrix_rmul(self, other) # if 'other' is not iterable then scalar multiplication. if not isinstance(other, Iterable): try: return self._eval_scalar_rmul(other) except TypeError: pass return NotImplemented @call_highest_priority('__sub__') def __rsub__(self, a): return (-self) + a @call_highest_priority('__rsub__') def __sub__(self, a): return self + (-a) class MatrixCommon(MatrixArithmetic, MatrixOperations, MatrixProperties, MatrixSpecial, MatrixShaping): """All common matrix operations including basic arithmetic, shaping, and special matrices like `zeros`, and `eye`.""" _diff_wrt = True # type: bool class _MinimalMatrix: """Class providing the minimum functionality for a matrix-like object and implementing every method required for a `MatrixRequired`. This class does not have everything needed to become a full-fledged SymPy object, but it will satisfy the requirements of anything inheriting from `MatrixRequired`. If you wish to make a specialized matrix type, make sure to implement these methods and properties with the exception of `__init__` and `__repr__` which are included for convenience.""" is_MatrixLike = True _sympify = staticmethod(sympify) _class_priority = 3 zero = S.Zero one = S.One is_Matrix = True is_MatrixExpr = False @classmethod def _new(cls, *args, **kwargs): return cls(*args, **kwargs) def __init__(self, rows, cols=None, mat=None, copy=False): if isfunction(mat): # if we passed in a function, use that to populate the indices mat = list(mat(i, j) for i in range(rows) for j in range(cols)) if cols is None and mat is None: mat = rows rows, cols = getattr(mat, 'shape', (rows, cols)) try: # if we passed in a list of lists, flatten it and set the size if cols is None and mat is None: mat = rows cols = len(mat[0]) rows = len(mat) mat = [x for l in mat for x in l] except (IndexError, TypeError): pass self.mat = tuple(self._sympify(x) for x in mat) self.rows, self.cols = rows, cols if self.rows is None or self.cols is None: raise NotImplementedError("Cannot initialize matrix with given parameters") def __getitem__(self, key): def _normalize_slices(row_slice, col_slice): """Ensure that row_slice and col_slice do not have `None` in their arguments. Any integers are converted to slices of length 1""" if not isinstance(row_slice, slice): row_slice = slice(row_slice, row_slice + 1, None) row_slice = slice(*row_slice.indices(self.rows)) if not isinstance(col_slice, slice): col_slice = slice(col_slice, col_slice + 1, None) col_slice = slice(*col_slice.indices(self.cols)) return (row_slice, col_slice) def _coord_to_index(i, j): """Return the index in _mat corresponding to the (i,j) position in the matrix. """ return i * self.cols + j if isinstance(key, tuple): i, j = key if isinstance(i, slice) or isinstance(j, slice): # if the coordinates are not slices, make them so # and expand the slices so they don't contain `None` i, j = _normalize_slices(i, j) rowsList, colsList = list(range(self.rows))[i], \ list(range(self.cols))[j] indices = (i * self.cols + j for i in rowsList for j in colsList) return self._new(len(rowsList), len(colsList), list(self.mat[i] for i in indices)) # if the key is a tuple of ints, change # it to an array index key = _coord_to_index(i, j) return self.mat[key] def __eq__(self, other): try: classof(self, other) except TypeError: return False return ( self.shape == other.shape and list(self) == list(other)) def __len__(self): return self.rows*self.cols def __repr__(self): return "_MinimalMatrix({}, {}, {})".format(self.rows, self.cols, self.mat) @property def shape(self): return (self.rows, self.cols) class _CastableMatrix: # this is needed here ONLY FOR TESTS. def as_mutable(self): return self def as_immutable(self): return self class _MatrixWrapper: """Wrapper class providing the minimum functionality for a matrix-like object: .rows, .cols, .shape, indexability, and iterability. CommonMatrix math operations should work on matrix-like objects. This one is intended for matrix-like objects which use the same indexing format as SymPy with respect to returning matrix elements instead of rows for non-tuple indexes. """ is_Matrix = False # needs to be here because of __getattr__ is_MatrixLike = True def __init__(self, mat, shape): self.mat = mat self.shape = shape self.rows, self.cols = shape def __getitem__(self, key): if isinstance(key, tuple): return sympify(self.mat.__getitem__(key)) return sympify(self.mat.__getitem__((key // self.rows, key % self.cols))) def __iter__(self): # supports numpy.matrix and numpy.array mat = self.mat cols = self.cols return iter(sympify(mat[r, c]) for r in range(self.rows) for c in range(cols)) class MatrixKind(Kind): """ Kind for all matrices in SymPy. Basic class for this kind is ``MatrixBase`` and ``MatrixExpr``, but any expression representing the matrix can have this. Parameters ========== element_kind : Kind Kind of the element. Default is :class:`sympy.core.kind.NumberKind`, which means that the matrix contains only numbers. Examples ======== Any instance of matrix class has ``MatrixKind``: >>> from sympy import MatrixSymbol >>> A = MatrixSymbol('A', 2,2) >>> A.kind MatrixKind(NumberKind) Although expression representing a matrix may be not instance of matrix class, it will have ``MatrixKind`` as well: >>> from sympy import MatrixExpr, Integral >>> from sympy.abc import x >>> intM = Integral(A, x) >>> isinstance(intM, MatrixExpr) False >>> intM.kind MatrixKind(NumberKind) Use ``isinstance()`` to check for ``MatrixKind`` without specifying the element kind. Use ``is`` with specifying the element kind: >>> from sympy import Matrix >>> from sympy.core import NumberKind >>> from sympy.matrices import MatrixKind >>> M = Matrix([1, 2]) >>> isinstance(M.kind, MatrixKind) True >>> M.kind is MatrixKind(NumberKind) True See Also ======== sympy.core.kind.NumberKind sympy.core.kind.UndefinedKind sympy.core.containers.TupleKind sympy.sets.sets.SetKind """ def __new__(cls, element_kind=NumberKind): obj = super().__new__(cls, element_kind) obj.element_kind = element_kind return obj def __repr__(self): return "MatrixKind(%s)" % self.element_kind def _matrixify(mat): """If `mat` is a Matrix or is matrix-like, return a Matrix or MatrixWrapper object. Otherwise `mat` is passed through without modification.""" if getattr(mat, 'is_Matrix', False) or getattr(mat, 'is_MatrixLike', False): return mat if not(getattr(mat, 'is_Matrix', True) or getattr(mat, 'is_MatrixLike', True)): return mat shape = None if hasattr(mat, 'shape'): # numpy, scipy.sparse if len(mat.shape) == 2: shape = mat.shape elif hasattr(mat, 'rows') and hasattr(mat, 'cols'): # mpmath shape = (mat.rows, mat.cols) if shape: return _MatrixWrapper(mat, shape) return mat def a2idx(j, n=None): """Return integer after making positive and validating against n.""" if not isinstance(j, 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__))
71302ad0adc69cb0623640a064d56bf6b2edf07debae7ca11da78b73f6130689
import random from sympy.core.basic import Basic 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.utilities.decorator import doctest_depends_on from sympy.utilities.exceptions import sympy_deprecation_warning from sympy.utilities.iterables import is_sequence from .common import ShapeError from .decompositions import _cholesky, _LDLdecomposition from .matrices import MatrixBase from .repmatrix import MutableRepMatrix, RepMatrix from .solvers import _lower_triangular_solve, _upper_triangular_solve def _iszero(x): """Returns True if x is zero.""" return x.is_zero class DenseMatrix(RepMatrix): """Matrix implementation based on DomainMatrix as the internal representation""" # # DenseMatrix is a superclass for both MutableDenseMatrix and # ImmutableDenseMatrix. Methods shared by both classes but not for the # Sparse classes should be implemented here. # is_MatrixExpr = False # type: bool _op_priority = 10.01 _class_priority = 4 @property def _mat(self): sympy_deprecation_warning( """ The private _mat attribute of Matrix is deprecated. Use the .flat() method instead. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-private-matrix-attributes" ) return self.flat() 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 as_immutable(self): """Returns an Immutable version of this Matrix """ from .immutable import ImmutableDenseMatrix as cls return cls._fromrep(self._rep.copy()) 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 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, MutableRepMatrix): 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 """ from sympy.simplify.simplify import simplify as _simplify for (i, j), element in self.todok().items(): self[i, j] = _simplify(element, **kwargs) MutableMatrix = Matrix = MutableDenseMatrix ########### # Numpy Utility Functions: # list2numpy, matrix2numpy, symmarray ########### 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 ########### # Rotation matrices: # rot_givens, rot_axis[123], rot_ccw_axis[123] ########### def rot_givens(i, j, theta, dim=3): r"""Returns a a Givens rotation matrix, a a rotation in the plane spanned by two coordinates axes. Explanation =========== The Givens rotation corresponds to a generalization of rotation matrices to any number of dimensions, given by: .. math:: G(i, j, \theta) = \begin{bmatrix} 1 & \cdots & 0 & \cdots & 0 & \cdots & 0 \\ \vdots & \ddots & \vdots & & \vdots & & \vdots \\ 0 & \cdots & c & \cdots & -s & \cdots & 0 \\ \vdots & & \vdots & \ddots & \vdots & & \vdots \\ 0 & \cdots & s & \cdots & c & \cdots & 0 \\ \vdots & & \vdots & & \vdots & \ddots & \vdots \\ 0 & \cdots & 0 & \cdots & 0 & \cdots & 1 \end{bmatrix} Where $c = \cos(\theta)$ and $s = \sin(\theta)$ appear at the intersections ``i``\th and ``j``\th rows and columns. For fixed ``i > j``\, the non-zero elements of a Givens matrix are given by: - $g_{kk} = 1$ for $k \ne i,\,j$ - $g_{kk} = c$ for $k = i,\,j$ - $g_{ji} = -g_{ij} = -s$ Parameters ========== i : int between ``0`` and ``dim - 1`` Represents first axis j : int between ``0`` and ``dim - 1`` Represents second axis dim : int bigger than 1 Number of dimentions. Defaults to 3. Examples ======== >>> from sympy import pi, rot_givens A counterclockwise rotation of pi/3 (60 degrees) around the third axis (z-axis): >>> rot_givens(1, 0, pi/3) 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_givens(1, 0, pi/2) Matrix([ [0, -1, 0], [1, 0, 0], [0, 0, 1]]) This can be generalized to any number of dimensions: >>> rot_givens(1, 0, pi/2, dim=4) Matrix([ [0, -1, 0, 0], [1, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) References ========== .. [1] https://en.wikipedia.org/wiki/Givens_rotation See Also ======== rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis (clockwise around the x axis) rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis (clockwise around the y axis) rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis (clockwise around the z axis) rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis (counterclockwise around the x axis) rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis (counterclockwise around the y axis) rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis (counterclockwise around the z axis) """ if not isinstance(dim, int) or dim < 2: raise ValueError('dim must be an integer biggen than one, ' 'got {}.'.format(dim)) if i == j: raise ValueError('i and j must be different, ' 'got ({}, {})'.format(i, j)) for ij in [i, j]: if not isinstance(ij, int) or ij < 0 or ij > dim - 1: raise ValueError('i and j must be integers between 0 and ' '{}, got i={} and j={}.'.format(dim-1, i, j)) theta = sympify(theta) c = cos(theta) s = sin(theta) M = eye(dim) M[i, i] = c M[j, j] = c M[i, j] = s M[j, i] = -s return M def rot_axis3(theta): r"""Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis. Explanation =========== For a right-handed coordinate system, this corresponds to a clockwise rotation around the `z`-axis, given by: .. math:: R = \begin{bmatrix} \cos(\theta) & \sin(\theta) & 0 \\ -\sin(\theta) & \cos(\theta) & 0 \\ 0 & 0 & 1 \end{bmatrix} Examples ======== >>> from sympy import pi, 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_givens: Returns a Givens rotation matrix (generalized rotation for any number of dimensions) rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis (counterclockwise around the z axis) rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis (clockwise around the x axis) rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis (clockwise around the y axis) """ return rot_givens(0, 1, theta, dim=3) def rot_axis2(theta): r"""Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis. Explanation =========== For a right-handed coordinate system, this corresponds to a clockwise rotation around the `y`-axis, given by: .. math:: R = \begin{bmatrix} \cos(\theta) & 0 & -\sin(\theta) \\ 0 & 1 & 0 \\ \sin(\theta) & 0 & \cos(\theta) \end{bmatrix} Examples ======== >>> from sympy import pi, 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_givens: Returns a Givens rotation matrix (generalized rotation for any number of dimensions) rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis (clockwise around the y axis) rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis (counterclockwise around the x axis) rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis (counterclockwise around the z axis) """ return rot_givens(2, 0, theta, dim=3) def rot_axis1(theta): r"""Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis. Explanation =========== For a right-handed coordinate system, this corresponds to a clockwise rotation around the `x`-axis, given by: .. math:: R = \begin{bmatrix} 1 & 0 & 0 \\ 0 & \cos(\theta) & \sin(\theta) \\ 0 & -\sin(\theta) & \cos(\theta) \end{bmatrix} Examples ======== >>> from sympy import pi, 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_givens: Returns a Givens rotation matrix (generalized rotation for any number of dimensions) rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis (counterclockwise around the x axis) rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis (clockwise around the y axis) rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis (clockwise around the z axis) """ return rot_givens(1, 2, theta, dim=3) def rot_ccw_axis3(theta): r"""Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis. Explanation =========== For a right-handed coordinate system, this corresponds to a counterclockwise rotation around the `z`-axis, given by: .. math:: R = \begin{bmatrix} \cos(\theta) & -\sin(\theta) & 0 \\ \sin(\theta) & \cos(\theta) & 0 \\ 0 & 0 & 1 \end{bmatrix} Examples ======== >>> from sympy import pi, rot_ccw_axis3 A rotation of pi/3 (60 degrees): >>> theta = pi/3 >>> rot_ccw_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_ccw_axis3(pi/2) Matrix([ [0, -1, 0], [1, 0, 0], [0, 0, 1]]) See Also ======== rot_givens: Returns a Givens rotation matrix (generalized rotation for any number of dimensions) rot_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis (clockwise around the z axis) rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis (counterclockwise around the x axis) rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis (counterclockwise around the y axis) """ return rot_givens(1, 0, theta, dim=3) def rot_ccw_axis2(theta): r"""Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis. Explanation =========== For a right-handed coordinate system, this corresponds to a counterclockwise rotation around the `y`-axis, given by: .. math:: R = \begin{bmatrix} \cos(\theta) & 0 & \sin(\theta) \\ 0 & 1 & 0 \\ -\sin(\theta) & 0 & \cos(\theta) \end{bmatrix} Examples ======== >>> from sympy import pi, rot_ccw_axis2 A rotation of pi/3 (60 degrees): >>> theta = pi/3 >>> rot_ccw_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_ccw_axis2(pi/2) Matrix([ [ 0, 0, 1], [ 0, 1, 0], [-1, 0, 0]]) See Also ======== rot_givens: Returns a Givens rotation matrix (generalized rotation for any number of dimensions) rot_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis (clockwise around the y axis) rot_ccw_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis (counterclockwise around the x axis) rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis (counterclockwise around the z axis) """ return rot_givens(0, 2, theta, dim=3) def rot_ccw_axis1(theta): r"""Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis. Explanation =========== For a right-handed coordinate system, this corresponds to a counterclockwise rotation around the `x`-axis, given by: .. math:: R = \begin{bmatrix} 1 & 0 & 0 \\ 0 & \cos(\theta) & -\sin(\theta) \\ 0 & \sin(\theta) & \cos(\theta) \end{bmatrix} Examples ======== >>> from sympy import pi, rot_ccw_axis1 A rotation of pi/3 (60 degrees): >>> theta = pi/3 >>> rot_ccw_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_ccw_axis1(pi/2) Matrix([ [1, 0, 0], [0, 0, -1], [0, 1, 0]]) See Also ======== rot_givens: Returns a Givens rotation matrix (generalized rotation for any number of dimensions) rot_axis1: Returns a rotation matrix for a rotation of theta (in radians) about the 1-axis (clockwise around the x axis) rot_ccw_axis2: Returns a rotation matrix for a rotation of theta (in radians) about the 2-axis (counterclockwise around the y axis) rot_ccw_axis3: Returns a rotation matrix for a rotation of theta (in radians) about the 3-axis (counterclockwise around the z axis) """ return rot_givens(2, 1, theta, dim=3) @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 .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 ========== .. [1] 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 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 import Matrix, matrix_multiply_elementwise >>> 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 import randMatrix >>> randMatrix(3) # doctest:+SKIP [25, 45, 27] [44, 54, 9] [23, 96, 46] >>> randMatrix(3, 2) # doctest:+SKIP [87, 29] [23, 37] [90, 26] >>> randMatrix(3, 3, 0, 2) # doctest:+SKIP [0, 2, 0] [2, 0, 1] [0, 0, 1] >>> randMatrix(3, symmetric=True) # doctest:+SKIP [85, 26, 29] [26, 71, 43] [29, 43, 57] >>> A = randMatrix(3, seed=1) >>> B = randMatrix(3, seed=2) >>> A == B False >>> A == randMatrix(3, seed=1) True >>> randMatrix(3, symmetric=True, percent=50) # doctest:+SKIP [77, 70, 0], [70, 0, 0], [ 0, 0, 88] """ # Note that ``Random()`` is equivalent to ``Random(None)`` prng = prng or random.Random(seed) if c is None: c = r if symmetric and r != c: raise ValueError('For symmetric matrices, r must equal c, but %i != %i' % (r, c)) ij = range(r * c) if percent != 100: ij = prng.sample(ij, int(len(ij)*percent // 100)) m = zeros(r, c) if not symmetric: for ijk in ij: i, j = divmod(ijk, c) m[i, j] = prng.randint(min, max) else: for ijk in ij: i, j = divmod(ijk, c) if i <= j: m[i, j] = m[j, i] = prng.randint(min, max) return m def wronskian(functions, var, method='bareiss'): """ Compute Wronskian for [] of functions :: | f1 f2 ... fn | | f1' f2' ... fn' | | . . . . | W(f1, ..., fn) = | . . . . | | . . . . | | (n) (n) (n) | | D (f1) D (f2) ... D (fn) | see: https://en.wikipedia.org/wiki/Wronskian See Also ======== sympy.matrices.matrices.MatrixCalculus.jacobian hessian """ functions = [sympify(f) for f in functions] n = len(functions) if n == 0: return S.One 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)
bbc25ccdd411351f0708b75949098e363baab118e34554ed5b1b36239313e5f6
import mpmath as mp from collections.abc import Callable from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.function import diff from sympy.core.expr import Expr from sympy.core.kind import _NumberKind, UndefinedKind from sympy.core.mul import Mul from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import Dummy, Symbol, uniquely_named_symbol from sympy.core.sympify import sympify, _sympify from sympy.functions.combinatorial.factorials import binomial, factorial from sympy.functions.elementary.complexes import re from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.miscellaneous import Max, Min, sqrt from sympy.functions.special.tensor_functions import KroneckerDelta, LeviCivita from sympy.polys import cancel from sympy.printing import sstr from sympy.printing.defaults import Printable from sympy.printing.str import StrPrinter from sympy.utilities.iterables import flatten, NotIterable, is_sequence, reshape from sympy.utilities.misc import as_int, filldedent from .common import ( MatrixCommon, MatrixError, NonSquareMatrixError, NonInvertibleMatrixError, ShapeError, MatrixKind, a2idx) from .utilities import _iszero, _is_zero_after_expand_mul, _simplify from .determinant import ( _find_reasonable_pivot, _find_reasonable_pivot_naive, _adjugate, _charpoly, _cofactor, _cofactor_matrix, _per, _det, _det_bareiss, _det_berkowitz, _det_LU, _minor, _minor_submatrix) from .reductions import _is_echelon, _echelon_form, _rank, _rref from .subspaces import _columnspace, _nullspace, _rowspace, _orthogonalize from .eigen import ( _eigenvals, _eigenvects, _bidiagonalize, _bidiagonal_decomposition, _is_diagonalizable, _diagonalize, _is_positive_definite, _is_positive_semidefinite, _is_negative_definite, _is_negative_semidefinite, _is_indefinite, _jordan_form, _left_eigenvects, _singular_values) from .decompositions import ( _rank_decomposition, _cholesky, _LDLdecomposition, _LUdecomposition, _LUdecomposition_Simple, _LUdecompositionFF, _singular_value_decomposition, _QRdecomposition, _upper_hessenberg_decomposition) from .graph import ( _connected_components, _connected_components_decomposition, _strongly_connected_components, _strongly_connected_components_decomposition) from .solvers import ( _diagonal_solve, _lower_triangular_solve, _upper_triangular_solve, _cholesky_solve, _LDLsolve, _LUsolve, _QRsolve, _gauss_jordan_solve, _pinv_solve, _solve, _solve_least_squares) from .inverse import ( _pinv, _inv_mod, _inv_ADJ, _inv_GE, _inv_LU, _inv_CH, _inv_LDL, _inv_QR, _inv, _inv_block) class DeferredVector(Symbol, NotIterable): """A vector whose components are deferred (e.g. for use with lambdify). Examples ======== >>> from sympy import DeferredVector, lambdify >>> X = DeferredVector( 'X' ) >>> X X >>> expr = (X[0] + 2, X[2] + 3) >>> func = lambdify( X, expr) >>> func( [1, 2, 3] ) (3, 6) """ def __getitem__(self, i): if i == -0: i = 0 if i < 0: raise IndexError('DeferredVector index out of range') component_name = '%s[%d]' % (self.name, i) return Symbol(component_name) def __str__(self): return sstr(self) def __repr__(self): return "DeferredVector('%s')" % self.name class MatrixDeterminant(MatrixCommon): """Provides basic matrix determinant operations. Should not be instantiated directly. See ``determinant.py`` for their implementations.""" def _eval_det_bareiss(self, iszerofunc=_is_zero_after_expand_mul): return _det_bareiss(self, iszerofunc=iszerofunc) def _eval_det_berkowitz(self): return _det_berkowitz(self) def _eval_det_lu(self, iszerofunc=_iszero, simpfunc=None): return _det_LU(self, iszerofunc=iszerofunc, simpfunc=simpfunc) def _eval_determinant(self): # for expressions.determinant.Determinant return _det(self) def adjugate(self, method="berkowitz"): return _adjugate(self, method=method) def charpoly(self, x='lambda', simplify=_simplify): return _charpoly(self, x=x, simplify=simplify) def cofactor(self, i, j, method="berkowitz"): return _cofactor(self, i, j, method=method) def cofactor_matrix(self, method="berkowitz"): return _cofactor_matrix(self, method=method) def det(self, method="bareiss", iszerofunc=None): return _det(self, method=method, iszerofunc=iszerofunc) def per(self): return _per(self) def minor(self, i, j, method="berkowitz"): return _minor(self, i, j, method=method) def minor_submatrix(self, i, j): return _minor_submatrix(self, i, j) _find_reasonable_pivot.__doc__ = _find_reasonable_pivot.__doc__ _find_reasonable_pivot_naive.__doc__ = _find_reasonable_pivot_naive.__doc__ _eval_det_bareiss.__doc__ = _det_bareiss.__doc__ _eval_det_berkowitz.__doc__ = _det_berkowitz.__doc__ _eval_det_lu.__doc__ = _det_LU.__doc__ _eval_determinant.__doc__ = _det.__doc__ adjugate.__doc__ = _adjugate.__doc__ charpoly.__doc__ = _charpoly.__doc__ cofactor.__doc__ = _cofactor.__doc__ cofactor_matrix.__doc__ = _cofactor_matrix.__doc__ det.__doc__ = _det.__doc__ per.__doc__ = _per.__doc__ minor.__doc__ = _minor.__doc__ minor_submatrix.__doc__ = _minor_submatrix.__doc__ class MatrixReductions(MatrixDeterminant): """Provides basic matrix row/column operations. Should not be instantiated directly. See ``reductions.py`` for some of their implementations.""" def echelon_form(self, iszerofunc=_iszero, simplify=False, with_pivots=False): return _echelon_form(self, iszerofunc=iszerofunc, simplify=simplify, with_pivots=with_pivots) @property def is_echelon(self): return _is_echelon(self) def rank(self, iszerofunc=_iszero, simplify=False): return _rank(self, iszerofunc=iszerofunc, simplify=simplify) def rref(self, iszerofunc=_iszero, simplify=False, pivots=True, normalize_last=True): return _rref(self, iszerofunc=iszerofunc, simplify=simplify, pivots=pivots, normalize_last=normalize_last) echelon_form.__doc__ = _echelon_form.__doc__ is_echelon.__doc__ = _is_echelon.__doc__ rank.__doc__ = _rank.__doc__ rref.__doc__ = _rref.__doc__ def _normalize_op_args(self, op, col, k, col1, col2, error_str="col"): """Validate the arguments for a row/column operation. ``error_str`` can be one of "row" or "col" depending on the arguments being parsed.""" if op not in ["n->kn", "n<->m", "n->n+km"]: raise ValueError("Unknown {} operation '{}'. Valid col operations " "are 'n->kn', 'n<->m', 'n->n+km'".format(error_str, op)) # define self_col according to error_str self_cols = self.cols if error_str == 'col' else self.rows # normalize and validate the arguments if op == "n->kn": col = col if col is not None else col1 if col is None or k is None: raise ValueError("For a {0} operation 'n->kn' you must provide the " "kwargs `{0}` and `k`".format(error_str)) if not 0 <= col < self_cols: raise ValueError("This matrix does not have a {} '{}'".format(error_str, col)) elif op == "n<->m": # we need two cols to swap. It does not 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 does not have a {} '{}'".format(error_str, col1)) if not 0 <= col2 < self_cols: raise ValueError("This matrix does not 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 does not have a {} '{}'".format(error_str, col)) if not 0 <= col2 < self_cols: raise ValueError("This matrix does not 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 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 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 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 berkowitz_charpoly(self, x=Dummy('lambda'), simplify=_simplify): return self.charpoly(x=x) def berkowitz_det(self): """Computes determinant using Berkowitz method. See Also ======== det berkowitz """ return self.det(method='berkowitz') def berkowitz_eigenvals(self, **flags): """Computes eigenvalues of a Matrix using Berkowitz method. See Also ======== berkowitz """ return self.eigenvals(**flags) def berkowitz_minors(self): """Computes principal minors using Berkowitz method. See Also ======== berkowitz """ sign, minors = self.one, [] for poly in self.berkowitz(): minors.append(sign * poly[-1]) sign = -sign return tuple(minors) def berkowitz(self): from sympy.matrices import zeros berk = ((1,),) if not self: return berk if not self.is_square: raise NonSquareMatrixError() A, N = self, self.rows transforms = [0] * (N - 1) for n in range(N, 1, -1): T, k = zeros(n + 1, n), n - 1 R, C = -A[k, :k], A[:k, k] A, a = A[:k, :k], -A[k, k] items = [C] for i in range(0, n - 2): items.append(A * items[i]) for i, B in enumerate(items): items[i] = (R * B)[0, 0] items = [self.one, a] + items for i in range(n): T[i:, i] = items[:n - i + 1] transforms[k - 1] = T polys = [self._new([self.one, -A[0, 0]])] for i, T in enumerate(transforms): polys.append(T * polys[i]) return berk + tuple(map(tuple, polys)) def cofactorMatrix(self, method="berkowitz"): return self.cofactor_matrix(method=method) def det_bareis(self): return _det_bareiss(self) def det_LU_decomposition(self): """Compute matrix determinant using LU decomposition. Note that this method fails if the LU decomposition itself fails. In particular, if the matrix has no inverse this method will fail. TODO: Implement algorithm for sparse matrices (SFF), http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps. See Also ======== det det_bareiss berkowitz_det """ return self.det(method='lu') def jordan_cell(self, eigenval, n): return self.jordan_block(size=n, eigenvalue=eigenval) def jordan_cells(self, calc_transformation=True): P, J = self.jordan_form() return P, J.get_diag_blocks() def minorEntry(self, i, j, method="berkowitz"): return self.minor(i, j, method=method) def minorMatrix(self, i, j): return self.minor_submatrix(i, j) def permuteBkwd(self, perm): """Permute the rows of the matrix with the given permutation in reverse.""" return self.permute_rows(perm, direction='backward') def permuteFwd(self, perm): """Permute the rows of the matrix with the given permutation.""" return self.permute_rows(perm, direction='forward') @Mul._kind_dispatcher.register(_NumberKind, MatrixKind) def num_mat_mul(k1, k2): """ Return MatrixKind. The element kind is selected by recursive dispatching. Do not need to dispatch in reversed order because KindDispatcher searches for this automatically. """ # Deal with Mul._kind_dispatcher's commutativity # XXX: this function is called with either k1 or k2 as MatrixKind because # the Mul kind dispatcher is commutative. Maybe it shouldn't be. Need to # swap the args here because NumberKind does not have an element_kind # attribute. if not isinstance(k2, MatrixKind): k1, k2 = k2, k1 elemk = Mul._kind_dispatcher(k1, k2.element_kind) return MatrixKind(elemk) @Mul._kind_dispatcher.register(MatrixKind, MatrixKind) def mat_mat_mul(k1, k2): """ Return MatrixKind. The element kind is selected by recursive dispatching. """ elemk = Mul._kind_dispatcher(k1.element_kind, k2.element_kind) return MatrixKind(elemk) class MatrixBase(MatrixDeprecated, MatrixCalculus, MatrixEigen, MatrixCommon, Printable): """Base class for matrix objects.""" # Added just for numpy compatibility __array_priority__ = 11 is_Matrix = True _class_priority = 3 _sympify = staticmethod(sympify) zero = S.Zero one = S.One @property def kind(self) -> MatrixKind: elem_kinds = set(e.kind for e in self.flat()) if len(elem_kinds) == 1: elemkind, = elem_kinds else: elemkind = UndefinedKind return MatrixKind(elemkind) def flat(self): return [self[i, j] for i in range(self.rows) for j in range(self.cols)] 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 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 S.Zero in self.shape: return 'Matrix(%s, %s, [])' % (self.rows, self.cols) return "Matrix(%s)" % str(self.tolist()) def _format_str(self, printer=None): if not printer: printer = StrPrinter() # Handle zero dimensions: if S.Zero in self.shape: 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]]) """ 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 import SparseMatrix from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.blockmatrix import BlockMatrix 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].flat() # 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().flat() 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 make_explicit(x): """make Block and Symbol explicit""" if isinstance(x, BlockMatrix): return x.as_explicit() elif isinstance(x, MatrixSymbol) and all(_.is_Integer for _ in x.shape): return x.as_explicit() else: return x def make_explicit_row(row): # Could be list or could be list of lists if isinstance(row, (list, tuple)): return [make_explicit(x) for x in row] else: return make_explicit(row) if isinstance(dat, (list, tuple)): dat = [make_explicit_row(row) for row in dat] if dat in ([], [[]]): 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([cls._sympify(ij) for ij in 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 isinstance(i, slice) or isinstance(j, 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.flat()) 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, 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)) if (1 not in self.shape) or (1 not in b.shape): raise ShapeError if len(self) != len(b): raise ShapeError( "Dimensions incorrect for dot product: %s, %s" % (self.shape, b.shape)) mat = self 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. A dual of a matrix 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.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 """ 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 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 """ 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 """ 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 S.One in self.shape: if ord in (2, 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 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, 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 S.Zero in self.shape: return '[]' # Build table of string representations of the elements res = [] # Track per-column max lengths for pretty alignment maxlen = [0] * self.cols for i in range(self.rows): res.append([]) for j in range(self.cols): s = printer._print(self[i, j]) res[-1].append(s) maxlen[j] = max(len(s), maxlen[j]) # Patch strings together align = { 'left': 'ljust', 'right': 'rjust', 'center': 'center', '<': 'ljust', '>': 'rjust', '^': 'center', }[align] for i, row in enumerate(res): for j, elem in enumerate(row): row[j] = getattr(elem, align)(maxlen[j]) res[i] = rowstart + colsep.join(row) + rowend return rowsep.join(res) def rank_decomposition(self, iszerofunc=_iszero, simplify=False): return _rank_decomposition(self, iszerofunc=iszerofunc, simplify=simplify) def cholesky(self, hermitian=True): raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix') def LDLdecomposition(self, hermitian=True): raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix') def LUdecomposition(self, iszerofunc=_iszero, simpfunc=None, rankcheck=False): return _LUdecomposition(self, iszerofunc=iszerofunc, simpfunc=simpfunc, rankcheck=rankcheck) def LUdecomposition_Simple(self, iszerofunc=_iszero, simpfunc=None, rankcheck=False): return _LUdecomposition_Simple(self, iszerofunc=iszerofunc, simpfunc=simpfunc, rankcheck=rankcheck) def LUdecompositionFF(self): return _LUdecompositionFF(self) def singular_value_decomposition(self): return _singular_value_decomposition(self) def QRdecomposition(self): return _QRdecomposition(self) def upper_hessenberg_decomposition(self): return _upper_hessenberg_decomposition(self) def diagonal_solve(self, rhs): return _diagonal_solve(self, rhs) def lower_triangular_solve(self, rhs): raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix') def upper_triangular_solve(self, rhs): raise NotImplementedError('This function is implemented in DenseMatrix or SparseMatrix') def cholesky_solve(self, rhs): return _cholesky_solve(self, rhs) def LDLsolve(self, rhs): return _LDLsolve(self, rhs) def LUsolve(self, rhs, iszerofunc=_iszero): return _LUsolve(self, rhs, iszerofunc=iszerofunc) def QRsolve(self, b): return _QRsolve(self, b) def gauss_jordan_solve(self, B, freevar=False): return _gauss_jordan_solve(self, B, freevar=freevar) def pinv_solve(self, B, arbitrary_matrix=None): return _pinv_solve(self, B, arbitrary_matrix=arbitrary_matrix) def solve(self, rhs, method='GJ'): return _solve(self, rhs, method=method) def solve_least_squares(self, rhs, method='CH'): return _solve_least_squares(self, rhs, method=method) def pinv(self, method='RD'): return _pinv(self, method=method) def inv_mod(self, m): return _inv_mod(self, m) def inverse_ADJ(self, iszerofunc=_iszero): return _inv_ADJ(self, iszerofunc=iszerofunc) def inverse_BLOCK(self, iszerofunc=_iszero): return _inv_block(self, iszerofunc=iszerofunc) def inverse_GE(self, iszerofunc=_iszero): return _inv_GE(self, iszerofunc=iszerofunc) def inverse_LU(self, iszerofunc=_iszero): return _inv_LU(self, iszerofunc=iszerofunc) def inverse_CH(self, iszerofunc=_iszero): return _inv_CH(self, iszerofunc=iszerofunc) def inverse_LDL(self, iszerofunc=_iszero): return _inv_LDL(self, iszerofunc=iszerofunc) def inverse_QR(self, iszerofunc=_iszero): return _inv_QR(self, iszerofunc=iszerofunc) def inv(self, method=None, iszerofunc=_iszero, try_block_diag=False): return _inv(self, method=method, iszerofunc=iszerofunc, try_block_diag=try_block_diag) def connected_components(self): return _connected_components(self) def connected_components_decomposition(self): return _connected_components_decomposition(self) def strongly_connected_components(self): return _strongly_connected_components(self) def strongly_connected_components_decomposition(self, lower=True): return _strongly_connected_components_decomposition(self, lower=lower) _sage_ = Basic._sage_ rank_decomposition.__doc__ = _rank_decomposition.__doc__ cholesky.__doc__ = _cholesky.__doc__ LDLdecomposition.__doc__ = _LDLdecomposition.__doc__ LUdecomposition.__doc__ = _LUdecomposition.__doc__ LUdecomposition_Simple.__doc__ = _LUdecomposition_Simple.__doc__ LUdecompositionFF.__doc__ = _LUdecompositionFF.__doc__ singular_value_decomposition.__doc__ = _singular_value_decomposition.__doc__ QRdecomposition.__doc__ = _QRdecomposition.__doc__ upper_hessenberg_decomposition.__doc__ = _upper_hessenberg_decomposition.__doc__ diagonal_solve.__doc__ = _diagonal_solve.__doc__ lower_triangular_solve.__doc__ = _lower_triangular_solve.__doc__ upper_triangular_solve.__doc__ = _upper_triangular_solve.__doc__ cholesky_solve.__doc__ = _cholesky_solve.__doc__ LDLsolve.__doc__ = _LDLsolve.__doc__ LUsolve.__doc__ = _LUsolve.__doc__ QRsolve.__doc__ = _QRsolve.__doc__ gauss_jordan_solve.__doc__ = _gauss_jordan_solve.__doc__ pinv_solve.__doc__ = _pinv_solve.__doc__ solve.__doc__ = _solve.__doc__ solve_least_squares.__doc__ = _solve_least_squares.__doc__ pinv.__doc__ = _pinv.__doc__ inv_mod.__doc__ = _inv_mod.__doc__ inverse_ADJ.__doc__ = _inv_ADJ.__doc__ inverse_GE.__doc__ = _inv_GE.__doc__ inverse_LU.__doc__ = _inv_LU.__doc__ inverse_CH.__doc__ = _inv_CH.__doc__ inverse_LDL.__doc__ = _inv_LDL.__doc__ inverse_QR.__doc__ = _inv_QR.__doc__ inverse_BLOCK.__doc__ = _inv_block.__doc__ inv.__doc__ = _inv.__doc__ connected_components.__doc__ = _connected_components.__doc__ connected_components_decomposition.__doc__ = \ _connected_components_decomposition.__doc__ strongly_connected_components.__doc__ = \ _strongly_connected_components.__doc__ strongly_connected_components_decomposition.__doc__ = \ _strongly_connected_components_decomposition.__doc__
069ed4c1f7c830eee873c527155d75c9819c5d48d26b4361b2e3a041a35132df
from sympy.concrete.summations import Sum from sympy.core.basic import Basic from sympy.core.containers import Tuple from sympy.core.function import Lambda from sympy.core.numbers import (Rational, nan, oo, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.combinatorial.factorials import (FallingFactorial, binomial) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.delta_functions import DiracDelta from sympy.integrals.integrals import integrate from sympy.logic.boolalg import (And, Or) from sympy.matrices.dense import Matrix from sympy.sets.sets import Interval from sympy.tensor.indexed import Indexed 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, cmoment, moment, median) 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, warns_deprecated_sympy from sympy.external import import_module from sympy.core.numbers import comp from sympy.stats.frv_types import BernoulliDistribution from sympy.core.symbol import Dummy from sympy.functions.elementary.piecewise import Piecewise def test_where(): X, Y = Die('X'), Die('Y') Z = Normal('Z', 0, 1) assert where(Z**2 <= 1).set == Interval(-1, 1) assert where(Z**2 <= 1).as_boolean() == Interval(-1, 1).as_relational(Z.symbol) assert where(And(X > Y, Y > 4)).as_boolean() == And( Eq(X.symbol, 6), Eq(Y.symbol, 5)) assert len(where(X < 3).set) == 2 assert 1 in where(X < 3).set X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) assert where(And(X**2 <= 1, X >= 0)).set == Interval(0, 1) XX = given(X, And(X**2 <= 1, X >= 0)) assert XX.pspace.domain.set == Interval(0, 1) assert XX.pspace.domain.as_boolean() == \ And(0 <= X.symbol, X.symbol**2 <= 1, -oo < X.symbol, X.symbol < oo) with raises(TypeError): XX = given(X, X + 3) def test_random_symbols(): X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) assert set(random_symbols(2*X + 1)) == {X} assert set(random_symbols(2*X + Y)) == {X, Y} assert set(random_symbols(2*X + Y.symbol)) == {X} assert set(random_symbols(2)) == set() def test_characteristic_function(): # Imports I from sympy from sympy.core.numbers import I X = Normal('X',0,1) Y = DiscreteUniform('Y', [1,2,7]) Z = Poisson('Z', 2) t = symbols('_t') P = Lambda(t, exp(-t**2/2)) Q = Lambda(t, exp(7*t*I)/3 + exp(2*t*I)/3 + exp(t*I)/3) R = Lambda(t, exp(2 * exp(t*I) - 2)) assert characteristic_function(X).dummy_eq(P) assert characteristic_function(Y).dummy_eq(Q) assert characteristic_function(Z).dummy_eq(R) def test_moment_generating_function(): X = Normal('X',0,1) Y = DiscreteUniform('Y', [1,2,7]) Z = Poisson('Z', 2) t = symbols('_t') P = Lambda(t, exp(t**2/2)) Q = Lambda(t, (exp(7*t)/3 + exp(2*t)/3 + exp(t)/3)) R = Lambda(t, exp(2 * exp(t) - 2)) assert moment_generating_function(X).dummy_eq(P) assert moment_generating_function(Y).dummy_eq(Q) assert moment_generating_function(Z).dummy_eq(R) def test_sample_iter(): X = Normal('X',0,1) Y = DiscreteUniform('Y', [1, 2, 7]) Z = Poisson('Z', 2) scipy = import_module('scipy') if not scipy: skip('Scipy is not installed. Abort tests') expr = X**2 + 3 iterator = sample_iter(expr) expr2 = Y**2 + 5*Y + 4 iterator2 = sample_iter(expr2) expr3 = Z**3 + 4 iterator3 = sample_iter(expr3) def is_iterator(obj): if ( hasattr(obj, '__iter__') and (hasattr(obj, 'next') or hasattr(obj, '__next__')) and callable(obj.__iter__) and obj.__iter__() is obj ): return True else: return False assert is_iterator(iterator) assert is_iterator(iterator2) assert is_iterator(iterator3) def test_pspace(): X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) x = Symbol('x') raises(ValueError, lambda: pspace(5 + 3)) raises(ValueError, lambda: pspace(x < 1)) assert pspace(X) == X.pspace assert pspace(2*X + 1) == X.pspace assert pspace(2*X + Y) == IndependentProductPSpace(Y.pspace, X.pspace) def test_rs_swap(): X = Normal('x', 0, 1) Y = Exponential('y', 1) XX = Normal('x', 0, 2) YY = Normal('y', 0, 3) expr = 2*X + Y assert expr.subs(rs_swap((X, Y), (YY, XX))) == 2*XX + YY def test_RandomSymbol(): X = Normal('x', 0, 1) Y = Normal('x', 0, 2) assert X.symbol == Y.symbol assert X != Y assert X.name == X.symbol.name X = Normal('lambda', 0, 1) # make sure we can use protected terms X = Normal('Lambda', 0, 1) # make sure we can use SymPy terms def test_RandomSymbol_diff(): X = Normal('x', 0, 1) assert (2*X).diff(X) def test_random_symbol_no_pspace(): x = RandomSymbol(Symbol('x')) assert x.pspace == PSpace() def test_overlap(): X = Normal('x', 0, 1) Y = Normal('x', 0, 2) raises(ValueError, lambda: P(X > Y)) def test_IndependentProductPSpace(): X = Normal('X', 0, 1) Y = Normal('Y', 0, 1) px = X.pspace py = Y.pspace assert pspace(X + Y) == IndependentProductPSpace(px, py) assert pspace(X + Y) == IndependentProductPSpace(py, px) def test_E(): assert E(5) == 5 def test_H(): X = Normal('X', 0, 1) D = Die('D', sides = 4) G = Geometric('G', 0.5) assert H(X, X > 0) == -log(2)/2 + S.Half + log(pi)/2 assert H(D, D > 2) == log(2) assert comp(H(G).evalf().round(2), 1.39) def test_Sample(): X = Die('X', 6) Y = Normal('Y', 0, 1) z = Symbol('z', integer=True) scipy = import_module('scipy') if not scipy: skip('Scipy is not installed. Abort tests') assert sample(X) in [1, 2, 3, 4, 5, 6] assert isinstance(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.0 assert P(sin(Y) <= 1, cos(Y) < 1, numsamples=10) == 1.0 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)) numpy = import_module('numpy') if not numpy: skip('Numpy is not installed. Abort tests') #Test Issue #21563: Output of sample must be a float or array assert isinstance(sample(X), (numpy.int32, numpy.int64)) assert isinstance(sample(Y), numpy.float64) assert isinstance(sample(X, size=2), numpy.ndarray) with warns_deprecated_sympy(): sample(X, numsamples=2) @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) z = Symbol('z', real=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(S(1), S(2)) assert a.foo == 1 assert a.bar == 2 raises(AttributeError, lambda: a.baz) class Bar(Basic, NamedArgsMixin): pass raises(AttributeError, lambda: Bar(S(1), S(2)).foo) def test_density_constant(): assert density(3)(2) == 0 assert density(3)(3) == DiracDelta(0) def test_cmoment_constant(): assert variance(3) == 0 assert cmoment(3, 3) == 0 assert cmoment(3, 4) == 0 x = Symbol('x') assert variance(x) == 0 assert cmoment(x, 15) == 0 assert cmoment(x, 0) == 1 def test_moment_constant(): assert moment(3, 0) == 1 assert moment(3, 1) == 3 assert moment(3, 2) == 9 x = Symbol('x') assert moment(x, 2) == x**2 def test_median_constant(): assert median(3) == 3 x = Symbol('x') assert median(x) == x def test_real(): x = Normal('x', 0, 1) assert x.is_real def test_issue_10052(): X = Exponential('X', 3) assert P(X < oo) == 1 assert P(X > oo) == 0 assert P(X < 2, X > oo) == 0 assert P(X < oo, X > oo) == 0 assert P(X < oo, X > 2) == 1 assert P(X < 3, X == 2) == 0 raises(ValueError, lambda: P(1)) raises(ValueError, lambda: P(X < 1, 2)) def test_issue_11934(): density = {0: .5, 1: .5} X = FiniteRV('X', density) assert E(X) == 0.5 assert P( X>= 2) == 0 def test_issue_8129(): X = Exponential('X', 4) assert P(X >= X) == 1 assert P(X > X) == 0 assert P(X > X+1) == 0 def test_issue_12237(): X = Normal('X', 0, 1) Y = Normal('Y', 0, 1) U = P(X > 0, X) V = P(Y < 0, X) W = P(X + Y > 0, X) assert W == P(X + Y > 0, X) assert U == BernoulliDistribution(S.Half, S.Zero, S.One) assert V == S.Half def test_is_random(): X = Normal('X', 0, 1) Y = Normal('Y', 0, 1) a, b = symbols('a, b') G = GaussianUnitaryEnsemble('U', 2) B = BernoulliProcess('B', 0.9) assert not is_random(a) assert not is_random(a + b) assert not is_random(a * b) assert not is_random(Matrix([a**2, b**2])) assert is_random(X) assert is_random(X**2 + Y) assert is_random(Y + b**2) assert is_random(Y > 5) assert is_random(B[3] < 1) assert is_random(G) assert is_random(X * Y * B[1]) assert is_random(Matrix([[X, B[2]], [G, Y]])) assert is_random(Eq(X, 4)) def test_issue_12283(): x = symbols('x') X = RandomSymbol(x) Y = RandomSymbol('Y') Z = RandomMatrixSymbol('Z', 2, 1) W = RandomMatrixSymbol('W', 2, 1) RI = RandomIndexedSymbol(Indexed('RI', 3)) assert pspace(Z) == PSpace() assert pspace(RI) == PSpace() assert pspace(X) == PSpace() assert E(X) == Expectation(X) assert P(Y > 3) == Probability(Y > 3) assert variance(X) == Variance(X) assert variance(RI) == Variance(RI) assert covariance(X, Y) == Covariance(X, Y) assert covariance(W, Z) == Covariance(W, Z) def test_issue_6810(): X = Die('X', 6) Y = Normal('Y', 0, 1) assert P(Eq(X, 2)) == S(1)/6 assert P(Eq(Y, 0)) == 0 assert P(Or(X > 2, X < 3)) == 1 assert P(And(X > 3, X > 2)) == S(1)/2 def test_issue_20286(): n, p = symbols('n p') B = Binomial('B', n, p) k = Dummy('k', integer = True) eq = Sum(Piecewise((-p**k*(1 - p)**(-k + n)*log(p**k*(1 - p)**(-k + n)*binomial(n, k))*binomial(n, k), (k >= 0) & (k <= n)), (nan, True)), (k, 0, n)) assert eq.dummy_eq(H(B))
5b6f2b09161ccefe496b1ee4f9b8fb3af793fb2f803f8abe911474f8b35a597d
from sympy.concrete.products import Product from sympy.concrete.summations import Sum from sympy.core.numbers import (Rational, oo, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.combinatorial.factorials import (RisingFactorial, factorial) from sympy.functions.elementary.complexes import polar_lift from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.bessel import besselk from sympy.functions.special.gamma_functions import gamma from sympy.matrices.dense import eye from sympy.matrices.expressions.determinant import Determinant from sympy.sets.fancysets import Range from sympy.sets.sets import (Interval, ProductSet) from sympy.simplify.simplify import simplify from sympy.tensor.indexed import (Indexed, IndexedBase) from sympy.core.numbers import comp from sympy.integrals.integrals import integrate from sympy.matrices import Matrix, MatrixSymbol from sympy.matrices.expressions.matexpr import MatrixElement from sympy.stats import density, median, marginal_distribution, Normal, Laplace, E, sample from sympy.stats.joint_rv_types import (JointRV, MultivariateNormalDistribution, JointDistributionHandmade, MultivariateT, NormalGamma, GeneralizedMultivariateLogGammaOmega as GMVLGO, MultivariateBeta, GeneralizedMultivariateLogGamma as GMVLG, MultivariateEwens, Multinomial, NegativeMultinomial, MultivariateNormal, MultivariateLaplace) from sympy.testing.pytest import raises, XFAIL, skip, slow from sympy.external import import_module from sympy.abc import x, y def test_Normal(): m = Normal('A', [1, 2], [[1, 0], [0, 1]]) A = MultivariateNormal('A', [1, 2], [[1, 0], [0, 1]]) assert m == A assert density(m)(1, 2) == 1/(2*pi) assert m.pspace.distribution.set == ProductSet(S.Reals, S.Reals) raises (ValueError, lambda:m[2]) n = Normal('B', [1, 2, 3], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) p = Normal('C', Matrix([1, 2]), Matrix([[1, 0], [0, 1]])) assert density(m)(x, y) == density(p)(x, y) assert marginal_distribution(n, 0, 1)(1, 2) == 1/(2*pi) raises(ValueError, lambda: marginal_distribution(m)) assert integrate(density(m)(x, y), (x, -oo, oo), (y, -oo, oo)).evalf() == 1.0 N = Normal('N', [1, 2], [[x, 0], [0, y]]) assert density(N)(0, 0) == exp(-((4*x + y)/(2*x*y)))/(2*pi*sqrt(x*y)) raises (ValueError, lambda: Normal('M', [1, 2], [[1, 1], [1, -1]])) # symbolic n = symbols('n', integer=True, positive=True) mu = MatrixSymbol('mu', n, 1) sigma = MatrixSymbol('sigma', n, n) X = Normal('X', mu, sigma) assert density(X) == MultivariateNormalDistribution(mu, sigma) raises (NotImplementedError, lambda: median(m)) # Below tests should work after issue #17267 is resolved # assert E(X) == mu # assert variance(X) == sigma # test symbolic multivariate normal densities n = 3 Sg = MatrixSymbol('Sg', n, n) mu = MatrixSymbol('mu', n, 1) obs = MatrixSymbol('obs', n, 1) X = MultivariateNormal('X', mu, Sg) density_X = density(X) eval_a = density_X(obs).subs({Sg: eye(3), mu: Matrix([0, 0, 0]), obs: Matrix([0, 0, 0])}).doit() eval_b = density_X(0, 0, 0).subs({Sg: eye(3), mu: Matrix([0, 0, 0])}).doit() assert eval_a == sqrt(2)/(4*pi**Rational(3/2)) assert eval_b == sqrt(2)/(4*pi**Rational(3/2)) n = symbols('n', integer=True, positive=True) Sg = MatrixSymbol('Sg', n, n) mu = MatrixSymbol('mu', n, 1) obs = MatrixSymbol('obs', n, 1) X = MultivariateNormal('X', mu, Sg) density_X_at_obs = density(X)(obs) expected_density = MatrixElement( exp((S(1)/2) * (mu.T - obs.T) * Sg**(-1) * (-mu + obs)) / \ sqrt((2*pi)**n * Determinant(Sg)), 0, 0) assert density_X_at_obs == expected_density def test_MultivariateTDist(): t1 = MultivariateT('T', [0, 0], [[1, 0], [0, 1]], 2) assert(density(t1))(1, 1) == 1/(8*pi) assert t1.pspace.distribution.set == ProductSet(S.Reals, S.Reals) assert integrate(density(t1)(x, y), (x, -oo, oo), \ (y, -oo, oo)).evalf() == 1.0 raises(ValueError, lambda: MultivariateT('T', [1, 2], [[1, 1], [1, -1]], 1)) t2 = MultivariateT('t2', [1, 2], [[x, 0], [0, y]], 1) assert density(t2)(1, 2) == 1/(2*pi*sqrt(x*y)) def test_multivariate_laplace(): raises(ValueError, lambda: Laplace('T', [1, 2], [[1, 2], [2, 1]])) L = Laplace('L', [1, 0], [[1, 0], [0, 1]]) L2 = MultivariateLaplace('L2', [1, 0], [[1, 0], [0, 1]]) assert density(L)(2, 3) == exp(2)*besselk(0, sqrt(39))/pi L1 = Laplace('L1', [1, 2], [[x, 0], [0, y]]) assert density(L1)(0, 1) == \ exp(2/y)*besselk(0, sqrt((2 + 4/y + 1/x)/y))/(pi*sqrt(x*y)) assert L.pspace.distribution.set == ProductSet(S.Reals, S.Reals) assert L.pspace.distribution == L2.pspace.distribution def test_NormalGamma(): ng = NormalGamma('G', 1, 2, 3, 4) assert density(ng)(1, 1) == 32*exp(-4)/sqrt(pi) assert ng.pspace.distribution.set == ProductSet(S.Reals, Interval(0, oo)) raises(ValueError, lambda:NormalGamma('G', 1, 2, 3, -1)) assert marginal_distribution(ng, 0)(1) == \ 3*sqrt(10)*gamma(Rational(7, 4))/(10*sqrt(pi)*gamma(Rational(5, 4))) assert marginal_distribution(ng, y)(1) == exp(Rational(-1, 4))/128 assert marginal_distribution(ng,[0,1])(x) == x**2*exp(-x/4)/128 def test_GeneralizedMultivariateLogGammaDistribution(): h = S.Half omega = Matrix([[1, h, h, h], [h, 1, h, h], [h, h, 1, h], [h, h, h, 1]]) v, l, mu = (4, [1, 2, 3, 4], [1, 2, 3, 4]) y_1, y_2, y_3, y_4 = symbols('y_1:5', real=True) delta = symbols('d', positive=True) G = GMVLGO('G', omega, v, l, mu) Gd = GMVLG('Gd', delta, v, l, mu) dend = ("d**4*Sum(4*24**(-n - 4)*(1 - d)**n*exp((n + 4)*(y_1 + 2*y_2 + 3*y_3 " "+ 4*y_4) - exp(y_1) - exp(2*y_2)/2 - exp(3*y_3)/3 - exp(4*y_4)/4)/" "(gamma(n + 1)*gamma(n + 4)**3), (n, 0, oo))") assert str(density(Gd)(y_1, y_2, y_3, y_4)) == dend den = ("5*2**(2/3)*5**(1/3)*Sum(4*24**(-n - 4)*(-2**(2/3)*5**(1/3)/4 + 1)**n*" "exp((n + 4)*(y_1 + 2*y_2 + 3*y_3 + 4*y_4) - exp(y_1) - exp(2*y_2)/2 - " "exp(3*y_3)/3 - exp(4*y_4)/4)/(gamma(n + 1)*gamma(n + 4)**3), (n, 0, oo))/64") assert str(density(G)(y_1, y_2, y_3, y_4)) == den marg = ("5*2**(2/3)*5**(1/3)*exp(4*y_1)*exp(-exp(y_1))*Integral(exp(-exp(4*G[3])" "/4)*exp(16*G[3])*Integral(exp(-exp(3*G[2])/3)*exp(12*G[2])*Integral(exp(" "-exp(2*G[1])/2)*exp(8*G[1])*Sum((-1/4)**n*(-4 + 2**(2/3)*5**(1/3" "))**n*exp(n*y_1)*exp(2*n*G[1])*exp(3*n*G[2])*exp(4*n*G[3])/(24**n*gamma(n + 1)" "*gamma(n + 4)**3), (n, 0, oo)), (G[1], -oo, oo)), (G[2], -oo, oo)), (G[3]" ", -oo, oo))/5308416") assert str(marginal_distribution(G, G[0])(y_1)) == marg omega_f1 = Matrix([[1, h, h]]) omega_f2 = Matrix([[1, h, h, h], [h, 1, 2, h], [h, h, 1, h], [h, h, h, 1]]) omega_f3 = Matrix([[6, h, h, h], [h, 1, 2, h], [h, h, 1, h], [h, h, h, 1]]) v_f = symbols("v_f", positive=False, real=True) l_f = [1, 2, v_f, 4] m_f = [v_f, 2, 3, 4] omega_f4 = Matrix([[1, h, h, h, h], [h, 1, h, h, h], [h, h, 1, h, h], [h, h, h, 1, h], [h, h, h, h, 1]]) l_f1 = [1, 2, 3, 4, 5] omega_f5 = Matrix([[1]]) mu_f5 = l_f5 = [1] raises(ValueError, lambda: GMVLGO('G', omega_f1, v, l, mu)) raises(ValueError, lambda: GMVLGO('G', omega_f2, v, l, mu)) raises(ValueError, lambda: GMVLGO('G', omega_f3, v, l, mu)) raises(ValueError, lambda: GMVLGO('G', omega, v_f, l, mu)) raises(ValueError, lambda: GMVLGO('G', omega, v, l_f, mu)) raises(ValueError, lambda: GMVLGO('G', omega, v, l, m_f)) raises(ValueError, lambda: GMVLGO('G', omega_f4, v, l, mu)) raises(ValueError, lambda: GMVLGO('G', omega, v, l_f1, mu)) raises(ValueError, lambda: GMVLGO('G', omega_f5, v, l_f5, mu_f5)) raises(ValueError, lambda: GMVLG('G', Rational(3, 2), v, l, mu)) def test_MultivariateBeta(): a1, a2 = symbols('a1, a2', positive=True) a1_f, a2_f = symbols('a1, a2', positive=False, real=True) mb = MultivariateBeta('B', [a1, a2]) mb_c = MultivariateBeta('C', a1, a2) assert density(mb)(1, 2) == S(2)**(a2 - 1)*gamma(a1 + a2)/\ (gamma(a1)*gamma(a2)) assert marginal_distribution(mb_c, 0)(3) == S(3)**(a1 - 1)*gamma(a1 + a2)/\ (a2*gamma(a1)*gamma(a2)) raises(ValueError, lambda: MultivariateBeta('b1', [a1_f, a2])) raises(ValueError, lambda: MultivariateBeta('b2', [a1, a2_f])) raises(ValueError, lambda: MultivariateBeta('b3', [0, 0])) raises(ValueError, lambda: MultivariateBeta('b4', [a1_f, a2_f])) assert mb.pspace.distribution.set == ProductSet(Interval(0, 1), Interval(0, 1)) def test_MultivariateEwens(): n, theta, i = symbols('n theta i', positive=True) # tests for integer dimensions theta_f = symbols('t_f', negative=True) a = symbols('a_1:4', positive = True, integer = True) ed = MultivariateEwens('E', 3, theta) assert density(ed)(a[0], a[1], a[2]) == Piecewise((6*2**(-a[1])*3**(-a[2])* theta**a[0]*theta**a[1]*theta**a[2]/ (theta*(theta + 1)*(theta + 2)* factorial(a[0])*factorial(a[1])* factorial(a[2])), Eq(a[0] + 2*a[1] + 3*a[2], 3)), (0, True)) assert marginal_distribution(ed, ed[1])(a[1]) == Piecewise((6*2**(-a[1])* theta**a[1]/((theta + 1)* (theta + 2)*factorial(a[1])), Eq(2*a[1] + 1, 3)), (0, True)) raises(ValueError, lambda: MultivariateEwens('e1', 5, theta_f)) assert ed.pspace.distribution.set == ProductSet(Range(0, 4, 1), Range(0, 2, 1), Range(0, 2, 1)) # tests for symbolic dimensions eds = MultivariateEwens('E', n, theta) a = IndexedBase('a') j, k = symbols('j, k') den = Piecewise((factorial(n)*Product(theta**a[j]*(j + 1)**(-a[j])/ factorial(a[j]), (j, 0, n - 1))/RisingFactorial(theta, n), Eq(n, Sum((k + 1)*a[k], (k, 0, n - 1)))), (0, True)) assert density(eds)(a).dummy_eq(den) def test_Multinomial(): n, x1, x2, x3, x4 = symbols('n, x1, x2, x3, x4', nonnegative=True, integer=True) p1, p2, p3, p4 = symbols('p1, p2, p3, p4', positive=True) p1_f, n_f = symbols('p1_f, n_f', negative=True) M = Multinomial('M', n, [p1, p2, p3, p4]) C = Multinomial('C', 3, p1, p2, p3) f = factorial assert density(M)(x1, x2, x3, x4) == Piecewise((p1**x1*p2**x2*p3**x3*p4**x4* f(n)/(f(x1)*f(x2)*f(x3)*f(x4)), Eq(n, x1 + x2 + x3 + x4)), (0, True)) assert marginal_distribution(C, C[0])(x1).subs(x1, 1) ==\ 3*p1*p2**2 +\ 6*p1*p2*p3 +\ 3*p1*p3**2 raises(ValueError, lambda: Multinomial('b1', 5, [p1, p2, p3, p1_f])) raises(ValueError, lambda: Multinomial('b2', n_f, [p1, p2, p3, p4])) raises(ValueError, lambda: Multinomial('b3', n, 0.5, 0.4, 0.3, 0.1)) def test_NegativeMultinomial(): k0, x1, x2, x3, x4 = symbols('k0, x1, x2, x3, x4', nonnegative=True, integer=True) p1, p2, p3, p4 = symbols('p1, p2, p3, p4', positive=True) p1_f = symbols('p1_f', negative=True) N = NegativeMultinomial('N', 4, [p1, p2, p3, p4]) C = NegativeMultinomial('C', 4, 0.1, 0.2, 0.3) g = gamma f = factorial assert simplify(density(N)(x1, x2, x3, x4) - p1**x1*p2**x2*p3**x3*p4**x4*(-p1 - p2 - p3 - p4 + 1)**4*g(x1 + x2 + x3 + x4 + 4)/(6*f(x1)*f(x2)*f(x3)*f(x4))) is S.Zero assert comp(marginal_distribution(C, C[0])(1).evalf(), 0.33, .01) raises(ValueError, lambda: NegativeMultinomial('b1', 5, [p1, p2, p3, p1_f])) raises(ValueError, lambda: NegativeMultinomial('b2', k0, 0.5, 0.4, 0.3, 0.4)) assert N.pspace.distribution.set == ProductSet(Range(0, oo, 1), Range(0, oo, 1), Range(0, oo, 1), Range(0, oo, 1)) @slow def test_JointPSpace_marginal_distribution(): T = MultivariateT('T', [0, 0], [[1, 0], [0, 1]], 2) got = marginal_distribution(T, T[1])(x) ans = sqrt(2)*(x**2/2 + 1)/(4*polar_lift(x**2/2 + 1)**(S(5)/2)) assert got == ans, got assert integrate(marginal_distribution(T, 1)(x), (x, -oo, oo)) == 1 t = MultivariateT('T', [0, 0, 0], [[1, 0, 0], [0, 1, 0], [0, 0, 1]], 3) assert comp(marginal_distribution(t, 0)(1).evalf(), 0.2, .01) def test_JointRV(): x1, x2 = (Indexed('x', i) for i in (1, 2)) pdf = exp(-x1**2/2 + x1 - x2**2/2 - S.Half)/(2*pi) X = JointRV('x', pdf) assert density(X)(1, 2) == exp(-2)/(2*pi) assert isinstance(X.pspace.distribution, JointDistributionHandmade) assert marginal_distribution(X, 0)(2) == sqrt(2)*exp(Rational(-1, 2))/(2*sqrt(pi)) def test_expectation(): m = Normal('A', [x, y], [[1, 0], [0, 1]]) assert simplify(E(m[1])) == y @XFAIL def test_joint_vector_expectation(): m = Normal('A', [x, y], [[1, 0], [0, 1]]) assert E(m) == (x, y) def test_sample_numpy(): distribs_numpy = [ MultivariateNormal("M", [3, 4], [[2, 1], [1, 2]]), MultivariateBeta("B", [0.4, 5, 15, 50, 203]), Multinomial("N", 50, [0.3, 0.2, 0.1, 0.25, 0.15]) ] size = 3 numpy = import_module('numpy') if not numpy: skip('Numpy is not installed. Abort tests for _sample_numpy.') else: for X in distribs_numpy: samps = sample(X, size=size, library='numpy') for sam in samps: assert tuple(sam) in X.pspace.distribution.set N_c = NegativeMultinomial('N', 3, 0.1, 0.1, 0.1) raises(NotImplementedError, lambda: sample(N_c, library='numpy')) def test_sample_scipy(): distribs_scipy = [ MultivariateNormal("M", [0, 0], [[0.1, 0.025], [0.025, 0.1]]), MultivariateBeta("B", [0.4, 5, 15]), Multinomial("N", 8, [0.3, 0.2, 0.1, 0.4]) ] size = 3 scipy = import_module('scipy') if not scipy: skip('Scipy not installed. Abort tests for _sample_scipy.') else: for X in distribs_scipy: samps = sample(X, size=size) samps2 = sample(X, size=(2, 2)) for sam in samps: assert tuple(sam) in X.pspace.distribution.set for i in range(2): for j in range(2): assert tuple(samps2[i][j]) in X.pspace.distribution.set N_c = NegativeMultinomial('N', 3, 0.1, 0.1, 0.1) raises(NotImplementedError, lambda: sample(N_c)) def test_sample_pymc(): distribs_pymc = [ MultivariateNormal("M", [5, 2], [[1, 0], [0, 1]]), MultivariateBeta("B", [0.4, 5, 15]), Multinomial("N", 4, [0.3, 0.2, 0.1, 0.4]) ] size = 3 pymc = import_module('pymc') if not pymc: skip('PyMC is not installed. Abort tests for _sample_pymc.') else: for X in distribs_pymc: samps = sample(X, size=size, library='pymc') for sam in samps: assert tuple(sam.flatten()) in X.pspace.distribution.set N_c = NegativeMultinomial('N', 3, 0.1, 0.1, 0.1) raises(NotImplementedError, lambda: sample(N_c, library='pymc')) def test_sample_seed(): x1, x2 = (Indexed('x', i) for i in (1, 2)) pdf = exp(-x1**2/2 + x1 - x2**2/2 - S.Half)/(2*pi) X = JointRV('x', pdf) libraries = ['scipy', 'numpy', 'pymc'] for lib in libraries: try: imported_lib = import_module(lib) if imported_lib: s0, s1, s2 = [], [], [] s0 = sample(X, size=10, library=lib, seed=0) s1 = sample(X, size=10, library=lib, seed=0) s2 = sample(X, size=10, library=lib, seed=1) assert all(s0 == s1) assert all(s1 != s2) except NotImplementedError: continue # # XXX: This fails for pymc. Previously the test appeared to pass but that is # just because the library argument was not passed so the test always used # scipy. # def test_issue_21057(): m = Normal("x", [0, 0], [[0, 0], [0, 0]]) n = MultivariateNormal("x", [0, 0], [[0, 0], [0, 0]]) p = Normal("x", [0, 0], [[0, 0], [0, 1]]) assert m == n libraries = ('scipy', 'numpy') # , 'pymc') # <-- pymc fails for library in libraries: try: imported_lib = import_module(library) if imported_lib: s1 = sample(m, size=8, library=library) s2 = sample(n, size=8, library=library) s3 = sample(p, size=8, library=library) assert tuple(s1.flatten()) == tuple(s2.flatten()) for s in s3: assert tuple(s.flatten()) in p.pspace.distribution.set except NotImplementedError: continue # # When this passes the pymc part can be uncommented in test_issue_21057 above # and this can be deleted. # @XFAIL def test_issue_21057_pymc(): m = Normal("x", [0, 0], [[0, 0], [0, 0]]) n = MultivariateNormal("x", [0, 0], [[0, 0], [0, 0]]) p = Normal("x", [0, 0], [[0, 0], [0, 1]]) assert m == n libraries = ('pymc',) for library in libraries: try: imported_lib = import_module(library) if imported_lib: s1 = sample(m, size=8, library=library) s2 = sample(n, size=8, library=library) s3 = sample(p, size=8, library=library) assert tuple(s1.flatten()) == tuple(s2.flatten()) for s in s3: assert tuple(s.flatten()) in p.pspace.distribution.set except NotImplementedError: continue
42bd4c0b863cdecb0498c333ae5d740dd7d7069a0e6b35ad376d94cf18063573
from sympy.concrete.summations import Sum from sympy.core.containers import Tuple from sympy.core.function import Lambda from sympy.core.numbers import (Float, Rational, oo, pi) from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.integers import ceiling from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.special.error_functions import erf from sympy.functions.special.gamma_functions import (gamma, lowergamma) from sympy.logic.boolalg import (And, Not) from sympy.matrices.dense import Matrix from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.immutable import ImmutableMatrix from sympy.sets.contains import Contains from sympy.sets.fancysets import Range from sympy.sets.sets import (FiniteSet, Interval) 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, warns_deprecated_sympy) from sympy.external import import_module from sympy.stats.frv_types import BernoulliDistribution from sympy.stats.drv_types import PoissonDistribution from sympy.stats.crv_types import NormalDistribution, GammaDistribution from sympy.core.symbol import Str def test_DiscreteMarkovChain(): # pass only the name X = DiscreteMarkovChain("X") assert isinstance(X.state_space, Range) assert X.index_set == S.Naturals0 assert isinstance(X.transition_probabilities, MatrixSymbol) t = symbols('t', positive=True, integer=True) assert isinstance(X[t], RandomIndexedSymbol) assert E(X[0]) == Expectation(X[0]) raises(TypeError, lambda: DiscreteMarkovChain(1)) raises(NotImplementedError, lambda: X(t)) raises(NotImplementedError, lambda: X.communication_classes()) raises(NotImplementedError, lambda: X.canonical_form()) raises(NotImplementedError, lambda: X.decompose()) nz = Symbol('n', integer=True) TZ = MatrixSymbol('M', nz, nz) SZ = Range(nz) YZ = DiscreteMarkovChain('Y', SZ, TZ) assert P(Eq(YZ[2], 1), Eq(YZ[1], 0)) == TZ[0, 1] raises(ValueError, lambda: sample_stochastic_process(t)) raises(ValueError, lambda: next(sample_stochastic_process(X))) # pass name and state_space # any hashable object should be a valid state # states should be valid as a tuple/set/list/Tuple/Range sym, rainy, cloudy, sunny = symbols('a Rainy Cloudy Sunny', real=True) state_spaces = [(1, 2, 3), [Str('Hello'), sym, DiscreteMarkovChain("Y", (1,2,3))], Tuple(S(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, ImmutableMatrix) # pass name, state_space and transition_probabilities T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]]) TS = MatrixSymbol('T', 3, 3) Y = DiscreteMarkovChain("Y", [0, 1, 2], T) YS = DiscreteMarkovChain("Y", ['One', 'Two', 3], TS) assert Y.joint_distribution(1, Y[2], 3) == JointDistribution(Y[1], Y[2], Y[3]) raises(ValueError, lambda: Y.joint_distribution(Y[1].symbol, Y[2].symbol)) assert P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2) == Float(0.36, 2) assert (P(Eq(YS[3], 2), Eq(YS[1], 1)) - (TS[0, 2]*TS[1, 0] + TS[1, 1]*TS[1, 2] + TS[1, 2]*TS[2, 2])).simplify() == 0 assert P(Eq(YS[1], 1), Eq(YS[2], 2)) == Probability(Eq(YS[1], 1)) assert P(Eq(YS[3], 3), Eq(YS[1], 1)) == TS[0, 2]*TS[1, 0] + TS[1, 1]*TS[1, 2] + TS[1, 2]*TS[2, 2] TO = Matrix([[0.25, 0.75, 0],[0, 0.25, 0.75],[0.75, 0, 0.25]]) assert P(Eq(Y[3], 2), Eq(Y[1], 1) & TransitionMatrixOf(Y, TO)).round(3) == Float(0.375, 3) with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed assert E(Y[3], evaluate=False) == Expectation(Y[3]) assert E(Y[3], Eq(Y[2], 1)).round(2) == Float(1.1, 3) TSO = MatrixSymbol('T', 4, 4) raises(ValueError, lambda: str(P(Eq(YS[3], 2), Eq(YS[1], 1) & TransitionMatrixOf(YS, TSO)))) raises(TypeError, lambda: DiscreteMarkovChain("Z", [0, 1, 2], symbols('M'))) raises(ValueError, lambda: DiscreteMarkovChain("Z", [0, 1, 2], MatrixSymbol('T', 3, 4))) raises(ValueError, lambda: E(Y[3], Eq(Y[2], 6))) raises(ValueError, lambda: E(Y[2], Eq(Y[3], 1))) # extended tests for probability queries TO1 = Matrix([[Rational(1, 4), Rational(3, 4), 0],[Rational(1, 3), Rational(1, 3), Rational(1, 3)],[0, Rational(1, 4), Rational(3, 4)]]) assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)), Eq(Probability(Eq(Y[0], 0)), Rational(1, 4)) & TransitionMatrixOf(Y, TO1)) == Rational(1, 16) assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)), TransitionMatrixOf(Y, TO1)) == \ Probability(Eq(Y[0], 0))/4 assert P(Lt(X[1], 2) & Gt(X[1], 0), Eq(X[0], 2) & StochasticStateSpaceOf(X, [0, 1, 2]) & TransitionMatrixOf(X, TO1)) == Rational(1, 4) assert P(Lt(X[1], 2) & Gt(X[1], 0), Eq(X[0], 2) & StochasticStateSpaceOf(X, [S(0), '0', 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, [S(0), '0', 1]) & TransitionMatrixOf(X, TO1)) is S.Zero assert P(And(Eq(Y[2], 1), Eq(Y[1], 1), Eq(Y[0], 0)), Eq(Y[1], 1)) == 0.1*Probability(Eq(Y[0], 0)) # testing properties of Markov chain TO2 = Matrix([[S.One, 0, 0],[Rational(1, 3), Rational(1, 3), Rational(1, 3)],[0, Rational(1, 4), Rational(3, 4)]]) TO3 = Matrix([[Rational(1, 4), Rational(3, 4), 0],[Rational(1, 3), Rational(1, 3), Rational(1, 3)], [0, Rational(1, 4), Rational(3, 4)]]) Y2 = DiscreteMarkovChain('Y', trans_probs=TO2) Y3 = DiscreteMarkovChain('Y', trans_probs=TO3) assert Y3.fundamental_matrix() == ImmutableMatrix([[176, 81, -132], [36, 141, -52], [-44, -39, 208]])/125 assert Y2.is_absorbing_chain() == True assert Y3.is_absorbing_chain() == False assert Y2.canonical_form() == ([0, 1, 2], TO2) assert Y3.canonical_form() == ([0, 1, 2], TO3) assert Y2.decompose() == ([0, 1, 2], TO2[0:1, 0:1], TO2[1:3, 0:1], TO2[1:3, 1:3]) assert Y3.decompose() == ([0, 1, 2], TO3, Matrix(0, 3, []), Matrix(0, 0, [])) TO4 = Matrix([[Rational(1, 5), Rational(2, 5), Rational(2, 5)], [Rational(1, 10), S.Half, Rational(2, 5)], [Rational(3, 5), Rational(3, 10), Rational(1, 10)]]) Y4 = DiscreteMarkovChain('Y', trans_probs=TO4) w = ImmutableMatrix([[Rational(11, 39), Rational(16, 39), Rational(4, 13)]]) assert Y4.limiting_distribution == w assert Y4.is_regular() == True assert Y4.is_ergodic() == True TS1 = MatrixSymbol('T', 3, 3) Y5 = DiscreteMarkovChain('Y', trans_probs=TS1) assert Y5.limiting_distribution(w, TO4).doit() == True assert Y5.stationary_distribution(condition_set=True).subs(TS1, TO4).contains(w).doit() == S.true TO6 = Matrix([[S.One, 0, 0, 0, 0],[S.Half, 0, S.Half, 0, 0],[0, S.Half, 0, S.Half, 0], [0, 0, S.Half, 0, S.Half], [0, 0, 0, 0, 1]]) Y6 = DiscreteMarkovChain('Y', trans_probs=TO6) assert Y6.fundamental_matrix() == ImmutableMatrix([[Rational(3, 2), S.One, S.Half], [S.One, S(2), S.One], [S.Half, S.One, Rational(3, 2)]]) assert Y6.absorbing_probabilities() == ImmutableMatrix([[Rational(3, 4), Rational(1, 4)], [S.Half, S.Half], [Rational(1, 4), Rational(3, 4)]]) with warns_deprecated_sympy(): Y6.absorbing_probabilites() TO7 = Matrix([[Rational(1, 2), Rational(1, 4), Rational(1, 4)], [Rational(1, 2), 0, Rational(1, 2)], [Rational(1, 4), Rational(1, 4), Rational(1, 2)]]) Y7 = DiscreteMarkovChain('Y', trans_probs=TO7) assert Y7.is_absorbing_chain() == False assert Y7.fundamental_matrix() == ImmutableMatrix([[Rational(86, 75), Rational(1, 25), Rational(-14, 75)], [Rational(2, 25), Rational(21, 25), Rational(2, 25)], [Rational(-14, 75), Rational(1, 25), Rational(86, 75)]]) # test for zero-sized matrix functionality X = DiscreteMarkovChain('X', trans_probs=Matrix([[]])) assert X.number_of_states == 0 assert X.stationary_distribution() == Matrix([[]]) assert X.communication_classes() == [] assert X.canonical_form() == ([], Matrix([[]])) assert X.decompose() == ([], Matrix([[]]), Matrix([[]]), Matrix([[]])) assert X.is_regular() == False assert X.is_ergodic() == False # test communication_class # see https://drive.google.com/drive/folders/1HbxLlwwn2b3U8Lj7eb_ASIUb5vYaNIjg?usp=sharing # tutorial 2.pdf TO7 = Matrix([[0, 5, 5, 0, 0], [0, 0, 0, 10, 0], [5, 0, 5, 0, 0], [0, 10, 0, 0, 0], [0, 3, 0, 3, 4]])/10 Y7 = DiscreteMarkovChain('Y', trans_probs=TO7) tuples = Y7.communication_classes() classes, recurrence, periods = list(zip(*tuples)) assert classes == ([1, 3], [0, 2], [4]) assert recurrence == (True, False, False) assert periods == (2, 1, 1) TO8 = Matrix([[0, 0, 0, 10, 0, 0], [5, 0, 5, 0, 0, 0], [0, 4, 0, 0, 0, 6], [10, 0, 0, 0, 0, 0], [0, 10, 0, 0, 0, 0], [0, 0, 0, 5, 5, 0]])/10 Y8 = DiscreteMarkovChain('Y', trans_probs=TO8) tuples = Y8.communication_classes() classes, recurrence, periods = list(zip(*tuples)) assert classes == ([0, 3], [1, 2, 5, 4]) assert recurrence == (True, False) assert periods == (2, 2) TO9 = Matrix([[2, 0, 0, 3, 0, 0, 3, 2, 0, 0], [0, 10, 0, 0, 0, 0, 0, 0, 0, 0], [0, 2, 2, 0, 0, 0, 0, 0, 3, 3], [0, 0, 0, 3, 0, 0, 6, 1, 0, 0], [0, 0, 0, 0, 5, 5, 0, 0, 0, 0], [0, 0, 0, 0, 0, 10, 0, 0, 0, 0], [4, 0, 0, 5, 0, 0, 1, 0, 0, 0], [2, 0, 0, 4, 0, 0, 2, 2, 0, 0], [3, 0, 1, 0, 0, 0, 0, 0, 4, 2], [0, 0, 4, 0, 0, 0, 0, 0, 3, 3]])/10 Y9 = DiscreteMarkovChain('Y', trans_probs=TO9) tuples = Y9.communication_classes() classes, recurrence, periods = list(zip(*tuples)) assert classes == ([0, 3, 6, 7], [1], [2, 8, 9], [5], [4]) assert recurrence == (True, True, False, True, False) assert periods == (1, 1, 1, 1, 1) # test canonical form # see https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf # example 11.13 T = Matrix([[1, 0, 0, 0, 0], [S(1) / 2, 0, S(1) / 2, 0, 0], [0, S(1) / 2, 0, S(1) / 2, 0], [0, 0, S(1) / 2, 0, S(1) / 2], [0, 0, 0, 0, S(1)]]) DW = DiscreteMarkovChain('DW', [0, 1, 2, 3, 4], T) states, A, B, C = DW.decompose() assert states == [0, 4, 1, 2, 3] assert A == Matrix([[1, 0], [0, 1]]) assert B == Matrix([[S(1)/2, 0], [0, 0], [0, S(1)/2]]) assert C == Matrix([[0, S(1)/2, 0], [S(1)/2, 0, S(1)/2], [0, S(1)/2, 0]]) states, new_matrix = DW.canonical_form() assert states == [0, 4, 1, 2, 3] assert new_matrix == Matrix([[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [S(1)/2, 0, 0, S(1)/2, 0], [0, 0, S(1)/2, 0, S(1)/2], [0, S(1)/2, 0, S(1)/2, 0]]) # test regular and ergodic # https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf T = Matrix([[0, 4, 0, 0, 0], [1, 0, 3, 0, 0], [0, 2, 0, 2, 0], [0, 0, 3, 0, 1], [0, 0, 0, 4, 0]])/4 X = DiscreteMarkovChain('X', trans_probs=T) assert not X.is_regular() assert X.is_ergodic() T = Matrix([[0, 1], [1, 0]]) X = DiscreteMarkovChain('X', trans_probs=T) assert not X.is_regular() assert X.is_ergodic() # http://www.math.wisc.edu/~valko/courses/331/MC2.pdf T = Matrix([[2, 1, 1], [2, 0, 2], [1, 1, 2]])/4 X = DiscreteMarkovChain('X', trans_probs=T) assert X.is_regular() assert X.is_ergodic() # https://docs.ufpr.br/~lucambio/CE222/1S2014/Kemeny-Snell1976.pdf T = Matrix([[1, 1], [1, 1]])/2 X = DiscreteMarkovChain('X', trans_probs=T) assert X.is_regular() assert X.is_ergodic() # test is_absorbing_chain T = Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]]) X = DiscreteMarkovChain('X', trans_probs=T) assert not X.is_absorbing_chain() # https://en.wikipedia.org/wiki/Absorbing_Markov_chain T = Matrix([[1, 1, 0, 0], [0, 1, 1, 0], [1, 0, 0, 1], [0, 0, 0, 2]])/2 X = DiscreteMarkovChain('X', trans_probs=T) assert X.is_absorbing_chain() T = Matrix([[2, 0, 0, 0, 0], [1, 0, 1, 0, 0], [0, 1, 0, 1, 0], [0, 0, 1, 0, 1], [0, 0, 0, 0, 2]])/2 X = DiscreteMarkovChain('X', trans_probs=T) assert X.is_absorbing_chain() # test custom state space Y10 = DiscreteMarkovChain('Y', [1, 2, 3], TO2) tuples = Y10.communication_classes() classes, recurrence, periods = list(zip(*tuples)) assert classes == ([1], [2, 3]) assert recurrence == (True, False) assert periods == (1, 1) assert Y10.canonical_form() == ([1, 2, 3], TO2) assert Y10.decompose() == ([1, 2, 3], TO2[0:1, 0:1], TO2[1:3, 0:1], TO2[1:3, 1:3]) # testing miscellaneous queries T = Matrix([[S.Half, Rational(1, 4), Rational(1, 4)], [Rational(1, 3), 0, Rational(2, 3)], [S.Half, S.Half, 0]]) X = DiscreteMarkovChain('X', [0, 1, 2], T) assert P(Eq(X[1], 2) & Eq(X[2], 1) & Eq(X[3], 0), Eq(P(Eq(X[1], 0)), Rational(1, 4)) & Eq(P(Eq(X[1], 1)), Rational(1, 4))) == Rational(1, 12) assert P(Eq(X[2], 1) | Eq(X[2], 2), Eq(X[1], 1)) == Rational(2, 3) assert P(Eq(X[2], 1) & Eq(X[2], 2), Eq(X[1], 1)) is S.Zero assert P(Ne(X[2], 2), Eq(X[1], 1)) == Rational(1, 3) assert E(X[1]**2, Eq(X[0], 1)) == Rational(8, 3) assert variance(X[1], Eq(X[0], 1)) == Rational(8, 9) raises(ValueError, lambda: E(X[1], Eq(X[2], 1))) raises(ValueError, lambda: DiscreteMarkovChain('X', [0, 1], T)) # testing miscellaneous queries with different state space X = DiscreteMarkovChain('X', ['A', 'B', 'C'], T) assert P(Eq(X[1], 2) & Eq(X[2], 1) & Eq(X[3], 0), Eq(P(Eq(X[1], 0)), Rational(1, 4)) & Eq(P(Eq(X[1], 1)), Rational(1, 4))) == Rational(1, 12) assert P(Eq(X[2], 1) | Eq(X[2], 2), Eq(X[1], 1)) == Rational(2, 3) assert P(Eq(X[2], 1) & Eq(X[2], 2), Eq(X[1], 1)) is S.Zero assert P(Ne(X[2], 2), Eq(X[1], 1)) == Rational(1, 3) a = X.state_space.args[0] c = X.state_space.args[2] assert (E(X[1] ** 2, Eq(X[0], 1)) - (a**2/3 + 2*c**2/3)).simplify() == 0 assert (variance(X[1], Eq(X[0], 1)) - (2*(-a/3 + c/3)**2/3 + (2*a/3 - 2*c/3)**2/3)).simplify() == 0 raises(ValueError, lambda: E(X[1], Eq(X[2], 1))) #testing queries with multiple RandomIndexedSymbols T = Matrix([[Rational(5, 10), Rational(3, 10), Rational(2, 10)], [Rational(2, 10), Rational(7, 10), Rational(1, 10)], [Rational(3, 10), Rational(3, 10), Rational(4, 10)]]) Y = DiscreteMarkovChain("Y", [0, 1, 2], T) assert P(Eq(Y[7], Y[5]), Eq(Y[2], 0)).round(5) == Float(0.44428, 5) assert P(Gt(Y[3], Y[1]), Eq(Y[0], 0)).round(2) == Float(0.36, 2) assert P(Le(Y[5], Y[10]), Eq(Y[4], 2)).round(6) == Float(0.583120, 6) assert Float(P(Eq(Y[10], Y[5]), Eq(Y[4], 1)), 14) == Float(1 - P(Ne(Y[10], Y[5]), Eq(Y[4], 1)), 14) assert Float(P(Gt(Y[8], Y[9]), Eq(Y[3], 2)), 14) == Float(1 - P(Le(Y[8], Y[9]), Eq(Y[3], 2)), 14) assert Float(P(Lt(Y[1], Y[4]), Eq(Y[0], 0)), 14) == Float(1 - P(Ge(Y[1], Y[4]), Eq(Y[0], 0)), 14) assert P(Eq(Y[5], Y[10]), Eq(Y[2], 1)) == P(Eq(Y[10], Y[5]), Eq(Y[2], 1)) assert P(Gt(Y[1], Y[2]), Eq(Y[0], 1)) == P(Lt(Y[2], Y[1]), Eq(Y[0], 1)) assert P(Ge(Y[7], Y[6]), Eq(Y[4], 1)) == P(Le(Y[6], Y[7]), Eq(Y[4], 1)) #test symbolic queries a, b, c, d = symbols('a b c d') T = Matrix([[Rational(1, 10), Rational(4, 10), Rational(5, 10)], [Rational(3, 10), Rational(4, 10), Rational(3, 10)], [Rational(7, 10), Rational(2, 10), Rational(1, 10)]]) Y = DiscreteMarkovChain("Y", [0, 1, 2], T) query = P(Eq(Y[a], b), Eq(Y[c], d)) assert query.subs({a:10, b:2, c:5, d:1}).evalf().round(4) == P(Eq(Y[10], 2), Eq(Y[5], 1)).round(4) assert query.subs({a:15, b:0, c:10, d:1}).evalf().round(4) == P(Eq(Y[15], 0), Eq(Y[10], 1)).round(4) query_gt = P(Gt(Y[a], b), Eq(Y[c], d)) query_le = P(Le(Y[a], b), Eq(Y[c], d)) assert query_gt.subs({a:5, b:2, c:1, d:0}).evalf() + query_le.subs({a:5, b:2, c:1, d:0}).evalf() == 1.0 query_ge = P(Ge(Y[a], b), Eq(Y[c], d)) query_lt = P(Lt(Y[a], b), Eq(Y[c], d)) assert query_ge.subs({a:4, b:1, c:0, d:2}).evalf() + query_lt.subs({a:4, b:1, c:0, d:2}).evalf() == 1.0 #test issue 20078 assert (2*Y[1] + 3*Y[1]).simplify() == 5*Y[1] assert (2*Y[1] - 3*Y[1]).simplify() == -Y[1] assert (2*(0.25*Y[1])).simplify() == 0.5*Y[1] assert ((2*Y[1]) * (0.25*Y[1])).simplify() == 0.5*Y[1]**2 assert (Y[1]**2 + Y[1]**3).simplify() == (Y[1] + 1)*Y[1]**2 def test_sample_stochastic_process(): if not import_module('scipy'): skip('SciPy Not installed. Skip sampling tests') import random random.seed(0) numpy = import_module('numpy') if numpy: numpy.random.seed(0) # scipy uses numpy to sample so to set its seed T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]]) Y = DiscreteMarkovChain("Y", [0, 1, 2], T) for samps in range(10): assert next(sample_stochastic_process(Y)) in Y.state_space Z = DiscreteMarkovChain("Z", ['1', 1, 0], T) for samps in range(10): assert next(sample_stochastic_process(Z)) in Z.state_space T = Matrix([[S.Half, Rational(1, 4), Rational(1, 4)], [Rational(1, 3), 0, Rational(2, 3)], [S.Half, S.Half, 0]]) X = DiscreteMarkovChain('X', [0, 1, 2], T) for samps in range(10): assert next(sample_stochastic_process(X)) in X.state_space W = DiscreteMarkovChain('W', [1, pi, oo], T) for samps in range(10): assert next(sample_stochastic_process(W)) in W.state_space def test_ContinuousMarkovChain(): T1 = Matrix([[S(-2), S(2), S.Zero], [S.Zero, S.NegativeOne, S.One], [Rational(3, 2), Rational(3, 2), S(-3)]]) C1 = ContinuousMarkovChain('C', [0, 1, 2], T1) assert C1.limiting_distribution() == ImmutableMatrix([[Rational(3, 19), Rational(12, 19), Rational(4, 19)]]) T2 = Matrix([[-S.One, S.One, S.Zero], [S.One, -S.One, S.Zero], [S.Zero, S.One, -S.One]]) C2 = ContinuousMarkovChain('C', [0, 1, 2], T2) A, t = C2.generator_matrix, symbols('t', positive=True) assert C2.transition_probabilities(A)(t) == Matrix([[S.Half + exp(-2*t)/2, S.Half - exp(-2*t)/2, 0], [S.Half - exp(-2*t)/2, S.Half + exp(-2*t)/2, 0], [S.Half - exp(-t) + exp(-2*t)/2, S.Half - exp(-2*t)/2, exp(-t)]]) with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed assert P(Eq(C2(1), 1), Eq(C2(0), 1), evaluate=False) == Probability(Eq(C2(1), 1), Eq(C2(0), 1)) assert P(Eq(C2(1), 1), Eq(C2(0), 1)) == exp(-2)/2 + S.Half assert P(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 1), Eq(P(Eq(C2(1), 0)), S.Half)) == (Rational(1, 4) - exp(-2)/4)*(exp(-2)/2 + S.Half) assert P(Not(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)) | (Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)), Eq(P(Eq(C2(1), 0)), Rational(1, 4)) & Eq(P(Eq(C2(1), 1)), Rational(1, 4))) is S.One assert E(C2(Rational(3, 2)), Eq(C2(0), 2)) == -exp(-3)/2 + 2*exp(Rational(-3, 2)) + S.Half assert variance(C2(Rational(3, 2)), Eq(C2(0), 1)) == ((S.Half - exp(-3)/2)**2*(exp(-3)/2 + S.Half) + (Rational(-1, 2) - exp(-3)/2)**2*(S.Half - exp(-3)/2)) raises(KeyError, lambda: P(Eq(C2(1), 0), Eq(P(Eq(C2(1), 1)), S.Half))) assert P(Eq(C2(1), 0), Eq(P(Eq(C2(5), 1)), S.Half)) == Probability(Eq(C2(1), 0)) TS1 = MatrixSymbol('G', 3, 3) CS1 = ContinuousMarkovChain('C', [0, 1, 2], TS1) A = CS1.generator_matrix assert CS1.transition_probabilities(A)(t) == exp(t*A) C3 = ContinuousMarkovChain('C', [Symbol('0'), Symbol('1'), Symbol('2')], T2) assert P(Eq(C3(1), 1), Eq(C3(0), 1)) == exp(-2)/2 + S.Half assert P(Eq(C3(1), Symbol('1')), Eq(C3(0), Symbol('1'))) == exp(-2)/2 + S.Half #test probability queries G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]]) C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G) assert P(Eq(C(7.385), C(3.19)), Eq(C(0.862), 0)).round(5) == Float(0.35469, 5) assert P(Gt(C(98.715), C(19.807)), Eq(C(11.314), 2)).round(5) == Float(0.32452, 5) assert P(Le(C(5.9), C(10.112)), Eq(C(4), 1)).round(6) == Float(0.675214, 6) assert Float(P(Eq(C(7.32), C(2.91)), Eq(C(2.63), 1)), 14) == Float(1 - P(Ne(C(7.32), C(2.91)), Eq(C(2.63), 1)), 14) assert Float(P(Gt(C(3.36), C(1.101)), Eq(C(0.8), 2)), 14) == Float(1 - P(Le(C(3.36), C(1.101)), Eq(C(0.8), 2)), 14) assert Float(P(Lt(C(4.9), C(2.79)), Eq(C(1.61), 0)), 14) == Float(1 - P(Ge(C(4.9), C(2.79)), Eq(C(1.61), 0)), 14) assert P(Eq(C(5.243), C(10.912)), Eq(C(2.174), 1)) == P(Eq(C(10.912), C(5.243)), Eq(C(2.174), 1)) assert P(Gt(C(2.344), C(9.9)), Eq(C(1.102), 1)) == P(Lt(C(9.9), C(2.344)), Eq(C(1.102), 1)) assert P(Ge(C(7.87), C(1.008)), Eq(C(0.153), 1)) == P(Le(C(1.008), C(7.87)), Eq(C(0.153), 1)) #test symbolic queries a, b, c, d = symbols('a b c d') query = P(Eq(C(a), b), Eq(C(c), d)) assert query.subs({a:3.65, b:2, c:1.78, d:1}).evalf().round(10) == P(Eq(C(3.65), 2), Eq(C(1.78), 1)).round(10) query_gt = P(Gt(C(a), b), Eq(C(c), d)) query_le = P(Le(C(a), b), Eq(C(c), d)) assert query_gt.subs({a:13.2, b:0, c:3.29, d:2}).evalf() + query_le.subs({a:13.2, b:0, c:3.29, d:2}).evalf() == 1.0 query_ge = P(Ge(C(a), b), Eq(C(c), d)) query_lt = P(Lt(C(a), b), Eq(C(c), d)) assert query_ge.subs({a:7.43, b:1, c:1.45, d:0}).evalf() + query_lt.subs({a:7.43, b:1, c:1.45, d:0}).evalf() == 1.0 #test issue 20078 assert (2*C(1) + 3*C(1)).simplify() == 5*C(1) assert (2*C(1) - 3*C(1)).simplify() == -C(1) assert (2*(0.25*C(1))).simplify() == 0.5*C(1) assert (2*C(1) * 0.25*C(1)).simplify() == 0.5*C(1)**2 assert (C(1)**2 + C(1)**3).simplify() == (C(1) + 1)*C(1)**2 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.0 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} #test issue 20078 assert (2*B[t] + 3*B[t]).simplify() == 5*B[t] assert (2*B[t] - 3*B[t]).simplify() == -B[t] assert (2*(0.25*B[t])).simplify() == 0.5*B[t] assert (2*B[t] * 0.25*B[t]).simplify() == 0.5*B[t]**2 assert (B[t]**2 + B[t]**3).simplify() == (B[t] + 1)*B[t]**2 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(t) == PoissonDistribution(3*t) with warns_deprecated_sympy(): X.distribution(X(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)) #test issue 20078 assert (2*X(t) + 3*X(t)).simplify() == 5*X(t) assert (2*X(t) - 3*X(t)).simplify() == -X(t) assert (2*(0.25*X(t))).simplify() == 0.5*X(t) assert (2*X(t) * 0.25*X(t)).simplify() == 0.5*X(t)**2 assert (X(t)**2 + X(t)**3).simplify() == (X(t) + 1)*X(t)**2 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(t) == NormalDistribution(0, sqrt(t)) with warns_deprecated_sympy(): X.distribution(X(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 #test issue 20078 assert (2*X(t) + 3*X(t)).simplify() == 5*X(t) assert (2*X(t) - 3*X(t)).simplify() == -X(t) assert (2*(0.25*X(t))).simplify() == 0.5*X(t) assert (2*X(t) * 0.25*X(t)).simplify() == 0.5*X(t)**2 assert (X(t)**2 + X(t)**3).simplify() == (X(t) + 1)*X(t)**2 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(t) == GammaDistribution(g*t, 1/l) with warns_deprecated_sympy(): X.distribution(X(t)) 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) #test issue 20078 assert (2*X(t) + 3*X(t)).simplify() == 5*X(t) assert (2*X(t) - 3*X(t)).simplify() == -X(t) assert (2*(0.25*X(t))).simplify() == 0.5*X(t) assert (2*X(t) * 0.25*X(t)).simplify() == 0.5*X(t)**2 assert (X(t)**2 + X(t)**3).simplify() == (X(t) + 1)*X(t)**2 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
6a6ad913b1ec5dc4adf7a32092eee93d33051c3960365f58fb3bf076934003ab
from sympy.concrete.products import Product from sympy.core.numbers import pi from sympy.core.singleton import S from sympy.core.symbol import (Dummy, symbols) from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.special.gamma_functions import gamma from sympy.matrices import Determinant, Matrix, Trace, MatrixSymbol, MatrixSet from sympy.stats import density, sample from sympy.stats.matrix_distributions import (MatrixGammaDistribution, MatrixGamma, MatrixPSpace, Wishart, MatrixNormal, MatrixStudentT) from sympy.testing.pytest import raises, skip from sympy.external import import_module def test_MatrixPSpace(): M = MatrixGammaDistribution(1, 2, [[2, 1], [1, 2]]) MP = MatrixPSpace('M', M, 2, 2) assert MP.distribution == M raises(ValueError, lambda: MatrixPSpace('M', M, 1.2, 2)) def test_MatrixGamma(): M = MatrixGamma('M', 1, 2, [[1, 0], [0, 1]]) assert M.pspace.distribution.set == MatrixSet(2, 2, S.Reals) assert isinstance(density(M), MatrixGammaDistribution) X = MatrixSymbol('X', 2, 2) num = exp(Trace(Matrix([[-S(1)/2, 0], [0, -S(1)/2]])*X)) assert density(M)(X).doit() == num/(4*pi*sqrt(Determinant(X))) assert density(M)([[2, 1], [1, 2]]).doit() == sqrt(3)*exp(-2)/(12*pi) X = MatrixSymbol('X', 1, 2) Y = MatrixSymbol('Y', 1, 2) assert density(M)([X, Y]).doit() == exp(-X[0, 0]/2 - Y[0, 1]/2)/(4*pi*sqrt( X[0, 0]*Y[0, 1] - X[0, 1]*Y[0, 0])) # symbolic a, b = symbols('a b', positive=True) d = symbols('d', positive=True, integer=True) Y = MatrixSymbol('Y', d, d) Z = MatrixSymbol('Z', 2, 2) SM = MatrixSymbol('SM', d, d) M2 = MatrixGamma('M2', a, b, SM) M3 = MatrixGamma('M3', 2, 3, [[2, 1], [1, 2]]) k = Dummy('k') exprd = pi**(-d*(d - 1)/4)*b**(-a*d)*exp(Trace((-1/b)*SM**(-1)*Y) )*Determinant(SM)**(-a)*Determinant(Y)**(a - d/2 - S(1)/2)/Product( gamma(-k/2 + a + S(1)/2), (k, 1, d)) assert density(M2)(Y).dummy_eq(exprd) raises(NotImplementedError, lambda: density(M3 + M)(Z)) raises(ValueError, lambda: density(M)(1)) raises(ValueError, lambda: MatrixGamma('M', -1, 2, [[1, 0], [0, 1]])) raises(ValueError, lambda: MatrixGamma('M', -1, -2, [[1, 0], [0, 1]])) raises(ValueError, lambda: MatrixGamma('M', -1, 2, [[1, 0], [2, 1]])) raises(ValueError, lambda: MatrixGamma('M', -1, 2, [[1, 0], [0]])) def test_Wishart(): W = Wishart('W', 5, [[1, 0], [0, 1]]) assert W.pspace.distribution.set == MatrixSet(2, 2, S.Reals) X = MatrixSymbol('X', 2, 2) term1 = exp(Trace(Matrix([[-S(1)/2, 0], [0, -S(1)/2]])*X)) assert density(W)(X).doit() == term1 * Determinant(X)/(24*pi) assert density(W)([[2, 1], [1, 2]]).doit() == exp(-2)/(8*pi) n = symbols('n', positive=True) d = symbols('d', positive=True, integer=True) Y = MatrixSymbol('Y', d, d) SM = MatrixSymbol('SM', d, d) W = Wishart('W', n, SM) k = Dummy('k') exprd = 2**(-d*n/2)*pi**(-d*(d - 1)/4)*exp(Trace(-(S(1)/2)*SM**(-1)*Y) )*Determinant(SM)**(-n/2)*Determinant(Y)**( -d/2 + n/2 - S(1)/2)/Product(gamma(-k/2 + n/2 + S(1)/2), (k, 1, d)) assert density(W)(Y).dummy_eq(exprd) raises(ValueError, lambda: density(W)(1)) raises(ValueError, lambda: Wishart('W', -1, [[1, 0], [0, 1]])) raises(ValueError, lambda: Wishart('W', -1, [[1, 0], [2, 1]])) raises(ValueError, lambda: Wishart('W', 2, [[1, 0], [0]])) def test_MatrixNormal(): M = MatrixNormal('M', [[5, 6]], [4], [[2, 1], [1, 2]]) assert M.pspace.distribution.set == MatrixSet(1, 2, S.Reals) X = MatrixSymbol('X', 1, 2) term1 = exp(-Trace(Matrix([[ S(2)/3, -S(1)/3], [-S(1)/3, S(2)/3]])*( Matrix([[-5], [-6]]) + X.T)*Matrix([[S(1)/4]])*(Matrix([[-5, -6]]) + X))/2) assert density(M)(X).doit() == term1/(24*pi) assert density(M)([[7, 8]]).doit() == exp(-S(1)/3)/(24*pi) d, n = symbols('d n', positive=True, integer=True) SM2 = MatrixSymbol('SM2', d, d) SM1 = MatrixSymbol('SM1', n, n) LM = MatrixSymbol('LM', n, d) Y = MatrixSymbol('Y', n, d) M = MatrixNormal('M', LM, SM1, SM2) exprd = 4*(2*pi)**(-d*n/2)*exp(-Trace(SM2**(-1)*(-LM.T + Y.T)*SM1**(-1)*(-LM + Y) )/2)*Determinant(SM1)**(-d)*Determinant(SM2)**(-n) assert density(M)(Y).doit() == exprd raises(ValueError, lambda: density(M)(1)) raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [0, 1]], [[1, 0], [2, 1]])) raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [2, 1]], [[1, 0], [0, 1]])) raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [0, 1]], [[1, 0], [0, 1]])) raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [2]], [[1, 0], [0, 1]])) raises(ValueError, lambda: MatrixNormal('M', [1, 2], [[1, 0], [2, 1]], [[1, 0], [0]])) raises(ValueError, lambda: MatrixNormal('M', [[1, 2]], [[1, 0], [0, 1]], [[1, 0]])) raises(ValueError, lambda: MatrixNormal('M', [[1, 2]], [1], [[1, 0]])) def test_MatrixStudentT(): M = MatrixStudentT('M', 2, [[5, 6]], [[2, 1], [1, 2]], [4]) assert M.pspace.distribution.set == MatrixSet(1, 2, S.Reals) X = MatrixSymbol('X', 1, 2) D = pi ** (-1.0) * Determinant(Matrix([[4]])) ** (-1.0) * Determinant(Matrix([[2, 1], [1, 2]])) \ ** (-0.5) / Determinant(Matrix([[S(1) / 4]]) * (Matrix([[-5, -6]]) + X) * Matrix([[S(2) / 3, -S(1) / 3], [-S(1) / 3, S(2) / 3]]) * ( Matrix([[-5], [-6]]) + X.T) + Matrix([[1]])) ** 2 assert density(M)(X) == D v = symbols('v', positive=True) n, p = 1, 2 Omega = MatrixSymbol('Omega', p, p) Sigma = MatrixSymbol('Sigma', n, n) Location = MatrixSymbol('Location', n, p) Y = MatrixSymbol('Y', n, p) M = MatrixStudentT('M', v, Location, Omega, Sigma) exprd = gamma(v/2 + 1)*Determinant(Matrix([[1]]) + Sigma**(-1)*(-Location + Y)*Omega**(-1)*(-Location.T + Y.T))**(-v/2 - 1) / \ (pi*gamma(v/2)*sqrt(Determinant(Omega))*Determinant(Sigma)) assert density(M)(Y) == exprd raises(ValueError, lambda: density(M)(1)) raises(ValueError, lambda: MatrixStudentT('M', 1, [1, 2], [[1, 0], [0, 1]], [[1, 0], [2, 1]])) raises(ValueError, lambda: MatrixStudentT('M', 1, [1, 2], [[1, 0], [2, 1]], [[1, 0], [0, 1]])) raises(ValueError, lambda: MatrixStudentT('M', 1, [1, 2], [[1, 0], [0, 1]], [[1, 0], [0, 1]])) raises(ValueError, lambda: MatrixStudentT('M', 1, [1, 2], [[1, 0], [2]], [[1, 0], [0, 1]])) raises(ValueError, lambda: MatrixStudentT('M', 1, [1, 2], [[1, 0], [2, 1]], [[1], [2]])) raises(ValueError, lambda: MatrixStudentT('M', 1, [[1, 2]], [[1, 0], [0, 1]], [[1, 0]])) raises(ValueError, lambda: MatrixStudentT('M', 1, [[1, 2]], [1], [[1, 0]])) raises(ValueError, lambda: MatrixStudentT('M', -1, [1, 2], [[1, 0], [0, 1]], [4])) def test_sample_scipy(): distribs_scipy = [ MatrixNormal('M', [[5, 6]], [4], [[2, 1], [1, 2]]), Wishart('W', 5, [[1, 0], [0, 1]]) ] size = 5 scipy = import_module('scipy') if not scipy: skip('Scipy not installed. Abort tests for _sample_scipy.') else: for X in distribs_scipy: samps = sample(X, size=size) for sam in samps: assert Matrix(sam) in X.pspace.distribution.set M = MatrixGamma('M', 1, 2, [[1, 0], [0, 1]]) raises(NotImplementedError, lambda: sample(M, size=3)) def test_sample_pymc(): distribs_pymc = [ MatrixNormal('M', [[5, 6], [3, 4]], [[1, 0], [0, 1]], [[2, 1], [1, 2]]), Wishart('W', 7, [[2, 1], [1, 2]]) ] size = 3 pymc = import_module('pymc') if not pymc: skip('PyMC is not installed. Abort tests for _sample_pymc.') else: for X in distribs_pymc: samps = sample(X, size=size, library='pymc') for sam in samps: assert Matrix(sam) in X.pspace.distribution.set M = MatrixGamma('M', 1, 2, [[1, 0], [0, 1]]) raises(NotImplementedError, lambda: sample(M, size=3)) def test_sample_seed(): X = MatrixNormal('M', [[5, 6], [3, 4]], [[1, 0], [0, 1]], [[2, 1], [1, 2]]) libraries = ['scipy', 'numpy', 'pymc'] for lib in libraries: try: imported_lib = import_module(lib) if imported_lib: s0, s1, s2 = [], [], [] s0 = sample(X, size=10, library=lib, seed=0) s1 = sample(X, size=10, library=lib, seed=0) s2 = sample(X, size=10, library=lib, seed=1) for i in range(10): assert (s0[i] == s1[i]).all() assert (s1[i] != s2[i]).all() except NotImplementedError: continue
8cd1281a20f99c4d0974e6acf98b957029cd45337dbdd5a5b6aa1f6a3ac252a5
from __future__ import annotations from sympy.ntheory import qs from sympy.ntheory.qs import SievePolynomial, _generate_factor_base, \ _initialize_first_polynomial, _initialize_ith_poly, \ _gen_sieve_array, _check_smoothness, _trial_division_stage, _gauss_mod_2, \ _build_matrix, _find_factor from sympy.testing.pytest import slow @slow def test_qs_1(): assert qs(10009202107, 100, 10000) == {100043, 100049} assert qs(211107295182713951054568361, 1000, 10000) == \ {13791315212531, 15307263442931} assert qs(980835832582657*990377764891511, 3000, 50000) == \ {980835832582657, 990377764891511} assert qs(18640889198609*20991129234731, 1000, 50000) == \ {18640889198609, 20991129234731} def test_qs_2(): n = 10009202107 M = 50 # a = 10, b = 15, modified_coeff = [a**2, 2*a*b, b**2 - N] sieve_poly = SievePolynomial([100, 1600, -10009195707], 10, 80) assert sieve_poly.eval(10) == -10009169707 assert sieve_poly.eval(5) == -10009185207 idx_1000, idx_5000, factor_base = _generate_factor_base(2000, n) assert idx_1000 == 82 assert [factor_base[i].prime for i in range(15)] == \ [2, 3, 7, 11, 17, 19, 29, 31, 43, 59, 61, 67, 71, 73, 79] assert [factor_base[i].tmem_p for i in range(15)] == \ [1, 1, 3, 5, 3, 6, 6, 14, 1, 16, 24, 22, 18, 22, 15] assert [factor_base[i].log_p for i in range(5)] == \ [710, 1125, 1993, 2455, 2901] g, B = _initialize_first_polynomial( n, M, factor_base, idx_1000, idx_5000, seed=0) assert g.a == 1133107 assert g.b == 682543 assert B == [272889, 409654] assert [factor_base[i].soln1 for i in range(15)] == \ [0, 0, 3, 7, 13, 0, 8, 19, 9, 43, 27, 25, 63, 29, 19] assert [factor_base[i].soln2 for i in range(15)] == \ [0, 1, 1, 3, 12, 16, 15, 6, 15, 1, 56, 55, 61, 58, 16] assert [factor_base[i].a_inv for i in range(15)] == \ [1, 1, 5, 7, 3, 5, 26, 6, 40, 5, 21, 45, 4, 1, 8] assert [factor_base[i].b_ainv for i in range(5)] == \ [[0, 0], [0, 2], [3, 0], [3, 9], [13, 13]] g_1 = _initialize_ith_poly(n, factor_base, 1, g, B) assert g_1.a == 1133107 assert g_1.b == 136765 sieve_array = _gen_sieve_array(M, factor_base) assert sieve_array[0:5] == [8424, 13603, 1835, 5335, 710] assert _check_smoothness(9645, factor_base) == (5, False) assert _check_smoothness(210313, factor_base)[0][0:15] == \ [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1] assert _check_smoothness(210313, factor_base)[1] partial_relations: dict[int, tuple[int, int]] = {} smooth_relation, partial_relation = _trial_division_stage( n, M, factor_base, sieve_array, sieve_poly, partial_relations, ERROR_TERM=25*2**10) assert partial_relations == { 8699: (440, -10009008507), 166741: (490, -10008962007), 131449: (530, -10008921207), 6653: (550, -10008899607) } assert [smooth_relation[i][0] for i in range(5)] == [ -250, -670615476700, -45211565844500, -231723037747200, -1811665537200] assert [smooth_relation[i][1] for i in range(5)] == [ -10009139607, 1133094251961, 5302606761, 53804049849, 1950723889] assert smooth_relation[0][2][0:15] == [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] assert _gauss_mod_2( [[0, 0, 1], [1, 0, 1], [0, 1, 0], [0, 1, 1], [0, 1, 1]] ) == ( [[[0, 1, 1], 3], [[0, 1, 1], 4]], [True, True, True, False, False], [[0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 1, 1], [0, 1, 1]] ) def test_qs_3(): N = 1817 smooth_relations = [ (2455024, 637, [0, 0, 0, 1]), (-27993000, 81536, [0, 1, 0, 1]), (11461840, 12544, [0, 0, 0, 0]), (149, 20384, [0, 1, 0, 1]), (-31138074, 19208, [0, 1, 0, 0]) ] matrix = _build_matrix(smooth_relations) assert matrix == [ [0, 0, 0, 1], [0, 1, 0, 1], [0, 0, 0, 0], [0, 1, 0, 1], [0, 1, 0, 0] ] dependent_row, mark, gauss_matrix = _gauss_mod_2(matrix) assert dependent_row == [[[0, 0, 0, 0], 2], [[0, 1, 0, 0], 3]] assert mark == [True, True, False, False, True] assert gauss_matrix == [ [0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0], [0, 1, 0, 1] ] factor = _find_factor( dependent_row, mark, gauss_matrix, 0, smooth_relations, N) assert factor == 23
d2d8b78380fc841a6fa6c4ab736098211c55c2a2ce44a3b92bcf287df0f029f3
from math import prod from sympy.concrete.expr_with_intlimits import ReorderError from sympy.concrete.products import (Product, product) from sympy.concrete.summations import (Sum, summation, telescopic, eval_sum_residue, _dummy_with_inherited_properties_concrete) from sympy.core.function import (Derivative, Function) from sympy.core import (Catalan, EulerGamma) from sympy.core.facts import InconsistentAssumptions from sympy.core.mod import Mod from sympy.core.numbers import (E, I, Rational, nan, oo, pi) from sympy.core.relational import Eq from sympy.core.numbers import Float from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import (rf, binomial, factorial) from sympy.functions.combinatorial.numbers import harmonic from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import (sinh, tanh) from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.gamma_functions import (gamma, lowergamma) from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.functions.special.zeta_functions import zeta from sympy.integrals.integrals import Integral from sympy.logic.boolalg import And, Or from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.special import Identity from sympy.matrices import (Matrix, SparseMatrix, ImmutableDenseMatrix, ImmutableSparseMatrix, diag) from sympy.sets.fancysets import Range from sympy.sets.sets import Interval from sympy.simplify.combsimp import combsimp from sympy.simplify.simplify import simplify from sympy.tensor.indexed import (Idx, Indexed, IndexedBase) from sympy.testing.pytest import XFAIL, raises, slow from sympy.abc import a, b, c, d, k, m, x, y, z n = Symbol('n', integer=True) f, g = symbols('f g', cls=Function) def test_karr_convention(): # Test the Karr summation convention that we want to hold. # See his paper "Summation in Finite Terms" for a detailed # reasoning why we really want exactly this definition. # The convention is described on page 309 and essentially # in section 1.4, definition 3: # # \sum_{m <= i < n} f(i) 'has the obvious meaning' for m < n # \sum_{m <= i < n} f(i) = 0 for m = n # \sum_{m <= i < n} f(i) = - \sum_{n <= i < m} f(i) for m > n # # It is important to note that he defines all sums with # the upper limit being *exclusive*. # In contrast, SymPy and the usual mathematical notation has: # # sum_{i = a}^b f(i) = f(a) + f(a+1) + ... + f(b-1) + f(b) # # with the upper limit *inclusive*. So translating between # the two we find that: # # \sum_{m <= i < n} f(i) = \sum_{i = m}^{n-1} f(i) # # where we intentionally used two different ways to typeset the # sum and its limits. i = Symbol("i", integer=True) k = Symbol("k", integer=True) j = Symbol("j", integer=True) # A simple example with a concrete summand and symbolic limits. # The normal sum: m = k and n = k + j and therefore m < n: m = k n = k + j a = m b = n - 1 S1 = Sum(i**2, (i, a, b)).doit() # The reversed sum: m = k + j and n = k and therefore m > n: m = k + j n = k a = m b = n - 1 S2 = Sum(i**2, (i, a, b)).doit() assert simplify(S1 + S2) == 0 # Test the empty sum: m = k and n = k and therefore m = n: m = k n = k a = m b = n - 1 Sz = Sum(i**2, (i, a, b)).doit() assert Sz == 0 # Another example this time with an unspecified summand and # numeric limits. (We can not do both tests in the same example.) # The normal sum with m < n: m = 2 n = 11 a = m b = n - 1 S1 = Sum(f(i), (i, a, b)).doit() # The reversed sum with m > n: m = 11 n = 2 a = m b = n - 1 S2 = Sum(f(i), (i, a, b)).doit() assert simplify(S1 + S2) == 0 # Test the empty sum with m = n: m = 5 n = 5 a = m b = n - 1 Sz = Sum(f(i), (i, a, b)).doit() assert Sz == 0 e = Piecewise((exp(-i), Mod(i, 2) > 0), (0, True)) s = Sum(e, (i, 0, 11)) assert s.n(3) == s.doit().n(3) def test_karr_proposition_2a(): # Test Karr, page 309, proposition 2, part a i = Symbol("i", integer=True) u = Symbol("u", integer=True) v = Symbol("v", integer=True) def test_the_sum(m, n): # g g = i**3 + 2*i**2 - 3*i # f = Delta g f = simplify(g.subs(i, i+1) - g) # The sum a = m b = n - 1 S = Sum(f, (i, a, b)).doit() # Test if Sum_{m <= i < n} f(i) = g(n) - g(m) assert simplify(S - (g.subs(i, n) - g.subs(i, m))) == 0 # m < n test_the_sum(u, u+v) # m = n test_the_sum(u, u ) # m > n test_the_sum(u+v, u ) def test_karr_proposition_2b(): # Test Karr, page 309, proposition 2, part b i = Symbol("i", integer=True) u = Symbol("u", integer=True) v = Symbol("v", integer=True) w = Symbol("w", integer=True) def test_the_sum(l, n, m): # Summand s = i**3 # First sum a = l b = n - 1 S1 = Sum(s, (i, a, b)).doit() # Second sum a = l b = m - 1 S2 = Sum(s, (i, a, b)).doit() # Third sum a = m b = n - 1 S3 = Sum(s, (i, a, b)).doit() # Test if S1 = S2 + S3 as required assert S1 - (S2 + S3) == 0 # l < m < n test_the_sum(u, u+v, u+v+w) # l < m = n test_the_sum(u, u+v, u+v ) # l < m > n test_the_sum(u, u+v+w, v ) # l = m < n test_the_sum(u, u, u+v ) # l = m = n test_the_sum(u, u, u ) # l = m > n test_the_sum(u+v, u+v, u ) # l > m < n test_the_sum(u+v, u, u+w ) # l > m = n test_the_sum(u+v, u, u ) # l > m > n test_the_sum(u+v+w, u+v, u ) def test_arithmetic_sums(): assert summation(1, (n, a, b)) == b - a + 1 assert Sum(S.NaN, (n, a, b)) is S.NaN assert Sum(x, (n, a, a)).doit() == x assert Sum(x, (x, a, a)).doit() == a assert Sum(x, (n, 1, a)).doit() == a*x assert Sum(x, (x, Range(1, 11))).doit() == 55 assert Sum(x, (x, Range(1, 11, 2))).doit() == 25 assert Sum(x, (x, Range(1, 10, 2))) == Sum(x, (x, Range(9, 0, -2))) lo, hi = 1, 2 s1 = Sum(n, (n, lo, hi)) s2 = Sum(n, (n, hi, lo)) assert s1 != s2 assert s1.doit() == 3 and s2.doit() == 0 lo, hi = x, x + 1 s1 = Sum(n, (n, lo, hi)) s2 = Sum(n, (n, hi, lo)) assert s1 != s2 assert s1.doit() == 2*x + 1 and s2.doit() == 0 assert Sum(Integral(x, (x, 1, y)) + x, (x, 1, 2)).doit() == \ y**2 + 2 assert summation(1, (n, 1, 10)) == 10 assert summation(2*n, (n, 0, 10**10)) == 100000000010000000000 assert summation(4*n*m, (n, a, 1), (m, 1, d)).expand() == \ 2*d + 2*d**2 + a*d + a*d**2 - d*a**2 - a**2*d**2 assert summation(cos(n), (n, -2, 1)) == cos(-2) + cos(-1) + cos(0) + cos(1) assert summation(cos(n), (n, x, x + 2)) == cos(x) + cos(x + 1) + cos(x + 2) assert isinstance(summation(cos(n), (n, x, x + S.Half)), Sum) assert summation(k, (k, 0, oo)) is oo assert summation(k, (k, Range(1, 11))) == 55 def test_polynomial_sums(): assert summation(n**2, (n, 3, 8)) == 199 assert summation(n, (n, a, b)) == \ ((a + b)*(b - a + 1)/2).expand() assert summation(n**2, (n, 1, b)) == \ ((2*b**3 + 3*b**2 + b)/6).expand() assert summation(n**3, (n, 1, b)) == \ ((b**4 + 2*b**3 + b**2)/4).expand() assert summation(n**6, (n, 1, b)) == \ ((6*b**7 + 21*b**6 + 21*b**5 - 7*b**3 + b)/42).expand() def test_geometric_sums(): assert summation(pi**n, (n, 0, b)) == (1 - pi**(b + 1)) / (1 - pi) assert summation(2 * 3**n, (n, 0, b)) == 3**(b + 1) - 1 assert summation(S.Half**n, (n, 1, oo)) == 1 assert summation(2**n, (n, 0, b)) == 2**(b + 1) - 1 assert summation(2**n, (n, 1, oo)) is oo assert summation(2**(-n), (n, 1, oo)) == 1 assert summation(3**(-n), (n, 4, oo)) == Rational(1, 54) assert summation(2**(-4*n + 3), (n, 1, oo)) == Rational(8, 15) assert summation(2**(n + 1), (n, 1, b)).expand() == 4*(2**b - 1) # issue 6664: assert summation(x**n, (n, 0, oo)) == \ Piecewise((1/(-x + 1), Abs(x) < 1), (Sum(x**n, (n, 0, oo)), True)) assert summation(-2**n, (n, 0, oo)) is -oo assert summation(I**n, (n, 0, oo)) == Sum(I**n, (n, 0, oo)) # issue 6802: assert summation((-1)**(2*x + 2), (x, 0, n)) == n + 1 assert summation((-2)**(2*x + 2), (x, 0, n)) == 4*4**(n + 1)/S(3) - Rational(4, 3) assert summation((-1)**x, (x, 0, n)) == -(-1)**(n + 1)/S(2) + S.Half assert summation(y**x, (x, a, b)) == \ Piecewise((-a + b + 1, Eq(y, 1)), ((y**a - y**(b + 1))/(-y + 1), True)) assert summation((-2)**(y*x + 2), (x, 0, n)) == \ 4*Piecewise((n + 1, Eq((-2)**y, 1)), ((-(-2)**(y*(n + 1)) + 1)/(-(-2)**y + 1), True)) # issue 8251: assert summation((1/(n + 1)**2)*n**2, (n, 0, oo)) is oo #issue 9908: assert Sum(1/(n**3 - 1), (n, -oo, -2)).doit() == summation(1/(n**3 - 1), (n, -oo, -2)) #issue 11642: result = Sum(0.5**n, (n, 1, oo)).doit() assert result == 1.0 assert result.is_Float result = Sum(0.25**n, (n, 1, oo)).doit() assert result == 1/3. assert result.is_Float result = Sum(0.99999**n, (n, 1, oo)).doit() assert result == 99999.0 assert result.is_Float result = Sum(S.Half**n, (n, 1, oo)).doit() assert result == 1 assert not result.is_Float result = Sum(Rational(3, 5)**n, (n, 1, oo)).doit() assert result == Rational(3, 2) assert not result.is_Float assert Sum(1.0**n, (n, 1, oo)).doit() is oo assert Sum(2.43**n, (n, 1, oo)).doit() is oo # Issue 13979 i, k, q = symbols('i k q', integer=True) result = summation( exp(-2*I*pi*k*i/n) * exp(2*I*pi*q*i/n) / n, (i, 0, n - 1) ) assert result.simplify() == Piecewise( (1, Eq(exp(-2*I*pi*(k - q)/n), 1)), (0, True) ) #Issue 23491 assert Sum(1/(n**2 + 1), (n, 1, oo)).doit() == S(-1)/2 + pi/(2*tanh(pi)) def test_harmonic_sums(): assert summation(1/k, (k, 0, n)) == Sum(1/k, (k, 0, n)) assert summation(1/k, (k, 1, n)) == harmonic(n) assert summation(n/k, (k, 1, n)) == n*harmonic(n) assert summation(1/k, (k, 5, n)) == harmonic(n) - harmonic(4) def test_composite_sums(): f = S.Half*(7 - 6*n + Rational(1, 7)*n**3) s = summation(f, (n, a, b)) assert not isinstance(s, Sum) A = 0 for i in range(-3, 5): A += f.subs(n, i) B = s.subs(a, -3).subs(b, 4) assert A == B def test_hypergeometric_sums(): assert summation( binomial(2*k, k)/4**k, (k, 0, n)) == (1 + 2*n)*binomial(2*n, n)/4**n assert summation(binomial(2*k, k)/5**k, (k, -oo, oo)) == sqrt(5) def test_other_sums(): f = m**2 + m*exp(m) g = 3*exp(Rational(3, 2))/2 + exp(S.Half)/2 - exp(Rational(-1, 2))/2 - 3*exp(Rational(-3, 2))/2 + 5 assert summation(f, (m, Rational(-3, 2), Rational(3, 2))) == g assert summation(f, (m, -1.5, 1.5)).evalf().epsilon_eq(g.evalf(), 1e-10) fac = factorial def NS(e, n=15, **options): return str(sympify(e).evalf(n, **options)) def test_evalf_fast_series(): # Euler transformed series for sqrt(1+x) assert NS(Sum( fac(2*n + 1)/fac(n)**2/2**(3*n + 1), (n, 0, oo)), 100) == NS(sqrt(2), 100) # Some series for exp(1) estr = NS(E, 100) assert NS(Sum(1/fac(n), (n, 0, oo)), 100) == estr assert NS(1/Sum((1 - 2*n)/fac(2*n), (n, 0, oo)), 100) == estr assert NS(Sum((2*n + 1)/fac(2*n), (n, 0, oo)), 100) == estr assert NS(Sum((4*n + 3)/2**(2*n + 1)/fac(2*n + 1), (n, 0, oo))**2, 100) == estr pistr = NS(pi, 100) # Ramanujan series for pi assert NS(9801/sqrt(8)/Sum(fac( 4*n)*(1103 + 26390*n)/fac(n)**4/396**(4*n), (n, 0, oo)), 100) == pistr assert NS(1/Sum( binomial(2*n, n)**3 * (42*n + 5)/2**(12*n + 4), (n, 0, oo)), 100) == pistr # Machin's formula for pi assert NS(16*Sum((-1)**n/(2*n + 1)/5**(2*n + 1), (n, 0, oo)) - 4*Sum((-1)**n/(2*n + 1)/239**(2*n + 1), (n, 0, oo)), 100) == pistr # Apery's constant astr = NS(zeta(3), 100) P = 126392*n**5 + 412708*n**4 + 531578*n**3 + 336367*n**2 + 104000* \ n + 12463 assert NS(Sum((-1)**n * P / 24 * (fac(2*n + 1)*fac(2*n)*fac( n))**3 / fac(3*n + 2) / fac(4*n + 3)**3, (n, 0, oo)), 100) == astr assert NS(Sum((-1)**n * (205*n**2 + 250*n + 77)/64 * fac(n)**10 / fac(2*n + 1)**5, (n, 0, oo)), 100) == astr def test_evalf_fast_series_issue_4021(): # Catalan's constant assert NS(Sum((-1)**(n - 1)*2**(8*n)*(40*n**2 - 24*n + 3)*fac(2*n)**3* fac(n)**2/n**3/(2*n - 1)/fac(4*n)**2, (n, 1, oo))/64, 100) == \ NS(Catalan, 100) astr = NS(zeta(3), 100) assert NS(5*Sum( (-1)**(n - 1)*fac(n)**2 / n**3 / fac(2*n), (n, 1, oo))/2, 100) == astr assert NS(Sum((-1)**(n - 1)*(56*n**2 - 32*n + 5) / (2*n - 1)**2 * fac(n - 1) **3 / fac(3*n), (n, 1, oo))/4, 100) == astr def test_evalf_slow_series(): assert NS(Sum((-1)**n / n, (n, 1, oo)), 15) == NS(-log(2), 15) assert NS(Sum((-1)**n / n, (n, 1, oo)), 50) == NS(-log(2), 50) assert NS(Sum(1/n**2, (n, 1, oo)), 15) == NS(pi**2/6, 15) assert NS(Sum(1/n**2, (n, 1, oo)), 100) == NS(pi**2/6, 100) assert NS(Sum(1/n**2, (n, 1, oo)), 500) == NS(pi**2/6, 500) assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 15) == NS(pi**3/32, 15) assert NS(Sum((-1)**n / (2*n + 1)**3, (n, 0, oo)), 50) == NS(pi**3/32, 50) def test_evalf_oo_to_oo(): # There used to be an error in certain cases # Does not evaluate, but at least do not throw an error # Evaluates symbolically to 0, which is not correct assert Sum(1/(n**2+1), (n, -oo, oo)).evalf() == Sum(1/(n**2+1), (n, -oo, oo)) # This evaluates if from 1 to oo and symbolically assert Sum(1/(factorial(abs(n))), (n, -oo, -1)).evalf() == Sum(1/(factorial(abs(n))), (n, -oo, -1)) def test_euler_maclaurin(): # Exact polynomial sums with E-M def check_exact(f, a, b, m, n): A = Sum(f, (k, a, b)) s, e = A.euler_maclaurin(m, n) assert (e == 0) and (s.expand() == A.doit()) check_exact(k**4, a, b, 0, 2) check_exact(k**4 + 2*k, a, b, 1, 2) check_exact(k**4 + k**2, a, b, 1, 5) check_exact(k**5, 2, 6, 1, 2) check_exact(k**5, 2, 6, 1, 3) assert Sum(x-1, (x, 0, 2)).euler_maclaurin(m=30, n=30, eps=2**-15) == (0, 0) # Not exact assert Sum(k**6, (k, a, b)).euler_maclaurin(0, 2)[1] != 0 # Numerical test for mi, ni in [(2, 4), (2, 20), (10, 20), (18, 20)]: A = Sum(1/k**3, (k, 1, oo)) s, e = A.euler_maclaurin(mi, ni) assert abs((s - zeta(3)).evalf()) < e.evalf() raises(ValueError, lambda: Sum(1, (x, 0, 1), (k, 0, 1)).euler_maclaurin()) @slow def test_evalf_euler_maclaurin(): assert NS(Sum(1/k**k, (k, 1, oo)), 15) == '1.29128599706266' assert NS(Sum(1/k**k, (k, 1, oo)), 50) == '1.2912859970626635404072825905956005414986193682745' assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 15) == NS(EulerGamma, 15) assert NS(Sum(1/k - log(1 + 1/k), (k, 1, oo)), 50) == NS(EulerGamma, 50) assert NS(Sum(log(k)/k**2, (k, 1, oo)), 15) == '0.937548254315844' assert NS(Sum(log(k)/k**2, (k, 1, oo)), 50) == '0.93754825431584375370257409456786497789786028861483' assert NS(Sum(1/k, (k, 1000000, 2000000)), 15) == '0.693147930560008' assert NS(Sum(1/k, (k, 1000000, 2000000)), 50) == '0.69314793056000780941723211364567656807940638436025' def test_evalf_symbolic(): # issue 6328 expr = Sum(f(x), (x, 1, 3)) + Sum(g(x), (x, 1, 3)) assert expr.evalf() == expr def test_evalf_issue_3273(): assert Sum(0, (k, 1, oo)).evalf() == 0 def test_simple_products(): assert Product(S.NaN, (x, 1, 3)) is S.NaN assert product(S.NaN, (x, 1, 3)) is S.NaN assert Product(x, (n, a, a)).doit() == x assert Product(x, (x, a, a)).doit() == a assert Product(x, (y, 1, a)).doit() == x**a lo, hi = 1, 2 s1 = Product(n, (n, lo, hi)) s2 = Product(n, (n, hi, lo)) assert s1 != s2 # This IS correct according to Karr product convention assert s1.doit() == 2 assert s2.doit() == 1 lo, hi = x, x + 1 s1 = Product(n, (n, lo, hi)) s2 = Product(n, (n, hi, lo)) s3 = 1 / Product(n, (n, hi + 1, lo - 1)) assert s1 != s2 # This IS correct according to Karr product convention assert s1.doit() == x*(x + 1) assert s2.doit() == 1 assert s3.doit() == x*(x + 1) assert Product(Integral(2*x, (x, 1, y)) + 2*x, (x, 1, 2)).doit() == \ (y**2 + 1)*(y**2 + 3) assert product(2, (n, a, b)) == 2**(b - a + 1) assert product(n, (n, 1, b)) == factorial(b) assert product(n**3, (n, 1, b)) == factorial(b)**3 assert product(3**(2 + n), (n, a, b)) \ == 3**(2*(1 - a + b) + b/2 + (b**2)/2 + a/2 - (a**2)/2) assert product(cos(n), (n, 3, 5)) == cos(3)*cos(4)*cos(5) assert product(cos(n), (n, x, x + 2)) == cos(x)*cos(x + 1)*cos(x + 2) assert isinstance(product(cos(n), (n, x, x + S.Half)), Product) # If Product managed to evaluate this one, it most likely got it wrong! assert isinstance(Product(n**n, (n, 1, b)), Product) def test_rational_products(): assert combsimp(product(1 + 1/n, (n, a, b))) == (1 + b)/a assert combsimp(product(n + 1, (n, a, b))) == gamma(2 + b)/gamma(1 + a) assert combsimp(product((n + 1)/(n - 1), (n, a, b))) == b*(1 + b)/(a*(a - 1)) assert combsimp(product(n/(n + 1)/(n + 2), (n, a, b))) == \ a*gamma(a + 2)/(b + 1)/gamma(b + 3) assert combsimp(product(n*(n + 1)/(n - 1)/(n - 2), (n, a, b))) == \ b**2*(b - 1)*(1 + b)/(a - 1)**2/(a*(a - 2)) def test_wallis_product(): # Wallis product, given in two different forms to ensure that Product # can factor simple rational expressions A = Product(4*n**2 / (4*n**2 - 1), (n, 1, b)) B = Product((2*n)*(2*n)/(2*n - 1)/(2*n + 1), (n, 1, b)) R = pi*gamma(b + 1)**2/(2*gamma(b + S.Half)*gamma(b + Rational(3, 2))) assert simplify(A.doit()) == R assert simplify(B.doit()) == R # This one should eventually also be doable (Euler's product formula for sin) # assert Product(1+x/n**2, (n, 1, b)) == ... def test_telescopic_sums(): #checks also input 2 of comment 1 issue 4127 assert Sum(1/k - 1/(k + 1), (k, 1, n)).doit() == 1 - 1/(1 + n) assert Sum( f(k) - f(k + 2), (k, m, n)).doit() == -f(1 + n) - f(2 + n) + f(m) + f(1 + m) assert Sum(cos(k) - cos(k + 3), (k, 1, n)).doit() == -cos(1 + n) - \ cos(2 + n) - cos(3 + n) + cos(1) + cos(2) + cos(3) # dummy variable shouldn't matter assert telescopic(1/m, -m/(1 + m), (m, n - 1, n)) == \ telescopic(1/k, -k/(1 + k), (k, n - 1, n)) assert Sum(1/x/(x - 1), (x, a, b)).doit() == 1/(a - 1) - 1/b eq = 1/((5*n + 2)*(5*(n + 1) + 2)) assert Sum(eq, (n, 0, oo)).doit() == S(1)/10 nz = symbols('nz', nonzero=True) v = Sum(eq.subs(5, nz), (n, 0, oo)).doit() assert v.subs(nz, 5).simplify() == S(1)/10 # check that apart is being used in non-symbolic case s = Sum(eq, (n, 0, k)).doit() v = Sum(eq, (n, 0, 10**100)).doit() assert v == s.subs(k, 10**100) def test_sum_reconstruct(): s = Sum(n**2, (n, -1, 1)) assert s == Sum(*s.args) raises(ValueError, lambda: Sum(x, x)) raises(ValueError, lambda: Sum(x, (x, 1))) def test_limit_subs(): for F in (Sum, Product, Integral): assert F(a*exp(a), (a, -2, 2)) == F(a*exp(a), (a, -b, b)).subs(b, 2) assert F(a, (a, F(b, (b, 1, 2)), 4)).subs(F(b, (b, 1, 2)), c) == \ F(a, (a, c, 4)) assert F(x, (x, 1, x + y)).subs(x, 1) == F(x, (x, 1, y + 1)) def test_function_subs(): S = Sum(x*f(y),(x,0,oo),(y,0,oo)) assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo)) assert S.subs(f(x),x) == S raises(ValueError, lambda: S.subs(f(y),x+y) ) S = Sum(x*log(y),(x,0,oo),(y,0,oo)) assert S.subs(log(y),y) == S S = Sum(x*f(y),(x,0,oo),(y,0,oo)) assert S.subs(f(y),y) == Sum(x*y,(x,0,oo),(y,0,oo)) def test_equality(): # if this fails remove special handling below raises(ValueError, lambda: Sum(x, x)) r = symbols('x', real=True) for F in (Sum, Product, Integral): try: assert F(x, x) != F(y, y) assert F(x, (x, 1, 2)) != F(x, x) assert F(x, (x, x)) != F(x, x) # or else they print the same assert F(1, x) != F(1, y) except ValueError: pass assert F(a, (x, 1, 2)) != F(a, (x, 1, 3)) # diff limit assert F(a, (x, 1, x)) != F(a, (y, 1, y)) assert F(a, (x, 1, 2)) != F(b, (x, 1, 2)) # diff expression assert F(x, (x, 1, 2)) != F(r, (r, 1, 2)) # diff assumptions assert F(1, (x, 1, x)) != F(1, (y, 1, x)) # only dummy is diff assert F(1, (x, 1, x)).dummy_eq(F(1, (y, 1, x))) # issue 5265 assert Sum(x, (x, 1, x)).subs(x, a) == Sum(x, (x, 1, a)) def test_Sum_doit(): assert Sum(n*Integral(a**2), (n, 0, 2)).doit() == a**3 assert Sum(n*Integral(a**2), (n, 0, 2)).doit(deep=False) == \ 3*Integral(a**2) assert summation(n*Integral(a**2), (n, 0, 2)) == 3*Integral(a**2) # test nested sum evaluation s = Sum( Sum( Sum(2,(z,1,n+1)), (y,x+1,n)), (x,1,n)) assert 0 == (s.doit() - n*(n+1)*(n-1)).factor() # Integer assumes finite assert Sum(KroneckerDelta(x, y), (x, -oo, oo)).doit() == Piecewise((1, And(-oo < y, y < oo)), (0, True)) assert Sum(KroneckerDelta(m, n), (m, -oo, oo)).doit() == 1 assert Sum(m*KroneckerDelta(x, y), (x, -oo, oo)).doit() == Piecewise((m, And(-oo < y, y < oo)), (0, True)) assert Sum(x*KroneckerDelta(m, n), (m, -oo, oo)).doit() == x assert Sum(Sum(KroneckerDelta(m, n), (m, 1, 3)), (n, 1, 3)).doit() == 3 assert Sum(Sum(KroneckerDelta(k, m), (m, 1, 3)), (n, 1, 3)).doit() == \ 3 * Piecewise((1, And(1 <= k, k <= 3)), (0, True)) assert Sum(f(n) * Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, 3)).doit() == \ f(1) + f(2) + f(3) assert Sum(f(n) * Sum(KroneckerDelta(m, n), (m, 0, oo)), (n, 1, oo)).doit() == \ Sum(f(n), (n, 1, oo)) # issue 2597 nmax = symbols('N', integer=True, positive=True) pw = Piecewise((1, And(1 <= n, n <= nmax)), (0, True)) assert Sum(pw, (n, 1, nmax)).doit() == Sum(Piecewise((1, nmax >= n), (0, True)), (n, 1, nmax)) q, s = symbols('q, s') assert summation(1/n**(2*s), (n, 1, oo)) == Piecewise((zeta(2*s), 2*s > 1), (Sum(n**(-2*s), (n, 1, oo)), True)) assert summation(1/(n+1)**s, (n, 0, oo)) == Piecewise((zeta(s), s > 1), (Sum((n + 1)**(-s), (n, 0, oo)), True)) assert summation(1/(n+q)**s, (n, 0, oo)) == Piecewise( (zeta(s, q), And(q > 0, s > 1)), (Sum((n + q)**(-s), (n, 0, oo)), True)) assert summation(1/(n+q)**s, (n, q, oo)) == Piecewise( (zeta(s, 2*q), And(2*q > 0, s > 1)), (Sum((n + q)**(-s), (n, q, oo)), True)) assert summation(1/n**2, (n, 1, oo)) == zeta(2) assert summation(1/n**s, (n, 0, oo)) == Sum(n**(-s), (n, 0, oo)) def test_Product_doit(): assert Product(n*Integral(a**2), (n, 1, 3)).doit() == 2 * a**9 / 9 assert Product(n*Integral(a**2), (n, 1, 3)).doit(deep=False) == \ 6*Integral(a**2)**3 assert product(n*Integral(a**2), (n, 1, 3)) == 6*Integral(a**2)**3 def test_Sum_interface(): assert isinstance(Sum(0, (n, 0, 2)), Sum) assert Sum(nan, (n, 0, 2)) is nan assert Sum(nan, (n, 0, oo)) is nan assert Sum(0, (n, 0, 2)).doit() == 0 assert isinstance(Sum(0, (n, 0, oo)), Sum) assert Sum(0, (n, 0, oo)).doit() == 0 raises(ValueError, lambda: Sum(1)) raises(ValueError, lambda: summation(1)) def test_diff(): assert Sum(x, (x, 1, 2)).diff(x) == 0 assert Sum(x*y, (x, 1, 2)).diff(x) == 0 assert Sum(x*y, (y, 1, 2)).diff(x) == Sum(y, (y, 1, 2)) e = Sum(x*y, (x, 1, a)) assert e.diff(a) == Derivative(e, a) assert Sum(x*y, (x, 1, 3), (a, 2, 5)).diff(y).doit() == \ Sum(x*y, (x, 1, 3), (a, 2, 5)).doit().diff(y) == 24 assert Sum(x, (x, 1, 2)).diff(y) == 0 def test_hypersum(): assert simplify(summation(x**n/fac(n), (n, 1, oo))) == -1 + exp(x) assert summation((-1)**n * x**(2*n) / fac(2*n), (n, 0, oo)) == cos(x) assert simplify(summation((-1)**n*x**(2*n + 1) / factorial(2*n + 1), (n, 3, oo))) == -x + sin(x) + x**3/6 - x**5/120 assert summation(1/(n + 2)**3, (n, 1, oo)) == Rational(-9, 8) + zeta(3) assert summation(1/n**4, (n, 1, oo)) == pi**4/90 s = summation(x**n*n, (n, -oo, 0)) assert s.is_Piecewise assert s.args[0].args[0] == -1/(x*(1 - 1/x)**2) assert s.args[0].args[1] == (abs(1/x) < 1) m = Symbol('n', integer=True, positive=True) assert summation(binomial(m, k), (k, 0, m)) == 2**m def test_issue_4170(): assert summation(1/factorial(k), (k, 0, oo)) == E def test_is_commutative(): from sympy.physics.secondquant import NO, F, Fd m = Symbol('m', commutative=False) for f in (Sum, Product, Integral): assert f(z, (z, 1, 1)).is_commutative is True assert f(z*y, (z, 1, 6)).is_commutative is True assert f(m*x, (x, 1, 2)).is_commutative is False assert f(NO(Fd(x)*F(y))*z, (z, 1, 2)).is_commutative is False def test_is_zero(): for func in [Sum, Product]: assert func(0, (x, 1, 1)).is_zero is True assert func(x, (x, 1, 1)).is_zero is None assert Sum(0, (x, 1, 0)).is_zero is True assert Product(0, (x, 1, 0)).is_zero is False def test_is_number(): # is number should not rely on evaluation or assumptions, # it should be equivalent to `not foo.free_symbols` assert Sum(1, (x, 1, 1)).is_number is True assert Sum(1, (x, 1, x)).is_number is False assert Sum(0, (x, y, z)).is_number is False assert Sum(x, (y, 1, 2)).is_number is False assert Sum(x, (y, 1, 1)).is_number is False assert Sum(x, (x, 1, 2)).is_number is True assert Sum(x*y, (x, 1, 2), (y, 1, 3)).is_number is True assert Product(2, (x, 1, 1)).is_number is True assert Product(2, (x, 1, y)).is_number is False assert Product(0, (x, y, z)).is_number is False assert Product(1, (x, y, z)).is_number is False assert Product(x, (y, 1, x)).is_number is False assert Product(x, (y, 1, 2)).is_number is False assert Product(x, (y, 1, 1)).is_number is False assert Product(x, (x, 1, 2)).is_number is True def test_free_symbols(): for func in [Sum, Product]: assert func(1, (x, 1, 2)).free_symbols == set() assert func(0, (x, 1, y)).free_symbols == {y} assert func(2, (x, 1, y)).free_symbols == {y} assert func(x, (x, 1, 2)).free_symbols == set() assert func(x, (x, 1, y)).free_symbols == {y} assert func(x, (y, 1, y)).free_symbols == {x, y} assert func(x, (y, 1, 2)).free_symbols == {x} assert func(x, (y, 1, 1)).free_symbols == {x} assert func(x, (y, 1, z)).free_symbols == {x, z} assert func(x, (x, 1, y), (y, 1, 2)).free_symbols == set() assert func(x, (x, 1, y), (y, 1, z)).free_symbols == {z} assert func(x, (x, 1, y), (y, 1, y)).free_symbols == {y} assert func(x, (y, 1, y), (y, 1, z)).free_symbols == {x, z} assert Sum(1, (x, 1, y)).free_symbols == {y} # free_symbols answers whether the object *as written* has free symbols, # not whether the evaluated expression has free symbols assert Product(1, (x, 1, y)).free_symbols == {y} # don't count free symbols that are not independent of integration # variable(s) assert func(f(x), (f(x), 1, 2)).free_symbols == set() assert func(f(x), (f(x), 1, x)).free_symbols == {x} assert func(f(x), (f(x), 1, y)).free_symbols == {y} assert func(f(x), (z, 1, y)).free_symbols == {x, y} def test_conjugate_transpose(): A, B = symbols("A B", commutative=False) p = Sum(A*B**n, (n, 1, 3)) assert p.adjoint().doit() == p.doit().adjoint() assert p.conjugate().doit() == p.doit().conjugate() assert p.transpose().doit() == p.doit().transpose() p = Sum(B**n*A, (n, 1, 3)) assert p.adjoint().doit() == p.doit().adjoint() assert p.conjugate().doit() == p.doit().conjugate() assert p.transpose().doit() == p.doit().transpose() def test_noncommutativity_honoured(): A, B = symbols("A B", commutative=False) M = symbols('M', integer=True, positive=True) p = Sum(A*B**n, (n, 1, M)) assert p.doit() == A*Piecewise((M, Eq(B, 1)), ((B - B**(M + 1))*(1 - B)**(-1), True)) p = Sum(B**n*A, (n, 1, M)) assert p.doit() == Piecewise((M, Eq(B, 1)), ((B - B**(M + 1))*(1 - B)**(-1), True))*A p = Sum(B**n*A*B**n, (n, 1, M)) assert p.doit() == p def test_issue_4171(): assert summation(factorial(2*k + 1)/factorial(2*k), (k, 0, oo)) is oo assert summation(2*k + 1, (k, 0, oo)) is oo def test_issue_6273(): assert Sum(x, (x, 1, n)).n(2, subs={n: 1}) == Float(1, 2) def test_issue_6274(): assert Sum(x, (x, 1, 0)).doit() == 0 assert NS(Sum(x, (x, 1, 0))) == '0' assert Sum(n, (n, 10, 5)).doit() == -30 assert NS(Sum(n, (n, 10, 5))) == '-30.0000000000000' def test_simplify_sum(): y, t, v = symbols('y, t, v') _simplify = lambda e: simplify(e, doit=False) assert _simplify(Sum(x*y, (x, n, m), (y, a, k)) + \ Sum(y, (x, n, m), (y, a, k))) == Sum(y * (x + 1), (x, n, m), (y, a, k)) assert _simplify(Sum(x, (x, n, m)) + Sum(x, (x, m + 1, a))) == \ Sum(x, (x, n, a)) assert _simplify(Sum(x, (x, k + 1, a)) + Sum(x, (x, n, k))) == \ Sum(x, (x, n, a)) assert _simplify(Sum(x, (x, k + 1, a)) + Sum(x + 1, (x, n, k))) == \ Sum(x, (x, n, a)) + Sum(1, (x, n, k)) assert _simplify(Sum(x, (x, 0, 3)) * 3 + 3 * Sum(x, (x, 4, 6)) + \ 4 * Sum(z, (z, 0, 1))) == 4*Sum(z, (z, 0, 1)) + 3*Sum(x, (x, 0, 6)) assert _simplify(3*Sum(x**2, (x, a, b)) + Sum(x, (x, a, b))) == \ Sum(x*(3*x + 1), (x, a, b)) assert _simplify(Sum(x**3, (x, n, k)) * 3 + 3 * Sum(x, (x, n, k)) + \ 4 * y * Sum(z, (z, n, k))) + 1 == \ 4*y*Sum(z, (z, n, k)) + 3*Sum(x**3 + x, (x, n, k)) + 1 assert _simplify(Sum(x, (x, a, b)) + 1 + Sum(x, (x, b + 1, c))) == \ 1 + Sum(x, (x, a, c)) assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + \ Sum(x, (t, b+1, c))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b)) assert _simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + \ Sum(y, (t, a, b))) == x * Sum(1, (t, a, c)) + y * Sum(1, (t, a, b)) assert _simplify(Sum(x, (t, a, b)) + 2 * Sum(x, (t, b+1, c))) == \ _simplify(Sum(x, (t, a, b)) + Sum(x, (t, b+1, c)) + Sum(x, (t, b+1, c))) assert _simplify(Sum(x, (x, a, b))*Sum(x**2, (x, a, b))) == \ Sum(x, (x, a, b)) * Sum(x**2, (x, a, b)) assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b))) \ == (x + y + z) * Sum(1, (t, a, b)) # issue 8596 assert _simplify(Sum(x, (t, a, b)) + Sum(y, (t, a, b)) + Sum(z, (t, a, b)) + \ Sum(v, (t, a, b))) == (x + y + z + v) * Sum(1, (t, a, b)) # issue 8596 assert _simplify(Sum(x * y, (x, a, b)) / (3 * y)) == \ (Sum(x, (x, a, b)) / 3) assert _simplify(Sum(f(x) * y * z, (x, a, b)) / (y * z)) \ == Sum(f(x), (x, a, b)) assert _simplify(Sum(c * x, (x, a, b)) - c * Sum(x, (x, a, b))) == 0 assert _simplify(c * (Sum(x, (x, a, b)) + y)) == c * (y + Sum(x, (x, a, b))) assert _simplify(c * (Sum(x, (x, a, b)) + y * Sum(x, (x, a, b)))) == \ c * (y + 1) * Sum(x, (x, a, b)) assert _simplify(Sum(Sum(c * x, (x, a, b)), (y, a, b))) == \ c * Sum(x, (x, a, b), (y, a, b)) assert _simplify(Sum((3 + y) * Sum(c * x, (x, a, b)), (y, a, b))) == \ c * Sum((3 + y), (y, a, b)) * Sum(x, (x, a, b)) assert _simplify(Sum((3 + t) * Sum(c * t, (x, a, b)), (y, a, b))) == \ c*t*(t + 3)*Sum(1, (x, a, b))*Sum(1, (y, a, b)) assert _simplify(Sum(Sum(d * t, (x, a, b - 1)) + \ Sum(d * t, (x, b, c)), (t, a, b))) == \ d * Sum(1, (x, a, c)) * Sum(t, (t, a, b)) assert _simplify(Sum(sin(t)**2 + cos(t)**2 + 1, (t, a, b))) == \ 2 * Sum(1, (t, a, b)) def test_change_index(): b, v, w = symbols('b, v, w', integer = True) assert Sum(x, (x, a, b)).change_index(x, x + 1, y) == \ Sum(y - 1, (y, a + 1, b + 1)) assert Sum(x**2, (x, a, b)).change_index( x, x - 1) == \ Sum((x+1)**2, (x, a - 1, b - 1)) assert Sum(x**2, (x, a, b)).change_index( x, -x, y) == \ Sum((-y)**2, (y, -b, -a)) assert Sum(x, (x, a, b)).change_index( x, -x - 1) == \ Sum(-x - 1, (x, -b - 1, -a - 1)) assert Sum(x*y, (x, a, b), (y, c, d)).change_index( x, x - 1, z) == \ Sum((z + 1)*y, (z, a - 1, b - 1), (y, c, d)) assert Sum(x, (x, a, b)).change_index( x, x + v) == \ Sum(-v + x, (x, a + v, b + v)) assert Sum(x, (x, a, b)).change_index( x, -x - v) == \ Sum(-v - x, (x, -b - v, -a - v)) assert Sum(x, (x, a, b)).change_index(x, w*x, v) == \ Sum(v/w, (v, b*w, a*w)) raises(ValueError, lambda: Sum(x, (x, a, b)).change_index(x, 2*x)) def test_reorder(): b, y, c, d, z = symbols('b, y, c, d, z', integer = True) assert Sum(x*y, (x, a, b), (y, c, d)).reorder((0, 1)) == \ Sum(x*y, (y, c, d), (x, a, b)) assert Sum(x, (x, a, b), (x, c, d)).reorder((0, 1)) == \ Sum(x, (x, c, d), (x, a, b)) assert Sum(x*y + z, (x, a, b), (z, m, n), (y, c, d)).reorder(\ (2, 0), (0, 1)) == Sum(x*y + z, (z, m, n), (y, c, d), (x, a, b)) assert Sum(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\ (0, 1), (1, 2), (0, 2)) == Sum(x*y*z, (x, a, b), (z, m, n), (y, c, d)) assert Sum(x*y*z, (x, a, b), (y, c, d), (z, m, n)).reorder(\ (x, y), (y, z), (x, z)) == Sum(x*y*z, (x, a, b), (z, m, n), (y, c, d)) assert Sum(x*y, (x, a, b), (y, c, d)).reorder((x, 1)) == \ Sum(x*y, (y, c, d), (x, a, b)) assert Sum(x*y, (x, a, b), (y, c, d)).reorder((y, x)) == \ Sum(x*y, (y, c, d), (x, a, b)) def test_reverse_order(): assert Sum(x, (x, 0, 3)).reverse_order(0) == Sum(-x, (x, 4, -1)) assert Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(0, 1) == \ Sum(x*y, (x, 6, 0), (y, 7, -1)) assert Sum(x, (x, 1, 2)).reverse_order(0) == Sum(-x, (x, 3, 0)) assert Sum(x, (x, 1, 3)).reverse_order(0) == Sum(-x, (x, 4, 0)) assert Sum(x, (x, 1, a)).reverse_order(0) == Sum(-x, (x, a + 1, 0)) assert Sum(x, (x, a, 5)).reverse_order(0) == Sum(-x, (x, 6, a - 1)) assert Sum(x, (x, a + 1, a + 5)).reverse_order(0) == \ Sum(-x, (x, a + 6, a)) assert Sum(x, (x, a + 1, a + 2)).reverse_order(0) == \ Sum(-x, (x, a + 3, a)) assert Sum(x, (x, a + 1, a + 1)).reverse_order(0) == \ Sum(-x, (x, a + 2, a)) assert Sum(x, (x, a, b)).reverse_order(0) == Sum(-x, (x, b + 1, a - 1)) assert Sum(x, (x, a, b)).reverse_order(x) == Sum(-x, (x, b + 1, a - 1)) assert Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) == \ Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) assert Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) == \ Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) def test_issue_7097(): assert sum(x**n/n for n in range(1, 401)) == summation(x**n/n, (n, 1, 400)) def test_factor_expand_subs(): # test factoring assert Sum(4 * x, (x, 1, y)).factor() == 4 * Sum(x, (x, 1, y)) assert Sum(x * a, (x, 1, y)).factor() == a * Sum(x, (x, 1, y)) assert Sum(4 * x * a, (x, 1, y)).factor() == 4 * a * Sum(x, (x, 1, y)) assert Sum(4 * x * y, (x, 1, y)).factor() == 4 * y * Sum(x, (x, 1, y)) # test expand _x = Symbol('x', zero=False) assert Sum(x+1,(x,1,y)).expand() == Sum(x,(x,1,y)) + Sum(1,(x,1,y)) assert Sum(x+a*x**2,(x,1,y)).expand() == Sum(x,(x,1,y)) + Sum(a*x**2,(x,1,y)) assert Sum(_x**(n + 1)*(n + 1), (n, -1, oo)).expand() \ == Sum(n*_x*_x**n + _x*_x**n, (n, -1, oo)) assert Sum(x**(n + 1)*(n + 1), (n, -1, oo)).expand(power_exp=False) \ == Sum(n*x**(n + 1) + x**(n + 1), (n, -1, oo)) assert Sum(x**(n + 1)*(n + 1), (n, -1, oo)).expand(force=True) \ == Sum(x*x**n, (n, -1, oo)) + Sum(n*x*x**n, (n, -1, oo)) assert Sum(a*n+a*n**2,(n,0,4)).expand() \ == Sum(a*n,(n,0,4)) + Sum(a*n**2,(n,0,4)) assert Sum(_x**a*_x**n,(x,0,3)) \ == Sum(_x**(a+n),(x,0,3)).expand(power_exp=True) _a, _n = symbols('a n', positive=True) assert Sum(x**(_a+_n),(x,0,3)).expand(power_exp=True) \ == Sum(x**_a*x**_n, (x, 0, 3)) assert Sum(x**(_a-_n),(x,0,3)).expand(power_exp=True) \ == Sum(x**(_a-_n),(x,0,3)).expand(power_exp=False) # test subs assert Sum(1/(1+a*x**2),(x,0,3)).subs([(a,3)]) == Sum(1/(1+3*x**2),(x,0,3)) assert Sum(x*y,(x,0,y),(y,0,x)).subs([(x,3)]) == Sum(x*y,(x,0,y),(y,0,3)) assert Sum(x,(x,1,10)).subs([(x,y-2)]) == Sum(x,(x,1,10)) assert Sum(1/x,(x,1,10)).subs([(x,(3+n)**3)]) == Sum(1/x,(x,1,10)) assert Sum(1/x,(x,1,10)).subs([(x,3*x-2)]) == Sum(1/x,(x,1,10)) def test_distribution_over_equality(): assert Product(Eq(x*2, f(x)), (x, 1, 3)).doit() == Eq(48, f(1)*f(2)*f(3)) assert Sum(Eq(f(x), x**2), (x, 0, y)) == \ Eq(Sum(f(x), (x, 0, y)), Sum(x**2, (x, 0, y))) def test_issue_2787(): n, k = symbols('n k', positive=True, integer=True) p = symbols('p', positive=True) binomial_dist = binomial(n, k)*p**k*(1 - p)**(n - k) s = Sum(binomial_dist*k, (k, 0, n)) res = s.doit().simplify() ans = Piecewise( (n*p, x), (Sum(k*p**k*binomial(n, k)*(1 - p)**(n - k), (k, 0, n)), True)).subs(x, (Eq(n, 1) | (n > 1)) & (p/Abs(p - 1) <= 1)) ans2 = Piecewise( (n*p, x), (factorial(n)*Sum(p**k*(1 - p)**(-k + n)/ (factorial(-k + n)*factorial(k - 1)), (k, 0, n)), True)).subs(x, (Eq(n, 1) | (n > 1)) & (p/Abs(p - 1) <= 1)) assert res in [ans, ans2] # XXX system dependent # Issue #17165: make sure that another simplify does not complicate # the result by much. Why didn't first simplify replace # Eq(n, 1) | (n > 1) with True? assert res.simplify().count_ops() <= res.count_ops() + 2 def test_issue_4668(): assert summation(1/n, (n, 2, oo)) is oo def test_matrix_sum(): A = Matrix([[0, 1], [n, 0]]) result = Sum(A, (n, 0, 3)).doit() assert result == Matrix([[0, 4], [6, 0]]) assert result.__class__ == ImmutableDenseMatrix A = SparseMatrix([[0, 1], [n, 0]]) result = Sum(A, (n, 0, 3)).doit() assert result.__class__ == ImmutableSparseMatrix def test_failing_matrix_sum(): n = Symbol('n') # TODO Implement matrix geometric series summation. A = Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 0]]) assert Sum(A ** n, (n, 1, 4)).doit() == \ Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) # issue sympy/sympy#16989 assert summation(A**n, (n, 1, 1)) == A def test_indexed_idx_sum(): i = symbols('i', cls=Idx) r = Indexed('r', i) assert Sum(r, (i, 0, 3)).doit() == sum([r.xreplace({i: j}) for j in range(4)]) assert Product(r, (i, 0, 3)).doit() == prod([r.xreplace({i: j}) for j in range(4)]) j = symbols('j', integer=True) assert Sum(r, (i, j, j+2)).doit() == sum([r.xreplace({i: j+k}) for k in range(3)]) assert Product(r, (i, j, j+2)).doit() == prod([r.xreplace({i: j+k}) for k in range(3)]) k = Idx('k', range=(1, 3)) A = IndexedBase('A') assert Sum(A[k], k).doit() == sum([A[Idx(j, (1, 3))] for j in range(1, 4)]) assert Product(A[k], k).doit() == prod([A[Idx(j, (1, 3))] for j in range(1, 4)]) raises(ValueError, lambda: Sum(A[k], (k, 1, 4))) raises(ValueError, lambda: Sum(A[k], (k, 0, 3))) raises(ValueError, lambda: Sum(A[k], (k, 2, oo))) raises(ValueError, lambda: Product(A[k], (k, 1, 4))) raises(ValueError, lambda: Product(A[k], (k, 0, 3))) raises(ValueError, lambda: Product(A[k], (k, 2, oo))) @slow def test_is_convergent(): # divergence tests -- assert Sum(n/(2*n + 1), (n, 1, oo)).is_convergent() is S.false assert Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent() is S.false assert Sum(3**(-2*n - 1)*n**n, (n, 1, oo)).is_convergent() is S.false assert Sum((-1)**n*n, (n, 3, oo)).is_convergent() is S.false assert Sum((-1)**n, (n, 1, oo)).is_convergent() is S.false assert Sum(log(1/n), (n, 2, oo)).is_convergent() is S.false # Raabe's test -- assert Sum(Product((3*m),(m,1,n))/Product((3*m+4),(m,1,n)),(n,1,oo)).is_convergent() is S.true # root test -- assert Sum((-12)**n/n, (n, 1, oo)).is_convergent() is S.false # integral test -- # p-series test -- assert Sum(1/(n**2 + 1), (n, 1, oo)).is_convergent() is S.true assert Sum(1/n**Rational(6, 5), (n, 1, oo)).is_convergent() is S.true assert Sum(2/(n*sqrt(n - 1)), (n, 2, oo)).is_convergent() is S.true assert Sum(1/(sqrt(n)*sqrt(n)), (n, 2, oo)).is_convergent() is S.false assert Sum(factorial(n) / factorial(n+2), (n, 1, oo)).is_convergent() is S.true assert Sum(rf(5,n)/rf(7,n),(n,1,oo)).is_convergent() is S.true assert Sum((rf(1, n)*rf(2, n))/(rf(3, n)*factorial(n)),(n,1,oo)).is_convergent() is S.false # comparison test -- assert Sum(1/(n + log(n)), (n, 1, oo)).is_convergent() is S.false assert Sum(1/(n**2*log(n)), (n, 2, oo)).is_convergent() is S.true assert Sum(1/(n*log(n)), (n, 2, oo)).is_convergent() is S.false assert Sum(2/(n*log(n)*log(log(n))**2), (n, 5, oo)).is_convergent() is S.true assert Sum(2/(n*log(n)**2), (n, 2, oo)).is_convergent() is S.true assert Sum((n - 1)/(n**2*log(n)**3), (n, 2, oo)).is_convergent() is S.true assert Sum(1/(n*log(n)*log(log(n))), (n, 5, oo)).is_convergent() is S.false assert Sum((n - 1)/(n*log(n)**3), (n, 3, oo)).is_convergent() is S.false assert Sum(2/(n**2*log(n)), (n, 2, oo)).is_convergent() is S.true assert Sum(1/(n*sqrt(log(n))*log(log(n))), (n, 100, oo)).is_convergent() is S.false assert Sum(log(log(n))/(n*log(n)**2), (n, 100, oo)).is_convergent() is S.true assert Sum(log(n)/n**2, (n, 5, oo)).is_convergent() is S.true # alternating series tests -- assert Sum((-1)**(n - 1)/(n**2 - 1), (n, 3, oo)).is_convergent() is S.true # with -negativeInfinite Limits assert Sum(1/(n**2 + 1), (n, -oo, 1)).is_convergent() is S.true assert Sum(1/(n - 1), (n, -oo, -1)).is_convergent() is S.false assert Sum(1/(n**2 - 1), (n, -oo, -5)).is_convergent() is S.true assert Sum(1/(n**2 - 1), (n, -oo, 2)).is_convergent() is S.true assert Sum(1/(n**2 - 1), (n, -oo, oo)).is_convergent() is S.true # piecewise functions f = Piecewise((n**(-2), n <= 1), (n**2, n > 1)) assert Sum(f, (n, 1, oo)).is_convergent() is S.false assert Sum(f, (n, -oo, oo)).is_convergent() is S.false assert Sum(f, (n, 1, 100)).is_convergent() is S.true #assert Sum(f, (n, -oo, 1)).is_convergent() is S.true # integral test assert Sum(log(n)/n**3, (n, 1, oo)).is_convergent() is S.true assert Sum(-log(n)/n**3, (n, 1, oo)).is_convergent() is S.true # the following function has maxima located at (x, y) = # (1.2, 0.43), (3.0, -0.25) and (6.8, 0.050) eq = (x - 2)*(x**2 - 6*x + 4)*exp(-x) assert Sum(eq, (x, 1, oo)).is_convergent() is S.true assert Sum(eq, (x, 1, 2)).is_convergent() is S.true assert Sum(1/(x**3), (x, 1, oo)).is_convergent() is S.true assert Sum(1/(x**S.Half), (x, 1, oo)).is_convergent() is S.false # issue 19545 assert Sum(1/n - 3/(3*n +2), (n, 1, oo)).is_convergent() is S.true # issue 19836 assert Sum(4/(n + 2) - 5/(n + 1) + 1/n,(n, 7, oo)).is_convergent() is S.true def test_is_absolutely_convergent(): assert Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent() is S.false assert Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent() is S.true @XFAIL def test_convergent_failing(): # dirichlet tests assert Sum(sin(n)/n, (n, 1, oo)).is_convergent() is S.true assert Sum(sin(2*n)/n, (n, 1, oo)).is_convergent() is S.true def test_issue_6966(): i, k, m = symbols('i k m', integer=True) z_i, q_i = symbols('z_i q_i') a_k = Sum(-q_i*z_i/k,(i,1,m)) b_k = a_k.diff(z_i) assert isinstance(b_k, Sum) assert b_k == Sum(-q_i/k,(i,1,m)) def test_issue_10156(): cx = Sum(2*y**2*x, (x, 1,3)) e = 2*y*Sum(2*cx*x**2, (x, 1, 9)) assert e.factor() == \ 8*y**3*Sum(x, (x, 1, 3))*Sum(x**2, (x, 1, 9)) def test_issue_10973(): assert Sum((-n + (n**3 + 1)**(S(1)/3))/log(n), (n, 1, oo)).is_convergent() is S.true def test_issue_14129(): x = Symbol('x', zero=False) assert Sum( k*x**k, (k, 0, n-1)).doit() == \ Piecewise((n**2/2 - n/2, Eq(x, 1)), ((n*x*x**n - n*x**n - x*x**n + x)/(x - 1)**2, True)) assert Sum( x**k, (k, 0, n-1)).doit() == \ Piecewise((n, Eq(x, 1)), ((-x**n + 1)/(-x + 1), True)) assert Sum( k*(x/y+x)**k, (k, 0, n-1)).doit() == \ Piecewise((n*(n - 1)/2, Eq(x, y/(y + 1))), (x*(y + 1)*(n*x*y*(x + x/y)**(n - 1) + n*x*(x + x/y)**(n - 1) - n*y*(x + x/y)**(n - 1) - x*y*(x + x/y)**(n - 1) - x*(x + x/y)**(n - 1) + y)/ (x*y + x - y)**2, True)) def test_issue_14112(): assert Sum((-1)**n/sqrt(n), (n, 1, oo)).is_absolutely_convergent() is S.false assert Sum((-1)**(2*n)/n, (n, 1, oo)).is_convergent() is S.false assert Sum((-2)**n + (-3)**n, (n, 1, oo)).is_convergent() is S.false def test_issue_14219(): A = diag(0, 2, -3) res = diag(1, 15, -20) assert Sum(A**n, (n, 0, 3)).doit() == res def test_sin_times_absolutely_convergent(): assert Sum(sin(n) / n**3, (n, 1, oo)).is_convergent() is S.true assert Sum(sin(n) * log(n) / n**3, (n, 1, oo)).is_convergent() is S.true def test_issue_14111(): assert Sum(1/log(log(n)), (n, 22, oo)).is_convergent() is S.false def test_issue_14484(): assert Sum(sin(n)/log(log(n)), (n, 22, oo)).is_convergent() is S.false def test_issue_14640(): i, n = symbols("i n", integer=True) a, b, c = symbols("a b c", zero=False) assert Sum(a**-i/(a - b), (i, 0, n)).doit() == Sum( 1/(a*a**i - a**i*b), (i, 0, n)).doit() == Piecewise( (n + 1, Eq(1/a, 1)), ((-a**(-n - 1) + 1)/(1 - 1/a), True))/(a - b) assert Sum((b*a**i - c*a**i)**-2, (i, 0, n)).doit() == Piecewise( (n + 1, Eq(a**(-2), 1)), ((-a**(-2*n - 2) + 1)/(1 - 1/a**2), True))/(b - c)**2 s = Sum(i*(a**(n - i) - b**(n - i))/(a - b), (i, 0, n)).doit() assert not s.has(Sum) assert s.subs({a: 2, b: 3, n: 5}) == 122 def test_issue_15943(): s = Sum(binomial(n, k)*factorial(n - k), (k, 0, n)).doit().rewrite(gamma) assert s == -E*(n + 1)*gamma(n + 1)*lowergamma(n + 1, 1)/gamma(n + 2 ) + E*gamma(n + 1) assert s.simplify() == E*(factorial(n) - lowergamma(n + 1, 1)) def test_Sum_dummy_eq(): assert not Sum(x, (x, a, b)).dummy_eq(1) assert not Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, b), (a, 1, 2))) assert not Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, c))) assert Sum(x, (x, a, b)).dummy_eq(Sum(x, (x, a, b))) d = Dummy() assert Sum(x, (x, a, d)).dummy_eq(Sum(x, (x, a, c)), c) assert not Sum(x, (x, a, d)).dummy_eq(Sum(x, (x, a, c))) assert Sum(x, (x, a, c)).dummy_eq(Sum(y, (y, a, c))) assert Sum(x, (x, a, d)).dummy_eq(Sum(y, (y, a, c)), c) assert not Sum(x, (x, a, d)).dummy_eq(Sum(y, (y, a, c))) def test_issue_15852(): assert summation(x**y*y, (y, -oo, oo)).doit() == Sum(x**y*y, (y, -oo, oo)) def test_exceptions(): S = Sum(x, (x, a, b)) raises(ValueError, lambda: S.change_index(x, x**2, y)) S = Sum(x, (x, a, b), (x, 1, 4)) raises(ValueError, lambda: S.index(x)) S = Sum(x, (x, a, b), (y, 1, 4)) raises(ValueError, lambda: S.reorder([x])) S = Sum(x, (x, y, b), (y, 1, 4)) raises(ReorderError, lambda: S.reorder_limit(0, 1)) S = Sum(x*y, (x, a, b), (y, 1, 4)) raises(NotImplementedError, lambda: S.is_convergent()) def test_sumproducts_assumptions(): M = Symbol('M', integer=True, positive=True) m = Symbol('m', integer=True) for func in [Sum, Product]: assert func(m, (m, -M, M)).is_positive is None assert func(m, (m, -M, M)).is_nonpositive is None assert func(m, (m, -M, M)).is_negative is None assert func(m, (m, -M, M)).is_nonnegative is None assert func(m, (m, -M, M)).is_finite is True m = Symbol('m', integer=True, nonnegative=True) for func in [Sum, Product]: assert func(m, (m, 0, M)).is_positive is None assert func(m, (m, 0, M)).is_nonpositive is None assert func(m, (m, 0, M)).is_negative is False assert func(m, (m, 0, M)).is_nonnegative is True assert func(m, (m, 0, M)).is_finite is True m = Symbol('m', integer=True, positive=True) for func in [Sum, Product]: assert func(m, (m, 1, M)).is_positive is True assert func(m, (m, 1, M)).is_nonpositive is False assert func(m, (m, 1, M)).is_negative is False assert func(m, (m, 1, M)).is_nonnegative is True assert func(m, (m, 1, M)).is_finite is True m = Symbol('m', integer=True, negative=True) assert Sum(m, (m, -M, -1)).is_positive is False assert Sum(m, (m, -M, -1)).is_nonpositive is True assert Sum(m, (m, -M, -1)).is_negative is True assert Sum(m, (m, -M, -1)).is_nonnegative is False assert Sum(m, (m, -M, -1)).is_finite is True assert Product(m, (m, -M, -1)).is_positive is None assert Product(m, (m, -M, -1)).is_nonpositive is None assert Product(m, (m, -M, -1)).is_negative is None assert Product(m, (m, -M, -1)).is_nonnegative is None assert Product(m, (m, -M, -1)).is_finite is True m = Symbol('m', integer=True, nonpositive=True) assert Sum(m, (m, -M, 0)).is_positive is False assert Sum(m, (m, -M, 0)).is_nonpositive is True assert Sum(m, (m, -M, 0)).is_negative is None assert Sum(m, (m, -M, 0)).is_nonnegative is None assert Sum(m, (m, -M, 0)).is_finite is True assert Product(m, (m, -M, 0)).is_positive is None assert Product(m, (m, -M, 0)).is_nonpositive is None assert Product(m, (m, -M, 0)).is_negative is None assert Product(m, (m, -M, 0)).is_nonnegative is None assert Product(m, (m, -M, 0)).is_finite is True m = Symbol('m', integer=True) assert Sum(2, (m, 0, oo)).is_positive is None assert Sum(2, (m, 0, oo)).is_nonpositive is None assert Sum(2, (m, 0, oo)).is_negative is None assert Sum(2, (m, 0, oo)).is_nonnegative is None assert Sum(2, (m, 0, oo)).is_finite is None assert Product(2, (m, 0, oo)).is_positive is None assert Product(2, (m, 0, oo)).is_nonpositive is None assert Product(2, (m, 0, oo)).is_negative is False assert Product(2, (m, 0, oo)).is_nonnegative is None assert Product(2, (m, 0, oo)).is_finite is None assert Product(0, (x, M, M-1)).is_positive is True assert Product(0, (x, M, M-1)).is_finite is True def test_expand_with_assumptions(): M = Symbol('M', integer=True, positive=True) x = Symbol('x', positive=True) m = Symbol('m', nonnegative=True) assert log(Product(x**m, (m, 0, M))).expand() == Sum(m*log(x), (m, 0, M)) assert log(Product(exp(x**m), (m, 0, M))).expand() == Sum(x**m, (m, 0, M)) assert log(Product(x**m, (m, 0, M))).rewrite(Sum).expand() == Sum(m*log(x), (m, 0, M)) assert log(Product(exp(x**m), (m, 0, M))).rewrite(Sum).expand() == Sum(x**m, (m, 0, M)) n = Symbol('n', nonnegative=True) i, j = symbols('i,j', positive=True, integer=True) x, y = symbols('x,y', positive=True) assert log(Product(x**i*y**j, (i, 1, n), (j, 1, m))).expand() \ == Sum(i*log(x) + j*log(y), (i, 1, n), (j, 1, m)) m = Symbol('m', nonnegative=True, integer=True) s = Sum(x**m, (m, 0, M)) s_as_product = s.rewrite(Product) assert s_as_product.has(Product) assert s_as_product == log(Product(exp(x**m), (m, 0, M))) assert s_as_product.expand() == s s5 = s.subs(M, 5) s5_as_product = s5.rewrite(Product) assert s5_as_product.has(Product) assert s5_as_product.doit().expand() == s5.doit() def test_has_finite_limits(): x = Symbol('x') assert Sum(1, (x, 1, 9)).has_finite_limits is True assert Sum(1, (x, 1, oo)).has_finite_limits is False M = Symbol('M') assert Sum(1, (x, 1, M)).has_finite_limits is None M = Symbol('M', positive=True) assert Sum(1, (x, 1, M)).has_finite_limits is True x = Symbol('x', positive=True) M = Symbol('M') assert Sum(1, (x, 1, M)).has_finite_limits is True assert Sum(1, (x, 1, M), (y, -oo, oo)).has_finite_limits is False def test_has_reversed_limits(): assert Sum(1, (x, 1, 1)).has_reversed_limits is False assert Sum(1, (x, 1, 9)).has_reversed_limits is False assert Sum(1, (x, 1, -9)).has_reversed_limits is True assert Sum(1, (x, 1, 0)).has_reversed_limits is True assert Sum(1, (x, 1, oo)).has_reversed_limits is False M = Symbol('M') assert Sum(1, (x, 1, M)).has_reversed_limits is None M = Symbol('M', positive=True, integer=True) assert Sum(1, (x, 1, M)).has_reversed_limits is False assert Sum(1, (x, 1, M), (y, -oo, oo)).has_reversed_limits is False M = Symbol('M', negative=True) assert Sum(1, (x, 1, M)).has_reversed_limits is True assert Sum(1, (x, 1, M), (y, -oo, oo)).has_reversed_limits is True assert Sum(1, (x, oo, oo)).has_reversed_limits is None def test_has_empty_sequence(): assert Sum(1, (x, 1, 1)).has_empty_sequence is False assert Sum(1, (x, 1, 9)).has_empty_sequence is False assert Sum(1, (x, 1, -9)).has_empty_sequence is False assert Sum(1, (x, 1, 0)).has_empty_sequence is True assert Sum(1, (x, y, y - 1)).has_empty_sequence is True assert Sum(1, (x, 3, 2), (y, -oo, oo)).has_empty_sequence is True assert Sum(1, (y, -oo, oo), (x, 3, 2)).has_empty_sequence is True assert Sum(1, (x, oo, oo)).has_empty_sequence is False def test_empty_sequence(): assert Product(x*y, (x, -oo, oo), (y, 1, 0)).doit() == 1 assert Product(x*y, (y, 1, 0), (x, -oo, oo)).doit() == 1 assert Sum(x, (x, -oo, oo), (y, 1, 0)).doit() == 0 assert Sum(x, (y, 1, 0), (x, -oo, oo)).doit() == 0 def test_issue_8016(): k = Symbol('k', integer=True) n, m = symbols('n, m', integer=True, positive=True) s = Sum(binomial(m, k)*binomial(m, n - k)*(-1)**k, (k, 0, n)) assert s.doit().simplify() == \ cos(pi*n/2)*gamma(m + 1)/gamma(n/2 + 1)/gamma(m - n/2 + 1) def test_issue_14313(): assert Sum(S.Half**floor(n/2), (n, 1, oo)).is_convergent() def test_issue_14563(): # The assertion was failing due to no assumptions methods in Sums and Product assert 1 % Sum(1, (x, 0, 1)) == 1 def test_issue_16735(): assert Sum(5**n/gamma(n+1), (n, 1, oo)).is_convergent() is S.true def test_issue_14871(): assert Sum((Rational(1, 10))**n*rf(0, n)/factorial(n), (n, 0, oo)).rewrite(factorial).doit() == 1 def test_issue_17165(): n = symbols("n", integer=True) x = symbols('x') s = (x*Sum(x**n, (n, -1, oo))) ssimp = s.doit().simplify() assert ssimp == Piecewise((-1/(x - 1), (x > -1) & (x < 1)), (x*Sum(x**n, (n, -1, oo)), True)), ssimp assert ssimp.simplify() == ssimp def test_issue_19379(): assert Sum(factorial(n)/factorial(n + 2), (n, 1, oo)).is_convergent() is S.true def test_issue_20777(): assert Sum(exp(x*sin(n/m)), (n, 1, m)).doit() == Sum(exp(x*sin(n/m)), (n, 1, m)) def test__dummy_with_inherited_properties_concrete(): x = Symbol('x') from sympy.core.containers import Tuple d = _dummy_with_inherited_properties_concrete(Tuple(x, 0, 5)) assert d.is_real assert d.is_integer assert d.is_nonnegative assert d.is_extended_nonnegative d = _dummy_with_inherited_properties_concrete(Tuple(x, 1, 9)) assert d.is_real assert d.is_integer assert d.is_positive assert d.is_odd is None d = _dummy_with_inherited_properties_concrete(Tuple(x, -5, 5)) assert d.is_real assert d.is_integer assert d.is_positive is None assert d.is_extended_nonnegative is None assert d.is_odd is None d = _dummy_with_inherited_properties_concrete(Tuple(x, -1.5, 1.5)) assert d.is_real assert d.is_integer is None assert d.is_positive is None assert d.is_extended_nonnegative is None N = Symbol('N', integer=True, positive=True) d = _dummy_with_inherited_properties_concrete(Tuple(x, 2, N)) assert d.is_real assert d.is_positive assert d.is_integer # Return None if no assumptions are added N = Symbol('N', integer=True, positive=True) d = _dummy_with_inherited_properties_concrete(Tuple(N, 2, 4)) assert d is None x = Symbol('x', negative=True) raises(InconsistentAssumptions, lambda: _dummy_with_inherited_properties_concrete(Tuple(x, 1, 5))) def test_matrixsymbol_summation_numerical_limits(): A = MatrixSymbol('A', 3, 3) n = Symbol('n', integer=True) assert Sum(A**n, (n, 0, 2)).doit() == Identity(3) + A + A**2 assert Sum(A, (n, 0, 2)).doit() == 3*A assert Sum(n*A, (n, 0, 2)).doit() == 3*A B = Matrix([[0, n, 0], [-1, 0, 0], [0, 0, 2]]) ans = Matrix([[0, 6, 0], [-4, 0, 0], [0, 0, 8]]) + 4*A assert Sum(A+B, (n, 0, 3)).doit() == ans ans = A*Matrix([[0, 6, 0], [-4, 0, 0], [0, 0, 8]]) assert Sum(A*B, (n, 0, 3)).doit() == ans ans = (A**2*Matrix([[-2, 0, 0], [0,-2, 0], [0, 0, 4]]) + A**3*Matrix([[0, -9, 0], [3, 0, 0], [0, 0, 8]]) + A*Matrix([[0, 1, 0], [-1, 0, 0], [0, 0, 2]])) assert Sum(A**n*B**n, (n, 1, 3)).doit() == ans def test_issue_21651(): i = Symbol('i') a = Sum(floor(2*2**(-i)), (i, S.One, 2)) assert a.doit() == S.One @XFAIL def test_matrixsymbol_summation_symbolic_limits(): N = Symbol('N', integer=True, positive=True) A = MatrixSymbol('A', 3, 3) n = Symbol('n', integer=True) assert Sum(A, (n, 0, N)).doit() == (N+1)*A assert Sum(n*A, (n, 0, N)).doit() == (N**2/2+N/2)*A def test_summation_by_residues(): x = Symbol('x') # Examples from Nakhle H. Asmar, Loukas Grafakos, # Complex Analysis with Applications assert eval_sum_residue(1 / (x**2 + 1), (x, -oo, oo)) == pi/tanh(pi) assert eval_sum_residue(1 / x**6, (x, S(1), oo)) == pi**6/945 assert eval_sum_residue(1 / (x**2 + 9), (x, -oo, oo)) == pi/(3*tanh(3*pi)) assert eval_sum_residue(1 / (x**2 + 1)**2, (x, -oo, oo)).cancel() == \ (-pi**2*tanh(pi)**2 + pi*tanh(pi) + pi**2)/(2*tanh(pi)**2) assert eval_sum_residue(x**2 / (x**2 + 1)**2, (x, -oo, oo)).cancel() == \ (-pi**2 + pi*tanh(pi) + pi**2*tanh(pi)**2)/(2*tanh(pi)**2) assert eval_sum_residue(1 / (4*x**2 - 1), (x, -oo, oo)) == 0 assert eval_sum_residue(x**2 / (x**2 - S(1)/4)**2, (x, -oo, oo)) == pi**2/2 assert eval_sum_residue(1 / (4*x**2 - 1)**2, (x, -oo, oo)) == pi**2/8 assert eval_sum_residue(1 / ((x - S(1)/2)**2 + 1), (x, -oo, oo)) == pi*tanh(pi) assert eval_sum_residue(1 / x**2, (x, S(1), oo)) == pi**2/6 assert eval_sum_residue(1 / x**4, (x, S(1), oo)) == pi**4/90 assert eval_sum_residue(1 / x**2 / (x**2 + 4), (x, S(1), oo)) == \ -pi*(-pi/12 - 1/(16*pi) + 1/(8*tanh(2*pi)))/2 # Some examples made from 1 / (x**2 + 1) assert eval_sum_residue(1 / (x**2 + 1), (x, S(0), oo)) == \ S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue(1 / (x**2 + 1), (x, S(1), oo)) == \ -S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue(1 / (x**2 + 1), (x, S(-1), oo)) == \ 1 + pi/(2*tanh(pi)) assert eval_sum_residue((-1)**x / (x**2 + 1), (x, -oo, oo)) == \ pi/sinh(pi) assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(0), oo)) == \ pi/(2*sinh(pi)) + S(1)/2 assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(1), oo)) == \ -S(1)/2 + pi/(2*sinh(pi)) assert eval_sum_residue((-1)**x / (x**2 + 1), (x, S(-1), oo)) == \ pi/(2*sinh(pi)) # Some examples made from shifting of 1 / (x**2 + 1) assert eval_sum_residue(1 / (x**2 + 2*x + 2), (x, S(-1), oo)) == S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue(1 / (x**2 + 4*x + 5), (x, S(-2), oo)) == S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue(1 / (x**2 - 2*x + 2), (x, S(1), oo)) == S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue(1 / (x**2 - 4*x + 5), (x, S(2), oo)) == S(1)/2 + pi/(2*tanh(pi)) assert eval_sum_residue((-1)**x * -1 / (x**2 + 2*x + 2), (x, S(-1), oo)) == S(1)/2 + pi/(2*sinh(pi)) assert eval_sum_residue((-1)**x * -1 / (x**2 -2*x + 2), (x, S(1), oo)) == S(1)/2 + pi/(2*sinh(pi)) # Some examples made from 1 / x**2 assert eval_sum_residue(1 / x**2, (x, S(2), oo)) == -1 + pi**2/6 assert eval_sum_residue(1 / x**2, (x, S(3), oo)) == -S(5)/4 + pi**2/6 assert eval_sum_residue((-1)**x / x**2, (x, S(1), oo)) == -pi**2/12 assert eval_sum_residue((-1)**x / x**2, (x, S(2), oo)) == 1 - pi**2/12 @slow def test_summation_by_residues_failing(): x = Symbol('x') # Failing because of the bug in residue computation assert eval_sum_residue(x**2 / (x**4 + 1), (x, S(1), oo)) assert eval_sum_residue(1 / ((x - 1)*(x - 2) + 1), (x, -oo, oo)) != 0 def test_process_limits(): from sympy.concrete.expr_with_limits import _process_limits # these should be (x, Range(3)) not Range(3) raises(ValueError, lambda: _process_limits( Range(3), discrete=True)) raises(ValueError, lambda: _process_limits( Range(3), discrete=False)) # these should be (x, union) not union # (but then we would get a TypeError because we don't # handle non-contiguous sets: see below use of `union`) union = Or(x < 1, x > 3).as_set() raises(ValueError, lambda: _process_limits( union, discrete=True)) raises(ValueError, lambda: _process_limits( union, discrete=False)) # error not triggered if not needed assert _process_limits((x, 1, 2)) == ([(x, 1, 2)], 1) # this equivalence is used to detect Reals in _process_limits assert isinstance(S.Reals, Interval) C = Integral # continuous limits assert C(x, x >= 5) == C(x, (x, 5, oo)) assert C(x, x < 3) == C(x, (x, -oo, 3)) ans = C(x, (x, 0, 3)) assert C(x, And(x >= 0, x < 3)) == ans assert C(x, (x, Interval.Ropen(0, 3))) == ans raises(TypeError, lambda: C(x, (x, Range(3)))) # discrete limits for D in (Sum, Product): r, ans = Range(3, 10, 2), D(2*x + 3, (x, 0, 3)) assert D(x, (x, r)) == ans assert D(x, (x, r.reversed)) == ans r, ans = Range(3, oo, 2), D(2*x + 3, (x, 0, oo)) assert D(x, (x, r)) == ans assert D(x, (x, r.reversed)) == ans r, ans = Range(-oo, 5, 2), D(3 - 2*x, (x, 0, oo)) assert D(x, (x, r)) == ans assert D(x, (x, r.reversed)) == ans raises(TypeError, lambda: D(x, x > 0)) raises(ValueError, lambda: D(x, Interval(1, 3))) raises(NotImplementedError, lambda: D(x, (x, union))) def test_pr_22677(): b = Symbol('b', integer=True, positive=True) assert Sum(1/x**2,(x, 0, b)).doit() == Sum(x**(-2), (x, 0, b)) assert Sum(1/(x - b)**2,(x, 0, b-1)).doit() == Sum( (-b + x)**(-2), (x, 0, b - 1)) def test_issue_23952(): p, q = symbols("p q", real=True, nonnegative=True) k1, k2 = symbols("k1 k2", integer=True, nonnegative=True) n = Symbol("n", integer=True, positive=True) expr = Sum(abs(k1 - k2)*p**k1 *(1 - q)**(n - k2), (k1, 0, n), (k2, 0, n)) assert expr.subs(p,0).subs(q,1).subs(n, 3).doit() == 3
aec482a435a965018ca3445fae4092e573a5fbec1516623265c6985286855dd7
from sympy.core.evalf import N from sympy.core.function import (Derivative, Function, PoleError, Subs) from sympy.core.numbers import (E, Float, Rational, oo, pi, I) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.exponential import (LambertW, exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (atan, cos, sin) from sympy.functions.special.gamma_functions import gamma from sympy.integrals.integrals import Integral, integrate from sympy.series.order import O from sympy.series.series import series from sympy.abc import x, y, n, k from sympy.testing.pytest import raises def test_sin(): e1 = sin(x).series(x, 0) e2 = series(sin(x), x, 0) assert e1 == e2 def test_cos(): e1 = cos(x).series(x, 0) e2 = series(cos(x), x, 0) assert e1 == e2 def test_exp(): e1 = exp(x).series(x, 0) e2 = series(exp(x), x, 0) assert e1 == e2 def test_exp2(): e1 = exp(cos(x)).series(x, 0) e2 = series(exp(cos(x)), x, 0) assert e1 == e2 def test_issue_5223(): assert series(1, x) == 1 assert next(S.Zero.lseries(x)) == 0 assert cos(x).series() == cos(x).series(x) raises(ValueError, lambda: cos(x + y).series()) raises(ValueError, lambda: x.series(dir="")) assert (cos(x).series(x, 1) - cos(x + 1).series(x).subs(x, x - 1)).removeO() == 0 e = cos(x).series(x, 1, n=None) assert [next(e) for i in range(2)] == [cos(1), -((x - 1)*sin(1))] e = cos(x).series(x, 1, n=None, dir='-') assert [next(e) for i in range(2)] == [cos(1), (1 - x)*sin(1)] # the following test is exact so no need for x -> x - 1 replacement assert abs(x).series(x, 1, dir='-') == x assert exp(x).series(x, 1, dir='-', n=3).removeO() == \ E - E*(-x + 1) + E*(-x + 1)**2/2 D = Derivative assert D(x**2 + x**3*y**2, x, 2, y, 1).series(x).doit() == 12*x*y assert next(D(cos(x), x).lseries()) == D(1, x) assert D( exp(x), x).series(n=3) == D(1, x) + D(x, x) + D(x**2/2, x) + D(x**3/6, x) + O(x**3) assert Integral(x, (x, 1, 3), (y, 1, x)).series(x) == -4 + 4*x assert (1 + x + O(x**2)).getn() == 2 assert (1 + x).getn() is None raises(PoleError, lambda: ((1/sin(x))**oo).series()) logx = Symbol('logx') assert ((sin(x))**y).nseries(x, n=1, logx=logx) == \ exp(y*logx) + O(x*exp(y*logx), x) assert sin(1/x).series(x, oo, n=5) == 1/x - 1/(6*x**3) + O(x**(-5), (x, oo)) assert abs(x).series(x, oo, n=5, dir='+') == x assert abs(x).series(x, -oo, n=5, dir='-') == -x assert abs(-x).series(x, oo, n=5, dir='+') == x assert abs(-x).series(x, -oo, n=5, dir='-') == -x assert exp(x*log(x)).series(n=3) == \ 1 + x*log(x) + x**2*log(x)**2/2 + O(x**3*log(x)**3) # XXX is this right? If not, fix "ngot > n" handling in expr. p = Symbol('p', positive=True) assert exp(sqrt(p)**3*log(p)).series(n=3) == \ 1 + p**S('3/2')*log(p) + O(p**3*log(p)**3) assert exp(sin(x)*log(x)).series(n=2) == 1 + x*log(x) + O(x**2*log(x)**2) def test_issue_6350(): expr = integrate(exp(k*(y**3 - 3*y)), (y, 0, oo), conds='none') assert expr.series(k, 0, 3) == -(-1)**(S(2)/3)*sqrt(3)*gamma(S(1)/3)**2*gamma(S(2)/3)/(6*pi*k**(S(1)/3)) - \ sqrt(3)*k*gamma(-S(2)/3)*gamma(-S(1)/3)/(6*pi) - \ (-1)**(S(1)/3)*sqrt(3)*k**(S(1)/3)*gamma(-S(1)/3)*gamma(S(1)/3)*gamma(S(2)/3)/(6*pi) - \ (-1)**(S(2)/3)*sqrt(3)*k**(S(5)/3)*gamma(S(1)/3)**2*gamma(S(2)/3)/(4*pi) - \ (-1)**(S(1)/3)*sqrt(3)*k**(S(7)/3)*gamma(-S(1)/3)*gamma(S(1)/3)*gamma(S(2)/3)/(8*pi) + O(k**3) def test_issue_11313(): assert Integral(cos(x), x).series(x) == sin(x).series(x) assert Derivative(sin(x), x).series(x, n=3).doit() == cos(x).series(x, n=3) assert Derivative(x**3, x).as_leading_term(x) == 3*x**2 assert Derivative(x**3, y).as_leading_term(x) == 0 assert Derivative(sin(x), x).as_leading_term(x) == 1 assert Derivative(cos(x), x).as_leading_term(x) == -x # This result is equivalent to zero, zero is not return because # `Expr.series` doesn't currently detect an `x` in its `free_symbol`s. assert Derivative(1, x).as_leading_term(x) == Derivative(1, x) assert Derivative(exp(x), x).series(x).doit() == exp(x).series(x) assert 1 + Integral(exp(x), x).series(x) == exp(x).series(x) assert Derivative(log(x), x).series(x).doit() == (1/x).series(x) assert Integral(log(x), x).series(x) == Integral(log(x), x).doit().series(x).removeO() def test_series_of_Subs(): from sympy.abc import z subs1 = Subs(sin(x), x, y) subs2 = Subs(sin(x) * cos(z), x, y) subs3 = Subs(sin(x * z), (x, z), (y, x)) assert subs1.series(x) == subs1 subs1_series = (Subs(x, x, y) + Subs(-x**3/6, x, y) + Subs(x**5/120, x, y) + O(y**6)) assert subs1.series() == subs1_series assert subs1.series(y) == subs1_series assert subs1.series(z) == subs1 assert subs2.series(z) == (Subs(z**4*sin(x)/24, x, y) + Subs(-z**2*sin(x)/2, x, y) + Subs(sin(x), x, y) + O(z**6)) assert subs3.series(x).doit() == subs3.doit().series(x) assert subs3.series(z).doit() == sin(x*y) raises(ValueError, lambda: Subs(x + 2*y, y, z).series()) assert Subs(x + y, y, z).series(x).doit() == x + z def test_issue_3978(): f = Function('f') assert f(x).series(x, 0, 3, dir='-') == \ f(0) + x*Subs(Derivative(f(x), x), x, 0) + \ x**2*Subs(Derivative(f(x), x, x), x, 0)/2 + O(x**3) assert f(x).series(x, 0, 3) == \ f(0) + x*Subs(Derivative(f(x), x), x, 0) + \ x**2*Subs(Derivative(f(x), x, x), x, 0)/2 + O(x**3) assert f(x**2).series(x, 0, 3) == \ f(0) + x**2*Subs(Derivative(f(x), x), x, 0) + O(x**3) assert f(x**2+1).series(x, 0, 3) == \ f(1) + x**2*Subs(Derivative(f(x), x), x, 1) + O(x**3) class TestF(Function): pass assert TestF(x).series(x, 0, 3) == TestF(0) + \ x*Subs(Derivative(TestF(x), x), x, 0) + \ x**2*Subs(Derivative(TestF(x), x, x), x, 0)/2 + O(x**3) from sympy.series.acceleration import richardson, shanks from sympy.concrete.summations import Sum from sympy.core.numbers import Integer def test_acceleration(): e = (1 + 1/n)**n assert round(richardson(e, n, 10, 20).evalf(), 10) == round(E.evalf(), 10) A = Sum(Integer(-1)**(k + 1) / k, (k, 1, n)) assert round(shanks(A, n, 25).evalf(), 4) == round(log(2).evalf(), 4) assert round(shanks(A, n, 25, 5).evalf(), 10) == round(log(2).evalf(), 10) def test_issue_5852(): assert series(1/cos(x/log(x)), x, 0) == 1 + x**2/(2*log(x)**2) + \ 5*x**4/(24*log(x)**4) + O(x**6) def test_issue_4583(): assert cos(1 + x + x**2).series(x, 0, 5) == cos(1) - x*sin(1) + \ x**2*(-sin(1) - cos(1)/2) + x**3*(-cos(1) + sin(1)/6) + \ x**4*(-11*cos(1)/24 + sin(1)/2) + O(x**5) def test_issue_6318(): eq = (1/x)**Rational(2, 3) assert (eq + 1).as_leading_term(x) == eq def test_x_is_base_detection(): eq = (x**2)**Rational(2, 3) assert eq.series() == x**Rational(4, 3) def test_issue_7203(): assert series(cos(x), x, pi, 3) == \ -1 + (x - pi)**2/2 + O((x - pi)**3, (x, pi)) def test_exp_product_positive_factors(): a, b = symbols('a, b', positive=True) x = a * b assert series(exp(x), x, n=8) == 1 + a*b + a**2*b**2/2 + \ a**3*b**3/6 + a**4*b**4/24 + a**5*b**5/120 + a**6*b**6/720 + \ a**7*b**7/5040 + O(a**8*b**8, a, b) def test_issue_8805(): assert series(1, n=8) == 1 def test_issue_9549(): y = (x**2 + x + 1) / (x**3 + x**2) assert series(y, x, oo) == x**(-5) - 1/x**4 + x**(-3) + 1/x + O(x**(-6), (x, oo)) def test_issue_10761(): assert series(1/(x**-2 + x**-3), x, 0) == x**3 - x**4 + x**5 + O(x**6) def test_issue_12578(): y = (1 - 1/(x/2 - 1/(2*x))**4)**(S(1)/8) assert y.series(x, 0, n=17) == 1 - 2*x**4 - 8*x**6 - 34*x**8 - 152*x**10 - 714*x**12 - \ 3472*x**14 - 17318*x**16 + O(x**17) def test_issue_12791(): beta = symbols('beta', positive=True) theta, varphi = symbols('theta varphi', real=True) expr = (-beta**2*varphi*sin(theta) + beta**2*cos(theta) + \ beta*varphi*sin(theta) - beta*cos(theta) - beta + 1)/(beta*cos(theta) - 1)**2 sol = 0.5/(0.5*cos(theta) - 1.0)**2 - 0.25*cos(theta)/(0.5*cos(theta)\ - 1.0)**2 + (beta - 0.5)*(-0.25*varphi*sin(2*theta) - 1.5*cos(theta)\ + 0.25*cos(2*theta) + 1.25)/(0.5*cos(theta) - 1.0)**3\ + 0.25*varphi*sin(theta)/(0.5*cos(theta) - 1.0)**2 + O((beta - S.Half)**2, (beta, S.Half)) assert expr.series(beta, 0.5, 2).trigsimp() == sol def test_issue_14384(): x, a = symbols('x a') assert series(x**a, x) == x**a assert series(x**(-2*a), x) == x**(-2*a) assert series(exp(a*log(x)), x) == exp(a*log(x)) assert series(x**I, x) == x**I assert series(x**(I + 1), x) == x**(1 + I) assert series(exp(I*log(x)), x) == exp(I*log(x)) def test_issue_14885(): assert series(x**Rational(-3, 2)*exp(x), x, 0) == (x**Rational(-3, 2) + 1/sqrt(x) + sqrt(x)/2 + x**Rational(3, 2)/6 + x**Rational(5, 2)/24 + x**Rational(7, 2)/120 + x**Rational(9, 2)/720 + x**Rational(11, 2)/5040 + O(x**6)) def test_issue_15539(): assert series(atan(x), x, -oo) == (-1/(5*x**5) + 1/(3*x**3) - 1/x - pi/2 + O(x**(-6), (x, -oo))) assert series(atan(x), x, oo) == (-1/(5*x**5) + 1/(3*x**3) - 1/x + pi/2 + O(x**(-6), (x, oo))) def test_issue_7259(): assert series(LambertW(x), x) == x - x**2 + 3*x**3/2 - 8*x**4/3 + 125*x**5/24 + O(x**6) assert series(LambertW(x**2), x, n=8) == x**2 - x**4 + 3*x**6/2 + O(x**8) assert series(LambertW(sin(x)), x, n=4) == x - x**2 + 4*x**3/3 + O(x**4) def test_issue_11884(): assert cos(x).series(x, 1, n=1) == cos(1) + O(x - 1, (x, 1)) def test_issue_18008(): y = x*(1 + x*(1 - x))/((1 + x*(1 - x)) - (1 - x)*(1 - x)) assert y.series(x, oo, n=4) == -9/(32*x**3) - 3/(16*x**2) - 1/(8*x) + S(1)/4 + x/2 + \ O(x**(-4), (x, oo)) def test_issue_18842(): f = log(x/(1 - x)) assert f.series(x, 0.491, n=1).removeO().nsimplify() == \ -S(180019443780011)/5000000000000000 def test_issue_19534(): dt = symbols('dt', real=True) expr = 16*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0)/45 + \ 49*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \ 0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \ 0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + 0.051640768506639183825*dt + \ dt*(1/2 - sqrt(21)/14) + 1.0)/180 + 49*dt*(-0.23637909581542530626*dt*(2.0*dt + 1.0) - \ 0.74817562366625959291*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.88085458023927036857*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + \ 2.1165151389911680013*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \ 0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \ 0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) - \ 1.1854881643947648988*dt + dt*(sqrt(21)/14 + 1/2) + 1.0)/180 + \ dt*(0.66666666666666666667*dt*(2.0*dt + 1.0) + \ 6.0173399699313066769*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \ 4.1117044797036320069*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) - \ 7.0189140975801991157*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \ 0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \ 0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) + \ 0.94010945196161777522*dt*(-0.23637909581542530626*dt*(2.0*dt + 1.0) - \ 0.74817562366625959291*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.88085458023927036857*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + \ 2.1165151389911680013*dt*(-0.049335189898860408029*dt*(2.0*dt + 1.0) + \ 0.29601113939316244817*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) - \ 0.12564355335492979587*dt*(0.074074074074074074074*dt*(2.0*dt + 1.0) + \ 0.2962962962962962963*dt*(0.125*dt*(2.0*dt + 1.0) + 0.875*dt + 1.0) + \ 0.96296296296296296296*dt + 1.0) + 0.22431393315265061193*dt + 1.0) - \ 0.35816132904077632692*dt + 1.0) + 5.5065024887242400038*dt + 1.0)/20 + dt/20 + 1 assert N(expr.series(dt, 0, 8), 20) == ( - Float('0.00092592592592592596126289', precision=70) * dt**7 + Float('0.0027777777777777783174695', precision=70) * dt**6 + Float('0.016666666666666656027029', precision=70) * dt**5 + Float('0.083333333333333300951828', precision=70) * dt**4 + Float('0.33333333333333337034077', precision=70) * dt**3 + Float('1.0', precision=70) * dt**2 + Float('1.0', precision=70) * dt + Float('1.0', precision=70) ) def test_issue_11407(): a, b, c, x = symbols('a b c x') assert series(sqrt(a + b + c*x), x, 0, 1) == sqrt(a + b) + O(x) assert series(sqrt(a + b + c + c*x), x, 0, 1) == sqrt(a + b + c) + O(x) def test_issue_14037(): assert (sin(x**50)/x**51).series(x, n=0) == 1/x + O(1, x) def test_issue_20551(): expr = (exp(x)/x).series(x, n=None) terms = [ next(expr) for i in range(3) ] assert terms == [1/x, 1, x/2] def test_issue_20697(): p_0, p_1, p_2, p_3, b_0, b_1, b_2 = symbols('p_0 p_1 p_2 p_3 b_0 b_1 b_2') Q = (p_0 + (p_1 + (p_2 + p_3/y)/y)/y)/(1 + ((p_3/(b_0*y) + (b_0*p_2\ - b_1*p_3)/b_0**2)/y + (b_0**2*p_1 - b_0*b_1*p_2 - p_3*(b_0*b_2\ - b_1**2))/b_0**3)/y) assert Q.series(y, n=3).ratsimp() == b_2*y**2 + b_1*y + b_0 + O(y**3) def test_issue_21245(): fi = (1 + sqrt(5))/2 assert (1/(1 - x - x**2)).series(x, 1/fi, 1).factor() == \ (-4812 - 2152*sqrt(5) + 1686*x + 754*sqrt(5)*x\ + O((x - 2/(1 + sqrt(5)))**2, (x, 2/(1 + sqrt(5)))))/((1 + sqrt(5))\ *(20 + 9*sqrt(5))**2*(x + sqrt(5)*x - 2)) def test_issue_21938(): expr = sin(1/x + exp(-x)) - sin(1/x) assert expr.series(x, oo) == (1/(24*x**4) - 1/(2*x**2) + 1 + O(x**(-6), (x, oo)))*exp(-x) def test_issue_23432(): expr = 1/sqrt(1 - x**2) result = expr.series(x, 0.5) assert result.is_Add and len(result.args) == 7 def test_issue_23727(): res = series(sqrt(1 - x**2), x, 0.1) assert res.is_Add == True
c8cc3fe57d862d7c9b5471cc9d0d07d0dc7cb1758f60af441fc6e849904e630a
from itertools import product from sympy.concrete.summations import Sum from sympy.core.function import (Function, diff) from sympy.core import EulerGamma from sympy.core.numbers import (E, I, Rational, oo, pi, zoo) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.combinatorial.factorials import (binomial, factorial, subfactorial) from sympy.functions.elementary.complexes import (Abs, re, sign) from sympy.functions.elementary.exponential import (LambertW, exp, log) from sympy.functions.elementary.hyperbolic import (acosh, acoth, acsch, asech, atanh, sinh, tanh) from sympy.functions.elementary.integers import (ceiling, floor, frac) from sympy.functions.elementary.miscellaneous import (cbrt, real_root, sqrt) from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (acos, acot, acsc, asec, asin, atan, cos, cot, csc, sec, sin, tan) from sympy.functions.special.bessel import (besseli, bessely, besselj, besselk) from sympy.functions.special.error_functions import (Ei, erf, erfc, erfi, fresnelc, fresnels) from sympy.functions.special.gamma_functions import (digamma, gamma, uppergamma) from sympy.functions.special.hyper import meijerg from sympy.integrals.integrals import (Integral, integrate) from sympy.series.limits import (Limit, limit) from sympy.simplify.simplify import (logcombine, simplify) from sympy.simplify.hyperexpand import hyperexpand from sympy.calculus.accumulationbounds import AccumBounds from sympy.core.mul import Mul from sympy.series.limits import heuristics from sympy.series.order import Order from sympy.testing.pytest import XFAIL, raises from sympy.abc import x, y, z, k n = Symbol('n', integer=True, positive=True) def test_basic1(): assert limit(x, x, oo) is oo assert limit(x, x, -oo) is -oo assert limit(-x, x, oo) is -oo assert limit(x**2, x, -oo) is oo assert limit(-x**2, x, oo) is -oo assert limit(x*log(x), x, 0, dir="+") == 0 assert limit(1/x, x, oo) == 0 assert limit(exp(x), x, oo) is oo assert limit(-exp(x), x, oo) is -oo assert limit(exp(x)/x, x, oo) is oo assert limit(1/x - exp(-x), x, oo) == 0 assert limit(x + 1/x, x, oo) is oo assert limit(x - x**2, x, oo) is -oo assert limit((1 + x)**(1 + sqrt(2)), x, 0) == 1 assert limit((1 + x)**oo, x, 0) == Limit((x + 1)**oo, x, 0) assert limit((1 + x)**oo, x, 0, dir='-') == Limit((x + 1)**oo, x, 0, dir='-') assert limit((1 + x + y)**oo, x, 0, dir='-') == Limit((1 + x + y)**oo, x, 0, dir='-') assert limit(y/x/log(x), x, 0) == -oo*sign(y) assert limit(cos(x + y)/x, x, 0) == sign(cos(y))*oo assert limit(gamma(1/x + 3), x, oo) == 2 assert limit(S.NaN, x, -oo) is S.NaN assert limit(Order(2)*x, x, S.NaN) is S.NaN assert limit(1/(x - 1), x, 1, dir="+") is oo assert limit(1/(x - 1), x, 1, dir="-") is -oo assert limit(1/(5 - x)**3, x, 5, dir="+") is -oo assert limit(1/(5 - x)**3, x, 5, dir="-") is oo assert limit(1/sin(x), x, pi, dir="+") is -oo assert limit(1/sin(x), x, pi, dir="-") is oo assert limit(1/cos(x), x, pi/2, dir="+") is -oo assert limit(1/cos(x), x, pi/2, dir="-") is oo assert limit(1/tan(x**3), x, (2*pi)**Rational(1, 3), dir="+") is oo assert limit(1/tan(x**3), x, (2*pi)**Rational(1, 3), dir="-") is -oo assert limit(1/cot(x)**3, x, (pi*Rational(3, 2)), dir="+") is -oo assert limit(1/cot(x)**3, x, (pi*Rational(3, 2)), dir="-") is oo assert limit(tan(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity) assert limit(cot(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity) assert limit(sec(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity) assert limit(csc(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity) # test bi-directional limits assert limit(sin(x)/x, x, 0, dir="+-") == 1 assert limit(x**2, x, 0, dir="+-") == 0 assert limit(1/x**2, x, 0, dir="+-") is oo # test failing bi-directional limits assert limit(1/x, x, 0, dir="+-") is zoo # approaching 0 # from dir="+" assert limit(1 + 1/x, x, 0) is oo # from dir='-' # Add assert limit(1 + 1/x, x, 0, dir='-') is -oo # Pow assert limit(x**(-2), x, 0, dir='-') is oo assert limit(x**(-3), x, 0, dir='-') is -oo assert limit(1/sqrt(x), x, 0, dir='-') == (-oo)*I assert limit(x**2, x, 0, dir='-') == 0 assert limit(sqrt(x), x, 0, dir='-') == 0 assert limit(x**-pi, x, 0, dir='-') == -oo*(-1)**(1 - pi) assert limit((1 + cos(x))**oo, x, 0) == Limit((cos(x) + 1)**oo, x, 0) # test pull request 22491 assert limit(1/asin(x), x, 0, dir = '+') == oo assert limit(1/asin(x), x, 0, dir = '-') == -oo assert limit(1/sinh(x), x, 0, dir = '+') == oo assert limit(1/sinh(x), x, 0, dir = '-') == -oo assert limit(log(1/x) + 1/sin(x), x, 0, dir = '+') == oo assert limit(log(1/x) + 1/x, x, 0, dir = '+') == oo def test_basic2(): assert limit(x**x, x, 0, dir="+") == 1 assert limit((exp(x) - 1)/x, x, 0) == 1 assert limit(1 + 1/x, x, oo) == 1 assert limit(-exp(1/x), x, oo) == -1 assert limit(x + exp(-x), x, oo) is oo assert limit(x + exp(-x**2), x, oo) is oo assert limit(x + exp(-exp(x)), x, oo) is oo assert limit(13 + 1/x - exp(-x), x, oo) == 13 def test_basic3(): assert limit(1/x, x, 0, dir="+") is oo assert limit(1/x, x, 0, dir="-") is -oo def test_basic4(): assert limit(2*x + y*x, x, 0) == 0 assert limit(2*x + y*x, x, 1) == 2 + y assert limit(2*x**8 + y*x**(-3), x, -2) == 512 - y/8 assert limit(sqrt(x + 1) - sqrt(x), x, oo) == 0 assert integrate(1/(x**3 + 1), (x, 0, oo)) == 2*pi*sqrt(3)/9 def test_log(): # https://github.com/sympy/sympy/issues/21598 a, b, c = symbols('a b c', positive=True) A = log(a/b) - (log(a) - log(b)) assert A.limit(a, oo) == 0 assert (A * c).limit(a, oo) == 0 tau, x = symbols('tau x', positive=True) # The value of manualintegrate in the issue expr = tau**2*((tau - 1)*(tau + 1)*log(x + 1)/(tau**2 + 1)**2 + 1/((tau**2\ + 1)*(x + 1)) - (-2*tau*atan(x/tau) + (tau**2/2 - 1/2)*log(tau**2\ + x**2))/(tau**2 + 1)**2) assert limit(expr, x, oo) == pi*tau**3/(tau**2 + 1)**2 def test_piecewise(): # https://github.com/sympy/sympy/issues/18363 assert limit((real_root(x - 6, 3) + 2)/(x + 2), x, -2, '+') == Rational(1, 12) def test_piecewise2(): func1 = 2*sqrt(x)*Piecewise(((4*x - 2)/Abs(sqrt(4 - 4*(2*x - 1)**2)), 4*x - 2\ >= 0), ((2 - 4*x)/Abs(sqrt(4 - 4*(2*x - 1)**2)), True)) func2 = Piecewise((x**2/2, x <= 0.5), (x/2 - 0.125, True)) func3 = Piecewise(((x - 9) / 5, x < -1), ((x - 9) / 5, x > 4), (sqrt(Abs(x - 3)), True)) assert limit(func1, x, 0) == 1 assert limit(func2, x, 0) == 0 assert limit(func3, x, -1) == 2 def test_basic5(): class my(Function): @classmethod def eval(cls, arg): if arg is S.Infinity: return S.NaN assert limit(my(x), x, oo) == Limit(my(x), x, oo) def test_issue_3885(): assert limit(x*y + x*z, z, 2) == x*y + 2*x def test_Limit(): assert Limit(sin(x)/x, x, 0) != 1 assert Limit(sin(x)/x, x, 0).doit() == 1 assert Limit(x, x, 0, dir='+-').args == (x, x, 0, Symbol('+-')) def test_floor(): assert limit(floor(x), x, -2, "+") == -2 assert limit(floor(x), x, -2, "-") == -3 assert limit(floor(x), x, -1, "+") == -1 assert limit(floor(x), x, -1, "-") == -2 assert limit(floor(x), x, 0, "+") == 0 assert limit(floor(x), x, 0, "-") == -1 assert limit(floor(x), x, 1, "+") == 1 assert limit(floor(x), x, 1, "-") == 0 assert limit(floor(x), x, 2, "+") == 2 assert limit(floor(x), x, 2, "-") == 1 assert limit(floor(x), x, 248, "+") == 248 assert limit(floor(x), x, 248, "-") == 247 # https://github.com/sympy/sympy/issues/14478 assert limit(x*floor(3/x)/2, x, 0, '+') == Rational(3, 2) assert limit(floor(x + 1/2) - floor(x), x, oo) == AccumBounds(-S.Half, S(3)/2) # test issue 9158 assert limit(floor(atan(x)), x, oo) == 1 assert limit(floor(atan(x)), x, -oo) == -2 assert limit(ceiling(atan(x)), x, oo) == 2 assert limit(ceiling(atan(x)), x, -oo) == -1 def test_floor_requires_robust_assumptions(): assert limit(floor(sin(x)), x, 0, "+") == 0 assert limit(floor(sin(x)), x, 0, "-") == -1 assert limit(floor(cos(x)), x, 0, "+") == 0 assert limit(floor(cos(x)), x, 0, "-") == 0 assert limit(floor(5 + sin(x)), x, 0, "+") == 5 assert limit(floor(5 + sin(x)), x, 0, "-") == 4 assert limit(floor(5 + cos(x)), x, 0, "+") == 5 assert limit(floor(5 + cos(x)), x, 0, "-") == 5 def test_ceiling(): assert limit(ceiling(x), x, -2, "+") == -1 assert limit(ceiling(x), x, -2, "-") == -2 assert limit(ceiling(x), x, -1, "+") == 0 assert limit(ceiling(x), x, -1, "-") == -1 assert limit(ceiling(x), x, 0, "+") == 1 assert limit(ceiling(x), x, 0, "-") == 0 assert limit(ceiling(x), x, 1, "+") == 2 assert limit(ceiling(x), x, 1, "-") == 1 assert limit(ceiling(x), x, 2, "+") == 3 assert limit(ceiling(x), x, 2, "-") == 2 assert limit(ceiling(x), x, 248, "+") == 249 assert limit(ceiling(x), x, 248, "-") == 248 # https://github.com/sympy/sympy/issues/14478 assert limit(x*ceiling(3/x)/2, x, 0, '+') == Rational(3, 2) assert limit(ceiling(x + 1/2) - ceiling(x), x, oo) == AccumBounds(-S.Half, S(3)/2) def test_ceiling_requires_robust_assumptions(): assert limit(ceiling(sin(x)), x, 0, "+") == 1 assert limit(ceiling(sin(x)), x, 0, "-") == 0 assert limit(ceiling(cos(x)), x, 0, "+") == 1 assert limit(ceiling(cos(x)), x, 0, "-") == 1 assert limit(ceiling(5 + sin(x)), x, 0, "+") == 6 assert limit(ceiling(5 + sin(x)), x, 0, "-") == 5 assert limit(ceiling(5 + cos(x)), x, 0, "+") == 6 assert limit(ceiling(5 + cos(x)), x, 0, "-") == 6 def test_frac(): assert limit(frac(x), x, oo) == AccumBounds(0, 1) assert limit(frac(x)**(1/x), x, oo) == AccumBounds(0, 1) assert limit(frac(x)**(1/x), x, -oo) == AccumBounds(1, oo) assert limit(frac(x)**x, x, oo) == AccumBounds(0, oo) # wolfram gives (0, 1) assert limit(frac(sin(x)), x, 0, "+") == 0 assert limit(frac(sin(x)), x, 0, "-") == 1 assert limit(frac(cos(x)), x, 0, "+-") == 1 assert limit(frac(x**2), x, 0, "+-") == 0 raises(ValueError, lambda: limit(frac(x), x, 0, '+-')) assert limit(frac(-2*x + 1), x, 0, "+") == 1 assert limit(frac(-2*x + 1), x, 0, "-") == 0 assert limit(frac(x + S.Half), x, 0, "+-") == 1/2 assert limit(frac(1/x), x, 0) == AccumBounds(0, 1) def test_issue_14355(): assert limit(floor(sin(x)/x), x, 0, '+') == 0 assert limit(floor(sin(x)/x), x, 0, '-') == 0 # test comment https://github.com/sympy/sympy/issues/14355#issuecomment-372121314 assert limit(floor(-tan(x)/x), x, 0, '+') == -2 assert limit(floor(-tan(x)/x), x, 0, '-') == -2 def test_atan(): x = Symbol("x", real=True) assert limit(atan(x)*sin(1/x), x, 0) == 0 assert limit(atan(x) + sqrt(x + 1) - sqrt(x), x, oo) == pi/2 def test_set_signs(): assert limit(abs(x), x, 0) == 0 assert limit(abs(sin(x)), x, 0) == 0 assert limit(abs(cos(x)), x, 0) == 1 assert limit(abs(sin(x + 1)), x, 0) == sin(1) # https://github.com/sympy/sympy/issues/9449 assert limit((Abs(x + y) - Abs(x - y))/(2*x), x, 0) == sign(y) # https://github.com/sympy/sympy/issues/12398 assert limit(Abs(log(x)/x**3), x, oo) == 0 assert limit(x*(Abs(log(x)/x**3)/Abs(log(x + 1)/(x + 1)**3) - 1), x, oo) == 3 # https://github.com/sympy/sympy/issues/18501 assert limit(Abs(log(x - 1)**3 - 1), x, 1, '+') == oo # https://github.com/sympy/sympy/issues/18997 assert limit(Abs(log(x)), x, 0) == oo assert limit(Abs(log(Abs(x))), x, 0) == oo # https://github.com/sympy/sympy/issues/19026 z = Symbol('z', positive=True) assert limit(Abs(log(z) + 1)/log(z), z, oo) == 1 # https://github.com/sympy/sympy/issues/20704 assert limit(z*(Abs(1/z + y) - Abs(y - 1/z))/2, z, 0) == 0 # https://github.com/sympy/sympy/issues/21606 assert limit(cos(z)/sign(z), z, pi, '-') == -1 def test_heuristic(): x = Symbol("x", real=True) assert heuristics(sin(1/x) + atan(x), x, 0, '+') == AccumBounds(-1, 1) assert limit(log(2 + sqrt(atan(x))*sqrt(sin(1/x))), x, 0) == log(2) def test_issue_3871(): z = Symbol("z", positive=True) f = -1/z*exp(-z*x) assert limit(f, x, oo) == 0 assert f.limit(x, oo) == 0 def test_exponential(): n = Symbol('n') x = Symbol('x', real=True) assert limit((1 + x/n)**n, n, oo) == exp(x) assert limit((1 + x/(2*n))**n, n, oo) == exp(x/2) assert limit((1 + x/(2*n + 1))**n, n, oo) == exp(x/2) assert limit(((x - 1)/(x + 1))**x, x, oo) == exp(-2) assert limit(1 + (1 + 1/x)**x, x, oo) == 1 + S.Exp1 assert limit((2 + 6*x)**x/(6*x)**x, x, oo) == exp(S('1/3')) def test_exponential2(): n = Symbol('n') assert limit((1 + x/(n + sin(n)))**n, n, oo) == exp(x) def test_doit(): f = Integral(2 * x, x) l = Limit(f, x, oo) assert l.doit() is oo def test_series_AccumBounds(): assert limit(sin(k) - sin(k + 1), k, oo) == AccumBounds(-2, 2) assert limit(cos(k) - cos(k + 1) + 1, k, oo) == AccumBounds(-1, 3) # not the exact bound assert limit(sin(k) - sin(k)*cos(k), k, oo) == AccumBounds(-2, 2) # test for issue #9934 lo = (-3 + cos(1))/2 hi = (1 + cos(1))/2 t1 = Mul(AccumBounds(lo, hi), 1/(-1 + cos(1)), evaluate=False) assert limit(simplify(Sum(cos(n).rewrite(exp), (n, 0, k)).doit().rewrite(sin)), k, oo) == t1 t2 = Mul(AccumBounds(-1 + sin(1)/2, sin(1)/2 + 1), 1/(1 - cos(1))) assert limit(simplify(Sum(sin(n).rewrite(exp), (n, 0, k)).doit().rewrite(sin)), k, oo) == t2 assert limit(((sin(x) + 1)/2)**x, x, oo) == AccumBounds(0, oo) # wolfram says 0 # https://github.com/sympy/sympy/issues/12312 e = 2**(-x)*(sin(x) + 1)**x assert limit(e, x, oo) == AccumBounds(0, oo) def test_bessel_functions_at_infinity(): # Pull Request 23844 implements limits for all bessel and modified bessel # functions approaching infinity along any direction i.e. abs(z0) tends to oo assert limit(besselj(1, x), x, oo) == 0 assert limit(besselj(1, x), x, -oo) == 0 assert limit(besselj(1, x), x, I*oo) == oo*I assert limit(besselj(1, x), x, -I*oo) == -oo*I assert limit(bessely(1, x), x, oo) == 0 assert limit(bessely(1, x), x, -oo) == 0 assert limit(bessely(1, x), x, I*oo) == -oo assert limit(bessely(1, x), x, -I*oo) == -oo assert limit(besseli(1, x), x, oo) == oo assert limit(besseli(1, x), x, -oo) == -oo assert limit(besseli(1, x), x, I*oo) == 0 assert limit(besseli(1, x), x, -I*oo) == 0 assert limit(besselk(1, x), x, oo) == 0 assert limit(besselk(1, x), x, -oo) == -oo*I assert limit(besselk(1, x), x, I*oo) == 0 assert limit(besselk(1, x), x, -I*oo) == 0 # test issue 14874 assert limit(besselk(0, x), x, oo) == 0 @XFAIL def test_doit2(): f = Integral(2 * x, x) l = Limit(f, x, oo) # limit() breaks on the contained Integral. assert l.doit(deep=False) == l def test_issue_2929(): assert limit((x * exp(x))/(exp(x) - 1), x, -oo) == 0 def test_issue_3792(): assert limit((1 - cos(x))/x**2, x, S.Half) == 4 - 4*cos(S.Half) assert limit(sin(sin(x + 1) + 1), x, 0) == sin(1 + sin(1)) assert limit(abs(sin(x + 1) + 1), x, 0) == 1 + sin(1) def test_issue_4090(): assert limit(1/(x + 3), x, 2) == Rational(1, 5) assert limit(1/(x + pi), x, 2) == S.One/(2 + pi) assert limit(log(x)/(x**2 + 3), x, 2) == log(2)/7 assert limit(log(x)/(x**2 + pi), x, 2) == log(2)/(4 + pi) def test_issue_4547(): assert limit(cot(x), x, 0, dir='+') is oo assert limit(cot(x), x, pi/2, dir='+') == 0 def test_issue_5164(): assert limit(x**0.5, x, oo) == oo**0.5 is oo assert limit(x**0.5, x, 16) == S(16)**0.5 assert limit(x**0.5, x, 0) == 0 assert limit(x**(-0.5), x, oo) == 0 assert limit(x**(-0.5), x, 4) == S(4)**(-0.5) def test_issue_5383(): func = (1.0 * 1 + 1.0 * x)**(1.0 * 1 / x) assert limit(func, x, 0) == E def test_issue_14793(): expr = ((x + S(1)/2) * log(x) - x + log(2*pi)/2 - \ log(factorial(x)) + S(1)/(12*x))*x**3 assert limit(expr, x, oo) == S(1)/360 def test_issue_5183(): # using list(...) so py.test can recalculate values tests = list(product([x, -x], [-1, 1], [2, 3, S.Half, Rational(2, 3)], ['-', '+'])) results = (oo, oo, -oo, oo, -oo*I, oo, -oo*(-1)**Rational(1, 3), oo, 0, 0, 0, 0, 0, 0, 0, 0, oo, oo, oo, -oo, oo, -oo*I, oo, -oo*(-1)**Rational(1, 3), 0, 0, 0, 0, 0, 0, 0, 0) assert len(tests) == len(results) for i, (args, res) in enumerate(zip(tests, results)): y, s, e, d = args eq = y**(s*e) try: assert limit(eq, x, 0, dir=d) == res except AssertionError: if 0: # change to 1 if you want to see the failing tests print() print(i, res, eq, d, limit(eq, x, 0, dir=d)) else: assert None def test_issue_5184(): assert limit(sin(x)/x, x, oo) == 0 assert limit(atan(x), x, oo) == pi/2 assert limit(gamma(x), x, oo) is oo assert limit(cos(x)/x, x, oo) == 0 assert limit(gamma(x), x, S.Half) == sqrt(pi) r = Symbol('r', real=True) assert limit(r*sin(1/r), r, 0) == 0 def test_issue_5229(): assert limit((1 + y)**(1/y) - S.Exp1, y, 0) == 0 def test_issue_4546(): # using list(...) so py.test can recalculate values tests = list(product([cot, tan], [-pi/2, 0, pi/2, pi, pi*Rational(3, 2)], ['-', '+'])) results = (0, 0, -oo, oo, 0, 0, -oo, oo, 0, 0, oo, -oo, 0, 0, oo, -oo, 0, 0, oo, -oo) assert len(tests) == len(results) for i, (args, res) in enumerate(zip(tests, results)): f, l, d = args eq = f(x) try: assert limit(eq, x, l, dir=d) == res except AssertionError: if 0: # change to 1 if you want to see the failing tests print() print(i, res, eq, l, d, limit(eq, x, l, dir=d)) else: assert None def test_issue_3934(): assert limit((1 + x**log(3))**(1/x), x, 0) == 1 assert limit((5**(1/x) + 3**(1/x))**x, x, 0) == 5 def test_calculate_series(): # NOTE # The calculate_series method is being deprecated and is no longer responsible # for result being returned. The mrv_leadterm function now uses simple leadterm # calls rather than calculate_series. # needs gruntz calculate_series to go to n = 32 assert limit(x**Rational(77, 3)/(1 + x**Rational(77, 3)), x, oo) == 1 # needs gruntz calculate_series to go to n = 128 assert limit(x**101.1/(1 + x**101.1), x, oo) == 1 def test_issue_5955(): assert limit((x**16)/(1 + x**16), x, oo) == 1 assert limit((x**100)/(1 + x**100), x, oo) == 1 assert limit((x**1885)/(1 + x**1885), x, oo) == 1 assert limit((x**1000/((x + 1)**1000 + exp(-x))), x, oo) == 1 def test_newissue(): assert limit(exp(1/sin(x))/exp(cot(x)), x, 0) == 1 def test_extended_real_line(): assert limit(x - oo, x, oo) == Limit(x - oo, x, oo) assert limit(1/(x + sin(x)) - oo, x, 0) == Limit(1/(x + sin(x)) - oo, x, 0) assert limit(oo/x, x, oo) == Limit(oo/x, x, oo) assert limit(x - oo + 1/x, x, oo) == Limit(x - oo + 1/x, x, oo) @XFAIL def test_order_oo(): x = Symbol('x', positive=True) assert Order(x)*oo != Order(1, x) assert limit(oo/(x**2 - 4), x, oo) is oo def test_issue_5436(): raises(NotImplementedError, lambda: limit(exp(x*y), x, oo)) raises(NotImplementedError, lambda: limit(exp(-x*y), x, oo)) def test_Limit_dir(): raises(TypeError, lambda: Limit(x, x, 0, dir=0)) raises(ValueError, lambda: Limit(x, x, 0, dir='0')) def test_polynomial(): assert limit((x + 1)**1000/((x + 1)**1000 + 1), x, oo) == 1 assert limit((x + 1)**1000/((x + 1)**1000 + 1), x, -oo) == 1 def test_rational(): assert limit(1/y - (1/(y + x) + x/(y + x)/y)/z, x, oo) == (z - 1)/(y*z) assert limit(1/y - (1/(y + x) + x/(y + x)/y)/z, x, -oo) == (z - 1)/(y*z) def test_issue_5740(): assert limit(log(x)*z - log(2*x)*y, x, 0) == oo*sign(y - z) def test_issue_6366(): n = Symbol('n', integer=True, positive=True) r = (n + 1)*x**(n + 1)/(x**(n + 1) - 1) - x/(x - 1) assert limit(r, x, 1).cancel() == n/2 def test_factorial(): f = factorial(x) assert limit(f, x, oo) is oo assert limit(x/f, x, oo) == 0 # see Stirling's approximation: # https://en.wikipedia.org/wiki/Stirling's_approximation assert limit(f/(sqrt(2*pi*x)*(x/E)**x), x, oo) == 1 assert limit(f, x, -oo) == gamma(-oo) def test_issue_6560(): e = (5*x**3/4 - x*Rational(3, 4) + (y*(3*x**2/2 - S.Half) + 35*x**4/8 - 15*x**2/4 + Rational(3, 8))/(2*(y + 1))) assert limit(e, y, oo) == 5*x**3/4 + 3*x**2/4 - 3*x/4 - Rational(1, 4) @XFAIL def test_issue_5172(): n = Symbol('n') r = Symbol('r', positive=True) c = Symbol('c') p = Symbol('p', positive=True) m = Symbol('m', negative=True) expr = ((2*n*(n - r + 1)/(n + r*(n - r + 1)))**c + (r - 1)*(n*(n - r + 2)/(n + r*(n - r + 1)))**c - n)/(n**c - n) expr = expr.subs(c, c + 1) raises(NotImplementedError, lambda: limit(expr, n, oo)) assert limit(expr.subs(c, m), n, oo) == 1 assert limit(expr.subs(c, p), n, oo).simplify() == \ (2**(p + 1) + r - 1)/(r + 1)**(p + 1) def test_issue_7088(): a = Symbol('a') assert limit(sqrt(x/(x + a)), x, oo) == 1 def test_branch_cuts(): assert limit(asin(I*x + 2), x, 0) == pi - asin(2) assert limit(asin(I*x + 2), x, 0, '-') == asin(2) assert limit(asin(I*x - 2), x, 0) == -asin(2) assert limit(asin(I*x - 2), x, 0, '-') == -pi + asin(2) assert limit(acos(I*x + 2), x, 0) == -acos(2) assert limit(acos(I*x + 2), x, 0, '-') == acos(2) assert limit(acos(I*x - 2), x, 0) == acos(-2) assert limit(acos(I*x - 2), x, 0, '-') == 2*pi - acos(-2) assert limit(atan(x + 2*I), x, 0) == I*atanh(2) assert limit(atan(x + 2*I), x, 0, '-') == -pi + I*atanh(2) assert limit(atan(x - 2*I), x, 0) == pi - I*atanh(2) assert limit(atan(x - 2*I), x, 0, '-') == -I*atanh(2) assert limit(atan(1/x), x, 0) == pi/2 assert limit(atan(1/x), x, 0, '-') == -pi/2 assert limit(atan(x), x, oo) == pi/2 assert limit(atan(x), x, -oo) == -pi/2 assert limit(acot(x + S(1)/2*I), x, 0) == pi - I*acoth(S(1)/2) assert limit(acot(x + S(1)/2*I), x, 0, '-') == -I*acoth(S(1)/2) assert limit(acot(x - S(1)/2*I), x, 0) == I*acoth(S(1)/2) assert limit(acot(x - S(1)/2*I), x, 0, '-') == -pi + I*acoth(S(1)/2) assert limit(acot(x), x, 0) == pi/2 assert limit(acot(x), x, 0, '-') == -pi/2 assert limit(asec(I*x + S(1)/2), x, 0) == asec(S(1)/2) assert limit(asec(I*x + S(1)/2), x, 0, '-') == -asec(S(1)/2) assert limit(asec(I*x - S(1)/2), x, 0) == 2*pi - asec(-S(1)/2) assert limit(asec(I*x - S(1)/2), x, 0, '-') == asec(-S(1)/2) assert limit(acsc(I*x + S(1)/2), x, 0) == acsc(S(1)/2) assert limit(acsc(I*x + S(1)/2), x, 0, '-') == pi - acsc(S(1)/2) assert limit(acsc(I*x - S(1)/2), x, 0) == -pi + acsc(S(1)/2) assert limit(acsc(I*x - S(1)/2), x, 0, '-') == -acsc(S(1)/2) assert limit(log(I*x - 1), x, 0) == I*pi assert limit(log(I*x - 1), x, 0, '-') == -I*pi assert limit(log(-I*x - 1), x, 0) == -I*pi assert limit(log(-I*x - 1), x, 0, '-') == I*pi assert limit(sqrt(I*x - 1), x, 0) == I assert limit(sqrt(I*x - 1), x, 0, '-') == -I assert limit(sqrt(-I*x - 1), x, 0) == -I assert limit(sqrt(-I*x - 1), x, 0, '-') == I assert limit(cbrt(I*x - 1), x, 0) == (-1)**(S(1)/3) assert limit(cbrt(I*x - 1), x, 0, '-') == -(-1)**(S(2)/3) assert limit(cbrt(-I*x - 1), x, 0) == -(-1)**(S(2)/3) assert limit(cbrt(-I*x - 1), x, 0, '-') == (-1)**(S(1)/3) def test_issue_6364(): a = Symbol('a') e = z/(1 - sqrt(1 + z)*sin(a)**2 - sqrt(1 - z)*cos(a)**2) assert limit(e, z, 0) == 1/(cos(a)**2 - S.Half) def test_issue_6682(): assert limit(exp(2*Ei(-x))/x**2, x, 0) == exp(2*EulerGamma) def test_issue_4099(): a = Symbol('a') assert limit(a/x, x, 0) == oo*sign(a) assert limit(-a/x, x, 0) == -oo*sign(a) assert limit(-a*x, x, oo) == -oo*sign(a) assert limit(a*x, x, oo) == oo*sign(a) def test_issue_4503(): dx = Symbol('dx') assert limit((sqrt(1 + exp(x + dx)) - sqrt(1 + exp(x)))/dx, dx, 0) == \ exp(x)/(2*sqrt(exp(x) + 1)) def test_issue_6052(): G = meijerg((), (), (1,), (0,), -x) g = hyperexpand(G) assert limit(g, x, 0, '+-') == 0 assert limit(g, x, oo) == -oo def test_issue_7224(): expr = sqrt(x)*besseli(1,sqrt(8*x)) assert limit(x*diff(expr, x, x)/expr, x, 0) == 2 assert limit(x*diff(expr, x, x)/expr, x, 1).evalf() == 2.0 def test_issue_8208(): assert limit(n**(Rational(1, 1e9) - 1), n, oo) == 0 def test_issue_8229(): assert limit((x**Rational(1, 4) - 2)/(sqrt(x) - 4)**Rational(2, 3), x, 16) == 0 def test_issue_8433(): d, t = symbols('d t', positive=True) assert limit(erf(1 - t/d), t, oo) == -1 def test_issue_8481(): k = Symbol('k', integer=True, nonnegative=True) lamda = Symbol('lamda', positive=True) assert limit(lamda**k * exp(-lamda) / factorial(k), k, oo) == 0 def test_issue_8462(): assert limit(binomial(n, n/2), n, oo) == oo assert limit(binomial(n, n/2) * 3 ** (-n), n, oo) == 0 def test_issue_8634(): n = Symbol('n', integer=True, positive=True) x = Symbol('x') assert limit(x**n, x, -oo) == oo*sign((-1)**n) def test_issue_8635_18176(): x = Symbol('x', real=True) k = Symbol('k', positive=True) assert limit(x**n - x**(n - 0), x, oo) == 0 assert limit(x**n - x**(n - 5), x, oo) == oo assert limit(x**n - x**(n - 2.5), x, oo) == oo assert limit(x**n - x**(n - k - 1), x, oo) == oo x = Symbol('x', positive=True) assert limit(x**n - x**(n - 1), x, oo) == oo assert limit(x**n - x**(n + 2), x, oo) == -oo def test_issue_8730(): assert limit(subfactorial(x), x, oo) is oo def test_issue_9252(): n = Symbol('n', integer=True) c = Symbol('c', positive=True) assert limit((log(n))**(n/log(n)) / (1 + c)**n, n, oo) == 0 # limit should depend on the value of c raises(NotImplementedError, lambda: limit((log(n))**(n/log(n)) / c**n, n, oo)) def test_issue_9558(): assert limit(sin(x)**15, x, 0, '-') == 0 def test_issue_10801(): # make sure limits work with binomial assert limit(16**k / (k * binomial(2*k, k)**2), k, oo) == pi def test_issue_10976(): s, x = symbols('s x', real=True) assert limit(erf(s*x)/erf(s), s, 0) == x def test_issue_9041(): assert limit(factorial(n) / ((n/exp(1))**n * sqrt(2*pi*n)), n, oo) == 1 def test_issue_9205(): x, y, a = symbols('x, y, a') assert Limit(x, x, a).free_symbols == {a} assert Limit(x, x, a, '-').free_symbols == {a} assert Limit(x + y, x + y, a).free_symbols == {a} assert Limit(-x**2 + y, x**2, a).free_symbols == {y, a} def test_issue_9471(): assert limit(((27**(log(n,3)))/n**3),n,oo) == 1 assert limit(((27**(log(n,3)+1))/n**3),n,oo) == 27 def test_issue_11496(): assert limit(erfc(log(1/x)), x, oo) == 2 def test_issue_11879(): assert simplify(limit(((x+y)**n-x**n)/y, y, 0)) == n*x**(n-1) def test_limit_with_Float(): k = symbols("k") assert limit(1.0 ** k, k, oo) == 1 assert limit(0.3*1.0**k, k, oo) == Rational(3, 10) def test_issue_10610(): assert limit(3**x*3**(-x - 1)*(x + 1)**2/x**2, x, oo) == Rational(1, 3) def test_issue_10868(): assert limit(log(x) + asech(x), x, 0, '+') == log(2) assert limit(log(x) + asech(x), x, 0, '-') == log(2) + 2*I*pi raises(ValueError, lambda: limit(log(x) + asech(x), x, 0, '+-')) assert limit(log(x) + asech(x), x, oo) == oo assert limit(log(x) + acsch(x), x, 0, '+') == log(2) assert limit(log(x) + acsch(x), x, 0, '-') == -oo raises(ValueError, lambda: limit(log(x) + acsch(x), x, 0, '+-')) assert limit(log(x) + acsch(x), x, oo) == oo def test_issue_6599(): assert limit((n + cos(n))/n, n, oo) == 1 def test_issue_12555(): assert limit((3**x + 2* x**10) / (x**10 + exp(x)), x, -oo) == 2 assert limit((3**x + 2* x**10) / (x**10 + exp(x)), x, oo) is oo def test_issue_12769(): r, z, x = symbols('r z x', real=True) a, b, s0, K, F0, s, T = symbols('a b s0 K F0 s T', positive=True, real=True) fx = (F0**b*K**b*r*s0 - sqrt((F0**2*K**(2*b)*a**2*(b - 1) + \ F0**(2*b)*K**2*a**2*(b - 1) + F0**(2*b)*K**(2*b)*s0**2*(b - 1)*(b**2 - 2*b + 1) - \ 2*F0**(2*b)*K**(b + 1)*a*r*s0*(b**2 - 2*b + 1) + \ 2*F0**(b + 1)*K**(2*b)*a*r*s0*(b**2 - 2*b + 1) - \ 2*F0**(b + 1)*K**(b + 1)*a**2*(b - 1))/((b - 1)*(b**2 - 2*b + 1))))*(b*r - b - r + 1) assert fx.subs(K, F0).factor(deep=True) == limit(fx, K, F0).factor(deep=True) def test_issue_13332(): assert limit(sqrt(30)*5**(-5*x - 1)*(46656*x)**x*(5*x + 2)**(5*x + 5*S.Half) * (6*x + 2)**(-6*x - 5*S.Half), x, oo) == Rational(25, 36) def test_issue_12564(): assert limit(x**2 + x*sin(x) + cos(x), x, -oo) is oo assert limit(x**2 + x*sin(x) + cos(x), x, oo) is oo assert limit(((x + cos(x))**2).expand(), x, oo) is oo assert limit(((x + sin(x))**2).expand(), x, oo) is oo assert limit(((x + cos(x))**2).expand(), x, -oo) is oo assert limit(((x + sin(x))**2).expand(), x, -oo) is oo def test_issue_14456(): raises(NotImplementedError, lambda: Limit(exp(x), x, zoo).doit()) raises(NotImplementedError, lambda: Limit(x**2/(x+1), x, zoo).doit()) def test_issue_14411(): assert limit(3*sec(4*pi*x - x/3), x, 3*pi/(24*pi - 2)) is -oo def test_issue_13382(): assert limit(x*(((x + 1)**2 + 1)/(x**2 + 1) - 1), x, oo) == 2 def test_issue_13403(): assert limit(x*(-1 + (x + log(x + 1) + 1)/(x + log(x))), x, oo) == 1 def test_issue_13416(): assert limit((-x**3*log(x)**3 + (x - 1)*(x + 1)**2*log(x + 1)**3)/(x**2*log(x)**3), x, oo) == 1 def test_issue_13462(): assert limit(n**2*(2*n*(-(1 - 1/(2*n))**x + 1) - x - (-x**2/4 + x/4)/n), n, oo) == x**3/24 - x**2/8 + x/12 def test_issue_13750(): a = Symbol('a') assert limit(erf(a - x), x, oo) == -1 assert limit(erf(sqrt(x) - x), x, oo) == -1 def test_issue_14276(): assert isinstance(limit(sin(x)**log(x), x, oo), Limit) assert isinstance(limit(sin(x)**cos(x), x, oo), Limit) assert isinstance(limit(sin(log(cos(x))), x, oo), Limit) assert limit((1 + 1/(x**2 + cos(x)))**(x**2 + x), x, oo) == E def test_issue_14514(): assert limit((1/(log(x)**log(x)))**(1/x), x, oo) == 1 def test_issues_14525(): assert limit(sin(x)**2 - cos(x) + tan(x)*csc(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity) assert limit(sin(x)**2 - cos(x) + sin(x)*cot(x), x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity) assert limit(cot(x) - tan(x)**2, x, oo) == AccumBounds(S.NegativeInfinity, S.Infinity) assert limit(cos(x) - tan(x)**2, x, oo) == AccumBounds(S.NegativeInfinity, S.One) assert limit(sin(x) - tan(x)**2, x, oo) == AccumBounds(S.NegativeInfinity, S.One) assert limit(cos(x)**2 - tan(x)**2, x, oo) == AccumBounds(S.NegativeInfinity, S.One) assert limit(tan(x)**2 + sin(x)**2 - cos(x), x, oo) == AccumBounds(-S.One, S.Infinity) def test_issue_14574(): assert limit(sqrt(x)*cos(x - x**2) / (x + 1), x, oo) == 0 def test_issue_10102(): assert limit(fresnels(x), x, oo) == S.Half assert limit(3 + fresnels(x), x, oo) == 3 + S.Half assert limit(5*fresnels(x), x, oo) == Rational(5, 2) assert limit(fresnelc(x), x, oo) == S.Half assert limit(fresnels(x), x, -oo) == Rational(-1, 2) assert limit(4*fresnelc(x), x, -oo) == -2 def test_issue_14377(): raises(NotImplementedError, lambda: limit(exp(I*x)*sin(pi*x), x, oo)) def test_issue_15146(): e = (x/2) * (-2*x**3 - 2*(x**3 - 1) * x**2 * digamma(x**3 + 1) + \ 2*(x**3 - 1) * x**2 * digamma(x**3 + x + 1) + x + 3) assert limit(e, x, oo) == S(1)/3 def test_issue_15202(): e = (2**x*(2 + 2**(-x)*(-2*2**x + x + 2))/(x + 1))**(x + 1) assert limit(e, x, oo) == exp(1) e = (log(x, 2)**7 + 10*x*factorial(x) + 5**x) / (factorial(x + 1) + 3*factorial(x) + 10**x) assert limit(e, x, oo) == 10 def test_issue_15282(): assert limit((x**2000 - (x + 1)**2000) / x**1999, x, oo) == -2000 def test_issue_15984(): assert limit((-x + log(exp(x) + 1))/x, x, oo, dir='-') == 0 def test_issue_13571(): assert limit(uppergamma(x, 1) / gamma(x), x, oo) == 1 def test_issue_13575(): assert limit(acos(erfi(x)), x, 1) == acos(erfi(S.One)) def test_issue_17325(): assert Limit(sin(x)/x, x, 0, dir="+-").doit() == 1 assert Limit(x**2, x, 0, dir="+-").doit() == 0 assert Limit(1/x**2, x, 0, dir="+-").doit() is oo assert Limit(1/x, x, 0, dir="+-").doit() is zoo def test_issue_10978(): assert LambertW(x).limit(x, 0) == 0 def test_issue_14313_comment(): assert limit(floor(n/2), n, oo) is oo @XFAIL def test_issue_15323(): d = ((1 - 1/x)**x).diff(x) assert limit(d, x, 1, dir='+') == 1 def test_issue_12571(): assert limit(-LambertW(-log(x))/log(x), x, 1) == 1 def test_issue_14590(): assert limit((x**3*((x + 1)/x)**x)/((x + 1)*(x + 2)*(x + 3)), x, oo) == exp(1) def test_issue_14393(): a, b = symbols('a b') assert limit((x**b - y**b)/(x**a - y**a), x, y) == b*y**(-a + b)/a def test_issue_14556(): assert limit(factorial(n + 1)**(1/(n + 1)) - factorial(n)**(1/n), n, oo) == exp(-1) def test_issue_14811(): assert limit(((1 + ((S(2)/3)**(x + 1)))**(2**x))/(2**((S(4)/3)**(x - 1))), x, oo) == oo def test_issue_16222(): assert limit(exp(x), x, 1000000000) == exp(1000000000) def test_issue_16714(): assert limit(((x**(x + 1) + (x + 1)**x) / x**(x + 1))**x, x, oo) == exp(exp(1)) def test_issue_16722(): z = symbols('z', positive=True) assert limit(binomial(n + z, n)*n**-z, n, oo) == 1/gamma(z + 1) z = symbols('z', positive=True, integer=True) assert limit(binomial(n + z, n)*n**-z, n, oo) == 1/gamma(z + 1) def test_issue_17431(): assert limit(((n + 1) + 1) / (((n + 1) + 2) * factorial(n + 1)) * (n + 2) * factorial(n) / (n + 1), n, oo) == 0 assert limit((n + 2)**2*factorial(n)/((n + 1)*(n + 3)*factorial(n + 1)) , n, oo) == 0 assert limit((n + 1) * factorial(n) / (n * factorial(n + 1)), n, oo) == 0 def test_issue_17671(): assert limit(Ei(-log(x)) - log(log(x))/x, x, 1) == EulerGamma def test_issue_17751(): a, b, c, x = symbols('a b c x', positive=True) assert limit((a + 1)*x - sqrt((a + 1)**2*x**2 + b*x + c), x, oo) == -b/(2*a + 2) def test_issue_17792(): assert limit(factorial(n)/sqrt(n)*(exp(1)/n)**n, n, oo) == sqrt(2)*sqrt(pi) def test_issue_18118(): assert limit(sign(sin(x)), x, 0, "-") == -1 assert limit(sign(sin(x)), x, 0, "+") == 1 def test_issue_18306(): assert limit(sin(sqrt(x))/sqrt(sin(x)), x, 0, '+') == 1 def test_issue_18378(): assert limit(log(exp(3*x) + x)/log(exp(x) + x**100), x, oo) == 3 def test_issue_18399(): assert limit((1 - S(1)/2*x)**(3*x), x, oo) is zoo assert limit((-x)**x, x, oo) is zoo def test_issue_18442(): assert limit(tan(x)**(2**(sqrt(pi))), x, oo, dir='-') == Limit(tan(x)**(2**(sqrt(pi))), x, oo, dir='-') def test_issue_18452(): assert limit(abs(log(x))**x, x, 0) == 1 assert limit(abs(log(x))**x, x, 0, "-") == 1 def test_issue_18473(): assert limit(sin(x)**(1/x), x, oo) == Limit(sin(x)**(1/x), x, oo, dir='-') assert limit(cos(x)**(1/x), x, oo) == Limit(cos(x)**(1/x), x, oo, dir='-') assert limit(tan(x)**(1/x), x, oo) == Limit(tan(x)**(1/x), x, oo, dir='-') assert limit((cos(x) + 2)**(1/x), x, oo) == 1 assert limit((sin(x) + 10)**(1/x), x, oo) == 1 assert limit((cos(x) - 2)**(1/x), x, oo) == Limit((cos(x) - 2)**(1/x), x, oo, dir='-') assert limit((cos(x) + 1)**(1/x), x, oo) == AccumBounds(0, 1) assert limit((tan(x)**2)**(2/x) , x, oo) == AccumBounds(0, oo) assert limit((sin(x)**2)**(1/x), x, oo) == AccumBounds(0, 1) # Tests for issue #23751 assert limit((cos(x) + 1)**(1/x), x, -oo) == AccumBounds(1, oo) assert limit((sin(x)**2)**(1/x), x, -oo) == AccumBounds(1, oo) assert limit((tan(x)**2)**(2/x) , x, -oo) == AccumBounds(0, oo) def test_issue_18482(): assert limit((2*exp(3*x)/(exp(2*x) + 1))**(1/x), x, oo) == exp(1) def test_issue_18508(): assert limit(sin(x)/sqrt(1-cos(x)), x, 0) == sqrt(2) assert limit(sin(x)/sqrt(1-cos(x)), x, 0, dir='+') == sqrt(2) assert limit(sin(x)/sqrt(1-cos(x)), x, 0, dir='-') == -sqrt(2) def test_issue_18521(): raises(NotImplementedError, lambda: limit(exp((2 - n) * x), x, oo)) def test_issue_18969(): a, b = symbols('a b', positive=True) assert limit(LambertW(a), a, b) == LambertW(b) assert limit(exp(LambertW(a)), a, b) == exp(LambertW(b)) def test_issue_18992(): assert limit(n/(factorial(n)**(1/n)), n, oo) == exp(1) def test_issue_19067(): x = Symbol('x') assert limit(gamma(x)/(gamma(x - 1)*gamma(x + 2)), x, 0) == -1 def test_issue_19586(): assert limit(x**(2**x*3**(-x)), x, oo) == 1 def test_issue_13715(): n = Symbol('n') p = Symbol('p', zero=True) assert limit(n + p, n, 0) == 0 def test_issue_15055(): assert limit(n**3*((-n - 1)*sin(1/n) + (n + 2)*sin(1/(n + 1)))/(-n + 1), n, oo) == 1 def test_issue_16708(): m, vi = symbols('m vi', positive=True) B, ti, d = symbols('B ti d') assert limit((B*ti*vi - sqrt(m)*sqrt(-2*B*d*vi + m*(vi)**2) + m*vi)/(B*vi), B, 0) == (d + ti*vi)/vi def test_issue_19154(): assert limit(besseli(1, 3 *x)/(x *besseli(1, x)**3), x , oo) == 2*sqrt(3)*pi/3 assert limit(besseli(1, 3 *x)/(x *besseli(1, x)**3), x , -oo) == -2*sqrt(3)*pi/3 def test_issue_19453(): beta = Symbol("beta", positive=True) h = Symbol("h", positive=True) m = Symbol("m", positive=True) w = Symbol("omega", positive=True) g = Symbol("g", positive=True) e = exp(1) q = 3*h**2*beta*g*e**(0.5*h*beta*w) p = m**2*w**2 s = e**(h*beta*w) - 1 Z = -q/(4*p*s) - q/(2*p*s**2) - q*(e**(h*beta*w) + 1)/(2*p*s**3)\ + e**(0.5*h*beta*w)/s E = -diff(log(Z), beta) assert limit(E - 0.5*h*w, beta, oo) == 0 assert limit(E.simplify() - 0.5*h*w, beta, oo) == 0 def test_issue_19739(): assert limit((-S(1)/4)**x, x, oo) == 0 def test_issue_19766(): assert limit(2**(-x)*sqrt(4**(x + 1) + 1), x, oo) == 2 def test_issue_19770(): m = Symbol('m') # the result is not 0 for non-real m assert limit(cos(m*x)/x, x, oo) == Limit(cos(m*x)/x, x, oo, dir='-') m = Symbol('m', real=True) # can be improved to give the correct result 0 assert limit(cos(m*x)/x, x, oo) == Limit(cos(m*x)/x, x, oo, dir='-') m = Symbol('m', nonzero=True) assert limit(cos(m*x), x, oo) == AccumBounds(-1, 1) assert limit(cos(m*x)/x, x, oo) == 0 def test_issue_7535(): assert limit(tan(x)/sin(tan(x)), x, pi/2) == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='+') assert limit(tan(x)/sin(tan(x)), x, pi/2, dir='-') == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='-') assert limit(tan(x)/sin(tan(x)), x, pi/2, dir='+-') == Limit(tan(x)/sin(tan(x)), x, pi/2, dir='+-') assert limit(sin(tan(x)),x,pi/2) == AccumBounds(-1, 1) assert -oo*(1/sin(-oo)) == AccumBounds(-oo, oo) assert oo*(1/sin(oo)) == AccumBounds(-oo, oo) assert oo*(1/sin(-oo)) == AccumBounds(-oo, oo) assert -oo*(1/sin(oo)) == AccumBounds(-oo, oo) def test_issue_20365(): assert limit(((x + 1)**(1/x) - E)/x, x, 0) == -E/2 def test_issue_21031(): assert limit(((1 + x)**(1/x) - (1 + 2*x)**(1/(2*x)))/asin(x), x, 0) == E/2 def test_issue_21038(): assert limit(sin(pi*x)/(3*x - 12), x, 4) == pi/3 def test_issue_20578(): expr = abs(x) * sin(1/x) assert limit(expr,x,0,'+') == 0 assert limit(expr,x,0,'-') == 0 assert limit(expr,x,0,'+-') == 0 def test_issue_21227(): f = log(x) assert f.nseries(x, logx=y) == y assert f.nseries(x, logx=-x) == -x f = log(-log(x)) assert f.nseries(x, logx=y) == log(-y) assert f.nseries(x, logx=-x) == log(x) f = log(log(x)) assert f.nseries(x, logx=y) == log(y) assert f.nseries(x, logx=-x) == log(-x) assert f.nseries(x, logx=x) == log(x) f = log(log(log(1/x))) assert f.nseries(x, logx=y) == log(log(-y)) assert f.nseries(x, logx=-y) == log(log(y)) assert f.nseries(x, logx=x) == log(log(-x)) assert f.nseries(x, logx=-x) == log(log(x)) def test_issue_21415(): exp = (x-1)*cos(1/(x-1)) assert exp.limit(x,1) == 0 assert exp.expand().limit(x,1) == 0 def test_issue_21530(): assert limit(sinh(n + 1)/sinh(n), n, oo) == E def test_issue_21550(): r = (sqrt(5) - 1)/2 assert limit((x - r)/(x**2 + x - 1), x, r) == sqrt(5)/5 def test_issue_21661(): out = limit((x**(x + 1) * (log(x) + 1) + 1) / x, x, 11) assert out == S(3138428376722)/11 + 285311670611*log(11) def test_issue_21701(): assert limit((besselj(z, x)/x**z).subs(z, 7), x, 0) == S(1)/645120 def test_issue_21721(): a = Symbol('a', real=True) I = integrate(1/(pi*(1 + (x - a)**2)), x) assert I.limit(x, oo) == S.Half def test_issue_21756(): term = (1 - exp(-2*I*pi*z))/(1 - exp(-2*I*pi*z/5)) assert term.limit(z, 0) == 5 assert re(term).limit(z, 0) == 5 def test_issue_21785(): a = Symbol('a') assert sqrt((-a**2 + x**2)/(1 - x**2)).limit(a, 1, '-') == I def test_issue_22181(): assert limit((-1)**x * 2**(-x), x, oo) == 0 def test_issue_22220(): e1 = sqrt(30)*atan(sqrt(30)*tan(x/2)/6)/30 e2 = sqrt(30)*I*(-log(sqrt(2)*tan(x/2) - 2*sqrt(15)*I/5) + +log(sqrt(2)*tan(x/2) + 2*sqrt(15)*I/5))/60 assert limit(e1, x, -pi) == -sqrt(30)*pi/60 assert limit(e2, x, -pi) == -sqrt(30)*pi/30 assert limit(e1, x, -pi, '-') == sqrt(30)*pi/60 assert limit(e2, x, -pi, '-') == 0 # test https://github.com/sympy/sympy/issues/22220#issuecomment-972727694 expr = log(x - I) - log(-x - I) expr2 = logcombine(expr, force=True) assert limit(expr, x, oo) == limit(expr2, x, oo) == I*pi # test https://github.com/sympy/sympy/issues/22220#issuecomment-1077618340 expr = expr = (-log(tan(x/2) - I) +log(tan(x/2) + I)) assert limit(expr, x, pi, '+') == 2*I*pi assert limit(expr, x, pi, '-') == 0 def test_issue_22334(): k, n = symbols('k, n', positive=True) assert limit((n+1)**k/((n+1)**(k+1) - (n)**(k+1)), n, oo) == 1/(k + 1) assert limit((n+1)**k/((n+1)**(k+1) - (n)**(k+1)).expand(), n, oo) == 1/(k + 1) assert limit((n+1)**k/(n*(-n**k + (n + 1)**k) + (n + 1)**k), n, oo) == 1/(k + 1) def test_sympyissue_22986(): assert limit(acosh(1 + 1/x)*sqrt(x), x, oo) == sqrt(2) def test_issue_23231(): f = (2**x - 2**(-x))/(2**x + 2**(-x)) assert limit(f, x, -oo) == -1 def test_issue_23596(): assert integrate(((1 + x)/x**2)*exp(-1/x), (x, 0, oo)) == oo def test_issue_23752(): expr1 = sqrt(-I*x**2 + x - 3) expr2 = sqrt(-I*x**2 + I*x - 3) assert limit(expr1, x, 0, '+') == -sqrt(3)*I assert limit(expr1, x, 0, '-') == -sqrt(3)*I assert limit(expr2, x, 0, '+') == sqrt(3)*I assert limit(expr2, x, 0, '-') == -sqrt(3)*I def test_issue_24276(): fx = log(tan(pi/2*tanh(x))).diff(x) assert fx.limit(x, oo) == 2 assert fx.simplify().limit(x, oo) == 2 assert fx.rewrite(sin).limit(x, oo) == 2 assert fx.rewrite(sin).simplify().limit(x, oo) == 2
bc6e4f0d30cd3ae172a53ec7f4348c8c8a2594faa429d3615afe45063eaf1671
from itertools import product from sympy.core.function import (Subs, count_ops, diff, expand) from sympy.core.numbers import (E, I, Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import (cosh, coth, sinh, tanh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (cos, cot, sin, tan) from sympy.functions.elementary.trigonometric import (acos, asin, atan2) from sympy.functions.elementary.trigonometric import (asec, acsc) from sympy.functions.elementary.trigonometric import (acot, atan) from sympy.integrals.integrals import integrate from sympy.matrices.dense import Matrix from sympy.simplify.simplify import simplify from sympy.simplify.trigsimp import (exptrigsimp, trigsimp) from sympy.testing.pytest import XFAIL from sympy.abc import x, y def test_trigsimp1(): x, y = symbols('x,y') assert trigsimp(1 - sin(x)**2) == cos(x)**2 assert trigsimp(1 - cos(x)**2) == sin(x)**2 assert trigsimp(sin(x)**2 + cos(x)**2) == 1 assert trigsimp(1 + tan(x)**2) == 1/cos(x)**2 assert trigsimp(1/cos(x)**2 - 1) == tan(x)**2 assert trigsimp(1/cos(x)**2 - tan(x)**2) == 1 assert trigsimp(1 + cot(x)**2) == 1/sin(x)**2 assert trigsimp(1/sin(x)**2 - 1) == 1/tan(x)**2 assert trigsimp(1/sin(x)**2 - cot(x)**2) == 1 assert trigsimp(5*cos(x)**2 + 5*sin(x)**2) == 5 assert trigsimp(5*cos(x/2)**2 + 2*sin(x/2)**2) == 3*cos(x)/2 + Rational(7, 2) assert trigsimp(sin(x)/cos(x)) == tan(x) assert trigsimp(2*tan(x)*cos(x)) == 2*sin(x) assert trigsimp(cot(x)**3*sin(x)**3) == cos(x)**3 assert trigsimp(y*tan(x)**2/sin(x)**2) == y/cos(x)**2 assert trigsimp(cot(x)/cos(x)) == 1/sin(x) assert trigsimp(sin(x + y) + sin(x - y)) == 2*sin(x)*cos(y) assert trigsimp(sin(x + y) - sin(x - y)) == 2*sin(y)*cos(x) assert trigsimp(cos(x + y) + cos(x - y)) == 2*cos(x)*cos(y) assert trigsimp(cos(x + y) - cos(x - y)) == -2*sin(x)*sin(y) assert trigsimp(tan(x + y) - tan(x)/(1 - tan(x)*tan(y))) == \ sin(y)/(-sin(y)*tan(x) + cos(y)) # -tan(y)/(tan(x)*tan(y) - 1) assert trigsimp(sinh(x + y) + sinh(x - y)) == 2*sinh(x)*cosh(y) assert trigsimp(sinh(x + y) - sinh(x - y)) == 2*sinh(y)*cosh(x) assert trigsimp(cosh(x + y) + cosh(x - y)) == 2*cosh(x)*cosh(y) assert trigsimp(cosh(x + y) - cosh(x - y)) == 2*sinh(x)*sinh(y) assert trigsimp(tanh(x + y) - tanh(x)/(1 + tanh(x)*tanh(y))) == \ sinh(y)/(sinh(y)*tanh(x) + cosh(y)) assert trigsimp(cos(0.12345)**2 + sin(0.12345)**2) == 1.0 e = 2*sin(x)**2 + 2*cos(x)**2 assert trigsimp(log(e)) == log(2) def test_trigsimp1a(): assert trigsimp(sin(2)**2*cos(3)*exp(2)/cos(2)**2) == tan(2)**2*cos(3)*exp(2) assert trigsimp(tan(2)**2*cos(3)*exp(2)*cos(2)**2) == sin(2)**2*cos(3)*exp(2) assert trigsimp(cot(2)*cos(3)*exp(2)*sin(2)) == cos(3)*exp(2)*cos(2) assert trigsimp(tan(2)*cos(3)*exp(2)/sin(2)) == cos(3)*exp(2)/cos(2) assert trigsimp(cot(2)*cos(3)*exp(2)/cos(2)) == cos(3)*exp(2)/sin(2) assert trigsimp(cot(2)*cos(3)*exp(2)*tan(2)) == cos(3)*exp(2) assert trigsimp(sinh(2)*cos(3)*exp(2)/cosh(2)) == tanh(2)*cos(3)*exp(2) assert trigsimp(tanh(2)*cos(3)*exp(2)*cosh(2)) == sinh(2)*cos(3)*exp(2) assert trigsimp(coth(2)*cos(3)*exp(2)*sinh(2)) == cosh(2)*cos(3)*exp(2) assert trigsimp(tanh(2)*cos(3)*exp(2)/sinh(2)) == cos(3)*exp(2)/cosh(2) assert trigsimp(coth(2)*cos(3)*exp(2)/cosh(2)) == cos(3)*exp(2)/sinh(2) assert trigsimp(coth(2)*cos(3)*exp(2)*tanh(2)) == cos(3)*exp(2) def test_trigsimp2(): x, y = symbols('x,y') assert trigsimp(cos(x)**2*sin(y)**2 + cos(x)**2*cos(y)**2 + sin(x)**2, recursive=True) == 1 assert trigsimp(sin(x)**2*sin(y)**2 + sin(x)**2*cos(y)**2 + cos(x)**2, recursive=True) == 1 assert trigsimp( Subs(x, x, sin(y)**2 + cos(y)**2)) == Subs(x, x, 1) def test_issue_4373(): x = Symbol("x") assert abs(trigsimp(2.0*sin(x)**2 + 2.0*cos(x)**2) - 2.0) < 1e-10 def test_trigsimp3(): x, y = symbols('x,y') assert trigsimp(sin(x)/cos(x)) == tan(x) assert trigsimp(sin(x)**2/cos(x)**2) == tan(x)**2 assert trigsimp(sin(x)**3/cos(x)**3) == tan(x)**3 assert trigsimp(sin(x)**10/cos(x)**10) == tan(x)**10 assert trigsimp(cos(x)/sin(x)) == 1/tan(x) assert trigsimp(cos(x)**2/sin(x)**2) == 1/tan(x)**2 assert trigsimp(cos(x)**10/sin(x)**10) == 1/tan(x)**10 assert trigsimp(tan(x)) == trigsimp(sin(x)/cos(x)) def test_issue_4661(): a, x, y = symbols('a x y') eq = -4*sin(x)**4 + 4*cos(x)**4 - 8*cos(x)**2 assert trigsimp(eq) == -4 n = sin(x)**6 + 4*sin(x)**4*cos(x)**2 + 5*sin(x)**2*cos(x)**4 + 2*cos(x)**6 d = -sin(x)**2 - 2*cos(x)**2 assert simplify(n/d) == -1 assert trigsimp(-2*cos(x)**2 + cos(x)**4 - sin(x)**4) == -1 eq = (- sin(x)**3/4)*cos(x) + (cos(x)**3/4)*sin(x) - sin(2*x)*cos(2*x)/8 assert trigsimp(eq) == 0 def test_issue_4494(): a, b = symbols('a b') eq = sin(a)**2*sin(b)**2 + cos(a)**2*cos(b)**2*tan(a)**2 + cos(a)**2 assert trigsimp(eq) == 1 def test_issue_5948(): a, x, y = symbols('a x y') assert trigsimp(diff(integrate(cos(x)/sin(x)**7, x), x)) == \ cos(x)/sin(x)**7 def test_issue_4775(): a, x, y = symbols('a x y') assert trigsimp(sin(x)*cos(y)+cos(x)*sin(y)) == sin(x + y) assert trigsimp(sin(x)*cos(y)+cos(x)*sin(y)+3) == sin(x + y) + 3 def test_issue_4280(): a, x, y = symbols('a x y') assert trigsimp(cos(x)**2 + cos(y)**2*sin(x)**2 + sin(y)**2*sin(x)**2) == 1 assert trigsimp(a**2*sin(x)**2 + a**2*cos(y)**2*cos(x)**2 + a**2*cos(x)**2*sin(y)**2) == a**2 assert trigsimp(a**2*cos(y)**2*sin(x)**2 + a**2*sin(y)**2*sin(x)**2) == a**2*sin(x)**2 def test_issue_3210(): eqs = (sin(2)*cos(3) + sin(3)*cos(2), -sin(2)*sin(3) + cos(2)*cos(3), sin(2)*cos(3) - sin(3)*cos(2), sin(2)*sin(3) + cos(2)*cos(3), sin(2)*sin(3) + cos(2)*cos(3) + cos(2), sinh(2)*cosh(3) + sinh(3)*cosh(2), sinh(2)*sinh(3) + cosh(2)*cosh(3), ) assert [trigsimp(e) for e in eqs] == [ sin(5), cos(5), -sin(1), cos(1), cos(1) + cos(2), sinh(5), cosh(5), ] def test_trigsimp_issues(): a, x, y = symbols('a x y') # issue 4625 - factor_terms works, too assert trigsimp(sin(x)**3 + cos(x)**2*sin(x)) == sin(x) # issue 5948 assert trigsimp(diff(integrate(cos(x)/sin(x)**3, x), x)) == \ cos(x)/sin(x)**3 assert trigsimp(diff(integrate(sin(x)/cos(x)**3, x), x)) == \ sin(x)/cos(x)**3 # check integer exponents e = sin(x)**y/cos(x)**y assert trigsimp(e) == e assert trigsimp(e.subs(y, 2)) == tan(x)**2 assert trigsimp(e.subs(x, 1)) == tan(1)**y # check for multiple patterns assert (cos(x)**2/sin(x)**2*cos(y)**2/sin(y)**2).trigsimp() == \ 1/tan(x)**2/tan(y)**2 assert trigsimp(cos(x)/sin(x)*cos(x+y)/sin(x+y)) == \ 1/(tan(x)*tan(x + y)) eq = cos(2)*(cos(3) + 1)**2/(cos(3) - 1)**2 assert trigsimp(eq) == eq.factor() # factor makes denom (-1 + cos(3))**2 assert trigsimp(cos(2)*(cos(3) + 1)**2*(cos(3) - 1)**2) == \ cos(2)*sin(3)**4 # issue 6789; this generates an expression that formerly caused # trigsimp to hang assert cot(x).equals(tan(x)) is False # nan or the unchanged expression is ok, but not sin(1) z = cos(x)**2 + sin(x)**2 - 1 z1 = tan(x)**2 - 1/cot(x)**2 n = (1 + z1/z) assert trigsimp(sin(n)) != sin(1) eq = x*(n - 1) - x*n assert trigsimp(eq) is S.NaN assert trigsimp(eq, recursive=True) is S.NaN assert trigsimp(1).is_Integer assert trigsimp(-sin(x)**4 - 2*sin(x)**2*cos(x)**2 - cos(x)**4) == -1 def test_trigsimp_issue_2515(): x = Symbol('x') assert trigsimp(x*cos(x)*tan(x)) == x*sin(x) assert trigsimp(-sin(x) + cos(x)*tan(x)) == 0 def test_trigsimp_issue_3826(): assert trigsimp(tan(2*x).expand(trig=True)) == tan(2*x) def test_trigsimp_issue_4032(): n = Symbol('n', integer=True, positive=True) assert trigsimp(2**(n/2)*cos(pi*n/4)/2 + 2**(n - 1)/2) == \ 2**(n/2)*cos(pi*n/4)/2 + 2**n/4 def test_trigsimp_issue_7761(): assert trigsimp(cosh(pi/4)) == cosh(pi/4) def test_trigsimp_noncommutative(): x, y = symbols('x,y') A, B = symbols('A,B', commutative=False) assert trigsimp(A - A*sin(x)**2) == A*cos(x)**2 assert trigsimp(A - A*cos(x)**2) == A*sin(x)**2 assert trigsimp(A*sin(x)**2 + A*cos(x)**2) == A assert trigsimp(A + A*tan(x)**2) == A/cos(x)**2 assert trigsimp(A/cos(x)**2 - A) == A*tan(x)**2 assert trigsimp(A/cos(x)**2 - A*tan(x)**2) == A assert trigsimp(A + A*cot(x)**2) == A/sin(x)**2 assert trigsimp(A/sin(x)**2 - A) == A/tan(x)**2 assert trigsimp(A/sin(x)**2 - A*cot(x)**2) == A assert trigsimp(y*A*cos(x)**2 + y*A*sin(x)**2) == y*A assert trigsimp(A*sin(x)/cos(x)) == A*tan(x) assert trigsimp(A*tan(x)*cos(x)) == A*sin(x) assert trigsimp(A*cot(x)**3*sin(x)**3) == A*cos(x)**3 assert trigsimp(y*A*tan(x)**2/sin(x)**2) == y*A/cos(x)**2 assert trigsimp(A*cot(x)/cos(x)) == A/sin(x) assert trigsimp(A*sin(x + y) + A*sin(x - y)) == 2*A*sin(x)*cos(y) assert trigsimp(A*sin(x + y) - A*sin(x - y)) == 2*A*sin(y)*cos(x) assert trigsimp(A*cos(x + y) + A*cos(x - y)) == 2*A*cos(x)*cos(y) assert trigsimp(A*cos(x + y) - A*cos(x - y)) == -2*A*sin(x)*sin(y) assert trigsimp(A*sinh(x + y) + A*sinh(x - y)) == 2*A*sinh(x)*cosh(y) assert trigsimp(A*sinh(x + y) - A*sinh(x - y)) == 2*A*sinh(y)*cosh(x) assert trigsimp(A*cosh(x + y) + A*cosh(x - y)) == 2*A*cosh(x)*cosh(y) assert trigsimp(A*cosh(x + y) - A*cosh(x - y)) == 2*A*sinh(x)*sinh(y) assert trigsimp(A*cos(0.12345)**2 + A*sin(0.12345)**2) == 1.0*A def test_hyperbolic_simp(): x, y = symbols('x,y') assert trigsimp(sinh(x)**2 + 1) == cosh(x)**2 assert trigsimp(cosh(x)**2 - 1) == sinh(x)**2 assert trigsimp(cosh(x)**2 - sinh(x)**2) == 1 assert trigsimp(1 - tanh(x)**2) == 1/cosh(x)**2 assert trigsimp(1 - 1/cosh(x)**2) == tanh(x)**2 assert trigsimp(tanh(x)**2 + 1/cosh(x)**2) == 1 assert trigsimp(coth(x)**2 - 1) == 1/sinh(x)**2 assert trigsimp(1/sinh(x)**2 + 1) == 1/tanh(x)**2 assert trigsimp(coth(x)**2 - 1/sinh(x)**2) == 1 assert trigsimp(5*cosh(x)**2 - 5*sinh(x)**2) == 5 assert trigsimp(5*cosh(x/2)**2 - 2*sinh(x/2)**2) == 3*cosh(x)/2 + Rational(7, 2) assert trigsimp(sinh(x)/cosh(x)) == tanh(x) assert trigsimp(tanh(x)) == trigsimp(sinh(x)/cosh(x)) assert trigsimp(cosh(x)/sinh(x)) == 1/tanh(x) assert trigsimp(2*tanh(x)*cosh(x)) == 2*sinh(x) assert trigsimp(coth(x)**3*sinh(x)**3) == cosh(x)**3 assert trigsimp(y*tanh(x)**2/sinh(x)**2) == y/cosh(x)**2 assert trigsimp(coth(x)/cosh(x)) == 1/sinh(x) for a in (pi/6*I, pi/4*I, pi/3*I): assert trigsimp(sinh(a)*cosh(x) + cosh(a)*sinh(x)) == sinh(x + a) assert trigsimp(-sinh(a)*cosh(x) + cosh(a)*sinh(x)) == sinh(x - a) e = 2*cosh(x)**2 - 2*sinh(x)**2 assert trigsimp(log(e)) == log(2) # issue 19535: assert trigsimp(sqrt(cosh(x)**2 - 1)) == sqrt(sinh(x)**2) assert trigsimp(cosh(x)**2*cosh(y)**2 - cosh(x)**2*sinh(y)**2 - sinh(x)**2, recursive=True) == 1 assert trigsimp(sinh(x)**2*sinh(y)**2 - sinh(x)**2*cosh(y)**2 + cosh(x)**2, recursive=True) == 1 assert abs(trigsimp(2.0*cosh(x)**2 - 2.0*sinh(x)**2) - 2.0) < 1e-10 assert trigsimp(sinh(x)**2/cosh(x)**2) == tanh(x)**2 assert trigsimp(sinh(x)**3/cosh(x)**3) == tanh(x)**3 assert trigsimp(sinh(x)**10/cosh(x)**10) == tanh(x)**10 assert trigsimp(cosh(x)**3/sinh(x)**3) == 1/tanh(x)**3 assert trigsimp(cosh(x)/sinh(x)) == 1/tanh(x) assert trigsimp(cosh(x)**2/sinh(x)**2) == 1/tanh(x)**2 assert trigsimp(cosh(x)**10/sinh(x)**10) == 1/tanh(x)**10 assert trigsimp(x*cosh(x)*tanh(x)) == x*sinh(x) assert trigsimp(-sinh(x) + cosh(x)*tanh(x)) == 0 assert tan(x) != 1/cot(x) # cot doesn't auto-simplify assert trigsimp(tan(x) - 1/cot(x)) == 0 assert trigsimp(3*tanh(x)**7 - 2/coth(x)**7) == tanh(x)**7 def test_trigsimp_groebner(): from sympy.simplify.trigsimp import trigsimp_groebner c = cos(x) s = sin(x) ex = (4*s*c + 12*s + 5*c**3 + 21*c**2 + 23*c + 15)/( -s*c**2 + 2*s*c + 15*s + 7*c**3 + 31*c**2 + 37*c + 21) resnum = (5*s - 5*c + 1) resdenom = (8*s - 6*c) results = [resnum/resdenom, (-resnum)/(-resdenom)] assert trigsimp_groebner(ex) in results assert trigsimp_groebner(s/c, hints=[tan]) == tan(x) assert trigsimp_groebner(c*s) == c*s assert trigsimp((-s + 1)/c + c/(-s + 1), method='groebner') == 2/c assert trigsimp((-s + 1)/c + c/(-s + 1), method='groebner', polynomial=True) == 2/c # Test quick=False works assert trigsimp_groebner(ex, hints=[2]) in results assert trigsimp_groebner(ex, hints=[int(2)]) in results # test "I" assert trigsimp_groebner(sin(I*x)/cos(I*x), hints=[tanh]) == I*tanh(x) # test hyperbolic / sums assert trigsimp_groebner((tanh(x)+tanh(y))/(1+tanh(x)*tanh(y)), hints=[(tanh, x, y)]) == tanh(x + y) def test_issue_2827_trigsimp_methods(): measure1 = lambda expr: len(str(expr)) measure2 = lambda expr: -count_ops(expr) # Return the most complicated result expr = (x + 1)/(x + sin(x)**2 + cos(x)**2) ans = Matrix([1]) M = Matrix([expr]) assert trigsimp(M, method='fu', measure=measure1) == ans assert trigsimp(M, method='fu', measure=measure2) != ans # all methods should work with Basic expressions even if they # aren't Expr M = Matrix.eye(1) assert all(trigsimp(M, method=m) == M for m in 'fu matching groebner old'.split()) # watch for E in exptrigsimp, not only exp() eq = 1/sqrt(E) + E assert exptrigsimp(eq) == eq def test_issue_15129_trigsimp_methods(): t1 = Matrix([sin(Rational(1, 50)), cos(Rational(1, 50)), 0]) t2 = Matrix([sin(Rational(1, 25)), cos(Rational(1, 25)), 0]) t3 = Matrix([cos(Rational(1, 25)), sin(Rational(1, 25)), 0]) r1 = t1.dot(t2) r2 = t1.dot(t3) assert trigsimp(r1) == cos(Rational(1, 50)) assert trigsimp(r2) == sin(Rational(3, 50)) def test_exptrigsimp(): def valid(a, b): from sympy.core.random import verify_numerically as tn if not (tn(a, b) and a == b): return False return True assert exptrigsimp(exp(x) + exp(-x)) == 2*cosh(x) assert exptrigsimp(exp(x) - exp(-x)) == 2*sinh(x) assert exptrigsimp((2*exp(x)-2*exp(-x))/(exp(x)+exp(-x))) == 2*tanh(x) assert exptrigsimp((2*exp(2*x)-2)/(exp(2*x)+1)) == 2*tanh(x) e = [cos(x) + I*sin(x), cos(x) - I*sin(x), cosh(x) - sinh(x), cosh(x) + sinh(x)] ok = [exp(I*x), exp(-I*x), exp(-x), exp(x)] assert all(valid(i, j) for i, j in zip( [exptrigsimp(ei) for ei in e], ok)) ue = [cos(x) + sin(x), cos(x) - sin(x), cosh(x) + I*sinh(x), cosh(x) - I*sinh(x)] assert [exptrigsimp(ei) == ei for ei in ue] res = [] ok = [y*tanh(1), 1/(y*tanh(1)), I*y*tan(1), -I/(y*tan(1)), y*tanh(x), 1/(y*tanh(x)), I*y*tan(x), -I/(y*tan(x)), y*tanh(1 + I), 1/(y*tanh(1 + I))] for a in (1, I, x, I*x, 1 + I): w = exp(a) eq = y*(w - 1/w)/(w + 1/w) res.append(simplify(eq)) res.append(simplify(1/eq)) assert all(valid(i, j) for i, j in zip(res, ok)) for a in range(1, 3): w = exp(a) e = w + 1/w s = simplify(e) assert s == exptrigsimp(e) assert valid(s, 2*cosh(a)) e = w - 1/w s = simplify(e) assert s == exptrigsimp(e) assert valid(s, 2*sinh(a)) def test_exptrigsimp_noncommutative(): a,b = symbols('a b', commutative=False) x = Symbol('x', commutative=True) assert exp(a + x) == exptrigsimp(exp(a)*exp(x)) p = exp(a)*exp(b) - exp(b)*exp(a) assert p == exptrigsimp(p) != 0 def test_powsimp_on_numbers(): assert 2**(Rational(1, 3) - 2) == 2**Rational(1, 3)/4 @XFAIL def test_issue_6811_fail(): # from doc/src/modules/physics/mechanics/examples.rst, the current `eq` # at Line 576 (in different variables) was formerly the equivalent and # shorter expression given below...it would be nice to get the short one # back again xp, y, x, z = symbols('xp, y, x, z') eq = 4*(-19*sin(x)*y + 5*sin(3*x)*y + 15*cos(2*x)*z - 21*z)*xp/(9*cos(x) - 5*cos(3*x)) assert trigsimp(eq) == -2*(2*cos(x)*tan(x)*y + 3*z)*xp/cos(x) def test_Piecewise(): e1 = x*(x + y) - y*(x + y) e2 = sin(x)**2 + cos(x)**2 e3 = expand((x + y)*y/x) # s1 = simplify(e1) s2 = simplify(e2) # s3 = simplify(e3) # trigsimp tries not to touch non-trig containing args assert trigsimp(Piecewise((e1, e3 < e2), (e3, True))) == \ Piecewise((e1, e3 < s2), (e3, True)) def test_issue_21594(): assert simplify(exp(Rational(1,2)) + exp(Rational(-1,2))) == cosh(S.Half)*2 def test_trigsimp_old(): x, y = symbols('x,y') assert trigsimp(1 - sin(x)**2, old=True) == cos(x)**2 assert trigsimp(1 - cos(x)**2, old=True) == sin(x)**2 assert trigsimp(sin(x)**2 + cos(x)**2, old=True) == 1 assert trigsimp(1 + tan(x)**2, old=True) == 1/cos(x)**2 assert trigsimp(1/cos(x)**2 - 1, old=True) == tan(x)**2 assert trigsimp(1/cos(x)**2 - tan(x)**2, old=True) == 1 assert trigsimp(1 + cot(x)**2, old=True) == 1/sin(x)**2 assert trigsimp(1/sin(x)**2 - cot(x)**2, old=True) == 1 assert trigsimp(5*cos(x)**2 + 5*sin(x)**2, old=True) == 5 assert trigsimp(sin(x)/cos(x), old=True) == tan(x) assert trigsimp(2*tan(x)*cos(x), old=True) == 2*sin(x) assert trigsimp(cot(x)**3*sin(x)**3, old=True) == cos(x)**3 assert trigsimp(y*tan(x)**2/sin(x)**2, old=True) == y/cos(x)**2 assert trigsimp(cot(x)/cos(x), old=True) == 1/sin(x) assert trigsimp(sin(x + y) + sin(x - y), old=True) == 2*sin(x)*cos(y) assert trigsimp(sin(x + y) - sin(x - y), old=True) == 2*sin(y)*cos(x) assert trigsimp(cos(x + y) + cos(x - y), old=True) == 2*cos(x)*cos(y) assert trigsimp(cos(x + y) - cos(x - y), old=True) == -2*sin(x)*sin(y) assert trigsimp(sinh(x + y) + sinh(x - y), old=True) == 2*sinh(x)*cosh(y) assert trigsimp(sinh(x + y) - sinh(x - y), old=True) == 2*sinh(y)*cosh(x) assert trigsimp(cosh(x + y) + cosh(x - y), old=True) == 2*cosh(x)*cosh(y) assert trigsimp(cosh(x + y) - cosh(x - y), old=True) == 2*sinh(x)*sinh(y) assert trigsimp(cos(0.12345)**2 + sin(0.12345)**2, old=True) == 1.0 assert trigsimp(sin(x)/cos(x), old=True, method='combined') == tan(x) assert trigsimp(sin(x)/cos(x), old=True, method='groebner') == sin(x)/cos(x) assert trigsimp(sin(x)/cos(x), old=True, method='groebner', hints=[tan]) == tan(x) assert trigsimp(1-sin(sin(x)**2+cos(x)**2)**2, old=True, deep=True) == cos(1)**2 def test_trigsimp_inverse(): alpha = symbols('alpha') s, c = sin(alpha), cos(alpha) for finv in [asin, acos, asec, acsc, atan, acot]: f = finv.inverse(None) assert alpha == trigsimp(finv(f(alpha)), inverse=True) # test atan2(cos, sin), atan2(sin, cos), etc... for a, b in [[c, s], [s, c]]: for i, j in product([-1, 1], repeat=2): angle = atan2(i*b, j*a) angle_inverted = trigsimp(angle, inverse=True) assert angle_inverted != angle # assures simplification happened assert sin(angle_inverted) == trigsimp(sin(angle)) assert cos(angle_inverted) == trigsimp(cos(angle))
93adeb8130dd8cdbe34b0e017f82e493628807ec5eb0e4fd3f1569bd57a78b29
from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.expr import unchanged from sympy.core.function import (count_ops, diff, expand, expand_multinomial, Function, Derivative) from sympy.core.mul import Mul, _keep_coeff from sympy.core import GoldenRatio from sympy.core.numbers import (E, Float, I, oo, pi, Rational, zoo) from sympy.core.relational import (Eq, Lt, Gt, Ge, Le) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import (binomial, factorial) from sympy.functions.elementary.complexes import (Abs, sign) from sympy.functions.elementary.exponential import (exp, exp_polar, log) from sympy.functions.elementary.hyperbolic import (cosh, csch, sinh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (acos, asin, atan, cos, sin, sinc, tan) from sympy.functions.special.error_functions import erf from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import hyper from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.geometry.polygon import rad from sympy.integrals.integrals import (Integral, integrate) from sympy.logic.boolalg import (And, Or) from sympy.matrices.dense import (Matrix, eye) from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.polys.polytools import (factor, Poly) from sympy.simplify.simplify import (besselsimp, hypersimp, inversecombine, logcombine, nsimplify, nthroot, posify, separatevars, signsimp, simplify) from sympy.solvers.solvers import solve from sympy.testing.pytest import XFAIL, slow, _both_exp_pow from sympy.abc import x, y, z, t, a, b, c, d, e, f, g, h, i, n def test_issue_7263(): assert abs((simplify(30.8**2 - 82.5**2 * sin(rad(11.6))**2)).evalf() - \ 673.447451402970) < 1e-12 def test_factorial_simplify(): # There are more tests in test_factorials.py. x = Symbol('x') assert simplify(factorial(x)/x) == gamma(x) assert simplify(factorial(factorial(x))) == factorial(factorial(x)) def test_simplify_expr(): x, y, z, k, n, m, w, s, A = symbols('x,y,z,k,n,m,w,s,A') f = Function('f') assert all(simplify(tmp) == tmp for tmp in [I, E, oo, x, -x, -oo, -E, -I]) e = 1/x + 1/y assert e != (x + y)/(x*y) assert simplify(e) == (x + y)/(x*y) e = A**2*s**4/(4*pi*k*m**3) assert simplify(e) == e e = (4 + 4*x - 2*(2 + 2*x))/(2 + 2*x) assert simplify(e) == 0 e = (-4*x*y**2 - 2*y**3 - 2*x**2*y)/(x + y)**2 assert simplify(e) == -2*y e = -x - y - (x + y)**(-1)*y**2 + (x + y)**(-1)*x**2 assert simplify(e) == -2*y e = (x + x*y)/x assert simplify(e) == 1 + y e = (f(x) + y*f(x))/f(x) assert simplify(e) == 1 + y e = (2 * (1/n - cos(n * pi)/n))/pi assert simplify(e) == (-cos(pi*n) + 1)/(pi*n)*2 e = integrate(1/(x**3 + 1), x).diff(x) assert simplify(e) == 1/(x**3 + 1) e = integrate(x/(x**2 + 3*x + 1), x).diff(x) assert simplify(e) == x/(x**2 + 3*x + 1) f = Symbol('f') A = Matrix([[2*k - m*w**2, -k], [-k, k - m*w**2]]).inv() assert simplify((A*Matrix([0, f]))[1] - (-f*(2*k - m*w**2)/(k**2 - (k - m*w**2)*(2*k - m*w**2)))) == 0 f = -x + y/(z + t) + z*x/(z + t) + z*a/(z + t) + t*x/(z + t) assert simplify(f) == (y + a*z)/(z + t) # issue 10347 expr = -x*(y**2 - 1)*(2*y**2*(x**2 - 1)/(a*(x**2 - y**2)**2) + (x**2 - 1) /(a*(x**2 - y**2)))/(a*(x**2 - y**2)) + x*(-2*x**2*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(a*(x**2 - y**2)**2) - x**2*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(a*(x**2 - 1)*(x**2 - y**2)) + (x**2*sqrt((-x**2 + 1)* (y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(x**2 - 1) + sqrt( (-x**2 + 1)*(y**2 - 1))*(x*(-x*y**2 + x)/sqrt(-x**2*y**2 + x**2 + y**2 - 1) + sqrt(-x**2*y**2 + x**2 + y**2 - 1))*sin(z))/(a*sqrt((-x**2 + 1)*( y**2 - 1))*(x**2 - y**2)))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(a* (x**2 - y**2)) + x*(-2*x**2*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a* (x**2 - y**2)**2) - x**2*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a* (x**2 - 1)*(x**2 - y**2)) + (x**2*sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2 *y**2 + x**2 + y**2 - 1)*cos(z)/(x**2 - 1) + x*sqrt((-x**2 + 1)*(y**2 - 1))*(-x*y**2 + x)*cos(z)/sqrt(-x**2*y**2 + x**2 + y**2 - 1) + sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z))/(a*sqrt((-x**2 + 1)*(y**2 - 1))*(x**2 - y**2)))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos( z)/(a*(x**2 - y**2)) - y*sqrt((-x**2 + 1)*(y**2 - 1))*(-x*y*sqrt(-x**2* y**2 + x**2 + y**2 - 1)*sin(z)/(a*(x**2 - y**2)*(y**2 - 1)) + 2*x*y*sqrt( -x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(a*(x**2 - y**2)**2) + (x*y*sqrt(( -x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin(z)/(y**2 - 1) + x*sqrt((-x**2 + 1)*(y**2 - 1))*(-x**2*y + y)*sin(z)/sqrt(-x**2*y**2 + x**2 + y**2 - 1))/(a*sqrt((-x**2 + 1)*(y**2 - 1))*(x**2 - y**2)))*sin( z)/(a*(x**2 - y**2)) + y*(x**2 - 1)*(-2*x*y*(x**2 - 1)/(a*(x**2 - y**2) **2) + 2*x*y/(a*(x**2 - y**2)))/(a*(x**2 - y**2)) + y*(x**2 - 1)*(y**2 - 1)*(-x*y*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a*(x**2 - y**2)*(y**2 - 1)) + 2*x*y*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(a*(x**2 - y**2) **2) + (x*y*sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)/(y**2 - 1) + x*sqrt((-x**2 + 1)*(y**2 - 1))*(-x**2*y + y)*cos( z)/sqrt(-x**2*y**2 + x**2 + y**2 - 1))/(a*sqrt((-x**2 + 1)*(y**2 - 1) )*(x**2 - y**2)))*cos(z)/(a*sqrt((-x**2 + 1)*(y**2 - 1))*(x**2 - y**2) ) - x*sqrt((-x**2 + 1)*(y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*sin( z)**2/(a**2*(x**2 - 1)*(x**2 - y**2)*(y**2 - 1)) - x*sqrt((-x**2 + 1)*( y**2 - 1))*sqrt(-x**2*y**2 + x**2 + y**2 - 1)*cos(z)**2/(a**2*(x**2 - 1)*( x**2 - y**2)*(y**2 - 1)) assert simplify(expr) == 2*x/(a**2*(x**2 - y**2)) #issue 17631 assert simplify('((-1/2)*Boole(True)*Boole(False)-1)*Boole(True)') == \ Mul(sympify('(2 + Boole(True)*Boole(False))'), sympify('-Boole(True)/2')) A, B = symbols('A,B', commutative=False) assert simplify(A*B - B*A) == A*B - B*A assert simplify(A/(1 + y/x)) == x*A/(x + y) assert simplify(A*(1/x + 1/y)) == A/x + A/y #(x + y)*A/(x*y) assert simplify(log(2) + log(3)) == log(6) assert simplify(log(2*x) - log(2)) == log(x) assert simplify(hyper([], [], x)) == exp(x) def test_issue_3557(): f_1 = x*a + y*b + z*c - 1 f_2 = x*d + y*e + z*f - 1 f_3 = x*g + y*h + z*i - 1 solutions = solve([f_1, f_2, f_3], x, y, z, simplify=False) assert simplify(solutions[y]) == \ (a*i + c*d + f*g - a*f - c*g - d*i)/ \ (a*e*i + b*f*g + c*d*h - a*f*h - b*d*i - c*e*g) def test_simplify_other(): assert simplify(sin(x)**2 + cos(x)**2) == 1 assert simplify(gamma(x + 1)/gamma(x)) == x assert simplify(sin(x)**2 + cos(x)**2 + factorial(x)/gamma(x)) == 1 + x assert simplify( Eq(sin(x)**2 + cos(x)**2, factorial(x)/gamma(x))) == Eq(x, 1) nc = symbols('nc', commutative=False) assert simplify(x + x*nc) == x*(1 + nc) # issue 6123 # f = exp(-I*(k*sqrt(t) + x/(2*sqrt(t)))**2) # ans = integrate(f, (k, -oo, oo), conds='none') ans = I*(-pi*x*exp(I*pi*Rational(-3, 4) + I*x**2/(4*t))*erf(x*exp(I*pi*Rational(-3, 4))/ (2*sqrt(t)))/(2*sqrt(t)) + pi*x*exp(I*pi*Rational(-3, 4) + I*x**2/(4*t))/ (2*sqrt(t)))*exp(-I*x**2/(4*t))/(sqrt(pi)*x) - I*sqrt(pi) * \ (-erf(x*exp(I*pi/4)/(2*sqrt(t))) + 1)*exp(I*pi/4)/(2*sqrt(t)) assert simplify(ans) == -(-1)**Rational(3, 4)*sqrt(pi)/sqrt(t) # issue 6370 assert simplify(2**(2 + x)/4) == 2**x @_both_exp_pow def test_simplify_complex(): cosAsExp = cos(x)._eval_rewrite_as_exp(x) tanAsExp = tan(x)._eval_rewrite_as_exp(x) assert simplify(cosAsExp*tanAsExp) == sin(x) # issue 4341 # issue 10124 assert simplify(exp(Matrix([[0, -1], [1, 0]]))) == Matrix([[cos(1), -sin(1)], [sin(1), cos(1)]]) def test_simplify_ratio(): # roots of x**3-3*x+5 roots = ['(1/2 - sqrt(3)*I/2)*(sqrt(21)/2 + 5/2)**(1/3) + 1/((1/2 - ' 'sqrt(3)*I/2)*(sqrt(21)/2 + 5/2)**(1/3))', '1/((1/2 + sqrt(3)*I/2)*(sqrt(21)/2 + 5/2)**(1/3)) + ' '(1/2 + sqrt(3)*I/2)*(sqrt(21)/2 + 5/2)**(1/3)', '-(sqrt(21)/2 + 5/2)**(1/3) - 1/(sqrt(21)/2 + 5/2)**(1/3)'] for r in roots: r = S(r) assert count_ops(simplify(r, ratio=1)) <= count_ops(r) # If ratio=oo, simplify() is always applied: assert simplify(r, ratio=oo) is not r def test_simplify_measure(): measure1 = lambda expr: len(str(expr)) measure2 = lambda expr: -count_ops(expr) # Return the most complicated result expr = (x + 1)/(x + sin(x)**2 + cos(x)**2) assert measure1(simplify(expr, measure=measure1)) <= measure1(expr) assert measure2(simplify(expr, measure=measure2)) <= measure2(expr) expr2 = Eq(sin(x)**2 + cos(x)**2, 1) assert measure1(simplify(expr2, measure=measure1)) <= measure1(expr2) assert measure2(simplify(expr2, measure=measure2)) <= measure2(expr2) def test_simplify_rational(): expr = 2**x*2.**y assert simplify(expr, rational = True) == 2**(x+y) assert simplify(expr, rational = None) == 2.0**(x+y) assert simplify(expr, rational = False) == expr assert simplify('0.9 - 0.8 - 0.1', rational = True) == 0 def test_simplify_issue_1308(): assert simplify(exp(Rational(-1, 2)) + exp(Rational(-3, 2))) == \ (1 + E)*exp(Rational(-3, 2)) def test_issue_5652(): assert simplify(E + exp(-E)) == exp(-E) + E n = symbols('n', commutative=False) assert simplify(n + n**(-n)) == n + n**(-n) def test_simplify_fail1(): x = Symbol('x') y = Symbol('y') e = (x + y)**2/(-4*x*y**2 - 2*y**3 - 2*x**2*y) assert simplify(e) == 1 / (-2*y) def test_nthroot(): assert nthroot(90 + 34*sqrt(7), 3) == sqrt(7) + 3 q = 1 + sqrt(2) - 2*sqrt(3) + sqrt(6) + sqrt(7) assert nthroot(expand_multinomial(q**3), 3) == q assert nthroot(41 + 29*sqrt(2), 5) == 1 + sqrt(2) assert nthroot(-41 - 29*sqrt(2), 5) == -1 - sqrt(2) expr = 1320*sqrt(10) + 4216 + 2576*sqrt(6) + 1640*sqrt(15) assert nthroot(expr, 5) == 1 + sqrt(6) + sqrt(15) q = 1 + sqrt(2) + sqrt(3) + sqrt(5) assert expand_multinomial(nthroot(expand_multinomial(q**5), 5)) == q q = 1 + sqrt(2) + 7*sqrt(6) + 2*sqrt(10) assert nthroot(expand_multinomial(q**5), 5, 8) == q q = 1 + sqrt(2) - 2*sqrt(3) + 1171*sqrt(6) assert nthroot(expand_multinomial(q**3), 3) == q assert nthroot(expand_multinomial(q**6), 6) == q def test_nthroot1(): q = 1 + sqrt(2) + sqrt(3) + S.One/10**20 p = expand_multinomial(q**5) assert nthroot(p, 5) == q q = 1 + sqrt(2) + sqrt(3) + S.One/10**30 p = expand_multinomial(q**5) assert nthroot(p, 5) == q @_both_exp_pow def test_separatevars(): x, y, z, n = symbols('x,y,z,n') assert separatevars(2*n*x*z + 2*x*y*z) == 2*x*z*(n + y) assert separatevars(x*z + x*y*z) == x*z*(1 + y) assert separatevars(pi*x*z + pi*x*y*z) == pi*x*z*(1 + y) assert separatevars(x*y**2*sin(x) + x*sin(x)*sin(y)) == \ x*(sin(y) + y**2)*sin(x) assert separatevars(x*exp(x + y) + x*exp(x)) == x*(1 + exp(y))*exp(x) assert separatevars((x*(y + 1))**z).is_Pow # != x**z*(1 + y)**z assert separatevars(1 + x + y + x*y) == (x + 1)*(y + 1) assert separatevars(y/pi*exp(-(z - x)/cos(n))) == \ y*exp(x/cos(n))*exp(-z/cos(n))/pi assert separatevars((x + y)*(x - y) + y**2 + 2*x + 1) == (x + 1)**2 # issue 4858 p = Symbol('p', positive=True) assert separatevars(sqrt(p**2 + x*p**2)) == p*sqrt(1 + x) assert separatevars(sqrt(y*(p**2 + x*p**2))) == p*sqrt(y*(1 + x)) assert separatevars(sqrt(y*(p**2 + x*p**2)), force=True) == \ p*sqrt(y)*sqrt(1 + x) # issue 4865 assert separatevars(sqrt(x*y)).is_Pow assert separatevars(sqrt(x*y), force=True) == sqrt(x)*sqrt(y) # issue 4957 # any type sequence for symbols is fine assert separatevars(((2*x + 2)*y), dict=True, symbols=()) == \ {'coeff': 1, x: 2*x + 2, y: y} # separable assert separatevars(((2*x + 2)*y), dict=True, symbols=[x]) == \ {'coeff': y, x: 2*x + 2} assert separatevars(((2*x + 2)*y), dict=True, symbols=[]) == \ {'coeff': 1, x: 2*x + 2, y: y} assert separatevars(((2*x + 2)*y), dict=True) == \ {'coeff': 1, x: 2*x + 2, y: y} assert separatevars(((2*x + 2)*y), dict=True, symbols=None) == \ {'coeff': y*(2*x + 2)} # not separable assert separatevars(3, dict=True) is None assert separatevars(2*x + y, dict=True, symbols=()) is None assert separatevars(2*x + y, dict=True) is None assert separatevars(2*x + y, dict=True, symbols=None) == {'coeff': 2*x + y} # issue 4808 n, m = symbols('n,m', commutative=False) assert separatevars(m + n*m) == (1 + n)*m assert separatevars(x + x*n) == x*(1 + n) # issue 4910 f = Function('f') assert separatevars(f(x) + x*f(x)) == f(x) + x*f(x) # a noncommutable object present eq = x*(1 + hyper((), (), y*z)) assert separatevars(eq) == eq s = separatevars(abs(x*y)) assert s == abs(x)*abs(y) and s.is_Mul z = cos(1)**2 + sin(1)**2 - 1 a = abs(x*z) s = separatevars(a) assert not a.is_Mul and s.is_Mul and s == abs(x)*abs(z) s = separatevars(abs(x*y*z)) assert s == abs(x)*abs(y)*abs(z) # abs(x+y)/abs(z) would be better but we test this here to # see that it doesn't raise assert separatevars(abs((x+y)/z)) == abs((x+y)/z) def test_separatevars_advanced_factor(): x, y, z = symbols('x,y,z') assert separatevars(1 + log(x)*log(y) + log(x) + log(y)) == \ (log(x) + 1)*(log(y) + 1) assert separatevars(1 + x - log(z) - x*log(z) - exp(y)*log(z) - x*exp(y)*log(z) + x*exp(y) + exp(y)) == \ -((x + 1)*(log(z) - 1)*(exp(y) + 1)) x, y = symbols('x,y', positive=True) assert separatevars(1 + log(x**log(y)) + log(x*y)) == \ (log(x) + 1)*(log(y) + 1) def test_hypersimp(): n, k = symbols('n,k', integer=True) assert hypersimp(factorial(k), k) == k + 1 assert hypersimp(factorial(k**2), k) is None assert hypersimp(1/factorial(k), k) == 1/(k + 1) assert hypersimp(2**k/factorial(k)**2, k) == 2/(k + 1)**2 assert hypersimp(binomial(n, k), k) == (n - k)/(k + 1) assert hypersimp(binomial(n + 1, k), k) == (n - k + 1)/(k + 1) term = (4*k + 1)*factorial(k)/factorial(2*k + 1) assert hypersimp(term, k) == S.Half*((4*k + 5)/(3 + 14*k + 8*k**2)) term = 1/((2*k - 1)*factorial(2*k + 1)) assert hypersimp(term, k) == (k - S.Half)/((k + 1)*(2*k + 1)*(2*k + 3)) term = binomial(n, k)*(-1)**k/factorial(k) assert hypersimp(term, k) == (k - n)/(k + 1)**2 def test_nsimplify(): x = Symbol("x") assert nsimplify(0) == 0 assert nsimplify(-1) == -1 assert nsimplify(1) == 1 assert nsimplify(1 + x) == 1 + x assert nsimplify(2.7) == Rational(27, 10) assert nsimplify(1 - GoldenRatio) == (1 - sqrt(5))/2 assert nsimplify((1 + sqrt(5))/4, [GoldenRatio]) == GoldenRatio/2 assert nsimplify(2/GoldenRatio, [GoldenRatio]) == 2*GoldenRatio - 2 assert nsimplify(exp(pi*I*Rational(5, 3), evaluate=False)) == \ sympify('1/2 - sqrt(3)*I/2') assert nsimplify(sin(pi*Rational(3, 5), evaluate=False)) == \ sympify('sqrt(sqrt(5)/8 + 5/8)') assert nsimplify(sqrt(atan('1', evaluate=False))*(2 + I), [pi]) == \ sqrt(pi) + sqrt(pi)/2*I assert nsimplify(2 + exp(2*atan('1/4')*I)) == sympify('49/17 + 8*I/17') assert nsimplify(pi, tolerance=0.01) == Rational(22, 7) assert nsimplify(pi, tolerance=0.001) == Rational(355, 113) assert nsimplify(0.33333, tolerance=1e-4) == Rational(1, 3) assert nsimplify(2.0**(1/3.), tolerance=0.001) == Rational(635, 504) assert nsimplify(2.0**(1/3.), tolerance=0.001, full=True) == \ 2**Rational(1, 3) assert nsimplify(x + .5, rational=True) == S.Half + x assert nsimplify(1/.3 + x, rational=True) == Rational(10, 3) + x assert nsimplify(log(3).n(), rational=True) == \ sympify('109861228866811/100000000000000') assert nsimplify(Float(0.272198261287950), [pi, log(2)]) == pi*log(2)/8 assert nsimplify(Float(0.272198261287950).n(3), [pi, log(2)]) == \ -pi/4 - log(2) + Rational(7, 4) assert nsimplify(x/7.0) == x/7 assert nsimplify(pi/1e2) == pi/100 assert nsimplify(pi/1e2, rational=False) == pi/100.0 assert nsimplify(pi/1e-7) == 10000000*pi assert not nsimplify( factor(-3.0*z**2*(z**2)**(-2.5) + 3*(z**2)**(-1.5))).atoms(Float) e = x**0.0 assert e.is_Pow and nsimplify(x**0.0) == 1 assert nsimplify(3.333333, tolerance=0.1, rational=True) == Rational(10, 3) assert nsimplify(3.333333, tolerance=0.01, rational=True) == Rational(10, 3) assert nsimplify(3.666666, tolerance=0.1, rational=True) == Rational(11, 3) assert nsimplify(3.666666, tolerance=0.01, rational=True) == Rational(11, 3) assert nsimplify(33, tolerance=10, rational=True) == Rational(33) assert nsimplify(33.33, tolerance=10, rational=True) == Rational(30) assert nsimplify(37.76, tolerance=10, rational=True) == Rational(40) assert nsimplify(-203.1) == Rational(-2031, 10) assert nsimplify(.2, tolerance=0) == Rational(1, 5) assert nsimplify(-.2, tolerance=0) == Rational(-1, 5) assert nsimplify(.2222, tolerance=0) == Rational(1111, 5000) assert nsimplify(-.2222, tolerance=0) == Rational(-1111, 5000) # issue 7211, PR 4112 assert nsimplify(S(2e-8)) == Rational(1, 50000000) # issue 7322 direct test assert nsimplify(1e-42, rational=True) != 0 # issue 10336 inf = Float('inf') infs = (-oo, oo, inf, -inf) for zi in infs: ans = sign(zi)*oo assert nsimplify(zi) == ans assert nsimplify(zi + x) == x + ans assert nsimplify(0.33333333, rational=True, rational_conversion='exact') == Rational(0.33333333) # Make sure nsimplify on expressions uses full precision assert nsimplify(pi.evalf(100)*x, rational_conversion='exact').evalf(100) == pi.evalf(100)*x def test_issue_9448(): tmp = sympify("1/(1 - (-1)**(2/3) - (-1)**(1/3)) + 1/(1 + (-1)**(2/3) + (-1)**(1/3))") assert nsimplify(tmp) == S.Half def test_extract_minus_sign(): x = Symbol("x") y = Symbol("y") a = Symbol("a") b = Symbol("b") assert simplify(-x/-y) == x/y assert simplify(-x/y) == -x/y assert simplify(x/y) == x/y assert simplify(x/-y) == -x/y assert simplify(-x/0) == zoo*x assert simplify(Rational(-5, 0)) is zoo assert simplify(-a*x/(-y - b)) == a*x/(b + y) def test_diff(): x = Symbol("x") y = Symbol("y") f = Function("f") g = Function("g") assert simplify(g(x).diff(x)*f(x).diff(x) - f(x).diff(x)*g(x).diff(x)) == 0 assert simplify(2*f(x)*f(x).diff(x) - diff(f(x)**2, x)) == 0 assert simplify(diff(1/f(x), x) + f(x).diff(x)/f(x)**2) == 0 assert simplify(f(x).diff(x, y) - f(x).diff(y, x)) == 0 def test_logcombine_1(): x, y = symbols("x,y") a = Symbol("a") z, w = symbols("z,w", positive=True) b = Symbol("b", real=True) assert logcombine(log(x) + 2*log(y)) == log(x) + 2*log(y) assert logcombine(log(x) + 2*log(y), force=True) == log(x*y**2) assert logcombine(a*log(w) + log(z)) == a*log(w) + log(z) assert logcombine(b*log(z) + b*log(x)) == log(z**b) + b*log(x) assert logcombine(b*log(z) - log(w)) == log(z**b/w) assert logcombine(log(x)*log(z)) == log(x)*log(z) assert logcombine(log(w)*log(x)) == log(w)*log(x) assert logcombine(cos(-2*log(z) + b*log(w))) in [cos(log(w**b/z**2)), cos(log(z**2/w**b))] assert logcombine(log(log(x) - log(y)) - log(z), force=True) == \ log(log(x/y)/z) assert logcombine((2 + I)*log(x), force=True) == (2 + I)*log(x) assert logcombine((x**2 + log(x) - log(y))/(x*y), force=True) == \ (x**2 + log(x/y))/(x*y) # the following could also give log(z*x**log(y**2)), what we # are testing is that a canonical result is obtained assert logcombine(log(x)*2*log(y) + log(z), force=True) == \ log(z*y**log(x**2)) assert logcombine((x*y + sqrt(x**4 + y**4) + log(x) - log(y))/(pi*x**Rational(2, 3)* sqrt(y)**3), force=True) == ( x*y + sqrt(x**4 + y**4) + log(x/y))/(pi*x**Rational(2, 3)*y**Rational(3, 2)) assert logcombine(gamma(-log(x/y))*acos(-log(x/y)), force=True) == \ acos(-log(x/y))*gamma(-log(x/y)) assert logcombine(2*log(z)*log(w)*log(x) + log(z) + log(w)) == \ log(z**log(w**2))*log(x) + log(w*z) assert logcombine(3*log(w) + 3*log(z)) == log(w**3*z**3) assert logcombine(x*(y + 1) + log(2) + log(3)) == x*(y + 1) + log(6) assert logcombine((x + y)*log(w) + (-x - y)*log(3)) == (x + y)*log(w/3) # a single unknown can combine assert logcombine(log(x) + log(2)) == log(2*x) eq = log(abs(x)) + log(abs(y)) assert logcombine(eq) == eq reps = {x: 0, y: 0} assert log(abs(x)*abs(y)).subs(reps) != eq.subs(reps) def test_logcombine_complex_coeff(): i = Integral((sin(x**2) + cos(x**3))/x, x) assert logcombine(i, force=True) == i assert logcombine(i + 2*log(x), force=True) == \ i + log(x**2) def test_issue_5950(): x, y = symbols("x,y", positive=True) assert logcombine(log(3) - log(2)) == log(Rational(3,2), evaluate=False) assert logcombine(log(x) - log(y)) == log(x/y) assert logcombine(log(Rational(3,2), evaluate=False) - log(2)) == \ log(Rational(3,4), evaluate=False) def test_posify(): x = symbols('x') assert str(posify( x + Symbol('p', positive=True) + Symbol('n', negative=True))) == '(_x + n + p, {_x: x})' eq, rep = posify(1/x) assert log(eq).expand().subs(rep) == -log(x) assert str(posify([x, 1 + x])) == '([_x, _x + 1], {_x: x})' p = symbols('p', positive=True) n = symbols('n', negative=True) orig = [x, n, p] modified, reps = posify(orig) assert str(modified) == '[_x, n, p]' assert [w.subs(reps) for w in modified] == orig assert str(Integral(posify(1/x + y)[0], (y, 1, 3)).expand()) == \ 'Integral(1/_x, (y, 1, 3)) + Integral(_y, (y, 1, 3))' assert str(Sum(posify(1/x**n)[0], (n,1,3)).expand()) == \ 'Sum(_x**(-n), (n, 1, 3))' # issue 16438 k = Symbol('k', finite=True) eq, rep = posify(k) assert eq.assumptions0 == {'positive': True, 'zero': False, 'imaginary': False, 'nonpositive': False, 'commutative': True, 'hermitian': True, 'real': True, 'nonzero': True, 'nonnegative': True, 'negative': False, 'complex': True, 'finite': True, 'infinite': False, 'extended_real':True, 'extended_negative': False, 'extended_nonnegative': True, 'extended_nonpositive': False, 'extended_nonzero': True, 'extended_positive': True} def test_issue_4194(): # simplify should call cancel f = Function('f') assert simplify((4*x + 6*f(y))/(2*x + 3*f(y))) == 2 @XFAIL def test_simplify_float_vs_integer(): # Test for issue 4473: # https://github.com/sympy/sympy/issues/4473 assert simplify(x**2.0 - x**2) == 0 assert simplify(x**2 - x**2.0) == 0 def test_as_content_primitive(): assert (x/2 + y).as_content_primitive() == (S.Half, x + 2*y) assert (x/2 + y).as_content_primitive(clear=False) == (S.One, x/2 + y) assert (y*(x/2 + y)).as_content_primitive() == (S.Half, y*(x + 2*y)) assert (y*(x/2 + y)).as_content_primitive(clear=False) == (S.One, y*(x/2 + y)) # although the _as_content_primitive methods do not alter the underlying structure, # the as_content_primitive function will touch up the expression and join # bases that would otherwise have not been joined. assert (x*(2 + 2*x)*(3*x + 3)**2).as_content_primitive() == \ (18, x*(x + 1)**3) assert (2 + 2*x + 2*y*(3 + 3*y)).as_content_primitive() == \ (2, x + 3*y*(y + 1) + 1) assert ((2 + 6*x)**2).as_content_primitive() == \ (4, (3*x + 1)**2) assert ((2 + 6*x)**(2*y)).as_content_primitive() == \ (1, (_keep_coeff(S(2), (3*x + 1)))**(2*y)) assert (5 + 10*x + 2*y*(3 + 3*y)).as_content_primitive() == \ (1, 10*x + 6*y*(y + 1) + 5) assert (5*(x*(1 + y)) + 2*x*(3 + 3*y)).as_content_primitive() == \ (11, x*(y + 1)) assert ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive() == \ (121, x**2*(y + 1)**2) assert (y**2).as_content_primitive() == \ (1, y**2) assert (S.Infinity).as_content_primitive() == (1, oo) eq = x**(2 + y) assert (eq).as_content_primitive() == (1, eq) assert (S.Half**(2 + x)).as_content_primitive() == (Rational(1, 4), 2**-x) assert (Rational(-1, 2)**(2 + x)).as_content_primitive() == \ (Rational(1, 4), (Rational(-1, 2))**x) assert (Rational(-1, 2)**(2 + x)).as_content_primitive() == \ (Rational(1, 4), Rational(-1, 2)**x) assert (4**((1 + y)/2)).as_content_primitive() == (2, 4**(y/2)) assert (3**((1 + y)/2)).as_content_primitive() == \ (1, 3**(Mul(S.Half, 1 + y, evaluate=False))) assert (5**Rational(3, 4)).as_content_primitive() == (1, 5**Rational(3, 4)) assert (5**Rational(7, 4)).as_content_primitive() == (5, 5**Rational(3, 4)) assert Add(z*Rational(5, 7), 0.5*x, y*Rational(3, 2), evaluate=False).as_content_primitive() == \ (Rational(1, 14), 7.0*x + 21*y + 10*z) assert (2**Rational(3, 4) + 2**Rational(1, 4)*sqrt(3)).as_content_primitive(radical=True) == \ (1, 2**Rational(1, 4)*(sqrt(2) + sqrt(3))) def test_signsimp(): e = x*(-x + 1) + x*(x - 1) assert signsimp(Eq(e, 0)) is S.true assert Abs(x - 1) == Abs(1 - x) assert signsimp(y - x) == y - x assert signsimp(y - x, evaluate=False) == Mul(-1, x - y, evaluate=False) def test_besselsimp(): from sympy.functions.special.bessel import (besseli, besselj, bessely) from sympy.integrals.transforms import cosine_transform assert besselsimp(exp(-I*pi*y/2)*besseli(y, z*exp_polar(I*pi/2))) == \ besselj(y, z) assert besselsimp(exp(-I*pi*a/2)*besseli(a, 2*sqrt(x)*exp_polar(I*pi/2))) == \ besselj(a, 2*sqrt(x)) assert besselsimp(sqrt(2)*sqrt(pi)*x**Rational(1, 4)*exp(I*pi/4)*exp(-I*pi*a/2) * besseli(Rational(-1, 2), sqrt(x)*exp_polar(I*pi/2)) * besseli(a, sqrt(x)*exp_polar(I*pi/2))/2) == \ besselj(a, sqrt(x)) * cos(sqrt(x)) assert besselsimp(besseli(Rational(-1, 2), z)) == \ sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z)) assert besselsimp(besseli(a, z*exp_polar(-I*pi/2))) == \ exp(-I*pi*a/2)*besselj(a, z) assert cosine_transform(1/t*sin(a/t), t, y) == \ sqrt(2)*sqrt(pi)*besselj(0, 2*sqrt(a)*sqrt(y))/2 assert besselsimp(x**2*(a*(-2*besselj(5*I, x) + besselj(-2 + 5*I, x) + besselj(2 + 5*I, x)) + b*(-2*bessely(5*I, x) + bessely(-2 + 5*I, x) + bessely(2 + 5*I, x)))/4 + x*(a*(besselj(-1 + 5*I, x)/2 - besselj(1 + 5*I, x)/2) + b*(bessely(-1 + 5*I, x)/2 - bessely(1 + 5*I, x)/2)) + (x**2 + 25)*(a*besselj(5*I, x) + b*bessely(5*I, x))) == 0 assert besselsimp(81*x**2*(a*(besselj(Rational(-5, 3), 9*x) - 2*besselj(Rational(1, 3), 9*x) + besselj(Rational(7, 3), 9*x)) + b*(bessely(Rational(-5, 3), 9*x) - 2*bessely(Rational(1, 3), 9*x) + bessely(Rational(7, 3), 9*x)))/4 + x*(a*(9*besselj(Rational(-2, 3), 9*x)/2 - 9*besselj(Rational(4, 3), 9*x)/2) + b*(9*bessely(Rational(-2, 3), 9*x)/2 - 9*bessely(Rational(4, 3), 9*x)/2)) + (81*x**2 - Rational(1, 9))*(a*besselj(Rational(1, 3), 9*x) + b*bessely(Rational(1, 3), 9*x))) == 0 assert besselsimp(besselj(a-1,x) + besselj(a+1, x) - 2*a*besselj(a, x)/x) == 0 assert besselsimp(besselj(a-1,x) + besselj(a+1, x) + besselj(a, x)) == (2*a + x)*besselj(a, x)/x assert besselsimp(x**2* besselj(a,x) + x**3*besselj(a+1, x) + besselj(a+2, x)) == \ 2*a*x*besselj(a + 1, x) + x**3*besselj(a + 1, x) - x**2*besselj(a + 2, x) + 2*x*besselj(a + 1, x) + besselj(a + 2, x) def test_Piecewise(): e1 = x*(x + y) - y*(x + y) e2 = sin(x)**2 + cos(x)**2 e3 = expand((x + y)*y/x) s1 = simplify(e1) s2 = simplify(e2) s3 = simplify(e3) assert simplify(Piecewise((e1, x < e2), (e3, True))) == \ Piecewise((s1, x < s2), (s3, True)) def test_polymorphism(): class A(Basic): def _eval_simplify(x, **kwargs): return S.One a = A(S(5), S(2)) assert simplify(a) == 1 def test_issue_from_PR1599(): n1, n2, n3, n4 = symbols('n1 n2 n3 n4', negative=True) assert simplify(I*sqrt(n1)) == -sqrt(-n1) def test_issue_6811(): eq = (x + 2*y)*(2*x + 2) assert simplify(eq) == (x + 1)*(x + 2*y)*2 # reject the 2-arg Mul -- these are a headache for test writing assert simplify(eq.expand()) == \ 2*x**2 + 4*x*y + 2*x + 4*y def test_issue_6920(): e = [cos(x) + I*sin(x), cos(x) - I*sin(x), cosh(x) - sinh(x), cosh(x) + sinh(x)] ok = [exp(I*x), exp(-I*x), exp(-x), exp(x)] # wrap in f to show that the change happens wherever ei occurs f = Function('f') assert [simplify(f(ei)).args[0] for ei in e] == ok def test_issue_7001(): from sympy.abc import r, R assert simplify(-(r*Piecewise((pi*Rational(4, 3), r <= R), (-8*pi*R**3/(3*r**3), True)) + 2*Piecewise((pi*r*Rational(4, 3), r <= R), (4*pi*R**3/(3*r**2), True)))/(4*pi*r)) == \ Piecewise((-1, r <= R), (0, True)) def test_inequality_no_auto_simplify(): # no simplify on creation but can be simplified lhs = cos(x)**2 + sin(x)**2 rhs = 2 e = Lt(lhs, rhs, evaluate=False) assert e is not S.true assert simplify(e) def test_issue_9398(): from sympy.core.numbers import Number from sympy.polys.polytools import cancel assert cancel(1e-14) != 0 assert cancel(1e-14*I) != 0 assert simplify(1e-14) != 0 assert simplify(1e-14*I) != 0 assert (I*Number(1.)*Number(10)**Number(-14)).simplify() != 0 assert cancel(1e-20) != 0 assert cancel(1e-20*I) != 0 assert simplify(1e-20) != 0 assert simplify(1e-20*I) != 0 assert cancel(1e-100) != 0 assert cancel(1e-100*I) != 0 assert simplify(1e-100) != 0 assert simplify(1e-100*I) != 0 f = Float("1e-1000") assert cancel(f) != 0 assert cancel(f*I) != 0 assert simplify(f) != 0 assert simplify(f*I) != 0 def test_issue_9324_simplify(): M = MatrixSymbol('M', 10, 10) e = M[0, 0] + M[5, 4] + 1304 assert simplify(e) == e def test_issue_9817_simplify(): # simplify on trace of substituted explicit quadratic form of matrix # expressions (a scalar) should return without errors (AttributeError) # See issue #9817 and #9190 for the original bug more discussion on this from sympy.matrices.expressions import Identity, trace v = MatrixSymbol('v', 3, 1) A = MatrixSymbol('A', 3, 3) x = Matrix([i + 1 for i in range(3)]) X = Identity(3) quadratic = v.T * A * v assert simplify((trace(quadratic.as_explicit())).xreplace({v:x, A:X})) == 14 def test_issue_13474(): x = Symbol('x') assert simplify(x + csch(sinc(1))) == x + csch(sinc(1)) @_both_exp_pow def test_simplify_function_inverse(): # "inverse" attribute does not guarantee that f(g(x)) is x # so this simplification should not happen automatically. # See issue #12140 x, y = symbols('x, y') g = Function('g') class f(Function): def inverse(self, argindex=1): return g assert simplify(f(g(x))) == f(g(x)) assert inversecombine(f(g(x))) == x assert simplify(f(g(x)), inverse=True) == x assert simplify(f(g(sin(x)**2 + cos(x)**2)), inverse=True) == 1 assert simplify(f(g(x, y)), inverse=True) == f(g(x, y)) assert unchanged(asin, sin(x)) assert simplify(asin(sin(x))) == asin(sin(x)) assert simplify(2*asin(sin(3*x)), inverse=True) == 6*x assert simplify(log(exp(x))) == log(exp(x)) assert simplify(log(exp(x)), inverse=True) == x assert simplify(exp(log(x)), inverse=True) == x assert simplify(log(exp(x), 2), inverse=True) == x/log(2) assert simplify(log(exp(x), 2, evaluate=False), inverse=True) == x/log(2) def test_clear_coefficients(): from sympy.simplify.simplify import clear_coefficients assert clear_coefficients(4*y*(6*x + 3)) == (y*(2*x + 1), 0) assert clear_coefficients(4*y*(6*x + 3) - 2) == (y*(2*x + 1), Rational(1, 6)) assert clear_coefficients(4*y*(6*x + 3) - 2, x) == (y*(2*x + 1), x/12 + Rational(1, 6)) assert clear_coefficients(sqrt(2) - 2) == (sqrt(2), 2) assert clear_coefficients(4*sqrt(2) - 2) == (sqrt(2), S.Half) assert clear_coefficients(S(3), x) == (0, x - 3) assert clear_coefficients(S.Infinity, x) == (S.Infinity, x) assert clear_coefficients(-S.Pi, x) == (S.Pi, -x) assert clear_coefficients(2 - S.Pi/3, x) == (pi, -3*x + 6) def test_nc_simplify(): from sympy.simplify.simplify import nc_simplify from sympy.matrices.expressions import MatPow, Identity from sympy.core import Pow from functools import reduce a, b, c, d = symbols('a b c d', commutative = False) x = Symbol('x') A = MatrixSymbol("A", x, x) B = MatrixSymbol("B", x, x) C = MatrixSymbol("C", x, x) D = MatrixSymbol("D", x, x) subst = {a: A, b: B, c: C, d:D} funcs = {Add: lambda x,y: x+y, Mul: lambda x,y: x*y } def _to_matrix(expr): if expr in subst: return subst[expr] if isinstance(expr, Pow): return MatPow(_to_matrix(expr.args[0]), expr.args[1]) elif isinstance(expr, (Add, Mul)): return reduce(funcs[expr.func],[_to_matrix(a) for a in expr.args]) else: return expr*Identity(x) def _check(expr, simplified, deep=True, matrix=True): assert nc_simplify(expr, deep=deep) == simplified assert expand(expr) == expand(simplified) if matrix: m_simp = _to_matrix(simplified).doit(inv_expand=False) assert nc_simplify(_to_matrix(expr), deep=deep) == m_simp _check(a*b*a*b*a*b*c*(a*b)**3*c, ((a*b)**3*c)**2) _check(a*b*(a*b)**-2*a*b, 1) _check(a**2*b*a*b*a*b*(a*b)**-1, a*(a*b)**2, matrix=False) _check(b*a*b**2*a*b**2*a*b**2, b*(a*b**2)**3) _check(a*b*a**2*b*a**2*b*a**3, (a*b*a)**3*a**2) _check(a**2*b*a**4*b*a**4*b*a**2, (a**2*b*a**2)**3) _check(a**3*b*a**4*b*a**4*b*a, a**3*(b*a**4)**3*a**-3) _check(a*b*a*b + a*b*c*x*a*b*c, (a*b)**2 + x*(a*b*c)**2) _check(a*b*a*b*c*a*b*a*b*c, ((a*b)**2*c)**2) _check(b**-1*a**-1*(a*b)**2, a*b) _check(a**-1*b*c**-1, (c*b**-1*a)**-1) expr = a**3*b*a**4*b*a**4*b*a**2*b*a**2*(b*a**2)**2*b*a**2*b*a**2 for _ in range(10): expr *= a*b _check(expr, a**3*(b*a**4)**2*(b*a**2)**6*(a*b)**10) _check((a*b*a*b)**2, (a*b*a*b)**2, deep=False) _check(a*b*(c*d)**2, a*b*(c*d)**2) expr = b**-1*(a**-1*b**-1 - a**-1*c*b**-1)**-1*a**-1 assert nc_simplify(expr) == (1-c)**-1 # commutative expressions should be returned without an error assert nc_simplify(2*x**2) == 2*x**2 def test_issue_15965(): A = Sum(z*x**y, (x, 1, a)) anew = z*Sum(x**y, (x, 1, a)) B = Integral(x*y, x) bdo = x**2*y/2 assert simplify(A + B) == anew + bdo assert simplify(A) == anew assert simplify(B) == bdo assert simplify(B, doit=False) == y*Integral(x, x) def test_issue_17137(): assert simplify(cos(x)**I) == cos(x)**I assert simplify(cos(x)**(2 + 3*I)) == cos(x)**(2 + 3*I) def test_issue_21869(): x = Symbol('x', real=True) y = Symbol('y', real=True) expr = And(Eq(x**2, 4), Le(x, y)) assert expr.simplify() == expr expr = And(Eq(x**2, 4), Eq(x, 2)) assert expr.simplify() == Eq(x, 2) expr = And(Eq(x**3, x**2), Eq(x, 1)) assert expr.simplify() == Eq(x, 1) expr = And(Eq(sin(x), x**2), Eq(x, 0)) assert expr.simplify() == Eq(x, 0) expr = And(Eq(x**3, x**2), Eq(x, 2)) assert expr.simplify() == S.false expr = And(Eq(y, x**2), Eq(x, 1)) assert expr.simplify() == And(Eq(y,1), Eq(x, 1)) expr = And(Eq(y**2, 1), Eq(y, x**2), Eq(x, 1)) assert expr.simplify() == And(Eq(y,1), Eq(x, 1)) expr = And(Eq(y**2, 4), Eq(y, 2*x**2), Eq(x, 1)) assert expr.simplify() == And(Eq(y,2), Eq(x, 1)) expr = And(Eq(y**2, 4), Eq(y, x**2), Eq(x, 1)) assert expr.simplify() == S.false def test_issue_7971_21740(): z = Integral(x, (x, 1, 1)) assert z != 0 assert simplify(z) is S.Zero assert simplify(S.Zero) is S.Zero z = simplify(Float(0)) assert z is not S.Zero and z == 0.0 @slow def test_issue_17141_slow(): # Should not give RecursionError assert simplify((2**acos(I+1)**2).rewrite('log')) == 2**((pi + 2*I*log(-1 + sqrt(1 - 2*I) + I))**2/4) def test_issue_17141(): # Check that there is no RecursionError assert simplify(x**(1 / acos(I))) == x**(2/(pi - 2*I*log(1 + sqrt(2)))) assert simplify(acos(-I)**2*acos(I)**2) == \ log(1 + sqrt(2))**4 + pi**2*log(1 + sqrt(2))**2/2 + pi**4/16 assert simplify(2**acos(I)**2) == 2**((pi - 2*I*log(1 + sqrt(2)))**2/4) p = 2**acos(I+1)**2 assert simplify(p) == p def test_simplify_kroneckerdelta(): i, j = symbols("i j") K = KroneckerDelta assert simplify(K(i, j)) == K(i, j) assert simplify(K(0, j)) == K(0, j) assert simplify(K(i, 0)) == K(i, 0) assert simplify(K(0, j).rewrite(Piecewise) * K(1, j)) == 0 assert simplify(K(1, i) + Piecewise((1, Eq(j, 2)), (0, True))) == K(1, i) + K(2, j) # issue 17214 assert simplify(K(0, j) * K(1, j)) == 0 n = Symbol('n', integer=True) assert simplify(K(0, n) * K(1, n)) == 0 M = Matrix(4, 4, lambda i, j: K(j - i, n) if i <= j else 0) assert simplify(M**2) == Matrix([[K(0, n), 0, K(1, n), 0], [0, K(0, n), 0, K(1, n)], [0, 0, K(0, n), 0], [0, 0, 0, K(0, n)]]) assert simplify(eye(1) * KroneckerDelta(0, n) * KroneckerDelta(1, n)) == Matrix([[0]]) assert simplify(S.Infinity * KroneckerDelta(0, n) * KroneckerDelta(1, n)) is S.NaN def test_issue_17292(): assert simplify(abs(x)/abs(x**2)) == 1/abs(x) # this is bigger than the issue: check that deep processing works assert simplify(5*abs((x**2 - 1)/(x - 1))) == 5*Abs(x + 1) def test_issue_19822(): expr = And(Gt(n-2, 1), Gt(n, 1)) assert simplify(expr) == Gt(n, 3) def test_issue_18645(): expr = And(Ge(x, 3), Le(x, 3)) assert simplify(expr) == Eq(x, 3) expr = And(Eq(x, 3), Le(x, 3)) assert simplify(expr) == Eq(x, 3) @XFAIL def test_issue_18642(): i = Symbol("i", integer=True) n = Symbol("n", integer=True) expr = And(Eq(i, 2 * n), Le(i, 2*n -1)) assert simplify(expr) == S.false @XFAIL def test_issue_18389(): n = Symbol("n", integer=True) expr = Eq(n, 0) | (n >= 1) assert simplify(expr) == Ge(n, 0) def test_issue_8373(): x = Symbol('x', real=True) assert simplify(Or(x < 1, x >= 1)) == S.true def test_issue_7950(): expr = And(Eq(x, 1), Eq(x, 2)) assert simplify(expr) == S.false def test_issue_22020(): expr = I*pi/2 -oo assert simplify(expr) == expr # Used to throw an error def test_issue_19484(): assert simplify(sign(x) * Abs(x)) == x e = x + sign(x + x**3) assert simplify(Abs(x + x**3)*e) == x**3 + x*Abs(x**3 + x) + x e = x**2 + sign(x**3 + 1) assert simplify(Abs(x**3 + 1) * e) == x**3 + x**2*Abs(x**3 + 1) + 1 f = Function('f') e = x + sign(x + f(x)**3) assert simplify(Abs(x + f(x)**3) * e) == x*Abs(x + f(x)**3) + x + f(x)**3 def test_issue_23543(): # Used to give an error x, y, z = symbols("x y z", commutative=False) assert (x*(y + z/2)).simplify() == x*(2*y + z)/2 def test_issue_19161(): polynomial = Poly('x**2').simplify() assert (polynomial-x**2).simplify() == 0 def test_issue_22210(): d = Symbol('d', integer=True) expr = 2*Derivative(sin(x), (x, d)) assert expr.simplify() == expr
f38e4a9adcfea99383368768182734a4756050c744b82d006dea91dc84147e48
from sympy.core.function import diff from sympy.core.function import expand from sympy.core.numbers import (E, I, Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import (Abs, conjugate, im, re, sign) from sympy.functions.elementary.exponential import log from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, asin, cos, sin, atan2, atan) from sympy.integrals.integrals import integrate from sympy.matrices.dense import Matrix from sympy.simplify import simplify from sympy.simplify.trigsimp import trigsimp from sympy.algebras.quaternion import Quaternion from sympy.testing.pytest import raises from itertools import permutations, product w, x, y, z = symbols('w:z') phi = symbols('phi') def test_quaternion_construction(): q = Quaternion(w, x, y, z) assert q + q == Quaternion(2*w, 2*x, 2*y, 2*z) q2 = Quaternion.from_axis_angle((sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), pi*Rational(2, 3)) assert q2 == Quaternion(S.Half, S.Half, S.Half, S.Half) M = Matrix([[cos(phi), -sin(phi), 0], [sin(phi), cos(phi), 0], [0, 0, 1]]) q3 = trigsimp(Quaternion.from_rotation_matrix(M)) assert q3 == Quaternion(sqrt(2)*sqrt(cos(phi) + 1)/2, 0, 0, sqrt(2 - 2*cos(phi))*sign(sin(phi))/2) nc = Symbol('nc', commutative=False) raises(ValueError, lambda: Quaternion(w, x, nc, z)) def test_quaternion_construction_norm(): q1 = Quaternion(*symbols('a:d')) q2 = Quaternion(w, x, y, z) assert expand((q1*q2).norm()**2 - (q1.norm()**2 * q2.norm()**2)) == 0 q3 = Quaternion(w, x, y, z, norm=1) assert (q1 * q3).norm() == q1.norm() def test_to_and_from_Matrix(): q = Quaternion(w, x, y, z) q_full = Quaternion.from_Matrix(q.to_Matrix()) q_vect = Quaternion.from_Matrix(q.to_Matrix(True)) assert (q - q_full).is_zero_quaternion() assert (q.vector_part() - q_vect).is_zero_quaternion() def test_product_matrices(): q1 = Quaternion(w, x, y, z) q2 = Quaternion(*(symbols("a:d"))) assert (q1 * q2).to_Matrix() == q1.product_matrix_left * q2.to_Matrix() assert (q1 * q2).to_Matrix() == q2.product_matrix_right * q1.to_Matrix() R1 = (q1.product_matrix_left * q1.product_matrix_right.T)[1:, 1:] R2 = simplify(q1.to_rotation_matrix()*q1.norm()**2) assert R1 == R2 def test_quaternion_axis_angle(): test_data = [ # axis, angle, expected_quaternion ((1, 0, 0), 0, (1, 0, 0, 0)), ((1, 0, 0), pi/2, (sqrt(2)/2, sqrt(2)/2, 0, 0)), ((0, 1, 0), pi/2, (sqrt(2)/2, 0, sqrt(2)/2, 0)), ((0, 0, 1), pi/2, (sqrt(2)/2, 0, 0, sqrt(2)/2)), ((1, 0, 0), pi, (0, 1, 0, 0)), ((0, 1, 0), pi, (0, 0, 1, 0)), ((0, 0, 1), pi, (0, 0, 0, 1)), ((1, 1, 1), pi, (0, 1/sqrt(3),1/sqrt(3),1/sqrt(3))), ((sqrt(3)/3, sqrt(3)/3, sqrt(3)/3), pi*2/3, (S.Half, S.Half, S.Half, S.Half)) ] for axis, angle, expected in test_data: assert Quaternion.from_axis_angle(axis, angle) == Quaternion(*expected) def test_quaternion_axis_angle_simplification(): result = Quaternion.from_axis_angle((1, 2, 3), asin(4)) assert result.a == cos(asin(4)/2) assert result.b == sqrt(14)*sin(asin(4)/2)/14 assert result.c == sqrt(14)*sin(asin(4)/2)/7 assert result.d == 3*sqrt(14)*sin(asin(4)/2)/14 def test_quaternion_complex_real_addition(): a = symbols("a", complex=True) b = symbols("b", real=True) # This symbol is not complex: c = symbols("c", commutative=False) q = Quaternion(w, x, y, z) assert a + q == Quaternion(w + re(a), x + im(a), y, z) assert 1 + q == Quaternion(1 + w, x, y, z) assert I + q == Quaternion(w, 1 + x, y, z) assert b + q == Quaternion(w + b, x, y, z) raises(ValueError, lambda: c + q) raises(ValueError, lambda: q * c) raises(ValueError, lambda: c * q) assert -q == Quaternion(-w, -x, -y, -z) q1 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) q2 = Quaternion(1, 4, 7, 8) assert q1 + (2 + 3*I) == Quaternion(5 + 7*I, 2 + 5*I, 0, 7 + 8*I) assert q2 + (2 + 3*I) == Quaternion(3, 7, 7, 8) assert q1 * (2 + 3*I) == \ Quaternion((2 + 3*I)*(3 + 4*I), (2 + 3*I)*(2 + 5*I), 0, (2 + 3*I)*(7 + 8*I)) assert q2 * (2 + 3*I) == Quaternion(-10, 11, 38, -5) q1 = Quaternion(1, 2, 3, 4) q0 = Quaternion(0, 0, 0, 0) assert q1 + q0 == q1 assert q1 - q0 == q1 assert q1 - q1 == q0 def test_quaternion_evalf(): assert Quaternion(sqrt(2), 0, 0, sqrt(3)).evalf() == Quaternion(sqrt(2).evalf(), 0, 0, sqrt(3).evalf()) assert Quaternion(1/sqrt(2), 0, 0, 1/sqrt(2)).evalf() == Quaternion((1/sqrt(2)).evalf(), 0, 0, (1/sqrt(2)).evalf()) def test_quaternion_functions(): q = Quaternion(w, x, y, z) q1 = Quaternion(1, 2, 3, 4) q0 = Quaternion(0, 0, 0, 0) assert conjugate(q) == Quaternion(w, -x, -y, -z) assert q.norm() == sqrt(w**2 + x**2 + y**2 + z**2) assert q.normalize() == Quaternion(w, x, y, z) / sqrt(w**2 + x**2 + y**2 + z**2) assert q.inverse() == Quaternion(w, -x, -y, -z) / (w**2 + x**2 + y**2 + z**2) assert q.inverse() == q.pow(-1) raises(ValueError, lambda: q0.inverse()) assert q.pow(2) == Quaternion(w**2 - x**2 - y**2 - z**2, 2*w*x, 2*w*y, 2*w*z) assert q**(2) == Quaternion(w**2 - x**2 - y**2 - z**2, 2*w*x, 2*w*y, 2*w*z) assert q1.pow(-2) == Quaternion(Rational(-7, 225), Rational(-1, 225), Rational(-1, 150), Rational(-2, 225)) assert q1**(-2) == Quaternion(Rational(-7, 225), Rational(-1, 225), Rational(-1, 150), Rational(-2, 225)) assert q1.pow(-0.5) == NotImplemented raises(TypeError, lambda: q1**(-0.5)) assert q1.exp() == \ Quaternion(E * cos(sqrt(29)), 2 * sqrt(29) * E * sin(sqrt(29)) / 29, 3 * sqrt(29) * E * sin(sqrt(29)) / 29, 4 * sqrt(29) * E * sin(sqrt(29)) / 29) assert q1._ln() == \ Quaternion(log(sqrt(30)), 2 * sqrt(29) * acos(sqrt(30)/30) / 29, 3 * sqrt(29) * acos(sqrt(30)/30) / 29, 4 * sqrt(29) * acos(sqrt(30)/30) / 29) assert q1.pow_cos_sin(2) == \ Quaternion(30 * cos(2 * acos(sqrt(30)/30)), 60 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29, 90 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29, 120 * sqrt(29) * sin(2 * acos(sqrt(30)/30)) / 29) assert diff(Quaternion(x, x, x, x), x) == Quaternion(1, 1, 1, 1) assert integrate(Quaternion(x, x, x, x), x) == \ Quaternion(x**2 / 2, x**2 / 2, x**2 / 2, x**2 / 2) assert Quaternion.rotate_point((1, 1, 1), q1) == (S.One / 5, 1, S(7) / 5) n = Symbol('n') raises(TypeError, lambda: q1**n) n = Symbol('n', integer=True) raises(TypeError, lambda: q1**n) assert Quaternion(22, 23, 55, 8).scalar_part() == 22 assert Quaternion(w, x, y, z).scalar_part() == w assert Quaternion(22, 23, 55, 8).vector_part() == Quaternion(0, 23, 55, 8) assert Quaternion(w, x, y, z).vector_part() == Quaternion(0, x, y, z) assert q1.axis() == Quaternion(0, 2*sqrt(29)/29, 3*sqrt(29)/29, 4*sqrt(29)/29) assert q1.axis().pow(2) == Quaternion(-1, 0, 0, 0) assert q0.axis().scalar_part() == 0 assert q.axis() == Quaternion(0, x/sqrt(x**2 + y**2 + z**2), y/sqrt(x**2 + y**2 + z**2), z/sqrt(x**2 + y**2 + z**2)) assert q0.is_pure() == True assert q1.is_pure() == False assert Quaternion(0, 0, 0, 3).is_pure() == True assert Quaternion(0, 2, 10, 3).is_pure() == True assert Quaternion(w, 2, 10, 3).is_pure() == None assert q1.angle() == atan(sqrt(29)) assert q.angle() == atan2(sqrt(x**2 + y**2 + z**2), w) assert Quaternion.arc_coplanar(q1, Quaternion(2, 4, 6, 8)) == True assert Quaternion.arc_coplanar(q1, Quaternion(1, -2, -3, -4)) == True assert Quaternion.arc_coplanar(q1, Quaternion(1, 8, 12, 16)) == True assert Quaternion.arc_coplanar(q1, Quaternion(1, 2, 3, 4)) == True assert Quaternion.arc_coplanar(q1, Quaternion(w, 4, 6, 8)) == True assert Quaternion.arc_coplanar(q1, Quaternion(2, 7, 4, 1)) == False assert Quaternion.arc_coplanar(q1, Quaternion(w, x, y, z)) == None raises(ValueError, lambda: Quaternion.arc_coplanar(q1, q0)) assert Quaternion.vector_coplanar(Quaternion(0, 8, 12, 16), Quaternion(0, 4, 6, 8), Quaternion(0, 2, 3, 4)) == True assert Quaternion.vector_coplanar(Quaternion(0, 0, 0, 0), Quaternion(0, 4, 6, 8), Quaternion(0, 2, 3, 4)) == True assert Quaternion.vector_coplanar(Quaternion(0, 8, 2, 6), Quaternion(0, 1, 6, 6), Quaternion(0, 0, 3, 4)) == False assert Quaternion.vector_coplanar(Quaternion(0, 1, 3, 4), Quaternion(0, 4, w, 6), Quaternion(0, 6, 8, 1)) == None raises(ValueError, lambda: Quaternion.vector_coplanar(q0, Quaternion(0, 4, 6, 8), q1)) assert Quaternion(0, 1, 2, 3).parallel(Quaternion(0, 2, 4, 6)) == True assert Quaternion(0, 1, 2, 3).parallel(Quaternion(0, 2, 2, 6)) == False assert Quaternion(0, 1, 2, 3).parallel(Quaternion(w, x, y, 6)) == None raises(ValueError, lambda: q0.parallel(q1)) assert Quaternion(0, 1, 2, 3).orthogonal(Quaternion(0, -2, 1, 0)) == True assert Quaternion(0, 2, 4, 7).orthogonal(Quaternion(0, 2, 2, 6)) == False assert Quaternion(0, 2, 4, 7).orthogonal(Quaternion(w, x, y, 6)) == None raises(ValueError, lambda: q0.orthogonal(q1)) assert q1.index_vector() == Quaternion(0, 2*sqrt(870)/29, 3*sqrt(870)/29, 4*sqrt(870)/29) assert Quaternion(0, 3, 9, 4).index_vector() == Quaternion(0, 3, 9, 4) assert Quaternion(4, 3, 9, 4).mensor() == log(sqrt(122)) assert Quaternion(3, 3, 0, 2).mensor() == log(sqrt(22)) assert q0.is_zero_quaternion() == True assert q1.is_zero_quaternion() == False assert Quaternion(w, 0, 0, 0).is_zero_quaternion() == None def test_quaternion_conversions(): q1 = Quaternion(1, 2, 3, 4) assert q1.to_axis_angle() == ((2 * sqrt(29)/29, 3 * sqrt(29)/29, 4 * sqrt(29)/29), 2 * acos(sqrt(30)/30)) assert q1.to_rotation_matrix() == Matrix([[Rational(-2, 3), Rational(2, 15), Rational(11, 15)], [Rational(2, 3), Rational(-1, 3), Rational(2, 3)], [Rational(1, 3), Rational(14, 15), Rational(2, 15)]]) assert q1.to_rotation_matrix((1, 1, 1)) == Matrix([[Rational(-2, 3), Rational(2, 15), Rational(11, 15), Rational(4, 5)], [Rational(2, 3), Rational(-1, 3), Rational(2, 3), S.Zero], [Rational(1, 3), Rational(14, 15), Rational(2, 15), Rational(-2, 5)], [S.Zero, S.Zero, S.Zero, S.One]]) theta = symbols("theta", real=True) q2 = Quaternion(cos(theta/2), 0, 0, sin(theta/2)) assert trigsimp(q2.to_rotation_matrix()) == Matrix([ [cos(theta), -sin(theta), 0], [sin(theta), cos(theta), 0], [0, 0, 1]]) assert q2.to_axis_angle() == ((0, 0, sin(theta/2)/Abs(sin(theta/2))), 2*acos(cos(theta/2))) assert trigsimp(q2.to_rotation_matrix((1, 1, 1))) == Matrix([ [cos(theta), -sin(theta), 0, sin(theta) - cos(theta) + 1], [sin(theta), cos(theta), 0, -sin(theta) - cos(theta) + 1], [0, 0, 1, 0], [0, 0, 0, 1]]) def test_rotation_matrix_homogeneous(): q = Quaternion(w, x, y, z) R1 = q.to_rotation_matrix(homogeneous=True) * q.norm()**2 R2 = simplify(q.to_rotation_matrix(homogeneous=False) * q.norm()**2) assert R1 == R2 def test_quaternion_rotation_iss1593(): """ There was a sign mistake in the definition, of the rotation matrix. This tests that particular sign mistake. See issue 1593 for reference. See wikipedia https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Quaternion-derived_rotation_matrix for the correct definition """ q = Quaternion(cos(phi/2), sin(phi/2), 0, 0) assert(trigsimp(q.to_rotation_matrix()) == Matrix([ [1, 0, 0], [0, cos(phi), -sin(phi)], [0, sin(phi), cos(phi)]])) def test_quaternion_multiplication(): q1 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False) q2 = Quaternion(1, 2, 3, 5) q3 = Quaternion(1, 1, 1, y) assert Quaternion._generic_mul(S(4), S.One) == 4 assert Quaternion._generic_mul(S(4), q1) == Quaternion(12 + 16*I, 8 + 20*I, 0, 28 + 32*I) assert q2.mul(2) == Quaternion(2, 4, 6, 10) assert q2.mul(q3) == Quaternion(-5*y - 4, 3*y - 2, 9 - 2*y, y + 4) assert q2.mul(q3) == q2*q3 z = symbols('z', complex=True) z_quat = Quaternion(re(z), im(z), 0, 0) q = Quaternion(*symbols('q:4', real=True)) assert z * q == z_quat * q assert q * z == q * z_quat def test_issue_16318(): #for rtruediv q0 = Quaternion(0, 0, 0, 0) raises(ValueError, lambda: 1/q0) #for rotate_point q = Quaternion(1, 2, 3, 4) (axis, angle) = q.to_axis_angle() assert Quaternion.rotate_point((1, 1, 1), (axis, angle)) == (S.One / 5, 1, S(7) / 5) #test for to_axis_angle q = Quaternion(-1, 1, 1, 1) axis = (-sqrt(3)/3, -sqrt(3)/3, -sqrt(3)/3) angle = 2*pi/3 assert (axis, angle) == q.to_axis_angle() def test_to_euler(): q = Quaternion(w, x, y, z) q_normalized = q.normalize() seqs = ['zxy', 'zyx', 'zyz', 'zxz'] seqs += [seq.upper() for seq in seqs] for seq in seqs: euler_from_q = q.to_euler(seq) q_back = simplify(Quaternion.from_euler(euler_from_q, seq)) assert q_back == q_normalized def test_to_euler_iss24504(): """ There was a mistake in the degenerate case testing See issue 24504 for reference. """ q = Quaternion.from_euler((phi, 0, 0), 'zyz') assert trigsimp(q.to_euler('zyz'), inverse=True) == (phi, 0, 0) def test_to_euler_numerical_singilarities(): def test_one_case(angles, seq): q = Quaternion.from_euler(angles, seq) assert q.to_euler(seq) == angles # symmetric test_one_case((pi/2, 0, 0), 'zyz') test_one_case((pi/2, 0, 0), 'ZYZ') test_one_case((pi/2, pi, 0), 'zyz') test_one_case((pi/2, pi, 0), 'ZYZ') # asymmetric test_one_case((pi/2, pi/2, 0), 'zyx') test_one_case((pi/2, -pi/2, 0), 'zyx') test_one_case((pi/2, pi/2, 0), 'ZYX') test_one_case((pi/2, -pi/2, 0), 'ZYX') def test_to_euler_options(): def test_one_case(q): angles1 = Matrix(q.to_euler(seq, True, True)) angles2 = Matrix(q.to_euler(seq, False, False)) angle_errors = simplify(angles1-angles2).evalf() for angle_error in angle_errors: # forcing angles to set {-pi, pi} angle_error = (angle_error + pi) % (2 * pi) - pi assert angle_error < 10e-7 for xyz in ('xyz', 'XYZ'): for seq_tuple in permutations(xyz): for symmetric in (True, False): if symmetric: seq = ''.join([seq_tuple[0], seq_tuple[1], seq_tuple[0]]) else: seq = ''.join(seq_tuple) for elements in product([-1, 0, 1], repeat=4): q = Quaternion(*elements) if not q.is_zero_quaternion(): test_one_case(q)
6805a4fb201554d02614c9325256016d503c98f95316a50b3ad9973048b72cef
import math from sympy.core.containers import Tuple from sympy.core.numbers import nan, oo, Float, Integer from sympy.core.relational import Lt from sympy.core.symbol import symbols, Symbol from sympy.functions.elementary.trigonometric import sin from sympy.matrices.dense import Matrix from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.sets.fancysets import Range from sympy.tensor.indexed import Idx, IndexedBase from sympy.testing.pytest import raises from sympy.codegen.ast import ( Assignment, Attribute, aug_assign, CodeBlock, For, Type, Variable, Pointer, Declaration, AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssignment, DivAugmentedAssignment, ModAugmentedAssignment, value_const, pointer_const, integer, real, complex_, int8, uint8, float16 as f16, float32 as f32, float64 as f64, float80 as f80, float128 as f128, complex64 as c64, complex128 as c128, While, Scope, String, Print, QuotedString, FunctionPrototype, FunctionDefinition, Return, FunctionCall, untyped, IntBaseType, intc, Node, none, NoneToken, Token, Comment ) x, y, z, t, x0, x1, x2, a, b = symbols("x, y, z, t, x0, x1, x2, a, b") n = symbols("n", integer=True) A = MatrixSymbol('A', 3, 1) mat = Matrix([1, 2, 3]) B = IndexedBase('B') i = Idx("i", n) A22 = MatrixSymbol('A22',2,2) B22 = MatrixSymbol('B22',2,2) def test_Assignment(): # Here we just do things to show they don't error Assignment(x, y) Assignment(x, 0) Assignment(A, mat) Assignment(A[1,0], 0) Assignment(A[1,0], x) Assignment(B[i], x) Assignment(B[i], 0) a = Assignment(x, y) assert a.func(*a.args) == a assert a.op == ':=' # Here we test things to show that they error # Matrix to scalar raises(ValueError, lambda: Assignment(B[i], A)) raises(ValueError, lambda: Assignment(B[i], mat)) raises(ValueError, lambda: Assignment(x, mat)) raises(ValueError, lambda: Assignment(x, A)) raises(ValueError, lambda: Assignment(A[1,0], mat)) # Scalar to matrix raises(ValueError, lambda: Assignment(A, x)) raises(ValueError, lambda: Assignment(A, 0)) # Non-atomic lhs raises(TypeError, lambda: Assignment(mat, A)) raises(TypeError, lambda: Assignment(0, x)) raises(TypeError, lambda: Assignment(x*x, 1)) raises(TypeError, lambda: Assignment(A + A, mat)) raises(TypeError, lambda: Assignment(B, 0)) def test_AugAssign(): # Here we just do things to show they don't error aug_assign(x, '+', y) aug_assign(x, '+', 0) aug_assign(A, '+', mat) aug_assign(A[1, 0], '+', 0) aug_assign(A[1, 0], '+', x) aug_assign(B[i], '+', x) aug_assign(B[i], '+', 0) # Check creation via aug_assign vs constructor for binop, cls in [ ('+', AddAugmentedAssignment), ('-', SubAugmentedAssignment), ('*', MulAugmentedAssignment), ('/', DivAugmentedAssignment), ('%', ModAugmentedAssignment), ]: a = aug_assign(x, binop, y) b = cls(x, y) assert a.func(*a.args) == a == b assert a.binop == binop assert a.op == binop + '=' # Here we test things to show that they error # Matrix to scalar raises(ValueError, lambda: aug_assign(B[i], '+', A)) raises(ValueError, lambda: aug_assign(B[i], '+', mat)) raises(ValueError, lambda: aug_assign(x, '+', mat)) raises(ValueError, lambda: aug_assign(x, '+', A)) raises(ValueError, lambda: aug_assign(A[1, 0], '+', mat)) # Scalar to matrix raises(ValueError, lambda: aug_assign(A, '+', x)) raises(ValueError, lambda: aug_assign(A, '+', 0)) # Non-atomic lhs raises(TypeError, lambda: aug_assign(mat, '+', A)) raises(TypeError, lambda: aug_assign(0, '+', x)) raises(TypeError, lambda: aug_assign(x * x, '+', 1)) raises(TypeError, lambda: aug_assign(A + A, '+', mat)) raises(TypeError, lambda: aug_assign(B, '+', 0)) def test_Assignment_printing(): assignment_classes = [ Assignment, AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssignment, DivAugmentedAssignment, ModAugmentedAssignment, ] pairs = [ (x, 2 * y + 2), (B[i], x), (A22, B22), (A[0, 0], x), ] for cls in assignment_classes: for lhs, rhs in pairs: a = cls(lhs, rhs) assert repr(a) == '%s(%s, %s)' % (cls.__name__, repr(lhs), repr(rhs)) def test_CodeBlock(): c = CodeBlock(Assignment(x, 1), Assignment(y, x + 1)) assert c.func(*c.args) == c assert c.left_hand_sides == Tuple(x, y) assert c.right_hand_sides == Tuple(1, x + 1) def test_CodeBlock_topological_sort(): assignments = [ Assignment(x, y + z), Assignment(z, 1), Assignment(t, x), Assignment(y, 2), ] ordered_assignments = [ # Note that the unrelated z=1 and y=2 are kept in that order Assignment(z, 1), Assignment(y, 2), Assignment(x, y + z), Assignment(t, x), ] c1 = CodeBlock.topological_sort(assignments) assert c1 == CodeBlock(*ordered_assignments) # Cycle invalid_assignments = [ Assignment(x, y + z), Assignment(z, 1), Assignment(y, x), Assignment(y, 2), ] raises(ValueError, lambda: CodeBlock.topological_sort(invalid_assignments)) # Free symbols free_assignments = [ Assignment(x, y + z), Assignment(z, a * b), Assignment(t, x), Assignment(y, b + 3), ] free_assignments_ordered = [ Assignment(z, a * b), Assignment(y, b + 3), Assignment(x, y + z), Assignment(t, x), ] c2 = CodeBlock.topological_sort(free_assignments) assert c2 == CodeBlock(*free_assignments_ordered) def test_CodeBlock_free_symbols(): c1 = CodeBlock( Assignment(x, y + z), Assignment(z, 1), Assignment(t, x), Assignment(y, 2), ) assert c1.free_symbols == set() c2 = CodeBlock( Assignment(x, y + z), Assignment(z, a * b), Assignment(t, x), Assignment(y, b + 3), ) assert c2.free_symbols == {a, b} def test_CodeBlock_cse(): c1 = CodeBlock( Assignment(y, 1), Assignment(x, sin(y)), Assignment(z, sin(y)), Assignment(t, x*z), ) assert c1.cse() == CodeBlock( Assignment(y, 1), Assignment(x0, sin(y)), Assignment(x, x0), Assignment(z, x0), Assignment(t, x*z), ) # Multiple assignments to same symbol not supported raises(NotImplementedError, lambda: CodeBlock( Assignment(x, 1), Assignment(y, 1), Assignment(y, 2) ).cse()) # Check auto-generated symbols do not collide with existing ones c2 = CodeBlock( Assignment(x0, sin(y) + 1), Assignment(x1, 2 * sin(y)), Assignment(z, x * y), ) assert c2.cse() == CodeBlock( Assignment(x2, sin(y)), Assignment(x0, x2 + 1), Assignment(x1, 2 * x2), Assignment(z, x * y), ) def test_CodeBlock_cse__issue_14118(): # see https://github.com/sympy/sympy/issues/14118 c = CodeBlock( Assignment(A22, Matrix([[x, sin(y)],[3, 4]])), Assignment(B22, Matrix([[sin(y), 2*sin(y)], [sin(y)**2, 7]])) ) assert c.cse() == CodeBlock( Assignment(x0, sin(y)), Assignment(A22, Matrix([[x, x0],[3, 4]])), Assignment(B22, Matrix([[x0, 2*x0], [x0**2, 7]])) ) def test_For(): f = For(n, Range(0, 3), (Assignment(A[n, 0], x + n), aug_assign(x, '+', y))) f = For(n, (1, 2, 3, 4, 5), (Assignment(A[n, 0], x + n),)) assert f.func(*f.args) == f raises(TypeError, lambda: For(n, x, (x + y,))) def test_none(): assert none.is_Atom assert none == none class Foo(Token): pass foo = Foo() assert foo != none assert none == None assert none == NoneToken() assert none.func(*none.args) == none def test_String(): st = String('foobar') assert st.is_Atom assert st == String('foobar') assert st.text == 'foobar' assert st.func(**st.kwargs()) == st assert st.func(*st.args) == st class Signifier(String): pass si = Signifier('foobar') assert si != st assert si.text == st.text s = String('foo') assert str(s) == 'foo' assert repr(s) == "String('foo')" def test_Comment(): c = Comment('foobar') assert c.text == 'foobar' assert str(c) == 'foobar' def test_Node(): n = Node() assert n == Node() assert n.func(*n.args) == n def test_Type(): t = Type('MyType') assert len(t.args) == 1 assert t.name == String('MyType') assert str(t) == 'MyType' assert repr(t) == "Type(String('MyType'))" assert Type(t) == t assert t.func(*t.args) == t t1 = Type('t1') t2 = Type('t2') assert t1 != t2 assert t1 == t1 and t2 == t2 t1b = Type('t1') assert t1 == t1b assert t2 != t1b def test_Type__from_expr(): assert Type.from_expr(i) == integer u = symbols('u', real=True) assert Type.from_expr(u) == real assert Type.from_expr(n) == integer assert Type.from_expr(3) == integer assert Type.from_expr(3.0) == real assert Type.from_expr(3+1j) == complex_ raises(ValueError, lambda: Type.from_expr(sum)) def test_Type__cast_check__integers(): # Rounding raises(ValueError, lambda: integer.cast_check(3.5)) assert integer.cast_check('3') == 3 assert integer.cast_check(Float('3.0000000000000000000')) == 3 assert integer.cast_check(Float('3.0000000000000000001')) == 3 # unintuitive maybe? # Range assert int8.cast_check(127.0) == 127 raises(ValueError, lambda: int8.cast_check(128)) assert int8.cast_check(-128) == -128 raises(ValueError, lambda: int8.cast_check(-129)) assert uint8.cast_check(0) == 0 assert uint8.cast_check(128) == 128 raises(ValueError, lambda: uint8.cast_check(256.0)) raises(ValueError, lambda: uint8.cast_check(-1)) def test_Attribute(): noexcept = Attribute('noexcept') assert noexcept == Attribute('noexcept') alignas16 = Attribute('alignas', [16]) alignas32 = Attribute('alignas', [32]) assert alignas16 != alignas32 assert alignas16.func(*alignas16.args) == alignas16 def test_Variable(): v = Variable(x, type=real) assert v == Variable(v) assert v == Variable('x', type=real) assert v.symbol == x assert v.type == real assert value_const not in v.attrs assert v.func(*v.args) == v assert str(v) == 'Variable(x, type=real)' w = Variable(y, f32, attrs={value_const}) assert w.symbol == y assert w.type == f32 assert value_const in w.attrs assert w.func(*w.args) == w v_n = Variable(n, type=Type.from_expr(n)) assert v_n.type == integer assert v_n.func(*v_n.args) == v_n v_i = Variable(i, type=Type.from_expr(n)) assert v_i.type == integer assert v_i != v_n a_i = Variable.deduced(i) assert a_i.type == integer assert Variable.deduced(Symbol('x', real=True)).type == real assert a_i.func(*a_i.args) == a_i v_n2 = Variable.deduced(n, value=3.5, cast_check=False) assert v_n2.func(*v_n2.args) == v_n2 assert abs(v_n2.value - 3.5) < 1e-15 raises(ValueError, lambda: Variable.deduced(n, value=3.5, cast_check=True)) v_n3 = Variable.deduced(n) assert v_n3.type == integer assert str(v_n3) == 'Variable(n, type=integer)' assert Variable.deduced(z, value=3).type == integer assert Variable.deduced(z, value=3.0).type == real assert Variable.deduced(z, value=3.0+1j).type == complex_ def test_Pointer(): p = Pointer(x) assert p.symbol == x assert p.type == untyped assert value_const not in p.attrs assert pointer_const not in p.attrs assert p.func(*p.args) == p u = symbols('u', real=True) pu = Pointer(u, type=Type.from_expr(u), attrs={value_const, pointer_const}) assert pu.symbol is u assert pu.type == real assert value_const in pu.attrs assert pointer_const in pu.attrs assert pu.func(*pu.args) == pu i = symbols('i', integer=True) deref = pu[i] assert deref.indices == (i,) def test_Declaration(): u = symbols('u', real=True) vu = Variable(u, type=Type.from_expr(u)) assert Declaration(vu).variable.type == real vn = Variable(n, type=Type.from_expr(n)) assert Declaration(vn).variable.type == integer # PR 19107, does not allow comparison between expressions and Basic # lt = StrictLessThan(vu, vn) # assert isinstance(lt, StrictLessThan) vuc = Variable(u, Type.from_expr(u), value=3.0, attrs={value_const}) assert value_const in vuc.attrs assert pointer_const not in vuc.attrs decl = Declaration(vuc) assert decl.variable == vuc assert isinstance(decl.variable.value, Float) assert decl.variable.value == 3.0 assert decl.func(*decl.args) == decl assert vuc.as_Declaration() == decl assert vuc.as_Declaration(value=None, attrs=None) == Declaration(vu) vy = Variable(y, type=integer, value=3) decl2 = Declaration(vy) assert decl2.variable == vy assert decl2.variable.value == Integer(3) vi = Variable(i, type=Type.from_expr(i), value=3.0) decl3 = Declaration(vi) assert decl3.variable.type == integer assert decl3.variable.value == 3.0 raises(ValueError, lambda: Declaration(vi, 42)) def test_IntBaseType(): assert intc.name == String('intc') assert intc.args == (intc.name,) assert str(IntBaseType('a').name) == 'a' def test_FloatType(): assert f16.dig == 3 assert f32.dig == 6 assert f64.dig == 15 assert f80.dig == 18 assert f128.dig == 33 assert f16.decimal_dig == 5 assert f32.decimal_dig == 9 assert f64.decimal_dig == 17 assert f80.decimal_dig == 21 assert f128.decimal_dig == 36 assert f16.max_exponent == 16 assert f32.max_exponent == 128 assert f64.max_exponent == 1024 assert f80.max_exponent == 16384 assert f128.max_exponent == 16384 assert f16.min_exponent == -13 assert f32.min_exponent == -125 assert f64.min_exponent == -1021 assert f80.min_exponent == -16381 assert f128.min_exponent == -16381 assert abs(f16.eps / Float('0.00097656', precision=16) - 1) < 0.1*10**-f16.dig assert abs(f32.eps / Float('1.1920929e-07', precision=32) - 1) < 0.1*10**-f32.dig assert abs(f64.eps / Float('2.2204460492503131e-16', precision=64) - 1) < 0.1*10**-f64.dig assert abs(f80.eps / Float('1.08420217248550443401e-19', precision=80) - 1) < 0.1*10**-f80.dig assert abs(f128.eps / Float(' 1.92592994438723585305597794258492732e-34', precision=128) - 1) < 0.1*10**-f128.dig assert abs(f16.max / Float('65504', precision=16) - 1) < .1*10**-f16.dig assert abs(f32.max / Float('3.40282347e+38', precision=32) - 1) < 0.1*10**-f32.dig assert abs(f64.max / Float('1.79769313486231571e+308', precision=64) - 1) < 0.1*10**-f64.dig # cf. np.finfo(np.float64).max assert abs(f80.max / Float('1.18973149535723176502e+4932', precision=80) - 1) < 0.1*10**-f80.dig assert abs(f128.max / Float('1.18973149535723176508575932662800702e+4932', precision=128) - 1) < 0.1*10**-f128.dig # cf. np.finfo(np.float32).tiny assert abs(f16.tiny / Float('6.1035e-05', precision=16) - 1) < 0.1*10**-f16.dig assert abs(f32.tiny / Float('1.17549435e-38', precision=32) - 1) < 0.1*10**-f32.dig assert abs(f64.tiny / Float('2.22507385850720138e-308', precision=64) - 1) < 0.1*10**-f64.dig assert abs(f80.tiny / Float('3.36210314311209350626e-4932', precision=80) - 1) < 0.1*10**-f80.dig assert abs(f128.tiny / Float('3.3621031431120935062626778173217526e-4932', precision=128) - 1) < 0.1*10**-f128.dig assert f64.cast_check(0.5) == Float(0.5, 17) assert abs(f64.cast_check(3.7) - 3.7) < 3e-17 assert isinstance(f64.cast_check(3), (Float, float)) assert f64.cast_nocheck(oo) == float('inf') assert f64.cast_nocheck(-oo) == float('-inf') assert f64.cast_nocheck(float(oo)) == float('inf') assert f64.cast_nocheck(float(-oo)) == float('-inf') assert math.isnan(f64.cast_nocheck(nan)) assert f32 != f64 assert f64 == f64.func(*f64.args) def test_Type__cast_check__floating_point(): raises(ValueError, lambda: f32.cast_check(123.45678949)) raises(ValueError, lambda: f32.cast_check(12.345678949)) raises(ValueError, lambda: f32.cast_check(1.2345678949)) raises(ValueError, lambda: f32.cast_check(.12345678949)) assert abs(123.456789049 - f32.cast_check(123.456789049) - 4.9e-8) < 1e-8 assert abs(0.12345678904 - f32.cast_check(0.12345678904) - 4e-11) < 1e-11 dcm21 = Float('0.123456789012345670499') # 21 decimals assert abs(dcm21 - f64.cast_check(dcm21) - 4.99e-19) < 1e-19 f80.cast_check(Float('0.12345678901234567890103', precision=88)) raises(ValueError, lambda: f80.cast_check(Float('0.12345678901234567890149', precision=88))) v10 = 12345.67894 raises(ValueError, lambda: f32.cast_check(v10)) assert abs(Float(str(v10), precision=64+8) - f64.cast_check(v10)) < v10*1e-16 assert abs(f32.cast_check(2147483647) - 2147483650) < 1 def test_Type__cast_check__complex_floating_point(): val9_11 = 123.456789049 + 0.123456789049j raises(ValueError, lambda: c64.cast_check(.12345678949 + .12345678949j)) assert abs(val9_11 - c64.cast_check(val9_11) - 4.9e-8) < 1e-8 dcm21 = Float('0.123456789012345670499') + 1e-20j # 21 decimals assert abs(dcm21 - c128.cast_check(dcm21) - 4.99e-19) < 1e-19 v19 = Float('0.1234567890123456749') + 1j*Float('0.1234567890123456749') raises(ValueError, lambda: c128.cast_check(v19)) def test_While(): xpp = AddAugmentedAssignment(x, 1) whl1 = While(x < 2, [xpp]) assert whl1.condition.args[0] == x assert whl1.condition.args[1] == 2 assert whl1.condition == Lt(x, 2, evaluate=False) assert whl1.body.args == (xpp,) assert whl1.func(*whl1.args) == whl1 cblk = CodeBlock(AddAugmentedAssignment(x, 1)) whl2 = While(x < 2, cblk) assert whl1 == whl2 assert whl1 != While(x < 3, [xpp]) def test_Scope(): assign = Assignment(x, y) incr = AddAugmentedAssignment(x, 1) scp = Scope([assign, incr]) cblk = CodeBlock(assign, incr) assert scp.body == cblk assert scp == Scope(cblk) assert scp != Scope([incr, assign]) assert scp.func(*scp.args) == scp def test_Print(): fmt = "%d %.3f" ps = Print([n, x], fmt) assert str(ps.format_string) == fmt assert ps.print_args == Tuple(n, x) assert ps.args == (Tuple(n, x), QuotedString(fmt), none) assert ps == Print((n, x), fmt) assert ps != Print([x, n], fmt) assert ps.func(*ps.args) == ps ps2 = Print([n, x]) assert ps2 == Print([n, x]) assert ps2 != ps assert ps2.format_string == None def test_FunctionPrototype_and_FunctionDefinition(): vx = Variable(x, type=real) vn = Variable(n, type=integer) fp1 = FunctionPrototype(real, 'power', [vx, vn]) assert fp1.return_type == real assert fp1.name == String('power') assert fp1.parameters == Tuple(vx, vn) assert fp1 == FunctionPrototype(real, 'power', [vx, vn]) assert fp1 != FunctionPrototype(real, 'power', [vn, vx]) assert fp1.func(*fp1.args) == fp1 body = [Assignment(x, x**n), Return(x)] fd1 = FunctionDefinition(real, 'power', [vx, vn], body) assert fd1.return_type == real assert str(fd1.name) == 'power' assert fd1.parameters == Tuple(vx, vn) assert fd1.body == CodeBlock(*body) assert fd1 == FunctionDefinition(real, 'power', [vx, vn], body) assert fd1 != FunctionDefinition(real, 'power', [vx, vn], body[::-1]) assert fd1.func(*fd1.args) == fd1 fp2 = FunctionPrototype.from_FunctionDefinition(fd1) assert fp2 == fp1 fd2 = FunctionDefinition.from_FunctionPrototype(fp1, body) assert fd2 == fd1 def test_Return(): rs = Return(x) assert rs.args == (x,) assert rs == Return(x) assert rs != Return(y) assert rs.func(*rs.args) == rs def test_FunctionCall(): fc = FunctionCall('power', (x, 3)) assert fc.function_args[0] == x assert fc.function_args[1] == 3 assert len(fc.function_args) == 2 assert isinstance(fc.function_args[1], Integer) assert fc == FunctionCall('power', (x, 3)) assert fc != FunctionCall('power', (3, x)) assert fc != FunctionCall('Power', (x, 3)) assert fc.func(*fc.args) == fc fc2 = FunctionCall('fma', [2, 3, 4]) assert len(fc2.function_args) == 3 assert fc2.function_args[0] == 2 assert fc2.function_args[1] == 3 assert fc2.function_args[2] == 4 assert str(fc2) in ( # not sure if QuotedString is a better default... 'FunctionCall(fma, function_args=(2, 3, 4))', 'FunctionCall("fma", function_args=(2, 3, 4))', ) def test_ast_replace(): x = Variable('x', real) y = Variable('y', real) n = Variable('n', integer) pwer = FunctionDefinition(real, 'pwer', [x, n], [pow(x.symbol, n.symbol)]) pname = pwer.name pcall = FunctionCall('pwer', [y, 3]) tree1 = CodeBlock(pwer, pcall) assert str(tree1.args[0].name) == 'pwer' assert str(tree1.args[1].name) == 'pwer' for a, b in zip(tree1, [pwer, pcall]): assert a == b tree2 = tree1.replace(pname, String('power')) assert str(tree1.args[0].name) == 'pwer' assert str(tree1.args[1].name) == 'pwer' assert str(tree2.args[0].name) == 'power' assert str(tree2.args[1].name) == 'power'