hash
stringlengths
64
64
content
stringlengths
0
1.51M
f60b416cbc0ca92827d6079803fe0352f73395e27d1e5faab3cee89bac5abc92
from sympy.core.basic import Basic from sympy.functions import adjoint, conjugate from sympy.matrices.expressions.matexpr import MatrixExpr class Transpose(MatrixExpr): """ The transpose of a matrix expression. This is a symbolic object that simply stores its argument without evaluating it. To actually compute the transpose, use the ``transpose()`` function, or the ``.T`` attribute of matrices. Examples ======== >>> from sympy.matrices import MatrixSymbol, Transpose >>> from sympy.functions import transpose >>> A = MatrixSymbol('A', 3, 5) >>> B = MatrixSymbol('B', 5, 3) >>> Transpose(A) A.T >>> A.T == transpose(A) == Transpose(A) True >>> Transpose(A*B) (A*B).T >>> transpose(A*B) B.T*A.T """ is_Transpose = True def doit(self, **hints): arg = self.arg if hints.get('deep', True) and isinstance(arg, Basic): arg = arg.doit(**hints) _eval_transpose = getattr(arg, '_eval_transpose', None) if _eval_transpose is not None: result = _eval_transpose() return result if result is not None else Transpose(arg) else: return Transpose(arg) @property def arg(self): return self.args[0] @property def shape(self): return self.arg.shape[::-1] def _entry(self, i, j, expand=False, **kwargs): return self.arg._entry(j, i, expand=expand, **kwargs) def _eval_adjoint(self): return conjugate(self.arg) def _eval_conjugate(self): return adjoint(self.arg) def _eval_transpose(self): return self.arg def _eval_trace(self): from .trace import Trace return Trace(self.arg) # Trace(X.T) => Trace(X) def _eval_determinant(self): from sympy.matrices.expressions.determinant import det return det(self.arg) def _eval_derivative(self, x): # x is a scalar: return self.arg._eval_derivative(x) def _eval_derivative_matrix_lines(self, x): lines = self.args[0]._eval_derivative_matrix_lines(x) return [i.transpose() for i in lines] def transpose(expr): """Matrix transpose""" return Transpose(expr).doit(deep=False) from sympy.assumptions.ask import ask, Q from sympy.assumptions.refine import handlers_dict def refine_Transpose(expr, assumptions): """ >>> from sympy import MatrixSymbol, Q, assuming, refine >>> X = MatrixSymbol('X', 2, 2) >>> X.T X.T >>> with assuming(Q.symmetric(X)): ... print(refine(X.T)) X """ if ask(Q.symmetric(expr), assumptions): return expr.arg return expr handlers_dict['Transpose'] = refine_Transpose
d937ac1e46b084d501e8282b04fb2d54382e08e0095de53dc8fb3d22c0df8177
from sympy.assumptions.ask import ask, Q from sympy.assumptions.refine import handlers_dict from sympy.core import Basic, sympify, S from sympy.core.mul import mul, Mul from sympy.core.numbers import Number, Integer from sympy.core.symbol import Dummy from sympy.functions import adjoint from sympy.strategies import (rm_id, unpack, typed, flatten, exhaust, do_one, new) from sympy.matrices.common import ShapeError, NonInvertibleMatrixError from sympy.matrices.matrices import MatrixBase from .inverse import Inverse from .matexpr import MatrixExpr from .matpow import MatPow from .transpose import transpose from .permutation import PermutationMatrix from .special import ZeroMatrix, Identity, GenericIdentity, OneMatrix # XXX: MatMul should perhaps not subclass directly from Mul class MatMul(MatrixExpr, Mul): """ A product of matrix expressions Examples ======== >>> from sympy import MatMul, MatrixSymbol >>> A = MatrixSymbol('A', 5, 4) >>> B = MatrixSymbol('B', 4, 3) >>> C = MatrixSymbol('C', 3, 6) >>> MatMul(A, B, C) A*B*C """ is_MatMul = True identity = GenericIdentity() def __new__(cls, *args, evaluate=False, check=True, _sympify=True): if not args: return cls.identity # This must be removed aggressively in the constructor to avoid # TypeErrors from GenericIdentity().shape args = list(filter(lambda i: cls.identity != i, args)) if _sympify: args = list(map(sympify, args)) obj = Basic.__new__(cls, *args) factor, matrices = obj.as_coeff_matrices() if check: validate(*matrices) if not matrices: # Should it be # # return Basic.__neq__(cls, factor, GenericIdentity()) ? return factor if evaluate: return canonicalize(obj) return obj @property def shape(self): matrices = [arg for arg in self.args if arg.is_Matrix] return (matrices[0].rows, matrices[-1].cols) def could_extract_minus_sign(self): return self.args[0].could_extract_minus_sign() def _entry(self, i, j, expand=True, **kwargs): # Avoid cyclic imports from sympy.concrete.summations import Sum from sympy.matrices.immutable import ImmutableMatrix coeff, matrices = self.as_coeff_matrices() if len(matrices) == 1: # situation like 2*X, matmul is just X return coeff * matrices[0][i, j] indices = [None]*(len(matrices) + 1) ind_ranges = [None]*(len(matrices) - 1) indices[0] = i indices[-1] = j def f(): counter = 1 while True: yield Dummy("i_%i" % counter) counter += 1 dummy_generator = kwargs.get("dummy_generator", f()) for i in range(1, len(matrices)): indices[i] = next(dummy_generator) for i, arg in enumerate(matrices[:-1]): ind_ranges[i] = arg.shape[1] - 1 matrices = [arg._entry(indices[i], indices[i+1], dummy_generator=dummy_generator) for i, arg in enumerate(matrices)] expr_in_sum = Mul.fromiter(matrices) if any(v.has(ImmutableMatrix) for v in matrices): expand = True result = coeff*Sum( expr_in_sum, *zip(indices[1:-1], [0]*len(ind_ranges), ind_ranges) ) # Don't waste time in result.doit() if the sum bounds are symbolic if not any(isinstance(v, (Integer, int)) for v in ind_ranges): expand = False return result.doit() if expand else result def as_coeff_matrices(self): scalars = [x for x in self.args if not x.is_Matrix] matrices = [x for x in self.args if x.is_Matrix] coeff = Mul(*scalars) if coeff.is_commutative is False: raise NotImplementedError("noncommutative scalars in MatMul are not supported.") return coeff, matrices def as_coeff_mmul(self): coeff, matrices = self.as_coeff_matrices() return coeff, MatMul(*matrices) def _eval_transpose(self): """Transposition of matrix multiplication. Notes ===== The following rules are applied. Transposition for matrix multiplied with another matrix: `\\left(A B\\right)^{T} = B^{T} A^{T}` Transposition for matrix multiplied with scalar: `\\left(c A\\right)^{T} = c A^{T}` References ========== .. [1] https://en.wikipedia.org/wiki/Transpose """ coeff, matrices = self.as_coeff_matrices() return MatMul( coeff, *[transpose(arg) for arg in matrices[::-1]]).doit() def _eval_adjoint(self): return MatMul(*[adjoint(arg) for arg in self.args[::-1]]).doit() def _eval_trace(self): factor, mmul = self.as_coeff_mmul() if factor != 1: from .trace import trace return factor * trace(mmul.doit()) else: raise NotImplementedError("Can't simplify any further") def _eval_determinant(self): from sympy.matrices.expressions.determinant import Determinant factor, matrices = self.as_coeff_matrices() square_matrices = only_squares(*matrices) return factor**self.rows * Mul(*list(map(Determinant, square_matrices))) def _eval_inverse(self): try: return MatMul(*[ arg.inverse() if isinstance(arg, MatrixExpr) else arg**-1 for arg in self.args[::-1]]).doit() except ShapeError: return Inverse(self) def doit(self, **kwargs): deep = kwargs.get('deep', True) if deep: args = [arg.doit(**kwargs) for arg in self.args] else: args = self.args # treat scalar*MatrixSymbol or scalar*MatPow separately expr = canonicalize(MatMul(*args)) return expr # Needed for partial compatibility with Mul def args_cnc(self, **kwargs): coeff_c = [x for x in self.args if x.is_commutative] coeff_nc = [x for x in self.args if not x.is_commutative] return [coeff_c, coeff_nc] def _eval_derivative_matrix_lines(self, x): from .transpose import Transpose with_x_ind = [i for i, arg in enumerate(self.args) if arg.has(x)] lines = [] for ind in with_x_ind: left_args = self.args[:ind] right_args = self.args[ind+1:] if right_args: right_mat = MatMul.fromiter(right_args) else: right_mat = Identity(self.shape[1]) if left_args: left_rev = MatMul.fromiter([Transpose(i).doit() if i.is_Matrix else i for i in reversed(left_args)]) else: left_rev = Identity(self.shape[0]) d = self.args[ind]._eval_derivative_matrix_lines(x) for i in d: i.append_first(left_rev) i.append_second(right_mat) lines.append(i) return lines mul.register_handlerclass((Mul, MatMul), MatMul) def validate(*matrices): """ Checks for valid shapes for args of MatMul """ for i in range(len(matrices)-1): A, B = matrices[i:i+2] if A.cols != B.rows: raise ShapeError("Matrices %s and %s are not aligned"%(A, B)) # Rules def newmul(*args): if args[0] == 1: args = args[1:] return new(MatMul, *args) def any_zeros(mul): if any(arg.is_zero or (arg.is_Matrix and arg.is_ZeroMatrix) for arg in mul.args): matrices = [arg for arg in mul.args if arg.is_Matrix] return ZeroMatrix(matrices[0].rows, matrices[-1].cols) return mul def merge_explicit(matmul): """ Merge explicit MatrixBase arguments >>> from sympy import MatrixSymbol, Matrix, MatMul, pprint >>> from sympy.matrices.expressions.matmul import merge_explicit >>> A = MatrixSymbol('A', 2, 2) >>> B = Matrix([[1, 1], [1, 1]]) >>> C = Matrix([[1, 2], [3, 4]]) >>> X = MatMul(A, B, C) >>> pprint(X) [1 1] [1 2] A*[ ]*[ ] [1 1] [3 4] >>> pprint(merge_explicit(X)) [4 6] A*[ ] [4 6] >>> X = MatMul(B, A, C) >>> pprint(X) [1 1] [1 2] [ ]*A*[ ] [1 1] [3 4] >>> pprint(merge_explicit(X)) [1 1] [1 2] [ ]*A*[ ] [1 1] [3 4] """ if not any(isinstance(arg, MatrixBase) for arg in matmul.args): return matmul newargs = [] last = matmul.args[0] for arg in matmul.args[1:]: if isinstance(arg, (MatrixBase, Number)) and isinstance(last, (MatrixBase, Number)): last = last * arg else: newargs.append(last) last = arg newargs.append(last) return MatMul(*newargs) def remove_ids(mul): """ Remove Identities from a MatMul This is a modified version of sympy.strategies.rm_id. This is necesssary because MatMul may contain both MatrixExprs and Exprs as args. See Also ======== sympy.strategies.rm_id """ # Separate Exprs from MatrixExprs in args factor, mmul = mul.as_coeff_mmul() # Apply standard rm_id for MatMuls result = rm_id(lambda x: x.is_Identity is True)(mmul) if result != mmul: return newmul(factor, *result.args) # Recombine and return else: return mul def factor_in_front(mul): factor, matrices = mul.as_coeff_matrices() if factor != 1: return newmul(factor, *matrices) return mul def combine_powers(mul): r"""Combine consecutive powers with the same base into one, e.g. $$A \times A^2 \Rightarrow A^3$$ This also cancels out the possible matrix inverses using the knowledgebase of :class:`~.Inverse`, e.g., $$ Y \times X \times X^{-1} \Rightarrow Y $$ """ factor, args = mul.as_coeff_matrices() new_args = [args[0]] for B in args[1:]: A = new_args[-1] if A.is_square == False or B.is_square == False: new_args.append(B) continue if isinstance(A, MatPow): A_base, A_exp = A.args else: A_base, A_exp = A, S.One if isinstance(B, MatPow): B_base, B_exp = B.args else: B_base, B_exp = B, S.One if A_base == B_base: new_exp = A_exp + B_exp new_args[-1] = MatPow(A_base, new_exp).doit(deep=False) continue elif not isinstance(B_base, MatrixBase): try: B_base_inv = B_base.inverse() except NonInvertibleMatrixError: B_base_inv = None if B_base_inv is not None and A_base == B_base_inv: new_exp = A_exp - B_exp new_args[-1] = MatPow(A_base, new_exp).doit(deep=False) continue new_args.append(B) return newmul(factor, *new_args) def combine_permutations(mul): """Refine products of permutation matrices as the products of cycles. """ args = mul.args l = len(args) if l < 2: return mul result = [args[0]] for i in range(1, l): A = result[-1] B = args[i] if isinstance(A, PermutationMatrix) and \ isinstance(B, PermutationMatrix): cycle_1 = A.args[0] cycle_2 = B.args[0] result[-1] = PermutationMatrix(cycle_1 * cycle_2) else: result.append(B) return MatMul(*result) def combine_one_matrices(mul): """ Combine products of OneMatrix e.g. OneMatrix(2, 3) * OneMatrix(3, 4) -> 3 * OneMatrix(2, 4) """ factor, args = mul.as_coeff_matrices() new_args = [args[0]] for B in args[1:]: A = new_args[-1] if not isinstance(A, OneMatrix) or not isinstance(B, OneMatrix): new_args.append(B) continue new_args.pop() new_args.append(OneMatrix(A.shape[0], B.shape[1])) factor *= A.shape[1] return newmul(factor, *new_args) def distribute_monom(mul): """ Simplify MatMul expressions but distributing rational term to MatMul. e.g. 2*(A+B) -> 2*A + 2*B """ args = mul.args if len(args) == 2: from .matadd import MatAdd if args[0].is_MatAdd and args[1].is_Rational: return MatAdd(*[MatMul(mat, args[1]).doit() for mat in args[0].args]) if args[1].is_MatAdd and args[0].is_Rational: return MatAdd(*[MatMul(args[0], mat).doit() for mat in args[1].args]) return mul rules = ( distribute_monom, any_zeros, remove_ids, combine_one_matrices, combine_powers, unpack, rm_id(lambda x: x == 1), merge_explicit, factor_in_front, flatten, combine_permutations) canonicalize = exhaust(typed({MatMul: do_one(*rules)})) def only_squares(*matrices): """factor matrices only if they are square""" if matrices[0].rows != matrices[-1].cols: raise RuntimeError("Invalid matrices being multiplied") out = [] start = 0 for i, M in enumerate(matrices): if M.cols == matrices[start].rows: out.append(MatMul(*matrices[start:i+1]).doit()) start = i+1 return out def refine_MatMul(expr, assumptions): """ >>> from sympy import MatrixSymbol, Q, assuming, refine >>> X = MatrixSymbol('X', 2, 2) >>> expr = X * X.T >>> print(expr) X*X.T >>> with assuming(Q.orthogonal(X)): ... print(refine(expr)) I """ newargs = [] exprargs = [] for args in expr.args: if args.is_Matrix: exprargs.append(args) else: newargs.append(args) last = exprargs[0] for arg in exprargs[1:]: if arg == last.T and ask(Q.orthogonal(arg), assumptions): last = Identity(arg.shape[0]) elif arg == last.conjugate() and ask(Q.unitary(arg), assumptions): last = Identity(arg.shape[0]) else: newargs.append(last) last = arg newargs.append(last) return MatMul(*newargs) handlers_dict['MatMul'] = refine_MatMul
97478e4c44c1a46ed91221f5a7028c184c2d15012fe715f91c5523ed93caeaca
from sympy.matrices.common import NonSquareMatrixError from .matexpr import MatrixExpr from .special import Identity from sympy.core import S from sympy.core.expr import ExprBuilder from sympy.core.cache import cacheit from sympy.core.power import Pow from sympy.core.sympify import _sympify from sympy.matrices import MatrixBase class MatPow(MatrixExpr): def __new__(cls, base, exp, evaluate=False, **options): base = _sympify(base) if not base.is_Matrix: raise TypeError("MatPow base should be a matrix") if not base.is_square: raise NonSquareMatrixError("Power of non-square matrix %s" % base) exp = _sympify(exp) obj = super().__new__(cls, base, exp) if evaluate: obj = obj.doit(deep=False) return obj @property def base(self): return self.args[0] @property def exp(self): return self.args[1] @property def shape(self): return self.base.shape @cacheit def _get_explicit_matrix(self): return self.base.as_explicit()**self.exp def _entry(self, i, j, **kwargs): from sympy.matrices.expressions import MatMul A = self.doit() if isinstance(A, MatPow): # We still have a MatPow, make an explicit MatMul out of it. if A.exp.is_Integer and A.exp.is_positive: A = MatMul(*[A.base for k in range(A.exp)]) elif not self._is_shape_symbolic(): return A._get_explicit_matrix()[i, j] else: # Leave the expression unevaluated: from sympy.matrices.expressions.matexpr import MatrixElement return MatrixElement(self, i, j) return A[i, j] def doit(self, **kwargs): if kwargs.get('deep', True): base, exp = [arg.doit(**kwargs) for arg in self.args] else: base, exp = self.args # combine all powers, e.g. (A ** 2) ** 3 -> A ** 6 while isinstance(base, MatPow): exp *= base.args[1] base = base.args[0] if isinstance(base, MatrixBase): # Delegate return base ** exp # Handle simple cases so that _eval_power() in MatrixExpr sub-classes can ignore them if exp == S.One: return base if exp == S.Zero: return Identity(base.rows) if exp == S.NegativeOne: from sympy.matrices.expressions import Inverse return Inverse(base).doit(**kwargs) eval_power = getattr(base, '_eval_power', None) if eval_power is not None: return eval_power(exp) return MatPow(base, exp) def _eval_transpose(self): base, exp = self.args return MatPow(base.T, exp) def _eval_derivative(self, x): return Pow._eval_derivative(self, x) def _eval_derivative_matrix_lines(self, x): from sympy.tensor.array.expressions.array_expressions import ArrayContraction from ...tensor.array.expressions.array_expressions import ArrayTensorProduct from .matmul import MatMul from .inverse import Inverse exp = self.exp if self.base.shape == (1, 1) and not exp.has(x): lr = self.base._eval_derivative_matrix_lines(x) for i in lr: subexpr = ExprBuilder( ArrayContraction, [ ExprBuilder( ArrayTensorProduct, [ Identity(1), i._lines[0], exp*self.base**(exp-1), i._lines[1], Identity(1), ] ), (0, 3, 4), (5, 7, 8) ], validator=ArrayContraction._validate ) i._first_pointer_parent = subexpr.args[0].args i._first_pointer_index = 0 i._second_pointer_parent = subexpr.args[0].args i._second_pointer_index = 4 i._lines = [subexpr] return lr if (exp > 0) == True: newexpr = MatMul.fromiter([self.base for i in range(exp)]) elif (exp == -1) == True: return Inverse(self.base)._eval_derivative_matrix_lines(x) elif (exp < 0) == True: newexpr = MatMul.fromiter([Inverse(self.base) for i in range(-exp)]) elif (exp == 0) == True: return self.doit()._eval_derivative_matrix_lines(x) else: raise NotImplementedError("cannot evaluate %s derived by %s" % (self, x)) return newexpr._eval_derivative_matrix_lines(x) def _eval_inverse(self): return MatPow(self.base, -self.exp)
0a12d4c0f4ded47cffeda2d96039d83ac39449b19c1aaadd3389c8d02981ceca
from sympy.assumptions.ask import ask, Q from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.sympify import _sympify from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.matrices.common import NonInvertibleMatrixError from .matexpr import MatrixExpr class ZeroMatrix(MatrixExpr): """The Matrix Zero 0 - additive identity Examples ======== >>> from sympy import MatrixSymbol, ZeroMatrix >>> A = MatrixSymbol('A', 3, 5) >>> Z = ZeroMatrix(3, 5) >>> A + Z A >>> Z*A.T 0 """ is_ZeroMatrix = True def __new__(cls, m, n): m, n = _sympify(m), _sympify(n) cls._check_dim(m) cls._check_dim(n) return super().__new__(cls, m, n) @property def shape(self): return (self.args[0], self.args[1]) def _eval_power(self, exp): # exp = -1, 0, 1 are already handled at this stage if (exp < 0) == True: raise NonInvertibleMatrixError("Matrix det == 0; not invertible") return self def _eval_transpose(self): return ZeroMatrix(self.cols, self.rows) def _eval_trace(self): return S.Zero def _eval_determinant(self): return S.Zero def _eval_inverse(self): raise NonInvertibleMatrixError("Matrix det == 0; not invertible.") def conjugate(self): return self def _entry(self, i, j, **kwargs): return S.Zero class GenericZeroMatrix(ZeroMatrix): """ A zero matrix without a specified shape This exists primarily so MatAdd() with no arguments can return something meaningful. """ def __new__(cls): # super(ZeroMatrix, cls) instead of super(GenericZeroMatrix, cls) # because ZeroMatrix.__new__ doesn't have the same signature return super(ZeroMatrix, cls).__new__(cls) @property def rows(self): raise TypeError("GenericZeroMatrix does not have a specified shape") @property def cols(self): raise TypeError("GenericZeroMatrix does not have a specified shape") @property def shape(self): raise TypeError("GenericZeroMatrix does not have a specified shape") # Avoid Matrix.__eq__ which might call .shape def __eq__(self, other): return isinstance(other, GenericZeroMatrix) def __ne__(self, other): return not (self == other) def __hash__(self): return super().__hash__() class Identity(MatrixExpr): """The Matrix Identity I - multiplicative identity Examples ======== >>> from sympy.matrices import Identity, MatrixSymbol >>> A = MatrixSymbol('A', 3, 5) >>> I = Identity(3) >>> I*A A """ is_Identity = True def __new__(cls, n): n = _sympify(n) cls._check_dim(n) return super().__new__(cls, n) @property def rows(self): return self.args[0] @property def cols(self): return self.args[0] @property def shape(self): return (self.args[0], self.args[0]) @property def is_square(self): return True def _eval_transpose(self): return self def _eval_trace(self): return self.rows def _eval_inverse(self): return self def conjugate(self): return self def _entry(self, i, j, **kwargs): eq = Eq(i, j) if eq is S.true: return S.One elif eq is S.false: return S.Zero return KroneckerDelta(i, j, (0, self.cols-1)) def _eval_determinant(self): return S.One def _eval_power(self, exp): return self class GenericIdentity(Identity): """ An identity matrix without a specified shape This exists primarily so MatMul() with no arguments can return something meaningful. """ def __new__(cls): # super(Identity, cls) instead of super(GenericIdentity, cls) because # Identity.__new__ doesn't have the same signature return super(Identity, cls).__new__(cls) @property def rows(self): raise TypeError("GenericIdentity does not have a specified shape") @property def cols(self): raise TypeError("GenericIdentity does not have a specified shape") @property def shape(self): raise TypeError("GenericIdentity does not have a specified shape") # Avoid Matrix.__eq__ which might call .shape def __eq__(self, other): return isinstance(other, GenericIdentity) def __ne__(self, other): return not (self == other) def __hash__(self): return super().__hash__() class OneMatrix(MatrixExpr): """ Matrix whose all entries are ones. """ def __new__(cls, m, n, evaluate=False): m, n = _sympify(m), _sympify(n) cls._check_dim(m) cls._check_dim(n) if evaluate: condition = Eq(m, 1) & Eq(n, 1) if condition == True: return Identity(1) obj = super().__new__(cls, m, n) return obj @property def shape(self): return self._args @property def is_Identity(self): return self._is_1x1() == True def as_explicit(self): from sympy.matrices.immutable import ImmutableDenseMatrix return ImmutableDenseMatrix.ones(*self.shape) def doit(self, **hints): args = self.args if hints.get('deep', True): args = [a.doit(**hints) for a in args] return self.func(*args, evaluate=True) def _eval_power(self, exp): # exp = -1, 0, 1 are already handled at this stage if self._is_1x1() == True: return Identity(1) if (exp < 0) == True: raise NonInvertibleMatrixError("Matrix det == 0; not invertible") if ask(Q.integer(exp)): return self.shape[0] ** (exp - 1) * OneMatrix(*self.shape) return super()._eval_power(exp) def _eval_transpose(self): return OneMatrix(self.cols, self.rows) def _eval_trace(self): return S.One*self.rows def _is_1x1(self): """Returns true if the matrix is known to be 1x1""" shape = self.shape return Eq(shape[0], 1) & Eq(shape[1], 1) def _eval_determinant(self): condition = self._is_1x1() if condition == True: return S.One elif condition == False: return S.Zero else: from sympy.matrices.expressions.determinant import Determinant return Determinant(self) def _eval_inverse(self): condition = self._is_1x1() if condition == True: return Identity(1) elif condition == False: raise NonInvertibleMatrixError("Matrix det == 0; not invertible.") else: from .inverse import Inverse return Inverse(self) def conjugate(self): return self def _entry(self, i, j, **kwargs): return S.One
d955e247df1a2ae8c4fea709d3dfbdfb051cc96748e400890b5a400405d50b19
from typing import Tuple as tTuple from functools import wraps from sympy.core import S, Integer, Basic, Mul, Add from sympy.core.assumptions import check_assumptions from sympy.core.decorators import call_highest_priority from sympy.core.expr import Expr, ExprBuilder from sympy.core.logic import FuzzyBool from sympy.core.symbol import Str, Dummy, symbols, Symbol from sympy.core.sympify import SympifyError, _sympify from sympy.external.gmpy import SYMPY_INTS from sympy.functions import conjugate, adjoint from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.matrices.common import NonSquareMatrixError from sympy.matrices.matrices import MatrixKind, MatrixBase from sympy.multipledispatch import dispatch from sympy.simplify import simplify from sympy.utilities.misc import filldedent def _sympifyit(arg, retval=None): # This version of _sympifyit sympifies MutableMatrix objects def deco(func): @wraps(func) def __sympifyit_wrapper(a, b): try: b = _sympify(b) return func(a, b) except SympifyError: return retval return __sympifyit_wrapper return deco class MatrixExpr(Expr): """Superclass for Matrix Expressions MatrixExprs represent abstract matrices, linear transformations represented within a particular basis. Examples ======== >>> from sympy import MatrixSymbol >>> A = MatrixSymbol('A', 3, 3) >>> y = MatrixSymbol('y', 3, 1) >>> x = (A.T*A).I * A * y See Also ======== MatrixSymbol, MatAdd, MatMul, Transpose, Inverse """ # Should not be considered iterable by the # sympy.utilities.iterables.iterable function. Subclass that actually are # iterable (i.e., explicit matrices) should set this to True. _iterable = False _op_priority = 11.0 is_Matrix = True # type: bool is_MatrixExpr = True # type: bool is_Identity = None # type: FuzzyBool is_Inverse = False is_Transpose = False is_ZeroMatrix = False is_MatAdd = False is_MatMul = False is_commutative = False is_number = False is_symbol = False is_scalar = False kind: MatrixKind = MatrixKind() def __new__(cls, *args, **kwargs): args = map(_sympify, args) return Basic.__new__(cls, *args, **kwargs) # The following is adapted from the core Expr object @property def shape(self) -> tTuple[Expr, Expr]: raise NotImplementedError @property def _add_handler(self): return MatAdd @property def _mul_handler(self): return MatMul def __neg__(self): return MatMul(S.NegativeOne, self).doit() def __abs__(self): raise NotImplementedError @_sympifyit('other', NotImplemented) @call_highest_priority('__radd__') def __add__(self, other): return MatAdd(self, other, check=True).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__add__') def __radd__(self, other): return MatAdd(other, self, check=True).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__rsub__') def __sub__(self, other): return MatAdd(self, -other, check=True).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__sub__') def __rsub__(self, other): return MatAdd(other, -self, check=True).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__rmul__') def __mul__(self, other): return MatMul(self, other).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__rmul__') def __matmul__(self, other): return MatMul(self, other).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__mul__') def __rmul__(self, other): return MatMul(other, self).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__mul__') def __rmatmul__(self, other): return MatMul(other, self).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__rpow__') def __pow__(self, other): return MatPow(self, other).doit() @_sympifyit('other', NotImplemented) @call_highest_priority('__pow__') def __rpow__(self, other): raise NotImplementedError("Matrix Power not defined") @_sympifyit('other', NotImplemented) @call_highest_priority('__rtruediv__') def __truediv__(self, other): return self * other**S.NegativeOne @_sympifyit('other', NotImplemented) @call_highest_priority('__truediv__') def __rtruediv__(self, other): raise NotImplementedError() #return MatMul(other, Pow(self, S.NegativeOne)) @property def rows(self): return self.shape[0] @property def cols(self): return self.shape[1] @property def is_square(self): return self.rows == self.cols def _eval_conjugate(self): from sympy.matrices.expressions.adjoint import Adjoint return Adjoint(Transpose(self)) def as_real_imag(self, deep=True, **hints): real = S.Half * (self + self._eval_conjugate()) im = (self - self._eval_conjugate())/(2*S.ImaginaryUnit) return (real, im) def _eval_inverse(self): return Inverse(self) def _eval_determinant(self): return Determinant(self) def _eval_transpose(self): return Transpose(self) def _eval_power(self, exp): """ Override this in sub-classes to implement simplification of powers. The cases where the exponent is -1, 0, 1 are already covered in MatPow.doit(), so implementations can exclude these cases. """ return MatPow(self, exp) def _eval_simplify(self, **kwargs): if self.is_Atom: return self else: return self.func(*[simplify(x, **kwargs) for x in self.args]) def _eval_adjoint(self): from sympy.matrices.expressions.adjoint import Adjoint return Adjoint(self) def _eval_derivative_n_times(self, x, n): return Basic._eval_derivative_n_times(self, x, n) def _eval_derivative(self, x): # `x` is a scalar: if self.has(x): # See if there are other methods using it: return super()._eval_derivative(x) else: return ZeroMatrix(*self.shape) @classmethod def _check_dim(cls, dim): """Helper function to check invalid matrix dimensions""" ok = check_assumptions(dim, integer=True, nonnegative=True) if ok is False: raise ValueError( "The dimension specification {} should be " "a nonnegative integer.".format(dim)) def _entry(self, i, j, **kwargs): raise NotImplementedError( "Indexing not implemented for %s" % self.__class__.__name__) def adjoint(self): return adjoint(self) def as_coeff_Mul(self, rational=False): """Efficiently extract the coefficient of a product. """ return S.One, self def conjugate(self): return conjugate(self) def transpose(self): from sympy.matrices.expressions.transpose import transpose return transpose(self) @property def T(self): '''Matrix transposition''' return self.transpose() def inverse(self): if not self.is_square: raise NonSquareMatrixError('Inverse of non-square matrix') return self._eval_inverse() def inv(self): return self.inverse() def det(self): from sympy.matrices.expressions.determinant import det return det(self) @property def I(self): return self.inverse() def valid_index(self, i, j): def is_valid(idx): return isinstance(idx, (int, Integer, Symbol, Expr)) return (is_valid(i) and is_valid(j) and (self.rows is None or (0 <= i) != False and (i < self.rows) != False) and (0 <= j) != False and (j < self.cols) != False) def __getitem__(self, key): if not isinstance(key, tuple) and isinstance(key, slice): from sympy.matrices.expressions.slice import MatrixSlice return MatrixSlice(self, key, (0, None, 1)) if isinstance(key, tuple) and len(key) == 2: i, j = key if isinstance(i, slice) or isinstance(j, slice): from sympy.matrices.expressions.slice import MatrixSlice return MatrixSlice(self, i, j) i, j = _sympify(i), _sympify(j) if self.valid_index(i, j) != False: return self._entry(i, j) else: raise IndexError("Invalid indices (%s, %s)" % (i, j)) elif isinstance(key, (SYMPY_INTS, Integer)): # row-wise decomposition of matrix rows, cols = self.shape # allow single indexing if number of columns is known if not isinstance(cols, Integer): raise IndexError(filldedent(''' Single indexing is only supported when the number of columns is known.''')) key = _sympify(key) i = key // cols j = key % cols if self.valid_index(i, j) != False: return self._entry(i, j) else: raise IndexError("Invalid index %s" % key) elif isinstance(key, (Symbol, Expr)): raise IndexError(filldedent(''' Only integers may be used when addressing the matrix with a single index.''')) raise IndexError("Invalid index, wanted %s[i,j]" % self) def _is_shape_symbolic(self) -> bool: return (not isinstance(self.rows, (SYMPY_INTS, Integer)) or not isinstance(self.cols, (SYMPY_INTS, Integer))) def as_explicit(self): """ Returns a dense Matrix with elements represented explicitly Returns an object of type ImmutableDenseMatrix. Examples ======== >>> from sympy import Identity >>> I = Identity(3) >>> I I >>> I.as_explicit() Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) See Also ======== as_mutable: returns mutable Matrix type """ if self._is_shape_symbolic(): raise ValueError( 'Matrix with symbolic shape ' 'cannot be represented explicitly.') from sympy.matrices.immutable import ImmutableDenseMatrix return ImmutableDenseMatrix([[self[i, j] for j in range(self.cols)] for i in range(self.rows)]) def as_mutable(self): """ Returns a dense, mutable matrix with elements represented explicitly Examples ======== >>> from sympy import Identity >>> I = Identity(3) >>> I I >>> I.shape (3, 3) >>> I.as_mutable() Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) See Also ======== as_explicit: returns ImmutableDenseMatrix """ return self.as_explicit().as_mutable() def __array__(self): from numpy import empty a = empty(self.shape, dtype=object) for i in range(self.rows): for j in range(self.cols): a[i, j] = self[i, j] return a def equals(self, other): """ Test elementwise equality between matrices, potentially of different types >>> from sympy import Identity, eye >>> Identity(3).equals(eye(3)) True """ return self.as_explicit().equals(other) def canonicalize(self): return self def as_coeff_mmul(self): return 1, MatMul(self) @staticmethod def from_index_summation(expr, first_index=None, last_index=None, dimensions=None): r""" Parse expression of matrices with explicitly summed indices into a matrix expression without indices, if possible. This transformation expressed in mathematical notation: `\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}` Optional parameter ``first_index``: specify which free index to use as the index starting the expression. Examples ======== >>> from sympy import MatrixSymbol, MatrixExpr, Sum >>> from sympy.abc import i, j, k, l, N >>> A = MatrixSymbol("A", N, N) >>> B = MatrixSymbol("B", N, N) >>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1)) >>> MatrixExpr.from_index_summation(expr) A*B Transposition is detected: >>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1)) >>> MatrixExpr.from_index_summation(expr) A.T*B Detect the trace: >>> expr = Sum(A[i, i], (i, 0, N-1)) >>> MatrixExpr.from_index_summation(expr) Trace(A) More complicated expressions: >>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1)) >>> MatrixExpr.from_index_summation(expr) A*B.T*A.T """ from sympy.tensor.array.expressions.conv_indexed_to_array import convert_indexed_to_array from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix first_indices = [] if first_index is not None: first_indices.append(first_index) if last_index is not None: first_indices.append(last_index) arr = convert_indexed_to_array(expr, first_indices=first_indices) return convert_array_to_matrix(arr) def applyfunc(self, func): from .applyfunc import ElementwiseApplyFunction return ElementwiseApplyFunction(func, self) @dispatch(MatrixExpr, Expr) def _eval_is_eq(lhs, rhs): # noqa:F811 return False @dispatch(MatrixExpr, MatrixExpr) # type: ignore def _eval_is_eq(lhs, rhs): # noqa:F811 if lhs.shape != rhs.shape: return False if (lhs - rhs).is_ZeroMatrix: return True def get_postprocessor(cls): def _postprocessor(expr): # To avoid circular imports, we can't have MatMul/MatAdd on the top level mat_class = {Mul: MatMul, Add: MatAdd}[cls] nonmatrices = [] matrices = [] for term in expr.args: if isinstance(term, MatrixExpr): matrices.append(term) else: nonmatrices.append(term) if not matrices: return cls._from_args(nonmatrices) if nonmatrices: if cls == Mul: for i in range(len(matrices)): if not matrices[i].is_MatrixExpr: # If one of the matrices explicit, absorb the scalar into it # (doit will combine all explicit matrices into one, so it # doesn't matter which) matrices[i] = matrices[i].__mul__(cls._from_args(nonmatrices)) nonmatrices = [] break else: # Maintain the ability to create Add(scalar, matrix) without # raising an exception. That way different algorithms can # replace matrix expressions with non-commutative symbols to # manipulate them like non-commutative scalars. return cls._from_args(nonmatrices + [mat_class(*matrices).doit(deep=False)]) if mat_class == MatAdd: return mat_class(*matrices).doit(deep=False) return mat_class(cls._from_args(nonmatrices), *matrices).doit(deep=False) return _postprocessor Basic._constructor_postprocessor_mapping[MatrixExpr] = { "Mul": [get_postprocessor(Mul)], "Add": [get_postprocessor(Add)], } def _matrix_derivative(expr, x, old_algorithm=False): if isinstance(expr, MatrixBase) or isinstance(x, MatrixBase): # Do not use array expressions for explicit matrices: old_algorithm = True if old_algorithm: return _matrix_derivative_old_algorithm(expr, x) from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array from sympy.tensor.array.expressions.arrayexpr_derivatives import array_derive from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix array_expr = convert_matrix_to_array(expr) diff_array_expr = array_derive(array_expr, x) diff_matrix_expr = convert_array_to_matrix(diff_array_expr) return diff_matrix_expr def _matrix_derivative_old_algorithm(expr, x): from sympy.tensor.array.array_derivatives import ArrayDerivative lines = expr._eval_derivative_matrix_lines(x) parts = [i.build() for i in lines] from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix parts = [[convert_array_to_matrix(j) for j in i] for i in parts] def _get_shape(elem): if isinstance(elem, MatrixExpr): return elem.shape return 1, 1 def get_rank(parts): return sum([j not in (1, None) for i in parts for j in _get_shape(i)]) ranks = [get_rank(i) for i in parts] rank = ranks[0] def contract_one_dims(parts): if len(parts) == 1: return parts[0] else: p1, p2 = parts[:2] if p2.is_Matrix: p2 = p2.T if p1 == Identity(1): pbase = p2 elif p2 == Identity(1): pbase = p1 else: pbase = p1*p2 if len(parts) == 2: return pbase else: # len(parts) > 2 if pbase.is_Matrix: raise ValueError("") return pbase*Mul.fromiter(parts[2:]) if rank <= 2: return Add.fromiter([contract_one_dims(i) for i in parts]) return ArrayDerivative(expr, x) class MatrixElement(Expr): parent = property(lambda self: self.args[0]) i = property(lambda self: self.args[1]) j = property(lambda self: self.args[2]) _diff_wrt = True is_symbol = True is_commutative = True def __new__(cls, name, n, m): n, m = map(_sympify, (n, m)) from sympy.matrices.matrices import MatrixBase if isinstance(name, (MatrixBase,)): if n.is_Integer and m.is_Integer: return name[n, m] if isinstance(name, str): name = Symbol(name) else: name = _sympify(name) if not isinstance(name.kind, MatrixKind): raise TypeError("First argument of MatrixElement should be a matrix") obj = Expr.__new__(cls, name, n, m) return obj def doit(self, **kwargs): deep = kwargs.get('deep', True) if deep: args = [arg.doit(**kwargs) for arg in self.args] else: args = self.args return args[0][args[1], args[2]] @property def indices(self): return self.args[1:] def _eval_derivative(self, v): if not isinstance(v, MatrixElement): from sympy.matrices.matrices import MatrixBase if isinstance(self.parent, MatrixBase): return self.parent.diff(v)[self.i, self.j] return S.Zero M = self.args[0] m, n = self.parent.shape if M == v.args[0]: return KroneckerDelta(self.args[1], v.args[1], (0, m-1)) * \ KroneckerDelta(self.args[2], v.args[2], (0, n-1)) if isinstance(M, Inverse): from sympy.concrete.summations import Sum i, j = self.args[1:] i1, i2 = symbols("z1, z2", cls=Dummy) Y = M.args[0] r1, r2 = Y.shape return -Sum(M[i, i1]*Y[i1, i2].diff(v)*M[i2, j], (i1, 0, r1-1), (i2, 0, r2-1)) if self.has(v.args[0]): return None return S.Zero class MatrixSymbol(MatrixExpr): """Symbolic representation of a Matrix object Creates a SymPy Symbol to represent a Matrix. This matrix has a shape and can be included in Matrix Expressions Examples ======== >>> from sympy import MatrixSymbol, Identity >>> A = MatrixSymbol('A', 3, 4) # A 3 by 4 Matrix >>> B = MatrixSymbol('B', 4, 3) # A 4 by 3 Matrix >>> A.shape (3, 4) >>> 2*A*B + Identity(3) I + 2*A*B """ is_commutative = False is_symbol = True _diff_wrt = True def __new__(cls, name, n, m): n, m = _sympify(n), _sympify(m) cls._check_dim(m) cls._check_dim(n) if isinstance(name, str): name = Str(name) obj = Basic.__new__(cls, name, n, m) return obj @property def shape(self): return self.args[1], self.args[2] @property def name(self): return self.args[0].name def _entry(self, i, j, **kwargs): return MatrixElement(self, i, j) @property def free_symbols(self): return {self} def _eval_simplify(self, **kwargs): return self def _eval_derivative(self, x): # x is a scalar: return ZeroMatrix(self.shape[0], self.shape[1]) def _eval_derivative_matrix_lines(self, x): if self != x: first = ZeroMatrix(x.shape[0], self.shape[0]) if self.shape[0] != 1 else S.Zero second = ZeroMatrix(x.shape[1], self.shape[1]) if self.shape[1] != 1 else S.Zero return [_LeftRightArgs( [first, second], )] else: first = Identity(self.shape[0]) if self.shape[0] != 1 else S.One second = Identity(self.shape[1]) if self.shape[1] != 1 else S.One return [_LeftRightArgs( [first, second], )] def matrix_symbols(expr): return [sym for sym in expr.free_symbols if sym.is_Matrix] class _LeftRightArgs: r""" Helper class to compute matrix derivatives. The logic: when an expression is derived by a matrix `X_{mn}`, two lines of matrix multiplications are created: the one contracted to `m` (first line), and the one contracted to `n` (second line). Transposition flips the side by which new matrices are connected to the lines. The trace connects the end of the two lines. """ def __init__(self, lines, higher=S.One): self._lines = [i for i in lines] self._first_pointer_parent = self._lines self._first_pointer_index = 0 self._first_line_index = 0 self._second_pointer_parent = self._lines self._second_pointer_index = 1 self._second_line_index = 1 self.higher = higher @property def first_pointer(self): return self._first_pointer_parent[self._first_pointer_index] @first_pointer.setter def first_pointer(self, value): self._first_pointer_parent[self._first_pointer_index] = value @property def second_pointer(self): return self._second_pointer_parent[self._second_pointer_index] @second_pointer.setter def second_pointer(self, value): self._second_pointer_parent[self._second_pointer_index] = value def __repr__(self): built = [self._build(i) for i in self._lines] return "_LeftRightArgs(lines=%s, higher=%s)" % ( built, self.higher, ) def transpose(self): self._first_pointer_parent, self._second_pointer_parent = self._second_pointer_parent, self._first_pointer_parent self._first_pointer_index, self._second_pointer_index = self._second_pointer_index, self._first_pointer_index self._first_line_index, self._second_line_index = self._second_line_index, self._first_line_index return self @staticmethod def _build(expr): if isinstance(expr, ExprBuilder): return expr.build() if isinstance(expr, list): if len(expr) == 1: return expr[0] else: return expr[0](*[_LeftRightArgs._build(i) for i in expr[1]]) else: return expr def build(self): data = [self._build(i) for i in self._lines] if self.higher != 1: data += [self._build(self.higher)] data = [i for i in data] return data def matrix_form(self): if self.first != 1 and self.higher != 1: raise ValueError("higher dimensional array cannot be represented") def _get_shape(elem): if isinstance(elem, MatrixExpr): return elem.shape return (None, None) if _get_shape(self.first)[1] != _get_shape(self.second)[1]: # Remove one-dimensional identity matrices: # (this is needed by `a.diff(a)` where `a` is a vector) if _get_shape(self.second) == (1, 1): return self.first*self.second[0, 0] if _get_shape(self.first) == (1, 1): return self.first[1, 1]*self.second.T raise ValueError("incompatible shapes") if self.first != 1: return self.first*self.second.T else: return self.higher def rank(self): """ Number of dimensions different from trivial (warning: not related to matrix rank). """ rank = 0 if self.first != 1: rank += sum([i != 1 for i in self.first.shape]) if self.second != 1: rank += sum([i != 1 for i in self.second.shape]) if self.higher != 1: rank += 2 return rank def _multiply_pointer(self, pointer, other): from ...tensor.array.expressions.array_expressions import ArrayTensorProduct from ...tensor.array.expressions.array_expressions import ArrayContraction subexpr = ExprBuilder( ArrayContraction, [ ExprBuilder( ArrayTensorProduct, [ pointer, other ] ), (1, 2) ], validator=ArrayContraction._validate ) return subexpr def append_first(self, other): self.first_pointer *= other def append_second(self, other): self.second_pointer *= other def _make_matrix(x): from sympy.matrices.immutable import ImmutableDenseMatrix if isinstance(x, MatrixExpr): return x return ImmutableDenseMatrix([[x]]) from .matmul import MatMul from .matadd import MatAdd from .matpow import MatPow from .transpose import Transpose from .inverse import Inverse from .special import ZeroMatrix, Identity from .determinant import Determinant
76f69fb6007d8e0911ffc113ca1cf254bb5fd5926eff0402f996e94d83176461
from sympy.core.sympify import _sympify from sympy.matrices.expressions import MatrixExpr from sympy.core.numbers import I from sympy.core.singleton import S from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt class DFT(MatrixExpr): r""" Returns a discrete Fourier transform matrix. The matrix is scaled with :math:`\frac{1}{\sqrt{n}}` so that it is unitary. Parameters ========== n : integer or Symbol Size of the transform. Examples ======== >>> from sympy.abc import n >>> from sympy.matrices.expressions.fourier import DFT >>> DFT(3) DFT(3) >>> DFT(3).as_explicit() Matrix([ [sqrt(3)/3, sqrt(3)/3, sqrt(3)/3], [sqrt(3)/3, sqrt(3)*exp(-2*I*pi/3)/3, sqrt(3)*exp(2*I*pi/3)/3], [sqrt(3)/3, sqrt(3)*exp(2*I*pi/3)/3, sqrt(3)*exp(-2*I*pi/3)/3]]) >>> DFT(n).shape (n, n) References ========== .. [1] https://en.wikipedia.org/wiki/DFT_matrix """ def __new__(cls, n): n = _sympify(n) cls._check_dim(n) obj = super().__new__(cls, n) return obj n = property(lambda self: self.args[0]) # type: ignore shape = property(lambda self: (self.n, self.n)) # type: ignore def _entry(self, i, j, **kwargs): w = exp(-2*S.Pi*I/self.n) return w**(i*j) / sqrt(self.n) def _eval_inverse(self): return IDFT(self.n) class IDFT(DFT): r""" Returns an inverse discrete Fourier transform matrix. The matrix is scaled with :math:`\frac{1}{\sqrt{n}}` so that it is unitary. Parameters ========== n : integer or Symbol Size of the transform Examples ======== >>> from sympy.matrices.expressions.fourier import DFT, IDFT >>> IDFT(3) IDFT(3) >>> IDFT(4)*DFT(4) I See Also ======== DFT """ def _entry(self, i, j, **kwargs): w = exp(-2*S.Pi*I/self.n) return w**(-i*j) / sqrt(self.n) def _eval_inverse(self): return DFT(self.n)
4bbaf18e4c269f0a6929ae173fd338a7b8ae77599634d17376bcd8d5ad31ec82
"""Implementation of the Kronecker product""" from sympy.core import Mul, prod, sympify from sympy.functions import adjoint from sympy.matrices.common import ShapeError from sympy.matrices.expressions.matexpr import MatrixExpr from sympy.matrices.expressions.transpose import transpose from sympy.matrices.expressions.special import Identity from sympy.matrices.matrices import MatrixBase from sympy.strategies import ( canon, condition, distribute, do_one, exhaust, flatten, typed, unpack) from sympy.strategies.traverse import bottom_up from sympy.utilities import sift from .matadd import MatAdd from .matmul import MatMul from .matpow import MatPow def kronecker_product(*matrices): """ The Kronecker product of two or more arguments. This computes the explicit Kronecker product for subclasses of ``MatrixBase`` i.e. explicit matrices. Otherwise, a symbolic ``KroneckerProduct`` object is returned. Examples ======== For ``MatrixSymbol`` arguments a ``KroneckerProduct`` object is returned. Elements of this matrix can be obtained by indexing, or for MatrixSymbols with known dimension the explicit matrix can be obtained with ``.as_explicit()`` >>> from sympy.matrices import kronecker_product, MatrixSymbol >>> A = MatrixSymbol('A', 2, 2) >>> B = MatrixSymbol('B', 2, 2) >>> kronecker_product(A) A >>> kronecker_product(A, B) KroneckerProduct(A, B) >>> kronecker_product(A, B)[0, 1] A[0, 0]*B[0, 1] >>> kronecker_product(A, B).as_explicit() Matrix([ [A[0, 0]*B[0, 0], A[0, 0]*B[0, 1], A[0, 1]*B[0, 0], A[0, 1]*B[0, 1]], [A[0, 0]*B[1, 0], A[0, 0]*B[1, 1], A[0, 1]*B[1, 0], A[0, 1]*B[1, 1]], [A[1, 0]*B[0, 0], A[1, 0]*B[0, 1], A[1, 1]*B[0, 0], A[1, 1]*B[0, 1]], [A[1, 0]*B[1, 0], A[1, 0]*B[1, 1], A[1, 1]*B[1, 0], A[1, 1]*B[1, 1]]]) For explicit matrices the Kronecker product is returned as a Matrix >>> from sympy.matrices import Matrix, kronecker_product >>> sigma_x = Matrix([ ... [0, 1], ... [1, 0]]) ... >>> Isigma_y = Matrix([ ... [0, 1], ... [-1, 0]]) ... >>> kronecker_product(sigma_x, Isigma_y) Matrix([ [ 0, 0, 0, 1], [ 0, 0, -1, 0], [ 0, 1, 0, 0], [-1, 0, 0, 0]]) See Also ======== KroneckerProduct """ if not matrices: raise TypeError("Empty Kronecker product is undefined") validate(*matrices) if len(matrices) == 1: return matrices[0] else: return KroneckerProduct(*matrices).doit() class KroneckerProduct(MatrixExpr): """ The Kronecker product of two or more arguments. The Kronecker product is a non-commutative product of matrices. Given two matrices of dimension (m, n) and (s, t) it produces a matrix of dimension (m s, n t). This is a symbolic object that simply stores its argument without evaluating it. To actually compute the product, use the function ``kronecker_product()`` or call the ``.doit()`` or ``.as_explicit()`` methods. >>> from sympy.matrices import KroneckerProduct, MatrixSymbol >>> A = MatrixSymbol('A', 5, 5) >>> B = MatrixSymbol('B', 5, 5) >>> isinstance(KroneckerProduct(A, B), KroneckerProduct) True """ is_KroneckerProduct = True def __new__(cls, *args, check=True): args = list(map(sympify, args)) if all(a.is_Identity for a in args): ret = Identity(prod(a.rows for a in args)) if all(isinstance(a, MatrixBase) for a in args): return ret.as_explicit() else: return ret if check: validate(*args) return super().__new__(cls, *args) @property def shape(self): rows, cols = self.args[0].shape for mat in self.args[1:]: rows *= mat.rows cols *= mat.cols return (rows, cols) def _entry(self, i, j, **kwargs): result = 1 for mat in reversed(self.args): i, m = divmod(i, mat.rows) j, n = divmod(j, mat.cols) result *= mat[m, n] return result def _eval_adjoint(self): return KroneckerProduct(*list(map(adjoint, self.args))).doit() def _eval_conjugate(self): return KroneckerProduct(*[a.conjugate() for a in self.args]).doit() def _eval_transpose(self): return KroneckerProduct(*list(map(transpose, self.args))).doit() def _eval_trace(self): from .trace import trace return prod(trace(a) for a in self.args) def _eval_determinant(self): from .determinant import det, Determinant if not all(a.is_square for a in self.args): return Determinant(self) m = self.rows return prod(det(a)**(m/a.rows) for a in self.args) def _eval_inverse(self): try: return KroneckerProduct(*[a.inverse() for a in self.args]) except ShapeError: from sympy.matrices.expressions.inverse import Inverse return Inverse(self) def structurally_equal(self, other): '''Determine whether two matrices have the same Kronecker product structure Examples ======== >>> from sympy import KroneckerProduct, MatrixSymbol, symbols >>> m, n = symbols(r'm, n', integer=True) >>> A = MatrixSymbol('A', m, m) >>> B = MatrixSymbol('B', n, n) >>> C = MatrixSymbol('C', m, m) >>> D = MatrixSymbol('D', n, n) >>> KroneckerProduct(A, B).structurally_equal(KroneckerProduct(C, D)) True >>> KroneckerProduct(A, B).structurally_equal(KroneckerProduct(D, C)) False >>> KroneckerProduct(A, B).structurally_equal(C) False ''' # Inspired by BlockMatrix return (isinstance(other, KroneckerProduct) and self.shape == other.shape and len(self.args) == len(other.args) and all(a.shape == b.shape for (a, b) in zip(self.args, other.args))) def has_matching_shape(self, other): '''Determine whether two matrices have the appropriate structure to bring matrix multiplication inside the KroneckerProdut Examples ======== >>> from sympy import KroneckerProduct, MatrixSymbol, symbols >>> m, n = symbols(r'm, n', integer=True) >>> A = MatrixSymbol('A', m, n) >>> B = MatrixSymbol('B', n, m) >>> KroneckerProduct(A, B).has_matching_shape(KroneckerProduct(B, A)) True >>> KroneckerProduct(A, B).has_matching_shape(KroneckerProduct(A, B)) False >>> KroneckerProduct(A, B).has_matching_shape(A) False ''' return (isinstance(other, KroneckerProduct) and self.cols == other.rows and len(self.args) == len(other.args) and all(a.cols == b.rows for (a, b) in zip(self.args, other.args))) def _eval_expand_kroneckerproduct(self, **hints): return flatten(canon(typed({KroneckerProduct: distribute(KroneckerProduct, MatAdd)}))(self)) def _kronecker_add(self, other): if self.structurally_equal(other): return self.__class__(*[a + b for (a, b) in zip(self.args, other.args)]) else: return self + other def _kronecker_mul(self, other): if self.has_matching_shape(other): return self.__class__(*[a*b for (a, b) in zip(self.args, other.args)]) else: return self * other def doit(self, **kwargs): deep = kwargs.get('deep', True) if deep: args = [arg.doit(**kwargs) for arg in self.args] else: args = self.args return canonicalize(KroneckerProduct(*args)) def validate(*args): if not all(arg.is_Matrix for arg in args): raise TypeError("Mix of Matrix and Scalar symbols") # rules def extract_commutative(kron): c_part = [] nc_part = [] for arg in kron.args: c, nc = arg.args_cnc() c_part.extend(c) nc_part.append(Mul._from_args(nc)) c_part = Mul(*c_part) if c_part != 1: return c_part*KroneckerProduct(*nc_part) return kron def matrix_kronecker_product(*matrices): """Compute the Kronecker product of a sequence of SymPy Matrices. This is the standard Kronecker product of matrices [1]. Parameters ========== matrices : tuple of MatrixBase instances The matrices to take the Kronecker product of. Returns ======= matrix : MatrixBase The Kronecker product matrix. Examples ======== >>> from sympy import Matrix >>> from sympy.matrices.expressions.kronecker import ( ... matrix_kronecker_product) >>> m1 = Matrix([[1,2],[3,4]]) >>> m2 = Matrix([[1,0],[0,1]]) >>> matrix_kronecker_product(m1, m2) Matrix([ [1, 0, 2, 0], [0, 1, 0, 2], [3, 0, 4, 0], [0, 3, 0, 4]]) >>> matrix_kronecker_product(m2, m1) Matrix([ [1, 2, 0, 0], [3, 4, 0, 0], [0, 0, 1, 2], [0, 0, 3, 4]]) References ========== .. [1] https://en.wikipedia.org/wiki/Kronecker_product """ # Make sure we have a sequence of Matrices if not all(isinstance(m, MatrixBase) for m in matrices): raise TypeError( 'Sequence of Matrices expected, got: %s' % repr(matrices) ) # Pull out the first element in the product. matrix_expansion = matrices[-1] # Do the kronecker product working from right to left. for mat in reversed(matrices[:-1]): rows = mat.rows cols = mat.cols # Go through each row appending kronecker product to. # running matrix_expansion. for i in range(rows): start = matrix_expansion*mat[i*cols] # Go through each column joining each item for j in range(cols - 1): start = start.row_join( matrix_expansion*mat[i*cols + j + 1] ) # If this is the first element, make it the start of the # new row. if i == 0: next = start else: next = next.col_join(start) matrix_expansion = next MatrixClass = max(matrices, key=lambda M: M._class_priority).__class__ if isinstance(matrix_expansion, MatrixClass): return matrix_expansion else: return MatrixClass(matrix_expansion) def explicit_kronecker_product(kron): # Make sure we have a sequence of Matrices if not all(isinstance(m, MatrixBase) for m in kron.args): return kron return matrix_kronecker_product(*kron.args) rules = (unpack, explicit_kronecker_product, flatten, extract_commutative) canonicalize = exhaust(condition(lambda x: isinstance(x, KroneckerProduct), do_one(*rules))) def _kronecker_dims_key(expr): if isinstance(expr, KroneckerProduct): return tuple(a.shape for a in expr.args) else: return (0,) def kronecker_mat_add(expr): from functools import reduce args = sift(expr.args, _kronecker_dims_key) nonkrons = args.pop((0,), None) if not args: return expr krons = [reduce(lambda x, y: x._kronecker_add(y), group) for group in args.values()] if not nonkrons: return MatAdd(*krons) else: return MatAdd(*krons) + nonkrons def kronecker_mat_mul(expr): # modified from block matrix code factor, matrices = expr.as_coeff_matrices() i = 0 while i < len(matrices) - 1: A, B = matrices[i:i+2] if isinstance(A, KroneckerProduct) and isinstance(B, KroneckerProduct): matrices[i] = A._kronecker_mul(B) matrices.pop(i+1) else: i += 1 return factor*MatMul(*matrices) def kronecker_mat_pow(expr): if isinstance(expr.base, KroneckerProduct) and all(a.is_square for a in expr.base.args): return KroneckerProduct(*[MatPow(a, expr.exp) for a in expr.base.args]) else: return expr def combine_kronecker(expr): """Combine KronekeckerProduct with expression. If possible write operations on KroneckerProducts of compatible shapes as a single KroneckerProduct. Examples ======== >>> from sympy.matrices.expressions import MatrixSymbol, KroneckerProduct, combine_kronecker >>> from sympy import symbols >>> m, n = symbols(r'm, n', integer=True) >>> A = MatrixSymbol('A', m, n) >>> B = MatrixSymbol('B', n, m) >>> combine_kronecker(KroneckerProduct(A, B)*KroneckerProduct(B, A)) KroneckerProduct(A*B, B*A) >>> combine_kronecker(KroneckerProduct(A, B)+KroneckerProduct(B.T, A.T)) KroneckerProduct(A + B.T, B + A.T) >>> C = MatrixSymbol('C', n, n) >>> D = MatrixSymbol('D', m, m) >>> combine_kronecker(KroneckerProduct(C, D)**m) KroneckerProduct(C**m, D**m) """ def haskron(expr): return isinstance(expr, MatrixExpr) and expr.has(KroneckerProduct) rule = exhaust( bottom_up(exhaust(condition(haskron, typed( {MatAdd: kronecker_mat_add, MatMul: kronecker_mat_mul, MatPow: kronecker_mat_pow}))))) result = rule(expr) doit = getattr(result, 'doit', None) if doit is not None: return doit() else: return result
36d20501fa6823f8e11257e427a582c5ce2bf6258df1504e4772cbc4a13326c1
from sympy.core.sympify import _sympify from sympy.matrices.expressions import MatrixExpr from sympy.core import S, Eq, Ge from sympy.core.mul import Mul from sympy.functions.special.tensor_functions import KroneckerDelta class DiagonalMatrix(MatrixExpr): """DiagonalMatrix(M) will create a matrix expression that behaves as though all off-diagonal elements, `M[i, j]` where `i != j`, are zero. Examples ======== >>> from sympy import MatrixSymbol, DiagonalMatrix, Symbol >>> n = Symbol('n', integer=True) >>> m = Symbol('m', integer=True) >>> D = DiagonalMatrix(MatrixSymbol('x', 2, 3)) >>> D[1, 2] 0 >>> D[1, 1] x[1, 1] The length of the diagonal -- the lesser of the two dimensions of `M` -- is accessed through the `diagonal_length` property: >>> D.diagonal_length 2 >>> DiagonalMatrix(MatrixSymbol('x', n + 1, n)).diagonal_length n When one of the dimensions is symbolic the other will be treated as though it is smaller: >>> tall = DiagonalMatrix(MatrixSymbol('x', n, 3)) >>> tall.diagonal_length 3 >>> tall[10, 1] 0 When the size of the diagonal is not known, a value of None will be returned: >>> DiagonalMatrix(MatrixSymbol('x', n, m)).diagonal_length is None True """ arg = property(lambda self: self.args[0]) shape = property(lambda self: self.arg.shape) # type:ignore @property def diagonal_length(self): r, c = self.shape if r.is_Integer and c.is_Integer: m = min(r, c) elif r.is_Integer and not c.is_Integer: m = r elif c.is_Integer and not r.is_Integer: m = c elif r == c: m = r else: try: m = min(r, c) except TypeError: m = None return m def _entry(self, i, j, **kwargs): if self.diagonal_length is not None: if Ge(i, self.diagonal_length) is S.true: return S.Zero elif Ge(j, self.diagonal_length) is S.true: return S.Zero eq = Eq(i, j) if eq is S.true: return self.arg[i, i] elif eq is S.false: return S.Zero return self.arg[i, j]*KroneckerDelta(i, j) class DiagonalOf(MatrixExpr): """DiagonalOf(M) will create a matrix expression that is equivalent to the diagonal of `M`, represented as a single column matrix. Examples ======== >>> from sympy import MatrixSymbol, DiagonalOf, Symbol >>> n = Symbol('n', integer=True) >>> m = Symbol('m', integer=True) >>> x = MatrixSymbol('x', 2, 3) >>> diag = DiagonalOf(x) >>> diag.shape (2, 1) The diagonal can be addressed like a matrix or vector and will return the corresponding element of the original matrix: >>> diag[1, 0] == diag[1] == x[1, 1] True The length of the diagonal -- the lesser of the two dimensions of `M` -- is accessed through the `diagonal_length` property: >>> diag.diagonal_length 2 >>> DiagonalOf(MatrixSymbol('x', n + 1, n)).diagonal_length n When only one of the dimensions is symbolic the other will be treated as though it is smaller: >>> dtall = DiagonalOf(MatrixSymbol('x', n, 3)) >>> dtall.diagonal_length 3 When the size of the diagonal is not known, a value of None will be returned: >>> DiagonalOf(MatrixSymbol('x', n, m)).diagonal_length is None True """ arg = property(lambda self: self.args[0]) @property def shape(self): r, c = self.arg.shape if r.is_Integer and c.is_Integer: m = min(r, c) elif r.is_Integer and not c.is_Integer: m = r elif c.is_Integer and not r.is_Integer: m = c elif r == c: m = r else: try: m = min(r, c) except TypeError: m = None return m, S.One @property def diagonal_length(self): return self.shape[0] def _entry(self, i, j, **kwargs): return self.arg._entry(i, i, **kwargs) class DiagMatrix(MatrixExpr): """ Turn a vector into a diagonal matrix. """ def __new__(cls, vector): vector = _sympify(vector) obj = MatrixExpr.__new__(cls, vector) shape = vector.shape dim = shape[1] if shape[0] == 1 else shape[0] if vector.shape[0] != 1: obj._iscolumn = True else: obj._iscolumn = False obj._shape = (dim, dim) obj._vector = vector return obj @property def shape(self): return self._shape def _entry(self, i, j, **kwargs): if self._iscolumn: result = self._vector._entry(i, 0, **kwargs) else: result = self._vector._entry(0, j, **kwargs) if i != j: result *= KroneckerDelta(i, j) return result def _eval_transpose(self): return self def as_explicit(self): from sympy.matrices.dense import diag return diag(*list(self._vector.as_explicit())) def doit(self, **hints): from sympy.assumptions import ask, Q from sympy.matrices.expressions.matmul import MatMul from sympy.matrices.expressions.transpose import Transpose from sympy.matrices.dense import eye from sympy.matrices.matrices import MatrixBase vector = self._vector # This accounts for shape (1, 1) and identity matrices, among others: if ask(Q.diagonal(vector)): return vector if isinstance(vector, MatrixBase): ret = eye(max(vector.shape)) for i in range(ret.shape[0]): ret[i, i] = vector[i] return type(vector)(ret) if vector.is_MatMul: matrices = [arg for arg in vector.args if arg.is_Matrix] scalars = [arg for arg in vector.args if arg not in matrices] if scalars: return Mul.fromiter(scalars)*DiagMatrix(MatMul.fromiter(matrices).doit()).doit() if isinstance(vector, Transpose): vector = vector.arg return DiagMatrix(vector) def diagonalize_vector(vector): return DiagMatrix(vector).doit()
5a21b64a1d1b2d7bbb9d9bfc6d28dae27d7598ef8c96507553693a2235eeb052
from sympy.core.basic import Basic from sympy.core.expr import Expr, ExprBuilder from sympy.core.singleton import S from sympy.core.sorting import default_sort_key from sympy.core.symbol import Dummy from sympy.core.sympify import sympify from sympy.matrices.matrices import MatrixBase from sympy.matrices.common import NonSquareMatrixError class Trace(Expr): """Matrix Trace Represents the trace of a matrix expression. Examples ======== >>> from sympy import MatrixSymbol, Trace, eye >>> A = MatrixSymbol('A', 3, 3) >>> Trace(A) Trace(A) >>> Trace(eye(3)) Trace(Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]])) >>> Trace(eye(3)).simplify() 3 """ is_Trace = True is_commutative = True def __new__(cls, mat): mat = sympify(mat) if not mat.is_Matrix: raise TypeError("input to Trace, %s, is not a matrix" % str(mat)) if not mat.is_square: raise NonSquareMatrixError("Trace of a non-square matrix") return Basic.__new__(cls, mat) def _eval_transpose(self): return self def _eval_derivative(self, v): from sympy.concrete.summations import Sum from .matexpr import MatrixElement if isinstance(v, MatrixElement): return self.rewrite(Sum).diff(v) expr = self.doit() if isinstance(expr, Trace): # Avoid looping infinitely: raise NotImplementedError return expr._eval_derivative(v) def _eval_derivative_matrix_lines(self, x): from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayContraction r = self.args[0]._eval_derivative_matrix_lines(x) for lr in r: if lr.higher == 1: lr.higher = ExprBuilder( ArrayContraction, [ ExprBuilder( ArrayTensorProduct, [ lr._lines[0], lr._lines[1], ] ), (1, 3), ], validator=ArrayContraction._validate ) else: # This is not a matrix line: lr.higher = ExprBuilder( ArrayContraction, [ ExprBuilder( ArrayTensorProduct, [ lr._lines[0], lr._lines[1], lr.higher, ] ), (1, 3), (0, 2) ] ) lr._lines = [S.One, S.One] lr._first_pointer_parent = lr._lines lr._second_pointer_parent = lr._lines lr._first_pointer_index = 0 lr._second_pointer_index = 1 return r @property def arg(self): return self.args[0] def doit(self, **kwargs): if kwargs.get('deep', True): arg = self.arg.doit(**kwargs) try: return arg._eval_trace() except (AttributeError, NotImplementedError): return Trace(arg) else: # _eval_trace would go too deep here if isinstance(self.arg, MatrixBase): return trace(self.arg) else: return Trace(self.arg) def as_explicit(self): return Trace(self.arg.as_explicit()).doit() def _normalize(self): # Normalization of trace of matrix products. Use transposition and # cyclic properties of traces to make sure the arguments of the matrix # product are sorted and the first argument is not a trasposition. from sympy.matrices.expressions.matmul import MatMul from sympy.matrices.expressions.transpose import Transpose trace_arg = self.arg if isinstance(trace_arg, MatMul): def get_arg_key(x): a = trace_arg.args[x] if isinstance(a, Transpose): a = a.arg return default_sort_key(a) indmin = min(range(len(trace_arg.args)), key=get_arg_key) if isinstance(trace_arg.args[indmin], Transpose): trace_arg = Transpose(trace_arg).doit() indmin = min(range(len(trace_arg.args)), key=lambda x: default_sort_key(trace_arg.args[x])) trace_arg = MatMul.fromiter(trace_arg.args[indmin:] + trace_arg.args[:indmin]) return Trace(trace_arg) return self def _eval_rewrite_as_Sum(self, expr, **kwargs): from sympy.concrete.summations import Sum i = Dummy('i') return Sum(self.arg[i, i], (i, 0, self.arg.rows-1)).doit() def trace(expr): """Trace of a Matrix. Sum of the diagonal elements. Examples ======== >>> from sympy import trace, Symbol, MatrixSymbol, eye >>> n = Symbol('n') >>> X = MatrixSymbol('X', n, n) # A square matrix >>> trace(2*X) 2*Trace(X) >>> trace(eye(3)) 3 """ return Trace(expr).doit()
f5b524849c8edd129c1e2769d144f56cbc7ca674b9682067f2fe89620da6ea16
from sympy.core import Mul, sympify from sympy.core.add import Add from sympy.core.expr import ExprBuilder from sympy.core.sorting import default_sort_key from sympy.matrices.common import ShapeError from sympy.matrices.expressions.matexpr import MatrixExpr from sympy.matrices.expressions.special import ZeroMatrix, OneMatrix from sympy.strategies import ( unpack, flatten, condition, exhaust, rm_id, sort ) def hadamard_product(*matrices): """ Return the elementwise (aka Hadamard) product of matrices. Examples ======== >>> from sympy.matrices import hadamard_product, MatrixSymbol >>> A = MatrixSymbol('A', 2, 3) >>> B = MatrixSymbol('B', 2, 3) >>> hadamard_product(A) A >>> hadamard_product(A, B) HadamardProduct(A, B) >>> hadamard_product(A, B)[0, 1] A[0, 1]*B[0, 1] """ if not matrices: raise TypeError("Empty Hadamard product is undefined") validate(*matrices) if len(matrices) == 1: return matrices[0] else: matrices = [i for i in matrices if not i.is_Identity] return HadamardProduct(*matrices).doit() class HadamardProduct(MatrixExpr): """ Elementwise product of matrix expressions Examples ======== Hadamard product for matrix symbols: >>> from sympy.matrices import hadamard_product, HadamardProduct, MatrixSymbol >>> A = MatrixSymbol('A', 5, 5) >>> B = MatrixSymbol('B', 5, 5) >>> isinstance(hadamard_product(A, B), HadamardProduct) True Notes ===== This is a symbolic object that simply stores its argument without evaluating it. To actually compute the product, use the function ``hadamard_product()`` or ``HadamardProduct.doit`` """ is_HadamardProduct = True def __new__(cls, *args, evaluate=False, check=True): args = list(map(sympify, args)) if check: validate(*args) obj = super().__new__(cls, *args) if evaluate: obj = obj.doit(deep=False) return obj @property def shape(self): return self.args[0].shape def _entry(self, i, j, **kwargs): return Mul(*[arg._entry(i, j, **kwargs) for arg in self.args]) def _eval_transpose(self): from sympy.matrices.expressions.transpose import transpose return HadamardProduct(*list(map(transpose, self.args))) def doit(self, **ignored): expr = self.func(*[i.doit(**ignored) for i in self.args]) # Check for explicit matrices: from sympy.matrices.matrices import MatrixBase from sympy.matrices.immutable import ImmutableMatrix explicit = [i for i in expr.args if isinstance(i, MatrixBase)] if explicit: remainder = [i for i in expr.args if i not in explicit] expl_mat = ImmutableMatrix([ Mul.fromiter(i) for i in zip(*explicit) ]).reshape(*self.shape) expr = HadamardProduct(*([expl_mat] + remainder)) return canonicalize(expr) def _eval_derivative(self, x): terms = [] args = list(self.args) for i in range(len(args)): factors = args[:i] + [args[i].diff(x)] + args[i+1:] terms.append(hadamard_product(*factors)) return Add.fromiter(terms) def _eval_derivative_matrix_lines(self, x): from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct from sympy.matrices.expressions.matexpr import _make_matrix with_x_ind = [i for i, arg in enumerate(self.args) if arg.has(x)] lines = [] for ind in with_x_ind: left_args = self.args[:ind] right_args = self.args[ind+1:] d = self.args[ind]._eval_derivative_matrix_lines(x) hadam = hadamard_product(*(right_args + left_args)) diagonal = [(0, 2), (3, 4)] diagonal = [e for j, e in enumerate(diagonal) if self.shape[j] != 1] for i in d: l1 = i._lines[i._first_line_index] l2 = i._lines[i._second_line_index] subexpr = ExprBuilder( ArrayDiagonal, [ ExprBuilder( ArrayTensorProduct, [ ExprBuilder(_make_matrix, [l1]), hadam, ExprBuilder(_make_matrix, [l2]), ] ), *diagonal], ) i._first_pointer_parent = subexpr.args[0].args[0].args i._first_pointer_index = 0 i._second_pointer_parent = subexpr.args[0].args[2].args i._second_pointer_index = 0 i._lines = [subexpr] lines.append(i) return lines def validate(*args): if not all(arg.is_Matrix for arg in args): raise TypeError("Mix of Matrix and Scalar symbols") A = args[0] for B in args[1:]: if A.shape != B.shape: raise ShapeError("Matrices %s and %s are not aligned" % (A, B)) # TODO Implement algorithm for rewriting Hadamard product as diagonal matrix # if matmul identy matrix is multiplied. def canonicalize(x): """Canonicalize the Hadamard product ``x`` with mathematical properties. Examples ======== >>> from sympy.matrices.expressions import MatrixSymbol, HadamardProduct >>> from sympy.matrices.expressions import OneMatrix, ZeroMatrix >>> from sympy.matrices.expressions.hadamard import canonicalize >>> from sympy import init_printing >>> init_printing(use_unicode=False) >>> A = MatrixSymbol('A', 2, 2) >>> B = MatrixSymbol('B', 2, 2) >>> C = MatrixSymbol('C', 2, 2) Hadamard product associativity: >>> X = HadamardProduct(A, HadamardProduct(B, C)) >>> X A.*(B.*C) >>> canonicalize(X) A.*B.*C Hadamard product commutativity: >>> X = HadamardProduct(A, B) >>> Y = HadamardProduct(B, A) >>> X A.*B >>> Y B.*A >>> canonicalize(X) A.*B >>> canonicalize(Y) A.*B Hadamard product identity: >>> X = HadamardProduct(A, OneMatrix(2, 2)) >>> X A.*1 >>> canonicalize(X) A Absorbing element of Hadamard product: >>> X = HadamardProduct(A, ZeroMatrix(2, 2)) >>> X A.*0 >>> canonicalize(X) 0 Rewriting to Hadamard Power >>> X = HadamardProduct(A, A, A) >>> X A.*A.*A >>> canonicalize(X) .3 A Notes ===== As the Hadamard product is associative, nested products can be flattened. The Hadamard product is commutative so that factors can be sorted for canonical form. A matrix of only ones is an identity for Hadamard product, so every matrices of only ones can be removed. Any zero matrix will make the whole product a zero matrix. Duplicate elements can be collected and rewritten as HadamardPower References ========== .. [1] https://en.wikipedia.org/wiki/Hadamard_product_(matrices) """ # Associativity rule = condition( lambda x: isinstance(x, HadamardProduct), flatten ) fun = exhaust(rule) x = fun(x) # Identity fun = condition( lambda x: isinstance(x, HadamardProduct), rm_id(lambda x: isinstance(x, OneMatrix)) ) x = fun(x) # Absorbing by Zero Matrix def absorb(x): if any(isinstance(c, ZeroMatrix) for c in x.args): return ZeroMatrix(*x.shape) else: return x fun = condition( lambda x: isinstance(x, HadamardProduct), absorb ) x = fun(x) # Rewriting with HadamardPower if isinstance(x, HadamardProduct): from collections import Counter tally = Counter(x.args) new_arg = [] for base, exp in tally.items(): if exp == 1: new_arg.append(base) else: new_arg.append(HadamardPower(base, exp)) x = HadamardProduct(*new_arg) # Commutativity fun = condition( lambda x: isinstance(x, HadamardProduct), sort(default_sort_key) ) x = fun(x) # Unpacking x = unpack(x) return x def hadamard_power(base, exp): base = sympify(base) exp = sympify(exp) if exp == 1: return base if not base.is_Matrix: return base**exp if exp.is_Matrix: raise ValueError("cannot raise expression to a matrix") return HadamardPower(base, exp) class HadamardPower(MatrixExpr): r""" Elementwise power of matrix expressions Parameters ========== base : scalar or matrix exp : scalar or matrix Notes ===== There are four definitions for the hadamard power which can be used. Let's consider `A, B` as `(m, n)` matrices, and `a, b` as scalars. Matrix raised to a scalar exponent: .. math:: A^{\circ b} = \begin{bmatrix} A_{0, 0}^b & A_{0, 1}^b & \cdots & A_{0, n-1}^b \\ A_{1, 0}^b & A_{1, 1}^b & \cdots & A_{1, n-1}^b \\ \vdots & \vdots & \ddots & \vdots \\ A_{m-1, 0}^b & A_{m-1, 1}^b & \cdots & A_{m-1, n-1}^b \end{bmatrix} Scalar raised to a matrix exponent: .. math:: a^{\circ B} = \begin{bmatrix} a^{B_{0, 0}} & a^{B_{0, 1}} & \cdots & a^{B_{0, n-1}} \\ a^{B_{1, 0}} & a^{B_{1, 1}} & \cdots & a^{B_{1, n-1}} \\ \vdots & \vdots & \ddots & \vdots \\ a^{B_{m-1, 0}} & a^{B_{m-1, 1}} & \cdots & a^{B_{m-1, n-1}} \end{bmatrix} Matrix raised to a matrix exponent: .. math:: A^{\circ B} = \begin{bmatrix} A_{0, 0}^{B_{0, 0}} & A_{0, 1}^{B_{0, 1}} & \cdots & A_{0, n-1}^{B_{0, n-1}} \\ A_{1, 0}^{B_{1, 0}} & A_{1, 1}^{B_{1, 1}} & \cdots & A_{1, n-1}^{B_{1, n-1}} \\ \vdots & \vdots & \ddots & \vdots \\ A_{m-1, 0}^{B_{m-1, 0}} & A_{m-1, 1}^{B_{m-1, 1}} & \cdots & A_{m-1, n-1}^{B_{m-1, n-1}} \end{bmatrix} Scalar raised to a scalar exponent: .. math:: a^{\circ b} = a^b """ def __new__(cls, base, exp): base = sympify(base) exp = sympify(exp) if base.is_scalar and exp.is_scalar: return base ** exp if base.is_Matrix and exp.is_Matrix and base.shape != exp.shape: raise ValueError( 'The shape of the base {} and ' 'the shape of the exponent {} do not match.' .format(base.shape, exp.shape) ) obj = super().__new__(cls, base, exp) return obj @property def base(self): return self._args[0] @property def exp(self): return self._args[1] @property def shape(self): if self.base.is_Matrix: return self.base.shape return self.exp.shape def _entry(self, i, j, **kwargs): base = self.base exp = self.exp if base.is_Matrix: a = base._entry(i, j, **kwargs) elif base.is_scalar: a = base else: raise ValueError( 'The base {} must be a scalar or a matrix.'.format(base)) if exp.is_Matrix: b = exp._entry(i, j, **kwargs) elif exp.is_scalar: b = exp else: raise ValueError( 'The exponent {} must be a scalar or a matrix.'.format(exp)) return a ** b def _eval_transpose(self): from sympy.matrices.expressions.transpose import transpose return HadamardPower(transpose(self.base), self.exp) def _eval_derivative(self, x): from sympy.functions.elementary.exponential import log dexp = self.exp.diff(x) logbase = self.base.applyfunc(log) dlbase = logbase.diff(x) return hadamard_product( dexp*logbase + self.exp*dlbase, self ) def _eval_derivative_matrix_lines(self, x): from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal from sympy.matrices.expressions.matexpr import _make_matrix lr = self.base._eval_derivative_matrix_lines(x) for i in lr: diagonal = [(1, 2), (3, 4)] diagonal = [e for j, e in enumerate(diagonal) if self.base.shape[j] != 1] l1 = i._lines[i._first_line_index] l2 = i._lines[i._second_line_index] subexpr = ExprBuilder( ArrayDiagonal, [ ExprBuilder( ArrayTensorProduct, [ ExprBuilder(_make_matrix, [l1]), self.exp*hadamard_power(self.base, self.exp-1), ExprBuilder(_make_matrix, [l2]), ] ), *diagonal], validator=ArrayDiagonal._validate ) i._first_pointer_parent = subexpr.args[0].args[0].args i._first_pointer_index = 0 i._first_line_index = 0 i._second_pointer_parent = subexpr.args[0].args[2].args i._second_pointer_index = 0 i._second_line_index = 0 i._lines = [subexpr] return lr
0e0261b29ad66c54b2dede932949d770b117fed0decabf74c2c0ab31a9a0ad9f
from sympy.assumptions.ask import (Q, ask) from sympy.core import Basic, Add, Mul, S from sympy.core.sympify import _sympify from sympy.functions.elementary.complexes import re, im from sympy.strategies import typed, exhaust, condition, do_one, unpack from sympy.strategies.traverse import bottom_up from sympy.utilities.iterables import is_sequence, sift from sympy.utilities.misc import filldedent from sympy.matrices import Matrix, ShapeError from sympy.matrices.common import NonInvertibleMatrixError from sympy.matrices.expressions.determinant import det, Determinant from sympy.matrices.expressions.inverse import Inverse from sympy.matrices.expressions.matadd import MatAdd from sympy.matrices.expressions.matexpr import MatrixExpr, MatrixElement from sympy.matrices.expressions.matmul import MatMul from sympy.matrices.expressions.matpow import MatPow from sympy.matrices.expressions.slice import MatrixSlice from sympy.matrices.expressions.special import ZeroMatrix, Identity from sympy.matrices.expressions.trace import trace from sympy.matrices.expressions.transpose import Transpose, transpose class BlockMatrix(MatrixExpr): """A BlockMatrix is a Matrix comprised of other matrices. The submatrices are stored in a SymPy Matrix object but accessed as part of a Matrix Expression >>> from sympy import (MatrixSymbol, BlockMatrix, symbols, ... Identity, ZeroMatrix, block_collapse) >>> n,m,l = symbols('n m l') >>> X = MatrixSymbol('X', n, n) >>> Y = MatrixSymbol('Y', m, m) >>> Z = MatrixSymbol('Z', n, m) >>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]]) >>> print(B) Matrix([ [X, Z], [0, Y]]) >>> C = BlockMatrix([[Identity(n), Z]]) >>> print(C) Matrix([[I, Z]]) >>> print(block_collapse(C*B)) Matrix([[X, Z + Z*Y]]) Some matrices might be comprised of rows of blocks with the matrices in each row having the same height and the rows all having the same total number of columns but not having the same number of columns for each matrix in each row. In this case, the matrix is not a block matrix and should be instantiated by Matrix. >>> from sympy import ones, Matrix >>> dat = [ ... [ones(3,2), ones(3,3)*2], ... [ones(2,3)*3, ones(2,2)*4]] ... >>> BlockMatrix(dat) Traceback (most recent call last): ... ValueError: Although this matrix is comprised of blocks, the blocks do not fill the matrix in a size-symmetric fashion. To create a full matrix from these arguments, pass them directly to Matrix. >>> Matrix(dat) Matrix([ [1, 1, 2, 2, 2], [1, 1, 2, 2, 2], [1, 1, 2, 2, 2], [3, 3, 3, 4, 4], [3, 3, 3, 4, 4]]) See Also ======== sympy.matrices.matrices.MatrixBase.irregular """ def __new__(cls, *args, **kwargs): from sympy.matrices.immutable import ImmutableDenseMatrix isMat = lambda i: getattr(i, 'is_Matrix', False) if len(args) != 1 or \ not is_sequence(args[0]) or \ len({isMat(r) for r in args[0]}) != 1: raise ValueError(filldedent(''' expecting a sequence of 1 or more rows containing Matrices.''')) rows = args[0] if args else [] if not isMat(rows): if rows and isMat(rows[0]): rows = [rows] # rows is not list of lists or [] # regularity check # same number of matrices in each row blocky = ok = len({len(r) for r in rows}) == 1 if ok: # same number of rows for each matrix in a row for r in rows: ok = len({i.rows for i in r}) == 1 if not ok: break blocky = ok if ok: # same number of cols for each matrix in each col for c in range(len(rows[0])): ok = len({rows[i][c].cols for i in range(len(rows))}) == 1 if not ok: break if not ok: # same total cols in each row ok = len({ sum([i.cols for i in r]) for r in rows}) == 1 if blocky and ok: raise ValueError(filldedent(''' Although this matrix is comprised of blocks, the blocks do not fill the matrix in a size-symmetric fashion. To create a full matrix from these arguments, pass them directly to Matrix.''')) raise ValueError(filldedent(''' When there are not the same number of rows in each row's matrices or there are not the same number of total columns in each row, the matrix is not a block matrix. If this matrix is known to consist of blocks fully filling a 2-D space then see Matrix.irregular.''')) mat = ImmutableDenseMatrix(rows, evaluate=False) obj = Basic.__new__(cls, mat) return obj @property def shape(self): numrows = numcols = 0 M = self.blocks for i in range(M.shape[0]): numrows += M[i, 0].shape[0] for i in range(M.shape[1]): numcols += M[0, i].shape[1] return (numrows, numcols) @property def blockshape(self): return self.blocks.shape @property def blocks(self): return self.args[0] @property def rowblocksizes(self): return [self.blocks[i, 0].rows for i in range(self.blockshape[0])] @property def colblocksizes(self): return [self.blocks[0, i].cols for i in range(self.blockshape[1])] def structurally_equal(self, other): return (isinstance(other, BlockMatrix) and self.shape == other.shape and self.blockshape == other.blockshape and self.rowblocksizes == other.rowblocksizes and self.colblocksizes == other.colblocksizes) def _blockmul(self, other): if (isinstance(other, BlockMatrix) and self.colblocksizes == other.rowblocksizes): return BlockMatrix(self.blocks*other.blocks) return self * other def _blockadd(self, other): if (isinstance(other, BlockMatrix) and self.structurally_equal(other)): return BlockMatrix(self.blocks + other.blocks) return self + other def _eval_transpose(self): # Flip all the individual matrices matrices = [transpose(matrix) for matrix in self.blocks] # Make a copy M = Matrix(self.blockshape[0], self.blockshape[1], matrices) # Transpose the block structure M = M.transpose() return BlockMatrix(M) def _eval_trace(self): if self.rowblocksizes == self.colblocksizes: return Add(*[trace(self.blocks[i, i]) for i in range(self.blockshape[0])]) raise NotImplementedError( "Can't perform trace of irregular blockshape") def _eval_determinant(self): if self.blockshape == (1, 1): return det(self.blocks[0, 0]) if self.blockshape == (2, 2): [[A, B], [C, D]] = self.blocks.tolist() if ask(Q.invertible(A)): return det(A)*det(D - C*A.I*B) elif ask(Q.invertible(D)): return det(D)*det(A - B*D.I*C) return Determinant(self) def as_real_imag(self): real_matrices = [re(matrix) for matrix in self.blocks] real_matrices = Matrix(self.blockshape[0], self.blockshape[1], real_matrices) im_matrices = [im(matrix) for matrix in self.blocks] im_matrices = Matrix(self.blockshape[0], self.blockshape[1], im_matrices) return (real_matrices, im_matrices) def transpose(self): """Return transpose of matrix. Examples ======== >>> from sympy import MatrixSymbol, BlockMatrix, ZeroMatrix >>> from sympy.abc import m, n >>> X = MatrixSymbol('X', n, n) >>> Y = MatrixSymbol('Y', m, m) >>> Z = MatrixSymbol('Z', n, m) >>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]]) >>> B.transpose() Matrix([ [X.T, 0], [Z.T, Y.T]]) >>> _.transpose() Matrix([ [X, Z], [0, Y]]) """ return self._eval_transpose() def schur(self, mat = 'A', generalized = False): """Return the Schur Complement of the 2x2 BlockMatrix Parameters ========== mat : String, optional The matrix with respect to which the Schur Complement is calculated. 'A' is used by default generalized : bool, optional If True, returns the generalized Schur Component which uses Moore-Penrose Inverse Examples ======== >>> from sympy import symbols, MatrixSymbol, BlockMatrix >>> m, n = symbols('m n') >>> A = MatrixSymbol('A', n, n) >>> B = MatrixSymbol('B', n, m) >>> C = MatrixSymbol('C', m, n) >>> D = MatrixSymbol('D', m, m) >>> X = BlockMatrix([[A, B], [C, D]]) The default Schur Complement is evaluated with "A" >>> X.schur() -C*A**(-1)*B + D >>> X.schur('D') A - B*D**(-1)*C Schur complement with non-invertible matrices is not defined. Instead, the generalized Schur complement can be calculated which uses the Moore-Penrose Inverse. To achieve this, `generalized` must be set to `True` >>> X.schur('B', generalized=True) C - D*(B.T*B)**(-1)*B.T*A >>> X.schur('C', generalized=True) -A*(C.T*C)**(-1)*C.T*D + B Returns ======= M : Matrix The Schur Complement Matrix Raises ====== ShapeError If the block matrix is not a 2x2 matrix NonInvertibleMatrixError If given matrix is non-invertible References ========== .. [1] Wikipedia Article on Schur Component : https://en.wikipedia.org/wiki/Schur_complement See Also ======== sympy.matrices.matrices.MatrixBase.pinv """ if self.blockshape == (2, 2): [[A, B], [C, D]] = self.blocks.tolist() d={'A' : A, 'B' : B, 'C' : C, 'D' : D} try: inv = (d[mat].T*d[mat]).inv()*d[mat].T if generalized else d[mat].inv() if mat == 'A': return D - C * inv * B elif mat == 'B': return C - D * inv * A elif mat == 'C': return B - A * inv * D elif mat == 'D': return A - B * inv * C #For matrices where no sub-matrix is square return self except NonInvertibleMatrixError: raise NonInvertibleMatrixError('The given matrix is not invertible. Please set generalized=True \ to compute the generalized Schur Complement which uses Moore-Penrose Inverse') else: raise ShapeError('Schur Complement can only be calculated for 2x2 block matrices') def LDUdecomposition(self): """Returns the Block LDU decomposition of a 2x2 Block Matrix Returns ======= (L, D, U) : Matrices L : Lower Diagonal Matrix D : Diagonal Matrix U : Upper Diagonal Matrix Examples ======== >>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse >>> m, n = symbols('m n') >>> A = MatrixSymbol('A', n, n) >>> B = MatrixSymbol('B', n, m) >>> C = MatrixSymbol('C', m, n) >>> D = MatrixSymbol('D', m, m) >>> X = BlockMatrix([[A, B], [C, D]]) >>> L, D, U = X.LDUdecomposition() >>> block_collapse(L*D*U) Matrix([ [A, B], [C, D]]) Raises ====== ShapeError If the block matrix is not a 2x2 matrix NonInvertibleMatrixError If the matrix "A" is non-invertible See Also ======== sympy.matrices.expressions.blockmatrix.BlockMatrix.UDLdecomposition sympy.matrices.expressions.blockmatrix.BlockMatrix.LUdecomposition """ if self.blockshape == (2,2): [[A, B], [C, D]] = self.blocks.tolist() try: AI = A.I except NonInvertibleMatrixError: raise NonInvertibleMatrixError('Block LDU decomposition cannot be calculated when\ "A" is singular') Ip = Identity(B.shape[0]) Iq = Identity(B.shape[1]) Z = ZeroMatrix(*B.shape) L = BlockMatrix([[Ip, Z], [C*AI, Iq]]) D = BlockDiagMatrix(A, self.schur()) U = BlockMatrix([[Ip, AI*B],[Z.T, Iq]]) return L, D, U else: raise ShapeError("Block LDU decomposition is supported only for 2x2 block matrices") def UDLdecomposition(self): """Returns the Block UDL decomposition of a 2x2 Block Matrix Returns ======= (U, D, L) : Matrices U : Upper Diagonal Matrix D : Diagonal Matrix L : Lower Diagonal Matrix Examples ======== >>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse >>> m, n = symbols('m n') >>> A = MatrixSymbol('A', n, n) >>> B = MatrixSymbol('B', n, m) >>> C = MatrixSymbol('C', m, n) >>> D = MatrixSymbol('D', m, m) >>> X = BlockMatrix([[A, B], [C, D]]) >>> U, D, L = X.UDLdecomposition() >>> block_collapse(U*D*L) Matrix([ [A, B], [C, D]]) Raises ====== ShapeError If the block matrix is not a 2x2 matrix NonInvertibleMatrixError If the matrix "D" is non-invertible See Also ======== sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition sympy.matrices.expressions.blockmatrix.BlockMatrix.LUdecomposition """ if self.blockshape == (2,2): [[A, B], [C, D]] = self.blocks.tolist() try: DI = D.I except NonInvertibleMatrixError: raise NonInvertibleMatrixError('Block UDL decomposition cannot be calculated when\ "D" is singular') Ip = Identity(A.shape[0]) Iq = Identity(B.shape[1]) Z = ZeroMatrix(*B.shape) U = BlockMatrix([[Ip, B*DI], [Z.T, Iq]]) D = BlockDiagMatrix(self.schur('D'), D) L = BlockMatrix([[Ip, Z],[DI*C, Iq]]) return U, D, L else: raise ShapeError("Block UDL decomposition is supported only for 2x2 block matrices") def LUdecomposition(self): """Returns the Block LU decomposition of a 2x2 Block Matrix Returns ======= (L, U) : Matrices L : Lower Diagonal Matrix U : Upper Diagonal Matrix Examples ======== >>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse >>> m, n = symbols('m n') >>> A = MatrixSymbol('A', n, n) >>> B = MatrixSymbol('B', n, m) >>> C = MatrixSymbol('C', m, n) >>> D = MatrixSymbol('D', m, m) >>> X = BlockMatrix([[A, B], [C, D]]) >>> L, U = X.LUdecomposition() >>> block_collapse(L*U) Matrix([ [A, B], [C, D]]) Raises ====== ShapeError If the block matrix is not a 2x2 matrix NonInvertibleMatrixError If the matrix "A" is non-invertible See Also ======== sympy.matrices.expressions.blockmatrix.BlockMatrix.UDLdecomposition sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition """ if self.blockshape == (2,2): [[A, B], [C, D]] = self.blocks.tolist() try: A = A**0.5 AI = A.I except NonInvertibleMatrixError: raise NonInvertibleMatrixError('Block LU decomposition cannot be calculated when\ "A" is singular') Z = ZeroMatrix(*B.shape) Q = self.schur()**0.5 L = BlockMatrix([[A, Z], [C*AI, Q]]) U = BlockMatrix([[A, AI*B],[Z.T, Q]]) return L, U else: raise ShapeError("Block LU decomposition is supported only for 2x2 block matrices") def _entry(self, i, j, **kwargs): # Find row entry orig_i, orig_j = i, j for row_block, numrows in enumerate(self.rowblocksizes): cmp = i < numrows if cmp == True: break elif cmp == False: i -= numrows elif row_block < self.blockshape[0] - 1: # Can't tell which block and it's not the last one, return unevaluated return MatrixElement(self, orig_i, orig_j) for col_block, numcols in enumerate(self.colblocksizes): cmp = j < numcols if cmp == True: break elif cmp == False: j -= numcols elif col_block < self.blockshape[1] - 1: return MatrixElement(self, orig_i, orig_j) return self.blocks[row_block, col_block][i, j] @property def is_Identity(self): if self.blockshape[0] != self.blockshape[1]: return False for i in range(self.blockshape[0]): for j in range(self.blockshape[1]): if i==j and not self.blocks[i, j].is_Identity: return False if i!=j and not self.blocks[i, j].is_ZeroMatrix: return False return True @property def is_structurally_symmetric(self): return self.rowblocksizes == self.colblocksizes def equals(self, other): if self == other: return True if (isinstance(other, BlockMatrix) and self.blocks == other.blocks): return True return super().equals(other) class BlockDiagMatrix(BlockMatrix): """A sparse matrix with block matrices along its diagonals Examples ======== >>> from sympy import MatrixSymbol, BlockDiagMatrix, symbols >>> n, m, l = symbols('n m l') >>> X = MatrixSymbol('X', n, n) >>> Y = MatrixSymbol('Y', m, m) >>> BlockDiagMatrix(X, Y) Matrix([ [X, 0], [0, Y]]) Notes ===== If you want to get the individual diagonal blocks, use :meth:`get_diag_blocks`. See Also ======== sympy.matrices.dense.diag """ def __new__(cls, *mats): return Basic.__new__(BlockDiagMatrix, *[_sympify(m) for m in mats]) @property def diag(self): return self.args @property def blocks(self): from sympy.matrices.immutable import ImmutableDenseMatrix mats = self.args data = [[mats[i] if i == j else ZeroMatrix(mats[i].rows, mats[j].cols) for j in range(len(mats))] for i in range(len(mats))] return ImmutableDenseMatrix(data, evaluate=False) @property def shape(self): return (sum(block.rows for block in self.args), sum(block.cols for block in self.args)) @property def blockshape(self): n = len(self.args) return (n, n) @property def rowblocksizes(self): return [block.rows for block in self.args] @property def colblocksizes(self): return [block.cols for block in self.args] def _all_square_blocks(self): """Returns true if all blocks are square""" return all(mat.is_square for mat in self.args) def _eval_determinant(self): if self._all_square_blocks(): return Mul(*[det(mat) for mat in self.args]) # At least one block is non-square. Since the entire matrix must be square we know there must # be at least two blocks in this matrix, in which case the entire matrix is necessarily rank-deficient return S.Zero def _eval_inverse(self, expand='ignored'): if self._all_square_blocks(): return BlockDiagMatrix(*[mat.inverse() for mat in self.args]) # See comment in _eval_determinant() raise NonInvertibleMatrixError('Matrix det == 0; not invertible.') def _eval_transpose(self): return BlockDiagMatrix(*[mat.transpose() for mat in self.args]) def _blockmul(self, other): if (isinstance(other, BlockDiagMatrix) and self.colblocksizes == other.rowblocksizes): return BlockDiagMatrix(*[a*b for a, b in zip(self.args, other.args)]) else: return BlockMatrix._blockmul(self, other) def _blockadd(self, other): if (isinstance(other, BlockDiagMatrix) and self.blockshape == other.blockshape and self.rowblocksizes == other.rowblocksizes and self.colblocksizes == other.colblocksizes): return BlockDiagMatrix(*[a + b for a, b in zip(self.args, other.args)]) else: return BlockMatrix._blockadd(self, other) def get_diag_blocks(self): """Return the list of diagonal blocks of the matrix. Examples ======== >>> from sympy.matrices import BlockDiagMatrix, Matrix >>> A = Matrix([[1, 2], [3, 4]]) >>> B = Matrix([[5, 6], [7, 8]]) >>> M = BlockDiagMatrix(A, B) How to get diagonal blocks from the block diagonal matrix: >>> diag_blocks = M.get_diag_blocks() >>> diag_blocks[0] Matrix([ [1, 2], [3, 4]]) >>> diag_blocks[1] Matrix([ [5, 6], [7, 8]]) """ return self.args def block_collapse(expr): """Evaluates a block matrix expression >>> from sympy import MatrixSymbol, BlockMatrix, symbols, Identity, ZeroMatrix, block_collapse >>> n,m,l = symbols('n m l') >>> X = MatrixSymbol('X', n, n) >>> Y = MatrixSymbol('Y', m, m) >>> Z = MatrixSymbol('Z', n, m) >>> B = BlockMatrix([[X, Z], [ZeroMatrix(m, n), Y]]) >>> print(B) Matrix([ [X, Z], [0, Y]]) >>> C = BlockMatrix([[Identity(n), Z]]) >>> print(C) Matrix([[I, Z]]) >>> print(block_collapse(C*B)) Matrix([[X, Z + Z*Y]]) """ from sympy.strategies.util import expr_fns hasbm = lambda expr: isinstance(expr, MatrixExpr) and expr.has(BlockMatrix) conditioned_rl = condition( hasbm, typed( {MatAdd: do_one(bc_matadd, bc_block_plus_ident), MatMul: do_one(bc_matmul, bc_dist), MatPow: bc_matmul, Transpose: bc_transpose, Inverse: bc_inverse, BlockMatrix: do_one(bc_unpack, deblock)} ) ) rule = exhaust( bottom_up( exhaust(conditioned_rl), fns=expr_fns ) ) result = rule(expr) doit = getattr(result, 'doit', None) if doit is not None: return doit() else: return result def bc_unpack(expr): if expr.blockshape == (1, 1): return expr.blocks[0, 0] return expr def bc_matadd(expr): args = sift(expr.args, lambda M: isinstance(M, BlockMatrix)) blocks = args[True] if not blocks: return expr nonblocks = args[False] block = blocks[0] for b in blocks[1:]: block = block._blockadd(b) if nonblocks: return MatAdd(*nonblocks) + block else: return block def bc_block_plus_ident(expr): idents = [arg for arg in expr.args if arg.is_Identity] if not idents: return expr blocks = [arg for arg in expr.args if isinstance(arg, BlockMatrix)] if (blocks and all(b.structurally_equal(blocks[0]) for b in blocks) and blocks[0].is_structurally_symmetric): block_id = BlockDiagMatrix(*[Identity(k) for k in blocks[0].rowblocksizes]) rest = [arg for arg in expr.args if not arg.is_Identity and not isinstance(arg, BlockMatrix)] return MatAdd(block_id * len(idents), *blocks, *rest).doit() return expr def bc_dist(expr): """ Turn a*[X, Y] into [a*X, a*Y] """ factor, mat = expr.as_coeff_mmul() if factor == 1: return expr unpacked = unpack(mat) if isinstance(unpacked, BlockDiagMatrix): B = unpacked.diag new_B = [factor * mat for mat in B] return BlockDiagMatrix(*new_B) elif isinstance(unpacked, BlockMatrix): B = unpacked.blocks new_B = [ [factor * B[i, j] for j in range(B.cols)] for i in range(B.rows)] return BlockMatrix(new_B) return unpacked def bc_matmul(expr): if isinstance(expr, MatPow): if expr.args[1].is_Integer: factor, matrices = (1, [expr.args[0]]*expr.args[1]) else: return expr else: factor, matrices = expr.as_coeff_matrices() i = 0 while (i+1 < len(matrices)): A, B = matrices[i:i+2] if isinstance(A, BlockMatrix) and isinstance(B, BlockMatrix): matrices[i] = A._blockmul(B) matrices.pop(i+1) elif isinstance(A, BlockMatrix): matrices[i] = A._blockmul(BlockMatrix([[B]])) matrices.pop(i+1) elif isinstance(B, BlockMatrix): matrices[i] = BlockMatrix([[A]])._blockmul(B) matrices.pop(i+1) else: i+=1 return MatMul(factor, *matrices).doit() def bc_transpose(expr): collapse = block_collapse(expr.arg) return collapse._eval_transpose() def bc_inverse(expr): if isinstance(expr.arg, BlockDiagMatrix): return expr.inverse() expr2 = blockinverse_1x1(expr) if expr != expr2: return expr2 return blockinverse_2x2(Inverse(reblock_2x2(expr.arg))) def blockinverse_1x1(expr): if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (1, 1): mat = Matrix([[expr.arg.blocks[0].inverse()]]) return BlockMatrix(mat) return expr def blockinverse_2x2(expr): if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (2, 2): # See: Inverses of 2x2 Block Matrices, Tzon-Tzer Lu and Sheng-Hua Shiou [[A, B], [C, D]] = expr.arg.blocks.tolist() formula = _choose_2x2_inversion_formula(A, B, C, D) if formula != None: MI = expr.arg.schur(formula).I if formula == 'A': AI = A.I return BlockMatrix([[AI + AI * B * MI * C * AI, -AI * B * MI], [-MI * C * AI, MI]]) if formula == 'B': BI = B.I return BlockMatrix([[-MI * D * BI, MI], [BI + BI * A * MI * D * BI, -BI * A * MI]]) if formula == 'C': CI = C.I return BlockMatrix([[-CI * D * MI, CI + CI * D * MI * A * CI], [MI, -MI * A * CI]]) if formula == 'D': DI = D.I return BlockMatrix([[MI, -MI * B * DI], [-DI * C * MI, DI + DI * C * MI * B * DI]]) return expr def _choose_2x2_inversion_formula(A, B, C, D): """ Assuming [[A, B], [C, D]] would form a valid square block matrix, find which of the classical 2x2 block matrix inversion formulas would be best suited. Returns 'A', 'B', 'C', 'D' to represent the algorithm involving inversion of the given argument or None if the matrix cannot be inverted using any of those formulas. """ # Try to find a known invertible matrix. Note that the Schur complement # is currently not being considered for this A_inv = ask(Q.invertible(A)) if A_inv == True: return 'A' B_inv = ask(Q.invertible(B)) if B_inv == True: return 'B' C_inv = ask(Q.invertible(C)) if C_inv == True: return 'C' D_inv = ask(Q.invertible(D)) if D_inv == True: return 'D' # Otherwise try to find a matrix that isn't known to be non-invertible if A_inv != False: return 'A' if B_inv != False: return 'B' if C_inv != False: return 'C' if D_inv != False: return 'D' return None def deblock(B): """ Flatten a BlockMatrix of BlockMatrices """ if not isinstance(B, BlockMatrix) or not B.blocks.has(BlockMatrix): return B wrap = lambda x: x if isinstance(x, BlockMatrix) else BlockMatrix([[x]]) bb = B.blocks.applyfunc(wrap) # everything is a block try: MM = Matrix(0, sum(bb[0, i].blocks.shape[1] for i in range(bb.shape[1])), []) for row in range(0, bb.shape[0]): M = Matrix(bb[row, 0].blocks) for col in range(1, bb.shape[1]): M = M.row_join(bb[row, col].blocks) MM = MM.col_join(M) return BlockMatrix(MM) except ShapeError: return B def reblock_2x2(expr): """ Reblock a BlockMatrix so that it has 2x2 blocks of block matrices. If possible in such a way that the matrix continues to be invertible using the classical 2x2 block inversion formulas. """ if not isinstance(expr, BlockMatrix) or not all(d > 2 for d in expr.blockshape): return expr BM = BlockMatrix # for brevity's sake rowblocks, colblocks = expr.blockshape blocks = expr.blocks for i in range(1, rowblocks): for j in range(1, colblocks): # try to split rows at i and cols at j A = bc_unpack(BM(blocks[:i, :j])) B = bc_unpack(BM(blocks[:i, j:])) C = bc_unpack(BM(blocks[i:, :j])) D = bc_unpack(BM(blocks[i:, j:])) formula = _choose_2x2_inversion_formula(A, B, C, D) if formula is not None: return BlockMatrix([[A, B], [C, D]]) # else: nothing worked, just split upper left corner return BM([[blocks[0, 0], BM(blocks[0, 1:])], [BM(blocks[1:, 0]), BM(blocks[1:, 1:])]]) def bounds(sizes): """ Convert sequence of numbers into pairs of low-high pairs >>> from sympy.matrices.expressions.blockmatrix import bounds >>> bounds((1, 10, 50)) [(0, 1), (1, 11), (11, 61)] """ low = 0 rv = [] for size in sizes: rv.append((low, low + size)) low += size return rv def blockcut(expr, rowsizes, colsizes): """ Cut a matrix expression into Blocks >>> from sympy import ImmutableMatrix, blockcut >>> M = ImmutableMatrix(4, 4, range(16)) >>> B = blockcut(M, (1, 3), (1, 3)) >>> type(B).__name__ 'BlockMatrix' >>> ImmutableMatrix(B.blocks[0, 1]) Matrix([[1, 2, 3]]) """ rowbounds = bounds(rowsizes) colbounds = bounds(colsizes) return BlockMatrix([[MatrixSlice(expr, rowbound, colbound) for colbound in colbounds] for rowbound in rowbounds])
86283ae8549d24225fb36cddcef583a9c709da89540722125e9fc0b6b20cf428
from sympy.core.assumptions import check_assumptions from sympy.core.logic import fuzzy_and from sympy.core.sympify import _sympify from sympy.sets.sets import Set from .matexpr import MatrixExpr class MatrixSet(Set): """ MatrixSet represents the set of matrices with ``shape = (n, m)`` over the given set. Examples ======== >>> from sympy.matrices import MatrixSet, Matrix >>> from sympy import S, I >>> M = MatrixSet(2, 2, set=S.Reals) >>> X = Matrix([[1, 2], [3, 4]]) >>> X in M True >>> X = Matrix([[1, 2], [I, 4]]) >>> X in M False """ is_empty = False def __new__(cls, n, m, set): n, m, set = _sympify(n), _sympify(m), _sympify(set) cls._check_dim(n) cls._check_dim(m) if not isinstance(set, Set): raise TypeError("{} should be an instance of Set.".format(set)) return Set.__new__(cls, n, m, set) @property def shape(self): return self.args[:2] @property def set(self): return self.args[2] def _contains(self, other): if not isinstance(other, MatrixExpr): raise TypeError("{} should be an instance of MatrixExpr.".format(other)) if other.shape != self.shape: are_symbolic = any(_sympify(x).is_Symbol for x in other.shape + self.shape) if are_symbolic: return None return False return fuzzy_and(self.set.contains(x) for x in other) @classmethod def _check_dim(cls, dim): """Helper function to check invalid matrix dimensions""" ok = check_assumptions(dim, integer=True, nonnegative=True) if ok is False: raise ValueError( "The dimension specification {} should be " "a nonnegative integer.".format(dim))
26594d39f65dc253343068387c5e775b5c9d417e88c2c1d1bb6939c8583aca14
from .matexpr import MatrixExpr from sympy.core.function import FunctionClass, Lambda from sympy.core.symbol import Dummy from sympy.core.sympify import _sympify, sympify from sympy.matrices import Matrix from sympy.functions.elementary.complexes import re, im class FunctionMatrix(MatrixExpr): """Represents a matrix using a function (``Lambda``) which gives outputs according to the coordinates of each matrix entries. Parameters ========== rows : nonnegative integer. Can be symbolic. cols : nonnegative integer. Can be symbolic. lamda : Function, Lambda or str If it is a SymPy ``Function`` or ``Lambda`` instance, it should be able to accept two arguments which represents the matrix coordinates. If it is a pure string containing Python ``lambda`` semantics, it is interpreted by the SymPy parser and casted into a SymPy ``Lambda`` instance. Examples ======== Creating a ``FunctionMatrix`` from ``Lambda``: >>> from sympy import FunctionMatrix, symbols, Lambda, MatPow >>> i, j, n, m = symbols('i,j,n,m') >>> FunctionMatrix(n, m, Lambda((i, j), i + j)) FunctionMatrix(n, m, Lambda((i, j), i + j)) Creating a ``FunctionMatrix`` from a SymPy function: >>> from sympy import KroneckerDelta >>> X = FunctionMatrix(3, 3, KroneckerDelta) >>> X.as_explicit() Matrix([ [1, 0, 0], [0, 1, 0], [0, 0, 1]]) Creating a ``FunctionMatrix`` from a SymPy undefined function: >>> from sympy import Function >>> f = Function('f') >>> X = FunctionMatrix(3, 3, f) >>> X.as_explicit() Matrix([ [f(0, 0), f(0, 1), f(0, 2)], [f(1, 0), f(1, 1), f(1, 2)], [f(2, 0), f(2, 1), f(2, 2)]]) Creating a ``FunctionMatrix`` from Python ``lambda``: >>> FunctionMatrix(n, m, 'lambda i, j: i + j') FunctionMatrix(n, m, Lambda((i, j), i + j)) Example of lazy evaluation of matrix product: >>> Y = FunctionMatrix(1000, 1000, Lambda((i, j), i + j)) >>> isinstance(Y*Y, MatPow) # this is an expression object True >>> (Y**2)[10,10] # So this is evaluated lazily 342923500 Notes ===== This class provides an alternative way to represent an extremely dense matrix with entries in some form of a sequence, in a most sparse way. """ def __new__(cls, rows, cols, lamda): rows, cols = _sympify(rows), _sympify(cols) cls._check_dim(rows) cls._check_dim(cols) lamda = sympify(lamda) if not isinstance(lamda, (FunctionClass, Lambda)): raise ValueError( "{} should be compatible with SymPy function classes." .format(lamda)) if 2 not in lamda.nargs: raise ValueError( '{} should be able to accept 2 arguments.'.format(lamda)) if not isinstance(lamda, Lambda): i, j = Dummy('i'), Dummy('j') lamda = Lambda((i, j), lamda(i, j)) return super().__new__(cls, rows, cols, lamda) @property def shape(self): return self.args[0:2] @property def lamda(self): return self.args[2] def _entry(self, i, j, **kwargs): return self.lamda(i, j) def _eval_trace(self): from sympy.matrices.expressions.trace import Trace from sympy.concrete.summations import Sum return Trace(self).rewrite(Sum).doit() def as_real_imag(self): return (re(Matrix(self)), im(Matrix(self)))
a7df8dbd3049eae140df01ad9be89e3bec479bcd074337bf8281d9ed0a326a6e
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.common import ShapeError from sympy.matrices.matrices import MatrixBase from sympy.matrices.expressions.transpose import transpose from sympy.strategies import (rm_id, unpack, flatten, sort, condition, exhaust, do_one, glom) from sympy.matrices.expressions.matexpr import MatrixExpr from sympy.matrices.expressions.special import ZeroMatrix, GenericZeroMatrix from sympy.utilities import sift # XXX: MatAdd should perhaps not subclass directly from Add class MatAdd(MatrixExpr, Add): """A Sum of Matrix Expressions MatAdd inherits from and operates like SymPy Add Examples ======== >>> from sympy import MatAdd, MatrixSymbol >>> A = MatrixSymbol('A', 5, 5) >>> B = MatrixSymbol('B', 5, 5) >>> C = MatrixSymbol('C', 5, 5) >>> MatAdd(A, B, C) A + B + C """ is_MatAdd = True identity = GenericZeroMatrix() def __new__(cls, *args, evaluate=False, check=False, _sympify=True): if not args: return cls.identity # This must be removed aggressively in the constructor to avoid # TypeErrors from GenericZeroMatrix().shape args = list(filter(lambda i: cls.identity != i, args)) if _sympify: args = list(map(sympify, args)) obj = Basic.__new__(cls, *args) if check: if not any(isinstance(i, MatrixExpr) for i in args): return Add.fromiter(args) validate(*args) if evaluate: if not any(isinstance(i, MatrixExpr) for i in args): return Add(*args, evaluate=True) obj = canonicalize(obj) return obj @property def shape(self): return self.args[0].shape def could_extract_minus_sign(self): return _could_extract_minus_sign(self) def _entry(self, i, j, **kwargs): return Add(*[arg._entry(i, j, **kwargs) for arg in self.args]) def _eval_transpose(self): return MatAdd(*[transpose(arg) for arg in self.args]).doit() def _eval_adjoint(self): return MatAdd(*[adjoint(arg) for arg in self.args]).doit() def _eval_trace(self): from .trace import trace return Add(*[trace(arg) for arg in self.args]).doit() def doit(self, **kwargs): deep = kwargs.get('deep', True) if deep: args = [arg.doit(**kwargs) for arg in self.args] else: args = self.args return canonicalize(MatAdd(*args)) def _eval_derivative_matrix_lines(self, x): add_lines = [arg._eval_derivative_matrix_lines(x) for arg in self.args] return [j for i in add_lines for j in i] add.register_handlerclass((Add, MatAdd), MatAdd) def validate(*args): if not all(arg.is_Matrix for arg in args): raise TypeError("Mix of Matrix and Scalar symbols") A = args[0] for B in args[1:]: if A.shape != B.shape: raise ShapeError("Matrices %s and %s are not aligned"%(A, B)) factor_of = lambda arg: arg.as_coeff_mmul()[0] matrix_of = lambda arg: unpack(arg.as_coeff_mmul()[1]) def combine(cnt, mat): if cnt == 1: return mat else: return cnt * mat def merge_explicit(matadd): """ Merge explicit MatrixBase arguments Examples ======== >>> from sympy import MatrixSymbol, eye, Matrix, MatAdd, pprint >>> from sympy.matrices.expressions.matadd import merge_explicit >>> A = MatrixSymbol('A', 2, 2) >>> B = eye(2) >>> C = Matrix([[1, 2], [3, 4]]) >>> X = MatAdd(A, B, C) >>> pprint(X) [1 0] [1 2] A + [ ] + [ ] [0 1] [3 4] >>> pprint(merge_explicit(X)) [2 2] A + [ ] [3 5] """ groups = sift(matadd.args, lambda arg: isinstance(arg, MatrixBase)) if len(groups[True]) > 1: return MatAdd(*(groups[False] + [reduce(operator.add, groups[True])])) else: return matadd rules = (rm_id(lambda x: x == 0 or isinstance(x, ZeroMatrix)), unpack, flatten, glom(matrix_of, factor_of, combine), merge_explicit, sort(default_sort_key)) canonicalize = exhaust(condition(lambda x: isinstance(x, MatAdd), do_one(*rules)))
68d758d44cb854947e502be83915f6921d83980e908cea7ec1a10dbd683c5951
from sympy.matrices.expressions.matexpr import MatrixExpr from sympy.core.basic import Basic from sympy.core.containers import Tuple from sympy.functions.elementary.integers import floor def normalize(i, parentsize): if isinstance(i, slice): i = (i.start, i.stop, i.step) if not isinstance(i, (tuple, list, Tuple)): if (i < 0) == True: i += parentsize i = (i, i+1, 1) i = list(i) if len(i) == 2: i.append(1) start, stop, step = i start = start or 0 if stop is None: stop = parentsize if (start < 0) == True: start += parentsize if (stop < 0) == True: stop += parentsize step = step or 1 if ((stop - start) * step < 1) == True: raise IndexError() return (start, stop, step) class MatrixSlice(MatrixExpr): """ A MatrixSlice of a Matrix Expression Examples ======== >>> from sympy import MatrixSlice, ImmutableMatrix >>> M = ImmutableMatrix(4, 4, range(16)) >>> M Matrix([ [ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> B = MatrixSlice(M, (0, 2), (2, 4)) >>> ImmutableMatrix(B) Matrix([ [2, 3], [6, 7]]) """ parent = property(lambda self: self.args[0]) rowslice = property(lambda self: self.args[1]) colslice = property(lambda self: self.args[2]) def __new__(cls, parent, rowslice, colslice): rowslice = normalize(rowslice, parent.shape[0]) colslice = normalize(colslice, parent.shape[1]) if not (len(rowslice) == len(colslice) == 3): raise IndexError() if ((0 > rowslice[0]) == True or (parent.shape[0] < rowslice[1]) == True or (0 > colslice[0]) == True or (parent.shape[1] < colslice[1]) == True): raise IndexError() if isinstance(parent, MatrixSlice): return mat_slice_of_slice(parent, rowslice, colslice) return Basic.__new__(cls, parent, Tuple(*rowslice), Tuple(*colslice)) @property def shape(self): rows = self.rowslice[1] - self.rowslice[0] rows = rows if self.rowslice[2] == 1 else floor(rows/self.rowslice[2]) cols = self.colslice[1] - self.colslice[0] cols = cols if self.colslice[2] == 1 else floor(cols/self.colslice[2]) return rows, cols def _entry(self, i, j, **kwargs): return self.parent._entry(i*self.rowslice[2] + self.rowslice[0], j*self.colslice[2] + self.colslice[0], **kwargs) @property def on_diag(self): return self.rowslice == self.colslice def slice_of_slice(s, t): start1, stop1, step1 = s start2, stop2, step2 = t start = start1 + start2*step1 step = step1 * step2 stop = start1 + step1*stop2 if stop > stop1: raise IndexError() return start, stop, step def mat_slice_of_slice(parent, rowslice, colslice): """ Collapse nested matrix slices >>> from sympy import MatrixSymbol >>> X = MatrixSymbol('X', 10, 10) >>> X[:, 1:5][5:8, :] X[5:8, 1:5] >>> X[1:9:2, 2:6][1:3, 2] X[3:7:2, 4:5] """ row = slice_of_slice(parent.rowslice, rowslice) col = slice_of_slice(parent.colslice, colslice) return MatrixSlice(parent.parent, row, col)
fa7d92bcdf071e064d98f9cee7956d28fe810f8a6863b6ce1c0aa7646b729148
from sympy.core import I, symbols, Basic, Mul, S from sympy.core.mul import mul from sympy.functions import adjoint, transpose 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 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) 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
02c05bde1f16f321f25d675535bf1e3d8b3cb0247b3dc05518ac57867ba9c9bf
from sympy.matrices.expressions.trace import Trace from sympy.testing.pytest import raises, slow from sympy.matrices.expressions.blockmatrix import ( block_collapse, bc_matmul, bc_block_plus_ident, BlockDiagMatrix, BlockMatrix, bc_dist, bc_matadd, bc_transpose, bc_inverse, blockcut, reblock_2x2, deblock) from sympy.matrices.expressions import (MatrixSymbol, Identity, Inverse, trace, Transpose, det, ZeroMatrix) from sympy.matrices.common import NonInvertibleMatrixError from sympy.matrices import ( Matrix, ImmutableMatrix, ImmutableSparseMatrix) from sympy.core import Tuple, symbols, Expr from sympy.functions import transpose i, j, k, l, m, n, p = symbols('i:n, p', integer=True) A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, n) C = MatrixSymbol('C', n, n) D = MatrixSymbol('D', n, n) G = MatrixSymbol('G', n, n) H = MatrixSymbol('H', n, n) b1 = BlockMatrix([[G, H]]) b2 = BlockMatrix([[G], [H]]) def test_bc_matmul(): assert bc_matmul(H*b1*b2*G) == BlockMatrix([[(H*G*G + H*H*H)*G]]) def test_bc_matadd(): assert bc_matadd(BlockMatrix([[G, H]]) + BlockMatrix([[H, H]])) == \ BlockMatrix([[G+H, H+H]]) def test_bc_transpose(): assert bc_transpose(Transpose(BlockMatrix([[A, B], [C, D]]))) == \ BlockMatrix([[A.T, C.T], [B.T, D.T]]) def test_bc_dist_diag(): A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', m, m) C = MatrixSymbol('C', l, l) X = BlockDiagMatrix(A, B, C) assert bc_dist(X+X).equals(BlockDiagMatrix(2*A, 2*B, 2*C)) def test_block_plus_ident(): A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, m) C = MatrixSymbol('C', m, n) D = MatrixSymbol('D', m, m) X = BlockMatrix([[A, B], [C, D]]) Z = MatrixSymbol('Z', n + m, n + m) assert bc_block_plus_ident(X + Identity(m + n) + Z) == \ BlockDiagMatrix(Identity(n), Identity(m)) + X + Z def test_BlockMatrix(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', n, k) C = MatrixSymbol('C', l, m) D = MatrixSymbol('D', l, k) M = MatrixSymbol('M', m + k, p) N = MatrixSymbol('N', l + n, k + m) X = BlockMatrix(Matrix([[A, B], [C, D]])) assert X.__class__(*X.args) == X # block_collapse does nothing on normal inputs E = MatrixSymbol('E', n, m) assert block_collapse(A + 2*E) == A + 2*E F = MatrixSymbol('F', m, m) assert block_collapse(E.T*A*F) == E.T*A*F assert X.shape == (l + n, k + m) assert X.blockshape == (2, 2) assert transpose(X) == BlockMatrix(Matrix([[A.T, C.T], [B.T, D.T]])) assert transpose(X).shape == X.shape[::-1] # Test that BlockMatrices and MatrixSymbols can still mix assert (X*M).is_MatMul assert X._blockmul(M).is_MatMul assert (X*M).shape == (n + l, p) assert (X + N).is_MatAdd assert X._blockadd(N).is_MatAdd assert (X + N).shape == X.shape E = MatrixSymbol('E', m, 1) F = MatrixSymbol('F', k, 1) Y = BlockMatrix(Matrix([[E], [F]])) assert (X*Y).shape == (l + n, 1) assert block_collapse(X*Y).blocks[0, 0] == A*E + B*F assert block_collapse(X*Y).blocks[1, 0] == C*E + D*F # block_collapse passes down into container objects, transposes, and inverse assert block_collapse(transpose(X*Y)) == transpose(block_collapse(X*Y)) assert block_collapse(Tuple(X*Y, 2*X)) == ( block_collapse(X*Y), block_collapse(2*X)) # Make sure that MatrixSymbols will enter 1x1 BlockMatrix if it simplifies Ab = BlockMatrix([[A]]) Z = MatrixSymbol('Z', *A.shape) assert block_collapse(Ab + Z) == A + Z def test_block_collapse_explicit_matrices(): A = Matrix([[1, 2], [3, 4]]) assert block_collapse(BlockMatrix([[A]])) == A A = ImmutableSparseMatrix([[1, 2], [3, 4]]) assert block_collapse(BlockMatrix([[A]])) == A def test_issue_17624(): a = MatrixSymbol("a", 2, 2) z = ZeroMatrix(2, 2) b = BlockMatrix([[a, z], [z, z]]) assert block_collapse(b * b) == BlockMatrix([[a**2, z], [z, z]]) assert block_collapse(b * b * b) == BlockMatrix([[a**3, z], [z, z]]) def test_issue_18618(): A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) assert A == Matrix(BlockDiagMatrix(A)) def test_BlockMatrix_trace(): A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD'] X = BlockMatrix([[A, B], [C, D]]) assert trace(X) == trace(A) + trace(D) assert trace(BlockMatrix([ZeroMatrix(n, n)])) == 0 def test_BlockMatrix_Determinant(): A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD'] X = BlockMatrix([[A, B], [C, D]]) from sympy.assumptions.ask import Q from sympy.assumptions.assume import assuming with assuming(Q.invertible(A)): assert det(X) == det(A) * det(X.schur('A')) assert isinstance(det(X), Expr) assert det(BlockMatrix([A])) == det(A) assert det(BlockMatrix([ZeroMatrix(n, n)])) == 0 def test_squareBlockMatrix(): A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, m) C = MatrixSymbol('C', m, n) D = MatrixSymbol('D', m, m) X = BlockMatrix([[A, B], [C, D]]) Y = BlockMatrix([[A]]) assert X.is_square Q = X + Identity(m + n) assert (block_collapse(Q) == BlockMatrix([[A + Identity(n), B], [C, D + Identity(m)]])) assert (X + MatrixSymbol('Q', n + m, n + m)).is_MatAdd assert (X * MatrixSymbol('Q', n + m, n + m)).is_MatMul assert block_collapse(Y.I) == A.I assert isinstance(X.inverse(), Inverse) assert not X.is_Identity Z = BlockMatrix([[Identity(n), B], [C, D]]) assert not Z.is_Identity def test_BlockMatrix_2x2_inverse_symbolic(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', n, k - m) C = MatrixSymbol('C', k - n, m) D = MatrixSymbol('D', k - n, k - m) X = BlockMatrix([[A, B], [C, D]]) assert X.is_square and X.shape == (k, k) assert isinstance(block_collapse(X.I), Inverse) # Can't invert when none of the blocks is square # test code path where only A is invertible A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, m) C = MatrixSymbol('C', m, n) D = ZeroMatrix(m, m) X = BlockMatrix([[A, B], [C, D]]) assert block_collapse(X.inverse()) == BlockMatrix([ [A.I + A.I * B * X.schur('A').I * C * A.I, -A.I * B * X.schur('A').I], [-X.schur('A').I * C * A.I, X.schur('A').I], ]) # test code path where only B is invertible A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', n, n) C = ZeroMatrix(m, m) D = MatrixSymbol('D', m, n) X = BlockMatrix([[A, B], [C, D]]) assert block_collapse(X.inverse()) == BlockMatrix([ [-X.schur('B').I * D * B.I, X.schur('B').I], [B.I + B.I * A * X.schur('B').I * D * B.I, -B.I * A * X.schur('B').I], ]) # test code path where only C is invertible A = MatrixSymbol('A', n, m) B = ZeroMatrix(n, n) C = MatrixSymbol('C', m, m) D = MatrixSymbol('D', m, n) X = BlockMatrix([[A, B], [C, D]]) assert block_collapse(X.inverse()) == BlockMatrix([ [-C.I * D * X.schur('C').I, C.I + C.I * D * X.schur('C').I * A * C.I], [X.schur('C').I, -X.schur('C').I * A * C.I], ]) # test code path where only D is invertible A = ZeroMatrix(n, n) B = MatrixSymbol('B', n, m) C = MatrixSymbol('C', m, n) D = MatrixSymbol('D', m, m) X = BlockMatrix([[A, B], [C, D]]) assert block_collapse(X.inverse()) == BlockMatrix([ [X.schur('D').I, -X.schur('D').I * B * D.I], [-D.I * C * X.schur('D').I, D.I + D.I * C * X.schur('D').I * B * D.I], ]) def test_BlockMatrix_2x2_inverse_numeric(): """Test 2x2 block matrix inversion numerically for all 4 formulas""" M = Matrix([[1, 2], [3, 4]]) # rank deficient matrices that have full rank when two of them combined D1 = Matrix([[1, 2], [2, 4]]) D2 = Matrix([[1, 3], [3, 9]]) D3 = Matrix([[1, 4], [4, 16]]) assert D1.rank() == D2.rank() == D3.rank() == 1 assert (D1 + D2).rank() == (D2 + D3).rank() == (D3 + D1).rank() == 2 # Only A is invertible K = BlockMatrix([[M, D1], [D2, D3]]) assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv() # Only B is invertible K = BlockMatrix([[D1, M], [D2, D3]]) assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv() # Only C is invertible K = BlockMatrix([[D1, D2], [M, D3]]) assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv() # Only D is invertible K = BlockMatrix([[D1, D2], [D3, M]]) assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv() @slow def test_BlockMatrix_3x3_symbolic(): # Only test one of these, instead of all permutations, because it's slow rowblocksizes = (n, m, k) colblocksizes = (m, k, n) K = BlockMatrix([ [MatrixSymbol('M%s%s' % (rows, cols), rows, cols) for cols in colblocksizes] for rows in rowblocksizes ]) collapse = block_collapse(K.I) assert isinstance(collapse, BlockMatrix) def test_BlockDiagMatrix(): A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', m, m) C = MatrixSymbol('C', l, l) M = MatrixSymbol('M', n + m + l, n + m + l) X = BlockDiagMatrix(A, B, C) Y = BlockDiagMatrix(A, 2*B, 3*C) assert X.blocks[1, 1] == B assert X.shape == (n + m + l, n + m + l) assert all(X.blocks[i, j].is_ZeroMatrix if i != j else X.blocks[i, j] in [A, B, C] for i in range(3) for j in range(3)) assert X.__class__(*X.args) == X assert X.get_diag_blocks() == (A, B, C) assert isinstance(block_collapse(X.I * X), Identity) assert bc_matmul(X*X) == BlockDiagMatrix(A*A, B*B, C*C) assert block_collapse(X*X) == BlockDiagMatrix(A*A, B*B, C*C) #XXX: should be == ?? assert block_collapse(X + X).equals(BlockDiagMatrix(2*A, 2*B, 2*C)) assert block_collapse(X*Y) == BlockDiagMatrix(A*A, 2*B*B, 3*C*C) assert block_collapse(X + Y) == BlockDiagMatrix(2*A, 3*B, 4*C) # Ensure that BlockDiagMatrices can still interact with normal MatrixExprs assert (X*(2*M)).is_MatMul assert (X + (2*M)).is_MatAdd assert (X._blockmul(M)).is_MatMul assert (X._blockadd(M)).is_MatAdd def test_BlockDiagMatrix_nonsquare(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', k, l) X = BlockDiagMatrix(A, B) assert X.shape == (n + k, m + l) assert X.shape == (n + k, m + l) assert X.rowblocksizes == [n, k] assert X.colblocksizes == [m, l] C = MatrixSymbol('C', n, m) D = MatrixSymbol('D', k, l) Y = BlockDiagMatrix(C, D) assert block_collapse(X + Y) == BlockDiagMatrix(A + C, B + D) assert block_collapse(X * Y.T) == BlockDiagMatrix(A * C.T, B * D.T) raises(NonInvertibleMatrixError, lambda: BlockDiagMatrix(A, C.T).inverse()) def test_BlockDiagMatrix_determinant(): A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', m, m) assert det(BlockDiagMatrix()) == 1 assert det(BlockDiagMatrix(A)) == det(A) assert det(BlockDiagMatrix(A, B)) == det(A) * det(B) # non-square blocks C = MatrixSymbol('C', m, n) D = MatrixSymbol('D', n, m) assert det(BlockDiagMatrix(C, D)) == 0 def test_BlockDiagMatrix_trace(): assert trace(BlockDiagMatrix()) == 0 assert trace(BlockDiagMatrix(ZeroMatrix(n, n))) == 0 A = MatrixSymbol('A', n, n) assert trace(BlockDiagMatrix(A)) == trace(A) B = MatrixSymbol('B', m, m) assert trace(BlockDiagMatrix(A, B)) == trace(A) + trace(B) # non-square blocks C = MatrixSymbol('C', m, n) D = MatrixSymbol('D', n, m) assert isinstance(trace(BlockDiagMatrix(C, D)), Trace) def test_BlockDiagMatrix_transpose(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', k, l) assert transpose(BlockDiagMatrix()) == BlockDiagMatrix() assert transpose(BlockDiagMatrix(A)) == BlockDiagMatrix(A.T) assert transpose(BlockDiagMatrix(A, B)) == BlockDiagMatrix(A.T, B.T) def test_issue_2460(): bdm1 = BlockDiagMatrix(Matrix([i]), Matrix([j])) bdm2 = BlockDiagMatrix(Matrix([k]), Matrix([l])) assert block_collapse(bdm1 + bdm2) == BlockDiagMatrix(Matrix([i + k]), Matrix([j + l])) def test_blockcut(): A = MatrixSymbol('A', n, m) B = blockcut(A, (n/2, n/2), (m/2, m/2)) assert B == BlockMatrix([[A[:n/2, :m/2], A[:n/2, m/2:]], [A[n/2:, :m/2], A[n/2:, m/2:]]]) M = ImmutableMatrix(4, 4, range(16)) B = blockcut(M, (2, 2), (2, 2)) assert M == ImmutableMatrix(B) B = blockcut(M, (1, 3), (2, 2)) assert ImmutableMatrix(B.blocks[0, 1]) == ImmutableMatrix([[2, 3]]) def test_reblock_2x2(): B = BlockMatrix([[MatrixSymbol('A_%d%d'%(i,j), 2, 2) for j in range(3)] for i in range(3)]) assert B.blocks.shape == (3, 3) BB = reblock_2x2(B) assert BB.blocks.shape == (2, 2) assert B.shape == BB.shape assert B.as_explicit() == BB.as_explicit() def test_deblock(): B = BlockMatrix([[MatrixSymbol('A_%d%d'%(i,j), n, n) for j in range(4)] for i in range(4)]) assert deblock(reblock_2x2(B)) == B def test_block_collapse_type(): bm1 = BlockDiagMatrix(ImmutableMatrix([1]), ImmutableMatrix([2])) bm2 = BlockDiagMatrix(ImmutableMatrix([3]), ImmutableMatrix([4])) assert bm1.T.__class__ == BlockDiagMatrix assert block_collapse(bm1 - bm2).__class__ == BlockDiagMatrix assert block_collapse(Inverse(bm1)).__class__ == BlockDiagMatrix assert block_collapse(Transpose(bm1)).__class__ == BlockDiagMatrix assert bc_transpose(Transpose(bm1)).__class__ == BlockDiagMatrix assert bc_inverse(Inverse(bm1)).__class__ == BlockDiagMatrix def test_invalid_block_matrix(): raises(ValueError, lambda: BlockMatrix([ [Identity(2), Identity(5)], ])) raises(ValueError, lambda: BlockMatrix([ [Identity(n), Identity(m)], ])) raises(ValueError, lambda: BlockMatrix([ [ZeroMatrix(n, n), ZeroMatrix(n, n)], [ZeroMatrix(n, n - 1), ZeroMatrix(n, n + 1)], ])) raises(ValueError, lambda: BlockMatrix([ [ZeroMatrix(n - 1, n), ZeroMatrix(n, n)], [ZeroMatrix(n + 1, n), ZeroMatrix(n, n)], ])) def test_block_lu_decomposition(): A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, m) C = MatrixSymbol('C', m, n) D = MatrixSymbol('D', m, m) X = BlockMatrix([[A, B], [C, D]]) #LDU decomposition L, D, U = X.LDUdecomposition() assert block_collapse(L*D*U) == X #UDL decomposition U, D, L = X.UDLdecomposition() assert block_collapse(U*D*L) == X #LU decomposition L, U = X.LUdecomposition() assert block_collapse(L*U) == X
ded45b126662da06539a4066ee60165036d7e23c047c2f2d0b8918a0ebb36948
from sympy.functions.elementary.miscellaneous import sqrt from sympy.simplify.powsimp import powsimp from sympy.testing.pytest import raises from sympy.core.expr import unchanged from sympy.core import symbols, S from sympy.matrices import Identity, MatrixSymbol, ImmutableMatrix, ZeroMatrix, OneMatrix, Matrix from sympy.matrices.common import NonSquareMatrixError from sympy.matrices.expressions import MatPow, MatAdd, MatMul from sympy.matrices.expressions.inverse import Inverse from sympy.matrices.expressions.matexpr import MatrixElement n, m, l, k = symbols('n m l k', 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_entry_matrix(): X = ImmutableMatrix([[1, 2], [3, 4]]) assert MatPow(X, 0)[0, 0] == 1 assert MatPow(X, 0)[0, 1] == 0 assert MatPow(X, 1)[0, 0] == 1 assert MatPow(X, 1)[0, 1] == 2 assert MatPow(X, 2)[0, 0] == 7 def test_entry_symbol(): from sympy.concrete import Sum assert MatPow(C, 0)[0, 0] == 1 assert MatPow(C, 0)[0, 1] == 0 assert MatPow(C, 1)[0, 0] == C[0, 0] assert isinstance(MatPow(C, 2)[0, 0], Sum) assert isinstance(MatPow(C, n)[0, 0], MatrixElement) def test_as_explicit_symbol(): X = MatrixSymbol('X', 2, 2) assert MatPow(X, 0).as_explicit() == ImmutableMatrix(Identity(2)) assert MatPow(X, 1).as_explicit() == X.as_explicit() assert MatPow(X, 2).as_explicit() == (X.as_explicit())**2 assert MatPow(X, n).as_explicit() == ImmutableMatrix([ [(X ** n)[0, 0], (X ** n)[0, 1]], [(X ** n)[1, 0], (X ** n)[1, 1]], ]) a = MatrixSymbol("a", 3, 1) b = MatrixSymbol("b", 3, 1) c = MatrixSymbol("c", 3, 1) expr = (a.T*b)**S.Half assert expr.as_explicit() == Matrix([[sqrt(a[0, 0]*b[0, 0] + a[1, 0]*b[1, 0] + a[2, 0]*b[2, 0])]]) expr = c*(a.T*b)**S.Half m = sqrt(a[0, 0]*b[0, 0] + a[1, 0]*b[1, 0] + a[2, 0]*b[2, 0]) assert expr.as_explicit() == Matrix([[c[0, 0]*m], [c[1, 0]*m], [c[2, 0]*m]]) expr = (a*b.T)**S.Half denom = sqrt(a[0, 0]*b[0, 0] + a[1, 0]*b[1, 0] + a[2, 0]*b[2, 0]) expected = (a*b.T).as_explicit()/denom assert expr.as_explicit() == expected expr = X**-1 det = X[0, 0]*X[1, 1] - X[1, 0]*X[0, 1] expected = Matrix([[X[1, 1], -X[0, 1]], [-X[1, 0], X[0, 0]]])/det assert expr.as_explicit() == expected expr = X**m assert expr.as_explicit() == X.as_explicit()**m def test_as_explicit_matrix(): A = ImmutableMatrix([[1, 2], [3, 4]]) assert MatPow(A, 0).as_explicit() == ImmutableMatrix(Identity(2)) assert MatPow(A, 1).as_explicit() == A assert MatPow(A, 2).as_explicit() == A**2 assert MatPow(A, -1).as_explicit() == A.inv() assert MatPow(A, -2).as_explicit() == (A.inv())**2 # less expensive than testing on a 2x2 A = ImmutableMatrix([4]) assert MatPow(A, S.Half).as_explicit() == A**S.Half def test_doit_symbol(): assert MatPow(C, 0).doit() == Identity(n) assert MatPow(C, 1).doit() == C assert MatPow(C, -1).doit() == C.I for r in [2, S.Half, S.Pi, n]: assert MatPow(C, r).doit() == MatPow(C, r) def test_doit_matrix(): X = ImmutableMatrix([[1, 2], [3, 4]]) assert MatPow(X, 0).doit() == ImmutableMatrix(Identity(2)) assert MatPow(X, 1).doit() == X assert MatPow(X, 2).doit() == X**2 assert MatPow(X, -1).doit() == X.inv() assert MatPow(X, -2).doit() == (X.inv())**2 # less expensive than testing on a 2x2 assert MatPow(ImmutableMatrix([4]), S.Half).doit() == ImmutableMatrix([2]) X = ImmutableMatrix([[0, 2], [0, 4]]) # det() == 0 raises(ValueError, lambda: MatPow(X,-1).doit()) raises(ValueError, lambda: MatPow(X,-2).doit()) def test_nonsquare(): A = MatrixSymbol('A', 2, 3) B = ImmutableMatrix([[1, 2, 3], [4, 5, 6]]) for r in [-1, 0, 1, 2, S.Half, S.Pi, n]: raises(NonSquareMatrixError, lambda: MatPow(A, r)) raises(NonSquareMatrixError, lambda: MatPow(B, r)) def test_doit_equals_pow(): #17179 X = ImmutableMatrix ([[1,0],[0,1]]) assert MatPow(X, n).doit() == X**n == X def test_doit_nested_MatrixExpr(): X = ImmutableMatrix([[1, 2], [3, 4]]) Y = ImmutableMatrix([[2, 3], [4, 5]]) assert MatPow(MatMul(X, Y), 2).doit() == (X*Y)**2 assert MatPow(MatAdd(X, Y), 2).doit() == (X + Y)**2 def test_identity_power(): k = Identity(n) assert MatPow(k, 4).doit() == k assert MatPow(k, n).doit() == k assert MatPow(k, -3).doit() == k assert MatPow(k, 0).doit() == k l = Identity(3) assert MatPow(l, n).doit() == l assert MatPow(l, -1).doit() == l assert MatPow(l, 0).doit() == l def test_zero_power(): z1 = ZeroMatrix(n, n) assert MatPow(z1, 3).doit() == z1 raises(ValueError, lambda:MatPow(z1, -1).doit()) assert MatPow(z1, 0).doit() == Identity(n) assert MatPow(z1, n).doit() == z1 raises(ValueError, lambda:MatPow(z1, -2).doit()) z2 = ZeroMatrix(4, 4) assert MatPow(z2, n).doit() == z2 raises(ValueError, lambda:MatPow(z2, -3).doit()) assert MatPow(z2, 2).doit() == z2 assert MatPow(z2, 0).doit() == Identity(4) raises(ValueError, lambda:MatPow(z2, -1).doit()) def test_OneMatrix_power(): o = OneMatrix(3, 3) assert o ** 0 == Identity(3) assert o ** 1 == o assert o * o == o ** 2 == 3 * o assert o * o * o == o ** 3 == 9 * o o = OneMatrix(n, n) assert o * o == o ** 2 == n * o # powsimp necessary as n ** (n - 2) * n does not produce n ** (n - 1) assert powsimp(o ** (n - 1) * o) == o ** n == n ** (n - 1) * o def test_transpose_power(): from sympy.matrices.expressions.transpose import Transpose as TP assert (C*D).T**5 == ((C*D)**5).T == (D.T * C.T)**5 assert ((C*D).T**5).T == (C*D)**5 assert (C.T.I.T)**7 == C**-7 assert (C.T**l).T**k == C**(l*k) assert ((E.T * A.T)**5).T == (A*E)**5 assert ((A*E).T**5).T**7 == (A*E)**35 assert TP(TP(C**2 * D**3)**5).doit() == (C**2 * D**3)**5 assert ((D*C)**-5).T**-5 == ((D*C)**25).T assert (((D*C)**l).T**k).T == (D*C)**(l*k) def test_Inverse(): assert Inverse(MatPow(C, 0)).doit() == Identity(n) assert Inverse(MatPow(C, 1)).doit() == Inverse(C) assert Inverse(MatPow(C, 2)).doit() == MatPow(C, -2) assert Inverse(MatPow(C, -1)).doit() == C assert MatPow(Inverse(C), 0).doit() == Identity(n) assert MatPow(Inverse(C), 1).doit() == Inverse(C) assert MatPow(Inverse(C), 2).doit() == MatPow(C, -2) assert MatPow(Inverse(C), -1).doit() == C def test_combine_powers(): assert (C ** 1) ** 1 == C assert (C ** 2) ** 3 == MatPow(C, 6) assert (C ** -2) ** -3 == MatPow(C, 6) assert (C ** -1) ** -1 == C assert (((C ** 2) ** 3) ** 4) ** 5 == MatPow(C, 120) assert (C ** n) ** n == C ** (n ** 2) def test_unchanged(): assert unchanged(MatPow, C, 0) assert unchanged(MatPow, C, 1) assert unchanged(MatPow, Inverse(C), -1) assert unchanged(Inverse, MatPow(C, -1), -1) assert unchanged(MatPow, MatPow(C, -1), -1) assert unchanged(MatPow, MatPow(C, 1), 1) def test_no_exponentiation(): # if this passes, Pow.as_numer_denom should recognize # MatAdd as exponent raises(NotImplementedError, lambda: 3**(-2*C))
f770aa8e3da4ddaa11ddac8c24b74951ae61d6ef3b6d14714f723c078150b2f5
from sympy.combinatorics import Permutation from sympy.core.expr import unchanged from sympy.matrices import Matrix from sympy.matrices.expressions import \ MatMul, BlockDiagMatrix, Determinant, Inverse from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.special import ZeroMatrix, OneMatrix, Identity from sympy.matrices.expressions.permutation import \ MatrixPermute, PermutationMatrix from sympy.testing.pytest import raises from sympy.core.symbol import Symbol def test_PermutationMatrix_basic(): p = Permutation([1, 0]) assert unchanged(PermutationMatrix, p) raises(ValueError, lambda: PermutationMatrix((0, 1, 2))) assert PermutationMatrix(p).as_explicit() == Matrix([[0, 1], [1, 0]]) assert isinstance(PermutationMatrix(p)*MatrixSymbol('A', 2, 2), MatMul) def test_PermutationMatrix_matmul(): p = Permutation([1, 2, 0]) P = PermutationMatrix(p) M = Matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) assert (P*M).as_explicit() == P.as_explicit()*M assert (M*P).as_explicit() == M*P.as_explicit() P1 = PermutationMatrix(Permutation([1, 2, 0])) P2 = PermutationMatrix(Permutation([2, 1, 0])) P3 = PermutationMatrix(Permutation([1, 0, 2])) assert P1*P2 == P3 def test_PermutationMatrix_matpow(): p1 = Permutation([1, 2, 0]) P1 = PermutationMatrix(p1) p2 = Permutation([2, 0, 1]) P2 = PermutationMatrix(p2) assert P1**2 == P2 assert P1**3 == Identity(3) def test_PermutationMatrix_identity(): p = Permutation([0, 1]) assert PermutationMatrix(p).is_Identity p = Permutation([1, 0]) assert not PermutationMatrix(p).is_Identity def test_PermutationMatrix_determinant(): P = PermutationMatrix(Permutation([0, 1, 2])) assert Determinant(P).doit() == 1 P = PermutationMatrix(Permutation([0, 2, 1])) assert Determinant(P).doit() == -1 P = PermutationMatrix(Permutation([2, 0, 1])) assert Determinant(P).doit() == 1 def test_PermutationMatrix_inverse(): P = PermutationMatrix(Permutation(0, 1, 2)) assert Inverse(P).doit() == PermutationMatrix(Permutation(0, 2, 1)) def test_PermutationMatrix_rewrite_BlockDiagMatrix(): P = PermutationMatrix(Permutation([0, 1, 2, 3, 4, 5])) P0 = PermutationMatrix(Permutation([0])) assert P.rewrite(BlockDiagMatrix) == \ BlockDiagMatrix(P0, P0, P0, P0, P0, P0) P = PermutationMatrix(Permutation([0, 1, 3, 2, 4, 5])) P10 = PermutationMatrix(Permutation(0, 1)) assert P.rewrite(BlockDiagMatrix) == \ BlockDiagMatrix(P0, P0, P10, P0, P0) P = PermutationMatrix(Permutation([1, 0, 3, 2, 5, 4])) assert P.rewrite(BlockDiagMatrix) == \ BlockDiagMatrix(P10, P10, P10) P = PermutationMatrix(Permutation([0, 4, 3, 2, 1, 5])) P3210 = PermutationMatrix(Permutation([3, 2, 1, 0])) assert P.rewrite(BlockDiagMatrix) == \ BlockDiagMatrix(P0, P3210, P0) P = PermutationMatrix(Permutation([0, 4, 2, 3, 1, 5])) P3120 = PermutationMatrix(Permutation([3, 1, 2, 0])) assert P.rewrite(BlockDiagMatrix) == \ BlockDiagMatrix(P0, P3120, P0) P = PermutationMatrix(Permutation(0, 3)(1, 4)(2, 5)) assert P.rewrite(BlockDiagMatrix) == BlockDiagMatrix(P) def test_MartrixPermute_basic(): p = Permutation(0, 1) P = PermutationMatrix(p) A = MatrixSymbol('A', 2, 2) raises(ValueError, lambda: MatrixPermute(Symbol('x'), p)) raises(ValueError, lambda: MatrixPermute(A, Symbol('x'))) assert MatrixPermute(A, P) == MatrixPermute(A, p) raises(ValueError, lambda: MatrixPermute(A, p, 2)) pp = Permutation(0, 1, size=3) assert MatrixPermute(A, pp) == MatrixPermute(A, p) pp = Permutation(0, 1, 2) raises(ValueError, lambda: MatrixPermute(A, pp)) def test_MatrixPermute_shape(): p = Permutation(0, 1) A = MatrixSymbol('A', 2, 3) assert MatrixPermute(A, p).shape == (2, 3) def test_MatrixPermute_explicit(): p = Permutation(0, 1, 2) A = MatrixSymbol('A', 3, 3) AA = A.as_explicit() assert MatrixPermute(A, p, 0).as_explicit() == \ AA.permute(p, orientation='rows') assert MatrixPermute(A, p, 1).as_explicit() == \ AA.permute(p, orientation='cols') def test_MatrixPermute_rewrite_MatMul(): p = Permutation(0, 1, 2) A = MatrixSymbol('A', 3, 3) assert MatrixPermute(A, p, 0).rewrite(MatMul).as_explicit() == \ MatrixPermute(A, p, 0).as_explicit() assert MatrixPermute(A, p, 1).rewrite(MatMul).as_explicit() == \ MatrixPermute(A, p, 1).as_explicit() def test_MatrixPermute_doit(): p = Permutation(0, 1, 2) A = MatrixSymbol('A', 3, 3) assert MatrixPermute(A, p).doit() == MatrixPermute(A, p) p = Permutation(0, size=3) A = MatrixSymbol('A', 3, 3) assert MatrixPermute(A, p).doit().as_explicit() == \ MatrixPermute(A, p).as_explicit() p = Permutation(0, 1, 2) A = Identity(3) assert MatrixPermute(A, p, 0).doit().as_explicit() == \ MatrixPermute(A, p, 0).as_explicit() assert MatrixPermute(A, p, 1).doit().as_explicit() == \ MatrixPermute(A, p, 1).as_explicit() A = ZeroMatrix(3, 3) assert MatrixPermute(A, p).doit() == A A = OneMatrix(3, 3) assert MatrixPermute(A, p).doit() == A A = MatrixSymbol('A', 4, 4) p1 = Permutation(0, 1, 2, 3) p2 = Permutation(0, 2, 3, 1) expr = MatrixPermute(MatrixPermute(A, p1, 0), p2, 0) assert expr.as_explicit() == expr.doit().as_explicit() expr = MatrixPermute(MatrixPermute(A, p1, 1), p2, 1) assert expr.as_explicit() == expr.doit().as_explicit()
5b8390602cdde3b07b647af3f4934c63bf05f8598d3e68a616c0e1de05aaff2d
from sympy.core import S, symbols from sympy.matrices import eye, ones, Matrix, ShapeError from sympy.matrices.expressions import ( Identity, MatrixExpr, MatrixSymbol, Determinant, det, per, ZeroMatrix, Transpose, Permanent ) from sympy.matrices.expressions.special import OneMatrix from sympy.testing.pytest import raises from sympy.assumptions.ask import Q from sympy.assumptions.refine import refine n = symbols('n', integer=True) A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, n) C = MatrixSymbol('C', 3, 4) def test_det(): assert isinstance(Determinant(A), Determinant) assert not isinstance(Determinant(A), MatrixExpr) raises(ShapeError, lambda: Determinant(C)) assert det(eye(3)) == 1 assert det(Matrix(3, 3, [1, 3, 2, 4, 1, 3, 2, 5, 2])) == 17 A / det(A) # Make sure this is possible raises(TypeError, lambda: Determinant(S.One)) assert Determinant(A).arg is A def test_eval_determinant(): assert det(Identity(n)) == 1 assert det(ZeroMatrix(n, n)) == 0 assert det(OneMatrix(n, n)) == Determinant(OneMatrix(n, n)) assert det(OneMatrix(1, 1)) == 1 assert det(OneMatrix(2, 2)) == 0 assert det(Transpose(A)) == det(A) def test_refine(): assert refine(det(A), Q.orthogonal(A)) == 1 assert refine(det(A), Q.singular(A)) == 0 assert refine(det(A), Q.unit_triangular(A)) == 1 assert refine(det(A), Q.normal(A)) == det(A) def test_commutative(): det_a = Determinant(A) det_b = Determinant(B) assert det_a.is_commutative assert det_b.is_commutative assert det_a * det_b == det_b * det_a def test_permanent(): assert isinstance(Permanent(A), Permanent) assert not isinstance(Permanent(A), MatrixExpr) assert isinstance(Permanent(C), Permanent) assert Permanent(ones(3, 3)).doit() == 6 C / per(C) assert per(Matrix(3, 3, [1, 3, 2, 4, 1, 3, 2, 5, 2])) == 103 raises(TypeError, lambda: Permanent(S.One)) assert Permanent(A).arg is A
3f7c0f3d1cb02a7ac0a695fa82cb200faeafd1121ca25c6a0e409a28618f55c3
from sympy.functions import adjoint, conjugate, transpose from sympy.matrices.expressions import MatrixSymbol, Adjoint, trace, Transpose from sympy.matrices import eye, Matrix from sympy.assumptions.ask import Q from sympy.assumptions.refine import refine from sympy.core.singleton import S from sympy.core.symbol import symbols n, m, l, k, p = symbols('n m l k p', integer=True) A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', m, l) C = MatrixSymbol('C', n, n) def test_transpose(): Sq = MatrixSymbol('Sq', n, n) assert transpose(A) == Transpose(A) assert Transpose(A).shape == (m, n) assert Transpose(A*B).shape == (l, n) assert transpose(Transpose(A)) == A assert isinstance(Transpose(Transpose(A)), Transpose) assert adjoint(Transpose(A)) == Adjoint(Transpose(A)) assert conjugate(Transpose(A)) == Adjoint(A) assert Transpose(eye(3)).doit() == eye(3) assert Transpose(S(5)).doit() == S(5) assert Transpose(Matrix([[1, 2], [3, 4]])).doit() == Matrix([[1, 3], [2, 4]]) assert transpose(trace(Sq)) == trace(Sq) assert trace(Transpose(Sq)) == trace(Sq) assert Transpose(Sq)[0, 1] == Sq[1, 0] assert Transpose(A*B).doit() == Transpose(B) * Transpose(A) def test_transpose_MatAdd_MatMul(): # Issue 16807 from sympy.functions.elementary.trigonometric import cos x = symbols('x') M = MatrixSymbol('M', 3, 3) N = MatrixSymbol('N', 3, 3) assert (N + (cos(x) * M)).T == cos(x)*M.T + N.T def test_refine(): assert refine(C.T, Q.symmetric(C)) == C def test_transpose1x1(): m = MatrixSymbol('m', 1, 1) assert m == refine(m.T) assert m == refine(m.T.T) def test_issue_9817(): from sympy.matrices.expressions import Identity v = MatrixSymbol('v', 3, 1) A = MatrixSymbol('A', 3, 3) x = Matrix([i + 1 for i in range(3)]) X = Identity(3) quadratic = v.T * A * v subbed = quadratic.xreplace({v:x, A:X}) assert subbed.as_explicit() == Matrix([[14]])
bd4bc868bef697649ca60b04daa979d3d2c5a0f50ef35ec782df54b2c50d71d8
""" Some examples have been taken from: http://www.math.uwaterloo.ca/~hwolkowi//matrixcookbook.pdf """ from sympy.combinatorics import Permutation from sympy.concrete.summations import Sum from sympy.core.numbers import Rational from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin, tan) from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.matrices.expressions.determinant import Determinant from sympy.matrices.expressions.diagonal import DiagMatrix from sympy.matrices.expressions.hadamard import (HadamardPower, HadamardProduct, hadamard_product) from sympy.matrices.expressions.inverse import Inverse from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.special import OneMatrix from sympy.matrices.expressions.trace import Trace from sympy.matrices.expressions.matadd import MatAdd from sympy.matrices.expressions.matmul import MatMul from sympy.matrices.expressions.special import (Identity, ZeroMatrix) from sympy.tensor.array.array_derivatives import ArrayDerivative from sympy.matrices.expressions import hadamard_power from sympy.tensor.array.expressions.array_expressions import ArrayAdd, ArrayTensorProduct, PermuteDims k = symbols("k") i, j = symbols("i j") m, n = symbols("m n") X = MatrixSymbol("X", k, k) x = MatrixSymbol("x", k, 1) y = MatrixSymbol("y", k, 1) A = MatrixSymbol("A", k, k) B = MatrixSymbol("B", k, k) C = MatrixSymbol("C", k, k) D = MatrixSymbol("D", k, k) a = MatrixSymbol("a", k, 1) b = MatrixSymbol("b", k, 1) c = MatrixSymbol("c", k, 1) d = MatrixSymbol("d", k, 1) KDelta = lambda i, j: KroneckerDelta(i, j, (0, k-1)) def _check_derivative_with_explicit_matrix(expr, x, diffexpr, dim=2): # TODO: this is commented because it slows down the tests. return expr = expr.xreplace({k: dim}) x = x.xreplace({k: dim}) diffexpr = diffexpr.xreplace({k: dim}) expr = expr.as_explicit() x = x.as_explicit() diffexpr = diffexpr.as_explicit() assert expr.diff(x).reshape(*diffexpr.shape).tomatrix() == diffexpr def test_matrix_derivative_by_scalar(): assert A.diff(i) == ZeroMatrix(k, k) assert (A*(X + B)*c).diff(i) == ZeroMatrix(k, 1) assert x.diff(i) == ZeroMatrix(k, 1) assert (x.T*y).diff(i) == ZeroMatrix(1, 1) assert (x*x.T).diff(i) == ZeroMatrix(k, k) assert (x + y).diff(i) == ZeroMatrix(k, 1) assert hadamard_power(x, 2).diff(i) == ZeroMatrix(k, 1) assert hadamard_power(x, i).diff(i).dummy_eq( HadamardProduct(x.applyfunc(log), HadamardPower(x, i))) assert hadamard_product(x, y).diff(i) == ZeroMatrix(k, 1) assert hadamard_product(i*OneMatrix(k, 1), x, y).diff(i) == hadamard_product(x, y) assert (i*x).diff(i) == x assert (sin(i)*A*B*x).diff(i) == cos(i)*A*B*x assert x.applyfunc(sin).diff(i) == ZeroMatrix(k, 1) assert Trace(i**2*X).diff(i) == 2*i*Trace(X) mu = symbols("mu") expr = (2*mu*x) assert expr.diff(x) == 2*mu*Identity(k) def test_matrix_derivative_non_matrix_result(): # This is a 4-dimensional array: I = Identity(k) AdA = PermuteDims(ArrayTensorProduct(I, I), Permutation(3)(1, 2)) assert A.diff(A) == AdA assert A.T.diff(A) == PermuteDims(ArrayTensorProduct(I, I), Permutation(3)(1, 2, 3)) assert (2*A).diff(A) == PermuteDims(ArrayTensorProduct(2*I, I), Permutation(3)(1, 2)) assert MatAdd(A, A).diff(A) == ArrayAdd(AdA, AdA) assert (A + B).diff(A) == AdA def test_matrix_derivative_trivial_cases(): # Cookbook example 33: # TODO: find a way to represent a four-dimensional zero-array: assert X.diff(A) == ArrayDerivative(X, A) def test_matrix_derivative_with_inverse(): # Cookbook example 61: expr = a.T*Inverse(X)*b assert expr.diff(X) == -Inverse(X).T*a*b.T*Inverse(X).T # Cookbook example 62: expr = Determinant(Inverse(X)) # Not implemented yet: # assert expr.diff(X) == -Determinant(X.inv())*(X.inv()).T # Cookbook example 63: expr = Trace(A*Inverse(X)*B) assert expr.diff(X) == -(X**(-1)*B*A*X**(-1)).T # Cookbook example 64: expr = Trace(Inverse(X + A)) assert expr.diff(X) == -(Inverse(X + A)).T**2 def test_matrix_derivative_vectors_and_scalars(): assert x.diff(x) == Identity(k) assert x[i, 0].diff(x[m, 0]).doit() == KDelta(m, i) assert x.T.diff(x) == Identity(k) # Cookbook example 69: expr = x.T*a assert expr.diff(x) == a assert expr[0, 0].diff(x[m, 0]).doit() == a[m, 0] expr = a.T*x assert expr.diff(x) == a # Cookbook example 70: expr = a.T*X*b assert expr.diff(X) == a*b.T # Cookbook example 71: expr = a.T*X.T*b assert expr.diff(X) == b*a.T # Cookbook example 72: expr = a.T*X*a assert expr.diff(X) == a*a.T expr = a.T*X.T*a assert expr.diff(X) == a*a.T # Cookbook example 77: expr = b.T*X.T*X*c assert expr.diff(X) == X*b*c.T + X*c*b.T # Cookbook example 78: expr = (B*x + b).T*C*(D*x + d) assert expr.diff(x) == B.T*C*(D*x + d) + D.T*C.T*(B*x + b) # Cookbook example 81: expr = x.T*B*x assert expr.diff(x) == B*x + B.T*x # Cookbook example 82: expr = b.T*X.T*D*X*c assert expr.diff(X) == D.T*X*b*c.T + D*X*c*b.T # Cookbook example 83: expr = (X*b + c).T*D*(X*b + c) assert expr.diff(X) == D*(X*b + c)*b.T + D.T*(X*b + c)*b.T assert str(expr[0, 0].diff(X[m, n]).doit()) == \ 'b[n, 0]*Sum((c[_i_1, 0] + Sum(X[_i_1, _i_3]*b[_i_3, 0], (_i_3, 0, k - 1)))*D[_i_1, m], (_i_1, 0, k - 1)) + Sum((c[_i_2, 0] + Sum(X[_i_2, _i_4]*b[_i_4, 0], (_i_4, 0, k - 1)))*D[m, _i_2]*b[n, 0], (_i_2, 0, k - 1))' def test_matrix_derivatives_of_traces(): expr = Trace(A)*A I = Identity(k) assert expr.diff(A) == ArrayAdd(ArrayTensorProduct(I, A), PermuteDims(ArrayTensorProduct(Trace(A)*I, I), Permutation(3)(1, 2))) assert expr[i, j].diff(A[m, n]).doit() == ( KDelta(i, m)*KDelta(j, n)*Trace(A) + KDelta(m, n)*A[i, j] ) ## First order: # Cookbook example 99: expr = Trace(X) assert expr.diff(X) == Identity(k) assert expr.rewrite(Sum).diff(X[m, n]).doit() == KDelta(m, n) # Cookbook example 100: expr = Trace(X*A) assert expr.diff(X) == A.T assert expr.rewrite(Sum).diff(X[m, n]).doit() == A[n, m] # Cookbook example 101: expr = Trace(A*X*B) assert expr.diff(X) == A.T*B.T assert expr.rewrite(Sum).diff(X[m, n]).doit().dummy_eq((A.T*B.T)[m, n]) # Cookbook example 102: expr = Trace(A*X.T*B) assert expr.diff(X) == B*A # Cookbook example 103: expr = Trace(X.T*A) assert expr.diff(X) == A # Cookbook example 104: expr = Trace(A*X.T) assert expr.diff(X) == A # Cookbook example 105: # TODO: TensorProduct is not supported #expr = Trace(TensorProduct(A, X)) #assert expr.diff(X) == Trace(A)*Identity(k) ## Second order: # Cookbook example 106: expr = Trace(X**2) assert expr.diff(X) == 2*X.T # Cookbook example 107: expr = Trace(X**2*B) assert expr.diff(X) == (X*B + B*X).T expr = Trace(MatMul(X, X, B)) assert expr.diff(X) == (X*B + B*X).T # Cookbook example 108: expr = Trace(X.T*B*X) assert expr.diff(X) == B*X + B.T*X # Cookbook example 109: expr = Trace(B*X*X.T) assert expr.diff(X) == B*X + B.T*X # Cookbook example 110: expr = Trace(X*X.T*B) assert expr.diff(X) == B*X + B.T*X # Cookbook example 111: expr = Trace(X*B*X.T) assert expr.diff(X) == X*B.T + X*B # Cookbook example 112: expr = Trace(B*X.T*X) assert expr.diff(X) == X*B.T + X*B # Cookbook example 113: expr = Trace(X.T*X*B) assert expr.diff(X) == X*B.T + X*B # Cookbook example 114: expr = Trace(A*X*B*X) assert expr.diff(X) == A.T*X.T*B.T + B.T*X.T*A.T # Cookbook example 115: expr = Trace(X.T*X) assert expr.diff(X) == 2*X expr = Trace(X*X.T) assert expr.diff(X) == 2*X # Cookbook example 116: expr = Trace(B.T*X.T*C*X*B) assert expr.diff(X) == C.T*X*B*B.T + C*X*B*B.T # Cookbook example 117: expr = Trace(X.T*B*X*C) assert expr.diff(X) == B*X*C + B.T*X*C.T # Cookbook example 118: expr = Trace(A*X*B*X.T*C) assert expr.diff(X) == A.T*C.T*X*B.T + C*A*X*B # Cookbook example 119: expr = Trace((A*X*B + C)*(A*X*B + C).T) assert expr.diff(X) == 2*A.T*(A*X*B + C)*B.T # Cookbook example 120: # TODO: no support for TensorProduct. # expr = Trace(TensorProduct(X, X)) # expr = Trace(X)*Trace(X) # expr.diff(X) == 2*Trace(X)*Identity(k) # Higher Order # Cookbook example 121: expr = Trace(X**k) #assert expr.diff(X) == k*(X**(k-1)).T # Cookbook example 122: expr = Trace(A*X**k) #assert expr.diff(X) == # Needs indices # Cookbook example 123: expr = Trace(B.T*X.T*C*X*X.T*C*X*B) assert expr.diff(X) == C*X*X.T*C*X*B*B.T + C.T*X*B*B.T*X.T*C.T*X + C*X*B*B.T*X.T*C*X + C.T*X*X.T*C.T*X*B*B.T # Other # Cookbook example 124: expr = Trace(A*X**(-1)*B) assert expr.diff(X) == -Inverse(X).T*A.T*B.T*Inverse(X).T # Cookbook example 125: expr = Trace(Inverse(X.T*C*X)*A) # Warning: result in the cookbook is equivalent if B and C are symmetric: assert expr.diff(X) == - X.inv().T*A.T*X.inv()*C.inv().T*X.inv().T - X.inv().T*A*X.inv()*C.inv()*X.inv().T # Cookbook example 126: expr = Trace((X.T*C*X).inv()*(X.T*B*X)) assert expr.diff(X) == -2*C*X*(X.T*C*X).inv()*X.T*B*X*(X.T*C*X).inv() + 2*B*X*(X.T*C*X).inv() # Cookbook example 127: expr = Trace((A + X.T*C*X).inv()*(X.T*B*X)) # Warning: result in the cookbook is equivalent if B and C are symmetric: assert expr.diff(X) == B*X*Inverse(A + X.T*C*X) - C*X*Inverse(A + X.T*C*X)*X.T*B*X*Inverse(A + X.T*C*X) - C.T*X*Inverse(A.T + (C*X).T*X)*X.T*B.T*X*Inverse(A.T + (C*X).T*X) + B.T*X*Inverse(A.T + (C*X).T*X) def test_derivatives_of_complicated_matrix_expr(): expr = a.T*(A*X*(X.T*B + X*A) + B.T*X.T*(a*b.T*(X*D*X.T + X*(X.T*B + A*X)*D*B - X.T*C.T*A)*B + B*(X*D.T + B*A*X*A.T - 3*X*D))*B + 42*X*B*X.T*A.T*(X + X.T))*b result = (B*(B*A*X*A.T - 3*X*D + X*D.T) + a*b.T*(X*(A*X + X.T*B)*D*B + X*D*X.T - X.T*C.T*A)*B)*B*b*a.T*B.T + B**2*b*a.T*B.T*X.T*a*b.T*X*D + 42*A*X*B.T*X.T*a*b.T + B*D*B**3*b*a.T*B.T*X.T*a*b.T*X + B*b*a.T*A*X + a*b.T*(42*X + 42*X.T)*A*X*B.T + b*a.T*X*B*a*b.T*B.T**2*X*D.T + b*a.T*X*B*a*b.T*B.T**3*D.T*(B.T*X + X.T*A.T) + 42*b*a.T*X*B*X.T*A.T + A.T*(42*X + 42*X.T)*b*a.T*X*B + A.T*B.T**2*X*B*a*b.T*B.T*A + A.T*a*b.T*(A.T*X.T + B.T*X) + A.T*X.T*b*a.T*X*B*a*b.T*B.T**3*D.T + B.T*X*B*a*b.T*B.T*D - 3*B.T*X*B*a*b.T*B.T*D.T - C.T*A*B**2*b*a.T*B.T*X.T*a*b.T + X.T*A.T*a*b.T*A.T assert expr.diff(X) == result def test_mixed_deriv_mixed_expressions(): expr = 3*Trace(A) assert expr.diff(A) == 3*Identity(k) expr = k deriv = expr.diff(A) assert isinstance(deriv, ZeroMatrix) assert deriv == ZeroMatrix(k, k) expr = Trace(A)**2 assert expr.diff(A) == (2*Trace(A))*Identity(k) expr = Trace(A)*A I = Identity(k) assert expr.diff(A) == ArrayAdd(ArrayTensorProduct(I, A), PermuteDims(ArrayTensorProduct(Trace(A)*I, I), Permutation(3)(1, 2))) expr = Trace(Trace(A)*A) assert expr.diff(A) == (2*Trace(A))*Identity(k) expr = Trace(Trace(Trace(A)*A)*A) assert expr.diff(A) == (3*Trace(A)**2)*Identity(k) def test_derivatives_matrix_norms(): expr = x.T*y assert expr.diff(x) == y assert expr[0, 0].diff(x[m, 0]).doit() == y[m, 0] expr = (x.T*y)**S.Half assert expr.diff(x) == y/(2*sqrt(x.T*y)) expr = (x.T*x)**S.Half assert expr.diff(x) == x*(x.T*x)**Rational(-1, 2) expr = (c.T*a*x.T*b)**S.Half assert expr.diff(x) == b*a.T*c/sqrt(c.T*a*x.T*b)/2 expr = (c.T*a*x.T*b)**Rational(1, 3) assert expr.diff(x) == b*a.T*c*(c.T*a*x.T*b)**Rational(-2, 3)/3 expr = (a.T*X*b)**S.Half assert expr.diff(X) == a/(2*sqrt(a.T*X*b))*b.T expr = d.T*x*(a.T*X*b)**S.Half*y.T*c assert expr.diff(X) == a/(2*sqrt(a.T*X*b))*x.T*d*y.T*c*b.T def test_derivatives_elementwise_applyfunc(): expr = x.applyfunc(tan) assert expr.diff(x).dummy_eq( DiagMatrix(x.applyfunc(lambda x: tan(x)**2 + 1))) assert expr[i, 0].diff(x[m, 0]).doit() == (tan(x[i, 0])**2 + 1)*KDelta(i, m) _check_derivative_with_explicit_matrix(expr, x, expr.diff(x)) expr = (i**2*x).applyfunc(sin) assert expr.diff(i).dummy_eq( HadamardProduct((2*i)*x, (i**2*x).applyfunc(cos))) assert expr[i, 0].diff(i).doit() == 2*i*x[i, 0]*cos(i**2*x[i, 0]) _check_derivative_with_explicit_matrix(expr, i, expr.diff(i)) expr = (log(i)*A*B).applyfunc(sin) assert expr.diff(i).dummy_eq( HadamardProduct(A*B/i, (log(i)*A*B).applyfunc(cos))) _check_derivative_with_explicit_matrix(expr, i, expr.diff(i)) expr = A*x.applyfunc(exp) # TODO: restore this result (currently returning the transpose): # assert expr.diff(x).dummy_eq(DiagMatrix(x.applyfunc(exp))*A.T) _check_derivative_with_explicit_matrix(expr, x, expr.diff(x)) expr = x.T*A*x + k*y.applyfunc(sin).T*x assert expr.diff(x).dummy_eq(A.T*x + A*x + k*y.applyfunc(sin)) _check_derivative_with_explicit_matrix(expr, x, expr.diff(x)) expr = x.applyfunc(sin).T*y # TODO: restore (currently returning the traspose): # assert expr.diff(x).dummy_eq(DiagMatrix(x.applyfunc(cos))*y) _check_derivative_with_explicit_matrix(expr, x, expr.diff(x)) expr = (a.T * X * b).applyfunc(sin) assert expr.diff(X).dummy_eq(a*(a.T*X*b).applyfunc(cos)*b.T) _check_derivative_with_explicit_matrix(expr, X, expr.diff(X)) expr = a.T * X.applyfunc(sin) * b assert expr.diff(X).dummy_eq( DiagMatrix(a)*X.applyfunc(cos)*DiagMatrix(b)) _check_derivative_with_explicit_matrix(expr, X, expr.diff(X)) expr = a.T * (A*X*B).applyfunc(sin) * b assert expr.diff(X).dummy_eq( A.T*DiagMatrix(a)*(A*X*B).applyfunc(cos)*DiagMatrix(b)*B.T) _check_derivative_with_explicit_matrix(expr, X, expr.diff(X)) expr = a.T * (A*X*b).applyfunc(sin) * b.T # TODO: not implemented #assert expr.diff(X) == ... #_check_derivative_with_explicit_matrix(expr, X, expr.diff(X)) expr = a.T*A*X.applyfunc(sin)*B*b assert expr.diff(X).dummy_eq( HadamardProduct(A.T * a * b.T * B.T, X.applyfunc(cos))) expr = a.T * (A*X.applyfunc(sin)*B).applyfunc(log) * b # TODO: wrong # assert expr.diff(X) == A.T*DiagMatrix(a)*(A*X.applyfunc(sin)*B).applyfunc(Lambda(k, 1/k))*DiagMatrix(b)*B.T expr = a.T * (X.applyfunc(sin)).applyfunc(log) * b # TODO: wrong # assert expr.diff(X) == DiagMatrix(a)*X.applyfunc(sin).applyfunc(Lambda(k, 1/k))*DiagMatrix(b) def test_derivatives_of_hadamard_expressions(): # Hadamard Product expr = hadamard_product(a, x, b) assert expr.diff(x) == DiagMatrix(hadamard_product(b, a)) expr = a.T*hadamard_product(A, X, B)*b assert expr.diff(X) == HadamardProduct(a*b.T, A, B) # Hadamard Power expr = hadamard_power(x, 2) assert expr.diff(x).doit() == 2*DiagMatrix(x) expr = hadamard_power(x.T, 2) assert expr.diff(x).doit() == 2*DiagMatrix(x) expr = hadamard_power(x, S.Half) assert expr.diff(x) == S.Half*DiagMatrix(hadamard_power(x, Rational(-1, 2))) expr = hadamard_power(a.T*X*b, 2) assert expr.diff(X) == 2*a*a.T*X*b*b.T expr = hadamard_power(a.T*X*b, S.Half) assert expr.diff(X) == a/(2*sqrt(a.T*X*b))*b.T
11856ce87150347d97a341f808c267442393c9549858f3f838775e3709b0ef79
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) 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, ShapeError, SparseMatrix, Transpose, Adjoint, NonSquareMatrixError, MatrixSet) 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_shape(): assert A.shape == (n, m) assert (A*B).shape == (n, l) raises(ShapeError, lambda: B*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_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 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(ShapeError, lambda: A + B.T) raises(TypeError, lambda: A + 1) raises(TypeError, lambda: 5 + A) raises(TypeError, lambda: 5 - A) assert A + ZeroMatrix(n, m) - A == ZeroMatrix(n, m) with raises(TypeError): 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) raises(ShapeError, lambda: B*A) 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_indexing(): A = MatrixSymbol('A', n, m) A[1, 2] A[l, k] A[l+1, k+1] 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
e943c0fd48422f924f6da40239ab4c9f18469d0f9a20799bde55ea6f0ad2a081
from sympy.matrices.expressions.factorizations import lu, LofCholesky, qr, svd from sympy.assumptions.ask import (Q, ask) from sympy.core.symbol import Symbol from sympy.matrices.expressions.matexpr import MatrixSymbol n = Symbol('n') X = MatrixSymbol('X', n, n) def test_LU(): L, U = lu(X) assert L.shape == U.shape == X.shape assert ask(Q.lower_triangular(L)) assert ask(Q.upper_triangular(U)) def test_Cholesky(): LofCholesky(X) def test_QR(): Q_, R = qr(X) assert Q_.shape == R.shape == X.shape assert ask(Q.orthogonal(Q_)) assert ask(Q.upper_triangular(R)) def test_svd(): U, S, V = svd(X) assert U.shape == S.shape == V.shape == X.shape assert ask(Q.orthogonal(U)) assert ask(Q.orthogonal(V)) assert ask(Q.diagonal(S))
c306106bb2cd9738410397d4e7480fc84f1ca9a25fd2cdceef43d4c7878d0840
from sympy.concrete.summations import Sum from sympy.core.symbol import symbols, Symbol, Dummy from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.matrices.dense import eye from sympy.matrices.expressions.blockmatrix import BlockMatrix from sympy.matrices.expressions.hadamard import HadamardPower from sympy.matrices.expressions.matexpr import (MatrixSymbol, MatrixExpr, MatrixElement) from sympy.matrices.expressions.matpow import MatPow from sympy.matrices.expressions.special import (ZeroMatrix, Identity, OneMatrix) from sympy.matrices.expressions.trace import Trace, trace from sympy.matrices.immutable import ImmutableMatrix from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct from sympy.testing.pytest import XFAIL, raises k, l, m, n = symbols('k l m n', integer=True) i, j = symbols('i j', integer=True) W = MatrixSymbol('W', k, l) X = MatrixSymbol('X', l, m) Y = MatrixSymbol('Y', l, m) Z = MatrixSymbol('Z', m, n) X1 = MatrixSymbol('X1', m, m) X2 = MatrixSymbol('X2', m, m) X3 = MatrixSymbol('X3', m, m) X4 = MatrixSymbol('X4', m, m) A = MatrixSymbol('A', 2, 2) B = MatrixSymbol('B', 2, 2) x = MatrixSymbol('x', 1, 2) y = MatrixSymbol('x', 2, 1) def test_symbolic_indexing(): x12 = X[1, 2] assert all(s in str(x12) for s in ['1', '2', X.name]) # We don't care about the exact form of this. We do want to make sure # that all of these features are present def test_add_index(): assert (X + Y)[i, j] == X[i, j] + Y[i, j] def test_mul_index(): assert (A*y)[0, 0] == A[0, 0]*y[0, 0] + A[0, 1]*y[1, 0] assert (A*B).as_mutable() == (A.as_mutable() * B.as_mutable()) X = MatrixSymbol('X', n, m) Y = MatrixSymbol('Y', m, k) result = (X*Y)[4,2] expected = Sum(X[4, i]*Y[i, 2], (i, 0, m - 1)) assert result.args[0].dummy_eq(expected.args[0], i) assert result.args[1][1:] == expected.args[1][1:] def test_pow_index(): Q = MatPow(A, 2) assert Q[0, 0] == A[0, 0]**2 + A[0, 1]*A[1, 0] n = symbols("n") Q2 = A**n assert Q2[0, 0] == 2*( -sqrt((A[0, 0] + A[1, 1])**2 - 4*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0])/2 + A[0, 0]/2 + A[1, 1]/2 )**n * \ A[0, 1]*A[1, 0]/( (sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] + A[1, 1]**2) + A[0, 0] - A[1, 1])* sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] + A[1, 1]**2) ) - 2*( sqrt((A[0, 0] + A[1, 1])**2 - 4*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0])/2 + A[0, 0]/2 + A[1, 1]/2 )**n * A[0, 1]*A[1, 0]/( (-sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] + A[1, 1]**2) + A[0, 0] - A[1, 1])* sqrt(A[0, 0]**2 - 2*A[0, 0]*A[1, 1] + 4*A[0, 1]*A[1, 0] + A[1, 1]**2) ) def test_transpose_index(): assert X.T[i, j] == X[j, i] def test_Identity_index(): I = Identity(3) assert I[0, 0] == I[1, 1] == I[2, 2] == 1 assert I[1, 0] == I[0, 1] == I[2, 1] == 0 assert I[i, 0].delta_range == (0, 2) raises(IndexError, lambda: I[3, 3]) def test_block_index(): I = Identity(3) Z = ZeroMatrix(3, 3) B = BlockMatrix([[I, I], [I, I]]) e3 = ImmutableMatrix(eye(3)) BB = BlockMatrix([[e3, e3], [e3, e3]]) assert B[0, 0] == B[3, 0] == B[0, 3] == B[3, 3] == 1 assert B[4, 3] == B[5, 1] == 0 BB = BlockMatrix([[e3, e3], [e3, e3]]) assert B.as_explicit() == BB.as_explicit() BI = BlockMatrix([[I, Z], [Z, I]]) assert BI.as_explicit().equals(eye(6)) def test_block_index_symbolic(): # Note that these matrices may be zero-sized and indices may be negative, which causes # all naive simplifications given in the comments to be invalid A1 = MatrixSymbol('A1', n, k) A2 = MatrixSymbol('A2', n, l) A3 = MatrixSymbol('A3', m, k) A4 = MatrixSymbol('A4', m, l) A = BlockMatrix([[A1, A2], [A3, A4]]) assert A[0, 0] == MatrixElement(A, 0, 0) # Cannot be A1[0, 0] assert A[n - 1, k - 1] == A1[n - 1, k - 1] assert A[n, k] == A4[0, 0] assert A[n + m - 1, 0] == MatrixElement(A, n + m - 1, 0) # Cannot be A3[m - 1, 0] assert A[0, k + l - 1] == MatrixElement(A, 0, k + l - 1) # Cannot be A2[0, l - 1] assert A[n + m - 1, k + l - 1] == MatrixElement(A, n + m - 1, k + l - 1) # Cannot be A4[m - 1, l - 1] assert A[i, j] == MatrixElement(A, i, j) assert A[n + i, k + j] == MatrixElement(A, n + i, k + j) # Cannot be A4[i, j] assert A[n - i - 1, k - j - 1] == MatrixElement(A, n - i - 1, k - j - 1) # Cannot be A1[n - i - 1, k - j - 1] def test_block_index_symbolic_nonzero(): # All invalid simplifications from test_block_index_symbolic() that become valid if all # matrices have nonzero size and all indices are nonnegative k, l, m, n = symbols('k l m n', integer=True, positive=True) i, j = symbols('i j', integer=True, nonnegative=True) A1 = MatrixSymbol('A1', n, k) A2 = MatrixSymbol('A2', n, l) A3 = MatrixSymbol('A3', m, k) A4 = MatrixSymbol('A4', m, l) A = BlockMatrix([[A1, A2], [A3, A4]]) assert A[0, 0] == A1[0, 0] assert A[n + m - 1, 0] == A3[m - 1, 0] assert A[0, k + l - 1] == A2[0, l - 1] assert A[n + m - 1, k + l - 1] == A4[m - 1, l - 1] assert A[i, j] == MatrixElement(A, i, j) assert A[n + i, k + j] == A4[i, j] assert A[n - i - 1, k - j - 1] == A1[n - i - 1, k - j - 1] assert A[2 * n, 2 * k] == A4[n, k] def test_block_index_large(): n, m, k = symbols('n m k', integer=True, positive=True) i = symbols('i', integer=True, nonnegative=True) A1 = MatrixSymbol('A1', n, n) A2 = MatrixSymbol('A2', n, m) A3 = MatrixSymbol('A3', n, k) A4 = MatrixSymbol('A4', m, n) A5 = MatrixSymbol('A5', m, m) A6 = MatrixSymbol('A6', m, k) A7 = MatrixSymbol('A7', k, n) A8 = MatrixSymbol('A8', k, m) A9 = MatrixSymbol('A9', k, k) A = BlockMatrix([[A1, A2, A3], [A4, A5, A6], [A7, A8, A9]]) assert A[n + i, n + i] == MatrixElement(A, n + i, n + i) @XFAIL def test_block_index_symbolic_fail(): # To make this work, symbolic matrix dimensions would need to be somehow assumed nonnegative # even if the symbols aren't specified as such. Then 2 * n < n would correctly evaluate to # False in BlockMatrix._entry() A1 = MatrixSymbol('A1', n, 1) A2 = MatrixSymbol('A2', m, 1) A = BlockMatrix([[A1], [A2]]) assert A[2 * n, 0] == A2[n, 0] def test_slicing(): A.as_explicit()[0, :] # does not raise an error def test_errors(): raises(IndexError, lambda: Identity(2)[1, 2, 3, 4, 5]) raises(IndexError, lambda: Identity(2)[[1, 2, 3, 4, 5]]) def test_matrix_expression_to_indices(): i, j = symbols("i, j") i1, i2, i3 = symbols("i_1:4") def replace_dummies(expr): repl = {i: Symbol(i.name) for i in expr.atoms(Dummy)} return expr.xreplace(repl) expr = W*X*Z assert replace_dummies(expr._entry(i, j)) == \ Sum(W[i, i1]*X[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1)) assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr expr = Z.T*X.T*W.T assert replace_dummies(expr._entry(i, j)) == \ Sum(W[j, i2]*X[i2, i1]*Z[i1, i], (i1, 0, m-1), (i2, 0, l-1)) assert MatrixExpr.from_index_summation(expr._entry(i, j), i) == expr expr = W*X*Z + W*Y*Z assert replace_dummies(expr._entry(i, j)) == \ Sum(W[i, i1]*X[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1)) +\ Sum(W[i, i1]*Y[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1)) assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr expr = 2*W*X*Z + 3*W*Y*Z assert replace_dummies(expr._entry(i, j)) == \ 2*Sum(W[i, i1]*X[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1)) +\ 3*Sum(W[i, i1]*Y[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1)) assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr expr = W*(X + Y)*Z assert replace_dummies(expr._entry(i, j)) == \ Sum(W[i, i1]*(X[i1, i2] + Y[i1, i2])*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1)) assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr expr = A*B**2*A #assert replace_dummies(expr._entry(i, j)) == \ # Sum(A[i, i1]*B[i1, i2]*B[i2, i3]*A[i3, j], (i1, 0, 1), (i2, 0, 1), (i3, 0, 1)) # Check that different dummies are used in sub-multiplications: expr = (X1*X2 + X2*X1)*X3 assert replace_dummies(expr._entry(i, j)) == \ Sum((Sum(X1[i, i2] * X2[i2, i1], (i2, 0, m - 1)) + Sum(X1[i3, i1] * X2[i, i3], (i3, 0, m - 1))) * X3[ i1, j], (i1, 0, m - 1)) def test_matrix_expression_from_index_summation(): from sympy.abc import a,b,c,d A = MatrixSymbol("A", k, k) B = MatrixSymbol("B", k, k) C = MatrixSymbol("C", k, k) w1 = MatrixSymbol("w1", k, 1) i0, i1, i2, i3, i4 = symbols("i0:5", cls=Dummy) expr = Sum(W[a,b]*X[b,c]*Z[c,d], (b, 0, l-1), (c, 0, m-1)) assert MatrixExpr.from_index_summation(expr, a) == W*X*Z expr = Sum(W.T[b,a]*X[b,c]*Z[c,d], (b, 0, l-1), (c, 0, m-1)) assert MatrixExpr.from_index_summation(expr, a) == W*X*Z expr = Sum(A[b, a]*B[b, c]*C[c, d], (b, 0, k-1), (c, 0, k-1)) assert MatrixSymbol.from_index_summation(expr, a) == A.T*B*C expr = Sum(A[b, a]*B[c, b]*C[c, d], (b, 0, k-1), (c, 0, k-1)) assert MatrixSymbol.from_index_summation(expr, a) == A.T*B.T*C expr = Sum(C[c, d]*A[b, a]*B[c, b], (b, 0, k-1), (c, 0, k-1)) assert MatrixSymbol.from_index_summation(expr, a) == A.T*B.T*C expr = Sum(A[a, b] + B[a, b], (a, 0, k-1), (b, 0, k-1)) assert MatrixExpr.from_index_summation(expr, a) == OneMatrix(1, k)*A*OneMatrix(k, 1) + OneMatrix(1, k)*B*OneMatrix(k, 1) expr = Sum(A[a, b]**2, (a, 0, k - 1), (b, 0, k - 1)) assert MatrixExpr.from_index_summation(expr, a) == Trace(A * A.T) expr = Sum(A[a, b]**3, (a, 0, k - 1), (b, 0, k - 1)) assert MatrixExpr.from_index_summation(expr, a) == Trace(HadamardPower(A.T, 2) * A) expr = Sum((A[a, b] + B[a, b])*C[b, c], (b, 0, k-1)) assert MatrixExpr.from_index_summation(expr, a) == (A+B)*C expr = Sum((A[a, b] + B[b, a])*C[b, c], (b, 0, k-1)) assert MatrixExpr.from_index_summation(expr, a) == (A+B.T)*C expr = Sum(A[a, b]*A[b, c]*A[c, d], (b, 0, k-1), (c, 0, k-1)) assert MatrixExpr.from_index_summation(expr, a) == A**3 expr = Sum(A[a, b]*A[b, c]*B[c, d], (b, 0, k-1), (c, 0, k-1)) assert MatrixExpr.from_index_summation(expr, a) == A**2*B # Parse the trace of a matrix: expr = Sum(A[a, a], (a, 0, k-1)) assert MatrixExpr.from_index_summation(expr, None) == trace(A) expr = Sum(A[a, a]*B[b, c]*C[c, d], (a, 0, k-1), (c, 0, k-1)) assert MatrixExpr.from_index_summation(expr, b) == trace(A)*B*C # Check wrong sum ranges (should raise an exception): ## Case 1: 0 to m instead of 0 to m-1 expr = Sum(W[a,b]*X[b,c]*Z[c,d], (b, 0, l-1), (c, 0, m)) raises(ValueError, lambda: MatrixExpr.from_index_summation(expr, a)) ## Case 2: 1 to m-1 instead of 0 to m-1 expr = Sum(W[a,b]*X[b,c]*Z[c,d], (b, 0, l-1), (c, 1, m-1)) raises(ValueError, lambda: MatrixExpr.from_index_summation(expr, a)) # Parse nested sums: expr = Sum(A[a, b]*Sum(B[b, c]*C[c, d], (c, 0, k-1)), (b, 0, k-1)) assert MatrixExpr.from_index_summation(expr, a) == A*B*C # Test Kronecker delta: expr = Sum(A[a, b]*KroneckerDelta(b, c)*B[c, d], (b, 0, k-1), (c, 0, k-1)) assert MatrixExpr.from_index_summation(expr, a) == A*B expr = Sum(KroneckerDelta(i1, m)*KroneckerDelta(i2, n)*A[i, i1]*A[j, i2], (i1, 0, k-1), (i2, 0, k-1)) assert MatrixExpr.from_index_summation(expr, m) == ArrayTensorProduct(A.T, A) # Test numbered indices: expr = Sum(A[i1, i2]*w1[i2, 0], (i2, 0, k-1)) assert MatrixExpr.from_index_summation(expr, i1) == MatrixElement(A*w1, i1, 0) expr = Sum(A[i1, i2]*B[i2, 0], (i2, 0, k-1)) assert MatrixExpr.from_index_summation(expr, i1) == MatrixElement(A*B, i1, 0)
d1e0faf5f6a81d705cb90ee0d90df57eab3e83247f5df7be82ffbb0d784987f7
from sympy.assumptions.ask import (Q, ask) from sympy.core.numbers import (I, Rational) from sympy.core.singleton import S from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.simplify.simplify import simplify from sympy.core.symbol import symbols from sympy.matrices.expressions.fourier import DFT, IDFT from sympy.matrices import det, Matrix, Identity from sympy.testing.pytest import raises def test_dft_creation(): assert DFT(2) assert DFT(0) raises(ValueError, lambda: DFT(-1)) raises(ValueError, lambda: DFT(2.0)) raises(ValueError, lambda: DFT(2 + 1j)) n = symbols('n') assert DFT(n) n = symbols('n', integer=False) raises(ValueError, lambda: DFT(n)) n = symbols('n', negative=True) raises(ValueError, lambda: DFT(n)) def test_dft(): n, i, j = symbols('n i j') assert DFT(4).shape == (4, 4) assert ask(Q.unitary(DFT(4))) assert Abs(simplify(det(Matrix(DFT(4))))) == 1 assert DFT(n)*IDFT(n) == Identity(n) assert DFT(n)[i, j] == exp(-2*S.Pi*I/n)**(i*j) / sqrt(n) def test_dft2(): assert DFT(1).as_explicit() == Matrix([[1]]) assert DFT(2).as_explicit() == 1/sqrt(2)*Matrix([[1,1],[1,-1]]) assert DFT(4).as_explicit() == Matrix([[S.Half, S.Half, S.Half, S.Half], [S.Half, -I/2, Rational(-1,2), I/2], [S.Half, Rational(-1,2), S.Half, Rational(-1,2)], [S.Half, I/2, Rational(-1,2), -I/2]])
dcbe95b3f62bdfa6bc76022a01e21c3447f4c5c5727b21a100d36ed1d948a702
from sympy.matrices.expressions import MatrixSymbol from sympy.matrices.expressions.diagonal import DiagonalMatrix, DiagonalOf, DiagMatrix, diagonalize_vector from sympy.assumptions.ask import (Q, ask) from sympy.core.symbol import Symbol from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.matrices.dense import Matrix from sympy.matrices.expressions.matmul import MatMul from sympy.matrices.expressions.special import Identity from sympy.testing.pytest import raises n = Symbol('n') m = Symbol('m') def test_DiagonalMatrix(): x = MatrixSymbol('x', n, m) D = DiagonalMatrix(x) assert D.diagonal_length is None assert D.shape == (n, m) x = MatrixSymbol('x', n, n) D = DiagonalMatrix(x) assert D.diagonal_length == n assert D.shape == (n, n) assert D[1, 2] == 0 assert D[1, 1] == x[1, 1] i = Symbol('i') j = Symbol('j') x = MatrixSymbol('x', 3, 3) ij = DiagonalMatrix(x)[i, j] assert ij != 0 assert ij.subs({i:0, j:0}) == x[0, 0] assert ij.subs({i:0, j:1}) == 0 assert ij.subs({i:1, j:1}) == x[1, 1] assert ask(Q.diagonal(D)) # affirm that D is diagonal x = MatrixSymbol('x', n, 3) D = DiagonalMatrix(x) assert D.diagonal_length == 3 assert D.shape == (n, 3) assert D[2, m] == KroneckerDelta(2, m)*x[2, m] assert D[3, m] == 0 raises(IndexError, lambda: D[m, 3]) x = MatrixSymbol('x', 3, n) D = DiagonalMatrix(x) assert D.diagonal_length == 3 assert D.shape == (3, n) assert D[m, 2] == KroneckerDelta(m, 2)*x[m, 2] assert D[m, 3] == 0 raises(IndexError, lambda: D[3, m]) x = MatrixSymbol('x', n, m) D = DiagonalMatrix(x) assert D.diagonal_length is None assert D.shape == (n, m) assert D[m, 4] != 0 x = MatrixSymbol('x', 3, 4) assert [DiagonalMatrix(x)[i] for i in range(12)] == [ x[0, 0], 0, 0, 0, 0, x[1, 1], 0, 0, 0, 0, x[2, 2], 0] # shape is retained, issue 12427 assert ( DiagonalMatrix(MatrixSymbol('x', 3, 4))* DiagonalMatrix(MatrixSymbol('x', 4, 2))).shape == (3, 2) def test_DiagonalOf(): x = MatrixSymbol('x', n, n) d = DiagonalOf(x) assert d.shape == (n, 1) assert d.diagonal_length == n assert d[2, 0] == d[2] == x[2, 2] x = MatrixSymbol('x', n, m) d = DiagonalOf(x) assert d.shape == (None, 1) assert d.diagonal_length is None assert d[2, 0] == d[2] == x[2, 2] d = DiagonalOf(MatrixSymbol('x', 4, 3)) assert d.shape == (3, 1) d = DiagonalOf(MatrixSymbol('x', n, 3)) assert d.shape == (3, 1) d = DiagonalOf(MatrixSymbol('x', 3, n)) assert d.shape == (3, 1) x = MatrixSymbol('x', n, m) assert [DiagonalOf(x)[i] for i in range(4)] ==[ x[0, 0], x[1, 1], x[2, 2], x[3, 3]] def test_DiagMatrix(): x = MatrixSymbol('x', n, 1) d = DiagMatrix(x) assert d.shape == (n, n) assert d[0, 1] == 0 assert d[0, 0] == x[0, 0] a = MatrixSymbol('a', 1, 1) d = diagonalize_vector(a) assert isinstance(d, MatrixSymbol) assert a == d assert diagonalize_vector(Identity(3)) == Identity(3) assert DiagMatrix(Identity(3)).doit() == Identity(3) assert isinstance(DiagMatrix(Identity(3)), DiagMatrix) # A diagonal matrix is equal to its transpose: assert DiagMatrix(x).T == DiagMatrix(x) assert diagonalize_vector(x.T) == DiagMatrix(x) dx = DiagMatrix(x) assert dx[0, 0] == x[0, 0] assert dx[1, 1] == x[1, 0] assert dx[0, 1] == 0 assert dx[0, m] == x[0, 0]*KroneckerDelta(0, m) z = MatrixSymbol('z', 1, n) dz = DiagMatrix(z) assert dz[0, 0] == z[0, 0] assert dz[1, 1] == z[0, 1] assert dz[0, 1] == 0 assert dz[0, m] == z[0, m]*KroneckerDelta(0, m) v = MatrixSymbol('v', 3, 1) dv = DiagMatrix(v) assert dv.as_explicit() == Matrix([ [v[0, 0], 0, 0], [0, v[1, 0], 0], [0, 0, v[2, 0]], ]) v = MatrixSymbol('v', 1, 3) dv = DiagMatrix(v) assert dv.as_explicit() == Matrix([ [v[0, 0], 0, 0], [0, v[0, 1], 0], [0, 0, v[0, 2]], ]) dv = DiagMatrix(3*v) assert dv.args == (3*v,) assert dv.doit() == 3*DiagMatrix(v) assert isinstance(dv.doit(), MatMul) a = MatrixSymbol("a", 3, 1).as_explicit() expr = DiagMatrix(a) result = Matrix([ [a[0, 0], 0, 0], [0, a[1, 0], 0], [0, 0, a[2, 0]], ]) assert expr.doit() == result expr = DiagMatrix(a.T) assert expr.doit() == result
9217bf65f6c023f246959a6c7131ead87b72d58c354ce6fb1f84df5c9375d16c
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 from sympy.testing.pytest import raises from sympy.matrices.common import ShapeError 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) raises(ShapeError, lambda: ElementwiseApplyFunction(exp, Z)*ElementwiseApplyFunction(exp, Z)) 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) raises(ShapeError, lambda: M*expr) 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
c580246daea493e9afaa9d19d4ebdfb9a12a43637bcc2d85d1b08fed0b7c7733
from sympy.core import symbols, S from sympy.matrices.expressions import MatrixSymbol, Inverse, MatPow, ZeroMatrix, OneMatrix from sympy.matrices.common import NonSquareMatrixError, NonInvertibleMatrixError 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(NonSquareMatrixError, lambda: Inverse(A)) raises(NonSquareMatrixError, lambda: Inverse(A*B)) raises(NonSquareMatrixError, lambda: ZeroMatrix(n, m).I) raises(NonInvertibleMatrixError, lambda: ZeroMatrix(n, n).I) raises(NonSquareMatrixError, lambda: OneMatrix(n, m).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()
7b91fa6afde2a0e9fc8e48f20c1ad3dcd1260a4c876cde991073a5c81f4e60b9
from sympy.core.mod import Mod from sympy.core.numbers import I from sympy.core.symbol import symbols from sympy.functions.elementary.integers import floor from sympy.matrices.dense import (Matrix, eye) from sympy.matrices import MatrixSymbol, Identity from sympy.matrices.expressions import det, trace from sympy.matrices.expressions.kronecker import (KroneckerProduct, kronecker_product, combine_kronecker) mat1 = Matrix([[1, 2 * I], [1 + I, 3]]) mat2 = Matrix([[2 * I, 3], [4 * I, 2]]) i, j, k, n, m, o, p, x = symbols('i,j,k,n,m,o,p,x') Z = MatrixSymbol('Z', n, n) W = MatrixSymbol('W', m, m) A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', n, m) C = MatrixSymbol('C', m, k) def test_KroneckerProduct(): assert isinstance(KroneckerProduct(A, B), KroneckerProduct) assert KroneckerProduct(A, B).subs(A, C) == KroneckerProduct(C, B) assert KroneckerProduct(A, C).shape == (n*m, m*k) assert (KroneckerProduct(A, C) + KroneckerProduct(-A, C)).is_ZeroMatrix assert (KroneckerProduct(W, Z) * KroneckerProduct(W.I, Z.I)).is_Identity def test_KroneckerProduct_identity(): assert KroneckerProduct(Identity(m), Identity(n)) == Identity(m*n) assert KroneckerProduct(eye(2), eye(3)) == eye(6) def test_KroneckerProduct_explicit(): X = MatrixSymbol('X', 2, 2) Y = MatrixSymbol('Y', 2, 2) kp = KroneckerProduct(X, Y) assert kp.shape == (4, 4) assert kp.as_explicit() == Matrix( [ [X[0, 0]*Y[0, 0], X[0, 0]*Y[0, 1], X[0, 1]*Y[0, 0], X[0, 1]*Y[0, 1]], [X[0, 0]*Y[1, 0], X[0, 0]*Y[1, 1], X[0, 1]*Y[1, 0], X[0, 1]*Y[1, 1]], [X[1, 0]*Y[0, 0], X[1, 0]*Y[0, 1], X[1, 1]*Y[0, 0], X[1, 1]*Y[0, 1]], [X[1, 0]*Y[1, 0], X[1, 0]*Y[1, 1], X[1, 1]*Y[1, 0], X[1, 1]*Y[1, 1]] ] ) def test_tensor_product_adjoint(): assert KroneckerProduct(I*A, B).adjoint() == \ -I*KroneckerProduct(A.adjoint(), B.adjoint()) assert KroneckerProduct(mat1, mat2).adjoint() == \ kronecker_product(mat1.adjoint(), mat2.adjoint()) def test_tensor_product_conjugate(): assert KroneckerProduct(I*A, B).conjugate() == \ -I*KroneckerProduct(A.conjugate(), B.conjugate()) assert KroneckerProduct(mat1, mat2).conjugate() == \ kronecker_product(mat1.conjugate(), mat2.conjugate()) def test_tensor_product_transpose(): assert KroneckerProduct(I*A, B).transpose() == \ I*KroneckerProduct(A.transpose(), B.transpose()) assert KroneckerProduct(mat1, mat2).transpose() == \ kronecker_product(mat1.transpose(), mat2.transpose()) def test_KroneckerProduct_is_associative(): assert kronecker_product(A, kronecker_product( B, C)) == kronecker_product(kronecker_product(A, B), C) assert kronecker_product(A, kronecker_product( B, C)) == KroneckerProduct(A, B, C) def test_KroneckerProduct_is_bilinear(): assert kronecker_product(x*A, B) == x*kronecker_product(A, B) assert kronecker_product(A, x*B) == x*kronecker_product(A, B) def test_KroneckerProduct_determinant(): kp = kronecker_product(W, Z) assert det(kp) == det(W)**n * det(Z)**m def test_KroneckerProduct_trace(): kp = kronecker_product(W, Z) assert trace(kp) == trace(W)*trace(Z) def test_KroneckerProduct_isnt_commutative(): assert KroneckerProduct(A, B) != KroneckerProduct(B, A) assert KroneckerProduct(A, B).is_commutative is False def test_KroneckerProduct_extracts_commutative_part(): assert kronecker_product(x * A, 2 * B) == x * \ 2 * KroneckerProduct(A, B) def test_KroneckerProduct_inverse(): kp = kronecker_product(W, Z) assert kp.inverse() == kronecker_product(W.inverse(), Z.inverse()) def test_KroneckerProduct_combine_add(): kp1 = kronecker_product(A, B) kp2 = kronecker_product(C, W) assert combine_kronecker(kp1*kp2) == kronecker_product(A*C, B*W) def test_KroneckerProduct_combine_mul(): X = MatrixSymbol('X', m, n) Y = MatrixSymbol('Y', m, n) kp1 = kronecker_product(A, X) kp2 = kronecker_product(B, Y) assert combine_kronecker(kp1+kp2) == kronecker_product(A+B, X+Y) def test_KroneckerProduct_combine_pow(): X = MatrixSymbol('X', n, n) Y = MatrixSymbol('Y', n, n) assert combine_kronecker(KroneckerProduct( X, Y)**x) == KroneckerProduct(X**x, Y**x) assert combine_kronecker(x * KroneckerProduct(X, Y) ** 2) == x * KroneckerProduct(X**2, Y**2) assert combine_kronecker( x * (KroneckerProduct(X, Y)**2) * KroneckerProduct(A, B)) == x * KroneckerProduct(X**2 * A, Y**2 * B) # cannot simplify because of non-square arguments to kronecker product: assert combine_kronecker(KroneckerProduct(A, B.T) ** m) == KroneckerProduct(A, B.T) ** m def test_KroneckerProduct_expand(): X = MatrixSymbol('X', n, n) Y = MatrixSymbol('Y', n, n) assert KroneckerProduct(X + Y, Y + Z).expand(kroneckerproduct=True) == \ KroneckerProduct(X, Y) + KroneckerProduct(X, Z) + \ KroneckerProduct(Y, Y) + KroneckerProduct(Y, Z) def test_KroneckerProduct_entry(): A = MatrixSymbol('A', n, m) B = MatrixSymbol('B', o, p) assert KroneckerProduct(A, B)._entry(i, j) == A[Mod(floor(i/o), n), Mod(floor(j/p), m)]*B[Mod(i, o), Mod(j, p)]
209a0b486d2863aa08f107af8f5e7d6fe2272550a7cbd753d43a1eff45a11936
from sympy.core import Lambda, S, symbols from sympy.concrete import Sum from sympy.functions import adjoint, conjugate, transpose from sympy.matrices import eye, Matrix, ShapeError, ImmutableMatrix from sympy.matrices.expressions import ( Adjoint, Identity, FunctionMatrix, MatrixExpr, MatrixSymbol, Trace, ZeroMatrix, trace, MatPow, MatAdd, MatMul ) from sympy.matrices.expressions.special import OneMatrix from sympy.testing.pytest import raises n = symbols('n', integer=True) A = MatrixSymbol('A', n, n) B = MatrixSymbol('B', n, n) C = MatrixSymbol('C', 3, 4) def test_Trace(): assert isinstance(Trace(A), Trace) assert not isinstance(Trace(A), MatrixExpr) raises(ShapeError, lambda: Trace(C)) assert trace(eye(3)) == 3 assert trace(Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])) == 15 assert adjoint(Trace(A)) == trace(Adjoint(A)) assert conjugate(Trace(A)) == trace(Adjoint(A)) assert transpose(Trace(A)) == Trace(A) A / Trace(A) # Make sure this is possible # Some easy simplifications assert trace(Identity(5)) == 5 assert trace(ZeroMatrix(5, 5)) == 0 assert trace(OneMatrix(1, 1)) == 1 assert trace(OneMatrix(2, 2)) == 2 assert trace(OneMatrix(n, n)) == n assert trace(2*A*B) == 2*Trace(A*B) assert trace(A.T) == trace(A) i, j = symbols('i j') F = FunctionMatrix(3, 3, Lambda((i, j), i + j)) assert trace(F) == (0 + 0) + (1 + 1) + (2 + 2) raises(TypeError, lambda: Trace(S.One)) assert Trace(A).arg is A assert str(trace(A)) == str(Trace(A).doit()) assert Trace(A).is_commutative is True def test_Trace_A_plus_B(): assert trace(A + B) == Trace(A) + Trace(B) assert Trace(A + B).arg == MatAdd(A, B) assert Trace(A + B).doit() == Trace(A) + Trace(B) def test_Trace_MatAdd_doit(): # See issue #9028 X = ImmutableMatrix([[1, 2, 3]]*3) Y = MatrixSymbol('Y', 3, 3) q = MatAdd(X, 2*X, Y, -3*Y) assert Trace(q).arg == q assert Trace(q).doit() == 18 - 2*Trace(Y) def test_Trace_MatPow_doit(): X = Matrix([[1, 2], [3, 4]]) assert Trace(X).doit() == 5 q = MatPow(X, 2) assert Trace(q).arg == q assert Trace(q).doit() == 29 def test_Trace_MutableMatrix_plus(): # See issue #9043 X = Matrix([[1, 2], [3, 4]]) assert Trace(X) + Trace(X) == 2*Trace(X) def test_Trace_doit_deep_False(): X = Matrix([[1, 2], [3, 4]]) q = MatPow(X, 2) assert Trace(q).doit(deep=False).arg == q q = MatAdd(X, 2*X) assert Trace(q).doit(deep=False).arg == q q = MatMul(X, 2*X) assert Trace(q).doit(deep=False).arg == q def test_trace_constant_factor(): # Issue 9052: gave 2*Trace(MatMul(A)) instead of 2*Trace(A) assert trace(2*A) == 2*Trace(A) X = ImmutableMatrix([[1, 2], [3, 4]]) assert trace(MatMul(2, X)) == 10 def test_rewrite(): assert isinstance(trace(A).rewrite(Sum), Sum) def test_trace_normalize(): assert Trace(B*A) != Trace(A*B) assert Trace(B*A)._normalize() == Trace(A*B) assert Trace(B*A.T)._normalize() == Trace(A*B.T) def test_trace_as_explicit(): raises(ValueError, lambda: Trace(A).as_explicit()) X = MatrixSymbol("X", 3, 3) assert Trace(X).as_explicit() == X[0, 0] + X[1, 1] + X[2, 2] assert Trace(eye(3)).as_explicit() == 3
4fb8b96604375cc266934cff9639e14882098c1af32cfd7f9a07b42d9209f996
from sympy.matrices.dense import Matrix 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 from sympy.matrices import ShapeError, 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(ShapeError, lambda: HadamardProduct(A, B.T)) 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) 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) C = MatrixSymbol('C', m, p) X = MatrixSymbol('X', m, m) I = Identity(m) with raises(TypeError): hadamard_product() assert hadamard_product(A) == A assert isinstance(hadamard_product(A, B), HadamardProduct) assert hadamard_product(A, B).doit() == hadamard_product(A, B) with raises(ShapeError): hadamard_product(A, C) hadamard_product(A, I) assert hadamard_product(X, I) == X assert isinstance(hadamard_product(X, I), MatrixSymbol) a = MatrixSymbol("a", k, 1) expr = MatAdd(ZeroMatrix(k, 1), OneMatrix(k, 1)) expr = HadamardProduct(expr, a) assert expr.doit() == a 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) 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]]])
2da9baafe7123a8923852949c2ce792aafa02f9fe91df795fd7baf9a7e4f9115
from sympy.core.expr import unchanged from sympy.core.symbol import Symbol, symbols from sympy.matrices.immutable import ImmutableDenseMatrix from sympy.matrices.expressions.companion import CompanionMatrix from sympy.polys.polytools import Poly from sympy.testing.pytest import raises def test_creation(): x = Symbol('x') y = Symbol('y') raises(ValueError, lambda: CompanionMatrix(1)) raises(ValueError, lambda: CompanionMatrix(Poly([1], x))) raises(ValueError, lambda: CompanionMatrix(Poly([2, 1], x))) raises(ValueError, lambda: CompanionMatrix(Poly(x*y, [x, y]))) assert unchanged(CompanionMatrix, Poly([1, 2, 3], x)) def test_shape(): c0, c1, c2 = symbols('c0:3') x = Symbol('x') assert CompanionMatrix(Poly([1, c0], x)).shape == (1, 1) assert CompanionMatrix(Poly([1, c1, c0], x)).shape == (2, 2) assert CompanionMatrix(Poly([1, c2, c1, c0], x)).shape == (3, 3) def test_entry(): c0, c1, c2 = symbols('c0:3') x = Symbol('x') A = CompanionMatrix(Poly([1, c2, c1, c0], x)) assert A[0, 0] == 0 assert A[1, 0] == 1 assert A[1, 1] == 0 assert A[2, 1] == 1 assert A[0, 2] == -c0 assert A[1, 2] == -c1 assert A[2, 2] == -c2 def test_as_explicit(): c0, c1, c2 = symbols('c0:3') x = Symbol('x') assert CompanionMatrix(Poly([1, c0], x)).as_explicit() == \ ImmutableDenseMatrix([-c0]) assert CompanionMatrix(Poly([1, c1, c0], x)).as_explicit() == \ ImmutableDenseMatrix([[0, -c0], [1, -c1]]) assert CompanionMatrix(Poly([1, c2, c1, c0], x)).as_explicit() == \ ImmutableDenseMatrix([[0, 0, -c0], [1, 0, -c1], [0, 1, -c2]])
41e1f2ac1e5fbbcdff86ebfe864f12d1910e2011ffdd5453dc484a5691c2dfb9
from sympy.core.function import Lambda from sympy.core.numbers import oo from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.elementary.miscellaneous import (Max, Min) from sympy.sets.sets import Set from sympy.core import Basic, Expr, Integer from sympy.core.numbers import Infinity, NegativeInfinity, Zero from sympy.multipledispatch import dispatch from sympy.sets import Interval, FiniteSet, Union, ImageSet _x, _y = symbols("x y") @dispatch(Basic, Basic) # type: ignore # noqa:F811 def _set_pow(x, y): # noqa:F811 return None @dispatch(Set, Set) # type: ignore # noqa:F811 def _set_pow(x, y): # noqa:F811 return ImageSet(Lambda((_x, _y), (_x ** _y)), x, y) @dispatch(Expr, Expr) # type: ignore # noqa:F811 def _set_pow(x, y): # noqa:F811 return x**y @dispatch(Interval, Zero) # type: ignore # noqa:F811 def _set_pow(x, z): # noqa:F811 return FiniteSet(S.One) @dispatch(Interval, Integer) # type: ignore # noqa:F811 def _set_pow(x, exponent): # noqa:F811 """ Powers in interval arithmetic https://en.wikipedia.org/wiki/Interval_arithmetic """ s1 = x.start**exponent s2 = x.end**exponent if ((s2 > s1) if exponent > 0 else (x.end > -x.start)) == True: left_open = x.left_open right_open = x.right_open # TODO: handle unevaluated condition. sleft = s2 else: # TODO: `s2 > s1` could be unevaluated. left_open = x.right_open right_open = x.left_open sleft = s1 if x.start.is_positive: return Interval( Min(s1, s2), Max(s1, s2), left_open, right_open) elif x.end.is_negative: return Interval( Min(s1, s2), Max(s1, s2), left_open, right_open) # Case where x.start < 0 and x.end > 0: if exponent.is_odd: if exponent.is_negative: if x.start.is_zero: return Interval(s2, oo, x.right_open) if x.end.is_zero: return Interval(-oo, s1, True, x.left_open) return Union(Interval(-oo, s1, True, x.left_open), Interval(s2, oo, x.right_open)) else: return Interval(s1, s2, x.left_open, x.right_open) elif exponent.is_even: if exponent.is_negative: if x.start.is_zero: return Interval(s2, oo, x.right_open) if x.end.is_zero: return Interval(s1, oo, x.left_open) return Interval(0, oo) else: return Interval(S.Zero, sleft, S.Zero not in x, left_open) @dispatch(Interval, Infinity) # type: ignore # noqa:F811 def _set_pow(b, e): # noqa:F811 # TODO: add logic for open intervals? if b.start.is_nonnegative: if b.end < 1: return FiniteSet(S.Zero) if b.start > 1: return FiniteSet(S.Infinity) return Interval(0, oo) elif b.end.is_negative: if b.start > -1: return FiniteSet(S.Zero) if b.end < -1: return FiniteSet(-oo, oo) return Interval(-oo, oo) else: if b.start > -1: if b.end < 1: return FiniteSet(S.Zero) return Interval(0, oo) return Interval(-oo, oo) @dispatch(Interval, NegativeInfinity) # type: ignore # noqa:F811 def _set_pow(b, e): # noqa:F811 from sympy.sets.setexpr import set_div return _set_pow(set_div(S.One, b), oo)
e006f14ab984903e467df5b569f2bfbf1beeafc986484fb27fb28f0c1b8e0a1b
from sympy.core.function import Lambda, expand_complex from sympy.core.mul import Mul from sympy.core.numbers import ilcm from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Dummy, symbols) from sympy.sets.fancysets import ComplexRegion from sympy.sets.sets import (FiniteSet, Intersection, Interval, Set, Union) from sympy.multipledispatch import dispatch from sympy.sets.conditionset import ConditionSet from sympy.sets.fancysets import (Integers, Naturals, Reals, Range, ImageSet, Rationals) from sympy.sets.sets import EmptySet, UniversalSet, imageset, ProductSet from sympy.simplify.radsimp import numer @dispatch(ConditionSet, ConditionSet) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 return None @dispatch(ConditionSet, Set) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 return ConditionSet(a.sym, a.condition, Intersection(a.base_set, b)) @dispatch(Naturals, Integers) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 return a @dispatch(Naturals, Naturals) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 return a if a is S.Naturals else b @dispatch(Interval, Naturals) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 return intersection_sets(b, a) @dispatch(ComplexRegion, Set) # type: ignore # noqa:F811 def intersection_sets(self, other): # noqa:F811 if other.is_ComplexRegion: # self in rectangular form if (not self.polar) and (not other.polar): return ComplexRegion(Intersection(self.sets, other.sets)) # self in polar form elif self.polar and other.polar: r1, theta1 = self.a_interval, self.b_interval r2, theta2 = other.a_interval, other.b_interval new_r_interval = Intersection(r1, r2) new_theta_interval = Intersection(theta1, theta2) # 0 and 2*Pi means the same if ((2*S.Pi in theta1 and S.Zero in theta2) or (2*S.Pi in theta2 and S.Zero in theta1)): new_theta_interval = Union(new_theta_interval, FiniteSet(0)) return ComplexRegion(new_r_interval*new_theta_interval, polar=True) if other.is_subset(S.Reals): new_interval = [] x = symbols("x", cls=Dummy, real=True) # self in rectangular form if not self.polar: for element in self.psets: if S.Zero in element.args[1]: new_interval.append(element.args[0]) new_interval = Union(*new_interval) return Intersection(new_interval, other) # self in polar form elif self.polar: for element in self.psets: if S.Zero in element.args[1]: new_interval.append(element.args[0]) if S.Pi in element.args[1]: new_interval.append(ImageSet(Lambda(x, -x), element.args[0])) if S.Zero in element.args[0]: new_interval.append(FiniteSet(0)) new_interval = Union(*new_interval) return Intersection(new_interval, other) @dispatch(Integers, Reals) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 return a @dispatch(Range, Interval) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 # Check that there are no symbolic arguments if not all(i.is_number for i in a.args + b.args[:2]): return # In case of null Range, return an EmptySet. if a.size == 0: return S.EmptySet from sympy.functions.elementary.integers import floor, ceiling # trim down to self's size, and represent # as a Range with step 1. start = ceiling(max(b.inf, a.inf)) if start not in b: start += 1 end = floor(min(b.sup, a.sup)) if end not in b: end -= 1 return intersection_sets(a, Range(start, end + 1)) @dispatch(Range, Naturals) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 return intersection_sets(a, Interval(b.inf, S.Infinity)) @dispatch(Range, Range) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 # Check that there are no symbolic range arguments if not all(all(v.is_number for v in r.args) for r in [a, b]): return None # non-overlap quick exits if not b: return S.EmptySet if not a: return S.EmptySet if b.sup < a.inf: return S.EmptySet if b.inf > a.sup: return S.EmptySet # work with finite end at the start r1 = a if r1.start.is_infinite: r1 = r1.reversed r2 = b if r2.start.is_infinite: r2 = r2.reversed # If both ends are infinite then it means that one Range is just the set # of all integers (the step must be 1). if r1.start.is_infinite: return b if r2.start.is_infinite: return a from sympy.solvers.diophantine.diophantine import diop_linear from sympy.functions.elementary.complexes import sign # this equation represents the values of the Range; # it's a linear equation eq = lambda r, i: r.start + i*r.step # we want to know when the two equations might # have integer solutions so we use the diophantine # solver va, vb = diop_linear(eq(r1, Dummy('a')) - eq(r2, Dummy('b'))) # check for no solution no_solution = va is None and vb is None if no_solution: return S.EmptySet # there is a solution # ------------------- # find the coincident point, c a0 = va.as_coeff_Add()[0] c = eq(r1, a0) # find the first point, if possible, in each range # since c may not be that point def _first_finite_point(r1, c): if c == r1.start: return c # st is the signed step we need to take to # get from c to r1.start st = sign(r1.start - c)*step # use Range to calculate the first point: # we want to get as close as possible to # r1.start; the Range will not be null since # it will at least contain c s1 = Range(c, r1.start + st, st)[-1] if s1 == r1.start: pass else: # if we didn't hit r1.start then, if the # sign of st didn't match the sign of r1.step # we are off by one and s1 is not in r1 if sign(r1.step) != sign(st): s1 -= st if s1 not in r1: return return s1 # calculate the step size of the new Range step = abs(ilcm(r1.step, r2.step)) s1 = _first_finite_point(r1, c) if s1 is None: return S.EmptySet s2 = _first_finite_point(r2, c) if s2 is None: return S.EmptySet # replace the corresponding start or stop in # the original Ranges with these points; the # result must have at least one point since # we know that s1 and s2 are in the Ranges def _updated_range(r, first): st = sign(r.step)*step if r.start.is_finite: rv = Range(first, r.stop, st) else: rv = Range(r.start, first + st, st) return rv r1 = _updated_range(a, s1) r2 = _updated_range(b, s2) # work with them both in the increasing direction if sign(r1.step) < 0: r1 = r1.reversed if sign(r2.step) < 0: r2 = r2.reversed # return clipped Range with positive step; it # can't be empty at this point start = max(r1.start, r2.start) stop = min(r1.stop, r2.stop) return Range(start, stop, step) @dispatch(Range, Integers) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 return a @dispatch(ImageSet, Set) # type: ignore # noqa:F811 def intersection_sets(self, other): # noqa:F811 from sympy.solvers.diophantine import diophantine # Only handle the straight-forward univariate case if (len(self.lamda.variables) > 1 or self.lamda.signature != self.lamda.variables): return None base_set = self.base_sets[0] # Intersection between ImageSets with Integers as base set # For {f(n) : n in Integers} & {g(m) : m in Integers} we solve the # diophantine equations f(n)=g(m). # If the solutions for n are {h(t) : t in Integers} then we return # {f(h(t)) : t in integers}. # If the solutions for n are {n_1, n_2, ..., n_k} then we return # {f(n_i) : 1 <= i <= k}. if base_set is S.Integers: gm = None if isinstance(other, ImageSet) and other.base_sets == (S.Integers,): gm = other.lamda.expr var = other.lamda.variables[0] # Symbol of second ImageSet lambda must be distinct from first m = Dummy('m') gm = gm.subs(var, m) elif other is S.Integers: m = gm = Dummy('m') if gm is not None: fn = self.lamda.expr n = self.lamda.variables[0] try: solns = list(diophantine(fn - gm, syms=(n, m), permute=True)) except (TypeError, NotImplementedError): # TypeError if equation not polynomial with rational coeff. # NotImplementedError if correct format but no solver. return # 3 cases are possible for solns: # - empty set, # - one or more parametric (infinite) solutions, # - a finite number of (non-parametric) solution couples. # Among those, there is one type of solution set that is # not helpful here: multiple parametric solutions. if len(solns) == 0: return S.EmptySet elif any(s.free_symbols for tupl in solns for s in tupl): if len(solns) == 1: soln, solm = solns[0] (t,) = soln.free_symbols expr = fn.subs(n, soln.subs(t, n)).expand() return imageset(Lambda(n, expr), S.Integers) else: return else: return FiniteSet(*(fn.subs(n, s[0]) for s in solns)) if other == S.Reals: from sympy.solvers.solvers import denoms, solve_linear def _solution_union(exprs, sym): # return a union of linear solutions to i in expr; # if i cannot be solved, use a ConditionSet for solution sols = [] for i in exprs: x, xis = solve_linear(i, 0, [sym]) if x == sym: sols.append(FiniteSet(xis)) else: sols.append(ConditionSet(sym, Eq(i, 0))) return Union(*sols) f = self.lamda.expr n = self.lamda.variables[0] n_ = Dummy(n.name, real=True) f_ = f.subs(n, n_) re, im = f_.as_real_imag() im = expand_complex(im) re = re.subs(n_, n) im = im.subs(n_, n) ifree = im.free_symbols lam = Lambda(n, re) if im.is_zero: # allow re-evaluation # of self in this case to make # the result canonical pass elif im.is_zero is False: return S.EmptySet elif ifree != {n}: return None else: # univarite imaginary part in same variable; # use numer instead of as_numer_denom to keep # this as fast as possible while still handling # simple cases base_set &= _solution_union( Mul.make_args(numer(im)), n) # exclude values that make denominators 0 base_set -= _solution_union(denoms(f), n) return imageset(lam, base_set) elif isinstance(other, Interval): from sympy.solvers.solveset import (invert_real, invert_complex, solveset) f = self.lamda.expr n = self.lamda.variables[0] new_inf, new_sup = None, None new_lopen, new_ropen = other.left_open, other.right_open if f.is_real: inverter = invert_real else: inverter = invert_complex g1, h1 = inverter(f, other.inf, n) g2, h2 = inverter(f, other.sup, n) if all(isinstance(i, FiniteSet) for i in (h1, h2)): if g1 == n: if len(h1) == 1: new_inf = h1.args[0] if g2 == n: if len(h2) == 1: new_sup = h2.args[0] # TODO: Design a technique to handle multiple-inverse # functions # Any of the new boundary values cannot be determined if any(i is None for i in (new_sup, new_inf)): return range_set = S.EmptySet if all(i.is_real for i in (new_sup, new_inf)): # this assumes continuity of underlying function # however fixes the case when it is decreasing if new_inf > new_sup: new_inf, new_sup = new_sup, new_inf new_interval = Interval(new_inf, new_sup, new_lopen, new_ropen) range_set = base_set.intersect(new_interval) else: if other.is_subset(S.Reals): solutions = solveset(f, n, S.Reals) if not isinstance(range_set, (ImageSet, ConditionSet)): range_set = solutions.intersect(other) else: return if range_set is S.EmptySet: return S.EmptySet elif isinstance(range_set, Range) and range_set.size is not S.Infinity: range_set = FiniteSet(*list(range_set)) if range_set is not None: return imageset(Lambda(n, f), range_set) return else: return @dispatch(ProductSet, ProductSet) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 if len(b.args) != len(a.args): return S.EmptySet return ProductSet(*(i.intersect(j) for i, j in zip(a.sets, b.sets))) @dispatch(Interval, Interval) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 # handle (-oo, oo) infty = S.NegativeInfinity, S.Infinity if a == Interval(*infty): l, r = a.left, a.right if l.is_real or l in infty or r.is_real or r in infty: return b # We can't intersect [0,3] with [x,6] -- we don't know if x>0 or x<0 if not a._is_comparable(b): return None empty = False if a.start <= b.end and b.start <= a.end: # Get topology right. if a.start < b.start: start = b.start left_open = b.left_open elif a.start > b.start: start = a.start left_open = a.left_open else: start = a.start left_open = a.left_open or b.left_open if a.end < b.end: end = a.end right_open = a.right_open elif a.end > b.end: end = b.end right_open = b.right_open else: end = a.end right_open = a.right_open or b.right_open if end - start == 0 and (left_open or right_open): empty = True else: empty = True if empty: return S.EmptySet return Interval(start, end, left_open, right_open) @dispatch(EmptySet, Set) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 return S.EmptySet @dispatch(UniversalSet, Set) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 return b @dispatch(FiniteSet, FiniteSet) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 return FiniteSet(*(a._elements & b._elements)) @dispatch(FiniteSet, Set) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 try: return FiniteSet(*[el for el in a if el in b]) except TypeError: return None # could not evaluate `el in b` due to symbolic ranges. @dispatch(Set, Set) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 return None @dispatch(Integers, Rationals) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 return a @dispatch(Naturals, Rationals) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 return a @dispatch(Rationals, Reals) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 return a def _intlike_interval(a, b): try: from sympy.functions.elementary.integers import floor, ceiling if b._inf is S.NegativeInfinity and b._sup is S.Infinity: return a s = Range(max(a.inf, ceiling(b.left)), floor(b.right) + 1) return intersection_sets(s, b) # take out endpoints if open interval except ValueError: return None @dispatch(Integers, Interval) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 return _intlike_interval(a, b) @dispatch(Naturals, Interval) # type: ignore # noqa:F811 def intersection_sets(a, b): # noqa:F811 return _intlike_interval(a, b)
b8aec56af1eff5941b9320953e478843a1130b8e4d5ed3d6886b9b48b2c86fab
from sympy.core.numbers import oo from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.core import Basic, Expr from sympy.core.numbers import Infinity, NegativeInfinity from sympy.multipledispatch import dispatch from sympy.sets import Interval, FiniteSet # XXX: The functions in this module are clearly not tested and are broken in a # number of ways. _x, _y = symbols("x y") @dispatch(Basic, Basic) # type: ignore # noqa:F811 def _set_add(x, y): # noqa:F811 return None @dispatch(Expr, Expr) # type: ignore # noqa:F811 def _set_add(x, y): # noqa:F811 return x+y @dispatch(Interval, Interval) # type: ignore # noqa:F811 def _set_add(x, y): # noqa:F811 """ Additions in interval arithmetic https://en.wikipedia.org/wiki/Interval_arithmetic """ return Interval(x.start + y.start, x.end + y.end, x.left_open or y.left_open, x.right_open or y.right_open) @dispatch(Interval, Infinity) # type: ignore # noqa:F811 def _set_add(x, y): # noqa:F811 if x.start is S.NegativeInfinity: return Interval(-oo, oo) return FiniteSet({S.Infinity}) @dispatch(Interval, NegativeInfinity) # type: ignore # noqa:F811 def _set_add(x, y): # noqa:F811 if x.end is S.Infinity: return Interval(-oo, oo) return FiniteSet({S.NegativeInfinity}) @dispatch(Basic, Basic) # type: ignore def _set_sub(x, y): # noqa:F811 return None @dispatch(Expr, Expr) # type: ignore # noqa:F811 def _set_sub(x, y): # noqa:F811 return x-y @dispatch(Interval, Interval) # type: ignore # noqa:F811 def _set_sub(x, y): # noqa:F811 """ Subtractions in interval arithmetic https://en.wikipedia.org/wiki/Interval_arithmetic """ return Interval(x.start - y.end, x.end - y.start, x.left_open or y.right_open, x.right_open or y.left_open) @dispatch(Interval, Infinity) # type: ignore # noqa:F811 def _set_sub(x, y): # noqa:F811 if x.start is S.NegativeInfinity: return Interval(-oo, oo) return FiniteSet(-oo) @dispatch(Interval, NegativeInfinity) # type: ignore # noqa:F811 def _set_sub(x, y): # noqa:F811 if x.start is S.NegativeInfinity: return Interval(-oo, oo) return FiniteSet(-oo)
102a4ec59f2e43fded7f443678d6c41be9d8abab34cd21cd743302e7af0d048d
from sympy.core.singleton import S from sympy.core.sympify import sympify from sympy.sets.sets import (EmptySet, FiniteSet, Intersection, Interval, ProductSet, Set, Union, UniversalSet) from sympy.sets.fancysets import (ComplexRegion, Naturals, Naturals0, Integers, Rationals, Reals) from sympy.multipledispatch import dispatch @dispatch(Naturals0, Naturals) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 return a @dispatch(Rationals, Naturals) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 return a @dispatch(Rationals, Naturals0) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 return a @dispatch(Reals, Naturals) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 return a @dispatch(Reals, Naturals0) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 return a @dispatch(Reals, Rationals) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 return a @dispatch(Integers, Set) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 intersect = Intersection(a, b) if intersect == a: return b elif intersect == b: return a @dispatch(ComplexRegion, Set) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 if b.is_subset(S.Reals): # treat a subset of reals as a complex region b = ComplexRegion.from_real(b) if b.is_ComplexRegion: # a in rectangular form if (not a.polar) and (not b.polar): return ComplexRegion(Union(a.sets, b.sets)) # a in polar form elif a.polar and b.polar: return ComplexRegion(Union(a.sets, b.sets), polar=True) return None @dispatch(EmptySet, Set) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 return b @dispatch(UniversalSet, Set) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 return a @dispatch(ProductSet, ProductSet) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 if b.is_subset(a): return a if len(b.sets) != len(a.sets): return None if len(a.sets) == 2: a1, a2 = a.sets b1, b2 = b.sets if a1 == b1: return a1 * Union(a2, b2) if a2 == b2: return Union(a1, b1) * a2 return None @dispatch(ProductSet, Set) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 if b.is_subset(a): return a return None @dispatch(Interval, Interval) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 if a._is_comparable(b): from sympy.functions.elementary.miscellaneous import Min, Max # Non-overlapping intervals end = Min(a.end, b.end) start = Max(a.start, b.start) if (end < start or (end == start and (end not in a and end not in b))): return None else: start = Min(a.start, b.start) end = Max(a.end, b.end) left_open = ((a.start != start or a.left_open) and (b.start != start or b.left_open)) right_open = ((a.end != end or a.right_open) and (b.end != end or b.right_open)) return Interval(start, end, left_open, right_open) @dispatch(Interval, UniversalSet) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 return S.UniversalSet @dispatch(Interval, Set) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 # If I have open end points and these endpoints are contained in b # But only in case, when endpoints are finite. Because # interval does not contain oo or -oo. open_left_in_b_and_finite = (a.left_open and sympify(b.contains(a.start)) is S.true and a.start.is_finite) open_right_in_b_and_finite = (a.right_open and sympify(b.contains(a.end)) is S.true and a.end.is_finite) if open_left_in_b_and_finite or open_right_in_b_and_finite: # Fill in my end points and return open_left = a.left_open and a.start not in b open_right = a.right_open and a.end not in b new_a = Interval(a.start, a.end, open_left, open_right) return {new_a, b} return None @dispatch(FiniteSet, FiniteSet) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 return FiniteSet(*(a._elements | b._elements)) @dispatch(FiniteSet, Set) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 # If `b` set contains one of my elements, remove it from `a` if any(b.contains(x) == True for x in a): return { FiniteSet(*[x for x in a if b.contains(x) != True]), b} return None @dispatch(Set, Set) # type: ignore # noqa:F811 def union_sets(a, b): # noqa:F811 return None
f04f39f3dd9b325d16cc638f1085f8ad5852107f5fddc833363e2b556ffa442a
from sympy.core.singleton import S from sympy.sets.sets import Set from sympy.calculus.singularities import singularities from sympy.core import Expr, Add from sympy.core.function import Lambda, FunctionClass, diff, expand_mul from sympy.core.numbers import Float, oo from sympy.core.symbol import Dummy, symbols, Wild from sympy.functions.elementary.exponential import exp, log from sympy.functions.elementary.miscellaneous import Min, Max from sympy.logic.boolalg import true from sympy.multipledispatch import dispatch from sympy.sets import (imageset, Interval, FiniteSet, Union, ImageSet, Intersection, Range) from sympy.sets.sets import EmptySet from sympy.sets.fancysets import Integers, Naturals, Reals from sympy.functions.elementary.exponential import match_real_imag _x, _y = symbols("x y") FunctionUnion = (FunctionClass, Lambda) @dispatch(FunctionClass, Set) # type: ignore # noqa:F811 def _set_function(f, x): # noqa:F811 return None @dispatch(FunctionUnion, FiniteSet) # type: ignore # noqa:F811 def _set_function(f, x): # noqa:F811 return FiniteSet(*map(f, x)) @dispatch(Lambda, Interval) # type: ignore # noqa:F811 def _set_function(f, x): # noqa:F811 from sympy.solvers.solveset import solveset from sympy.series import limit from sympy.sets import Complement # TODO: handle functions with infinitely many solutions (eg, sin, tan) # TODO: handle multivariate functions expr = f.expr if len(expr.free_symbols) > 1 or len(f.variables) != 1: return var = f.variables[0] if not var.is_real: if expr.subs(var, Dummy(real=True)).is_real is False: return if expr.is_Piecewise: result = S.EmptySet domain_set = x for (p_expr, p_cond) in expr.args: if p_cond is true: intrvl = domain_set else: intrvl = p_cond.as_set() intrvl = Intersection(domain_set, intrvl) if p_expr.is_Number: image = FiniteSet(p_expr) else: image = imageset(Lambda(var, p_expr), intrvl) result = Union(result, image) # remove the part which has been `imaged` domain_set = Complement(domain_set, intrvl) if domain_set is S.EmptySet: break return result if not x.start.is_comparable or not x.end.is_comparable: return try: from sympy.polys.polyutils import _nsort sing = list(singularities(expr, var, x)) if len(sing) > 1: sing = _nsort(sing) except NotImplementedError: return if x.left_open: _start = limit(expr, var, x.start, dir="+") elif x.start not in sing: _start = f(x.start) if x.right_open: _end = limit(expr, var, x.end, dir="-") elif x.end not in sing: _end = f(x.end) if len(sing) == 0: soln_expr = solveset(diff(expr, var), var) if not (isinstance(soln_expr, FiniteSet) or soln_expr is S.EmptySet): return solns = list(soln_expr) extr = [_start, _end] + [f(i) for i in solns if i.is_real and i in x] start, end = Min(*extr), Max(*extr) left_open, right_open = False, False if _start <= _end: # the minimum or maximum value can occur simultaneously # on both the edge of the interval and in some interior # point if start == _start and start not in solns: left_open = x.left_open if end == _end and end not in solns: right_open = x.right_open else: if start == _end and start not in solns: left_open = x.right_open if end == _start and end not in solns: right_open = x.left_open return Interval(start, end, left_open, right_open) else: return imageset(f, Interval(x.start, sing[0], x.left_open, True)) + \ Union(*[imageset(f, Interval(sing[i], sing[i + 1], True, True)) for i in range(0, len(sing) - 1)]) + \ imageset(f, Interval(sing[-1], x.end, True, x.right_open)) @dispatch(FunctionClass, Interval) # type: ignore # noqa:F811 def _set_function(f, x): # noqa:F811 if f == exp: return Interval(exp(x.start), exp(x.end), x.left_open, x.right_open) elif f == log: return Interval(log(x.start), log(x.end), x.left_open, x.right_open) return ImageSet(Lambda(_x, f(_x)), x) @dispatch(FunctionUnion, Union) # type: ignore # noqa:F811 def _set_function(f, x): # noqa:F811 return Union(*(imageset(f, arg) for arg in x.args)) @dispatch(FunctionUnion, Intersection) # type: ignore # noqa:F811 def _set_function(f, x): # noqa:F811 from sympy.sets.sets import is_function_invertible_in_set # If the function is invertible, intersect the maps of the sets. if is_function_invertible_in_set(f, x): return Intersection(*(imageset(f, arg) for arg in x.args)) else: return ImageSet(Lambda(_x, f(_x)), x) @dispatch(FunctionUnion, EmptySet) # type: ignore # noqa:F811 def _set_function(f, x): # noqa:F811 return x @dispatch(FunctionUnion, Set) # type: ignore # noqa:F811 def _set_function(f, x): # noqa:F811 return ImageSet(Lambda(_x, f(_x)), x) @dispatch(FunctionUnion, Range) # type: ignore # noqa:F811 def _set_function(f, self): # noqa:F811 if not self: return S.EmptySet if not isinstance(f.expr, Expr): return if self.size == 1: return FiniteSet(f(self[0])) if f is S.IdentityFunction: return self x = f.variables[0] expr = f.expr # handle f that is linear in f's variable if x not in expr.free_symbols or x in expr.diff(x).free_symbols: return if self.start.is_finite: F = f(self.step*x + self.start) # for i in range(len(self)) else: F = f(-self.step*x + self[-1]) F = expand_mul(F) if F != expr: return imageset(x, F, Range(self.size)) @dispatch(FunctionUnion, Integers) # type: ignore # noqa:F811 def _set_function(f, self): # noqa:F811 expr = f.expr if not isinstance(expr, Expr): return n = f.variables[0] if expr == abs(n): return S.Naturals0 # f(x) + c and f(-x) + c cover the same integers # so choose the form that has the fewest negatives c = f(0) fx = f(n) - c f_x = f(-n) - c neg_count = lambda e: sum(_.could_extract_minus_sign() for _ in Add.make_args(e)) if neg_count(f_x) < neg_count(fx): expr = f_x + c a = Wild('a', exclude=[n]) b = Wild('b', exclude=[n]) match = expr.match(a*n + b) if match and match[a] and ( not match[a].atoms(Float) and not match[b].atoms(Float)): # canonical shift a, b = match[a], match[b] if a in [1, -1]: # drop integer addends in b nonint = [] for bi in Add.make_args(b): if not bi.is_integer: nonint.append(bi) b = Add(*nonint) if b.is_number and a.is_real: # avoid Mod for complex numbers, #11391 br, bi = match_real_imag(b) if br and br.is_comparable and a.is_comparable: br %= a b = br + S.ImaginaryUnit*bi elif b.is_number and a.is_imaginary: br, bi = match_real_imag(b) ai = a/S.ImaginaryUnit if bi and bi.is_comparable and ai.is_comparable: bi %= ai b = br + S.ImaginaryUnit*bi expr = a*n + b if expr != f.expr: return ImageSet(Lambda(n, expr), S.Integers) @dispatch(FunctionUnion, Naturals) # type: ignore # noqa:F811 def _set_function(f, self): # noqa:F811 expr = f.expr if not isinstance(expr, Expr): return x = f.variables[0] if not expr.free_symbols - {x}: if expr == abs(x): if self is S.Naturals: return self return S.Naturals0 step = expr.coeff(x) c = expr.subs(x, 0) if c.is_Integer and step.is_Integer and expr == step*x + c: if self is S.Naturals: c += step if step > 0: if step == 1: if c == 0: return S.Naturals0 elif c == 1: return S.Naturals return Range(c, oo, step) return Range(c, -oo, step) @dispatch(FunctionUnion, Reals) # type: ignore # noqa:F811 def _set_function(f, self): # noqa:F811 expr = f.expr if not isinstance(expr, Expr): return return _set_function(f, Interval(-oo, oo))
40947ad68c0194122edbc3db9bb1fe1342c832080318d00219f2978258e6b64b
from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.core.logic import fuzzy_and, fuzzy_bool, fuzzy_not, fuzzy_or from sympy.core.relational import Eq from sympy.sets.sets import FiniteSet, Interval, Set, Union, ProductSet from sympy.sets.fancysets import Complexes, Reals, Range, Rationals from sympy.multipledispatch import dispatch _inf_sets = [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals, S.Complexes] @dispatch(Set, Set) # type: ignore # noqa:F811 def is_subset_sets(a, b): # noqa:F811 return None @dispatch(Interval, Interval) # type: ignore # noqa:F811 def is_subset_sets(a, b): # noqa:F811 # This is correct but can be made more comprehensive... if fuzzy_bool(a.start < b.start): return False if fuzzy_bool(a.end > b.end): return False if (b.left_open and not a.left_open and fuzzy_bool(Eq(a.start, b.start))): return False if (b.right_open and not a.right_open and fuzzy_bool(Eq(a.end, b.end))): return False @dispatch(Interval, FiniteSet) # type: ignore # noqa:F811 def is_subset_sets(a_interval, b_fs): # noqa:F811 # An Interval can only be a subset of a finite set if it is finite # which can only happen if it has zero measure. if fuzzy_not(a_interval.measure.is_zero): return False @dispatch(Interval, Union) # type: ignore # noqa:F811 def is_subset_sets(a_interval, b_u): # noqa:F811 if all(isinstance(s, (Interval, FiniteSet)) for s in b_u.args): intervals = [s for s in b_u.args if isinstance(s, Interval)] if all(fuzzy_bool(a_interval.start < s.start) for s in intervals): return False if all(fuzzy_bool(a_interval.end > s.end) for s in intervals): return False if a_interval.measure.is_nonzero: no_overlap = lambda s1, s2: fuzzy_or([ fuzzy_bool(s1.end <= s2.start), fuzzy_bool(s1.start >= s2.end), ]) if all(no_overlap(s, a_interval) for s in intervals): return False @dispatch(Range, Range) # type: ignore # noqa:F811 def is_subset_sets(a, b): # noqa:F811 if a.step == b.step == 1: return fuzzy_and([fuzzy_bool(a.start >= b.start), fuzzy_bool(a.stop <= b.stop)]) @dispatch(Range, Interval) # type: ignore # noqa:F811 def is_subset_sets(a_range, b_interval): # noqa:F811 if a_range.step.is_positive: if b_interval.left_open and a_range.inf.is_finite: cond_left = a_range.inf > b_interval.left else: cond_left = a_range.inf >= b_interval.left if b_interval.right_open and a_range.sup.is_finite: cond_right = a_range.sup < b_interval.right else: cond_right = a_range.sup <= b_interval.right return fuzzy_and([cond_left, cond_right]) @dispatch(Range, FiniteSet) # type: ignore # noqa:F811 def is_subset_sets(a_range, b_finiteset): # noqa:F811 try: a_size = a_range.size except ValueError: # symbolic Range of unknown size return None if a_size > len(b_finiteset): return False elif any(arg.has(Symbol) for arg in a_range.args): return fuzzy_and(b_finiteset.contains(x) for x in a_range) else: # Checking A \ B == EmptySet is more efficient than repeated naive # membership checks on an arbitrary FiniteSet. a_set = set(a_range) b_remaining = len(b_finiteset) # Symbolic expressions and numbers of unknown type (integer or not) are # all counted as "candidates", i.e. *potentially* matching some a in # a_range. cnt_candidate = 0 for b in b_finiteset: if b.is_Integer: a_set.discard(b) elif fuzzy_not(b.is_integer): pass else: cnt_candidate += 1 b_remaining -= 1 if len(a_set) > b_remaining + cnt_candidate: return False if len(a_set) == 0: return True return None @dispatch(Interval, Range) # type: ignore # noqa:F811 def is_subset_sets(a_interval, b_range): # noqa:F811 if a_interval.measure.is_extended_nonzero: return False @dispatch(Interval, Rationals) # type: ignore # noqa:F811 def is_subset_sets(a_interval, b_rationals): # noqa:F811 if a_interval.measure.is_extended_nonzero: return False @dispatch(Range, Complexes) # type: ignore # noqa:F811 def is_subset_sets(a, b): # noqa:F811 return True @dispatch(Complexes, Interval) # type: ignore # noqa:F811 def is_subset_sets(a, b): # noqa:F811 return False @dispatch(Complexes, Range) # type: ignore # noqa:F811 def is_subset_sets(a, b): # noqa:F811 return False @dispatch(Complexes, Rationals) # type: ignore # noqa:F811 def is_subset_sets(a, b): # noqa:F811 return False @dispatch(Rationals, Reals) # type: ignore # noqa:F811 def is_subset_sets(a, b): # noqa:F811 return True @dispatch(Rationals, Range) # type: ignore # noqa:F811 def is_subset_sets(a, b): # noqa:F811 return False @dispatch(ProductSet, FiniteSet) # type: ignore # noqa:F811 def is_subset_sets(a_ps, b_fs): # noqa:F811 return fuzzy_and(b_fs.contains(x) for x in a_ps)
b48be4eff23c2c63de310bc12ca6525ce9d6cbadafeaf6cdd21d44aff432403f
from sympy.core import Basic, Expr from sympy.core.numbers import oo from sympy.core.symbol import symbols from sympy.multipledispatch import dispatch from sympy.sets.sets import Interval, Set _x, _y = symbols("x y") @dispatch(Basic, Basic) # type: ignore # noqa:F811 def _set_mul(x, y): # noqa:F811 return None @dispatch(Set, Set) # type: ignore # noqa:F811 def _set_mul(x, y): # noqa:F811 return None @dispatch(Expr, Expr) # type: ignore # noqa:F811 def _set_mul(x, y): # noqa:F811 return x*y @dispatch(Interval, Interval) # type: ignore # noqa:F811 def _set_mul(x, y): # noqa:F811 """ Multiplications in interval arithmetic https://en.wikipedia.org/wiki/Interval_arithmetic """ # TODO: some intervals containing 0 and oo will fail as 0*oo returns nan. comvals = ( (x.start * y.start, bool(x.left_open or y.left_open)), (x.start * y.end, bool(x.left_open or y.right_open)), (x.end * y.start, bool(x.right_open or y.left_open)), (x.end * y.end, bool(x.right_open or y.right_open)), ) # TODO: handle symbolic intervals minval, minopen = min(comvals) maxval, maxopen = max(comvals) return Interval( minval, maxval, minopen, maxopen ) @dispatch(Basic, Basic) # type: ignore # noqa:F811 def _set_div(x, y): # noqa:F811 return None @dispatch(Expr, Expr) # type: ignore # noqa:F811 def _set_div(x, y): # noqa:F811 return x/y @dispatch(Set, Set) # type: ignore # noqa:F811 # noqa:F811 def _set_div(x, y): # noqa:F811 return None @dispatch(Interval, Interval) # type: ignore # noqa:F811 def _set_div(x, y): # noqa:F811 """ Divisions in interval arithmetic https://en.wikipedia.org/wiki/Interval_arithmetic """ from sympy.sets.setexpr import set_mul if (y.start*y.end).is_negative: return Interval(-oo, oo) if y.start == 0: s2 = oo else: s2 = 1/y.start if y.end == 0: s1 = -oo else: s1 = 1/y.end return set_mul(x, Interval(s1, s2, y.right_open, y.left_open))
8531cce7f2e309de37026ea6f874d054ca525e4bdc13d894429297e1de288196
from sympy.core.expr import unchanged from sympy.sets import (ConditionSet, Intersection, FiniteSet, EmptySet, Union, Contains, ImageSet) from sympy.core.function import (Function, Lambda) from sympy.core.mod import Mod from sympy.core.numbers import (oo, pi) from sympy.core.relational import (Eq, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.trigonometric import (asin, sin) from sympy.logic.boolalg import And from sympy.matrices.dense import Matrix from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.sets.sets import Interval from sympy.testing.pytest import raises, warns_deprecated_sympy w = Symbol('w') x = Symbol('x') y = Symbol('y') z = Symbol('z') f = Function('f') def test_CondSet(): sin_sols_principal = ConditionSet(x, Eq(sin(x), 0), Interval(0, 2*pi, False, True)) assert pi in sin_sols_principal assert pi/2 not in sin_sols_principal assert 3*pi not in sin_sols_principal assert oo not in sin_sols_principal assert 5 in ConditionSet(x, x**2 > 4, S.Reals) assert 1 not in ConditionSet(x, x**2 > 4, S.Reals) # in this case, 0 is not part of the base set so # it can't be in any subset selected by the condition assert 0 not in ConditionSet(x, y > 5, Interval(1, 7)) # since 'in' requires a true/false, the following raises # an error because the given value provides no information # for the condition to evaluate (since the condition does # not depend on the dummy symbol): the result is `y > 5`. # In this case, ConditionSet is just acting like # Piecewise((Interval(1, 7), y > 5), (S.EmptySet, True)). raises(TypeError, lambda: 6 in ConditionSet(x, y > 5, Interval(1, 7))) X = MatrixSymbol('X', 2, 2) matrix_set = ConditionSet(X, Eq(X*Matrix([[1, 1], [1, 1]]), X)) Y = Matrix([[0, 0], [0, 0]]) assert matrix_set.contains(Y).doit() is S.true Z = Matrix([[1, 2], [3, 4]]) assert matrix_set.contains(Z).doit() is S.false assert isinstance(ConditionSet(x, x < 1, {x, y}).base_set, FiniteSet) raises(TypeError, lambda: ConditionSet(x, x + 1, {x, y})) raises(TypeError, lambda: ConditionSet(x, x, 1)) I = S.Integers U = S.UniversalSet C = ConditionSet assert C(x, False, I) is S.EmptySet assert C(x, True, I) is I assert C(x, x < 1, C(x, x < 2, I) ) == C(x, (x < 1) & (x < 2), I) assert C(y, y < 1, C(x, y < 2, I) ) == C(x, (x < 1) & (y < 2), I), C(y, y < 1, C(x, y < 2, I)) assert C(y, y < 1, C(x, x < 2, I) ) == C(y, (y < 1) & (y < 2), I) assert C(y, y < 1, C(x, y < x, I) ) == C(x, (x < 1) & (y < x), I) assert unchanged(C, y, x < 1, C(x, y < x, I)) assert ConditionSet(x, x < 1).base_set is U # arg checking is not done at instantiation but this # will raise an error when containment is tested assert ConditionSet((x,), x < 1).base_set is U c = ConditionSet((x, y), x < y, I**2) assert (1, 2) in c assert (1, pi) not in c raises(TypeError, lambda: C(x, x > 1, C((x, y), x > 1, I**2))) # signature mismatch since only 3 args are accepted raises(TypeError, lambda: C((x, y), x + y < 2, U, U)) def test_CondSet_intersect(): input_conditionset = ConditionSet(x, x**2 > 4, Interval(1, 4, False, False)) other_domain = Interval(0, 3, False, False) output_conditionset = ConditionSet(x, x**2 > 4, Interval( 1, 3, False, False)) assert Intersection(input_conditionset, other_domain ) == output_conditionset def test_issue_9849(): assert ConditionSet(x, Eq(x, x), S.Naturals ) is S.Naturals assert ConditionSet(x, Eq(Abs(sin(x)), -1), S.Naturals ) == S.EmptySet def test_simplified_FiniteSet_in_CondSet(): assert ConditionSet(x, And(x < 1, x > -3), FiniteSet(0, 1, 2) ) == FiniteSet(0) assert ConditionSet(x, x < 0, FiniteSet(0, 1, 2)) == EmptySet assert ConditionSet(x, And(x < -3), EmptySet) == EmptySet y = Symbol('y') assert (ConditionSet(x, And(x > 0), FiniteSet(-1, 0, 1, y)) == Union(FiniteSet(1), ConditionSet(x, And(x > 0), FiniteSet(y)))) assert (ConditionSet(x, Eq(Mod(x, 3), 1), FiniteSet(1, 4, 2, y)) == Union(FiniteSet(1, 4), ConditionSet(x, Eq(Mod(x, 3), 1), FiniteSet(y)))) def test_free_symbols(): assert ConditionSet(x, Eq(y, 0), FiniteSet(z) ).free_symbols == {y, z} assert ConditionSet(x, Eq(x, 0), FiniteSet(z) ).free_symbols == {z} assert ConditionSet(x, Eq(x, 0), FiniteSet(x, z) ).free_symbols == {x, z} assert ConditionSet(x, Eq(x, 0), ImageSet(Lambda(y, y**2), S.Integers)).free_symbols == set() def test_bound_symbols(): assert ConditionSet(x, Eq(y, 0), FiniteSet(z) ).bound_symbols == [x] assert ConditionSet(x, Eq(x, 0), FiniteSet(x, y) ).bound_symbols == [x] assert ConditionSet(x, x < 10, ImageSet(Lambda(y, y**2), S.Integers) ).bound_symbols == [x] assert ConditionSet(x, x < 10, ConditionSet(y, y > 1, S.Integers) ).bound_symbols == [x] def test_as_dummy(): _0, _1 = symbols('_0 _1') assert ConditionSet(x, x < 1, Interval(y, oo) ).as_dummy() == ConditionSet(_0, _0 < 1, Interval(y, oo)) assert ConditionSet(x, x < 1, Interval(x, oo) ).as_dummy() == ConditionSet(_0, _0 < 1, Interval(x, oo)) assert ConditionSet(x, x < 1, ImageSet(Lambda(y, y**2), S.Integers) ).as_dummy() == ConditionSet( _0, _0 < 1, ImageSet(Lambda(_0, _0**2), S.Integers)) e = ConditionSet((x, y), x <= y, S.Reals**2) assert e.bound_symbols == [x, y] assert e.as_dummy() == ConditionSet((_0, _1), _0 <= _1, S.Reals**2) assert e.as_dummy() == ConditionSet((y, x), y <= x, S.Reals**2 ).as_dummy() def test_subs_CondSet(): s = FiniteSet(z, y) c = ConditionSet(x, x < 2, s) assert c.subs(x, y) == c assert c.subs(z, y) == ConditionSet(x, x < 2, FiniteSet(y)) assert c.xreplace({x: y}) == ConditionSet(y, y < 2, s) assert ConditionSet(x, x < y, s ).subs(y, w) == ConditionSet(x, x < w, s.subs(y, w)) # if the user uses assumptions that cause the condition # to evaluate, that can't be helped from SymPy's end n = Symbol('n', negative=True) assert ConditionSet(n, 0 < n, S.Integers) is S.EmptySet p = Symbol('p', positive=True) assert ConditionSet(n, n < y, S.Integers ).subs(n, x) == ConditionSet(n, n < y, S.Integers) raises(ValueError, lambda: ConditionSet( x + 1, x < 1, S.Integers)) assert ConditionSet( p, n < x, Interval(-5, 5)).subs(x, p) == Interval(-5, 5), ConditionSet( p, n < x, Interval(-5, 5)).subs(x, p) assert ConditionSet( n, n < x, Interval(-oo, 0)).subs(x, p ) == Interval(-oo, 0) assert ConditionSet(f(x), f(x) < 1, {w, z} ).subs(f(x), y) == ConditionSet(f(x), f(x) < 1, {w, z}) # issue 17341 k = Symbol('k') img1 = ImageSet(Lambda(k, 2*k*pi + asin(y)), S.Integers) img2 = ImageSet(Lambda(k, 2*k*pi + asin(S.One/3)), S.Integers) assert ConditionSet(x, Contains( y, Interval(-1,1)), img1).subs(y, S.One/3).dummy_eq(img2) assert (0, 1) in ConditionSet((x, y), x + y < 3, S.Integers**2) raises(TypeError, lambda: ConditionSet(n, n < -10, Interval(0, 10))) def test_subs_CondSet_tebr(): with warns_deprecated_sympy(): assert ConditionSet((x, y), {x + 1, x + y}, S.Reals**2) == \ ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals**2) def test_dummy_eq(): C = ConditionSet I = S.Integers c = C(x, x < 1, I) assert c.dummy_eq(C(y, y < 1, I)) assert c.dummy_eq(1) == False assert c.dummy_eq(C(x, x < 1, S.Reals)) == False c1 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals**2) c2 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals**2) c3 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Complexes**2) assert c1.dummy_eq(c2) assert c1.dummy_eq(c3) is False assert c.dummy_eq(c1) is False assert c1.dummy_eq(c) is False # issue 19496 m = Symbol('m') n = Symbol('n') a = Symbol('a') d1 = ImageSet(Lambda(m, m*pi), S.Integers) d2 = ImageSet(Lambda(n, n*pi), S.Integers) c1 = ConditionSet(x, Ne(a, 0), d1) c2 = ConditionSet(x, Ne(a, 0), d2) assert c1.dummy_eq(c2) def test_contains(): assert 6 in ConditionSet(x, x > 5, Interval(1, 7)) assert (8 in ConditionSet(x, y > 5, Interval(1, 7))) is False # `in` should give True or False; in this case there is not # enough information for that result raises(TypeError, lambda: 6 in ConditionSet(x, y > 5, Interval(1, 7))) # here, there is enough information but the comparison is # not defined raises(TypeError, lambda: 0 in ConditionSet(x, 1/x >= 0, S.Reals)) assert ConditionSet(x, y > 5, Interval(1, 7) ).contains(6) == (y > 5) assert ConditionSet(x, y > 5, Interval(1, 7) ).contains(8) is S.false assert ConditionSet(x, y > 5, Interval(1, 7) ).contains(w) == And(Contains(w, Interval(1, 7)), y > 5) # This returns an unevaluated Contains object # because 1/0 should not be defined for 1 and 0 in the context of # reals. assert ConditionSet(x, 1/x >= 0, S.Reals).contains(0) == \ Contains(0, ConditionSet(x, 1/x >= 0, S.Reals), evaluate=False) c = ConditionSet((x, y), x + y > 1, S.Integers**2) assert not c.contains(1) assert c.contains((2, 1)) assert not c.contains((0, 1)) c = ConditionSet((w, (x, y)), w + x + y > 1, S.Integers*S.Integers**2) assert not c.contains(1) assert not c.contains((1, 2)) assert not c.contains(((1, 2), 3)) assert not c.contains(((1, 2), (3, 4))) assert c.contains((1, (3, 4))) def test_as_relational(): assert ConditionSet((x, y), x > 1, S.Integers**2).as_relational((x, y) ) == (x > 1) & Contains((x, y), S.Integers**2) assert ConditionSet(x, x > 1, S.Integers).as_relational(x ) == Contains(x, S.Integers) & (x > 1) def test_flatten(): """Tests whether there is basic denesting functionality""" inner = ConditionSet(x, sin(x) + x > 0) outer = ConditionSet(x, Contains(x, inner), S.Reals) assert outer == ConditionSet(x, sin(x) + x > 0, S.Reals) inner = ConditionSet(y, sin(y) + y > 0) outer = ConditionSet(x, Contains(y, inner), S.Reals) assert outer != ConditionSet(x, sin(x) + x > 0, S.Reals) inner = ConditionSet(x, sin(x) + x > 0).intersect(Interval(-1, 1)) outer = ConditionSet(x, Contains(x, inner), S.Reals) assert outer == ConditionSet(x, sin(x) + x > 0, Interval(-1, 1)) def test_duplicate(): from sympy.core.function import BadSignatureError # test coverage for line 95 in conditionset.py, check for duplicates in symbols dup = symbols('a,a') raises(BadSignatureError, lambda: ConditionSet(dup, x < 0))
5be252d9f591cf1848240879d078b99672669dd9327fefebb6bed4982f66124f
from sympy.sets.setexpr import SetExpr from sympy.sets import Interval, FiniteSet, Intersection, ImageSet, Union from sympy.core.expr import Expr from sympy.core.function import Lambda from sympy.core.numbers import (I, Rational, oo) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt) from sympy.functions.elementary.trigonometric import cos from sympy.sets.sets import Set a, x = symbols("a, x") _d = Dummy("d") def test_setexpr(): se = SetExpr(Interval(0, 1)) assert isinstance(se.set, Set) assert isinstance(se, Expr) def test_scalar_funcs(): assert SetExpr(Interval(0, 1)).set == Interval(0, 1) a, b = Symbol('a', real=True), Symbol('b', real=True) a, b = 1, 2 # TODO: add support for more functions in the future: for f in [exp, log]: input_se = f(SetExpr(Interval(a, b))) output = input_se.set expected = Interval(Min(f(a), f(b)), Max(f(a), f(b))) assert output == expected def test_Add_Mul(): assert (SetExpr(Interval(0, 1)) + 1).set == Interval(1, 2) assert (SetExpr(Interval(0, 1))*2).set == Interval(0, 2) def test_Pow(): assert (SetExpr(Interval(0, 2))**2).set == Interval(0, 4) def test_compound(): assert (exp(SetExpr(Interval(0, 1))*2 + 1)).set == \ Interval(exp(1), exp(3)) def test_Interval_Interval(): assert (SetExpr(Interval(1, 2)) + SetExpr(Interval(10, 20))).set == \ Interval(11, 22) assert (SetExpr(Interval(1, 2))*SetExpr(Interval(10, 20))).set == \ Interval(10, 40) def test_FiniteSet_FiniteSet(): assert (SetExpr(FiniteSet(1, 2, 3)) + SetExpr(FiniteSet(1, 2))).set == \ FiniteSet(2, 3, 4, 5) assert (SetExpr(FiniteSet(1, 2, 3))*SetExpr(FiniteSet(1, 2))).set == \ FiniteSet(1, 2, 3, 4, 6) def test_Interval_FiniteSet(): assert (SetExpr(FiniteSet(1, 2)) + SetExpr(Interval(0, 10))).set == \ Interval(1, 12) def test_Many_Sets(): assert (SetExpr(Interval(0, 1)) + SetExpr(Interval(2, 3)) + SetExpr(FiniteSet(10, 11, 12))).set == Interval(12, 16) def test_same_setexprs_are_not_identical(): a = SetExpr(FiniteSet(0, 1)) b = SetExpr(FiniteSet(0, 1)) assert (a + b).set == FiniteSet(0, 1, 2) # Cannont detect the set being the same: # assert (a + a).set == FiniteSet(0, 2) def test_Interval_arithmetic(): i12cc = SetExpr(Interval(1, 2)) i12lo = SetExpr(Interval.Lopen(1, 2)) i12ro = SetExpr(Interval.Ropen(1, 2)) i12o = SetExpr(Interval.open(1, 2)) n23cc = SetExpr(Interval(-2, 3)) n23lo = SetExpr(Interval.Lopen(-2, 3)) n23ro = SetExpr(Interval.Ropen(-2, 3)) n23o = SetExpr(Interval.open(-2, 3)) n3n2cc = SetExpr(Interval(-3, -2)) assert i12cc + i12cc == SetExpr(Interval(2, 4)) assert i12cc - i12cc == SetExpr(Interval(-1, 1)) assert i12cc*i12cc == SetExpr(Interval(1, 4)) assert i12cc/i12cc == SetExpr(Interval(S.Half, 2)) assert i12cc**2 == SetExpr(Interval(1, 4)) assert i12cc**3 == SetExpr(Interval(1, 8)) assert i12lo + i12ro == SetExpr(Interval.open(2, 4)) assert i12lo - i12ro == SetExpr(Interval.Lopen(-1, 1)) assert i12lo*i12ro == SetExpr(Interval.open(1, 4)) assert i12lo/i12ro == SetExpr(Interval.Lopen(S.Half, 2)) assert i12lo + i12lo == SetExpr(Interval.Lopen(2, 4)) assert i12lo - i12lo == SetExpr(Interval.open(-1, 1)) assert i12lo*i12lo == SetExpr(Interval.Lopen(1, 4)) assert i12lo/i12lo == SetExpr(Interval.open(S.Half, 2)) assert i12lo + i12cc == SetExpr(Interval.Lopen(2, 4)) assert i12lo - i12cc == SetExpr(Interval.Lopen(-1, 1)) assert i12lo*i12cc == SetExpr(Interval.Lopen(1, 4)) assert i12lo/i12cc == SetExpr(Interval.Lopen(S.Half, 2)) assert i12lo + i12o == SetExpr(Interval.open(2, 4)) assert i12lo - i12o == SetExpr(Interval.open(-1, 1)) assert i12lo*i12o == SetExpr(Interval.open(1, 4)) assert i12lo/i12o == SetExpr(Interval.open(S.Half, 2)) assert i12lo**2 == SetExpr(Interval.Lopen(1, 4)) assert i12lo**3 == SetExpr(Interval.Lopen(1, 8)) assert i12ro + i12ro == SetExpr(Interval.Ropen(2, 4)) assert i12ro - i12ro == SetExpr(Interval.open(-1, 1)) assert i12ro*i12ro == SetExpr(Interval.Ropen(1, 4)) assert i12ro/i12ro == SetExpr(Interval.open(S.Half, 2)) assert i12ro + i12cc == SetExpr(Interval.Ropen(2, 4)) assert i12ro - i12cc == SetExpr(Interval.Ropen(-1, 1)) assert i12ro*i12cc == SetExpr(Interval.Ropen(1, 4)) assert i12ro/i12cc == SetExpr(Interval.Ropen(S.Half, 2)) assert i12ro + i12o == SetExpr(Interval.open(2, 4)) assert i12ro - i12o == SetExpr(Interval.open(-1, 1)) assert i12ro*i12o == SetExpr(Interval.open(1, 4)) assert i12ro/i12o == SetExpr(Interval.open(S.Half, 2)) assert i12ro**2 == SetExpr(Interval.Ropen(1, 4)) assert i12ro**3 == SetExpr(Interval.Ropen(1, 8)) assert i12o + i12lo == SetExpr(Interval.open(2, 4)) assert i12o - i12lo == SetExpr(Interval.open(-1, 1)) assert i12o*i12lo == SetExpr(Interval.open(1, 4)) assert i12o/i12lo == SetExpr(Interval.open(S.Half, 2)) assert i12o + i12ro == SetExpr(Interval.open(2, 4)) assert i12o - i12ro == SetExpr(Interval.open(-1, 1)) assert i12o*i12ro == SetExpr(Interval.open(1, 4)) assert i12o/i12ro == SetExpr(Interval.open(S.Half, 2)) assert i12o + i12cc == SetExpr(Interval.open(2, 4)) assert i12o - i12cc == SetExpr(Interval.open(-1, 1)) assert i12o*i12cc == SetExpr(Interval.open(1, 4)) assert i12o/i12cc == SetExpr(Interval.open(S.Half, 2)) assert i12o**2 == SetExpr(Interval.open(1, 4)) assert i12o**3 == SetExpr(Interval.open(1, 8)) assert n23cc + n23cc == SetExpr(Interval(-4, 6)) assert n23cc - n23cc == SetExpr(Interval(-5, 5)) assert n23cc*n23cc == SetExpr(Interval(-6, 9)) assert n23cc/n23cc == SetExpr(Interval.open(-oo, oo)) assert n23cc + n23ro == SetExpr(Interval.Ropen(-4, 6)) assert n23cc - n23ro == SetExpr(Interval.Lopen(-5, 5)) assert n23cc*n23ro == SetExpr(Interval.Ropen(-6, 9)) assert n23cc/n23ro == SetExpr(Interval.Lopen(-oo, oo)) assert n23cc + n23lo == SetExpr(Interval.Lopen(-4, 6)) assert n23cc - n23lo == SetExpr(Interval.Ropen(-5, 5)) assert n23cc*n23lo == SetExpr(Interval(-6, 9)) assert n23cc/n23lo == SetExpr(Interval.open(-oo, oo)) assert n23cc + n23o == SetExpr(Interval.open(-4, 6)) assert n23cc - n23o == SetExpr(Interval.open(-5, 5)) assert n23cc*n23o == SetExpr(Interval.open(-6, 9)) assert n23cc/n23o == SetExpr(Interval.open(-oo, oo)) assert n23cc**2 == SetExpr(Interval(0, 9)) assert n23cc**3 == SetExpr(Interval(-8, 27)) n32cc = SetExpr(Interval(-3, 2)) n32lo = SetExpr(Interval.Lopen(-3, 2)) n32ro = SetExpr(Interval.Ropen(-3, 2)) assert n32cc*n32lo == SetExpr(Interval.Ropen(-6, 9)) assert n32cc*n32cc == SetExpr(Interval(-6, 9)) assert n32lo*n32cc == SetExpr(Interval.Ropen(-6, 9)) assert n32cc*n32ro == SetExpr(Interval(-6, 9)) assert n32lo*n32ro == SetExpr(Interval.Ropen(-6, 9)) assert n32cc/n32lo == SetExpr(Interval.Ropen(-oo, oo)) assert i12cc/n32lo == SetExpr(Interval.Ropen(-oo, oo)) assert n3n2cc**2 == SetExpr(Interval(4, 9)) assert n3n2cc**3 == SetExpr(Interval(-27, -8)) assert n23cc + i12cc == SetExpr(Interval(-1, 5)) assert n23cc - i12cc == SetExpr(Interval(-4, 2)) assert n23cc*i12cc == SetExpr(Interval(-4, 6)) assert n23cc/i12cc == SetExpr(Interval(-2, 3)) def test_SetExpr_Intersection(): x, y, z, w = symbols("x y z w") set1 = Interval(x, y) set2 = Interval(w, z) inter = Intersection(set1, set2) se = SetExpr(inter) assert exp(se).set == Intersection( ImageSet(Lambda(x, exp(x)), set1), ImageSet(Lambda(x, exp(x)), set2)) assert cos(se).set == ImageSet(Lambda(x, cos(x)), inter) def test_SetExpr_Interval_div(): # TODO: some expressions cannot be calculated due to bugs (currently # commented): assert SetExpr(Interval(-3, -2))/SetExpr(Interval(-2, 1)) == SetExpr(Interval(-oo, oo)) assert SetExpr(Interval(2, 3))/SetExpr(Interval(-2, 2)) == SetExpr(Interval(-oo, oo)) assert SetExpr(Interval(-3, -2))/SetExpr(Interval(0, 4)) == SetExpr(Interval(-oo, Rational(-1, 2))) assert SetExpr(Interval(2, 4))/SetExpr(Interval(-3, 0)) == SetExpr(Interval(-oo, Rational(-2, 3))) assert SetExpr(Interval(2, 4))/SetExpr(Interval(0, 3)) == SetExpr(Interval(Rational(2, 3), oo)) # assert SetExpr(Interval(0, 1))/SetExpr(Interval(0, 1)) == SetExpr(Interval(0, oo)) # assert SetExpr(Interval(-1, 0))/SetExpr(Interval(0, 1)) == SetExpr(Interval(-oo, 0)) assert SetExpr(Interval(-1, 2))/SetExpr(Interval(-2, 2)) == SetExpr(Interval(-oo, oo)) assert 1/SetExpr(Interval(-1, 2)) == SetExpr(Union(Interval(-oo, -1), Interval(S.Half, oo))) assert 1/SetExpr(Interval(0, 2)) == SetExpr(Interval(S.Half, oo)) assert (-1)/SetExpr(Interval(0, 2)) == SetExpr(Interval(-oo, Rational(-1, 2))) assert 1/SetExpr(Interval(-oo, 0)) == SetExpr(Interval.open(-oo, 0)) assert 1/SetExpr(Interval(-1, 0)) == SetExpr(Interval(-oo, -1)) # assert (-2)/SetExpr(Interval(-oo, 0)) == SetExpr(Interval(0, oo)) # assert 1/SetExpr(Interval(-oo, -1)) == SetExpr(Interval(-1, 0)) # assert SetExpr(Interval(1, 2))/a == Mul(SetExpr(Interval(1, 2)), 1/a, evaluate=False) # assert SetExpr(Interval(1, 2))/0 == SetExpr(Interval(1, 2))*zoo # assert SetExpr(Interval(1, oo))/oo == SetExpr(Interval(0, oo)) # assert SetExpr(Interval(1, oo))/(-oo) == SetExpr(Interval(-oo, 0)) # assert SetExpr(Interval(-oo, -1))/oo == SetExpr(Interval(-oo, 0)) # assert SetExpr(Interval(-oo, -1))/(-oo) == SetExpr(Interval(0, oo)) # assert SetExpr(Interval(-oo, oo))/oo == SetExpr(Interval(-oo, oo)) # assert SetExpr(Interval(-oo, oo))/(-oo) == SetExpr(Interval(-oo, oo)) # assert SetExpr(Interval(-1, oo))/oo == SetExpr(Interval(0, oo)) # assert SetExpr(Interval(-1, oo))/(-oo) == SetExpr(Interval(-oo, 0)) # assert SetExpr(Interval(-oo, 1))/oo == SetExpr(Interval(-oo, 0)) # assert SetExpr(Interval(-oo, 1))/(-oo) == SetExpr(Interval(0, oo)) def test_SetExpr_Interval_pow(): assert SetExpr(Interval(0, 2))**2 == SetExpr(Interval(0, 4)) assert SetExpr(Interval(-1, 1))**2 == SetExpr(Interval(0, 1)) assert SetExpr(Interval(1, 2))**2 == SetExpr(Interval(1, 4)) assert SetExpr(Interval(-1, 2))**3 == SetExpr(Interval(-1, 8)) assert SetExpr(Interval(-1, 1))**0 == SetExpr(FiniteSet(1)) assert SetExpr(Interval(1, 2))**Rational(5, 2) == SetExpr(Interval(1, 4*sqrt(2))) #assert SetExpr(Interval(-1, 2))**Rational(1, 3) == SetExpr(Interval(-1, 2**Rational(1, 3))) #assert SetExpr(Interval(0, 2))**S.Half == SetExpr(Interval(0, sqrt(2))) #assert SetExpr(Interval(-4, 2))**Rational(2, 3) == SetExpr(Interval(0, 2*2**Rational(1, 3))) #assert SetExpr(Interval(-1, 5))**S.Half == SetExpr(Interval(0, sqrt(5))) #assert SetExpr(Interval(-oo, 2))**S.Half == SetExpr(Interval(0, sqrt(2))) #assert SetExpr(Interval(-2, 3))**(Rational(-1, 4)) == SetExpr(Interval(0, oo)) assert SetExpr(Interval(1, 5))**(-2) == SetExpr(Interval(Rational(1, 25), 1)) assert SetExpr(Interval(-1, 3))**(-2) == SetExpr(Interval(0, oo)) assert SetExpr(Interval(0, 2))**(-2) == SetExpr(Interval(Rational(1, 4), oo)) assert SetExpr(Interval(-1, 2))**(-3) == SetExpr(Union(Interval(-oo, -1), Interval(Rational(1, 8), oo))) assert SetExpr(Interval(-3, -2))**(-3) == SetExpr(Interval(Rational(-1, 8), Rational(-1, 27))) assert SetExpr(Interval(-3, -2))**(-2) == SetExpr(Interval(Rational(1, 9), Rational(1, 4))) #assert SetExpr(Interval(0, oo))**S.Half == SetExpr(Interval(0, oo)) #assert SetExpr(Interval(-oo, -1))**Rational(1, 3) == SetExpr(Interval(-oo, -1)) #assert SetExpr(Interval(-2, 3))**(Rational(-1, 3)) == SetExpr(Interval(-oo, oo)) assert SetExpr(Interval(-oo, 0))**(-2) == SetExpr(Interval.open(0, oo)) assert SetExpr(Interval(-2, 0))**(-2) == SetExpr(Interval(Rational(1, 4), oo)) assert SetExpr(Interval(Rational(1, 3), S.Half))**oo == SetExpr(FiniteSet(0)) assert SetExpr(Interval(0, S.Half))**oo == SetExpr(FiniteSet(0)) assert SetExpr(Interval(S.Half, 1))**oo == SetExpr(Interval(0, oo)) assert SetExpr(Interval(0, 1))**oo == SetExpr(Interval(0, oo)) assert SetExpr(Interval(2, 3))**oo == SetExpr(FiniteSet(oo)) assert SetExpr(Interval(1, 2))**oo == SetExpr(Interval(0, oo)) assert SetExpr(Interval(S.Half, 3))**oo == SetExpr(Interval(0, oo)) assert SetExpr(Interval(Rational(-1, 3), Rational(-1, 4)))**oo == SetExpr(FiniteSet(0)) assert SetExpr(Interval(-1, Rational(-1, 2)))**oo == SetExpr(Interval(-oo, oo)) assert SetExpr(Interval(-3, -2))**oo == SetExpr(FiniteSet(-oo, oo)) assert SetExpr(Interval(-2, -1))**oo == SetExpr(Interval(-oo, oo)) assert SetExpr(Interval(-2, Rational(-1, 2)))**oo == SetExpr(Interval(-oo, oo)) assert SetExpr(Interval(Rational(-1, 2), S.Half))**oo == SetExpr(FiniteSet(0)) assert SetExpr(Interval(Rational(-1, 2), 1))**oo == SetExpr(Interval(0, oo)) assert SetExpr(Interval(Rational(-2, 3), 2))**oo == SetExpr(Interval(0, oo)) assert SetExpr(Interval(-1, 1))**oo == SetExpr(Interval(-oo, oo)) assert SetExpr(Interval(-1, S.Half))**oo == SetExpr(Interval(-oo, oo)) assert SetExpr(Interval(-1, 2))**oo == SetExpr(Interval(-oo, oo)) assert SetExpr(Interval(-2, S.Half))**oo == SetExpr(Interval(-oo, oo)) assert (SetExpr(Interval(1, 2))**x).dummy_eq(SetExpr(ImageSet(Lambda(_d, _d**x), Interval(1, 2)))) assert SetExpr(Interval(2, 3))**(-oo) == SetExpr(FiniteSet(0)) assert SetExpr(Interval(0, 2))**(-oo) == SetExpr(Interval(0, oo)) assert (SetExpr(Interval(-1, 2))**(-oo)).dummy_eq(SetExpr(ImageSet(Lambda(_d, _d**(-oo)), Interval(-1, 2)))) def test_SetExpr_Integers(): assert SetExpr(S.Integers) + 1 == SetExpr(S.Integers) assert (SetExpr(S.Integers) + I).dummy_eq( SetExpr(ImageSet(Lambda(_d, _d + I), S.Integers))) assert SetExpr(S.Integers)*(-1) == SetExpr(S.Integers) assert (SetExpr(S.Integers)*2).dummy_eq( SetExpr(ImageSet(Lambda(_d, 2*_d), S.Integers))) assert (SetExpr(S.Integers)*I).dummy_eq( SetExpr(ImageSet(Lambda(_d, I*_d), S.Integers))) # issue #18050: assert SetExpr(S.Integers)._eval_func(Lambda(x, I*x + 1)).dummy_eq( SetExpr(ImageSet(Lambda(_d, I*_d + 1), S.Integers))) # needs improvement: assert (SetExpr(S.Integers)*I + 1).dummy_eq( SetExpr(ImageSet(Lambda(x, x + 1), ImageSet(Lambda(_d, _d*I), S.Integers))))
15baec27f8be779bfbbdc3c7a0601cf5361d8722d8286e14409324605c486048
from sympy.core.expr import unchanged from sympy.core.numbers import oo from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.sets.contains import Contains from sympy.sets.sets import (FiniteSet, Interval) from sympy.testing.pytest import raises def test_contains_basic(): raises(TypeError, lambda: Contains(S.Integers, 1)) assert Contains(2, S.Integers) is S.true assert Contains(-2, S.Naturals) is S.false i = Symbol('i', integer=True) assert Contains(i, S.Naturals) == Contains(i, S.Naturals, evaluate=False) def test_issue_6194(): x = Symbol('x') assert unchanged(Contains, x, Interval(0, 1)) assert Interval(0, 1).contains(x) == (S.Zero <= x) & (x <= 1) assert Contains(x, FiniteSet(0)) != S.false assert Contains(x, Interval(1, 1)) != S.false assert Contains(x, S.Integers) != S.false def test_issue_10326(): assert Contains(oo, Interval(-oo, oo)) == False assert Contains(-oo, Interval(-oo, oo)) == False def test_binary_symbols(): x = Symbol('x') y = Symbol('y') z = Symbol('z') assert Contains(x, FiniteSet(y, Eq(z, True)) ).binary_symbols == {y, z} def test_as_set(): x = Symbol('x') y = Symbol('y') # Contains is a BooleanFunction whose value depends on an arg's # containment in a Set -- rewriting as a Set is not yet implemented raises(NotImplementedError, lambda: Contains(x, FiniteSet(y)).as_set()) def test_type_error(): # Pass in a parameter not of type "set" raises(TypeError, lambda: Contains(2, None))
2f80d873a07240c0f0246173242dd885f4ab564e5ab96ee97f8418a49e7163bc
from sympy.sets.ordinals import Ordinal, OmegaPower, ord0, omega from sympy.testing.pytest import raises def test_string_ordinals(): assert str(omega) == 'w' assert str(Ordinal(OmegaPower(5, 3), OmegaPower(3, 2))) == 'w**5*3 + w**3*2' assert str(Ordinal(OmegaPower(5, 3), OmegaPower(0, 5))) == 'w**5*3 + 5' assert str(Ordinal(OmegaPower(1, 3), OmegaPower(0, 5))) == 'w*3 + 5' assert str(Ordinal(OmegaPower(omega + 1, 1), OmegaPower(3, 2))) == 'w**(w + 1) + w**3*2' def test_addition_with_integers(): assert 3 + Ordinal(OmegaPower(5, 3)) == Ordinal(OmegaPower(5, 3)) assert Ordinal(OmegaPower(5, 3))+3 == Ordinal(OmegaPower(5, 3), OmegaPower(0, 3)) assert Ordinal(OmegaPower(5, 3), OmegaPower(0, 2))+3 == \ Ordinal(OmegaPower(5, 3), OmegaPower(0, 5)) def test_addition_with_ordinals(): assert Ordinal(OmegaPower(5, 3), OmegaPower(3, 2)) + Ordinal(OmegaPower(3, 3)) == \ Ordinal(OmegaPower(5, 3), OmegaPower(3, 5)) assert Ordinal(OmegaPower(5, 3), OmegaPower(3, 2)) + Ordinal(OmegaPower(4, 2)) == \ Ordinal(OmegaPower(5, 3), OmegaPower(4, 2)) assert Ordinal(OmegaPower(omega, 2), OmegaPower(3, 2)) + Ordinal(OmegaPower(4, 2)) == \ Ordinal(OmegaPower(omega, 2), OmegaPower(4, 2)) def test_comparison(): assert Ordinal(OmegaPower(5, 3)) > Ordinal(OmegaPower(4, 3), OmegaPower(2, 1)) assert Ordinal(OmegaPower(5, 3), OmegaPower(3, 2)) < Ordinal(OmegaPower(5, 4)) assert Ordinal(OmegaPower(5, 4)) < Ordinal(OmegaPower(5, 5), OmegaPower(4, 1)) assert Ordinal(OmegaPower(5, 3), OmegaPower(3, 2)) == \ Ordinal(OmegaPower(5, 3), OmegaPower(3, 2)) assert not Ordinal(OmegaPower(5, 3), OmegaPower(3, 2)) == Ordinal(OmegaPower(5, 3)) assert Ordinal(OmegaPower(omega, 3)) > Ordinal(OmegaPower(5, 3)) def test_multiplication_with_integers(): w = omega assert 3*w == w assert w*9 == Ordinal(OmegaPower(1, 9)) def test_multiplication(): w = omega assert w*(w + 1) == w*w + w assert (w + 1)*(w + 1) == w*w + w + 1 assert w*1 == w assert 1*w == w assert w*ord0 == ord0 assert ord0*w == ord0 assert w**w == w * w**w assert (w**w)*w*w == w**(w + 2) def test_exponentiation(): w = omega assert w**2 == w*w assert w**3 == w*w*w assert w**(w + 1) == Ordinal(OmegaPower(omega + 1, 1)) assert (w**w)*(w**w) == w**(w*2) def test_comapre_not_instance(): w = OmegaPower(omega + 1, 1) assert(not (w == None)) assert(not (w < 5)) raises(TypeError, lambda: w < 6.66) def test_is_successort(): w = Ordinal(OmegaPower(5, 1)) assert not w.is_successor_ordinal
64e772e486ad3423f336bb3deb7a9cbba9f622a9c5501b019d13aba946b826b7
from sympy.core.expr import unchanged from sympy.sets.fancysets import (ImageSet, Range, normalize_theta_set, ComplexRegion) from sympy.sets.sets import (FiniteSet, Interval, Union, imageset, Intersection, ProductSet, Contains) from sympy.sets.conditionset import ConditionSet from sympy.simplify.simplify import simplify from sympy.core.basic import Basic from sympy.core.containers import Tuple from sympy.core.function import Lambda 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 (Dummy, Symbol, symbols) from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin, tan) from sympy.logic.boolalg import And from sympy.matrices.dense import eye from sympy.testing.pytest import XFAIL, raises from sympy.abc import x, y, t, z from sympy.core.mod import Mod import itertools def test_naturals(): N = S.Naturals assert 5 in N assert -5 not in N assert 5.5 not in N ni = iter(N) a, b, c, d = next(ni), next(ni), next(ni), next(ni) assert (a, b, c, d) == (1, 2, 3, 4) assert isinstance(a, Basic) assert N.intersect(Interval(-5, 5)) == Range(1, 6) assert N.intersect(Interval(-5, 5, True, True)) == Range(1, 5) assert N.boundary == N assert N.is_open == False assert N.is_closed == True assert N.inf == 1 assert N.sup is oo assert not N.contains(oo) for s in (S.Naturals0, S.Naturals): assert s.intersection(S.Reals) is s assert s.is_subset(S.Reals) assert N.as_relational(x) == And(Eq(floor(x), x), x >= 1, x < oo) def test_naturals0(): N = S.Naturals0 assert 0 in N assert -1 not in N assert next(iter(N)) == 0 assert not N.contains(oo) assert N.contains(sin(x)) == Contains(sin(x), N) def test_integers(): Z = S.Integers assert 5 in Z assert -5 in Z assert 5.5 not in Z assert not Z.contains(oo) assert not Z.contains(-oo) zi = iter(Z) a, b, c, d = next(zi), next(zi), next(zi), next(zi) assert (a, b, c, d) == (0, 1, -1, 2) assert isinstance(a, Basic) assert Z.intersect(Interval(-5, 5)) == Range(-5, 6) assert Z.intersect(Interval(-5, 5, True, True)) == Range(-4, 5) assert Z.intersect(Interval(5, S.Infinity)) == Range(5, S.Infinity) assert Z.intersect(Interval.Lopen(5, S.Infinity)) == Range(6, S.Infinity) assert Z.inf is -oo assert Z.sup is oo assert Z.boundary == Z assert Z.is_open == False assert Z.is_closed == True assert Z.as_relational(x) == And(Eq(floor(x), x), -oo < x, x < oo) def test_ImageSet(): raises(ValueError, lambda: ImageSet(x, S.Integers)) assert ImageSet(Lambda(x, 1), S.Integers) == FiniteSet(1) assert ImageSet(Lambda(x, y), S.Integers) == {y} assert ImageSet(Lambda(x, 1), S.EmptySet) == S.EmptySet empty = Intersection(FiniteSet(log(2)/pi), S.Integers) assert unchanged(ImageSet, Lambda(x, 1), empty) # issue #17471 squares = ImageSet(Lambda(x, x**2), S.Naturals) assert 4 in squares assert 5 not in squares assert FiniteSet(*range(10)).intersect(squares) == FiniteSet(1, 4, 9) assert 16 not in squares.intersect(Interval(0, 10)) si = iter(squares) a, b, c, d = next(si), next(si), next(si), next(si) assert (a, b, c, d) == (1, 4, 9, 16) harmonics = ImageSet(Lambda(x, 1/x), S.Naturals) assert Rational(1, 5) in harmonics assert Rational(.25) in harmonics assert 0.25 not in harmonics assert Rational(.3) not in harmonics assert (1, 2) not in harmonics assert harmonics.is_iterable assert imageset(x, -x, Interval(0, 1)) == Interval(-1, 0) assert ImageSet(Lambda(x, x**2), Interval(0, 2)).doit() == Interval(0, 4) assert ImageSet(Lambda((x, y), 2*x), {4}, {3}).doit() == FiniteSet(8) assert (ImageSet(Lambda((x, y), x+y), {1, 2, 3}, {10, 20, 30}).doit() == FiniteSet(11, 12, 13, 21, 22, 23, 31, 32, 33)) c = Interval(1, 3) * Interval(1, 3) assert Tuple(2, 6) in ImageSet(Lambda(((x, y),), (x, 2*y)), c) assert Tuple(2, S.Half) in ImageSet(Lambda(((x, y),), (x, 1/y)), c) assert Tuple(2, -2) not in ImageSet(Lambda(((x, y),), (x, y**2)), c) assert Tuple(2, -2) in ImageSet(Lambda(((x, y),), (x, -2)), c) c3 = ProductSet(Interval(3, 7), Interval(8, 11), Interval(5, 9)) assert Tuple(8, 3, 9) in ImageSet(Lambda(((t, y, x),), (y, t, x)), c3) assert Tuple(Rational(1, 8), 3, 9) in ImageSet(Lambda(((t, y, x),), (1/y, t, x)), c3) assert 2/pi not in ImageSet(Lambda(((x, y),), 2/x), c) assert 2/S(100) not in ImageSet(Lambda(((x, y),), 2/x), c) assert Rational(2, 3) in ImageSet(Lambda(((x, y),), 2/x), c) S1 = imageset(lambda x, y: x + y, S.Integers, S.Naturals) assert S1.base_pset == ProductSet(S.Integers, S.Naturals) assert S1.base_sets == (S.Integers, S.Naturals) # Passing a set instead of a FiniteSet shouldn't raise assert unchanged(ImageSet, Lambda(x, x**2), {1, 2, 3}) S2 = ImageSet(Lambda(((x, y),), x+y), {(1, 2), (3, 4)}) assert 3 in S2.doit() # FIXME: This doesn't yet work: #assert 3 in S2 assert S2._contains(3) is None raises(TypeError, lambda: ImageSet(Lambda(x, x**2), 1)) def test_image_is_ImageSet(): assert isinstance(imageset(x, sqrt(sin(x)), Range(5)), ImageSet) def test_halfcircle(): r, th = symbols('r, theta', real=True) L = Lambda(((r, th),), (r*cos(th), r*sin(th))) halfcircle = ImageSet(L, Interval(0, 1)*Interval(0, pi)) assert (1, 0) in halfcircle assert (0, -1) not in halfcircle assert (0, 0) in halfcircle assert halfcircle._contains((r, 0)) is None # This one doesn't work: #assert (r, 2*pi) not in halfcircle assert not halfcircle.is_iterable def test_ImageSet_iterator_not_injective(): L = Lambda(x, x - x % 2) # produces 0, 2, 2, 4, 4, 6, 6, ... evens = ImageSet(L, S.Naturals) i = iter(evens) # No repeats here assert (next(i), next(i), next(i), next(i)) == (0, 2, 4, 6) def test_inf_Range_len(): raises(ValueError, lambda: len(Range(0, oo, 2))) assert Range(0, oo, 2).size is S.Infinity assert Range(0, -oo, -2).size is S.Infinity assert Range(oo, 0, -2).size is S.Infinity assert Range(-oo, 0, 2).size is S.Infinity def test_Range_set(): empty = Range(0) assert Range(5) == Range(0, 5) == Range(0, 5, 1) r = Range(10, 20, 2) assert 12 in r assert 8 not in r assert 11 not in r assert 30 not in r assert list(Range(0, 5)) == list(range(5)) assert list(Range(5, 0, -1)) == list(range(5, 0, -1)) assert Range(5, 15).sup == 14 assert Range(5, 15).inf == 5 assert Range(15, 5, -1).sup == 15 assert Range(15, 5, -1).inf == 6 assert Range(10, 67, 10).sup == 60 assert Range(60, 7, -10).inf == 10 assert len(Range(10, 38, 10)) == 3 assert Range(0, 0, 5) == empty assert Range(oo, oo, 1) == empty assert Range(oo, 1, 1) == empty assert Range(-oo, 1, -1) == empty assert Range(1, oo, -1) == empty assert Range(1, -oo, 1) == empty assert Range(1, -4, oo) == empty ip = symbols('ip', positive=True) assert Range(0, ip, -1) == empty assert Range(0, -ip, 1) == empty assert Range(1, -4, -oo) == Range(1, 2) assert Range(1, 4, oo) == Range(1, 2) assert Range(-oo, oo).size == oo assert Range(oo, -oo, -1).size == oo raises(ValueError, lambda: Range(-oo, oo, 2)) raises(ValueError, lambda: Range(x, pi, y)) raises(ValueError, lambda: Range(x, y, 0)) assert 5 in Range(0, oo, 5) assert -5 in Range(-oo, 0, 5) assert oo not in Range(0, oo) ni = symbols('ni', integer=False) assert ni not in Range(oo) u = symbols('u', integer=None) assert Range(oo).contains(u) is not False inf = symbols('inf', infinite=True) assert inf not in Range(-oo, oo) raises(ValueError, lambda: Range(0, oo, 2)[-1]) raises(ValueError, lambda: Range(0, -oo, -2)[-1]) assert Range(-oo, 1, 1)[-1] is S.Zero assert Range(oo, 1, -1)[-1] == 2 assert inf not in Range(oo) assert Range(1, 10, 1)[-1] == 9 assert all(i.is_Integer for i in Range(0, -1, 1)) it = iter(Range(-oo, 0, 2)) raises(TypeError, lambda: next(it)) assert empty.intersect(S.Integers) == empty assert Range(-1, 10, 1).intersect(S.Integers) == Range(-1, 10, 1) assert Range(-1, 10, 1).intersect(S.Naturals) == Range(1, 10, 1) assert Range(-1, 10, 1).intersect(S.Naturals0) == Range(0, 10, 1) # test slicing assert Range(1, 10, 1)[5] == 6 assert Range(1, 12, 2)[5] == 11 assert Range(1, 10, 1)[-1] == 9 assert Range(1, 10, 3)[-1] == 7 raises(ValueError, lambda: Range(oo,0,-1)[1:3:0]) raises(ValueError, lambda: Range(oo,0,-1)[:1]) raises(ValueError, lambda: Range(1, oo)[-2]) raises(ValueError, lambda: Range(-oo, 1)[2]) raises(IndexError, lambda: Range(10)[-20]) raises(IndexError, lambda: Range(10)[20]) raises(ValueError, lambda: Range(2, -oo, -2)[2:2:0]) assert Range(2, -oo, -2)[2:2:2] == empty assert Range(2, -oo, -2)[:2:2] == Range(2, -2, -4) raises(ValueError, lambda: Range(-oo, 4, 2)[:2:2]) assert Range(-oo, 4, 2)[::-2] == Range(2, -oo, -4) raises(ValueError, lambda: Range(-oo, 4, 2)[::2]) assert Range(oo, 2, -2)[::] == Range(oo, 2, -2) assert Range(-oo, 4, 2)[:-2:-2] == Range(2, 0, -4) assert Range(-oo, 4, 2)[:-2:2] == Range(-oo, 0, 4) raises(ValueError, lambda: Range(-oo, 4, 2)[:0:-2]) raises(ValueError, lambda: Range(-oo, 4, 2)[:2:-2]) assert Range(-oo, 4, 2)[-2::-2] == Range(0, -oo, -4) raises(ValueError, lambda: Range(-oo, 4, 2)[-2:0:-2]) raises(ValueError, lambda: Range(-oo, 4, 2)[0::2]) assert Range(oo, 2, -2)[0::] == Range(oo, 2, -2) raises(ValueError, lambda: Range(-oo, 4, 2)[0:-2:2]) assert Range(oo, 2, -2)[0:-2:] == Range(oo, 6, -2) raises(ValueError, lambda: Range(oo, 2, -2)[0:2:]) raises(ValueError, lambda: Range(-oo, 4, 2)[2::-1]) assert Range(-oo, 4, 2)[-2::2] == Range(0, 4, 4) assert Range(oo, 0, -2)[-10:0:2] == empty raises(ValueError, lambda: Range(oo, 0, -2)[0]) raises(ValueError, lambda: Range(oo, 0, -2)[-10:10:2]) raises(ValueError, lambda: Range(oo, 0, -2)[0::-2]) assert Range(oo, 0, -2)[0:-4:-2] == empty assert Range(oo, 0, -2)[:0:2] == empty raises(ValueError, lambda: Range(oo, 0, -2)[:1:-1]) # test empty Range assert Range(x, x, y) == empty assert empty.reversed == empty assert 0 not in empty assert list(empty) == [] assert len(empty) == 0 assert empty.size is S.Zero assert empty.intersect(FiniteSet(0)) is S.EmptySet assert bool(empty) is False raises(IndexError, lambda: empty[0]) assert empty[:0] == empty raises(NotImplementedError, lambda: empty.inf) raises(NotImplementedError, lambda: empty.sup) assert empty.as_relational(x) is S.false AB = [None] + list(range(12)) for R in [ Range(1, 10), Range(1, 10, 2), ]: r = list(R) for a, b, c in itertools.product(AB, AB, [-3, -1, None, 1, 3]): for reverse in range(2): r = list(reversed(r)) R = R.reversed result = list(R[a:b:c]) ans = r[a:b:c] txt = ('\n%s[%s:%s:%s] = %s -> %s' % ( R, a, b, c, result, ans)) check = ans == result assert check, txt assert Range(1, 10, 1).boundary == Range(1, 10, 1) for r in (Range(1, 10, 2), Range(1, oo, 2)): rev = r.reversed assert r.inf == rev.inf and r.sup == rev.sup assert r.step == -rev.step builtin_range = range raises(TypeError, lambda: Range(builtin_range(1))) assert S(builtin_range(10)) == Range(10) assert S(builtin_range(1000000000000)) == Range(1000000000000) # test Range.as_relational assert Range(1, 4).as_relational(x) == (x >= 1) & (x <= 3) & Eq(Mod(x, 1), 0) assert Range(oo, 1, -2).as_relational(x) == (x >= 3) & (x < oo) & Eq(Mod(x + 1, -2), 0) def test_Range_symbolic(): # symbolic Range xr = Range(x, x + 4, 5) sr = Range(x, y, t) i = Symbol('i', integer=True) ip = Symbol('i', integer=True, positive=True) ipr = Range(ip) inr = Range(0, -ip, -1) ir = Range(i, i + 19, 2) ir2 = Range(i, i*8, 3*i) i = Symbol('i', integer=True) inf = symbols('inf', infinite=True) raises(ValueError, lambda: Range(inf)) raises(ValueError, lambda: Range(inf, 0, -1)) raises(ValueError, lambda: Range(inf, inf, 1)) raises(ValueError, lambda: Range(1, 1, inf)) # args assert xr.args == (x, x + 5, 5) assert sr.args == (x, y, t) assert ir.args == (i, i + 20, 2) assert ir2.args == (i, 10*i, 3*i) # reversed raises(ValueError, lambda: xr.reversed) raises(ValueError, lambda: sr.reversed) assert ipr.reversed.args == (ip - 1, -1, -1) assert inr.reversed.args == (-ip + 1, 1, 1) assert ir.reversed.args == (i + 18, i - 2, -2) assert ir2.reversed.args == (7*i, -2*i, -3*i) # contains assert inf not in sr assert inf not in ir assert 0 in ipr assert 0 in inr raises(TypeError, lambda: 1 in ipr) raises(TypeError, lambda: -1 in inr) assert .1 not in sr assert .1 not in ir assert i + 1 not in ir assert i + 2 in ir raises(TypeError, lambda: x in xr) # XXX is this what contains is supposed to do? raises(TypeError, lambda: 1 in sr) # XXX is this what contains is supposed to do? # iter raises(ValueError, lambda: next(iter(xr))) raises(ValueError, lambda: next(iter(sr))) assert next(iter(ir)) == i assert next(iter(ir2)) == i assert sr.intersect(S.Integers) == sr assert sr.intersect(FiniteSet(x)) == Intersection({x}, sr) raises(ValueError, lambda: sr[:2]) raises(ValueError, lambda: xr[0]) raises(ValueError, lambda: sr[0]) # len assert len(ir) == ir.size == 10 assert len(ir2) == ir2.size == 3 raises(ValueError, lambda: len(xr)) raises(ValueError, lambda: xr.size) raises(ValueError, lambda: len(sr)) raises(ValueError, lambda: sr.size) # bool assert bool(Range(0)) == False assert bool(xr) assert bool(ir) assert bool(ipr) assert bool(inr) raises(ValueError, lambda: bool(sr)) raises(ValueError, lambda: bool(ir2)) # inf raises(ValueError, lambda: xr.inf) raises(ValueError, lambda: sr.inf) assert ipr.inf == 0 assert inr.inf == -ip + 1 assert ir.inf == i raises(ValueError, lambda: ir2.inf) # sup raises(ValueError, lambda: xr.sup) raises(ValueError, lambda: sr.sup) assert ipr.sup == ip - 1 assert inr.sup == 0 assert ir.inf == i raises(ValueError, lambda: ir2.sup) # getitem raises(ValueError, lambda: xr[0]) raises(ValueError, lambda: sr[0]) raises(ValueError, lambda: sr[-1]) raises(ValueError, lambda: sr[:2]) assert ir[:2] == Range(i, i + 4, 2) assert ir[0] == i assert ir[-2] == i + 16 assert ir[-1] == i + 18 assert ir2[:2] == Range(i, 7*i, 3*i) assert ir2[0] == i assert ir2[-2] == 4*i assert ir2[-1] == 7*i raises(ValueError, lambda: Range(i)[-1]) assert ipr[0] == ipr.inf == 0 assert ipr[-1] == ipr.sup == ip - 1 assert inr[0] == inr.sup == 0 assert inr[-1] == inr.inf == -ip + 1 raises(ValueError, lambda: ipr[-2]) assert ir.inf == i assert ir.sup == i + 18 raises(ValueError, lambda: Range(i).inf) # as_relational assert ir.as_relational(x) == ((x >= i) & (x <= i + 18) & Eq(Mod(-i + x, 2), 0)) assert ir2.as_relational(x) == Eq( Mod(-i + x, 3*i), 0) & (((x >= i) & (x <= 7*i) & (3*i >= 1)) | ((x <= i) & (x >= 7*i) & (3*i <= -1))) assert Range(i, i + 1).as_relational(x) == Eq(x, i) assert sr.as_relational(z) == Eq( Mod(t, 1), 0) & Eq(Mod(x, 1), 0) & Eq(Mod(-x + z, t), 0 ) & (((z >= x) & (z <= -t + y) & (t >= 1)) | ((z <= x) & (z >= -t + y) & (t <= -1))) assert xr.as_relational(z) == Eq(z, x) & Eq(Mod(x, 1), 0) # symbols can clash if user wants (but it must be integer) assert xr.as_relational(x) == Eq(Mod(x, 1), 0) # contains() for symbolic values (issue #18146) e = Symbol('e', integer=True, even=True) o = Symbol('o', integer=True, odd=True) assert Range(5).contains(i) == And(i >= 0, i <= 4) assert Range(1).contains(i) == Eq(i, 0) assert Range(-oo, 5, 1).contains(i) == (i <= 4) assert Range(-oo, oo).contains(i) == True assert Range(0, 8, 2).contains(i) == Contains(i, Range(0, 8, 2)) assert Range(0, 8, 2).contains(e) == And(e >= 0, e <= 6) assert Range(0, 8, 2).contains(2*i) == And(2*i >= 0, 2*i <= 6) assert Range(0, 8, 2).contains(o) == False assert Range(1, 9, 2).contains(e) == False assert Range(1, 9, 2).contains(o) == And(o >= 1, o <= 7) assert Range(8, 0, -2).contains(o) == False assert Range(9, 1, -2).contains(o) == And(o >= 3, o <= 9) assert Range(-oo, 8, 2).contains(i) == Contains(i, Range(-oo, 8, 2)) def test_range_range_intersection(): for a, b, r in [ (Range(0), Range(1), S.EmptySet), (Range(3), Range(4, oo), S.EmptySet), (Range(3), Range(-3, -1), S.EmptySet), (Range(1, 3), Range(0, 3), Range(1, 3)), (Range(1, 3), Range(1, 4), Range(1, 3)), (Range(1, oo, 2), Range(2, oo, 2), S.EmptySet), (Range(0, oo, 2), Range(oo), Range(0, oo, 2)), (Range(0, oo, 2), Range(100), Range(0, 100, 2)), (Range(2, oo, 2), Range(oo), Range(2, oo, 2)), (Range(0, oo, 2), Range(5, 6), S.EmptySet), (Range(2, 80, 1), Range(55, 71, 4), Range(55, 71, 4)), (Range(0, 6, 3), Range(-oo, 5, 3), S.EmptySet), (Range(0, oo, 2), Range(5, oo, 3), Range(8, oo, 6)), (Range(4, 6, 2), Range(2, 16, 7), S.EmptySet),]: assert a.intersect(b) == r assert a.intersect(b.reversed) == r assert a.reversed.intersect(b) == r assert a.reversed.intersect(b.reversed) == r a, b = b, a assert a.intersect(b) == r assert a.intersect(b.reversed) == r assert a.reversed.intersect(b) == r assert a.reversed.intersect(b.reversed) == r def test_range_interval_intersection(): p = symbols('p', positive=True) assert isinstance(Range(3).intersect(Interval(p, p + 2)), Intersection) assert Range(4).intersect(Interval(0, 3)) == Range(4) assert Range(4).intersect(Interval(-oo, oo)) == Range(4) assert Range(4).intersect(Interval(1, oo)) == Range(1, 4) assert Range(4).intersect(Interval(1.1, oo)) == Range(2, 4) assert Range(4).intersect(Interval(0.1, 3)) == Range(1, 4) assert Range(4).intersect(Interval(0.1, 3.1)) == Range(1, 4) assert Range(4).intersect(Interval.open(0, 3)) == Range(1, 3) assert Range(4).intersect(Interval.open(0.1, 0.5)) is S.EmptySet # Null Range intersections assert Range(0).intersect(Interval(0.2, 0.8)) is S.EmptySet assert Range(0).intersect(Interval(-oo, oo)) is S.EmptySet def test_range_is_finite_set(): assert Range(-100, 100).is_finite_set is True assert Range(2, oo).is_finite_set is False assert Range(-oo, 50).is_finite_set is False assert Range(-oo, oo).is_finite_set is False assert Range(oo, -oo).is_finite_set is True assert Range(0, 0).is_finite_set is True assert Range(oo, oo).is_finite_set is True assert Range(-oo, -oo).is_finite_set is True n = Symbol('n', integer=True) m = Symbol('m', integer=True) assert Range(n, n + 49).is_finite_set is True assert Range(n, 0).is_finite_set is True assert Range(-3, n + 7).is_finite_set is True assert Range(n, m).is_finite_set is True assert Range(n + m, m - n).is_finite_set is True assert Range(n, n + m + n).is_finite_set is True assert Range(n, oo).is_finite_set is False assert Range(-oo, n).is_finite_set is False assert Range(n, -oo).is_finite_set is True assert Range(oo, n).is_finite_set is True def test_Range_is_iterable(): assert Range(-100, 100).is_iterable is True assert Range(2, oo).is_iterable is False assert Range(-oo, 50).is_iterable is False assert Range(-oo, oo).is_iterable is False assert Range(oo, -oo).is_iterable is True assert Range(0, 0).is_iterable is True assert Range(oo, oo).is_iterable is True assert Range(-oo, -oo).is_iterable is True n = Symbol('n', integer=True) m = Symbol('m', integer=True) p = Symbol('p', integer=True, positive=True) assert Range(n, n + 49).is_iterable is True assert Range(n, 0).is_iterable is False assert Range(-3, n + 7).is_iterable is False assert Range(-3, p + 7).is_iterable is False # Should work with better __iter__ assert Range(n, m).is_iterable is False assert Range(n + m, m - n).is_iterable is False assert Range(n, n + m + n).is_iterable is False assert Range(n, oo).is_iterable is False assert Range(-oo, n).is_iterable is False x = Symbol('x') assert Range(x, x + 49).is_iterable is False assert Range(x, 0).is_iterable is False assert Range(-3, x + 7).is_iterable is False assert Range(x, m).is_iterable is False assert Range(x + m, m - x).is_iterable is False assert Range(x, x + m + x).is_iterable is False assert Range(x, oo).is_iterable is False assert Range(-oo, x).is_iterable is False def test_Integers_eval_imageset(): ans = ImageSet(Lambda(x, 2*x + Rational(3, 7)), S.Integers) im = imageset(Lambda(x, -2*x + Rational(3, 7)), S.Integers) assert im == ans im = imageset(Lambda(x, -2*x - Rational(11, 7)), S.Integers) assert im == ans y = Symbol('y') L = imageset(x, 2*x + y, S.Integers) assert y + 4 in L a, b, c = 0.092, 0.433, 0.341 assert a in imageset(x, a + c*x, S.Integers) assert b in imageset(x, b + c*x, S.Integers) _x = symbols('x', negative=True) eq = _x**2 - _x + 1 assert imageset(_x, eq, S.Integers).lamda.expr == _x**2 + _x + 1 eq = 3*_x - 1 assert imageset(_x, eq, S.Integers).lamda.expr == 3*_x + 2 assert imageset(x, (x, 1/x), S.Integers) == \ ImageSet(Lambda(x, (x, 1/x)), S.Integers) def test_Range_eval_imageset(): a, b, c = symbols('a b c') assert imageset(x, a*(x + b) + c, Range(3)) == \ imageset(x, a*x + a*b + c, Range(3)) eq = (x + 1)**2 assert imageset(x, eq, Range(3)).lamda.expr == eq eq = a*(x + b) + c r = Range(3, -3, -2) imset = imageset(x, eq, r) assert imset.lamda.expr != eq assert list(imset) == [eq.subs(x, i).expand() for i in list(r)] def test_fun(): assert (FiniteSet(*ImageSet(Lambda(x, sin(pi*x/4)), Range(-10, 11))) == FiniteSet(-1, -sqrt(2)/2, 0, sqrt(2)/2, 1)) def test_Range_is_empty(): i = Symbol('i', integer=True) n = Symbol('n', negative=True, integer=True) p = Symbol('p', positive=True, integer=True) assert Range(0).is_empty assert not Range(1).is_empty assert Range(1, 0).is_empty assert not Range(-1, 0).is_empty assert Range(i).is_empty is None assert Range(n).is_empty assert Range(p).is_empty is False assert Range(n, 0).is_empty is False assert Range(n, p).is_empty is False assert Range(p, n).is_empty assert Range(n, -1).is_empty is None assert Range(p, n, -1).is_empty is False def test_Reals(): assert 5 in S.Reals assert S.Pi in S.Reals assert -sqrt(2) in S.Reals assert (2, 5) not in S.Reals assert sqrt(-1) not in S.Reals assert S.Reals == Interval(-oo, oo) assert S.Reals != Interval(0, oo) assert S.Reals.is_subset(Interval(-oo, oo)) assert S.Reals.intersect(Range(-oo, oo)) == Range(-oo, oo) assert S.ComplexInfinity not in S.Reals assert S.NaN not in S.Reals assert x + S.ComplexInfinity not in S.Reals def test_Complex(): assert 5 in S.Complexes assert 5 + 4*I in S.Complexes assert S.Pi in S.Complexes assert -sqrt(2) in S.Complexes assert -I in S.Complexes assert sqrt(-1) in S.Complexes assert S.Complexes.intersect(S.Reals) == S.Reals assert S.Complexes.union(S.Reals) == S.Complexes assert S.Complexes == ComplexRegion(S.Reals*S.Reals) assert (S.Complexes == ComplexRegion(Interval(1, 2)*Interval(3, 4))) == False assert str(S.Complexes) == "Complexes" assert repr(S.Complexes) == "Complexes" def take(n, iterable): "Return first n items of the iterable as a list" return list(itertools.islice(iterable, n)) def test_intersections(): assert S.Integers.intersect(S.Reals) == S.Integers assert 5 in S.Integers.intersect(S.Reals) assert 5 in S.Integers.intersect(S.Reals) assert -5 not in S.Naturals.intersect(S.Reals) assert 5.5 not in S.Integers.intersect(S.Reals) assert 5 in S.Integers.intersect(Interval(3, oo)) assert -5 in S.Integers.intersect(Interval(-oo, 3)) assert all(x.is_Integer for x in take(10, S.Integers.intersect(Interval(3, oo)) )) def test_infinitely_indexed_set_1(): from sympy.abc import n, m assert imageset(Lambda(n, n), S.Integers) == imageset(Lambda(m, m), S.Integers) assert imageset(Lambda(n, 2*n), S.Integers).intersect( imageset(Lambda(m, 2*m + 1), S.Integers)) is S.EmptySet assert imageset(Lambda(n, 2*n), S.Integers).intersect( imageset(Lambda(n, 2*n + 1), S.Integers)) is S.EmptySet assert imageset(Lambda(m, 2*m), S.Integers).intersect( imageset(Lambda(n, 3*n), S.Integers)).dummy_eq( ImageSet(Lambda(t, 6*t), S.Integers)) assert imageset(x, x/2 + Rational(1, 3), S.Integers).intersect(S.Integers) is S.EmptySet assert imageset(x, x/2 + S.Half, S.Integers).intersect(S.Integers) is S.Integers # https://github.com/sympy/sympy/issues/17355 S53 = ImageSet(Lambda(n, 5*n + 3), S.Integers) assert S53.intersect(S.Integers) == S53 def test_infinitely_indexed_set_2(): from sympy.abc import n a = Symbol('a', integer=True) assert imageset(Lambda(n, n), S.Integers) == \ imageset(Lambda(n, n + a), S.Integers) assert imageset(Lambda(n, n + pi), S.Integers) == \ imageset(Lambda(n, n + a + pi), S.Integers) assert imageset(Lambda(n, n), S.Integers) == \ imageset(Lambda(n, -n + a), S.Integers) assert imageset(Lambda(n, -6*n), S.Integers) == \ ImageSet(Lambda(n, 6*n), S.Integers) assert imageset(Lambda(n, 2*n + pi), S.Integers) == \ ImageSet(Lambda(n, 2*n + pi - 2), S.Integers) def test_imageset_intersect_real(): from sympy.abc import n assert imageset(Lambda(n, n + (n - 1)*(n + 1)*I), S.Integers).intersect(S.Reals) == FiniteSet(-1, 1) im = (n - 1)*(n + S.Half) assert imageset(Lambda(n, n + im*I), S.Integers ).intersect(S.Reals) == FiniteSet(1) assert imageset(Lambda(n, n + im*(n + 1)*I), S.Naturals0 ).intersect(S.Reals) == FiniteSet(1) assert imageset(Lambda(n, n/2 + im.expand()*I), S.Integers ).intersect(S.Reals) == ImageSet(Lambda(x, x/2), ConditionSet( n, Eq(n**2 - n/2 - S(1)/2, 0), S.Integers)) assert imageset(Lambda(n, n/(1/n - 1) + im*(n + 1)*I), S.Integers ).intersect(S.Reals) == FiniteSet(S.Half) assert imageset(Lambda(n, n/(n - 6) + (n - 3)*(n + 1)*I/(2*n + 2)), S.Integers).intersect( S.Reals) == FiniteSet(-1) assert imageset(Lambda(n, n/(n**2 - 9) + (n - 3)*(n + 1)*I/(2*n + 2)), S.Integers).intersect( S.Reals) is S.EmptySet s = ImageSet( Lambda(n, -I*(I*(2*pi*n - pi/4) + log(Abs(sqrt(-I))))), S.Integers) # s is unevaluated, but after intersection the result # should be canonical assert s.intersect(S.Reals) == imageset( Lambda(n, 2*n*pi - pi/4), S.Integers) == ImageSet( Lambda(n, 2*pi*n + pi*Rational(7, 4)), S.Integers) def test_imageset_intersect_interval(): from sympy.abc import n f1 = ImageSet(Lambda(n, n*pi), S.Integers) f2 = ImageSet(Lambda(n, 2*n), Interval(0, pi)) f3 = ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers) # complex expressions f4 = ImageSet(Lambda(n, n*I*pi), S.Integers) f5 = ImageSet(Lambda(n, 2*I*n*pi + pi/2), S.Integers) # non-linear expressions f6 = ImageSet(Lambda(n, log(n)), S.Integers) f7 = ImageSet(Lambda(n, n**2), S.Integers) f8 = ImageSet(Lambda(n, Abs(n)), S.Integers) f9 = ImageSet(Lambda(n, exp(n)), S.Naturals0) assert f1.intersect(Interval(-1, 1)) == FiniteSet(0) assert f1.intersect(Interval(0, 2*pi, False, True)) == FiniteSet(0, pi) assert f2.intersect(Interval(1, 2)) == Interval(1, 2) assert f3.intersect(Interval(-1, 1)) == S.EmptySet assert f3.intersect(Interval(-5, 5)) == FiniteSet(pi*Rational(-3, 2), pi/2) assert f4.intersect(Interval(-1, 1)) == FiniteSet(0) assert f4.intersect(Interval(1, 2)) == S.EmptySet assert f5.intersect(Interval(0, 1)) == S.EmptySet assert f6.intersect(Interval(0, 1)) == FiniteSet(S.Zero, log(2)) assert f7.intersect(Interval(0, 10)) == Intersection(f7, Interval(0, 10)) assert f8.intersect(Interval(0, 2)) == Intersection(f8, Interval(0, 2)) assert f9.intersect(Interval(1, 2)) == Intersection(f9, Interval(1, 2)) def test_imageset_intersect_diophantine(): from sympy.abc import m, n # Check that same lambda variable for both ImageSets is handled correctly img1 = ImageSet(Lambda(n, 2*n + 1), S.Integers) img2 = ImageSet(Lambda(n, 4*n + 1), S.Integers) assert img1.intersect(img2) == img2 # Empty solution set returned by diophantine: assert ImageSet(Lambda(n, 2*n), S.Integers).intersect( ImageSet(Lambda(n, 2*n + 1), S.Integers)) == S.EmptySet # Check intersection with S.Integers: assert ImageSet(Lambda(n, 9/n + 20*n/3), S.Integers).intersect( S.Integers) == FiniteSet(-61, -23, 23, 61) # Single solution (2, 3) for diophantine solution: assert ImageSet(Lambda(n, (n - 2)**2), S.Integers).intersect( ImageSet(Lambda(n, -(n - 3)**2), S.Integers)) == FiniteSet(0) # Single parametric solution for diophantine solution: assert ImageSet(Lambda(n, n**2 + 5), S.Integers).intersect( ImageSet(Lambda(m, 2*m), S.Integers)).dummy_eq(ImageSet( Lambda(n, 4*n**2 + 4*n + 6), S.Integers)) # 4 non-parametric solution couples for dioph. equation: assert ImageSet(Lambda(n, n**2 - 9), S.Integers).intersect( ImageSet(Lambda(m, -m**2), S.Integers)) == FiniteSet(-9, 0) # Double parametric solution for diophantine solution: assert ImageSet(Lambda(m, m**2 + 40), S.Integers).intersect( ImageSet(Lambda(n, 41*n), S.Integers)).dummy_eq(Intersection( ImageSet(Lambda(m, m**2 + 40), S.Integers), ImageSet(Lambda(n, 41*n), S.Integers))) # Check that diophantine returns *all* (8) solutions (permute=True) assert ImageSet(Lambda(n, n**4 - 2**4), S.Integers).intersect( ImageSet(Lambda(m, -m**4 + 3**4), S.Integers)) == FiniteSet(0, 65) assert ImageSet(Lambda(n, pi/12 + n*5*pi/12), S.Integers).intersect( ImageSet(Lambda(n, 7*pi/12 + n*11*pi/12), S.Integers)).dummy_eq(ImageSet( Lambda(n, 55*pi*n/12 + 17*pi/4), S.Integers)) # TypeError raised by diophantine (#18081) assert ImageSet(Lambda(n, n*log(2)), S.Integers).intersection( S.Integers).dummy_eq(Intersection(ImageSet( Lambda(n, n*log(2)), S.Integers), S.Integers)) # NotImplementedError raised by diophantine (no solver for cubic_thue) assert ImageSet(Lambda(n, n**3 + 1), S.Integers).intersect( ImageSet(Lambda(n, n**3), S.Integers)).dummy_eq(Intersection( ImageSet(Lambda(n, n**3 + 1), S.Integers), ImageSet(Lambda(n, n**3), S.Integers))) def test_infinitely_indexed_set_3(): from sympy.abc import n, m assert imageset(Lambda(m, 2*pi*m), S.Integers).intersect( imageset(Lambda(n, 3*pi*n), S.Integers)).dummy_eq( ImageSet(Lambda(t, 6*pi*t), S.Integers)) assert imageset(Lambda(n, 2*n + 1), S.Integers) == \ imageset(Lambda(n, 2*n - 1), S.Integers) assert imageset(Lambda(n, 3*n + 2), S.Integers) == \ imageset(Lambda(n, 3*n - 1), S.Integers) def test_ImageSet_simplification(): from sympy.abc import n, m assert imageset(Lambda(n, n), S.Integers) == S.Integers assert imageset(Lambda(n, sin(n)), imageset(Lambda(m, tan(m)), S.Integers)) == \ imageset(Lambda(m, sin(tan(m))), S.Integers) assert imageset(n, 1 + 2*n, S.Naturals) == Range(3, oo, 2) assert imageset(n, 1 + 2*n, S.Naturals0) == Range(1, oo, 2) assert imageset(n, 1 - 2*n, S.Naturals) == Range(-1, -oo, -2) def test_ImageSet_contains(): assert (2, S.Half) in imageset(x, (x, 1/x), S.Integers) assert imageset(x, x + I*3, S.Integers).intersection(S.Reals) is S.EmptySet i = Dummy(integer=True) q = imageset(x, x + I*y, S.Integers).intersection(S.Reals) assert q.subs(y, I*i).intersection(S.Integers) is S.Integers q = imageset(x, x + I*y/x, S.Integers).intersection(S.Reals) assert q.subs(y, 0) is S.Integers assert q.subs(y, I*i*x).intersection(S.Integers) is S.Integers z = cos(1)**2 + sin(1)**2 - 1 q = imageset(x, x + I*z, S.Integers).intersection(S.Reals) assert q is not S.EmptySet def test_ComplexRegion_contains(): r = Symbol('r', real=True) # contains in ComplexRegion a = Interval(2, 3) b = Interval(4, 6) c = Interval(7, 9) c1 = ComplexRegion(a*b) c2 = ComplexRegion(Union(a*b, c*a)) assert 2.5 + 4.5*I in c1 assert 2 + 4*I in c1 assert 3 + 4*I in c1 assert 8 + 2.5*I in c2 assert 2.5 + 6.1*I not in c1 assert 4.5 + 3.2*I not in c1 assert c1.contains(x) == Contains(x, c1, evaluate=False) assert c1.contains(r) == False assert c2.contains(x) == Contains(x, c2, evaluate=False) assert c2.contains(r) == False r1 = Interval(0, 1) theta1 = Interval(0, 2*S.Pi) c3 = ComplexRegion(r1*theta1, polar=True) assert (0.5 + I*Rational(6, 10)) in c3 assert (S.Half + I*Rational(6, 10)) in c3 assert (S.Half + .6*I) in c3 assert (0.5 + .6*I) in c3 assert I in c3 assert 1 in c3 assert 0 in c3 assert 1 + I not in c3 assert 1 - I not in c3 assert c3.contains(x) == Contains(x, c3, evaluate=False) assert c3.contains(r + 2*I) == Contains( r + 2*I, c3, evaluate=False) # is in fact False assert c3.contains(1/(1 + r**2)) == Contains( 1/(1 + r**2), c3, evaluate=False) # is in fact True r2 = Interval(0, 3) theta2 = Interval(pi, 2*pi, left_open=True) c4 = ComplexRegion(r2*theta2, polar=True) assert c4.contains(0) == True assert c4.contains(2 + I) == False assert c4.contains(-2 + I) == False assert c4.contains(-2 - I) == True assert c4.contains(2 - I) == True assert c4.contains(-2) == False assert c4.contains(2) == True assert c4.contains(x) == Contains(x, c4, evaluate=False) assert c4.contains(3/(1 + r**2)) == Contains( 3/(1 + r**2), c4, evaluate=False) # is in fact True raises(ValueError, lambda: ComplexRegion(r1*theta1, polar=2)) def test_symbolic_Range(): n = Symbol('n') raises(ValueError, lambda: Range(n)[0]) raises(IndexError, lambda: Range(n, n)[0]) raises(ValueError, lambda: Range(n, n+1)[0]) raises(ValueError, lambda: Range(n).size) n = Symbol('n', integer=True) raises(ValueError, lambda: Range(n)[0]) raises(IndexError, lambda: Range(n, n)[0]) assert Range(n, n+1)[0] == n raises(ValueError, lambda: Range(n).size) assert Range(n, n+1).size == 1 n = Symbol('n', integer=True, nonnegative=True) raises(ValueError, lambda: Range(n)[0]) raises(IndexError, lambda: Range(n, n)[0]) assert Range(n+1)[0] == 0 assert Range(n, n+1)[0] == n assert Range(n).size == n assert Range(n+1).size == n+1 assert Range(n, n+1).size == 1 n = Symbol('n', integer=True, positive=True) assert Range(n)[0] == 0 assert Range(n, n+1)[0] == n assert Range(n).size == n assert Range(n, n+1).size == 1 m = Symbol('m', integer=True, positive=True) assert Range(n, n+m)[0] == n assert Range(n, n+m).size == m assert Range(n, n+1).size == 1 assert Range(n, n+m, 2).size == floor(m/2) m = Symbol('m', integer=True, positive=True, even=True) assert Range(n, n+m, 2).size == m/2 def test_issue_18400(): n = Symbol('n', integer=True) raises(ValueError, lambda: imageset(lambda x: x*2, Range(n))) n = Symbol('n', integer=True, positive=True) # No exception assert imageset(lambda x: x*2, Range(n)) == imageset(lambda x: x*2, Range(n)) def test_ComplexRegion_intersect(): # Polar form X_axis = ComplexRegion(Interval(0, oo)*FiniteSet(0, S.Pi), polar=True) unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True) upper_half_unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True) upper_half_disk = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi), polar=True) lower_half_disk = ComplexRegion(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True) right_half_disk = ComplexRegion(Interval(0, oo)*Interval(-S.Pi/2, S.Pi/2), polar=True) first_quad_disk = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi/2), polar=True) assert upper_half_disk.intersect(unit_disk) == upper_half_unit_disk assert right_half_disk.intersect(first_quad_disk) == first_quad_disk assert upper_half_disk.intersect(right_half_disk) == first_quad_disk assert upper_half_disk.intersect(lower_half_disk) == X_axis c1 = ComplexRegion(Interval(0, 4)*Interval(0, 2*S.Pi), polar=True) assert c1.intersect(Interval(1, 5)) == Interval(1, 4) assert c1.intersect(Interval(4, 9)) == FiniteSet(4) assert c1.intersect(Interval(5, 12)) is S.EmptySet # Rectangular form X_axis = ComplexRegion(Interval(-oo, oo)*FiniteSet(0)) unit_square = ComplexRegion(Interval(-1, 1)*Interval(-1, 1)) upper_half_unit_square = ComplexRegion(Interval(-1, 1)*Interval(0, 1)) upper_half_plane = ComplexRegion(Interval(-oo, oo)*Interval(0, oo)) lower_half_plane = ComplexRegion(Interval(-oo, oo)*Interval(-oo, 0)) right_half_plane = ComplexRegion(Interval(0, oo)*Interval(-oo, oo)) first_quad_plane = ComplexRegion(Interval(0, oo)*Interval(0, oo)) assert upper_half_plane.intersect(unit_square) == upper_half_unit_square assert right_half_plane.intersect(first_quad_plane) == first_quad_plane assert upper_half_plane.intersect(right_half_plane) == first_quad_plane assert upper_half_plane.intersect(lower_half_plane) == X_axis c1 = ComplexRegion(Interval(-5, 5)*Interval(-10, 10)) assert c1.intersect(Interval(2, 7)) == Interval(2, 5) assert c1.intersect(Interval(5, 7)) == FiniteSet(5) assert c1.intersect(Interval(6, 9)) is S.EmptySet # unevaluated object C1 = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True) C2 = ComplexRegion(Interval(-1, 1)*Interval(-1, 1)) assert C1.intersect(C2) == Intersection(C1, C2, evaluate=False) def test_ComplexRegion_union(): # Polar form c1 = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True) c2 = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True) c3 = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi), polar=True) c4 = ComplexRegion(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True) p1 = Union(Interval(0, 1)*Interval(0, 2*S.Pi), Interval(0, 1)*Interval(0, S.Pi)) p2 = Union(Interval(0, oo)*Interval(0, S.Pi), Interval(0, oo)*Interval(S.Pi, 2*S.Pi)) assert c1.union(c2) == ComplexRegion(p1, polar=True) assert c3.union(c4) == ComplexRegion(p2, polar=True) # Rectangular form c5 = ComplexRegion(Interval(2, 5)*Interval(6, 9)) c6 = ComplexRegion(Interval(4, 6)*Interval(10, 12)) c7 = ComplexRegion(Interval(0, 10)*Interval(-10, 0)) c8 = ComplexRegion(Interval(12, 16)*Interval(14, 20)) p3 = Union(Interval(2, 5)*Interval(6, 9), Interval(4, 6)*Interval(10, 12)) p4 = Union(Interval(0, 10)*Interval(-10, 0), Interval(12, 16)*Interval(14, 20)) assert c5.union(c6) == ComplexRegion(p3) assert c7.union(c8) == ComplexRegion(p4) assert c1.union(Interval(2, 4)) == Union(c1, Interval(2, 4), evaluate=False) assert c5.union(Interval(2, 4)) == Union(c5, ComplexRegion.from_real(Interval(2, 4))) def test_ComplexRegion_from_real(): c1 = ComplexRegion(Interval(0, 1) * Interval(0, 2 * S.Pi), polar=True) raises(ValueError, lambda: c1.from_real(c1)) assert c1.from_real(Interval(-1, 1)) == ComplexRegion(Interval(-1, 1) * FiniteSet(0), False) def test_ComplexRegion_measure(): a, b = Interval(2, 5), Interval(4, 8) theta1, theta2 = Interval(0, 2*S.Pi), Interval(0, S.Pi) c1 = ComplexRegion(a*b) c2 = ComplexRegion(Union(a*theta1, b*theta2), polar=True) assert c1.measure == 12 assert c2.measure == 9*pi def test_normalize_theta_set(): # Interval assert normalize_theta_set(Interval(pi, 2*pi)) == \ Union(FiniteSet(0), Interval.Ropen(pi, 2*pi)) assert normalize_theta_set(Interval(pi*Rational(9, 2), 5*pi)) == Interval(pi/2, pi) assert normalize_theta_set(Interval(pi*Rational(-3, 2), pi/2)) == Interval.Ropen(0, 2*pi) assert normalize_theta_set(Interval.open(pi*Rational(-3, 2), pi/2)) == \ Union(Interval.Ropen(0, pi/2), Interval.open(pi/2, 2*pi)) assert normalize_theta_set(Interval.open(pi*Rational(-7, 2), pi*Rational(-3, 2))) == \ Union(Interval.Ropen(0, pi/2), Interval.open(pi/2, 2*pi)) assert normalize_theta_set(Interval(-pi/2, pi/2)) == \ Union(Interval(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi)) assert normalize_theta_set(Interval.open(-pi/2, pi/2)) == \ Union(Interval.Ropen(0, pi/2), Interval.open(pi*Rational(3, 2), 2*pi)) assert normalize_theta_set(Interval(-4*pi, 3*pi)) == Interval.Ropen(0, 2*pi) assert normalize_theta_set(Interval(pi*Rational(-3, 2), -pi/2)) == Interval(pi/2, pi*Rational(3, 2)) assert normalize_theta_set(Interval.open(0, 2*pi)) == Interval.open(0, 2*pi) assert normalize_theta_set(Interval.Ropen(-pi/2, pi/2)) == \ Union(Interval.Ropen(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi)) assert normalize_theta_set(Interval.Lopen(-pi/2, pi/2)) == \ Union(Interval(0, pi/2), Interval.open(pi*Rational(3, 2), 2*pi)) assert normalize_theta_set(Interval(-pi/2, pi/2)) == \ Union(Interval(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi)) assert normalize_theta_set(Interval.open(4*pi, pi*Rational(9, 2))) == Interval.open(0, pi/2) assert normalize_theta_set(Interval.Lopen(4*pi, pi*Rational(9, 2))) == Interval.Lopen(0, pi/2) assert normalize_theta_set(Interval.Ropen(4*pi, pi*Rational(9, 2))) == Interval.Ropen(0, pi/2) assert normalize_theta_set(Interval.open(3*pi, 5*pi)) == \ Union(Interval.Ropen(0, pi), Interval.open(pi, 2*pi)) # FiniteSet assert normalize_theta_set(FiniteSet(0, pi, 3*pi)) == FiniteSet(0, pi) assert normalize_theta_set(FiniteSet(0, pi/2, pi, 2*pi)) == FiniteSet(0, pi/2, pi) assert normalize_theta_set(FiniteSet(0, -pi/2, -pi, -2*pi)) == FiniteSet(0, pi, pi*Rational(3, 2)) assert normalize_theta_set(FiniteSet(pi*Rational(-3, 2), pi/2)) == \ FiniteSet(pi/2) assert normalize_theta_set(FiniteSet(2*pi)) == FiniteSet(0) # Unions assert normalize_theta_set(Union(Interval(0, pi/3), Interval(pi/2, pi))) == \ Union(Interval(0, pi/3), Interval(pi/2, pi)) assert normalize_theta_set(Union(Interval(0, pi), Interval(2*pi, pi*Rational(7, 3)))) == \ Interval(0, pi) # ValueError for non-real sets raises(ValueError, lambda: normalize_theta_set(S.Complexes)) # NotImplementedError for subset of reals raises(NotImplementedError, lambda: normalize_theta_set(Interval(0, 1))) # NotImplementedError without pi as coefficient raises(NotImplementedError, lambda: normalize_theta_set(Interval(1, 2*pi))) raises(NotImplementedError, lambda: normalize_theta_set(Interval(2*pi, 10))) raises(NotImplementedError, lambda: normalize_theta_set(FiniteSet(0, 3, 3*pi))) def test_ComplexRegion_FiniteSet(): x, y, z, a, b, c = symbols('x y z a b c') # Issue #9669 assert ComplexRegion(FiniteSet(a, b, c)*FiniteSet(x, y, z)) == \ FiniteSet(a + I*x, a + I*y, a + I*z, b + I*x, b + I*y, b + I*z, c + I*x, c + I*y, c + I*z) assert ComplexRegion(FiniteSet(2)*FiniteSet(3)) == FiniteSet(2 + 3*I) def test_union_RealSubSet(): assert (S.Complexes).union(Interval(1, 2)) == S.Complexes assert (S.Complexes).union(S.Integers) == S.Complexes def test_issue_9980(): c1 = ComplexRegion(Interval(1, 2)*Interval(2, 3)) c2 = ComplexRegion(Interval(1, 5)*Interval(1, 3)) R = Union(c1, c2) assert simplify(R) == ComplexRegion(Union(Interval(1, 2)*Interval(2, 3), \ Interval(1, 5)*Interval(1, 3)), False) assert c1.func(*c1.args) == c1 assert R.func(*R.args) == R def test_issue_11732(): interval12 = Interval(1, 2) finiteset1234 = FiniteSet(1, 2, 3, 4) pointComplex = Tuple(1, 5) assert (interval12 in S.Naturals) == False assert (interval12 in S.Naturals0) == False assert (interval12 in S.Integers) == False assert (interval12 in S.Complexes) == False assert (finiteset1234 in S.Naturals) == False assert (finiteset1234 in S.Naturals0) == False assert (finiteset1234 in S.Integers) == False assert (finiteset1234 in S.Complexes) == False assert (pointComplex in S.Naturals) == False assert (pointComplex in S.Naturals0) == False assert (pointComplex in S.Integers) == False assert (pointComplex in S.Complexes) == True def test_issue_11730(): unit = Interval(0, 1) square = ComplexRegion(unit ** 2) assert Union(S.Complexes, FiniteSet(oo)) != S.Complexes assert Union(S.Complexes, FiniteSet(eye(4))) != S.Complexes assert Union(unit, square) == square assert Intersection(S.Reals, square) == unit def test_issue_11938(): unit = Interval(0, 1) ival = Interval(1, 2) cr1 = ComplexRegion(ival * unit) assert Intersection(cr1, S.Reals) == ival assert Intersection(cr1, unit) == FiniteSet(1) arg1 = Interval(0, S.Pi) arg2 = FiniteSet(S.Pi) arg3 = Interval(S.Pi / 4, 3 * S.Pi / 4) cp1 = ComplexRegion(unit * arg1, polar=True) cp2 = ComplexRegion(unit * arg2, polar=True) cp3 = ComplexRegion(unit * arg3, polar=True) assert Intersection(cp1, S.Reals) == Interval(-1, 1) assert Intersection(cp2, S.Reals) == Interval(-1, 0) assert Intersection(cp3, S.Reals) == FiniteSet(0) def test_issue_11914(): a, b = Interval(0, 1), Interval(0, pi) c, d = Interval(2, 3), Interval(pi, 3 * pi / 2) cp1 = ComplexRegion(a * b, polar=True) cp2 = ComplexRegion(c * d, polar=True) assert -3 in cp1.union(cp2) assert -3 in cp2.union(cp1) assert -5 not in cp1.union(cp2) def test_issue_9543(): assert ImageSet(Lambda(x, x**2), S.Naturals).is_subset(S.Reals) def test_issue_16871(): assert ImageSet(Lambda(x, x), FiniteSet(1)) == {1} assert ImageSet(Lambda(x, x - 3), S.Integers ).intersection(S.Integers) is S.Integers @XFAIL def test_issue_16871b(): assert ImageSet(Lambda(x, x - 3), S.Integers).is_subset(S.Integers) def test_issue_18050(): assert imageset(Lambda(x, I*x + 1), S.Integers ) == ImageSet(Lambda(x, I*x + 1), S.Integers) assert imageset(Lambda(x, 3*I*x + 4 + 8*I), S.Integers ) == ImageSet(Lambda(x, 3*I*x + 4 + 2*I), S.Integers) # no 'Mod' for next 2 tests: assert imageset(Lambda(x, 2*x + 3*I), S.Integers ) == ImageSet(Lambda(x, 2*x + 3*I), S.Integers) r = Symbol('r', positive=True) assert imageset(Lambda(x, r*x + 10), S.Integers ) == ImageSet(Lambda(x, r*x + 10), S.Integers) # reduce real part: assert imageset(Lambda(x, 3*x + 8 + 5*I), S.Integers ) == ImageSet(Lambda(x, 3*x + 2 + 5*I), S.Integers) def test_Rationals(): assert S.Integers.is_subset(S.Rationals) assert S.Naturals.is_subset(S.Rationals) assert S.Naturals0.is_subset(S.Rationals) assert S.Rationals.is_subset(S.Reals) assert S.Rationals.inf is -oo assert S.Rationals.sup is oo it = iter(S.Rationals) assert [next(it) for i in range(12)] == [ 0, 1, -1, S.Half, 2, Rational(-1, 2), -2, Rational(1, 3), 3, Rational(-1, 3), -3, Rational(2, 3)] assert Basic() not in S.Rationals assert S.Half in S.Rationals assert S.Rationals.contains(0.5) == Contains(0.5, S.Rationals, evaluate=False) assert 2 in S.Rationals r = symbols('r', rational=True) assert r in S.Rationals raises(TypeError, lambda: x in S.Rationals) # issue #18134: assert S.Rationals.boundary == S.Reals assert S.Rationals.closure == S.Reals assert S.Rationals.is_open == False assert S.Rationals.is_closed == False def test_NZQRC_unions(): # check that all trivial number set unions are simplified: nbrsets = (S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals, S.Complexes) unions = (Union(a, b) for a in nbrsets for b in nbrsets) assert all(u.is_Union is False for u in unions) def test_imageset_intersection(): n = Dummy() s = ImageSet(Lambda(n, -I*(I*(2*pi*n - pi/4) + log(Abs(sqrt(-I))))), S.Integers) assert s.intersect(S.Reals) == ImageSet( Lambda(n, 2*pi*n + pi*Rational(7, 4)), S.Integers) def test_issue_17858(): assert 1 in Range(-oo, oo) assert 0 in Range(oo, -oo, -1) assert oo not in Range(-oo, oo) assert -oo not in Range(-oo, oo) def test_issue_17859(): r = Range(-oo,oo) raises(ValueError,lambda: r[::2]) raises(ValueError, lambda: r[::-2]) r = Range(oo,-oo,-1) raises(ValueError,lambda: r[::2]) raises(ValueError, lambda: r[::-2])
d51d9010591b4380600b5ccd1735aef14c730ded07cb8699caedde23c038929e
from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.function import Lambda from sympy.core.numbers import (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.core.sympify import sympify from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt) from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.logic.boolalg import (false, true) from sympy.matrices.dense import Matrix from sympy.polys.rootoftools import rootof from sympy.sets.contains import Contains from sympy.sets.fancysets import (ImageSet, Range) from sympy.sets.sets import (Complement, DisjointUnion, FiniteSet, Intersection, Interval, ProductSet, Set, SymmetricDifference, Union, imageset) from mpmath import mpi from sympy.core.expr import unchanged from sympy.core.relational import Eq, Ne, Le, Lt, LessThan from sympy.logic import And, Or, Xor from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy from sympy.abc import x, y, z, m, n EmptySet = S.EmptySet def test_imageset(): ints = S.Integers assert imageset(x, x - 1, S.Naturals) is S.Naturals0 assert imageset(x, x + 1, S.Naturals0) is S.Naturals assert imageset(x, abs(x), S.Naturals0) is S.Naturals0 assert imageset(x, abs(x), S.Naturals) is S.Naturals assert imageset(x, abs(x), S.Integers) is S.Naturals0 # issue 16878a r = symbols('r', real=True) assert imageset(x, (x, x), S.Reals)._contains((1, r)) == None assert imageset(x, (x, x), S.Reals)._contains((1, 2)) == False assert (r, r) in imageset(x, (x, x), S.Reals) assert 1 + I in imageset(x, x + I, S.Reals) assert {1} not in imageset(x, (x,), S.Reals) assert (1, 1) not in imageset(x, (x,), S.Reals) raises(TypeError, lambda: imageset(x, ints)) raises(ValueError, lambda: imageset(x, y, z, ints)) raises(ValueError, lambda: imageset(Lambda(x, cos(x)), y)) assert (1, 2) in imageset(Lambda((x, y), (x, y)), ints, ints) raises(ValueError, lambda: imageset(Lambda(x, x), ints, ints)) assert imageset(cos, ints) == ImageSet(Lambda(x, cos(x)), ints) def f(x): return cos(x) assert imageset(f, ints) == imageset(x, cos(x), ints) f = lambda x: cos(x) assert imageset(f, ints) == ImageSet(Lambda(x, cos(x)), ints) assert imageset(x, 1, ints) == FiniteSet(1) assert imageset(x, y, ints) == {y} assert imageset((x, y), (1, z), ints, S.Reals) == {(1, z)} clash = Symbol('x', integer=true) assert (str(imageset(lambda x: x + clash, Interval(-2, 1)).lamda.expr) in ('x0 + x', 'x + x0')) x1, x2 = symbols("x1, x2") assert imageset(lambda x, y: Add(x, y), Interval(1, 2), Interval(2, 3)).dummy_eq( ImageSet(Lambda((x1, x2), x1 + x2), Interval(1, 2), Interval(2, 3))) def test_is_empty(): for s in [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals, S.UniversalSet]: assert s.is_empty is False assert S.EmptySet.is_empty is True def test_is_finiteset(): for s in [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals, S.UniversalSet]: assert s.is_finite_set is False assert S.EmptySet.is_finite_set is True assert FiniteSet(1, 2).is_finite_set is True assert Interval(1, 2).is_finite_set is False assert Interval(x, y).is_finite_set is None assert ProductSet(FiniteSet(1), FiniteSet(2)).is_finite_set is True assert ProductSet(FiniteSet(1), Interval(1, 2)).is_finite_set is False assert ProductSet(FiniteSet(1), Interval(x, y)).is_finite_set is None assert Union(Interval(0, 1), Interval(2, 3)).is_finite_set is False assert Union(FiniteSet(1), Interval(2, 3)).is_finite_set is False assert Union(FiniteSet(1), FiniteSet(2)).is_finite_set is True assert Union(FiniteSet(1), Interval(x, y)).is_finite_set is None assert Intersection(Interval(x, y), FiniteSet(1)).is_finite_set is True assert Intersection(Interval(x, y), Interval(1, 2)).is_finite_set is None assert Intersection(FiniteSet(x), FiniteSet(y)).is_finite_set is True assert Complement(FiniteSet(1), Interval(x, y)).is_finite_set is True assert Complement(Interval(x, y), FiniteSet(1)).is_finite_set is None assert Complement(Interval(1, 2), FiniteSet(x)).is_finite_set is False assert DisjointUnion(Interval(-5, 3), FiniteSet(x, y)).is_finite_set is False assert DisjointUnion(S.EmptySet, FiniteSet(x, y), S.EmptySet).is_finite_set is True def test_deprecated_is_EmptySet(): with warns_deprecated_sympy(): S.EmptySet.is_EmptySet def test_interval_arguments(): assert Interval(0, oo) == Interval(0, oo, False, True) assert Interval(0, oo).right_open is true assert Interval(-oo, 0) == Interval(-oo, 0, True, False) assert Interval(-oo, 0).left_open is true assert Interval(oo, -oo) == S.EmptySet assert Interval(oo, oo) == S.EmptySet assert Interval(-oo, -oo) == S.EmptySet assert Interval(oo, x) == S.EmptySet assert Interval(oo, oo) == S.EmptySet assert Interval(x, -oo) == S.EmptySet assert Interval(x, x) == {x} assert isinstance(Interval(1, 1), FiniteSet) e = Sum(x, (x, 1, 3)) assert isinstance(Interval(e, e), FiniteSet) assert Interval(1, 0) == S.EmptySet assert Interval(1, 1).measure == 0 assert Interval(1, 1, False, True) == S.EmptySet assert Interval(1, 1, True, False) == S.EmptySet assert Interval(1, 1, True, True) == S.EmptySet assert isinstance(Interval(0, Symbol('a')), Interval) assert Interval(Symbol('a', real=True, positive=True), 0) == S.EmptySet raises(ValueError, lambda: Interval(0, S.ImaginaryUnit)) raises(ValueError, lambda: Interval(0, Symbol('z', extended_real=False))) raises(ValueError, lambda: Interval(x, x + S.ImaginaryUnit)) raises(NotImplementedError, lambda: Interval(0, 1, And(x, y))) raises(NotImplementedError, lambda: Interval(0, 1, False, And(x, y))) raises(NotImplementedError, lambda: Interval(0, 1, z, And(x, y))) def test_interval_symbolic_end_points(): a = Symbol('a', real=True) assert Union(Interval(0, a), Interval(0, 3)).sup == Max(a, 3) assert Union(Interval(a, 0), Interval(-3, 0)).inf == Min(-3, a) assert Interval(0, a).contains(1) == LessThan(1, a) def test_interval_is_empty(): x, y = symbols('x, y') r = Symbol('r', real=True) p = Symbol('p', positive=True) n = Symbol('n', negative=True) nn = Symbol('nn', nonnegative=True) assert Interval(1, 2).is_empty == False assert Interval(3, 3).is_empty == False # FiniteSet assert Interval(r, r).is_empty == False # FiniteSet assert Interval(r, r + nn).is_empty == False assert Interval(x, x).is_empty == False assert Interval(1, oo).is_empty == False assert Interval(-oo, oo).is_empty == False assert Interval(-oo, 1).is_empty == False assert Interval(x, y).is_empty == None assert Interval(r, oo).is_empty == False # real implies finite assert Interval(n, 0).is_empty == False assert Interval(n, 0, left_open=True).is_empty == False assert Interval(p, 0).is_empty == True # EmptySet assert Interval(nn, 0).is_empty == None assert Interval(n, p).is_empty == False assert Interval(0, p, left_open=True).is_empty == False assert Interval(0, p, right_open=True).is_empty == False assert Interval(0, nn, left_open=True).is_empty == None assert Interval(0, nn, right_open=True).is_empty == None def test_union(): assert Union(Interval(1, 2), Interval(2, 3)) == Interval(1, 3) assert Union(Interval(1, 2), Interval(2, 3, True)) == Interval(1, 3) assert Union(Interval(1, 3), Interval(2, 4)) == Interval(1, 4) assert Union(Interval(1, 2), Interval(1, 3)) == Interval(1, 3) assert Union(Interval(1, 3), Interval(1, 2)) == Interval(1, 3) assert Union(Interval(1, 3, False, True), Interval(1, 2)) == \ Interval(1, 3, False, True) assert Union(Interval(1, 3), Interval(1, 2, False, True)) == Interval(1, 3) assert Union(Interval(1, 2, True), Interval(1, 3)) == Interval(1, 3) assert Union(Interval(1, 2, True), Interval(1, 3, True)) == \ Interval(1, 3, True) assert Union(Interval(1, 2, True), Interval(1, 3, True, True)) == \ Interval(1, 3, True, True) assert Union(Interval(1, 2, True, True), Interval(1, 3, True)) == \ Interval(1, 3, True) assert Union(Interval(1, 3), Interval(2, 3)) == Interval(1, 3) assert Union(Interval(1, 3, False, True), Interval(2, 3)) == \ Interval(1, 3) assert Union(Interval(1, 2, False, True), Interval(2, 3, True)) != \ Interval(1, 3) assert Union(Interval(1, 2), S.EmptySet) == Interval(1, 2) assert Union(S.EmptySet) == S.EmptySet assert Union(Interval(0, 1), *[FiniteSet(1.0/n) for n in range(1, 10)]) == \ Interval(0, 1) # issue #18241: x = Symbol('x') assert Union(Interval(0, 1), FiniteSet(1, x)) == Union( Interval(0, 1), FiniteSet(x)) assert unchanged(Union, Interval(0, 1), FiniteSet(2, x)) assert Interval(1, 2).union(Interval(2, 3)) == \ Interval(1, 2) + Interval(2, 3) assert Interval(1, 2).union(Interval(2, 3)) == Interval(1, 3) assert Union(Set()) == Set() assert FiniteSet(1) + FiniteSet(2) + FiniteSet(3) == FiniteSet(1, 2, 3) assert FiniteSet('ham') + FiniteSet('eggs') == FiniteSet('ham', 'eggs') assert FiniteSet(1, 2, 3) + S.EmptySet == FiniteSet(1, 2, 3) assert FiniteSet(1, 2, 3) & FiniteSet(2, 3, 4) == FiniteSet(2, 3) assert FiniteSet(1, 2, 3) | FiniteSet(2, 3, 4) == FiniteSet(1, 2, 3, 4) assert FiniteSet(1, 2, 3) & S.EmptySet == S.EmptySet assert FiniteSet(1, 2, 3) | S.EmptySet == FiniteSet(1, 2, 3) x = Symbol("x") y = Symbol("y") z = Symbol("z") assert S.EmptySet | FiniteSet(x, FiniteSet(y, z)) == \ FiniteSet(x, FiniteSet(y, z)) # Test that Intervals and FiniteSets play nicely assert Interval(1, 3) + FiniteSet(2) == Interval(1, 3) assert Interval(1, 3, True, True) + FiniteSet(3) == \ Interval(1, 3, True, False) X = Interval(1, 3) + FiniteSet(5) Y = Interval(1, 2) + FiniteSet(3) XandY = X.intersect(Y) assert 2 in X and 3 in X and 3 in XandY assert XandY.is_subset(X) and XandY.is_subset(Y) raises(TypeError, lambda: Union(1, 2, 3)) assert X.is_iterable is False # issue 7843 assert Union(S.EmptySet, FiniteSet(-sqrt(-I), sqrt(-I))) == \ FiniteSet(-sqrt(-I), sqrt(-I)) assert Union(S.Reals, S.Integers) == S.Reals def test_union_iter(): # Use Range because it is ordered u = Union(Range(3), Range(5), Range(4), evaluate=False) # Round robin assert list(u) == [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4] def test_union_is_empty(): assert (Interval(x, y) + FiniteSet(1)).is_empty == False assert (Interval(x, y) + Interval(-x, y)).is_empty == None def test_difference(): assert Interval(1, 3) - Interval(1, 2) == Interval(2, 3, True) assert Interval(1, 3) - Interval(2, 3) == Interval(1, 2, False, True) assert Interval(1, 3, True) - Interval(2, 3) == Interval(1, 2, True, True) assert Interval(1, 3, True) - Interval(2, 3, True) == \ Interval(1, 2, True, False) assert Interval(0, 2) - FiniteSet(1) == \ Union(Interval(0, 1, False, True), Interval(1, 2, True, False)) # issue #18119 assert S.Reals - FiniteSet(I) == S.Reals assert S.Reals - FiniteSet(-I, I) == S.Reals assert Interval(0, 10) - FiniteSet(-I, I) == Interval(0, 10) assert Interval(0, 10) - FiniteSet(1, I) == Union( Interval.Ropen(0, 1), Interval.Lopen(1, 10)) assert S.Reals - FiniteSet(1, 2 + I, x, y**2) == Complement( Union(Interval.open(-oo, 1), Interval.open(1, oo)), FiniteSet(x, y**2), evaluate=False) assert FiniteSet(1, 2, 3) - FiniteSet(2) == FiniteSet(1, 3) assert FiniteSet('ham', 'eggs') - FiniteSet('eggs') == FiniteSet('ham') assert FiniteSet(1, 2, 3, 4) - Interval(2, 10, True, False) == \ FiniteSet(1, 2) assert FiniteSet(1, 2, 3, 4) - S.EmptySet == FiniteSet(1, 2, 3, 4) assert Union(Interval(0, 2), FiniteSet(2, 3, 4)) - Interval(1, 3) == \ Union(Interval(0, 1, False, True), FiniteSet(4)) assert -1 in S.Reals - S.Naturals def test_Complement(): A = FiniteSet(1, 3, 4) B = FiniteSet(3, 4) C = Interval(1, 3) D = Interval(1, 2) assert Complement(A, B, evaluate=False).is_iterable is True assert Complement(A, C, evaluate=False).is_iterable is True assert Complement(C, D, evaluate=False).is_iterable is None assert FiniteSet(*Complement(A, B, evaluate=False)) == FiniteSet(1) assert FiniteSet(*Complement(A, C, evaluate=False)) == FiniteSet(4) raises(TypeError, lambda: FiniteSet(*Complement(C, A, evaluate=False))) assert Complement(Interval(1, 3), Interval(1, 2)) == Interval(2, 3, True) assert Complement(FiniteSet(1, 3, 4), FiniteSet(3, 4)) == FiniteSet(1) assert Complement(Union(Interval(0, 2), FiniteSet(2, 3, 4)), Interval(1, 3)) == \ Union(Interval(0, 1, False, True), FiniteSet(4)) assert not 3 in Complement(Interval(0, 5), Interval(1, 4), evaluate=False) assert -1 in Complement(S.Reals, S.Naturals, evaluate=False) assert not 1 in Complement(S.Reals, S.Naturals, evaluate=False) assert Complement(S.Integers, S.UniversalSet) == EmptySet assert S.UniversalSet.complement(S.Integers) == EmptySet assert (not 0 in S.Reals.intersect(S.Integers - FiniteSet(0))) assert S.EmptySet - S.Integers == S.EmptySet assert (S.Integers - FiniteSet(0)) - FiniteSet(1) == S.Integers - FiniteSet(0, 1) assert S.Reals - Union(S.Naturals, FiniteSet(pi)) == \ Intersection(S.Reals - S.Naturals, S.Reals - FiniteSet(pi)) # issue 12712 assert Complement(FiniteSet(x, y, 2), Interval(-10, 10)) == \ Complement(FiniteSet(x, y), Interval(-10, 10)) A = FiniteSet(*symbols('a:c')) B = FiniteSet(*symbols('d:f')) assert unchanged(Complement, ProductSet(A, A), B) A2 = ProductSet(A, A) B3 = ProductSet(B, B, B) assert A2 - B3 == A2 assert B3 - A2 == B3 def test_set_operations_nonsets(): '''Tests that e.g. FiniteSet(1) * 2 raises TypeError''' ops = [ lambda a, b: a + b, lambda a, b: a - b, lambda a, b: a * b, lambda a, b: a / b, lambda a, b: a // b, lambda a, b: a | b, lambda a, b: a & b, lambda a, b: a ^ b, # FiniteSet(1) ** 2 gives a ProductSet #lambda a, b: a ** b, ] Sx = FiniteSet(x) Sy = FiniteSet(y) sets = [ {1}, FiniteSet(1), Interval(1, 2), Union(Sx, Interval(1, 2)), Intersection(Sx, Sy), Complement(Sx, Sy), ProductSet(Sx, Sy), S.EmptySet, ] nums = [0, 1, 2, S(0), S(1), S(2)] for si in sets: for ni in nums: for op in ops: raises(TypeError, lambda : op(si, ni)) raises(TypeError, lambda : op(ni, si)) raises(TypeError, lambda: si ** object()) raises(TypeError, lambda: si ** {1}) def test_complement(): assert Complement({1, 2}, {1}) == {2} assert Interval(0, 1).complement(S.Reals) == \ Union(Interval(-oo, 0, True, True), Interval(1, oo, True, True)) assert Interval(0, 1, True, False).complement(S.Reals) == \ Union(Interval(-oo, 0, True, False), Interval(1, oo, True, True)) assert Interval(0, 1, False, True).complement(S.Reals) == \ Union(Interval(-oo, 0, True, True), Interval(1, oo, False, True)) assert Interval(0, 1, True, True).complement(S.Reals) == \ Union(Interval(-oo, 0, True, False), Interval(1, oo, False, True)) assert S.UniversalSet.complement(S.EmptySet) == S.EmptySet assert S.UniversalSet.complement(S.Reals) == S.EmptySet assert S.UniversalSet.complement(S.UniversalSet) == S.EmptySet assert S.EmptySet.complement(S.Reals) == S.Reals assert Union(Interval(0, 1), Interval(2, 3)).complement(S.Reals) == \ Union(Interval(-oo, 0, True, True), Interval(1, 2, True, True), Interval(3, oo, True, True)) assert FiniteSet(0).complement(S.Reals) == \ Union(Interval(-oo, 0, True, True), Interval(0, oo, True, True)) assert (FiniteSet(5) + Interval(S.NegativeInfinity, 0)).complement(S.Reals) == \ Interval(0, 5, True, True) + Interval(5, S.Infinity, True, True) assert FiniteSet(1, 2, 3).complement(S.Reals) == \ Interval(S.NegativeInfinity, 1, True, True) + \ Interval(1, 2, True, True) + Interval(2, 3, True, True) +\ Interval(3, S.Infinity, True, True) assert FiniteSet(x).complement(S.Reals) == Complement(S.Reals, FiniteSet(x)) assert FiniteSet(0, x).complement(S.Reals) == Complement(Interval(-oo, 0, True, True) + Interval(0, oo, True, True) , FiniteSet(x), evaluate=False) square = Interval(0, 1) * Interval(0, 1) notsquare = square.complement(S.Reals*S.Reals) assert all(pt in square for pt in [(0, 0), (.5, .5), (1, 0), (1, 1)]) assert not any( pt in notsquare for pt in [(0, 0), (.5, .5), (1, 0), (1, 1)]) assert not any(pt in square for pt in [(-1, 0), (1.5, .5), (10, 10)]) assert all(pt in notsquare for pt in [(-1, 0), (1.5, .5), (10, 10)]) def test_intersect1(): assert all(S.Integers.intersection(i) is i for i in (S.Naturals, S.Naturals0)) assert all(i.intersection(S.Integers) is i for i in (S.Naturals, S.Naturals0)) s = S.Naturals0 assert S.Naturals.intersection(s) is S.Naturals assert s.intersection(S.Naturals) is S.Naturals x = Symbol('x') assert Interval(0, 2).intersect(Interval(1, 2)) == Interval(1, 2) assert Interval(0, 2).intersect(Interval(1, 2, True)) == \ Interval(1, 2, True) assert Interval(0, 2, True).intersect(Interval(1, 2)) == \ Interval(1, 2, False, False) assert Interval(0, 2, True, True).intersect(Interval(1, 2)) == \ Interval(1, 2, False, True) assert Interval(0, 2).intersect(Union(Interval(0, 1), Interval(2, 3))) == \ Union(Interval(0, 1), Interval(2, 2)) assert FiniteSet(1, 2).intersect(FiniteSet(1, 2, 3)) == FiniteSet(1, 2) assert FiniteSet(1, 2, x).intersect(FiniteSet(x)) == FiniteSet(x) assert FiniteSet('ham', 'eggs').intersect(FiniteSet('ham')) == \ FiniteSet('ham') assert FiniteSet(1, 2, 3, 4, 5).intersect(S.EmptySet) == S.EmptySet assert Interval(0, 5).intersect(FiniteSet(1, 3)) == FiniteSet(1, 3) assert Interval(0, 1, True, True).intersect(FiniteSet(1)) == S.EmptySet assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(1, 2)) == \ Union(Interval(1, 1), Interval(2, 2)) assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(0, 2)) == \ Union(Interval(0, 1), Interval(2, 2)) assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(1, 2, True, True)) == \ S.EmptySet assert Union(Interval(0, 1), Interval(2, 3)).intersect(S.EmptySet) == \ S.EmptySet assert Union(Interval(0, 5), FiniteSet('ham')).intersect(FiniteSet(2, 3, 4, 5, 6)) == \ Intersection(FiniteSet(2, 3, 4, 5, 6), Union(FiniteSet('ham'), Interval(0, 5))) assert Intersection(FiniteSet(1, 2, 3), Interval(2, x), Interval(3, y)) == \ Intersection(FiniteSet(3), Interval(2, x), Interval(3, y), evaluate=False) assert Intersection(FiniteSet(1, 2), Interval(0, 3), Interval(x, y)) == \ Intersection({1, 2}, Interval(x, y), evaluate=False) assert Intersection(FiniteSet(1, 2, 4), Interval(0, 3), Interval(x, y)) == \ Intersection({1, 2}, Interval(x, y), evaluate=False) # XXX: Is the real=True necessary here? # https://github.com/sympy/sympy/issues/17532 m, n = symbols('m, n', real=True) assert Intersection(FiniteSet(m), FiniteSet(m, n), Interval(m, m+1)) == \ FiniteSet(m) # issue 8217 assert Intersection(FiniteSet(x), FiniteSet(y)) == \ Intersection(FiniteSet(x), FiniteSet(y), evaluate=False) assert FiniteSet(x).intersect(S.Reals) == \ Intersection(S.Reals, FiniteSet(x), evaluate=False) # tests for the intersection alias assert Interval(0, 5).intersection(FiniteSet(1, 3)) == FiniteSet(1, 3) assert Interval(0, 1, True, True).intersection(FiniteSet(1)) == S.EmptySet assert Union(Interval(0, 1), Interval(2, 3)).intersection(Interval(1, 2)) == \ Union(Interval(1, 1), Interval(2, 2)) def test_intersection(): # iterable i = Intersection(FiniteSet(1, 2, 3), Interval(2, 5), evaluate=False) assert i.is_iterable assert set(i) == {S(2), S(3)} # challenging intervals x = Symbol('x', real=True) i = Intersection(Interval(0, 3), Interval(x, 6)) assert (5 in i) is False raises(TypeError, lambda: 2 in i) # Singleton special cases assert Intersection(Interval(0, 1), S.EmptySet) == S.EmptySet assert Intersection(Interval(-oo, oo), Interval(-oo, x)) == Interval(-oo, x) # Products line = Interval(0, 5) i = Intersection(line**2, line**3, evaluate=False) assert (2, 2) not in i assert (2, 2, 2) not in i raises(TypeError, lambda: list(i)) a = Intersection(Intersection(S.Integers, S.Naturals, evaluate=False), S.Reals, evaluate=False) assert a._argset == frozenset([Intersection(S.Naturals, S.Integers, evaluate=False), S.Reals]) assert Intersection(S.Complexes, FiniteSet(S.ComplexInfinity)) == S.EmptySet # issue 12178 assert Intersection() == S.UniversalSet # issue 16987 assert Intersection({1}, {1}, {x}) == Intersection({1}, {x}) def test_issue_9623(): n = Symbol('n') a = S.Reals b = Interval(0, oo) c = FiniteSet(n) assert Intersection(a, b, c) == Intersection(b, c) assert Intersection(Interval(1, 2), Interval(3, 4), FiniteSet(n)) == EmptySet def test_is_disjoint(): assert Interval(0, 2).is_disjoint(Interval(1, 2)) == False assert Interval(0, 2).is_disjoint(Interval(3, 4)) == True def test_ProductSet__len__(): A = FiniteSet(1, 2) B = FiniteSet(1, 2, 3) assert ProductSet(A).__len__() == 2 assert ProductSet(A).__len__() is not S(2) assert ProductSet(A, B).__len__() == 6 assert ProductSet(A, B).__len__() is not S(6) def test_ProductSet(): # ProductSet is always a set of Tuples assert ProductSet(S.Reals) == S.Reals ** 1 assert ProductSet(S.Reals, S.Reals) == S.Reals ** 2 assert ProductSet(S.Reals, S.Reals, S.Reals) == S.Reals ** 3 assert ProductSet(S.Reals) != S.Reals assert ProductSet(S.Reals, S.Reals) == S.Reals * S.Reals assert ProductSet(S.Reals, S.Reals, S.Reals) != S.Reals * S.Reals * S.Reals assert ProductSet(S.Reals, S.Reals, S.Reals) == (S.Reals * S.Reals * S.Reals).flatten() assert 1 not in ProductSet(S.Reals) assert (1,) in ProductSet(S.Reals) assert 1 not in ProductSet(S.Reals, S.Reals) assert (1, 2) in ProductSet(S.Reals, S.Reals) assert (1, I) not in ProductSet(S.Reals, S.Reals) assert (1, 2, 3) in ProductSet(S.Reals, S.Reals, S.Reals) assert (1, 2, 3) in S.Reals ** 3 assert (1, 2, 3) not in S.Reals * S.Reals * S.Reals assert ((1, 2), 3) in S.Reals * S.Reals * S.Reals assert (1, (2, 3)) not in S.Reals * S.Reals * S.Reals assert (1, (2, 3)) in S.Reals * (S.Reals * S.Reals) assert ProductSet() == FiniteSet(()) assert ProductSet(S.Reals, S.EmptySet) == S.EmptySet # See GH-17458 for ni in range(5): Rn = ProductSet(*(S.Reals,) * ni) assert (1,) * ni in Rn assert 1 not in Rn assert (S.Reals * S.Reals) * S.Reals != S.Reals * (S.Reals * S.Reals) S1 = S.Reals S2 = S.Integers x1 = pi x2 = 3 assert x1 in S1 assert x2 in S2 assert (x1, x2) in S1 * S2 S3 = S1 * S2 x3 = (x1, x2) assert x3 in S3 assert (x3, x3) in S3 * S3 assert x3 + x3 not in S3 * S3 raises(ValueError, lambda: S.Reals**-1) with warns_deprecated_sympy(): ProductSet(FiniteSet(s) for s in range(2)) raises(TypeError, lambda: ProductSet(None)) S1 = FiniteSet(1, 2) S2 = FiniteSet(3, 4) S3 = ProductSet(S1, S2) assert (S3.as_relational(x, y) == And(S1.as_relational(x), S2.as_relational(y)) == And(Or(Eq(x, 1), Eq(x, 2)), Or(Eq(y, 3), Eq(y, 4)))) raises(ValueError, lambda: S3.as_relational(x)) raises(ValueError, lambda: S3.as_relational(x, 1)) raises(ValueError, lambda: ProductSet(Interval(0, 1)).as_relational(x, y)) Z2 = ProductSet(S.Integers, S.Integers) assert Z2.contains((1, 2)) is S.true assert Z2.contains((1,)) is S.false assert Z2.contains(x) == Contains(x, Z2, evaluate=False) assert Z2.contains(x).subs(x, 1) is S.false assert Z2.contains((x, 1)).subs(x, 2) is S.true assert Z2.contains((x, y)) == Contains((x, y), Z2, evaluate=False) assert unchanged(Contains, (x, y), Z2) assert Contains((1, 2), Z2) is S.true def test_ProductSet_of_single_arg_is_not_arg(): assert unchanged(ProductSet, Interval(0, 1)) assert unchanged(ProductSet, ProductSet(Interval(0, 1))) def test_ProductSet_is_empty(): assert ProductSet(S.Integers, S.Reals).is_empty == False assert ProductSet(Interval(x, 1), S.Reals).is_empty == None def test_interval_subs(): a = Symbol('a', real=True) assert Interval(0, a).subs(a, 2) == Interval(0, 2) assert Interval(a, 0).subs(a, 2) == S.EmptySet def test_interval_to_mpi(): assert Interval(0, 1).to_mpi() == mpi(0, 1) assert Interval(0, 1, True, False).to_mpi() == mpi(0, 1) assert type(Interval(0, 1).to_mpi()) == type(mpi(0, 1)) def test_set_evalf(): assert Interval(S(11)/64, S.Half).evalf() == Interval( Float('0.171875'), Float('0.5')) assert Interval(x, S.Half, right_open=True).evalf() == Interval( x, Float('0.5'), right_open=True) assert Interval(-oo, S.Half).evalf() == Interval(-oo, Float('0.5')) assert FiniteSet(2, x).evalf() == FiniteSet(Float('2.0'), x) def test_measure(): a = Symbol('a', real=True) assert Interval(1, 3).measure == 2 assert Interval(0, a).measure == a assert Interval(1, a).measure == a - 1 assert Union(Interval(1, 2), Interval(3, 4)).measure == 2 assert Union(Interval(1, 2), Interval(3, 4), FiniteSet(5, 6, 7)).measure \ == 2 assert FiniteSet(1, 2, oo, a, -oo, -5).measure == 0 assert S.EmptySet.measure == 0 square = Interval(0, 10) * Interval(0, 10) offsetsquare = Interval(5, 15) * Interval(5, 15) band = Interval(-oo, oo) * Interval(2, 4) assert square.measure == offsetsquare.measure == 100 assert (square + offsetsquare).measure == 175 # there is some overlap assert (square - offsetsquare).measure == 75 assert (square * FiniteSet(1, 2, 3)).measure == 0 assert (square.intersect(band)).measure == 20 assert (square + band).measure is oo assert (band * FiniteSet(1, 2, 3)).measure is nan def test_is_subset(): assert Interval(0, 1).is_subset(Interval(0, 2)) is True assert Interval(0, 3).is_subset(Interval(0, 2)) is False assert Interval(0, 1).is_subset(FiniteSet(0, 1)) is False assert FiniteSet(1, 2).is_subset(FiniteSet(1, 2, 3, 4)) assert FiniteSet(4, 5).is_subset(FiniteSet(1, 2, 3, 4)) is False assert FiniteSet(1).is_subset(Interval(0, 2)) assert FiniteSet(1, 2).is_subset(Interval(0, 2, True, True)) is False assert (Interval(1, 2) + FiniteSet(3)).is_subset( Interval(0, 2, False, True) + FiniteSet(2, 3)) assert Interval(3, 4).is_subset(Union(Interval(0, 1), Interval(2, 5))) is True assert Interval(3, 6).is_subset(Union(Interval(0, 1), Interval(2, 5))) is False assert FiniteSet(1, 2, 3, 4).is_subset(Interval(0, 5)) is True assert S.EmptySet.is_subset(FiniteSet(1, 2, 3)) is True assert Interval(0, 1).is_subset(S.EmptySet) is False assert S.EmptySet.is_subset(S.EmptySet) is True raises(ValueError, lambda: S.EmptySet.is_subset(1)) # tests for the issubset alias assert FiniteSet(1, 2, 3, 4).issubset(Interval(0, 5)) is True assert S.EmptySet.issubset(FiniteSet(1, 2, 3)) is True assert S.Naturals.is_subset(S.Integers) assert S.Naturals0.is_subset(S.Integers) assert FiniteSet(x).is_subset(FiniteSet(y)) is None assert FiniteSet(x).is_subset(FiniteSet(y).subs(y, x)) is True assert FiniteSet(x).is_subset(FiniteSet(y).subs(y, x+1)) is False assert Interval(0, 1).is_subset(Interval(0, 1, left_open=True)) is False assert Interval(-2, 3).is_subset(Union(Interval(-oo, -2), Interval(3, oo))) is False n = Symbol('n', integer=True) assert Range(-3, 4, 1).is_subset(FiniteSet(-10, 10)) is False assert Range(S(10)**100).is_subset(FiniteSet(0, 1, 2)) is False assert Range(6, 0, -2).is_subset(FiniteSet(2, 4, 6)) is True assert Range(1, oo).is_subset(FiniteSet(1, 2)) is False assert Range(-oo, 1).is_subset(FiniteSet(1)) is False assert Range(3).is_subset(FiniteSet(0, 1, n)) is None assert Range(n, n + 2).is_subset(FiniteSet(n, n + 1)) is True assert Range(5).is_subset(Interval(0, 4, right_open=True)) is False #issue 19513 assert imageset(Lambda(n, 1/n), S.Integers).is_subset(S.Reals) is None def test_is_proper_subset(): assert Interval(0, 1).is_proper_subset(Interval(0, 2)) is True assert Interval(0, 3).is_proper_subset(Interval(0, 2)) is False assert S.EmptySet.is_proper_subset(FiniteSet(1, 2, 3)) is True raises(ValueError, lambda: Interval(0, 1).is_proper_subset(0)) def test_is_superset(): assert Interval(0, 1).is_superset(Interval(0, 2)) == False assert Interval(0, 3).is_superset(Interval(0, 2)) assert FiniteSet(1, 2).is_superset(FiniteSet(1, 2, 3, 4)) == False assert FiniteSet(4, 5).is_superset(FiniteSet(1, 2, 3, 4)) == False assert FiniteSet(1).is_superset(Interval(0, 2)) == False assert FiniteSet(1, 2).is_superset(Interval(0, 2, True, True)) == False assert (Interval(1, 2) + FiniteSet(3)).is_superset( Interval(0, 2, False, True) + FiniteSet(2, 3)) == False assert Interval(3, 4).is_superset(Union(Interval(0, 1), Interval(2, 5))) == False assert FiniteSet(1, 2, 3, 4).is_superset(Interval(0, 5)) == False assert S.EmptySet.is_superset(FiniteSet(1, 2, 3)) == False assert Interval(0, 1).is_superset(S.EmptySet) == True assert S.EmptySet.is_superset(S.EmptySet) == True raises(ValueError, lambda: S.EmptySet.is_superset(1)) # tests for the issuperset alias assert Interval(0, 1).issuperset(S.EmptySet) == True assert S.EmptySet.issuperset(S.EmptySet) == True def test_is_proper_superset(): assert Interval(0, 1).is_proper_superset(Interval(0, 2)) is False assert Interval(0, 3).is_proper_superset(Interval(0, 2)) is True assert FiniteSet(1, 2, 3).is_proper_superset(S.EmptySet) is True raises(ValueError, lambda: Interval(0, 1).is_proper_superset(0)) def test_contains(): assert Interval(0, 2).contains(1) is S.true assert Interval(0, 2).contains(3) is S.false assert Interval(0, 2, True, False).contains(0) is S.false assert Interval(0, 2, True, False).contains(2) is S.true assert Interval(0, 2, False, True).contains(0) is S.true assert Interval(0, 2, False, True).contains(2) is S.false assert Interval(0, 2, True, True).contains(0) is S.false assert Interval(0, 2, True, True).contains(2) is S.false assert (Interval(0, 2) in Interval(0, 2)) is False assert FiniteSet(1, 2, 3).contains(2) is S.true assert FiniteSet(1, 2, Symbol('x')).contains(Symbol('x')) is S.true assert FiniteSet(y)._contains(x) is None raises(TypeError, lambda: x in FiniteSet(y)) assert FiniteSet({x, y})._contains({x}) is None assert FiniteSet({x, y}).subs(y, x)._contains({x}) is True assert FiniteSet({x, y}).subs(y, x+1)._contains({x}) is False # issue 8197 from sympy.abc import a, b assert isinstance(FiniteSet(b).contains(-a), Contains) assert isinstance(FiniteSet(b).contains(a), Contains) assert isinstance(FiniteSet(a).contains(1), Contains) raises(TypeError, lambda: 1 in FiniteSet(a)) # issue 8209 rad1 = Pow(Pow(2, Rational(1, 3)) - 1, Rational(1, 3)) rad2 = Pow(Rational(1, 9), Rational(1, 3)) - Pow(Rational(2, 9), Rational(1, 3)) + Pow(Rational(4, 9), Rational(1, 3)) s1 = FiniteSet(rad1) s2 = FiniteSet(rad2) assert s1 - s2 == S.EmptySet items = [1, 2, S.Infinity, S('ham'), -1.1] fset = FiniteSet(*items) assert all(item in fset for item in items) assert all(fset.contains(item) is S.true for item in items) assert Union(Interval(0, 1), Interval(2, 5)).contains(3) is S.true assert Union(Interval(0, 1), Interval(2, 5)).contains(6) is S.false assert Union(Interval(0, 1), FiniteSet(2, 5)).contains(3) is S.false assert S.EmptySet.contains(1) is S.false assert FiniteSet(rootof(x**3 + x - 1, 0)).contains(S.Infinity) is S.false assert rootof(x**5 + x**3 + 1, 0) in S.Reals assert not rootof(x**5 + x**3 + 1, 1) in S.Reals # non-bool results assert Union(Interval(1, 2), Interval(3, 4)).contains(x) == \ Or(And(S.One <= x, x <= 2), And(S(3) <= x, x <= 4)) assert Intersection(Interval(1, x), Interval(2, 3)).contains(y) == \ And(y <= 3, y <= x, S.One <= y, S(2) <= y) assert (S.Complexes).contains(S.ComplexInfinity) == S.false def test_interval_symbolic(): x = Symbol('x') e = Interval(0, 1) assert e.contains(x) == And(S.Zero <= x, x <= 1) raises(TypeError, lambda: x in e) e = Interval(0, 1, True, True) assert e.contains(x) == And(S.Zero < x, x < 1) c = Symbol('c', real=False) assert Interval(x, x + 1).contains(c) == False e = Symbol('e', extended_real=True) assert Interval(-oo, oo).contains(e) == And( S.NegativeInfinity < e, e < S.Infinity) def test_union_contains(): x = Symbol('x') i1 = Interval(0, 1) i2 = Interval(2, 3) i3 = Union(i1, i2) assert i3.as_relational(x) == Or(And(S.Zero <= x, x <= 1), And(S(2) <= x, x <= 3)) raises(TypeError, lambda: x in i3) e = i3.contains(x) assert e == i3.as_relational(x) assert e.subs(x, -0.5) is false assert e.subs(x, 0.5) is true assert e.subs(x, 1.5) is false assert e.subs(x, 2.5) is true assert e.subs(x, 3.5) is false U = Interval(0, 2, True, True) + Interval(10, oo) + FiniteSet(-1, 2, 5, 6) assert all(el not in U for el in [0, 4, -oo]) assert all(el in U for el in [2, 5, 10]) def test_is_number(): assert Interval(0, 1).is_number is False assert Set().is_number is False def test_Interval_is_left_unbounded(): assert Interval(3, 4).is_left_unbounded is False assert Interval(-oo, 3).is_left_unbounded is True assert Interval(Float("-inf"), 3).is_left_unbounded is True def test_Interval_is_right_unbounded(): assert Interval(3, 4).is_right_unbounded is False assert Interval(3, oo).is_right_unbounded is True assert Interval(3, Float("+inf")).is_right_unbounded is True def test_Interval_as_relational(): x = Symbol('x') assert Interval(-1, 2, False, False).as_relational(x) == \ And(Le(-1, x), Le(x, 2)) assert Interval(-1, 2, True, False).as_relational(x) == \ And(Lt(-1, x), Le(x, 2)) assert Interval(-1, 2, False, True).as_relational(x) == \ And(Le(-1, x), Lt(x, 2)) assert Interval(-1, 2, True, True).as_relational(x) == \ And(Lt(-1, x), Lt(x, 2)) assert Interval(-oo, 2, right_open=False).as_relational(x) == And(Lt(-oo, x), Le(x, 2)) assert Interval(-oo, 2, right_open=True).as_relational(x) == And(Lt(-oo, x), Lt(x, 2)) assert Interval(-2, oo, left_open=False).as_relational(x) == And(Le(-2, x), Lt(x, oo)) assert Interval(-2, oo, left_open=True).as_relational(x) == And(Lt(-2, x), Lt(x, oo)) assert Interval(-oo, oo).as_relational(x) == And(Lt(-oo, x), Lt(x, oo)) x = Symbol('x', real=True) y = Symbol('y', real=True) assert Interval(x, y).as_relational(x) == (x <= y) assert Interval(y, x).as_relational(x) == (y <= x) def test_Finite_as_relational(): x = Symbol('x') y = Symbol('y') assert FiniteSet(1, 2).as_relational(x) == Or(Eq(x, 1), Eq(x, 2)) assert FiniteSet(y, -5).as_relational(x) == Or(Eq(x, y), Eq(x, -5)) def test_Union_as_relational(): x = Symbol('x') assert (Interval(0, 1) + FiniteSet(2)).as_relational(x) == \ Or(And(Le(0, x), Le(x, 1)), Eq(x, 2)) assert (Interval(0, 1, True, True) + FiniteSet(1)).as_relational(x) == \ And(Lt(0, x), Le(x, 1)) assert Or(x < 0, x > 0).as_set().as_relational(x) == \ And((x > -oo), (x < oo), Ne(x, 0)) assert (Interval.Ropen(1, 3) + Interval.Lopen(3, 5) ).as_relational(x) == And((x > 1), (x < 5), Ne(x, 3)) def test_Intersection_as_relational(): x = Symbol('x') assert (Intersection(Interval(0, 1), FiniteSet(2), evaluate=False).as_relational(x) == And(And(Le(0, x), Le(x, 1)), Eq(x, 2))) def test_Complement_as_relational(): x = Symbol('x') expr = Complement(Interval(0, 1), FiniteSet(2), evaluate=False) assert expr.as_relational(x) == \ And(Le(0, x), Le(x, 1), Ne(x, 2)) @XFAIL def test_Complement_as_relational_fail(): x = Symbol('x') expr = Complement(Interval(0, 1), FiniteSet(2), evaluate=False) # XXX This example fails because 0 <= x changes to x >= 0 # during the evaluation. assert expr.as_relational(x) == \ (0 <= x) & (x <= 1) & Ne(x, 2) def test_SymmetricDifference_as_relational(): x = Symbol('x') expr = SymmetricDifference(Interval(0, 1), FiniteSet(2), evaluate=False) assert expr.as_relational(x) == Xor(Eq(x, 2), Le(0, x) & Le(x, 1)) def test_EmptySet(): assert S.EmptySet.as_relational(Symbol('x')) is S.false assert S.EmptySet.intersect(S.UniversalSet) == S.EmptySet assert S.EmptySet.boundary == S.EmptySet def test_finite_basic(): x = Symbol('x') A = FiniteSet(1, 2, 3) B = FiniteSet(3, 4, 5) AorB = Union(A, B) AandB = A.intersect(B) assert A.is_subset(AorB) and B.is_subset(AorB) assert AandB.is_subset(A) assert AandB == FiniteSet(3) assert A.inf == 1 and A.sup == 3 assert AorB.inf == 1 and AorB.sup == 5 assert FiniteSet(x, 1, 5).sup == Max(x, 5) assert FiniteSet(x, 1, 5).inf == Min(x, 1) # issue 7335 assert FiniteSet(S.EmptySet) != S.EmptySet assert FiniteSet(FiniteSet(1, 2, 3)) != FiniteSet(1, 2, 3) assert FiniteSet((1, 2, 3)) != FiniteSet(1, 2, 3) # Ensure a variety of types can exist in a FiniteSet assert FiniteSet((1, 2), Float, A, -5, x, 'eggs', x**2, Interval) assert (A > B) is False assert (A >= B) is False assert (A < B) is False assert (A <= B) is False assert AorB > A and AorB > B assert AorB >= A and AorB >= B assert A >= A and A <= A assert A >= AandB and B >= AandB assert A > AandB and B > AandB assert FiniteSet(1.0) == FiniteSet(1) def test_product_basic(): H, T = 'H', 'T' unit_line = Interval(0, 1) d6 = FiniteSet(1, 2, 3, 4, 5, 6) d4 = FiniteSet(1, 2, 3, 4) coin = FiniteSet(H, T) square = unit_line * unit_line assert (0, 0) in square assert 0 not in square assert (H, T) in coin ** 2 assert (.5, .5, .5) in (square * unit_line).flatten() assert ((.5, .5), .5) in square * unit_line assert (H, 3, 3) in (coin * d6 * d6).flatten() assert ((H, 3), 3) in coin * d6 * d6 HH, TT = sympify(H), sympify(T) assert set(coin**2) == {(HH, HH), (HH, TT), (TT, HH), (TT, TT)} assert (d4*d4).is_subset(d6*d6) assert square.complement(Interval(-oo, oo)*Interval(-oo, oo)) == Union( (Interval(-oo, 0, True, True) + Interval(1, oo, True, True))*Interval(-oo, oo), Interval(-oo, oo)*(Interval(-oo, 0, True, True) + Interval(1, oo, True, True))) assert (Interval(-5, 5)**3).is_subset(Interval(-10, 10)**3) assert not (Interval(-10, 10)**3).is_subset(Interval(-5, 5)**3) assert not (Interval(-5, 5)**2).is_subset(Interval(-10, 10)**3) assert (Interval(.2, .5)*FiniteSet(.5)).is_subset(square) # segment in square assert len(coin*coin*coin) == 8 assert len(S.EmptySet*S.EmptySet) == 0 assert len(S.EmptySet*coin) == 0 raises(TypeError, lambda: len(coin*Interval(0, 2))) def test_real(): x = Symbol('x', real=True, finite=True) I = Interval(0, 5) J = Interval(10, 20) A = FiniteSet(1, 2, 30, x, S.Pi) B = FiniteSet(-4, 0) C = FiniteSet(100) D = FiniteSet('Ham', 'Eggs') assert all(s.is_subset(S.Reals) for s in [I, J, A, B, C]) assert not D.is_subset(S.Reals) assert all((a + b).is_subset(S.Reals) for a in [I, J, A, B, C] for b in [I, J, A, B, C]) assert not any((a + D).is_subset(S.Reals) for a in [I, J, A, B, C, D]) assert not (I + A + D).is_subset(S.Reals) def test_supinf(): x = Symbol('x', real=True) y = Symbol('y', real=True) assert (Interval(0, 1) + FiniteSet(2)).sup == 2 assert (Interval(0, 1) + FiniteSet(2)).inf == 0 assert (Interval(0, 1) + FiniteSet(x)).sup == Max(1, x) assert (Interval(0, 1) + FiniteSet(x)).inf == Min(0, x) assert FiniteSet(5, 1, x).sup == Max(5, x) assert FiniteSet(5, 1, x).inf == Min(1, x) assert FiniteSet(5, 1, x, y).sup == Max(5, x, y) assert FiniteSet(5, 1, x, y).inf == Min(1, x, y) assert FiniteSet(5, 1, x, y, S.Infinity, S.NegativeInfinity).sup == \ S.Infinity assert FiniteSet(5, 1, x, y, S.Infinity, S.NegativeInfinity).inf == \ S.NegativeInfinity assert FiniteSet('Ham', 'Eggs').sup == Max('Ham', 'Eggs') def test_universalset(): U = S.UniversalSet x = Symbol('x') assert U.as_relational(x) is S.true assert U.union(Interval(2, 4)) == U assert U.intersect(Interval(2, 4)) == Interval(2, 4) assert U.measure is S.Infinity assert U.boundary == S.EmptySet assert U.contains(0) is S.true def test_Union_of_ProductSets_shares(): line = Interval(0, 2) points = FiniteSet(0, 1, 2) assert Union(line * line, line * points) == line * line def test_Interval_free_symbols(): # issue 6211 assert Interval(0, 1).free_symbols == set() x = Symbol('x', real=True) assert Interval(0, x).free_symbols == {x} def test_image_interval(): x = Symbol('x', real=True) a = Symbol('a', real=True) assert imageset(x, 2*x, Interval(-2, 1)) == Interval(-4, 2) assert imageset(x, 2*x, Interval(-2, 1, True, False)) == \ Interval(-4, 2, True, False) assert imageset(x, x**2, Interval(-2, 1, True, False)) == \ Interval(0, 4, False, True) assert imageset(x, x**2, Interval(-2, 1)) == Interval(0, 4) assert imageset(x, x**2, Interval(-2, 1, True, False)) == \ Interval(0, 4, False, True) assert imageset(x, x**2, Interval(-2, 1, True, True)) == \ Interval(0, 4, False, True) assert imageset(x, (x - 2)**2, Interval(1, 3)) == Interval(0, 1) assert imageset(x, 3*x**4 - 26*x**3 + 78*x**2 - 90*x, Interval(0, 4)) == \ Interval(-35, 0) # Multiple Maxima assert imageset(x, x + 1/x, Interval(-oo, oo)) == Interval(-oo, -2) \ + Interval(2, oo) # Single Infinite discontinuity assert imageset(x, 1/x + 1/(x-1)**2, Interval(0, 2, True, False)) == \ Interval(Rational(3, 2), oo, False) # Multiple Infinite discontinuities # Test for Python lambda assert imageset(lambda x: 2*x, Interval(-2, 1)) == Interval(-4, 2) assert imageset(Lambda(x, a*x), Interval(0, 1)) == \ ImageSet(Lambda(x, a*x), Interval(0, 1)) assert imageset(Lambda(x, sin(cos(x))), Interval(0, 1)) == \ ImageSet(Lambda(x, sin(cos(x))), Interval(0, 1)) def test_image_piecewise(): f = Piecewise((x, x <= -1), (1/x**2, x <= 5), (x**3, True)) f1 = Piecewise((0, x <= 1), (1, x <= 2), (2, True)) assert imageset(x, f, Interval(-5, 5)) == Union(Interval(-5, -1), Interval(Rational(1, 25), oo)) assert imageset(x, f1, Interval(1, 2)) == FiniteSet(0, 1) @XFAIL # See: https://github.com/sympy/sympy/pull/2723#discussion_r8659826 def test_image_Intersection(): x = Symbol('x', real=True) y = Symbol('y', real=True) assert imageset(x, x**2, Interval(-2, 0).intersect(Interval(x, y))) == \ Interval(0, 4).intersect(Interval(Min(x**2, y**2), Max(x**2, y**2))) def test_image_FiniteSet(): x = Symbol('x', real=True) assert imageset(x, 2*x, FiniteSet(1, 2, 3)) == FiniteSet(2, 4, 6) def test_image_Union(): x = Symbol('x', real=True) assert imageset(x, x**2, Interval(-2, 0) + FiniteSet(1, 2, 3)) == \ (Interval(0, 4) + FiniteSet(9)) def test_image_EmptySet(): x = Symbol('x', real=True) assert imageset(x, 2*x, S.EmptySet) == S.EmptySet def test_issue_5724_7680(): assert I not in S.Reals # issue 7680 assert Interval(-oo, oo).contains(I) is S.false def test_boundary(): assert FiniteSet(1).boundary == FiniteSet(1) assert all(Interval(0, 1, left_open, right_open).boundary == FiniteSet(0, 1) for left_open in (true, false) for right_open in (true, false)) def test_boundary_Union(): assert (Interval(0, 1) + Interval(2, 3)).boundary == FiniteSet(0, 1, 2, 3) assert ((Interval(0, 1, False, True) + Interval(1, 2, True, False)).boundary == FiniteSet(0, 1, 2)) assert (Interval(0, 1) + FiniteSet(2)).boundary == FiniteSet(0, 1, 2) assert Union(Interval(0, 10), Interval(5, 15), evaluate=False).boundary \ == FiniteSet(0, 15) assert Union(Interval(0, 10), Interval(0, 1), evaluate=False).boundary \ == FiniteSet(0, 10) assert Union(Interval(0, 10, True, True), Interval(10, 15, True, True), evaluate=False).boundary \ == FiniteSet(0, 10, 15) @XFAIL def test_union_boundary_of_joining_sets(): """ Testing the boundary of unions is a hard problem """ assert Union(Interval(0, 10), Interval(10, 15), evaluate=False).boundary \ == FiniteSet(0, 15) def test_boundary_ProductSet(): open_square = Interval(0, 1, True, True) ** 2 assert open_square.boundary == (FiniteSet(0, 1) * Interval(0, 1) + Interval(0, 1) * FiniteSet(0, 1)) second_square = Interval(1, 2, True, True) * Interval(0, 1, True, True) assert (open_square + second_square).boundary == ( FiniteSet(0, 1) * Interval(0, 1) + FiniteSet(1, 2) * Interval(0, 1) + Interval(0, 1) * FiniteSet(0, 1) + Interval(1, 2) * FiniteSet(0, 1)) def test_boundary_ProductSet_line(): line_in_r2 = Interval(0, 1) * FiniteSet(0) assert line_in_r2.boundary == line_in_r2 def test_is_open(): assert Interval(0, 1, False, False).is_open is False assert Interval(0, 1, True, False).is_open is False assert Interval(0, 1, True, True).is_open is True assert FiniteSet(1, 2, 3).is_open is False def test_is_closed(): assert Interval(0, 1, False, False).is_closed is True assert Interval(0, 1, True, False).is_closed is False assert FiniteSet(1, 2, 3).is_closed is True def test_closure(): assert Interval(0, 1, False, True).closure == Interval(0, 1, False, False) def test_interior(): assert Interval(0, 1, False, True).interior == Interval(0, 1, True, True) def test_issue_7841(): raises(TypeError, lambda: x in S.Reals) def test_Eq(): assert Eq(Interval(0, 1), Interval(0, 1)) assert Eq(Interval(0, 1), Interval(0, 2)) == False s1 = FiniteSet(0, 1) s2 = FiniteSet(1, 2) assert Eq(s1, s1) assert Eq(s1, s2) == False assert Eq(s1*s2, s1*s2) assert Eq(s1*s2, s2*s1) == False assert unchanged(Eq, FiniteSet({x, y}), FiniteSet({x})) assert Eq(FiniteSet({x, y}).subs(y, x), FiniteSet({x})) is S.true assert Eq(FiniteSet({x, y}), FiniteSet({x})).subs(y, x) is S.true assert Eq(FiniteSet({x, y}).subs(y, x+1), FiniteSet({x})) is S.false assert Eq(FiniteSet({x, y}), FiniteSet({x})).subs(y, x+1) is S.false assert Eq(ProductSet({1}, {2}), Interval(1, 2)) is S.false assert Eq(ProductSet({1}), ProductSet({1}, {2})) is S.false assert Eq(FiniteSet(()), FiniteSet(1)) is S.false assert Eq(ProductSet(), FiniteSet(1)) is S.false i1 = Interval(0, 1) i2 = Interval(x, y) assert unchanged(Eq, ProductSet(i1, i1), ProductSet(i2, i2)) def test_SymmetricDifference(): A = FiniteSet(0, 1, 2, 3, 4, 5) B = FiniteSet(2, 4, 6, 8, 10) C = Interval(8, 10) assert SymmetricDifference(A, B, evaluate=False).is_iterable is True assert SymmetricDifference(A, C, evaluate=False).is_iterable is None assert FiniteSet(*SymmetricDifference(A, B, evaluate=False)) == \ FiniteSet(0, 1, 3, 5, 6, 8, 10) raises(TypeError, lambda: FiniteSet(*SymmetricDifference(A, C, evaluate=False))) assert SymmetricDifference(FiniteSet(0, 1, 2, 3, 4, 5), \ FiniteSet(2, 4, 6, 8, 10)) == FiniteSet(0, 1, 3, 5, 6, 8, 10) assert SymmetricDifference(FiniteSet(2, 3, 4), FiniteSet(2, 3, 4 ,5)) \ == FiniteSet(5) assert FiniteSet(1, 2, 3, 4, 5) ^ FiniteSet(1, 2, 5, 6) == \ FiniteSet(3, 4, 6) assert Set(S(1), S(2), S(3)) ^ Set(S(2), S(3), S(4)) == Union(Set(S(1), S(2), S(3)) - Set(S(2), S(3), S(4)), \ Set(S(2), S(3), S(4)) - Set(S(1), S(2), S(3))) assert Interval(0, 4) ^ Interval(2, 5) == Union(Interval(0, 4) - \ Interval(2, 5), Interval(2, 5) - Interval(0, 4)) def test_issue_9536(): from sympy.functions.elementary.exponential import log a = Symbol('a', real=True) assert FiniteSet(log(a)).intersect(S.Reals) == Intersection(S.Reals, FiniteSet(log(a))) def test_issue_9637(): n = Symbol('n') a = FiniteSet(n) b = FiniteSet(2, n) assert Complement(S.Reals, a) == Complement(S.Reals, a, evaluate=False) assert Complement(Interval(1, 3), a) == Complement(Interval(1, 3), a, evaluate=False) assert Complement(Interval(1, 3), b) == \ Complement(Union(Interval(1, 2, False, True), Interval(2, 3, True, False)), a) assert Complement(a, S.Reals) == Complement(a, S.Reals, evaluate=False) assert Complement(a, Interval(1, 3)) == Complement(a, Interval(1, 3), evaluate=False) def test_issue_9808(): # See https://github.com/sympy/sympy/issues/16342 assert Complement(FiniteSet(y), FiniteSet(1)) == Complement(FiniteSet(y), FiniteSet(1), evaluate=False) assert Complement(FiniteSet(1, 2, x), FiniteSet(x, y, 2, 3)) == \ Complement(FiniteSet(1), FiniteSet(y), evaluate=False) def test_issue_9956(): assert Union(Interval(-oo, oo), FiniteSet(1)) == Interval(-oo, oo) assert Interval(-oo, oo).contains(1) is S.true def test_issue_Symbol_inter(): i = Interval(0, oo) r = S.Reals mat = Matrix([0, 0, 0]) assert Intersection(r, i, FiniteSet(m), FiniteSet(m, n)) == \ Intersection(i, FiniteSet(m)) assert Intersection(FiniteSet(1, m, n), FiniteSet(m, n, 2), i) == \ Intersection(i, FiniteSet(m, n)) assert Intersection(FiniteSet(m, n, x), FiniteSet(m, z), r) == \ Intersection(Intersection({m, z}, {m, n, x}), r) assert Intersection(FiniteSet(m, n, 3), FiniteSet(m, n, x), r) == \ Intersection(FiniteSet(3, m, n), FiniteSet(m, n, x), r, evaluate=False) assert Intersection(FiniteSet(m, n, 3), FiniteSet(m, n, 2, 3), r) == \ Intersection(FiniteSet(3, m, n), r) assert Intersection(r, FiniteSet(mat, 2, n), FiniteSet(0, mat, n)) == \ Intersection(r, FiniteSet(n)) assert Intersection(FiniteSet(sin(x), cos(x)), FiniteSet(sin(x), cos(x), 1), r) == \ Intersection(r, FiniteSet(sin(x), cos(x))) assert Intersection(FiniteSet(x**2, 1, sin(x)), FiniteSet(x**2, 2, sin(x)), r) == \ Intersection(r, FiniteSet(x**2, sin(x))) def test_issue_11827(): assert S.Naturals0**4 def test_issue_10113(): f = x**2/(x**2 - 4) assert imageset(x, f, S.Reals) == Union(Interval(-oo, 0), Interval(1, oo, True, True)) assert imageset(x, f, Interval(-2, 2)) == Interval(-oo, 0) assert imageset(x, f, Interval(-2, 3)) == Union(Interval(-oo, 0), Interval(Rational(9, 5), oo)) def test_issue_10248(): raises( TypeError, lambda: list(Intersection(S.Reals, FiniteSet(x))) ) A = Symbol('A', real=True) assert list(Intersection(S.Reals, FiniteSet(A))) == [A] def test_issue_9447(): a = Interval(0, 1) + Interval(2, 3) assert Complement(S.UniversalSet, a) == Complement( S.UniversalSet, Union(Interval(0, 1), Interval(2, 3)), evaluate=False) assert Complement(S.Naturals, a) == Complement( S.Naturals, Union(Interval(0, 1), Interval(2, 3)), evaluate=False) def test_issue_10337(): assert (FiniteSet(2) == 3) is False assert (FiniteSet(2) != 3) is True raises(TypeError, lambda: FiniteSet(2) < 3) raises(TypeError, lambda: FiniteSet(2) <= 3) raises(TypeError, lambda: FiniteSet(2) > 3) raises(TypeError, lambda: FiniteSet(2) >= 3) def test_issue_10326(): bad = [ EmptySet, FiniteSet(1), Interval(1, 2), S.ComplexInfinity, S.ImaginaryUnit, S.Infinity, S.NaN, S.NegativeInfinity, ] interval = Interval(0, 5) for i in bad: assert i not in interval x = Symbol('x', real=True) nr = Symbol('nr', extended_real=False) assert x + 1 in Interval(x, x + 4) assert nr not in Interval(x, x + 4) assert Interval(1, 2) in FiniteSet(Interval(0, 5), Interval(1, 2)) assert Interval(-oo, oo).contains(oo) is S.false assert Interval(-oo, oo).contains(-oo) is S.false def test_issue_2799(): U = S.UniversalSet a = Symbol('a', real=True) inf_interval = Interval(a, oo) R = S.Reals assert U + inf_interval == inf_interval + U assert U + R == R + U assert R + inf_interval == inf_interval + R def test_issue_9706(): assert Interval(-oo, 0).closure == Interval(-oo, 0, True, False) assert Interval(0, oo).closure == Interval(0, oo, False, True) assert Interval(-oo, oo).closure == Interval(-oo, oo) def test_issue_8257(): reals_plus_infinity = Union(Interval(-oo, oo), FiniteSet(oo)) reals_plus_negativeinfinity = Union(Interval(-oo, oo), FiniteSet(-oo)) assert Interval(-oo, oo) + FiniteSet(oo) == reals_plus_infinity assert FiniteSet(oo) + Interval(-oo, oo) == reals_plus_infinity assert Interval(-oo, oo) + FiniteSet(-oo) == reals_plus_negativeinfinity assert FiniteSet(-oo) + Interval(-oo, oo) == reals_plus_negativeinfinity def test_issue_10931(): assert S.Integers - S.Integers == EmptySet assert S.Integers - S.Reals == EmptySet def test_issue_11174(): soln = Intersection(Interval(-oo, oo), FiniteSet(-x), evaluate=False) assert Intersection(FiniteSet(-x), S.Reals) == soln soln = Intersection(S.Reals, FiniteSet(x), evaluate=False) assert Intersection(FiniteSet(x), S.Reals) == soln def test_issue_18505(): assert ImageSet(Lambda(n, sqrt(pi*n/2 - 1 + pi/2)), S.Integers).contains(0) == \ Contains(0, ImageSet(Lambda(n, sqrt(pi*n/2 - 1 + pi/2)), S.Integers)) def test_finite_set_intersection(): # The following should not produce recursion errors # Note: some of these are not completely correct. See # https://github.com/sympy/sympy/issues/16342. assert Intersection(FiniteSet(-oo, x), FiniteSet(x)) == FiniteSet(x) assert Intersection._handle_finite_sets([FiniteSet(-oo, x), FiniteSet(0, x)]) == FiniteSet(x) assert Intersection._handle_finite_sets([FiniteSet(-oo, x), FiniteSet(x)]) == FiniteSet(x) assert Intersection._handle_finite_sets([FiniteSet(2, 3, x, y), FiniteSet(1, 2, x)]) == \ Intersection._handle_finite_sets([FiniteSet(1, 2, x), FiniteSet(2, 3, x, y)]) == \ Intersection(FiniteSet(1, 2, x), FiniteSet(2, 3, x, y)) == \ Intersection(FiniteSet(1, 2, x), FiniteSet(2, x, y)) assert FiniteSet(1+x-y) & FiniteSet(1) == \ FiniteSet(1) & FiniteSet(1+x-y) == \ Intersection(FiniteSet(1+x-y), FiniteSet(1), evaluate=False) assert FiniteSet(1) & FiniteSet(x) == FiniteSet(x) & FiniteSet(1) == \ Intersection(FiniteSet(1), FiniteSet(x), evaluate=False) assert FiniteSet({x}) & FiniteSet({x, y}) == \ Intersection(FiniteSet({x}), FiniteSet({x, y}), evaluate=False) def test_union_intersection_constructor(): # The actual exception does not matter here, so long as these fail sets = [FiniteSet(1), FiniteSet(2)] raises(Exception, lambda: Union(sets)) raises(Exception, lambda: Intersection(sets)) raises(Exception, lambda: Union(tuple(sets))) raises(Exception, lambda: Intersection(tuple(sets))) raises(Exception, lambda: Union(i for i in sets)) raises(Exception, lambda: Intersection(i for i in sets)) # Python sets are treated the same as FiniteSet # The union of a single set (of sets) is the set (of sets) itself assert Union(set(sets)) == FiniteSet(*sets) assert Intersection(set(sets)) == FiniteSet(*sets) assert Union({1}, {2}) == FiniteSet(1, 2) assert Intersection({1, 2}, {2, 3}) == FiniteSet(2) def test_Union_contains(): assert zoo not in Union( Interval.open(-oo, 0), Interval.open(0, oo)) @XFAIL def test_issue_16878b(): # in intersection_sets for (ImageSet, Set) there is no code # that handles the base_set of S.Reals like there is # for Integers assert imageset(x, (x, x), S.Reals).is_subset(S.Reals**2) is True def test_DisjointUnion(): assert DisjointUnion(FiniteSet(1, 2, 3), FiniteSet(1, 2, 3), FiniteSet(1, 2, 3)).rewrite(Union) == (FiniteSet(1, 2, 3) * FiniteSet(0, 1, 2)) assert DisjointUnion(Interval(1, 3), Interval(2, 4)).rewrite(Union) == Union(Interval(1, 3) * FiniteSet(0), Interval(2, 4) * FiniteSet(1)) assert DisjointUnion(Interval(0, 5), Interval(0, 5)).rewrite(Union) == Union(Interval(0, 5) * FiniteSet(0), Interval(0, 5) * FiniteSet(1)) assert DisjointUnion(Interval(-1, 2), S.EmptySet, S.EmptySet).rewrite(Union) == Interval(-1, 2) * FiniteSet(0) assert DisjointUnion(Interval(-1, 2)).rewrite(Union) == Interval(-1, 2) * FiniteSet(0) assert DisjointUnion(S.EmptySet, Interval(-1, 2), S.EmptySet).rewrite(Union) == Interval(-1, 2) * FiniteSet(1) assert DisjointUnion(Interval(-oo, oo)).rewrite(Union) == Interval(-oo, oo) * FiniteSet(0) assert DisjointUnion(S.EmptySet).rewrite(Union) == S.EmptySet assert DisjointUnion().rewrite(Union) == S.EmptySet raises(TypeError, lambda: DisjointUnion(Symbol('n'))) x = Symbol("x") y = Symbol("y") z = Symbol("z") assert DisjointUnion(FiniteSet(x), FiniteSet(y, z)).rewrite(Union) == (FiniteSet(x) * FiniteSet(0)) + (FiniteSet(y, z) * FiniteSet(1)) def test_DisjointUnion_is_empty(): assert DisjointUnion(S.EmptySet).is_empty is True assert DisjointUnion(S.EmptySet, S.EmptySet).is_empty is True assert DisjointUnion(S.EmptySet, FiniteSet(1, 2, 3)).is_empty is False def test_DisjointUnion_is_iterable(): assert DisjointUnion(S.Integers, S.Naturals, S.Rationals).is_iterable is True assert DisjointUnion(S.EmptySet, S.Reals).is_iterable is False assert DisjointUnion(FiniteSet(1, 2, 3), S.EmptySet, FiniteSet(x, y)).is_iterable is True assert DisjointUnion(S.EmptySet, S.EmptySet).is_iterable is False def test_DisjointUnion_contains(): assert (0, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (0, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (0, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (1, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (1, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (1, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (2, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (2, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (2, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (0, 1, 2) not in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (0, 0.5) not in DisjointUnion(FiniteSet(0.5)) assert (0, 5) not in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2)) assert (x, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y)) assert (y, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y)) assert (z, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y)) assert (y, 2) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y)) assert (0.5, 0) in DisjointUnion(Interval(0, 1), Interval(0, 2)) assert (0.5, 1) in DisjointUnion(Interval(0, 1), Interval(0, 2)) assert (1.5, 0) not in DisjointUnion(Interval(0, 1), Interval(0, 2)) assert (1.5, 1) in DisjointUnion(Interval(0, 1), Interval(0, 2)) def test_DisjointUnion_iter(): D = DisjointUnion(FiniteSet(3, 5, 7, 9), FiniteSet(x, y, z)) it = iter(D) L1 = [(x, 1), (y, 1), (z, 1)] L2 = [(3, 0), (5, 0), (7, 0), (9, 0)] nxt = next(it) assert nxt in L2 L2.remove(nxt) nxt = next(it) assert nxt in L1 L1.remove(nxt) nxt = next(it) assert nxt in L2 L2.remove(nxt) nxt = next(it) assert nxt in L1 L1.remove(nxt) nxt = next(it) assert nxt in L2 L2.remove(nxt) nxt = next(it) assert nxt in L1 L1.remove(nxt) nxt = next(it) assert nxt in L2 L2.remove(nxt) raises(StopIteration, lambda: next(it)) raises(ValueError, lambda: iter(DisjointUnion(Interval(0, 1), S.EmptySet))) def test_DisjointUnion_len(): assert len(DisjointUnion(FiniteSet(3, 5, 7, 9), FiniteSet(x, y, z))) == 7 assert len(DisjointUnion(S.EmptySet, S.EmptySet, FiniteSet(x, y, z), S.EmptySet)) == 3 raises(ValueError, lambda: len(DisjointUnion(Interval(0, 1), S.EmptySet))) def test_issue_20089(): B = FiniteSet(FiniteSet(1, 2), FiniteSet(1)) assert not 1 in B assert not 1.0 in B assert not Eq(1, FiniteSet(1, 2)) assert FiniteSet(1) in B A = FiniteSet(1, 2) assert A in B assert B.issubset(B) assert not A.issubset(B) assert 1 in A C = FiniteSet(FiniteSet(1, 2), FiniteSet(1), 1, 2) assert A.issubset(C) assert B.issubset(C) def test_issue_19378(): a = FiniteSet(1, 2) b = ProductSet(a, a) c = FiniteSet((1, 1), (1, 2), (2, 1), (2, 2)) assert b.is_subset(c) is True d = FiniteSet(1) assert b.is_subset(d) is False assert Eq(c, b).simplify() is S.true assert Eq(a, c).simplify() is S.false assert Eq({1}, {x}).simplify() == Eq({1}, {x}) def test_intersection_symbolic(): n = Symbol('n') # These should not throw an error assert isinstance(Intersection(Range(n), Range(100)), Intersection) assert isinstance(Intersection(Range(n), Interval(1, 100)), Intersection) assert isinstance(Intersection(Range(100), Interval(1, n)), Intersection) @XFAIL def test_intersection_symbolic_failing(): n = Symbol('n', integer=True, positive=True) assert Intersection(Range(10, n), Range(4, 500, 5)) == Intersection( Range(14, n), Range(14, 500, 5)) assert Intersection(Interval(10, n), Range(4, 500, 5)) == Intersection( Interval(14, n), Range(14, 500, 5)) def test_issue_20379(): #https://github.com/sympy/sympy/issues/20379 x = pi - 3.14159265358979 assert FiniteSet(x).evalf(2) == FiniteSet(Float('3.23108914886517e-15', 2)) def test_finiteset_simplify(): S = FiniteSet(1, cos(1)**2 + sin(1)**2) assert S.simplify() == {1}
3ba895161d82449d592d35af518f29ac512180c626b96ee2aa34a39730e35c7d
from sympy.core.numbers import (I, pi) from sympy.core.relational import Eq from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import re from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.trigonometric import (cos, sin, tan) from sympy.logic.boolalg import (And, Or) from sympy.plotting.plot_implicit import plot_implicit from sympy.plotting.plot import unset_show from tempfile import NamedTemporaryFile, mkdtemp from sympy.testing.pytest import skip, warns from sympy.external import import_module from sympy.testing.tmpfiles import TmpFileManager import os #Set plots not to show unset_show() def tmp_file(dir=None, name=''): return NamedTemporaryFile( suffix='.png', dir=dir, delete=False).name def plot_and_save(expr, *args, name='', dir=None, **kwargs): p = plot_implicit(expr, *args, **kwargs) p.save(tmp_file(dir=dir, name=name)) # Close the plot to avoid a warning from matplotlib p._backend.close() def plot_implicit_tests(name): temp_dir = mkdtemp() TmpFileManager.tmp_folder(temp_dir) x = Symbol('x') y = Symbol('y') #implicit plot tests plot_and_save(Eq(y, cos(x)), (x, -5, 5), (y, -2, 2), name=name, dir=temp_dir) plot_and_save(Eq(y**2, x**3 - x), (x, -5, 5), (y, -4, 4), name=name, dir=temp_dir) plot_and_save(y > 1 / x, (x, -5, 5), (y, -2, 2), name=name, dir=temp_dir) plot_and_save(y < 1 / tan(x), (x, -5, 5), (y, -2, 2), name=name, dir=temp_dir) plot_and_save(y >= 2 * sin(x) * cos(x), (x, -5, 5), (y, -2, 2), name=name, dir=temp_dir) plot_and_save(y <= x**2, (x, -3, 3), (y, -1, 5), name=name, dir=temp_dir) #Test all input args for plot_implicit plot_and_save(Eq(y**2, x**3 - x), dir=temp_dir) plot_and_save(Eq(y**2, x**3 - x), adaptive=False, dir=temp_dir) plot_and_save(Eq(y**2, x**3 - x), adaptive=False, points=500, dir=temp_dir) plot_and_save(y > x, (x, -5, 5), dir=temp_dir) plot_and_save(And(y > exp(x), y > x + 2), dir=temp_dir) plot_and_save(Or(y > x, y > -x), dir=temp_dir) plot_and_save(x**2 - 1, (x, -5, 5), dir=temp_dir) plot_and_save(x**2 - 1, dir=temp_dir) plot_and_save(y > x, depth=-5, dir=temp_dir) plot_and_save(y > x, depth=5, dir=temp_dir) plot_and_save(y > cos(x), adaptive=False, dir=temp_dir) plot_and_save(y < cos(x), adaptive=False, dir=temp_dir) plot_and_save(And(y > cos(x), Or(y > x, Eq(y, x))), dir=temp_dir) plot_and_save(y - cos(pi / x), dir=temp_dir) #Test plots which cannot be rendered using the adaptive algorithm with warns(UserWarning, match="Adaptive meshing could not be applied"): plot_and_save(Eq(y, re(cos(x) + I*sin(x))), name=name, dir=temp_dir) plot_and_save(x**2 - 1, title='An implicit plot', dir=temp_dir) def test_line_color(): x, y = symbols('x, y') p = plot_implicit(x**2 + y**2 - 1, line_color="green", show=False) assert p._series[0].line_color == "green" p = plot_implicit(x**2 + y**2 - 1, line_color='r', show=False) assert p._series[0].line_color == "r" def test_matplotlib(): matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) if matplotlib: try: plot_implicit_tests('test') test_line_color() finally: TmpFileManager.cleanup() else: skip("Matplotlib not the default backend") def test_region_and(): matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) if not matplotlib: skip("Matplotlib not the default backend") from matplotlib.testing.compare import compare_images test_directory = os.path.dirname(os.path.abspath(__file__)) try: temp_dir = mkdtemp() TmpFileManager.tmp_folder(temp_dir) x, y = symbols('x y') r1 = (x - 1)**2 + y**2 < 2 r2 = (x + 1)**2 + y**2 < 2 test_filename = tmp_file(dir=temp_dir, name="test_region_and") cmp_filename = os.path.join(test_directory, "test_region_and.png") p = plot_implicit(r1 & r2, x, y) p.save(test_filename) compare_images(cmp_filename, test_filename, 0.005) test_filename = tmp_file(dir=temp_dir, name="test_region_or") cmp_filename = os.path.join(test_directory, "test_region_or.png") p = plot_implicit(r1 | r2, x, y) p.save(test_filename) compare_images(cmp_filename, test_filename, 0.005) test_filename = tmp_file(dir=temp_dir, name="test_region_not") cmp_filename = os.path.join(test_directory, "test_region_not.png") p = plot_implicit(~r1, x, y) p.save(test_filename) compare_images(cmp_filename, test_filename, 0.005) test_filename = tmp_file(dir=temp_dir, name="test_region_xor") cmp_filename = os.path.join(test_directory, "test_region_xor.png") p = plot_implicit(r1 ^ r2, x, y) p.save(test_filename) compare_images(cmp_filename, test_filename, 0.005) finally: TmpFileManager.cleanup()
90600de17de28868e5dd4bf841b0c6583d80878a315454172f7e344b0e5a7546
import os from tempfile import TemporaryDirectory from sympy.concrete.summations import Sum from sympy.core.numbers import (I, oo, pi) from sympy.core.relational import Ne from sympy.core.symbol import Symbol from sympy.functions.elementary.exponential import (LambertW, exp, exp_polar, log) from sympy.functions.elementary.miscellaneous import (real_root, sqrt) from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.hyper import meijerg from sympy.integrals.integrals import Integral from sympy.logic.boolalg import And from sympy.core.singleton import S from sympy.core.sympify import sympify from sympy.external import import_module from sympy.plotting.plot import ( Plot, plot, plot_parametric, plot3d_parametric_line, plot3d, plot3d_parametric_surface) from sympy.plotting.plot import ( unset_show, plot_contour, PlotGrid, DefaultBackend, MatplotlibBackend, TextBackend, BaseBackend) from sympy.testing.pytest import skip, raises, warns from sympy.utilities import lambdify as lambdify_ unset_show() matplotlib = import_module( 'matplotlib', min_module_version='1.1.0', catch=(RuntimeError,)) class DummyBackendNotOk(BaseBackend): """ Used to verify if users can create their own backends. This backend is meant to raise NotImplementedError for methods `show`, `save`, `close`. """ pass class DummyBackendOk(BaseBackend): """ Used to verify if users can create their own backends. This backend is meant to pass all tests. """ def show(self): pass def save(self): pass def close(self): pass def test_plot_and_save_1(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') with TemporaryDirectory(prefix='sympy_') as tmpdir: ### # Examples from the 'introduction' notebook ### p = plot(x, legend=True, label='f1') p = plot(x*sin(x), x*cos(x), label='f2') p.extend(p) p[0].line_color = lambda a: a p[1].line_color = 'b' p.title = 'Big title' p.xlabel = 'the x axis' p[1].label = 'straight line' p.legend = True p.aspect_ratio = (1, 1) p.xlim = (-15, 20) filename = 'test_basic_options_and_colors.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p.extend(plot(x + 1)) p.append(plot(x + 3, x**2)[1]) filename = 'test_plot_extend_append.png' p.save(os.path.join(tmpdir, filename)) p[2] = plot(x**2, (x, -2, 3)) filename = 'test_plot_setitem.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(sin(x), (x, -2*pi, 4*pi)) filename = 'test_line_explicit.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(sin(x)) filename = 'test_line_default_range.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot((x**2, (x, -5, 5)), (x**3, (x, -3, 3))) filename = 'test_line_multiple_range.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() raises(ValueError, lambda: plot(x, y)) #Piecewise plots p = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1)) filename = 'test_plot_piecewise.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(Piecewise((x, x < 1), (x**2, True)), (x, -3, 3)) filename = 'test_plot_piecewise_2.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # test issue 7471 p1 = plot(x) p2 = plot(3) p1.extend(p2) filename = 'test_horizontal_line.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # test issue 10925 f = Piecewise((-1, x < -1), (x, And(-1 <= x, x < 0)), \ (x**2, And(0 <= x, x < 1)), (x**3, x >= 1)) p = plot(f, (x, -3, 3)) filename = 'test_plot_piecewise_3.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_plot_and_save_2(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') z = Symbol('z') with TemporaryDirectory(prefix='sympy_') as tmpdir: #parametric 2d plots. #Single plot with default range. p = plot_parametric(sin(x), cos(x)) filename = 'test_parametric.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #Single plot with range. p = plot_parametric( sin(x), cos(x), (x, -5, 5), legend=True, label='parametric_plot') filename = 'test_parametric_range.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #Multiple plots with same range. p = plot_parametric((sin(x), cos(x)), (x, sin(x))) filename = 'test_parametric_multiple.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #Multiple plots with different ranges. p = plot_parametric( (sin(x), cos(x), (x, -3, 3)), (x, sin(x), (x, -5, 5))) filename = 'test_parametric_multiple_ranges.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #depth of recursion specified. p = plot_parametric(x, sin(x), depth=13) filename = 'test_recursion_depth.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #No adaptive sampling. p = plot_parametric(cos(x), sin(x), adaptive=False, nb_of_points=500) filename = 'test_adaptive.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() #3d parametric plots p = plot3d_parametric_line( sin(x), cos(x), x, legend=True, label='3d_parametric_plot') filename = 'test_3d_line.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot3d_parametric_line( (sin(x), cos(x), x, (x, -5, 5)), (cos(x), sin(x), x, (x, -3, 3))) filename = 'test_3d_line_multiple.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot3d_parametric_line(sin(x), cos(x), x, nb_of_points=30) filename = 'test_3d_line_points.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # 3d surface single plot. p = plot3d(x * y) filename = 'test_surface.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Multiple 3D plots with same range. p = plot3d(-x * y, x * y, (x, -5, 5)) filename = 'test_surface_multiple.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Multiple 3D plots with different ranges. p = plot3d( (x * y, (x, -3, 3), (y, -3, 3)), (-x * y, (x, -3, 3), (y, -3, 3))) filename = 'test_surface_multiple_ranges.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Single Parametric 3D plot p = plot3d_parametric_surface(sin(x + y), cos(x - y), x - y) filename = 'test_parametric_surface.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Multiple Parametric 3D plots. p = plot3d_parametric_surface( (x*sin(z), x*cos(z), z, (x, -5, 5), (z, -5, 5)), (sin(x + y), cos(x - y), x - y, (x, -5, 5), (y, -5, 5))) filename = 'test_parametric_surface.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Single Contour plot. p = plot_contour(sin(x)*sin(y), (x, -5, 5), (y, -5, 5)) filename = 'test_contour_plot.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Multiple Contour plots with same range. p = plot_contour(x**2 + y**2, x**3 + y**3, (x, -5, 5), (y, -5, 5)) filename = 'test_contour_plot.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # Multiple Contour plots with different range. p = plot_contour( (x**2 + y**2, (x, -5, 5), (y, -5, 5)), (x**3 + y**3, (x, -3, 3), (y, -3, 3))) filename = 'test_contour_plot.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_plot_and_save_3(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') z = Symbol('z') with TemporaryDirectory(prefix='sympy_') as tmpdir: ### # Examples from the 'colors' notebook ### p = plot(sin(x)) p[0].line_color = lambda a: a filename = 'test_colors_line_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].line_color = lambda a, b: b filename = 'test_colors_line_arity2.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(x*sin(x), x*cos(x), (x, 0, 10)) p[0].line_color = lambda a: a filename = 'test_colors_param_line_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].line_color = lambda a, b: a filename = 'test_colors_param_line_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].line_color = lambda a, b: b filename = 'test_colors_param_line_arity2b.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot3d_parametric_line(sin(x) + 0.1*sin(x)*cos(7*x), cos(x) + 0.1*cos(x)*cos(7*x), 0.1*sin(7*x), (x, 0, 2*pi)) p[0].line_color = lambdify_(x, sin(4*x)) filename = 'test_colors_3d_line_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].line_color = lambda a, b: b filename = 'test_colors_3d_line_arity2.png' p.save(os.path.join(tmpdir, filename)) p[0].line_color = lambda a, b, c: c filename = 'test_colors_3d_line_arity3.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot3d(sin(x)*y, (x, 0, 6*pi), (y, -5, 5)) p[0].surface_color = lambda a: a filename = 'test_colors_surface_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].surface_color = lambda a, b: b filename = 'test_colors_surface_arity2.png' p.save(os.path.join(tmpdir, filename)) p[0].surface_color = lambda a, b, c: c filename = 'test_colors_surface_arity3a.png' p.save(os.path.join(tmpdir, filename)) p[0].surface_color = lambdify_((x, y, z), sqrt((x - 3*pi)**2 + y**2)) filename = 'test_colors_surface_arity3b.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot3d_parametric_surface(x * cos(4 * y), x * sin(4 * y), y, (x, -1, 1), (y, -1, 1)) p[0].surface_color = lambda a: a filename = 'test_colors_param_surf_arity1.png' p.save(os.path.join(tmpdir, filename)) p[0].surface_color = lambda a, b: a*b filename = 'test_colors_param_surf_arity2.png' p.save(os.path.join(tmpdir, filename)) p[0].surface_color = lambdify_((x, y, z), sqrt(x**2 + y**2 + z**2)) filename = 'test_colors_param_surf_arity3.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_plot_and_save_4(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') ### # Examples from the 'advanced' notebook ### # XXX: This raises the warning "The evaluation of the expression is # problematic. We are trying a failback method that may still work. Please # report this as a bug." It has to use the fallback because using evalf() # is the only way to evaluate the integral. We should perhaps just remove # that warning. with TemporaryDirectory(prefix='sympy_') as tmpdir: with warns( UserWarning, match="The evaluation of the expression is problematic"): i = Integral(log((sin(x)**2 + 1)*sqrt(x**2 + 1)), (x, 0, y)) p = plot(i, (y, 1, 5)) filename = 'test_advanced_integral.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_plot_and_save_5(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') with TemporaryDirectory(prefix='sympy_') as tmpdir: s = Sum(1/x**y, (x, 1, oo)) p = plot(s, (y, 2, 10)) filename = 'test_advanced_inf_sum.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p = plot(Sum(1/x, (x, 1, y)), (y, 2, 10), show=False) p[0].only_integers = True p[0].steps = True filename = 'test_advanced_fin_sum.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_plot_and_save_6(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') with TemporaryDirectory(prefix='sympy_') as tmpdir: filename = 'test.png' ### # Test expressions that can not be translated to np and generate complex # results. ### p = plot(sin(x) + I*cos(x)) p.save(os.path.join(tmpdir, filename)) p = plot(sqrt(sqrt(-x))) p.save(os.path.join(tmpdir, filename)) p = plot(LambertW(x)) p.save(os.path.join(tmpdir, filename)) p = plot(sqrt(LambertW(x))) p.save(os.path.join(tmpdir, filename)) #Characteristic function of a StudentT distribution with nu=10 x1 = 5 * x**2 * exp_polar(-I*pi)/2 m1 = meijerg(((1 / 2,), ()), ((5, 0, 1 / 2), ()), x1) x2 = 5*x**2 * exp_polar(I*pi)/2 m2 = meijerg(((1/2,), ()), ((5, 0, 1/2), ()), x2) expr = (m1 + m2) / (48 * pi) p = plot(expr, (x, 1e-6, 1e-2)) p.save(os.path.join(tmpdir, filename)) def test_plotgrid_and_save(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') y = Symbol('y') with TemporaryDirectory(prefix='sympy_') as tmpdir: p1 = plot(x) p2 = plot_parametric((sin(x), cos(x)), (x, sin(x)), show=False) p3 = plot_parametric( cos(x), sin(x), adaptive=False, nb_of_points=500, show=False) p4 = plot3d_parametric_line(sin(x), cos(x), x, show=False) # symmetric grid p = PlotGrid(2, 2, p1, p2, p3, p4) filename = 'test_grid1.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() # grid size greater than the number of subplots p = PlotGrid(3, 4, p1, p2, p3, p4) filename = 'test_grid2.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() p5 = plot(cos(x),(x, -pi, pi), show=False) p5[0].line_color = lambda a: a p6 = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1), show=False) p7 = plot_contour( (x**2 + y**2, (x, -5, 5), (y, -5, 5)), (x**3 + y**3, (x, -3, 3), (y, -3, 3)), show=False) # unsymmetric grid (subplots in one line) p = PlotGrid(1, 3, p5, p6, p7) filename = 'test_grid3.png' p.save(os.path.join(tmpdir, filename)) p._backend.close() def test_append_issue_7140(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p1 = plot(x) p2 = plot(x**2) plot(x + 2) # append a series p2.append(p1[0]) assert len(p2._series) == 2 with raises(TypeError): p1.append(p2) with raises(TypeError): p1.append(p2._series) def test_issue_15265(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') eqn = sin(x) p = plot(eqn, xlim=(-S.Pi, S.Pi), ylim=(-1, 1)) p._backend.close() p = plot(eqn, xlim=(-1, 1), ylim=(-S.Pi, S.Pi)) p._backend.close() p = plot(eqn, xlim=(-1, 1), ylim=(sympify('-3.14'), sympify('3.14'))) p._backend.close() p = plot(eqn, xlim=(sympify('-3.14'), sympify('3.14')), ylim=(-1, 1)) p._backend.close() raises(ValueError, lambda: plot(eqn, xlim=(-S.ImaginaryUnit, 1), ylim=(-1, 1))) raises(ValueError, lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.ImaginaryUnit))) raises(ValueError, lambda: plot(eqn, xlim=(S.NegativeInfinity, 1), ylim=(-1, 1))) raises(ValueError, lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.Infinity))) def test_empty_Plot(): if not matplotlib: skip("Matplotlib not the default backend") # No exception showing an empty plot plot() p = Plot() p.show() def test_issue_17405(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') f = x**0.3 - 10*x**3 + x**2 p = plot(f, (x, -10, 10), show=False) # Random number of segments, probably more than 100, but we want to see # that there are segments generated, as opposed to when the bug was present assert len(p[0].get_data()[0]) >= 30 def test_logplot_PR_16796(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p = plot(x, (x, .001, 100), xscale='log', show=False) # Random number of segments, probably more than 100, but we want to see # that there are segments generated, as opposed to when the bug was present assert len(p[0].get_data()[0]) >= 30 assert p[0].end == 100.0 assert p[0].start == .001 def test_issue_16572(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p = plot(LambertW(x), show=False) # Random number of segments, probably more than 50, but we want to see # that there are segments generated, as opposed to when the bug was present assert len(p[0].get_data()[0]) >= 30 def test_issue_11865(): if not matplotlib: skip("Matplotlib not the default backend") k = Symbol('k', integer=True) f = Piecewise((-I*exp(I*pi*k)/k + I*exp(-I*pi*k)/k, Ne(k, 0)), (2*pi, True)) p = plot(f, show=False) # Random number of segments, probably more than 100, but we want to see # that there are segments generated, as opposed to when the bug was present # and that there are no exceptions. assert len(p[0].get_data()[0]) >= 30 def test_issue_11461(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p = plot(real_root((log(x/(x-2))), 3), show=False) # Random number of segments, probably more than 100, but we want to see # that there are segments generated, as opposed to when the bug was present # and that there are no exceptions. assert len(p[0].get_data()[0]) >= 30 def test_issue_11764(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p = plot_parametric(cos(x), sin(x), (x, 0, 2 * pi), aspect_ratio=(1,1), show=False) p.aspect_ratio == (1, 1) # Random number of segments, probably more than 100, but we want to see # that there are segments generated, as opposed to when the bug was present assert len(p[0].get_data()[0]) >= 30 def test_issue_13516(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') pm = plot(sin(x), backend="matplotlib", show=False) assert pm.backend == MatplotlibBackend assert len(pm[0].get_data()[0]) >= 30 pt = plot(sin(x), backend="text", show=False) assert pt.backend == TextBackend assert len(pt[0].get_data()[0]) >= 30 pd = plot(sin(x), backend="default", show=False) assert pd.backend == DefaultBackend assert len(pd[0].get_data()[0]) >= 30 p = plot(sin(x), show=False) assert p.backend == DefaultBackend assert len(p[0].get_data()[0]) >= 30 def test_plot_limits(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p = plot(x, x**2, (x, -10, 10)) backend = p._backend xmin, xmax = backend.ax[0].get_xlim() assert abs(xmin + 10) < 2 assert abs(xmax - 10) < 2 ymin, ymax = backend.ax[0].get_ylim() assert abs(ymin + 10) < 10 assert abs(ymax - 100) < 10 def test_plot3d_parametric_line_limits(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') v1 = (2*cos(x), 2*sin(x), 2*x, (x, -5, 5)) v2 = (sin(x), cos(x), x, (x, -5, 5)) p = plot3d_parametric_line(v1, v2) backend = p._backend xmin, xmax = backend.ax[0].get_xlim() assert abs(xmin + 2) < 1e-2 assert abs(xmax - 2) < 1e-2 ymin, ymax = backend.ax[0].get_ylim() assert abs(ymin + 2) < 1e-2 assert abs(ymax - 2) < 1e-2 zmin, zmax = backend.ax[0].get_zlim() assert abs(zmin + 10) < 1e-2 assert abs(zmax - 10) < 1e-2 p = plot3d_parametric_line(v2, v1) backend = p._backend xmin, xmax = backend.ax[0].get_xlim() assert abs(xmin + 2) < 1e-2 assert abs(xmax - 2) < 1e-2 ymin, ymax = backend.ax[0].get_ylim() assert abs(ymin + 2) < 1e-2 assert abs(ymax - 2) < 1e-2 zmin, zmax = backend.ax[0].get_zlim() assert abs(zmin + 10) < 1e-2 assert abs(zmax - 10) < 1e-2 def test_plot_size(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') p1 = plot(sin(x), backend="matplotlib", size=(8, 4)) s1 = p1._backend.fig.get_size_inches() assert (s1[0] == 8) and (s1[1] == 4) p2 = plot(sin(x), backend="matplotlib", size=(5, 10)) s2 = p2._backend.fig.get_size_inches() assert (s2[0] == 5) and (s2[1] == 10) p3 = PlotGrid(2, 1, p1, p2, size=(6, 2)) s3 = p3._backend.fig.get_size_inches() assert (s3[0] == 6) and (s3[1] == 2) with raises(ValueError): plot(sin(x), backend="matplotlib", size=(-1, 3)) def test_issue_20113(): if not matplotlib: skip("Matplotlib not the default backend") x = Symbol('x') # verify the capability to use custom backends with raises(TypeError): plot(sin(x), backend=Plot, show=False) p2 = plot(sin(x), backend=MatplotlibBackend, show=False) assert p2.backend == MatplotlibBackend assert len(p2[0].get_data()[0]) >= 30 p3 = plot(sin(x), backend=DummyBackendOk, show=False) assert p3.backend == DummyBackendOk assert len(p3[0].get_data()[0]) >= 30 # test for an improper coded backend p4 = plot(sin(x), backend=DummyBackendNotOk, show=False) assert p4.backend == DummyBackendNotOk assert len(p4[0].get_data()[0]) >= 30 with raises(NotImplementedError): p4.show() with raises(NotImplementedError): p4.save("test/path") with raises(NotImplementedError): p4._backend.close() def test_custom_coloring(): x = Symbol('x') y = Symbol('y') plot(cos(x), line_color=lambda a: a) plot(cos(x), line_color=1) plot(cos(x), line_color="r") plot_parametric(cos(x), sin(x), line_color=lambda a: a) plot_parametric(cos(x), sin(x), line_color=1) plot_parametric(cos(x), sin(x), line_color="r") plot3d_parametric_line(cos(x), sin(x), x, line_color=lambda a: a) plot3d_parametric_line(cos(x), sin(x), x, line_color=1) plot3d_parametric_line(cos(x), sin(x), x, line_color="r") plot3d_parametric_surface(cos(x + y), sin(x - y), x - y, (x, -5, 5), (y, -5, 5), surface_color=lambda a, b: a**2 + b**2) plot3d_parametric_surface(cos(x + y), sin(x - y), x - y, (x, -5, 5), (y, -5, 5), surface_color=1) plot3d_parametric_surface(cos(x + y), sin(x - y), x - y, (x, -5, 5), (y, -5, 5), surface_color="r") plot3d(x*y, (x, -5, 5), (y, -5, 5), surface_color=lambda a, b: a**2 + b**2) plot3d(x*y, (x, -5, 5), (y, -5, 5), surface_color=1) plot3d(x*y, (x, -5, 5), (y, -5, 5), surface_color="r")
439eb28b0d86c1971bec0a6da882099a12d6d85a2972f8372eab54e067d9d44b
from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.elementary.exponential import log from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin from sympy.plotting.textplot import textplot_str def test_axes_alignment(): x = Symbol('x') lines = [ ' 1 | ..', ' | ... ', ' | .. ', ' | ... ', ' | ... ', ' | .. ', ' | ... ', ' | ... ', ' | .. ', ' | ... ', ' 0 |--------------------------...--------------------------', ' | ... ', ' | .. ', ' | ... ', ' | ... ', ' | .. ', ' | ... ', ' | ... ', ' | .. ', ' | ... ', ' -1 |_______________________________________________________', ' -1 0 1' ] assert lines == list(textplot_str(x, -1, 1)) lines = [ ' 1 | ..', ' | .... ', ' | ... ', ' | ... ', ' | .... ', ' | ... ', ' | ... ', ' | .... ', ' 0 |--------------------------...--------------------------', ' | .... ', ' | ... ', ' | ... ', ' | .... ', ' | ... ', ' | ... ', ' | .... ', ' -1 |_______________________________________________________', ' -1 0 1' ] assert lines == list(textplot_str(x, -1, 1, H=17)) def test_singularity(): x = Symbol('x') lines = [ ' 54 | . ', ' | ', ' | ', ' | ', ' | ',' | ', ' | ', ' | ', ' | ', ' | ', ' 27.5 |--.----------------------------------------------------', ' | ', ' | ', ' | ', ' | . ', ' | \\ ', ' | \\ ', ' | .. ', ' | ... ', ' | ............. ', ' 1 |_______________________________________________________', ' 0 0.5 1' ] assert lines == list(textplot_str(1/x, 0, 1)) lines = [ ' 0 | ......', ' | ........ ', ' | ........ ', ' | ...... ', ' | ..... ', ' | .... ', ' | ... ', ' | .. ', ' | ... ', ' | / ', ' -2 |-------..----------------------------------------------', ' | / ', ' | / ', ' | / ', ' | . ', ' | ', ' | . ', ' | ', ' | ', ' | ', ' -4 |_______________________________________________________', ' 0 0.5 1' ] assert lines == list(textplot_str(log(x), 0, 1)) def test_sinc(): x = Symbol('x') lines = [ ' 1 | . . ', ' | . . ', ' | ', ' | . . ', ' | ', ' | . . ', ' | ', ' | ', ' | . . ', ' | ', ' 0.4 |-------------------------------------------------------', ' | . . ', ' | ', ' | . . ', ' | ', ' | ..... ..... ', ' | .. \\ . . / .. ', ' | / \\ / \\ ', ' |/ \\ . . / \\', ' | \\ / \\ / ', ' -0.2 |_______________________________________________________', ' -10 0 10' ] assert lines == list(textplot_str(sin(x)/x, -10, 10)) def test_imaginary(): x = Symbol('x') lines = [ ' 1 | ..', ' | .. ', ' | ... ', ' | .. ', ' | .. ', ' | .. ', ' | .. ', ' | .. ', ' | .. ', ' | / ', ' 0.5 |----------------------------------/--------------------', ' | .. ', ' | / ', ' | . ', ' | ', ' | . ', ' | . ', ' | ', ' | ', ' | ', ' 0 |_______________________________________________________', ' -1 0 1' ] assert list(textplot_str(sqrt(x), -1, 1)) == lines lines = [ ' 1 | ', ' | ', ' | ', ' | ', ' | ', ' | ', ' | ', ' | ', ' | ', ' | ', ' 0 |-------------------------------------------------------', ' | ', ' | ', ' | ', ' | ', ' | ', ' | ', ' | ', ' | ', ' | ', ' -1 |_______________________________________________________', ' -1 0 1' ] assert list(textplot_str(S.ImaginaryUnit, -1, 1)) == lines
0e3abe7b0566b3f2684ab883a68943861b6db412507493bc043e04d27c8e59c4
from .plot_interval import PlotInterval from .plot_object import PlotObject from .util import parse_option_string from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.geometry.entity import GeometryEntity from sympy.utilities.iterables import is_sequence class PlotMode(PlotObject): """ Grandparent class for plotting modes. Serves as interface for registration, lookup, and init of modes. To create a new plot mode, inherit from PlotModeBase or one of its children, such as PlotSurface or PlotCurve. """ ## Class-level attributes ## used to register and lookup ## plot modes. See PlotModeBase ## for descriptions and usage. i_vars, d_vars = '', '' intervals = [] aliases = [] is_default = False ## Draw is the only method here which ## is meant to be overridden in child ## classes, and PlotModeBase provides ## a base implementation. def draw(self): raise NotImplementedError() ## Everything else in this file has to ## do with registration and retrieval ## of plot modes. This is where I've ## hidden much of the ugliness of automatic ## plot mode divination... ## Plot mode registry data structures _mode_alias_list = [] _mode_map = { 1: {1: {}, 2: {}}, 2: {1: {}, 2: {}}, 3: {1: {}, 2: {}}, } # [d][i][alias_str]: class _mode_default_map = { 1: {}, 2: {}, 3: {}, } # [d][i]: class _i_var_max, _d_var_max = 2, 3 def __new__(cls, *args, **kwargs): """ This is the function which interprets arguments given to Plot.__init__ and Plot.__setattr__. Returns an initialized instance of the appropriate child class. """ newargs, newkwargs = PlotMode._extract_options(args, kwargs) mode_arg = newkwargs.get('mode', '') # Interpret the arguments d_vars, intervals = PlotMode._interpret_args(newargs) i_vars = PlotMode._find_i_vars(d_vars, intervals) i, d = max([len(i_vars), len(intervals)]), len(d_vars) # Find the appropriate mode subcls = PlotMode._get_mode(mode_arg, i, d) # Create the object o = object.__new__(subcls) # Do some setup for the mode instance o.d_vars = d_vars o._fill_i_vars(i_vars) o._fill_intervals(intervals) o.options = newkwargs return o @staticmethod def _get_mode(mode_arg, i_var_count, d_var_count): """ Tries to return an appropriate mode class. Intended to be called only by __new__. mode_arg Can be a string or a class. If it is a PlotMode subclass, it is simply returned. If it is a string, it can an alias for a mode or an empty string. In the latter case, we try to find a default mode for the i_var_count and d_var_count. i_var_count The number of independent variables needed to evaluate the d_vars. d_var_count The number of dependent variables; usually the number of functions to be evaluated in plotting. For example, a Cartesian function y = f(x) has one i_var (x) and one d_var (y). A parametric form x,y,z = f(u,v), f(u,v), f(u,v) has two two i_vars (u,v) and three d_vars (x,y,z). """ # if the mode_arg is simply a PlotMode class, # check that the mode supports the numbers # of independent and dependent vars, then # return it try: m = None if issubclass(mode_arg, PlotMode): m = mode_arg except TypeError: pass if m: if not m._was_initialized: raise ValueError(("To use unregistered plot mode %s " "you must first call %s._init_mode().") % (m.__name__, m.__name__)) if d_var_count != m.d_var_count: raise ValueError(("%s can only plot functions " "with %i dependent variables.") % (m.__name__, m.d_var_count)) if i_var_count > m.i_var_count: raise ValueError(("%s cannot plot functions " "with more than %i independent " "variables.") % (m.__name__, m.i_var_count)) return m # If it is a string, there are two possibilities. if isinstance(mode_arg, str): i, d = i_var_count, d_var_count if i > PlotMode._i_var_max: raise ValueError(var_count_error(True, True)) if d > PlotMode._d_var_max: raise ValueError(var_count_error(False, True)) # If the string is '', try to find a suitable # default mode if not mode_arg: return PlotMode._get_default_mode(i, d) # Otherwise, interpret the string as a mode # alias (e.g. 'cartesian', 'parametric', etc) else: return PlotMode._get_aliased_mode(mode_arg, i, d) else: raise ValueError("PlotMode argument must be " "a class or a string") @staticmethod def _get_default_mode(i, d, i_vars=-1): if i_vars == -1: i_vars = i try: return PlotMode._mode_default_map[d][i] except KeyError: # Keep looking for modes in higher i var counts # which support the given d var count until we # reach the max i_var count. if i < PlotMode._i_var_max: return PlotMode._get_default_mode(i + 1, d, i_vars) else: raise ValueError(("Couldn't find a default mode " "for %i independent and %i " "dependent variables.") % (i_vars, d)) @staticmethod def _get_aliased_mode(alias, i, d, i_vars=-1): if i_vars == -1: i_vars = i if alias not in PlotMode._mode_alias_list: raise ValueError(("Couldn't find a mode called" " %s. Known modes: %s.") % (alias, ", ".join(PlotMode._mode_alias_list))) try: return PlotMode._mode_map[d][i][alias] except TypeError: # Keep looking for modes in higher i var counts # which support the given d var count and alias # until we reach the max i_var count. if i < PlotMode._i_var_max: return PlotMode._get_aliased_mode(alias, i + 1, d, i_vars) else: raise ValueError(("Couldn't find a %s mode " "for %i independent and %i " "dependent variables.") % (alias, i_vars, d)) @classmethod def _register(cls): """ Called once for each user-usable plot mode. For Cartesian2D, it is invoked after the class definition: Cartesian2D._register() """ name = cls.__name__ cls._init_mode() try: i, d = cls.i_var_count, cls.d_var_count # Add the mode to _mode_map under all # given aliases for a in cls.aliases: if a not in PlotMode._mode_alias_list: # Also track valid aliases, so # we can quickly know when given # an invalid one in _get_mode. PlotMode._mode_alias_list.append(a) PlotMode._mode_map[d][i][a] = cls if cls.is_default: # If this mode was marked as the # default for this d,i combination, # also set that. PlotMode._mode_default_map[d][i] = cls except Exception as e: raise RuntimeError(("Failed to register " "plot mode %s. Reason: %s") % (name, (str(e)))) @classmethod def _init_mode(cls): """ Initializes the plot mode based on the 'mode-specific parameters' above. Only intended to be called by PlotMode._register(). To use a mode without registering it, you can directly call ModeSubclass._init_mode(). """ def symbols_list(symbol_str): return [Symbol(s) for s in symbol_str] # Convert the vars strs into # lists of symbols. cls.i_vars = symbols_list(cls.i_vars) cls.d_vars = symbols_list(cls.d_vars) # Var count is used often, calculate # it once here cls.i_var_count = len(cls.i_vars) cls.d_var_count = len(cls.d_vars) if cls.i_var_count > PlotMode._i_var_max: raise ValueError(var_count_error(True, False)) if cls.d_var_count > PlotMode._d_var_max: raise ValueError(var_count_error(False, False)) # Try to use first alias as primary_alias if len(cls.aliases) > 0: cls.primary_alias = cls.aliases[0] else: cls.primary_alias = cls.__name__ di = cls.intervals if len(di) != cls.i_var_count: raise ValueError("Plot mode must provide a " "default interval for each i_var.") for i in range(cls.i_var_count): # default intervals must be given [min,max,steps] # (no var, but they must be in the same order as i_vars) if len(di[i]) != 3: raise ValueError("length should be equal to 3") # Initialize an incomplete interval, # to later be filled with a var when # the mode is instantiated. di[i] = PlotInterval(None, *di[i]) # To prevent people from using modes # without these required fields set up. cls._was_initialized = True _was_initialized = False ## Initializer Helper Methods @staticmethod def _find_i_vars(functions, intervals): i_vars = [] # First, collect i_vars in the # order they are given in any # intervals. for i in intervals: if i.v is None: continue elif i.v in i_vars: raise ValueError(("Multiple intervals given " "for %s.") % (str(i.v))) i_vars.append(i.v) # Then, find any remaining # i_vars in given functions # (aka d_vars) for f in functions: for a in f.free_symbols: if a not in i_vars: i_vars.append(a) return i_vars def _fill_i_vars(self, i_vars): # copy default i_vars self.i_vars = [Symbol(str(i)) for i in self.i_vars] # replace with given i_vars for i in range(len(i_vars)): self.i_vars[i] = i_vars[i] def _fill_intervals(self, intervals): # copy default intervals self.intervals = [PlotInterval(i) for i in self.intervals] # track i_vars used so far v_used = [] # fill copy of default # intervals with given info for i in range(len(intervals)): self.intervals[i].fill_from(intervals[i]) if self.intervals[i].v is not None: v_used.append(self.intervals[i].v) # Find any orphan intervals and # assign them i_vars for i in range(len(self.intervals)): if self.intervals[i].v is None: u = [v for v in self.i_vars if v not in v_used] if len(u) == 0: raise ValueError("length should not be equal to 0") self.intervals[i].v = u[0] v_used.append(u[0]) @staticmethod def _interpret_args(args): interval_wrong_order = "PlotInterval %s was given before any function(s)." interpret_error = "Could not interpret %s as a function or interval." functions, intervals = [], [] if isinstance(args[0], GeometryEntity): for coords in list(args[0].arbitrary_point()): functions.append(coords) intervals.append(PlotInterval.try_parse(args[0].plot_interval())) else: for a in args: i = PlotInterval.try_parse(a) if i is not None: if len(functions) == 0: raise ValueError(interval_wrong_order % (str(i))) else: intervals.append(i) else: if is_sequence(a, include=str): raise ValueError(interpret_error % (str(a))) try: f = sympify(a) functions.append(f) except TypeError: raise ValueError(interpret_error % str(a)) return functions, intervals @staticmethod def _extract_options(args, kwargs): newkwargs, newargs = {}, [] for a in args: if isinstance(a, str): newkwargs = dict(newkwargs, **parse_option_string(a)) else: newargs.append(a) newkwargs = dict(newkwargs, **kwargs) return newargs, newkwargs def var_count_error(is_independent, is_plotting): """ Used to format an error message which differs slightly in 4 places. """ if is_plotting: v = "Plotting" else: v = "Registering plot modes" if is_independent: n, s = PlotMode._i_var_max, "independent" else: n, s = PlotMode._d_var_max, "dependent" return ("%s with more than %i %s variables " "is not supported.") % (v, n, s)
eca64bb337b87feae24326ea545fd4484a217b14534bb9fa4650903fb85a2a2b
from threading import RLock # it is sufficient to import "pyglet" here once try: import pyglet.gl as pgl except ImportError: raise ImportError("pyglet is required for plotting.\n " "visit http://www.pyglet.org/") from sympy.core.numbers import Integer from sympy.external.gmpy import SYMPY_INTS from sympy.geometry.entity import GeometryEntity from sympy.plotting.pygletplot.plot_axes import PlotAxes from sympy.plotting.pygletplot.plot_mode import PlotMode from sympy.plotting.pygletplot.plot_object import PlotObject from sympy.plotting.pygletplot.plot_window import PlotWindow from sympy.plotting.pygletplot.util import parse_option_string from sympy.utilities.decorator import doctest_depends_on from sympy.utilities.iterables import is_sequence from time import sleep from os import getcwd, listdir import ctypes @doctest_depends_on(modules=('pyglet',)) class PygletPlot: """ Plot Examples ============= See examples/advanced/pyglet_plotting.py for many more examples. >>> from sympy.plotting.pygletplot import PygletPlot as Plot >>> from sympy.abc import x, y, z >>> Plot(x*y**3-y*x**3) [0]: -x**3*y + x*y**3, 'mode=cartesian' >>> p = Plot() >>> p[1] = x*y >>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4) >>> p = Plot() >>> p[1] = x**2+y**2 >>> p[2] = -x**2-y**2 Variable Intervals ================== The basic format is [var, min, max, steps], but the syntax is flexible and arguments left out are taken from the defaults for the current coordinate mode: >>> Plot(x**2) # implies [x,-5,5,100] [0]: x**2, 'mode=cartesian' >>> Plot(x**2, [], []) # [x,-1,1,40], [y,-1,1,40] [0]: x**2, 'mode=cartesian' >>> Plot(x**2-y**2, [100], [100]) # [x,-1,1,100], [y,-1,1,100] [0]: x**2 - y**2, 'mode=cartesian' >>> Plot(x**2, [x,-13,13,100]) [0]: x**2, 'mode=cartesian' >>> Plot(x**2, [-13,13]) # [x,-13,13,100] [0]: x**2, 'mode=cartesian' >>> Plot(x**2, [x,-13,13]) # [x,-13,13,10] [0]: x**2, 'mode=cartesian' >>> Plot(1*x, [], [x], mode='cylindrical') ... # [unbound_theta,0,2*Pi,40], [x,-1,1,20] [0]: x, 'mode=cartesian' Coordinate Modes ================ Plot supports several curvilinear coordinate modes, and they independent for each plotted function. You can specify a coordinate mode explicitly with the 'mode' named argument, but it can be automatically determined for Cartesian or parametric plots, and therefore must only be specified for polar, cylindrical, and spherical modes. Specifically, Plot(function arguments) and Plot[n] = (function arguments) will interpret your arguments as a Cartesian plot if you provide one function and a parametric plot if you provide two or three functions. Similarly, the arguments will be interpreted as a curve if one variable is used, and a surface if two are used. Supported mode names by number of variables: 1: parametric, cartesian, polar 2: parametric, cartesian, cylindrical = polar, spherical >>> Plot(1, mode='spherical') Calculator-like Interface ========================= >>> p = Plot(visible=False) >>> f = x**2 >>> p[1] = f >>> p[2] = f.diff(x) >>> p[3] = f.diff(x).diff(x) >>> p [1]: x**2, 'mode=cartesian' [2]: 2*x, 'mode=cartesian' [3]: 2, 'mode=cartesian' >>> p.show() >>> p.clear() >>> p <blank plot> >>> p[1] = x**2+y**2 >>> p[1].style = 'solid' >>> p[2] = -x**2-y**2 >>> p[2].style = 'wireframe' >>> p[1].color = z, (0.4,0.4,0.9), (0.9,0.4,0.4) >>> p[1].style = 'both' >>> p[2].style = 'both' >>> p.close() Plot Window Keyboard Controls ============================= Screen Rotation: X,Y axis Arrow Keys, A,S,D,W, Numpad 4,6,8,2 Z axis Q,E, Numpad 7,9 Model Rotation: Z axis Z,C, Numpad 1,3 Zoom: R,F, PgUp,PgDn, Numpad +,- Reset Camera: X, Numpad 5 Camera Presets: XY F1 XZ F2 YZ F3 Perspective F4 Sensitivity Modifier: SHIFT Axes Toggle: Visible F5 Colors F6 Close Window: ESCAPE ============================= """ @doctest_depends_on(modules=('pyglet',)) def __init__(self, *fargs, **win_args): """ Positional Arguments ==================== Any given positional arguments are used to initialize a plot function at index 1. In other words... >>> from sympy.plotting.pygletplot import PygletPlot as Plot >>> from sympy.abc import x >>> p = Plot(x**2, visible=False) ...is equivalent to... >>> p = Plot(visible=False) >>> p[1] = x**2 Note that in earlier versions of the plotting module, you were able to specify multiple functions in the initializer. This functionality has been dropped in favor of better automatic plot plot_mode detection. Named Arguments =============== axes An option string of the form "key1=value1; key2 = value2" which can use the following options: style = ordinate none OR frame OR box OR ordinate stride = 0.25 val OR (val_x, val_y, val_z) overlay = True (draw on top of plot) True OR False colored = False (False uses Black, True uses colors R,G,B = X,Y,Z) True OR False label_axes = False (display axis names at endpoints) True OR False visible = True (show immediately True OR False The following named arguments are passed as arguments to window initialization: antialiasing = True True OR False ortho = False True OR False invert_mouse_zoom = False True OR False """ # Register the plot modes from . import plot_modes # noqa self._win_args = win_args self._window = None self._render_lock = RLock() self._functions = {} self._pobjects = [] self._screenshot = ScreenShot(self) axe_options = parse_option_string(win_args.pop('axes', '')) self.axes = PlotAxes(**axe_options) self._pobjects.append(self.axes) self[0] = fargs if win_args.get('visible', True): self.show() ## Window Interfaces def show(self): """ Creates and displays a plot window, or activates it (gives it focus) if it has already been created. """ if self._window and not self._window.has_exit: self._window.activate() else: self._win_args['visible'] = True self.axes.reset_resources() #if hasattr(self, '_doctest_depends_on'): # self._win_args['runfromdoctester'] = True self._window = PlotWindow(self, **self._win_args) def close(self): """ Closes the plot window. """ if self._window: self._window.close() def saveimage(self, outfile=None, format='', size=(600, 500)): """ Saves a screen capture of the plot window to an image file. If outfile is given, it can either be a path or a file object. Otherwise a png image will be saved to the current working directory. If the format is omitted, it is determined from the filename extension. """ self._screenshot.save(outfile, format, size) ## Function List Interfaces def clear(self): """ Clears the function list of this plot. """ self._render_lock.acquire() self._functions = {} self.adjust_all_bounds() self._render_lock.release() def __getitem__(self, i): """ Returns the function at position i in the function list. """ return self._functions[i] def __setitem__(self, i, args): """ Parses and adds a PlotMode to the function list. """ if not (isinstance(i, (SYMPY_INTS, Integer)) and i >= 0): raise ValueError("Function index must " "be an integer >= 0.") if isinstance(args, PlotObject): f = args else: if (not is_sequence(args)) or isinstance(args, GeometryEntity): args = [args] if len(args) == 0: return # no arguments given kwargs = dict(bounds_callback=self.adjust_all_bounds) f = PlotMode(*args, **kwargs) if f: self._render_lock.acquire() self._functions[i] = f self._render_lock.release() else: raise ValueError("Failed to parse '%s'." % ', '.join(str(a) for a in args)) def __delitem__(self, i): """ Removes the function in the function list at position i. """ self._render_lock.acquire() del self._functions[i] self.adjust_all_bounds() self._render_lock.release() def firstavailableindex(self): """ Returns the first unused index in the function list. """ i = 0 self._render_lock.acquire() while i in self._functions: i += 1 self._render_lock.release() return i def append(self, *args): """ Parses and adds a PlotMode to the function list at the first available index. """ self.__setitem__(self.firstavailableindex(), args) def __len__(self): """ Returns the number of functions in the function list. """ return len(self._functions) def __iter__(self): """ Allows iteration of the function list. """ return self._functions.itervalues() def __repr__(self): return str(self) def __str__(self): """ Returns a string containing a new-line separated list of the functions in the function list. """ s = "" if len(self._functions) == 0: s += "<blank plot>" else: self._render_lock.acquire() s += "\n".join(["%s[%i]: %s" % ("", i, str(self._functions[i])) for i in self._functions]) self._render_lock.release() return s def adjust_all_bounds(self): self._render_lock.acquire() self.axes.reset_bounding_box() for f in self._functions: self.axes.adjust_bounds(self._functions[f].bounds) self._render_lock.release() def wait_for_calculations(self): sleep(0) self._render_lock.acquire() for f in self._functions: a = self._functions[f]._get_calculating_verts b = self._functions[f]._get_calculating_cverts while a() or b(): sleep(0) self._render_lock.release() class ScreenShot: def __init__(self, plot): self._plot = plot self.screenshot_requested = False self.outfile = None self.format = '' self.invisibleMode = False self.flag = 0 def __bool__(self): return self.screenshot_requested def _execute_saving(self): if self.flag < 3: self.flag += 1 return size_x, size_y = self._plot._window.get_size() size = size_x*size_y*4*ctypes.sizeof(ctypes.c_ubyte) image = ctypes.create_string_buffer(size) pgl.glReadPixels(0, 0, size_x, size_y, pgl.GL_RGBA, pgl.GL_UNSIGNED_BYTE, image) from PIL import Image im = Image.frombuffer('RGBA', (size_x, size_y), image.raw, 'raw', 'RGBA', 0, 1) im.transpose(Image.FLIP_TOP_BOTTOM).save(self.outfile, self.format) self.flag = 0 self.screenshot_requested = False if self.invisibleMode: self._plot._window.close() def save(self, outfile=None, format='', size=(600, 500)): self.outfile = outfile self.format = format self.size = size self.screenshot_requested = True if not self._plot._window or self._plot._window.has_exit: self._plot._win_args['visible'] = False self._plot._win_args['width'] = size[0] self._plot._win_args['height'] = size[1] self._plot.axes.reset_resources() self._plot._window = PlotWindow(self._plot, **self._plot._win_args) self.invisibleMode = True if self.outfile is None: self.outfile = self._create_unique_path() print(self.outfile) def _create_unique_path(self): cwd = getcwd() l = listdir(cwd) path = '' i = 0 while True: if not 'plot_%s.png' % i in l: path = cwd + '/plot_%s.png' % i break i += 1 return path
11ce4626ba2eaa4f48f42c462e080bf105febb55ec58fa7b75c4d1110656c15d
import pyglet.gl as pgl from sympy.core import S from sympy.plotting.pygletplot.color_scheme import ColorScheme from sympy.plotting.pygletplot.plot_mode import PlotMode from sympy.utilities.iterables import is_sequence from time import sleep from threading import Thread, Event, RLock import warnings class PlotModeBase(PlotMode): """ Intended parent class for plotting modes. Provides base functionality in conjunction with its parent, PlotMode. """ ## ## Class-Level Attributes ## """ The following attributes are meant to be set at the class level, and serve as parameters to the plot mode registry (in PlotMode). See plot_modes.py for concrete examples. """ """ i_vars 'x' for Cartesian2D 'xy' for Cartesian3D etc. d_vars 'y' for Cartesian2D 'r' for Polar etc. """ i_vars, d_vars = '', '' """ intervals Default intervals for each i_var, and in the same order. Specified [min, max, steps]. No variable can be given (it is bound later). """ intervals = [] """ aliases A list of strings which can be used to access this mode. 'cartesian' for Cartesian2D and Cartesian3D 'polar' for Polar 'cylindrical', 'polar' for Cylindrical Note that _init_mode chooses the first alias in the list as the mode's primary_alias, which will be displayed to the end user in certain contexts. """ aliases = [] """ is_default Whether to set this mode as the default for arguments passed to PlotMode() containing the same number of d_vars as this mode and at most the same number of i_vars. """ is_default = False """ All of the above attributes are defined in PlotMode. The following ones are specific to PlotModeBase. """ """ A list of the render styles. Do not modify. """ styles = {'wireframe': 1, 'solid': 2, 'both': 3} """ style_override Always use this style if not blank. """ style_override = '' """ default_wireframe_color default_solid_color Can be used when color is None or being calculated. Used by PlotCurve and PlotSurface, but not anywhere in PlotModeBase. """ default_wireframe_color = (0.85, 0.85, 0.85) default_solid_color = (0.6, 0.6, 0.9) default_rot_preset = 'xy' ## ## Instance-Level Attributes ## ## 'Abstract' member functions def _get_evaluator(self): if self.use_lambda_eval: try: e = self._get_lambda_evaluator() return e except Exception: warnings.warn("\nWarning: creating lambda evaluator failed. " "Falling back on SymPy subs evaluator.") return self._get_sympy_evaluator() def _get_sympy_evaluator(self): raise NotImplementedError() def _get_lambda_evaluator(self): raise NotImplementedError() def _on_calculate_verts(self): raise NotImplementedError() def _on_calculate_cverts(self): raise NotImplementedError() ## Base member functions def __init__(self, *args, bounds_callback=None, **kwargs): self.verts = [] self.cverts = [] self.bounds = [[S.Infinity, S.NegativeInfinity, 0], [S.Infinity, S.NegativeInfinity, 0], [S.Infinity, S.NegativeInfinity, 0]] self.cbounds = [[S.Infinity, S.NegativeInfinity, 0], [S.Infinity, S.NegativeInfinity, 0], [S.Infinity, S.NegativeInfinity, 0]] self._draw_lock = RLock() self._calculating_verts = Event() self._calculating_cverts = Event() self._calculating_verts_pos = 0.0 self._calculating_verts_len = 0.0 self._calculating_cverts_pos = 0.0 self._calculating_cverts_len = 0.0 self._max_render_stack_size = 3 self._draw_wireframe = [-1] self._draw_solid = [-1] self._style = None self._color = None self.predraw = [] self.postdraw = [] self.use_lambda_eval = self.options.pop('use_sympy_eval', None) is None self.style = self.options.pop('style', '') self.color = self.options.pop('color', 'rainbow') self.bounds_callback = bounds_callback self._on_calculate() def synchronized(f): def w(self, *args, **kwargs): self._draw_lock.acquire() try: r = f(self, *args, **kwargs) return r finally: self._draw_lock.release() return w @synchronized def push_wireframe(self, function): """ Push a function which performs gl commands used to build a display list. (The list is built outside of the function) """ assert callable(function) self._draw_wireframe.append(function) if len(self._draw_wireframe) > self._max_render_stack_size: del self._draw_wireframe[1] # leave marker element @synchronized def push_solid(self, function): """ Push a function which performs gl commands used to build a display list. (The list is built outside of the function) """ assert callable(function) self._draw_solid.append(function) if len(self._draw_solid) > self._max_render_stack_size: del self._draw_solid[1] # leave marker element def _create_display_list(self, function): dl = pgl.glGenLists(1) pgl.glNewList(dl, pgl.GL_COMPILE) function() pgl.glEndList() return dl def _render_stack_top(self, render_stack): top = render_stack[-1] if top == -1: return -1 # nothing to display elif callable(top): dl = self._create_display_list(top) render_stack[-1] = (dl, top) return dl # display newly added list elif len(top) == 2: if pgl.GL_TRUE == pgl.glIsList(top[0]): return top[0] # display stored list dl = self._create_display_list(top[1]) render_stack[-1] = (dl, top[1]) return dl # display regenerated list def _draw_solid_display_list(self, dl): pgl.glPushAttrib(pgl.GL_ENABLE_BIT | pgl.GL_POLYGON_BIT) pgl.glPolygonMode(pgl.GL_FRONT_AND_BACK, pgl.GL_FILL) pgl.glCallList(dl) pgl.glPopAttrib() def _draw_wireframe_display_list(self, dl): pgl.glPushAttrib(pgl.GL_ENABLE_BIT | pgl.GL_POLYGON_BIT) pgl.glPolygonMode(pgl.GL_FRONT_AND_BACK, pgl.GL_LINE) pgl.glEnable(pgl.GL_POLYGON_OFFSET_LINE) pgl.glPolygonOffset(-0.005, -50.0) pgl.glCallList(dl) pgl.glPopAttrib() @synchronized def draw(self): for f in self.predraw: if callable(f): f() if self.style_override: style = self.styles[self.style_override] else: style = self.styles[self._style] # Draw solid component if style includes solid if style & 2: dl = self._render_stack_top(self._draw_solid) if dl > 0 and pgl.GL_TRUE == pgl.glIsList(dl): self._draw_solid_display_list(dl) # Draw wireframe component if style includes wireframe if style & 1: dl = self._render_stack_top(self._draw_wireframe) if dl > 0 and pgl.GL_TRUE == pgl.glIsList(dl): self._draw_wireframe_display_list(dl) for f in self.postdraw: if callable(f): f() def _on_change_color(self, color): Thread(target=self._calculate_cverts).start() def _on_calculate(self): Thread(target=self._calculate_all).start() def _calculate_all(self): self._calculate_verts() self._calculate_cverts() def _calculate_verts(self): if self._calculating_verts.isSet(): return self._calculating_verts.set() try: self._on_calculate_verts() finally: self._calculating_verts.clear() if callable(self.bounds_callback): self.bounds_callback() def _calculate_cverts(self): if self._calculating_verts.isSet(): return while self._calculating_cverts.isSet(): sleep(0) # wait for previous calculation self._calculating_cverts.set() try: self._on_calculate_cverts() finally: self._calculating_cverts.clear() def _get_calculating_verts(self): return self._calculating_verts.isSet() def _get_calculating_verts_pos(self): return self._calculating_verts_pos def _get_calculating_verts_len(self): return self._calculating_verts_len def _get_calculating_cverts(self): return self._calculating_cverts.isSet() def _get_calculating_cverts_pos(self): return self._calculating_cverts_pos def _get_calculating_cverts_len(self): return self._calculating_cverts_len ## Property handlers def _get_style(self): return self._style @synchronized def _set_style(self, v): if v is None: return if v == '': step_max = 0 for i in self.intervals: if i.v_steps is None: continue step_max = max([step_max, int(i.v_steps)]) v = ['both', 'solid'][step_max > 40] if v not in self.styles: raise ValueError("v should be there in self.styles") if v == self._style: return self._style = v def _get_color(self): return self._color @synchronized def _set_color(self, v): try: if v is not None: if is_sequence(v): v = ColorScheme(*v) else: v = ColorScheme(v) if repr(v) == repr(self._color): return self._on_change_color(v) self._color = v except Exception as e: raise RuntimeError("Color change failed. " "Reason: %s" % (str(e))) style = property(_get_style, _set_style) color = property(_get_color, _set_color) calculating_verts = property(_get_calculating_verts) calculating_verts_pos = property(_get_calculating_verts_pos) calculating_verts_len = property(_get_calculating_verts_len) calculating_cverts = property(_get_calculating_cverts) calculating_cverts_pos = property(_get_calculating_cverts_pos) calculating_cverts_len = property(_get_calculating_cverts_len) ## String representations def __str__(self): f = ", ".join(str(d) for d in self.d_vars) o = "'mode=%s'" % (self.primary_alias) return ", ".join([f, o]) def __repr__(self): f = ", ".join(str(d) for d in self.d_vars) i = ", ".join(str(i) for i in self.intervals) d = [('mode', self.primary_alias), ('color', str(self.color)), ('style', str(self.style))] o = "'%s'" % ("; ".join("%s=%s" % (k, v) for k, v in d if v != 'None')) return ", ".join([f, i, o])
225799aec1d7b5d1d7380133d514237992ae89889fe0e2b4bd8b84efb9aa3aa7
from sympy.core.basic import Basic from sympy.core.symbol import (Symbol, symbols) from sympy.utilities.lambdify import lambdify from .util import interpolate, rinterpolate, create_bounds, update_bounds from sympy.utilities.iterables import sift class ColorGradient: colors = [0.4, 0.4, 0.4], [0.9, 0.9, 0.9] intervals = 0.0, 1.0 def __init__(self, *args): if len(args) == 2: self.colors = list(args) self.intervals = [0.0, 1.0] elif len(args) > 0: if len(args) % 2 != 0: raise ValueError("len(args) should be even") self.colors = [args[i] for i in range(1, len(args), 2)] self.intervals = [args[i] for i in range(0, len(args), 2)] assert len(self.colors) == len(self.intervals) def copy(self): c = ColorGradient() c.colors = [e[::] for e in self.colors] c.intervals = self.intervals[::] return c def _find_interval(self, v): m = len(self.intervals) i = 0 while i < m - 1 and self.intervals[i] <= v: i += 1 return i def _interpolate_axis(self, axis, v): i = self._find_interval(v) v = rinterpolate(self.intervals[i - 1], self.intervals[i], v) return interpolate(self.colors[i - 1][axis], self.colors[i][axis], v) def __call__(self, r, g, b): c = self._interpolate_axis return c(0, r), c(1, g), c(2, b) default_color_schemes = {} # defined at the bottom of this file class ColorScheme: def __init__(self, *args, **kwargs): self.args = args self.f, self.gradient = None, ColorGradient() if len(args) == 1 and not isinstance(args[0], Basic) and callable(args[0]): self.f = args[0] elif len(args) == 1 and isinstance(args[0], str): if args[0] in default_color_schemes: cs = default_color_schemes[args[0]] self.f, self.gradient = cs.f, cs.gradient.copy() else: self.f = lambdify('x,y,z,u,v', args[0]) else: self.f, self.gradient = self._interpret_args(args) self._test_color_function() if not isinstance(self.gradient, ColorGradient): raise ValueError("Color gradient not properly initialized. " "(Not a ColorGradient instance.)") def _interpret_args(self, args): f, gradient = None, self.gradient atoms, lists = self._sort_args(args) s = self._pop_symbol_list(lists) s = self._fill_in_vars(s) # prepare the error message for lambdification failure f_str = ', '.join(str(fa) for fa in atoms) s_str = (str(sa) for sa in s) s_str = ', '.join(sa for sa in s_str if sa.find('unbound') < 0) f_error = ValueError("Could not interpret arguments " "%s as functions of %s." % (f_str, s_str)) # try to lambdify args if len(atoms) == 1: fv = atoms[0] try: f = lambdify(s, [fv, fv, fv]) except TypeError: raise f_error elif len(atoms) == 3: fr, fg, fb = atoms try: f = lambdify(s, [fr, fg, fb]) except TypeError: raise f_error else: raise ValueError("A ColorScheme must provide 1 or 3 " "functions in x, y, z, u, and/or v.") # try to intrepret any given color information if len(lists) == 0: gargs = [] elif len(lists) == 1: gargs = lists[0] elif len(lists) == 2: try: (r1, g1, b1), (r2, g2, b2) = lists except TypeError: raise ValueError("If two color arguments are given, " "they must be given in the format " "(r1, g1, b1), (r2, g2, b2).") gargs = lists elif len(lists) == 3: try: (r1, r2), (g1, g2), (b1, b2) = lists except Exception: raise ValueError("If three color arguments are given, " "they must be given in the format " "(r1, r2), (g1, g2), (b1, b2). To create " "a multi-step gradient, use the syntax " "[0, colorStart, step1, color1, ..., 1, " "colorEnd].") gargs = [[r1, g1, b1], [r2, g2, b2]] else: raise ValueError("Don't know what to do with collection " "arguments %s." % (', '.join(str(l) for l in lists))) if gargs: try: gradient = ColorGradient(*gargs) except Exception as ex: raise ValueError(("Could not initialize a gradient " "with arguments %s. Inner " "exception: %s") % (gargs, str(ex))) return f, gradient def _pop_symbol_list(self, lists): symbol_lists = [] for l in lists: mark = True for s in l: if s is not None and not isinstance(s, Symbol): mark = False break if mark: lists.remove(l) symbol_lists.append(l) if len(symbol_lists) == 1: return symbol_lists[0] elif len(symbol_lists) == 0: return [] else: raise ValueError("Only one list of Symbols " "can be given for a color scheme.") def _fill_in_vars(self, args): defaults = symbols('x,y,z,u,v') v_error = ValueError("Could not find what to plot.") if len(args) == 0: return defaults if not isinstance(args, (tuple, list)): raise v_error if len(args) == 0: return defaults for s in args: if s is not None and not isinstance(s, Symbol): raise v_error # when vars are given explicitly, any vars # not given are marked 'unbound' as to not # be accidentally used in an expression vars = [Symbol('unbound%i' % (i)) for i in range(1, 6)] # interpret as t if len(args) == 1: vars[3] = args[0] # interpret as u,v elif len(args) == 2: if args[0] is not None: vars[3] = args[0] if args[1] is not None: vars[4] = args[1] # interpret as x,y,z elif len(args) >= 3: # allow some of x,y,z to be # left unbound if not given if args[0] is not None: vars[0] = args[0] if args[1] is not None: vars[1] = args[1] if args[2] is not None: vars[2] = args[2] # interpret the rest as t if len(args) >= 4: vars[3] = args[3] # ...or u,v if len(args) >= 5: vars[4] = args[4] return vars def _sort_args(self, args): lists, atoms = sift(args, lambda a: isinstance(a, (tuple, list)), binary=True) return atoms, lists def _test_color_function(self): if not callable(self.f): raise ValueError("Color function is not callable.") try: result = self.f(0, 0, 0, 0, 0) if len(result) != 3: raise ValueError("length should be equal to 3") except TypeError: raise ValueError("Color function needs to accept x,y,z,u,v, " "as arguments even if it doesn't use all of them.") except AssertionError: raise ValueError("Color function needs to return 3-tuple r,g,b.") except Exception: pass # color function probably not valid at 0,0,0,0,0 def __call__(self, x, y, z, u, v): try: return self.f(x, y, z, u, v) except Exception: return None def apply_to_curve(self, verts, u_set, set_len=None, inc_pos=None): """ Apply this color scheme to a set of vertices over a single independent variable u. """ bounds = create_bounds() cverts = list() if callable(set_len): set_len(len(u_set)*2) # calculate f() = r,g,b for each vert # and find the min and max for r,g,b for _u in range(len(u_set)): if verts[_u] is None: cverts.append(None) else: x, y, z = verts[_u] u, v = u_set[_u], None c = self(x, y, z, u, v) if c is not None: c = list(c) update_bounds(bounds, c) cverts.append(c) if callable(inc_pos): inc_pos() # scale and apply gradient for _u in range(len(u_set)): if cverts[_u] is not None: for _c in range(3): # scale from [f_min, f_max] to [0,1] cverts[_u][_c] = rinterpolate(bounds[_c][0], bounds[_c][1], cverts[_u][_c]) # apply gradient cverts[_u] = self.gradient(*cverts[_u]) if callable(inc_pos): inc_pos() return cverts def apply_to_surface(self, verts, u_set, v_set, set_len=None, inc_pos=None): """ Apply this color scheme to a set of vertices over two independent variables u and v. """ bounds = create_bounds() cverts = list() if callable(set_len): set_len(len(u_set)*len(v_set)*2) # calculate f() = r,g,b for each vert # and find the min and max for r,g,b for _u in range(len(u_set)): column = list() for _v in range(len(v_set)): if verts[_u][_v] is None: column.append(None) else: x, y, z = verts[_u][_v] u, v = u_set[_u], v_set[_v] c = self(x, y, z, u, v) if c is not None: c = list(c) update_bounds(bounds, c) column.append(c) if callable(inc_pos): inc_pos() cverts.append(column) # scale and apply gradient for _u in range(len(u_set)): for _v in range(len(v_set)): if cverts[_u][_v] is not None: # scale from [f_min, f_max] to [0,1] for _c in range(3): cverts[_u][_v][_c] = rinterpolate(bounds[_c][0], bounds[_c][1], cverts[_u][_v][_c]) # apply gradient cverts[_u][_v] = self.gradient(*cverts[_u][_v]) if callable(inc_pos): inc_pos() return cverts def str_base(self): return ", ".join(str(a) for a in self.args) def __repr__(self): return "%s" % (self.str_base()) x, y, z, t, u, v = symbols('x,y,z,t,u,v') default_color_schemes['rainbow'] = ColorScheme(z, y, x) default_color_schemes['zfade'] = ColorScheme(z, (0.4, 0.4, 0.97), (0.97, 0.4, 0.4), (None, None, z)) default_color_schemes['zfade3'] = ColorScheme(z, (None, None, z), [0.00, (0.2, 0.2, 1.0), 0.35, (0.2, 0.8, 0.4), 0.50, (0.3, 0.9, 0.3), 0.65, (0.4, 0.8, 0.2), 1.00, (1.0, 0.2, 0.2)]) default_color_schemes['zfade4'] = ColorScheme(z, (None, None, z), [0.0, (0.3, 0.3, 1.0), 0.30, (0.3, 1.0, 0.3), 0.55, (0.95, 1.0, 0.2), 0.65, (1.0, 0.95, 0.2), 0.85, (1.0, 0.7, 0.2), 1.0, (1.0, 0.3, 0.2)])
768aabdb0c67ac40f83090e5931434ec616f69a817dfa1d46fbee5cbfbc8b8a4
from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.core.numbers import Integer class PlotInterval: """ """ _v, _v_min, _v_max, _v_steps = None, None, None, None def require_all_args(f): def check(self, *args, **kwargs): for g in [self._v, self._v_min, self._v_max, self._v_steps]: if g is None: raise ValueError("PlotInterval is incomplete.") return f(self, *args, **kwargs) return check def __init__(self, *args): if len(args) == 1: if isinstance(args[0], PlotInterval): self.fill_from(args[0]) return elif isinstance(args[0], str): try: args = eval(args[0]) except TypeError: s_eval_error = "Could not interpret string %s." raise ValueError(s_eval_error % (args[0])) elif isinstance(args[0], (tuple, list)): args = args[0] else: raise ValueError("Not an interval.") if not isinstance(args, (tuple, list)) or len(args) > 4: f_error = "PlotInterval must be a tuple or list of length 4 or less." raise ValueError(f_error) args = list(args) if len(args) > 0 and (args[0] is None or isinstance(args[0], Symbol)): self.v = args.pop(0) if len(args) in [2, 3]: self.v_min = args.pop(0) self.v_max = args.pop(0) if len(args) == 1: self.v_steps = args.pop(0) elif len(args) == 1: self.v_steps = args.pop(0) def get_v(self): return self._v def set_v(self, v): if v is None: self._v = None return if not isinstance(v, Symbol): raise ValueError("v must be a SymPy Symbol.") self._v = v def get_v_min(self): return self._v_min def set_v_min(self, v_min): if v_min is None: self._v_min = None return try: self._v_min = sympify(v_min) float(self._v_min.evalf()) except TypeError: raise ValueError("v_min could not be interpreted as a number.") def get_v_max(self): return self._v_max def set_v_max(self, v_max): if v_max is None: self._v_max = None return try: self._v_max = sympify(v_max) float(self._v_max.evalf()) except TypeError: raise ValueError("v_max could not be interpreted as a number.") def get_v_steps(self): return self._v_steps def set_v_steps(self, v_steps): if v_steps is None: self._v_steps = None return if isinstance(v_steps, int): v_steps = Integer(v_steps) elif not isinstance(v_steps, Integer): raise ValueError("v_steps must be an int or SymPy Integer.") if v_steps <= S.Zero: raise ValueError("v_steps must be positive.") self._v_steps = v_steps @require_all_args def get_v_len(self): return self.v_steps + 1 v = property(get_v, set_v) v_min = property(get_v_min, set_v_min) v_max = property(get_v_max, set_v_max) v_steps = property(get_v_steps, set_v_steps) v_len = property(get_v_len) def fill_from(self, b): if b.v is not None: self.v = b.v if b.v_min is not None: self.v_min = b.v_min if b.v_max is not None: self.v_max = b.v_max if b.v_steps is not None: self.v_steps = b.v_steps @staticmethod def try_parse(*args): """ Returns a PlotInterval if args can be interpreted as such, otherwise None. """ if len(args) == 1 and isinstance(args[0], PlotInterval): return args[0] try: return PlotInterval(*args) except ValueError: return None def _str_base(self): return ",".join([str(self.v), str(self.v_min), str(self.v_max), str(self.v_steps)]) def __repr__(self): """ A string representing the interval in class constructor form. """ return "PlotInterval(%s)" % (self._str_base()) def __str__(self): """ A string representing the interval in list form. """ return "[%s]" % (self._str_base()) @require_all_args def assert_complete(self): pass @require_all_args def vrange(self): """ Yields v_steps+1 SymPy numbers ranging from v_min to v_max. """ d = (self.v_max - self.v_min) / self.v_steps for i in range(self.v_steps + 1): a = self.v_min + (d * Integer(i)) yield a @require_all_args def vrange2(self): """ Yields v_steps pairs of SymPy numbers ranging from (v_min, v_min + step) to (v_max - step, v_max). """ d = (self.v_max - self.v_min) / self.v_steps a = self.v_min + (d * S.Zero) for i in range(self.v_steps): b = self.v_min + (d * Integer(i + 1)) yield a, b a = b def frange(self): for i in self.vrange(): yield float(i.evalf())
80acc94a1cfa3976ba10729aafc4ae1d6ac42d5ce7c60fecd9de480509247981
from sympy.utilities.lambdify import lambdify from sympy.core.numbers import pi from sympy.functions import sin, cos from sympy.plotting.pygletplot.plot_curve import PlotCurve from sympy.plotting.pygletplot.plot_surface import PlotSurface from math import sin as p_sin from math import cos as p_cos def float_vec3(f): def inner(*args): v = f(*args) return float(v[0]), float(v[1]), float(v[2]) return inner class Cartesian2D(PlotCurve): i_vars, d_vars = 'x', 'y' intervals = [[-5, 5, 100]] aliases = ['cartesian'] is_default = True def _get_sympy_evaluator(self): fy = self.d_vars[0] x = self.t_interval.v @float_vec3 def e(_x): return (_x, fy.subs(x, _x), 0.0) return e def _get_lambda_evaluator(self): fy = self.d_vars[0] x = self.t_interval.v return lambdify([x], [x, fy, 0.0]) class Cartesian3D(PlotSurface): i_vars, d_vars = 'xy', 'z' intervals = [[-1, 1, 40], [-1, 1, 40]] aliases = ['cartesian', 'monge'] is_default = True def _get_sympy_evaluator(self): fz = self.d_vars[0] x = self.u_interval.v y = self.v_interval.v @float_vec3 def e(_x, _y): return (_x, _y, fz.subs(x, _x).subs(y, _y)) return e def _get_lambda_evaluator(self): fz = self.d_vars[0] x = self.u_interval.v y = self.v_interval.v return lambdify([x, y], [x, y, fz]) class ParametricCurve2D(PlotCurve): i_vars, d_vars = 't', 'xy' intervals = [[0, 2*pi, 100]] aliases = ['parametric'] is_default = True def _get_sympy_evaluator(self): fx, fy = self.d_vars t = self.t_interval.v @float_vec3 def e(_t): return (fx.subs(t, _t), fy.subs(t, _t), 0.0) return e def _get_lambda_evaluator(self): fx, fy = self.d_vars t = self.t_interval.v return lambdify([t], [fx, fy, 0.0]) class ParametricCurve3D(PlotCurve): i_vars, d_vars = 't', 'xyz' intervals = [[0, 2*pi, 100]] aliases = ['parametric'] is_default = True def _get_sympy_evaluator(self): fx, fy, fz = self.d_vars t = self.t_interval.v @float_vec3 def e(_t): return (fx.subs(t, _t), fy.subs(t, _t), fz.subs(t, _t)) return e def _get_lambda_evaluator(self): fx, fy, fz = self.d_vars t = self.t_interval.v return lambdify([t], [fx, fy, fz]) class ParametricSurface(PlotSurface): i_vars, d_vars = 'uv', 'xyz' intervals = [[-1, 1, 40], [-1, 1, 40]] aliases = ['parametric'] is_default = True def _get_sympy_evaluator(self): fx, fy, fz = self.d_vars u = self.u_interval.v v = self.v_interval.v @float_vec3 def e(_u, _v): return (fx.subs(u, _u).subs(v, _v), fy.subs(u, _u).subs(v, _v), fz.subs(u, _u).subs(v, _v)) return e def _get_lambda_evaluator(self): fx, fy, fz = self.d_vars u = self.u_interval.v v = self.v_interval.v return lambdify([u, v], [fx, fy, fz]) class Polar(PlotCurve): i_vars, d_vars = 't', 'r' intervals = [[0, 2*pi, 100]] aliases = ['polar'] is_default = False def _get_sympy_evaluator(self): fr = self.d_vars[0] t = self.t_interval.v def e(_t): _r = float(fr.subs(t, _t)) return (_r*p_cos(_t), _r*p_sin(_t), 0.0) return e def _get_lambda_evaluator(self): fr = self.d_vars[0] t = self.t_interval.v fx, fy = fr*cos(t), fr*sin(t) return lambdify([t], [fx, fy, 0.0]) class Cylindrical(PlotSurface): i_vars, d_vars = 'th', 'r' intervals = [[0, 2*pi, 40], [-1, 1, 20]] aliases = ['cylindrical', 'polar'] is_default = False def _get_sympy_evaluator(self): fr = self.d_vars[0] t = self.u_interval.v h = self.v_interval.v def e(_t, _h): _r = float(fr.subs(t, _t).subs(h, _h)) return (_r*p_cos(_t), _r*p_sin(_t), _h) return e def _get_lambda_evaluator(self): fr = self.d_vars[0] t = self.u_interval.v h = self.v_interval.v fx, fy = fr*cos(t), fr*sin(t) return lambdify([t, h], [fx, fy, h]) class Spherical(PlotSurface): i_vars, d_vars = 'tp', 'r' intervals = [[0, 2*pi, 40], [0, pi, 20]] aliases = ['spherical'] is_default = False def _get_sympy_evaluator(self): fr = self.d_vars[0] t = self.u_interval.v p = self.v_interval.v def e(_t, _p): _r = float(fr.subs(t, _t).subs(p, _p)) return (_r*p_cos(_t)*p_sin(_p), _r*p_sin(_t)*p_sin(_p), _r*p_cos(_p)) return e def _get_lambda_evaluator(self): fr = self.d_vars[0] t = self.u_interval.v p = self.v_interval.v fx = fr * cos(t) * sin(p) fy = fr * sin(t) * sin(p) fz = fr * cos(p) return lambdify([t, p], [fx, fy, fz]) Cartesian2D._register() Cartesian3D._register() ParametricCurve2D._register() ParametricCurve3D._register() ParametricSurface._register() Polar._register() Cylindrical._register() Spherical._register()
d758d221b274ffeaabf99f352551579b9e30e828c7b035967e0050400ba91041
try: from ctypes import c_float, c_int, c_double except ImportError: pass import pyglet.gl as pgl from sympy.core import S def get_model_matrix(array_type=c_float, glGetMethod=pgl.glGetFloatv): """ Returns the current modelview matrix. """ m = (array_type*16)() glGetMethod(pgl.GL_MODELVIEW_MATRIX, m) return m def get_projection_matrix(array_type=c_float, glGetMethod=pgl.glGetFloatv): """ Returns the current modelview matrix. """ m = (array_type*16)() glGetMethod(pgl.GL_PROJECTION_MATRIX, m) return m def get_viewport(): """ Returns the current viewport. """ m = (c_int*4)() pgl.glGetIntegerv(pgl.GL_VIEWPORT, m) return m def get_direction_vectors(): m = get_model_matrix() return ((m[0], m[4], m[8]), (m[1], m[5], m[9]), (m[2], m[6], m[10])) def get_view_direction_vectors(): m = get_model_matrix() return ((m[0], m[1], m[2]), (m[4], m[5], m[6]), (m[8], m[9], m[10])) def get_basis_vectors(): return ((1, 0, 0), (0, 1, 0), (0, 0, 1)) def screen_to_model(x, y, z): m = get_model_matrix(c_double, pgl.glGetDoublev) p = get_projection_matrix(c_double, pgl.glGetDoublev) w = get_viewport() mx, my, mz = c_double(), c_double(), c_double() pgl.gluUnProject(x, y, z, m, p, w, mx, my, mz) return float(mx.value), float(my.value), float(mz.value) def model_to_screen(x, y, z): m = get_model_matrix(c_double, pgl.glGetDoublev) p = get_projection_matrix(c_double, pgl.glGetDoublev) w = get_viewport() mx, my, mz = c_double(), c_double(), c_double() pgl.gluProject(x, y, z, m, p, w, mx, my, mz) return float(mx.value), float(my.value), float(mz.value) def vec_subs(a, b): return tuple(a[i] - b[i] for i in range(len(a))) def billboard_matrix(): """ Removes rotational components of current matrix so that primitives are always drawn facing the viewer. |1|0|0|x| |0|1|0|x| |0|0|1|x| (x means left unchanged) |x|x|x|x| """ m = get_model_matrix() # XXX: for i in range(11): m[i] = i ? m[0] = 1 m[1] = 0 m[2] = 0 m[4] = 0 m[5] = 1 m[6] = 0 m[8] = 0 m[9] = 0 m[10] = 1 pgl.glLoadMatrixf(m) def create_bounds(): return [[S.Infinity, S.NegativeInfinity, 0], [S.Infinity, S.NegativeInfinity, 0], [S.Infinity, S.NegativeInfinity, 0]] def update_bounds(b, v): if v is None: return for axis in range(3): b[axis][0] = min([b[axis][0], v[axis]]) b[axis][1] = max([b[axis][1], v[axis]]) def interpolate(a_min, a_max, a_ratio): return a_min + a_ratio * (a_max - a_min) def rinterpolate(a_min, a_max, a_value): a_range = a_max - a_min if a_max == a_min: a_range = 1.0 return (a_value - a_min) / float(a_range) def interpolate_color(color1, color2, ratio): return tuple(interpolate(color1[i], color2[i], ratio) for i in range(3)) def scale_value(v, v_min, v_len): return (v - v_min) / v_len def scale_value_list(flist): v_min, v_max = min(flist), max(flist) v_len = v_max - v_min return list(scale_value(f, v_min, v_len) for f in flist) def strided_range(r_min, r_max, stride, max_steps=50): o_min, o_max = r_min, r_max if abs(r_min - r_max) < 0.001: return [] try: range(int(r_min - r_max)) except (TypeError, OverflowError): return [] if r_min > r_max: raise ValueError("r_min cannot be greater than r_max") r_min_s = (r_min % stride) r_max_s = stride - (r_max % stride) if abs(r_max_s - stride) < 0.001: r_max_s = 0.0 r_min -= r_min_s r_max += r_max_s r_steps = int((r_max - r_min)/stride) if max_steps and r_steps > max_steps: return strided_range(o_min, o_max, stride*2) return [r_min] + list(r_min + e*stride for e in range(1, r_steps + 1)) + [r_max] def parse_option_string(s): if not isinstance(s, str): return None options = {} for token in s.split(';'): pieces = token.split('=') if len(pieces) == 1: option, value = pieces[0], "" elif len(pieces) == 2: option, value = pieces else: raise ValueError("Plot option string '%s' is malformed." % (s)) options[option.strip()] = value.strip() return options def dot_product(v1, v2): return sum(v1[i]*v2[i] for i in range(3)) def vec_sub(v1, v2): return tuple(v1[i] - v2[i] for i in range(3)) def vec_mag(v): return sum(v[i]**2 for i in range(3))**(0.5)
137a3927d8a9be20bb2b145f108109657b46ce6869b85d2b3e27b49e4a0871df
from time import perf_counter import pyglet.gl as pgl from sympy.plotting.pygletplot.managed_window import ManagedWindow from sympy.plotting.pygletplot.plot_camera import PlotCamera from sympy.plotting.pygletplot.plot_controller import PlotController class PlotWindow(ManagedWindow): def __init__(self, plot, antialiasing=True, ortho=False, invert_mouse_zoom=False, linewidth=1.5, caption="SymPy Plot", **kwargs): """ Named Arguments =============== antialiasing = True True OR False ortho = False True OR False invert_mouse_zoom = False True OR False """ self.plot = plot self.camera = None self._calculating = False self.antialiasing = antialiasing self.ortho = ortho self.invert_mouse_zoom = invert_mouse_zoom self.linewidth = linewidth self.title = caption self.last_caption_update = 0 self.caption_update_interval = 0.2 self.drawing_first_object = True super().__init__(**kwargs) def setup(self): self.camera = PlotCamera(self, ortho=self.ortho) self.controller = PlotController(self, invert_mouse_zoom=self.invert_mouse_zoom) self.push_handlers(self.controller) pgl.glClearColor(1.0, 1.0, 1.0, 0.0) pgl.glClearDepth(1.0) pgl.glDepthFunc(pgl.GL_LESS) pgl.glEnable(pgl.GL_DEPTH_TEST) pgl.glEnable(pgl.GL_LINE_SMOOTH) pgl.glShadeModel(pgl.GL_SMOOTH) pgl.glLineWidth(self.linewidth) pgl.glEnable(pgl.GL_BLEND) pgl.glBlendFunc(pgl.GL_SRC_ALPHA, pgl.GL_ONE_MINUS_SRC_ALPHA) if self.antialiasing: pgl.glHint(pgl.GL_LINE_SMOOTH_HINT, pgl.GL_NICEST) pgl.glHint(pgl.GL_POLYGON_SMOOTH_HINT, pgl.GL_NICEST) self.camera.setup_projection() def on_resize(self, w, h): super().on_resize(w, h) if self.camera is not None: self.camera.setup_projection() def update(self, dt): self.controller.update(dt) def draw(self): self.plot._render_lock.acquire() self.camera.apply_transformation() calc_verts_pos, calc_verts_len = 0, 0 calc_cverts_pos, calc_cverts_len = 0, 0 should_update_caption = (perf_counter() - self.last_caption_update > self.caption_update_interval) if len(self.plot._functions.values()) == 0: self.drawing_first_object = True try: dict.iteritems except AttributeError: # Python 3 iterfunctions = iter(self.plot._functions.values()) else: # Python 2 iterfunctions = self.plot._functions.itervalues() for r in iterfunctions: if self.drawing_first_object: self.camera.set_rot_preset(r.default_rot_preset) self.drawing_first_object = False pgl.glPushMatrix() r._draw() pgl.glPopMatrix() # might as well do this while we are # iterating and have the lock rather # than locking and iterating twice # per frame: if should_update_caption: try: if r.calculating_verts: calc_verts_pos += r.calculating_verts_pos calc_verts_len += r.calculating_verts_len if r.calculating_cverts: calc_cverts_pos += r.calculating_cverts_pos calc_cverts_len += r.calculating_cverts_len except ValueError: pass for r in self.plot._pobjects: pgl.glPushMatrix() r._draw() pgl.glPopMatrix() if should_update_caption: self.update_caption(calc_verts_pos, calc_verts_len, calc_cverts_pos, calc_cverts_len) self.last_caption_update = perf_counter() if self.plot._screenshot: self.plot._screenshot._execute_saving() self.plot._render_lock.release() def update_caption(self, calc_verts_pos, calc_verts_len, calc_cverts_pos, calc_cverts_len): caption = self.title if calc_verts_len or calc_cverts_len: caption += " (calculating" if calc_verts_len > 0: p = (calc_verts_pos / calc_verts_len) * 100 caption += " vertices %i%%" % (p) if calc_cverts_len > 0: p = (calc_cverts_pos / calc_cverts_len) * 100 caption += " colors %i%%" % (p) caption += ")" if self.caption != caption: self.set_caption(caption)
43d60df16d077753de7e51cbbcebd267e87178b5382aade75052d80c2d31d04f
import pyglet.gl as pgl from pyglet import font from sympy.core import S from sympy.plotting.pygletplot.plot_object import PlotObject from sympy.plotting.pygletplot.util import billboard_matrix, dot_product, \ get_direction_vectors, strided_range, vec_mag, vec_sub from sympy.utilities.iterables import is_sequence class PlotAxes(PlotObject): def __init__(self, *args, style='', none=None, frame=None, box=None, ordinate=None, stride=0.25, visible='', overlay='', colored='', label_axes='', label_ticks='', tick_length=0.1, font_face='Arial', font_size=28, **kwargs): # initialize style parameter style = style.lower() # allow alias kwargs to override style kwarg if none is not None: style = 'none' if frame is not None: style = 'frame' if box is not None: style = 'box' if ordinate is not None: style = 'ordinate' if style in ['', 'ordinate']: self._render_object = PlotAxesOrdinate(self) elif style in ['frame', 'box']: self._render_object = PlotAxesFrame(self) elif style in ['none']: self._render_object = None else: raise ValueError(("Unrecognized axes style %s.") % (style)) # initialize stride parameter try: stride = eval(stride) except TypeError: pass if is_sequence(stride): if len(stride) != 3: raise ValueError("length should be equal to 3") self._stride = stride else: self._stride = [stride, stride, stride] self._tick_length = float(tick_length) # setup bounding box and ticks self._origin = [0, 0, 0] self.reset_bounding_box() def flexible_boolean(input, default): if input in [True, False]: return input if input in ('f', 'F', 'false', 'False'): return False if input in ('t', 'T', 'true', 'True'): return True return default # initialize remaining parameters self.visible = flexible_boolean(kwargs, True) self._overlay = flexible_boolean(overlay, True) self._colored = flexible_boolean(colored, False) self._label_axes = flexible_boolean(label_axes, False) self._label_ticks = flexible_boolean(label_ticks, True) # setup label font self.font_face = font_face self.font_size = font_size # this is also used to reinit the # font on window close/reopen self.reset_resources() def reset_resources(self): self.label_font = None def reset_bounding_box(self): self._bounding_box = [[None, None], [None, None], [None, None]] self._axis_ticks = [[], [], []] def draw(self): if self._render_object: pgl.glPushAttrib(pgl.GL_ENABLE_BIT | pgl.GL_POLYGON_BIT | pgl.GL_DEPTH_BUFFER_BIT) if self._overlay: pgl.glDisable(pgl.GL_DEPTH_TEST) self._render_object.draw() pgl.glPopAttrib() def adjust_bounds(self, child_bounds): b = self._bounding_box c = child_bounds for i in range(3): if abs(c[i][0]) is S.Infinity or abs(c[i][1]) is S.Infinity: continue b[i][0] = c[i][0] if b[i][0] is None else min([b[i][0], c[i][0]]) b[i][1] = c[i][1] if b[i][1] is None else max([b[i][1], c[i][1]]) self._bounding_box = b self._recalculate_axis_ticks(i) def _recalculate_axis_ticks(self, axis): b = self._bounding_box if b[axis][0] is None or b[axis][1] is None: self._axis_ticks[axis] = [] else: self._axis_ticks[axis] = strided_range(b[axis][0], b[axis][1], self._stride[axis]) def toggle_visible(self): self.visible = not self.visible def toggle_colors(self): self._colored = not self._colored class PlotAxesBase(PlotObject): def __init__(self, parent_axes): self._p = parent_axes def draw(self): color = [([0.2, 0.1, 0.3], [0.2, 0.1, 0.3], [0.2, 0.1, 0.3]), ([0.9, 0.3, 0.5], [0.5, 1.0, 0.5], [0.3, 0.3, 0.9])][self._p._colored] self.draw_background(color) self.draw_axis(2, color[2]) self.draw_axis(1, color[1]) self.draw_axis(0, color[0]) def draw_background(self, color): pass # optional def draw_axis(self, axis, color): raise NotImplementedError() def draw_text(self, text, position, color, scale=1.0): if len(color) == 3: color = (color[0], color[1], color[2], 1.0) if self._p.label_font is None: self._p.label_font = font.load(self._p.font_face, self._p.font_size, bold=True, italic=False) label = font.Text(self._p.label_font, text, color=color, valign=font.Text.BASELINE, halign=font.Text.CENTER) pgl.glPushMatrix() pgl.glTranslatef(*position) billboard_matrix() scale_factor = 0.005 * scale pgl.glScalef(scale_factor, scale_factor, scale_factor) pgl.glColor4f(0, 0, 0, 0) label.draw() pgl.glPopMatrix() def draw_line(self, v, color): o = self._p._origin pgl.glBegin(pgl.GL_LINES) pgl.glColor3f(*color) pgl.glVertex3f(v[0][0] + o[0], v[0][1] + o[1], v[0][2] + o[2]) pgl.glVertex3f(v[1][0] + o[0], v[1][1] + o[1], v[1][2] + o[2]) pgl.glEnd() class PlotAxesOrdinate(PlotAxesBase): def __init__(self, parent_axes): super().__init__(parent_axes) def draw_axis(self, axis, color): ticks = self._p._axis_ticks[axis] radius = self._p._tick_length / 2.0 if len(ticks) < 2: return # calculate the vector for this axis axis_lines = [[0, 0, 0], [0, 0, 0]] axis_lines[0][axis], axis_lines[1][axis] = ticks[0], ticks[-1] axis_vector = vec_sub(axis_lines[1], axis_lines[0]) # calculate angle to the z direction vector pos_z = get_direction_vectors()[2] d = abs(dot_product(axis_vector, pos_z)) d = d / vec_mag(axis_vector) # don't draw labels if we're looking down the axis labels_visible = abs(d - 1.0) > 0.02 # draw the ticks and labels for tick in ticks: self.draw_tick_line(axis, color, radius, tick, labels_visible) # draw the axis line and labels self.draw_axis_line(axis, color, ticks[0], ticks[-1], labels_visible) def draw_axis_line(self, axis, color, a_min, a_max, labels_visible): axis_line = [[0, 0, 0], [0, 0, 0]] axis_line[0][axis], axis_line[1][axis] = a_min, a_max self.draw_line(axis_line, color) if labels_visible: self.draw_axis_line_labels(axis, color, axis_line) def draw_axis_line_labels(self, axis, color, axis_line): if not self._p._label_axes: return axis_labels = [axis_line[0][::], axis_line[1][::]] axis_labels[0][axis] -= 0.3 axis_labels[1][axis] += 0.3 a_str = ['X', 'Y', 'Z'][axis] self.draw_text("-" + a_str, axis_labels[0], color) self.draw_text("+" + a_str, axis_labels[1], color) def draw_tick_line(self, axis, color, radius, tick, labels_visible): tick_axis = {0: 1, 1: 0, 2: 1}[axis] tick_line = [[0, 0, 0], [0, 0, 0]] tick_line[0][axis] = tick_line[1][axis] = tick tick_line[0][tick_axis], tick_line[1][tick_axis] = -radius, radius self.draw_line(tick_line, color) if labels_visible: self.draw_tick_line_label(axis, color, radius, tick) def draw_tick_line_label(self, axis, color, radius, tick): if not self._p._label_axes: return tick_label_vector = [0, 0, 0] tick_label_vector[axis] = tick tick_label_vector[{0: 1, 1: 0, 2: 1}[axis]] = [-1, 1, 1][ axis] * radius * 3.5 self.draw_text(str(tick), tick_label_vector, color, scale=0.5) class PlotAxesFrame(PlotAxesBase): def __init__(self, parent_axes): super().__init__(parent_axes) def draw_background(self, color): pass def draw_axis(self, axis, color): raise NotImplementedError()
3a26e42392348bafcda457751c4978f1dfd1e0f456a1f528392e0761006454e7
""" Interval Arithmetic for plotting. This module does not implement interval arithmetic accurately and hence cannot be used for purposes other than plotting. If you want to use interval arithmetic, use mpmath's interval arithmetic. The module implements interval arithmetic using numpy and python floating points. The rounding up and down is not handled and hence this is not an accurate implementation of interval arithmetic. The module uses numpy for speed which cannot be achieved with mpmath. """ # Q: Why use numpy? Why not simply use mpmath's interval arithmetic? # A: mpmath's interval arithmetic simulates a floating point unit # and hence is slow, while numpy evaluations are orders of magnitude # faster. # Q: Why create a separate class for intervals? Why not use SymPy's # Interval Sets? # A: The functionalities that will be required for plotting is quite # different from what Interval Sets implement. # Q: Why is rounding up and down according to IEEE754 not handled? # A: It is not possible to do it in both numpy and python. An external # library has to used, which defeats the whole purpose i.e., speed. Also # rounding is handled for very few functions in those libraries. # Q Will my plots be affected? # A It will not affect most of the plots. The interval arithmetic # module based suffers the same problems as that of floating point # arithmetic. from sympy.core.logic import fuzzy_and from sympy.simplify.simplify import nsimplify from .interval_membership import intervalMembership class interval: """ Represents an interval containing floating points as start and end of the interval The is_valid variable tracks whether the interval obtained as the result of the function is in the domain and is continuous. - True: Represents the interval result of a function is continuous and in the domain of the function. - False: The interval argument of the function was not in the domain of the function, hence the is_valid of the result interval is False - None: The function was not continuous over the interval or the function's argument interval is partly in the domain of the function A comparison between an interval and a real number, or a comparison between two intervals may return ``intervalMembership`` of two 3-valued logic values. """ def __init__(self, *args, is_valid=True, **kwargs): self.is_valid = is_valid if len(args) == 1: if isinstance(args[0], interval): self.start, self.end = args[0].start, args[0].end else: self.start = float(args[0]) self.end = float(args[0]) elif len(args) == 2: if args[0] < args[1]: self.start = float(args[0]) self.end = float(args[1]) else: self.start = float(args[1]) self.end = float(args[0]) else: raise ValueError("interval takes a maximum of two float values " "as arguments") @property def mid(self): return (self.start + self.end) / 2.0 @property def width(self): return self.end - self.start def __repr__(self): return "interval(%f, %f)" % (self.start, self.end) def __str__(self): return "[%f, %f]" % (self.start, self.end) def __lt__(self, other): if isinstance(other, (int, float)): if self.end < other: return intervalMembership(True, self.is_valid) elif self.start > other: return intervalMembership(False, self.is_valid) else: return intervalMembership(None, self.is_valid) elif isinstance(other, interval): valid = fuzzy_and([self.is_valid, other.is_valid]) if self.end < other. start: return intervalMembership(True, valid) if self.start > other.end: return intervalMembership(False, valid) return intervalMembership(None, valid) else: return NotImplemented def __gt__(self, other): if isinstance(other, (int, float)): if self.start > other: return intervalMembership(True, self.is_valid) elif self.end < other: return intervalMembership(False, self.is_valid) else: return intervalMembership(None, self.is_valid) elif isinstance(other, interval): return other.__lt__(self) else: return NotImplemented def __eq__(self, other): if isinstance(other, (int, float)): if self.start == other and self.end == other: return intervalMembership(True, self.is_valid) if other in self: return intervalMembership(None, self.is_valid) else: return intervalMembership(False, self.is_valid) if isinstance(other, interval): valid = fuzzy_and([self.is_valid, other.is_valid]) if self.start == other.start and self.end == other.end: return intervalMembership(True, valid) elif self.__lt__(other)[0] is not None: return intervalMembership(False, valid) else: return intervalMembership(None, valid) else: return NotImplemented def __ne__(self, other): if isinstance(other, (int, float)): if self.start == other and self.end == other: return intervalMembership(False, self.is_valid) if other in self: return intervalMembership(None, self.is_valid) else: return intervalMembership(True, self.is_valid) if isinstance(other, interval): valid = fuzzy_and([self.is_valid, other.is_valid]) if self.start == other.start and self.end == other.end: return intervalMembership(False, valid) if not self.__lt__(other)[0] is None: return intervalMembership(True, valid) return intervalMembership(None, valid) else: return NotImplemented def __le__(self, other): if isinstance(other, (int, float)): if self.end <= other: return intervalMembership(True, self.is_valid) if self.start > other: return intervalMembership(False, self.is_valid) else: return intervalMembership(None, self.is_valid) if isinstance(other, interval): valid = fuzzy_and([self.is_valid, other.is_valid]) if self.end <= other.start: return intervalMembership(True, valid) if self.start > other.end: return intervalMembership(False, valid) return intervalMembership(None, valid) else: return NotImplemented def __ge__(self, other): if isinstance(other, (int, float)): if self.start >= other: return intervalMembership(True, self.is_valid) elif self.end < other: return intervalMembership(False, self.is_valid) else: return intervalMembership(None, self.is_valid) elif isinstance(other, interval): return other.__le__(self) def __add__(self, other): if isinstance(other, (int, float)): if self.is_valid: return interval(self.start + other, self.end + other) else: start = self.start + other end = self.end + other return interval(start, end, is_valid=self.is_valid) elif isinstance(other, interval): start = self.start + other.start end = self.end + other.end valid = fuzzy_and([self.is_valid, other.is_valid]) return interval(start, end, is_valid=valid) else: return NotImplemented __radd__ = __add__ def __sub__(self, other): if isinstance(other, (int, float)): start = self.start - other end = self.end - other return interval(start, end, is_valid=self.is_valid) elif isinstance(other, interval): start = self.start - other.end end = self.end - other.start valid = fuzzy_and([self.is_valid, other.is_valid]) return interval(start, end, is_valid=valid) else: return NotImplemented def __rsub__(self, other): if isinstance(other, (int, float)): start = other - self.end end = other - self.start return interval(start, end, is_valid=self.is_valid) elif isinstance(other, interval): return other.__sub__(self) else: return NotImplemented def __neg__(self): if self.is_valid: return interval(-self.end, -self.start) else: return interval(-self.end, -self.start, is_valid=self.is_valid) def __mul__(self, other): if isinstance(other, interval): if self.is_valid is False or other.is_valid is False: return interval(-float('inf'), float('inf'), is_valid=False) elif self.is_valid is None or other.is_valid is None: return interval(-float('inf'), float('inf'), is_valid=None) else: inters = [] inters.append(self.start * other.start) inters.append(self.end * other.start) inters.append(self.start * other.end) inters.append(self.end * other.end) start = min(inters) end = max(inters) return interval(start, end) elif isinstance(other, (int, float)): return interval(self.start*other, self.end*other, is_valid=self.is_valid) else: return NotImplemented __rmul__ = __mul__ def __contains__(self, other): if isinstance(other, (int, float)): return self.start <= other and self.end >= other else: return self.start <= other.start and other.end <= self.end def __rtruediv__(self, other): if isinstance(other, (int, float)): other = interval(other) return other.__truediv__(self) elif isinstance(other, interval): return other.__truediv__(self) else: return NotImplemented def __truediv__(self, other): # Both None and False are handled if not self.is_valid: # Don't divide as the value is not valid return interval(-float('inf'), float('inf'), is_valid=self.is_valid) if isinstance(other, (int, float)): if other == 0: # Divide by zero encountered. valid nowhere return interval(-float('inf'), float('inf'), is_valid=False) else: return interval(self.start / other, self.end / other) elif isinstance(other, interval): if other.is_valid is False or self.is_valid is False: return interval(-float('inf'), float('inf'), is_valid=False) elif other.is_valid is None or self.is_valid is None: return interval(-float('inf'), float('inf'), is_valid=None) else: # denominator contains both signs, i.e. being divided by zero # return the whole real line with is_valid = None if 0 in other: return interval(-float('inf'), float('inf'), is_valid=None) # denominator negative this = self if other.end < 0: this = -this other = -other # denominator positive inters = [] inters.append(this.start / other.start) inters.append(this.end / other.start) inters.append(this.start / other.end) inters.append(this.end / other.end) start = max(inters) end = min(inters) return interval(start, end) else: return NotImplemented def __pow__(self, other): # Implements only power to an integer. from .lib_interval import exp, log if not self.is_valid: return self if isinstance(other, interval): return exp(other * log(self)) elif isinstance(other, (float, int)): if other < 0: return 1 / self.__pow__(abs(other)) else: if int(other) == other: return _pow_int(self, other) else: return _pow_float(self, other) else: return NotImplemented def __rpow__(self, other): if isinstance(other, (float, int)): if not self.is_valid: #Don't do anything return self elif other < 0: if self.width > 0: return interval(-float('inf'), float('inf'), is_valid=False) else: power_rational = nsimplify(self.start) num, denom = power_rational.as_numer_denom() if denom % 2 == 0: return interval(-float('inf'), float('inf'), is_valid=False) else: start = -abs(other)**self.start end = start return interval(start, end) else: return interval(other**self.start, other**self.end) elif isinstance(other, interval): return other.__pow__(self) else: return NotImplemented def __hash__(self): return hash((self.is_valid, self.start, self.end)) def _pow_float(inter, power): """Evaluates an interval raised to a floating point.""" power_rational = nsimplify(power) num, denom = power_rational.as_numer_denom() if num % 2 == 0: start = abs(inter.start)**power end = abs(inter.end)**power if start < 0: ret = interval(0, max(start, end)) else: ret = interval(start, end) return ret elif denom % 2 == 0: if inter.end < 0: return interval(-float('inf'), float('inf'), is_valid=False) elif inter.start < 0: return interval(0, inter.end**power, is_valid=None) else: return interval(inter.start**power, inter.end**power) else: if inter.start < 0: start = -abs(inter.start)**power else: start = inter.start**power if inter.end < 0: end = -abs(inter.end)**power else: end = inter.end**power return interval(start, end, is_valid=inter.is_valid) def _pow_int(inter, power): """Evaluates an interval raised to an integer power""" power = int(power) if power & 1: return interval(inter.start**power, inter.end**power) else: if inter.start < 0 and inter.end > 0: start = 0 end = max(inter.start**power, inter.end**power) return interval(start, end) else: return interval(inter.start**power, inter.end**power)
362b2347ecae05125f42f8dc6f6d2c913477ca27765373212875bab32f11135d
from sympy.external.importtools import import_module disabled = False # if pyglet.gl fails to import, e.g. opengl is missing, we disable the tests pyglet_gl = import_module("pyglet.gl", catch=(OSError,)) pyglet_window = import_module("pyglet.window", catch=(OSError,)) if not pyglet_gl or not pyglet_window: disabled = True from sympy.core.symbol import symbols from sympy.functions.elementary.exponential import log from sympy.functions.elementary.trigonometric import (cos, sin) x, y, z = symbols('x, y, z') def test_plot_2d(): from sympy.plotting.pygletplot import PygletPlot p = PygletPlot(x, [x, -5, 5, 4], visible=False) p.wait_for_calculations() def test_plot_2d_discontinuous(): from sympy.plotting.pygletplot import PygletPlot p = PygletPlot(1/x, [x, -1, 1, 2], visible=False) p.wait_for_calculations() def test_plot_3d(): from sympy.plotting.pygletplot import PygletPlot p = PygletPlot(x*y, [x, -5, 5, 5], [y, -5, 5, 5], visible=False) p.wait_for_calculations() def test_plot_3d_discontinuous(): from sympy.plotting.pygletplot import PygletPlot p = PygletPlot(1/x, [x, -3, 3, 6], [y, -1, 1, 1], visible=False) p.wait_for_calculations() def test_plot_2d_polar(): from sympy.plotting.pygletplot import PygletPlot p = PygletPlot(1/x, [x, -1, 1, 4], 'mode=polar', visible=False) p.wait_for_calculations() def test_plot_3d_cylinder(): from sympy.plotting.pygletplot import PygletPlot p = PygletPlot( 1/y, [x, 0, 6.282, 4], [y, -1, 1, 4], 'mode=polar;style=solid', visible=False) p.wait_for_calculations() def test_plot_3d_spherical(): from sympy.plotting.pygletplot import PygletPlot p = PygletPlot( 1, [x, 0, 6.282, 4], [y, 0, 3.141, 4], 'mode=spherical;style=wireframe', visible=False) p.wait_for_calculations() def test_plot_2d_parametric(): from sympy.plotting.pygletplot import PygletPlot p = PygletPlot(sin(x), cos(x), [x, 0, 6.282, 4], visible=False) p.wait_for_calculations() def test_plot_3d_parametric(): from sympy.plotting.pygletplot import PygletPlot p = PygletPlot(sin(x), cos(x), x/5.0, [x, 0, 6.282, 4], visible=False) p.wait_for_calculations() def _test_plot_log(): from sympy.plotting.pygletplot import PygletPlot p = PygletPlot(log(x), [x, 0, 6.282, 4], 'mode=polar', visible=False) p.wait_for_calculations() def test_plot_integral(): # Make sure it doesn't treat x as an independent variable from sympy.plotting.pygletplot import PygletPlot from sympy.integrals.integrals import Integral p = PygletPlot(Integral(z*x, (x, 1, z), (z, 1, y)), visible=False) p.wait_for_calculations()
59b070b94af577832ebd36e5bf85a4ec5927d70ce0e303f501227ac72efd9e01
#!/usr/bin/env python3 import os from os.path import dirname, join, basename, normpath from os import chdir import shutil from helpers import run ROOTDIR = dirname(dirname(__file__)) DOCSDIR = join(ROOTDIR, 'doc') def main(version, outputdir): os.makedirs(outputdir, exist_ok=True) build_html(DOCSDIR, outputdir, version) build_latex(DOCSDIR, outputdir, version) def build_html(docsdir, outputdir, version): run('make', 'clean', cwd=docsdir) run('make', 'html', cwd=docsdir) builddir = join(docsdir, '_build') docsname = 'sympy-docs-html-%s' % (version,) zipname = docsname + '.zip' cwd = os.getcwd() try: chdir(builddir) shutil.move('html', docsname) run('zip', '-9lr', zipname, docsname) finally: chdir(cwd) shutil.move(join(builddir, zipname), join(outputdir, zipname)) def build_latex(docsdir, outputdir, version): run('make', 'clean', cwd=docsdir) run('make', 'latexpdf', cwd=docsdir) srcfilename = 'sympy-%s.pdf' % (version,) dstfilename = 'sympy-docs-pdf-%s.pdf' % (version,) src = join('doc', '_build', 'latex', srcfilename) dst = join(outputdir, dstfilename) shutil.copyfile(src, dst) if __name__ == "__main__": import sys main(*sys.argv[1:])
4dd6f1f61276ea1f60f6dc8beb1a04c8c25559512f003152952b586fd6ad23c4
""" 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, 7): raise ImportError("Python version 3.7 or above is required for SymPy.") del sys try: import mpmath except ImportError: raise ImportError("SymPy now depends on mpmath as an external library. " "See https://docs.sympy.org/latest/install.html#mpmath for more information.") del mpmath from sympy.release import __version__ if 'dev' in __version__: def enable_warnings(): import warnings warnings.filterwarnings('default', '.*', DeprecationWarning, module='sympy.*') del warnings enable_warnings() del enable_warnings def __sympy_debug(): # helper function so we don't import os globally import os debug_str = os.getenv('SYMPY_DEBUG', 'False') if debug_str in ('True', 'False'): return eval(debug_str) else: raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" % debug_str) SYMPY_DEBUG = __sympy_debug() # type: bool from .core import (sympify, SympifyError, cacheit, Basic, Atom, preorder_traversal, S, Expr, AtomicExpr, UnevaluatedExpr, Symbol, Wild, Dummy, symbols, var, Number, Float, Rational, Integer, NumberSymbol, RealNumber, igcd, ilcm, seterr, E, I, nan, oo, pi, zoo, AlgebraicNumber, comp, mod_inverse, Pow, integer_nthroot, integer_log, Mul, prod, Add, Mod, Rel, Eq, Ne, Lt, Le, Gt, Ge, Equality, GreaterThan, LessThan, Unequality, StrictGreaterThan, StrictLessThan, vectorize, Lambda, WildFunction, Derivative, diff, FunctionClass, Function, Subs, expand, PoleError, count_ops, expand_mul, expand_log, expand_func, expand_trig, expand_complex, expand_multinomial, nfloat, expand_power_base, expand_power_exp, arity, PrecisionExhausted, N, evalf, Tuple, Dict, gcd_terms, factor_terms, factor_nc, evaluate, Catalan, EulerGamma, GoldenRatio, TribonacciConstant, 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, legendre_poly, laguerre_poly, apart, apart_list, assemble_partfrac_list, Options, ring, xring, vring, sring, field, xfield, vfield, sfield) from .series import (Order, O, limit, Limit, gruntz, series, approximants, residue, EmptySequence, SeqPer, SeqFormula, sequence, SeqAdd, SeqMul, fourier_series, fps, difference_delta, limit_seq) from .functions import (factorial, factorial2, rf, ff, binomial, RisingFactorial, FallingFactorial, subfactorial, carmichael, fibonacci, lucas, motzkin, tribonacci, harmonic, bernoulli, bell, euler, catalan, genocchi, partition, sqrt, root, Min, Max, Id, real_root, 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, erf, erfc, erfi, erf2, erfinv, erfcinv, erf2inv, Ei, expint, E1, li, Li, Si, Ci, Shi, Chi, fresnels, fresnelc, gamma, lowergamma, uppergamma, polygamma, loggamma, digamma, trigamma, multigamma, dirichlet_eta, zeta, lerchphi, polylog, stieltjes, Eijk, LeviCivita, KroneckerDelta, SingularityFunction, DiracDelta, Heaviside, bspline_basis, bspline_basis_set, interpolating_spline, besselj, bessely, besseli, besselk, hankel1, hankel2, jn, yn, jn_zeros, hn1, hn2, airyai, airybi, airyaiprime, airybiprime, marcumq, hyper, meijerg, appellf1, legendre, assoc_legendre, hermite, chebyshevt, chebyshevu, chebyshevu_root, chebyshevt_root, laguerre, assoc_laguerre, gegenbauer, jacobi, jacobi_normalized, Ynm, Ynm_c, Znm, elliptic_k, elliptic_f, elliptic_e, elliptic_pi, beta, mathieus, mathieuc, mathieusprime, mathieucprime, 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) 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, source, threaded, xthreaded, public, memoize_property, timed) from .integrals import (integrate, Integral, line_integrate, mellin_transform, inverse_mellin_transform, MellinTransform, InverseMellinTransform, laplace_transform, inverse_laplace_transform, LaplaceTransform, InverseLaplaceTransform, fourier_transform, inverse_fourier_transform, FourierTransform, InverseFourierTransform, sine_transform, inverse_sine_transform, SineTransform, InverseSineTransform, cosine_transform, inverse_cosine_transform, CosineTransform, InverseCosineTransform, hankel_transform, inverse_hankel_transform, HankelTransform, InverseHankelTransform, singularityintegrate) from .tensor import (IndexedBase, Idx, Indexed, get_contraction_structure, get_indices, shape, MutableDenseNDimArray, ImmutableDenseNDimArray, MutableSparseNDimArray, ImmutableSparseNDimArray, NDimArray, tensorproduct, tensorcontraction, tensordiagonal, derive_by_array, permutedims, Array, DenseNDimArray, SparseNDimArray) from .parsing import parse_expr from .calculus import (euler_equations, singularities, is_increasing, is_strictly_increasing, is_decreasing, is_strictly_decreasing, is_monotonic, finite_diff_weights, apply_finite_diff, as_finite_diff, differentiate_finite, periodicity, not_empty_in, AccumBounds, is_convex, stationary_points, minimum, maximum) from .algebras import Quaternion from .printing import (pager_print, pretty, pretty_print, pprint, pprint_use_unicode, pprint_try_use_unicode, latex, print_latex, multiline_latex, mathml, print_mathml, python, print_python, pycode, ccode, print_ccode, glsl_code, print_glsl, cxxcode, fcode, print_fcode, rcode, print_rcode, jscode, print_jscode, julia_code, mathematica_code, octave_code, rust_code, print_gtk, preview, srepr, print_tree, StrPrinter, sstr, sstrrepr, TableForm, dotprint, maple_code, print_maple_code) from .testing import test, doctest # This module causes conflicts with other modules: # from .stats import * # Adds about .04-.05 seconds of import time # from combinatorics import * # This module is slow to import: #from physics import units from .plotting import plot, textplot, plot_backends, plot_implicit, plot_parametric from .interactive import init_session, init_printing, interactive_traversal evalf._create_evalf_table() __all__ = [ # sympy.core 'sympify', 'SympifyError', 'cacheit', 'Basic', 'Atom', 'preorder_traversal', 'S', 'Expr', 'AtomicExpr', 'UnevaluatedExpr', 'Symbol', 'Wild', 'Dummy', 'symbols', 'var', 'Number', 'Float', 'Rational', 'Integer', 'NumberSymbol', 'RealNumber', 'igcd', 'ilcm', 'seterr', 'E', 'I', 'nan', 'oo', 'pi', 'zoo', 'AlgebraicNumber', 'comp', 'mod_inverse', 'Pow', 'integer_nthroot', 'integer_log', 'Mul', 'prod', 'Add', 'Mod', 'Rel', 'Eq', 'Ne', 'Lt', 'Le', 'Gt', 'Ge', 'Equality', 'GreaterThan', 'LessThan', 'Unequality', 'StrictGreaterThan', 'StrictLessThan', 'vectorize', 'Lambda', 'WildFunction', 'Derivative', 'diff', 'FunctionClass', 'Function', 'Subs', 'expand', 'PoleError', 'count_ops', 'expand_mul', 'expand_log', 'expand_func', 'expand_trig', 'expand_complex', 'expand_multinomial', 'nfloat', 'expand_power_base', 'expand_power_exp', 'arity', 'PrecisionExhausted', 'N', 'evalf', 'Tuple', 'Dict', 'gcd_terms', 'factor_terms', 'factor_nc', 'evaluate', 'Catalan', 'EulerGamma', 'GoldenRatio', 'TribonacciConstant', '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', 'legendre_poly', 'laguerre_poly', 'apart', 'apart_list', 'assemble_partfrac_list', 'Options', 'ring', 'xring', 'vring', 'sring', 'field', 'xfield', 'vfield', 'sfield', # sympy.series 'Order', 'O', 'limit', 'Limit', 'gruntz', 'series', 'approximants', 'residue', 'EmptySequence', 'SeqPer', 'SeqFormula', 'sequence', 'SeqAdd', 'SeqMul', 'fourier_series', 'fps', 'difference_delta', 'limit_seq', # sympy.functions 'factorial', 'factorial2', 'rf', 'ff', 'binomial', 'RisingFactorial', 'FallingFactorial', 'subfactorial', 'carmichael', 'fibonacci', 'lucas', 'motzkin', 'tribonacci', 'harmonic', 'bernoulli', 'bell', 'euler', 'catalan', 'genocchi', 'partition', 'sqrt', 'root', 'Min', 'Max', 'Id', 'real_root', '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', 'erf', 'erfc', 'erfi', 'erf2', 'erfinv', 'erfcinv', 'erf2inv', 'Ei', 'expint', 'E1', 'li', 'Li', 'Si', 'Ci', 'Shi', 'Chi', 'fresnels', 'fresnelc', 'gamma', 'lowergamma', 'uppergamma', 'polygamma', 'loggamma', 'digamma', 'trigamma', 'multigamma', 'dirichlet_eta', 'zeta', 'lerchphi', 'polylog', 'stieltjes', 'Eijk', 'LeviCivita', 'KroneckerDelta', 'SingularityFunction', 'DiracDelta', 'Heaviside', 'bspline_basis', 'bspline_basis_set', 'interpolating_spline', 'besselj', 'bessely', 'besseli', 'besselk', 'hankel1', 'hankel2', 'jn', 'yn', 'jn_zeros', 'hn1', 'hn2', 'airyai', 'airybi', 'airyaiprime', 'airybiprime', 'marcumq', 'hyper', 'meijerg', 'appellf1', 'legendre', 'assoc_legendre', 'hermite', 'chebyshevt', 'chebyshevu', 'chebyshevu_root', 'chebyshevt_root', 'laguerre', 'assoc_laguerre', 'gegenbauer', 'jacobi', 'jacobi_normalized', 'Ynm', 'Ynm_c', 'Znm', 'elliptic_k', 'elliptic_f', 'elliptic_e', 'elliptic_pi', 'beta', 'mathieus', 'mathieuc', 'mathieusprime', 'mathieucprime', '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', # 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', 'source', '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', 'as_finite_diff', 'differentiate_finite', 'periodicity', 'not_empty_in', 'AccumBounds', 'is_convex', 'stationary_points', 'minimum', 'maximum', # sympy.algebras 'Quaternion', # sympy.printing 'pager_print', 'pretty', 'pretty_print', 'pprint', 'pprint_use_unicode', 'pprint_try_use_unicode', 'latex', 'print_latex', 'multiline_latex', 'mathml', 'print_mathml', 'python', 'print_python', 'pycode', 'ccode', 'print_ccode', 'glsl_code', 'print_glsl', 'cxxcode', 'fcode', 'print_fcode', 'rcode', 'print_rcode', 'jscode', 'print_jscode', 'julia_code', 'mathematica_code', 'octave_code', 'rust_code', 'print_gtk', 'preview', 'srepr', 'print_tree', 'StrPrinter', 'sstr', 'sstrrepr', 'TableForm', 'dotprint', 'maple_code', 'print_maple_code', # sympy.plotting 'plot', 'textplot', 'plot_backends', 'plot_implicit', 'plot_parametric', # sympy.interactive 'init_session', 'init_printing', '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', ))
5fbb51697e7257cd5d787d6d7ed090013f5e88136eea71242dc280a36d235efe
# # SymPy documentation build configuration file, created by # sphinx-quickstart.py on Sat Mar 22 19:34:32 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). # # All configuration values have a default value; values that are commented out # serve to show the default value. import sys import inspect import os import subprocess from datetime import datetime # Make sure we import sympy from git sys.path.insert(0, os.path.abspath('../..')) import sympy # If your extensions are in another directory, add it here. sys.path = ['ext'] + sys.path # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.addons.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.linkcode', 'sphinx_math_dollar', 'sphinx.ext.mathjax', 'numpydoc', 'sympylive', 'sphinx_reredirects', 'sphinx.ext.graphviz', 'matplotlib.sphinxext.plot_directive', 'myst_parser' ] redirects = { "install.rst": "guides/getting_started/install.html", "documentation-style-guide.rst": "guides/contributing/documentation-style-guide.html", "gotchas.rst": "explanation/gotchas.html", "special_topics/classification.rst": "explanation/classification.html", "special_topics/finite_diff_derivatives.rst": "explanation/finite_diff_derivatives.html", "special_topics/intro.rst": "explanation/index.html", "special_topics/index.rst": "explanation/index.html", "modules/index.rst": "reference/public/index.html", "modules/physics/index.rst": "reference/physics/index.html", } # Use this to use pngmath instead #extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.pngmath', ] # Enable warnings for all bad cross references. These are turned into errors # with the -W flag in the Makefile. nitpicky = True nitpick_ignore = [ ('py:class', 'sympy.logic.boolalg.Boolean') ] # To stop docstrings inheritance. autodoc_inherit_docstrings = False # See https://www.sympy.org/sphinx-math-dollar/ mathjax3_config = { "tex": { "inlineMath": [['\\(', '\\)']], "displayMath": [["\\[", "\\]"]], } } # Myst configuration (for .md files). See # https://myst-parser.readthedocs.io/en/latest/syntax/optional.html myst_enable_extensions = ["dollarmath", "linkify"] myst_heading_anchors = 2 # myst_update_mathjax = False # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' suppress_warnings = ['ref.citation', 'ref.footnote'] # General substitutions. project = 'SymPy' copyright = '{} SymPy Development Team'.format(datetime.utcnow().year) # The default replacements for |version| and |release|, also used in various # other places throughout the built documents. # # The short X.Y version. version = sympy.__version__ # The full version, including alpha/beta/rc tags. release = version # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # Don't show the source code hyperlinks when using matplotlib plot directive. plot_html_show_source_link = False # Options for HTML output # ----------------------- # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. html_style = 'default.css' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # was classic html_theme = "classic" html_logo = '_static/sympylogo.png' html_favicon = '../_build/logo/sympy-notailtext-favicon.ico' # See http://www.sphinx-doc.org/en/master/theming.html#builtin-themes # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Content template for the index page. #html_index = '' # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True html_domain_indices = ['py-modindex'] # If true, the reST sources are included in the HTML build as _sources/<name>. #html_copy_source = True # Output file base name for HTML help builder. htmlhelp_basename = 'SymPydoc' # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual], toctree_only). # toctree_only is set to True so that the start file document itself is not included in the # output, only the documents referenced by it via TOC trees. The extra stuff in the master # document is intended to show up in the HTML, but doesn't really belong in the LaTeX output. latex_documents = [('index', 'sympy-%s.tex' % release, 'SymPy Documentation', 'SymPy Development Team', 'manual', True)] # Additional stuff for the LaTeX preamble. # Tweaked to work with XeTeX. latex_elements = { 'babel': '', 'fontenc': r''' % Define version of \LaTeX that is usable in math mode \let\OldLaTeX\LaTeX \renewcommand{\LaTeX}{\text{\OldLaTeX}} \usepackage{bm} \usepackage{amssymb} \usepackage{fontspec} \usepackage[english]{babel} \defaultfontfeatures{Mapping=tex-text} \setmainfont{DejaVu Serif} \setsansfont{DejaVu Sans} \setmonofont{DejaVu Sans Mono} ''', 'fontpkg': '', 'inputenc': '', 'utf8extra': '', 'preamble': r''' ''' } # SymPy logo on title page html_logo = '_static/sympylogo.png' latex_logo = '_static/sympylogo_big.png' # Documents to append as an appendix to all manuals. #latex_appendices = [] # Show page numbers next to internal references latex_show_pagerefs = True # We use False otherwise the module index gets generated twice. latex_use_modindex = False default_role = 'math' pngmath_divpng_args = ['-gamma 1.5', '-D 110'] # Note, this is ignored by the mathjax extension # Any \newcommand should be defined in the file pngmath_latex_preamble = '\\usepackage{amsmath}\n' \ '\\usepackage{bm}\n' \ '\\usepackage{amsfonts}\n' \ '\\usepackage{amssymb}\n' \ '\\setlength{\\parindent}{0pt}\n' texinfo_documents = [ (master_doc, 'sympy', 'SymPy Documentation', 'SymPy Development Team', 'SymPy', 'Computer algebra system (CAS) in Python', 'Programming', 1), ] # Use svg for graphviz graphviz_output_format = 'svg' # Requried for linkcode extension. # Get commit hash from the external file. commit_hash_filepath = '../commit_hash.txt' commit_hash = None if os.path.isfile(commit_hash_filepath): with open(commit_hash_filepath) as f: commit_hash = f.readline() # Get commit hash from the external file. if not commit_hash: try: commit_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD']) commit_hash = commit_hash.decode('ascii') commit_hash = commit_hash.rstrip() except: import warnings warnings.warn( "Failed to get the git commit hash as the command " \ "'git rev-parse HEAD' is not working. The commit hash will be " \ "assumed as the SymPy master, but the lines may be misleading " \ "or nonexistent as it is not the correct branch the doc is " \ "built with. Check your installation of 'git' if you want to " \ "resolve this warning.") commit_hash = 'master' fork = 'sympy' blobpath = \ "https://github.com/{}/sympy/blob/{}/sympy/".format(fork, commit_hash) def linkcode_resolve(domain, info): """Determine the URL corresponding to Python object.""" if domain != 'py': return modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return obj = submod for part in fullname.split('.'): try: obj = getattr(obj, part) except Exception: return # strip decorators, which would resolve to the source of the decorator # possibly an upstream bug in getsourcefile, bpo-1764286 try: unwrap = inspect.unwrap except AttributeError: pass else: obj = unwrap(obj) try: fn = inspect.getsourcefile(obj) except Exception: fn = None if not fn: return try: source, lineno = inspect.getsourcelines(obj) except Exception: lineno = None if lineno: linespec = "#L%d-L%d" % (lineno, lineno + len(source) - 1) else: linespec = "" fn = os.path.relpath(fn, start=os.path.dirname(sympy.__file__)) return blobpath + fn + linespec
6e36ec0088cb874bcb07e728e1a6ee82b67db04a1d12718cac1c37550fdb912f
""" Continuous Random Variables - Prebuilt variables Contains ======== Arcsin Benini Beta BetaNoncentral BetaPrime BoundedPareto Cauchy Chi ChiNoncentral ChiSquared Dagum Erlang ExGaussian Exponential ExponentialPower FDistribution FisherZ Frechet Gamma GammaInverse Gumbel Gompertz Kumaraswamy Laplace Levy LogCauchy Logistic LogLogistic LogitNormal LogNormal Lomax Maxwell Moyal Nakagami Normal Pareto PowerFunction QuadraticU RaisedCosine Rayleigh Reciprocal ShiftedGompertz StudentT Trapezoidal Triangular Uniform UniformSum VonMises Wald Weibull WignerSemicircle """ from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.trigonometric import (atan, cos, sin, tan) from sympy.functions.special.bessel import (besseli, besselj, besselk) from sympy.functions.special.beta_functions import beta as beta_fn from sympy.concrete.summations import Sum from sympy.core.basic import Basic from sympy.core.function import Lambda from sympy.core.numbers import (I, Rational, pi) from sympy.core.relational import (Eq, Ne) from sympy.core.singleton import S from sympy.core.symbol import Dummy 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 log from sympy.functions.elementary.hyperbolic import sinh 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 asin from sympy.functions.special.error_functions import (erf, erfc, erfi, erfinv, expint) from sympy.functions.special.gamma_functions import (gamma, lowergamma, uppergamma) from sympy.functions.special.hyper import hyper from sympy.integrals.integrals import integrate from sympy.logic.boolalg import And from sympy.sets.sets import Interval from sympy.matrices import MatrixBase from sympy.stats.crv import SingleContinuousPSpace, SingleContinuousDistribution from sympy.stats.rv import _value_check, is_random oo = S.Infinity __all__ = ['ContinuousRV', 'Arcsin', 'Benini', 'Beta', 'BetaNoncentral', 'BetaPrime', 'BoundedPareto', 'Cauchy', 'Chi', 'ChiNoncentral', 'ChiSquared', 'Dagum', 'Erlang', 'ExGaussian', 'Exponential', 'ExponentialPower', 'FDistribution', 'FisherZ', 'Frechet', 'Gamma', 'GammaInverse', 'Gompertz', 'Gumbel', 'Kumaraswamy', 'Laplace', 'Levy', 'LogCauchy', 'Logistic', 'LogLogistic', 'LogitNormal', 'LogNormal', 'Lomax', 'Maxwell', 'Moyal', 'Nakagami', 'Normal', 'GaussianInverse', 'Pareto', 'PowerFunction', 'QuadraticU', 'RaisedCosine', 'Rayleigh', 'Reciprocal', 'StudentT', 'ShiftedGompertz', 'Trapezoidal', 'Triangular', 'Uniform', 'UniformSum', 'VonMises', 'Wald', 'Weibull', 'WignerSemicircle', ] @is_random.register(MatrixBase) def _(x): return any(is_random(i) for i in x) def rv(symbol, cls, args, **kwargs): args = list(map(sympify, args)) dist = cls(*args) if kwargs.pop('check', True): dist.check(*args) pspace = SingleContinuousPSpace(symbol, dist) if any(is_random(arg) for arg in args): from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution pspace = CompoundPSpace(symbol, CompoundDistribution(dist)) return pspace.value class ContinuousDistributionHandmade(SingleContinuousDistribution): _argnames = ('pdf',) def __new__(cls, pdf, set=Interval(-oo, oo)): return Basic.__new__(cls, pdf, set) @property def set(self): return self.args[1] @staticmethod def check(pdf, set): x = Dummy('x') val = integrate(pdf(x), (x, set)) _value_check(Eq(val, 1) != S.false, "The pdf on the given set is incorrect.") def ContinuousRV(symbol, density, set=Interval(-oo, oo), **kwargs): """ Create a Continuous Random Variable given the following: Parameters ========== symbol : Symbol Represents name of the random variable. density : Expression containing symbol Represents probability density function. set : set/Interval Represents the region where the pdf is valid, by default is real line. check : bool If True, it will check whether the given density integrates to 1 over the given set. If False, it will not perform this check. Default is False. Returns ======= RandomSymbol Many common continuous random variable types are already implemented. This function should be necessary only very rarely. Examples ======== >>> from sympy import Symbol, sqrt, exp, pi >>> from sympy.stats import ContinuousRV, P, E >>> x = Symbol("x") >>> pdf = sqrt(2)*exp(-x**2/2)/(2*sqrt(pi)) # Normal distribution >>> X = ContinuousRV(x, pdf) >>> E(X) 0 >>> P(X>0) 1/2 """ pdf = Piecewise((density, set.as_relational(symbol)), (0, True)) pdf = Lambda(symbol, pdf) # have a default of False while `rv` should have a default of True kwargs['check'] = kwargs.pop('check', False) return rv(symbol.name, ContinuousDistributionHandmade, (pdf, set), **kwargs) ######################################## # Continuous Probability Distributions # ######################################## #------------------------------------------------------------------------------- # Arcsin distribution ---------------------------------------------------------- class ArcsinDistribution(SingleContinuousDistribution): _argnames = ('a', 'b') @property def set(self): return Interval(self.a, self.b) def pdf(self, x): a, b = self.a, self.b return 1/(pi*sqrt((x - a)*(b - x))) def _cdf(self, x): a, b = self.a, self.b return Piecewise( (S.Zero, x < a), (2*asin(sqrt((x - a)/(b - a)))/pi, x <= b), (S.One, True)) def Arcsin(name, a=0, b=1): r""" Create a Continuous Random Variable with an arcsin distribution. The density of the arcsin distribution is given by .. math:: f(x) := \frac{1}{\pi\sqrt{(x-a)(b-x)}} with :math:`x \in (a,b)`. It must hold that :math:`-\infty < a < b < \infty`. Parameters ========== a : Real number, the left interval boundary b : Real number, the right interval boundary Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Arcsin, density, cdf >>> from sympy import Symbol >>> a = Symbol("a", real=True) >>> b = Symbol("b", real=True) >>> z = Symbol("z") >>> X = Arcsin("x", a, b) >>> density(X)(z) 1/(pi*sqrt((-a + z)*(b - z))) >>> cdf(X)(z) Piecewise((0, a > z), (2*asin(sqrt((-a + z)/(-a + b)))/pi, b >= z), (1, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Arcsine_distribution """ return rv(name, ArcsinDistribution, (a, b)) #------------------------------------------------------------------------------- # Benini distribution ---------------------------------------------------------- class BeniniDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta', 'sigma') @staticmethod def check(alpha, beta, sigma): _value_check(alpha > 0, "Shape parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") _value_check(sigma > 0, "Scale parameter Sigma must be positive.") @property def set(self): return Interval(self.sigma, oo) def pdf(self, x): alpha, beta, sigma = self.alpha, self.beta, self.sigma return (exp(-alpha*log(x/sigma) - beta*log(x/sigma)**2) *(alpha/x + 2*beta*log(x/sigma)/x)) def _moment_generating_function(self, t): raise NotImplementedError('The moment generating function of the ' 'Benini distribution does not exist.') def Benini(name, alpha, beta, sigma): r""" Create a Continuous Random Variable with a Benini distribution. The density of the Benini distribution is given by .. math:: f(x) := e^{-\alpha\log{\frac{x}{\sigma}} -\beta\log^2\left[{\frac{x}{\sigma}}\right]} \left(\frac{\alpha}{x}+\frac{2\beta\log{\frac{x}{\sigma}}}{x}\right) This is a heavy-tailed distribution and is also known as the log-Rayleigh distribution. Parameters ========== alpha : Real number, `\alpha > 0`, a shape beta : Real number, `\beta > 0`, a shape sigma : Real number, `\sigma > 0`, a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Benini, density, cdf >>> from sympy import Symbol, pprint >>> alpha = Symbol("alpha", positive=True) >>> beta = Symbol("beta", positive=True) >>> sigma = Symbol("sigma", positive=True) >>> z = Symbol("z") >>> X = Benini("x", alpha, beta, sigma) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) / / z \\ / z \ 2/ z \ | 2*beta*log|-----|| - alpha*log|-----| - beta*log |-----| |alpha \sigma/| \sigma/ \sigma/ |----- + -----------------|*e \ z z / >>> cdf(X)(z) Piecewise((1 - exp(-alpha*log(z/sigma) - beta*log(z/sigma)**2), sigma <= z), (0, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Benini_distribution .. [2] http://reference.wolfram.com/legacy/v8/ref/BeniniDistribution.html """ return rv(name, BeniniDistribution, (alpha, beta, sigma)) #------------------------------------------------------------------------------- # Beta distribution ------------------------------------------------------------ class BetaDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta') set = Interval(0, 1) @staticmethod def check(alpha, beta): _value_check(alpha > 0, "Shape parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") def pdf(self, x): alpha, beta = self.alpha, self.beta return x**(alpha - 1) * (1 - x)**(beta - 1) / beta_fn(alpha, beta) def _characteristic_function(self, t): return hyper((self.alpha,), (self.alpha + self.beta,), I*t) def _moment_generating_function(self, t): return hyper((self.alpha,), (self.alpha + self.beta,), t) def Beta(name, alpha, beta): r""" Create a Continuous Random Variable with a Beta distribution. The density of the Beta distribution is given by .. math:: f(x) := \frac{x^{\alpha-1}(1-x)^{\beta-1}} {\mathrm{B}(\alpha,\beta)} with :math:`x \in [0,1]`. Parameters ========== alpha : Real number, `\alpha > 0`, a shape beta : Real number, `\beta > 0`, a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Beta, density, E, variance >>> from sympy import Symbol, simplify, pprint, factor >>> alpha = Symbol("alpha", positive=True) >>> beta = Symbol("beta", positive=True) >>> z = Symbol("z") >>> X = Beta("x", alpha, beta) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) alpha - 1 beta - 1 z *(1 - z) -------------------------- B(alpha, beta) >>> simplify(E(X)) alpha/(alpha + beta) >>> factor(simplify(variance(X))) alpha*beta/((alpha + beta)**2*(alpha + beta + 1)) References ========== .. [1] https://en.wikipedia.org/wiki/Beta_distribution .. [2] http://mathworld.wolfram.com/BetaDistribution.html """ return rv(name, BetaDistribution, (alpha, beta)) #------------------------------------------------------------------------------- # Noncentral Beta distribution ------------------------------------------------------------ class BetaNoncentralDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta', 'lamda') set = Interval(0, 1) @staticmethod def check(alpha, beta, lamda): _value_check(alpha > 0, "Shape parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") _value_check(lamda >= 0, "Noncentrality parameter Lambda must be positive") def pdf(self, x): alpha, beta, lamda = self.alpha, self.beta, self.lamda k = Dummy("k") return Sum(exp(-lamda / 2) * (lamda / 2)**k * x**(alpha + k - 1) *( 1 - x)**(beta - 1) / (factorial(k) * beta_fn(alpha + k, beta)), (k, 0, oo)) def BetaNoncentral(name, alpha, beta, lamda): r""" Create a Continuous Random Variable with a Type I Noncentral Beta distribution. The density of the Noncentral Beta distribution is given by .. math:: f(x) := \sum_{k=0}^\infty e^{-\lambda/2}\frac{(\lambda/2)^k}{k!} \frac{x^{\alpha+k-1}(1-x)^{\beta-1}}{\mathrm{B}(\alpha+k,\beta)} with :math:`x \in [0,1]`. Parameters ========== alpha : Real number, `\alpha > 0`, a shape beta : Real number, `\beta > 0`, a shape lamda: Real number, `\lambda >= 0`, noncentrality parameter Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import BetaNoncentral, density, cdf >>> from sympy import Symbol, pprint >>> alpha = Symbol("alpha", positive=True) >>> beta = Symbol("beta", positive=True) >>> lamda = Symbol("lamda", nonnegative=True) >>> z = Symbol("z") >>> X = BetaNoncentral("x", alpha, beta, lamda) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) oo _____ \ ` \ -lamda \ k ------- \ k + alpha - 1 /lamda\ beta - 1 2 ) z *|-----| *(1 - z) *e / \ 2 / / ------------------------------------------------ / B(k + alpha, beta)*k! /____, k = 0 Compute cdf with specific 'x', 'alpha', 'beta' and 'lamda' values as follows : >>> cdf(BetaNoncentral("x", 1, 1, 1), evaluate=False)(2).doit() 2*exp(1/2) The argument evaluate=False prevents an attempt at evaluation of the sum for general x, before the argument 2 is passed. References ========== .. [1] https://en.wikipedia.org/wiki/Noncentral_beta_distribution .. [2] https://reference.wolfram.com/language/ref/NoncentralBetaDistribution.html """ return rv(name, BetaNoncentralDistribution, (alpha, beta, lamda)) #------------------------------------------------------------------------------- # Beta prime distribution ------------------------------------------------------ class BetaPrimeDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta') @staticmethod def check(alpha, beta): _value_check(alpha > 0, "Shape parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") set = Interval(0, oo) def pdf(self, x): alpha, beta = self.alpha, self.beta return x**(alpha - 1)*(1 + x)**(-alpha - beta)/beta_fn(alpha, beta) def BetaPrime(name, alpha, beta): r""" Create a continuous random variable with a Beta prime distribution. The density of the Beta prime distribution is given by .. math:: f(x) := \frac{x^{\alpha-1} (1+x)^{-\alpha -\beta}}{B(\alpha,\beta)} with :math:`x > 0`. Parameters ========== alpha : Real number, `\alpha > 0`, a shape beta : Real number, `\beta > 0`, a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import BetaPrime, density >>> from sympy import Symbol, pprint >>> alpha = Symbol("alpha", positive=True) >>> beta = Symbol("beta", positive=True) >>> z = Symbol("z") >>> X = BetaPrime("x", alpha, beta) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) alpha - 1 -alpha - beta z *(z + 1) ------------------------------- B(alpha, beta) References ========== .. [1] https://en.wikipedia.org/wiki/Beta_prime_distribution .. [2] http://mathworld.wolfram.com/BetaPrimeDistribution.html """ return rv(name, BetaPrimeDistribution, (alpha, beta)) #------------------------------------------------------------------------------- # Bounded Pareto Distribution -------------------------------------------------- class BoundedParetoDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'left', 'right') @property def set(self): return Interval(self.left, self.right) @staticmethod def check(alpha, left, right): _value_check (alpha.is_positive, "Shape must be positive.") _value_check (left.is_positive, "Left value should be positive.") _value_check (right > left, "Right should be greater than left.") def pdf(self, x): alpha, left, right = self.alpha, self.left, self.right num = alpha * (left**alpha) * x**(- alpha -1) den = 1 - (left/right)**alpha return num/den def BoundedPareto(name, alpha, left, right): r""" Create a continuous random variable with a Bounded Pareto distribution. The density of the Bounded Pareto distribution is given by .. math:: f(x) := \frac{\alpha L^{\alpha}x^{-\alpha-1}}{1-(\frac{L}{H})^{\alpha}} Parameters ========== alpha : Real Number, `alpha > 0` Shape parameter left : Real Number, `left > 0` Location parameter right : Real Number, `right > left` Location parameter Examples ======== >>> from sympy.stats import BoundedPareto, density, cdf, E >>> from sympy import symbols >>> L, H = symbols('L, H', positive=True) >>> X = BoundedPareto('X', 2, L, H) >>> x = symbols('x') >>> density(X)(x) 2*L**2/(x**3*(1 - L**2/H**2)) >>> cdf(X)(x) Piecewise((-H**2*L**2/(x**2*(H**2 - L**2)) + H**2/(H**2 - L**2), L <= x), (0, True)) >>> E(X).simplify() 2*H*L/(H + L) Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Pareto_distribution#Bounded_Pareto_distribution """ return rv (name, BoundedParetoDistribution, (alpha, left, right)) # ------------------------------------------------------------------------------ # Cauchy distribution ---------------------------------------------------------- class CauchyDistribution(SingleContinuousDistribution): _argnames = ('x0', 'gamma') @staticmethod def check(x0, gamma): _value_check(gamma > 0, "Scale parameter Gamma must be positive.") _value_check(x0.is_real, "Location parameter must be real.") def pdf(self, x): return 1/(pi*self.gamma*(1 + ((x - self.x0)/self.gamma)**2)) def _cdf(self, x): x0, gamma = self.x0, self.gamma return (1/pi)*atan((x - x0)/gamma) + S.Half def _characteristic_function(self, t): return exp(self.x0 * I * t - self.gamma * Abs(t)) def _moment_generating_function(self, t): raise NotImplementedError("The moment generating function for the " "Cauchy distribution does not exist.") def _quantile(self, p): return self.x0 + self.gamma*tan(pi*(p - S.Half)) def Cauchy(name, x0, gamma): r""" Create a continuous random variable with a Cauchy distribution. The density of the Cauchy distribution is given by .. math:: f(x) := \frac{1}{\pi \gamma [1 + {(\frac{x-x_0}{\gamma})}^2]} Parameters ========== x0 : Real number, the location gamma : Real number, `\gamma > 0`, a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Cauchy, density >>> from sympy import Symbol >>> x0 = Symbol("x0") >>> gamma = Symbol("gamma", positive=True) >>> z = Symbol("z") >>> X = Cauchy("x", x0, gamma) >>> density(X)(z) 1/(pi*gamma*(1 + (-x0 + z)**2/gamma**2)) References ========== .. [1] https://en.wikipedia.org/wiki/Cauchy_distribution .. [2] http://mathworld.wolfram.com/CauchyDistribution.html """ return rv(name, CauchyDistribution, (x0, gamma)) #------------------------------------------------------------------------------- # Chi distribution ------------------------------------------------------------- class ChiDistribution(SingleContinuousDistribution): _argnames = ('k',) @staticmethod def check(k): _value_check(k > 0, "Number of degrees of freedom (k) must be positive.") _value_check(k.is_integer, "Number of degrees of freedom (k) must be an integer.") set = Interval(0, oo) def pdf(self, x): return 2**(1 - self.k/2)*x**(self.k - 1)*exp(-x**2/2)/gamma(self.k/2) def _characteristic_function(self, t): k = self.k part_1 = hyper((k/2,), (S.Half,), -t**2/2) part_2 = I*t*sqrt(2)*gamma((k+1)/2)/gamma(k/2) part_3 = hyper(((k+1)/2,), (Rational(3, 2),), -t**2/2) return part_1 + part_2*part_3 def _moment_generating_function(self, t): k = self.k part_1 = hyper((k / 2,), (S.Half,), t ** 2 / 2) part_2 = t * sqrt(2) * gamma((k + 1) / 2) / gamma(k / 2) part_3 = hyper(((k + 1) / 2,), (S(3) / 2,), t ** 2 / 2) return part_1 + part_2 * part_3 def Chi(name, k): r""" Create a continuous random variable with a Chi distribution. The density of the Chi distribution is given by .. math:: f(x) := \frac{2^{1-k/2}x^{k-1}e^{-x^2/2}}{\Gamma(k/2)} with :math:`x \geq 0`. Parameters ========== k : Positive integer, The number of degrees of freedom Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Chi, density, E >>> from sympy import Symbol, simplify >>> k = Symbol("k", integer=True) >>> z = Symbol("z") >>> X = Chi("x", k) >>> density(X)(z) 2**(1 - k/2)*z**(k - 1)*exp(-z**2/2)/gamma(k/2) >>> simplify(E(X)) sqrt(2)*gamma(k/2 + 1/2)/gamma(k/2) References ========== .. [1] https://en.wikipedia.org/wiki/Chi_distribution .. [2] http://mathworld.wolfram.com/ChiDistribution.html """ return rv(name, ChiDistribution, (k,)) #------------------------------------------------------------------------------- # Non-central Chi distribution ------------------------------------------------- class ChiNoncentralDistribution(SingleContinuousDistribution): _argnames = ('k', 'l') @staticmethod def check(k, l): _value_check(k > 0, "Number of degrees of freedom (k) must be positive.") _value_check(k.is_integer, "Number of degrees of freedom (k) must be an integer.") _value_check(l > 0, "Shift parameter Lambda must be positive.") set = Interval(0, oo) def pdf(self, x): k, l = self.k, self.l return exp(-(x**2+l**2)/2)*x**k*l / (l*x)**(k/2) * besseli(k/2-1, l*x) def ChiNoncentral(name, k, l): r""" Create a continuous random variable with a non-central Chi distribution. Explanation =========== The density of the non-central Chi distribution is given by .. math:: f(x) := \frac{e^{-(x^2+\lambda^2)/2} x^k\lambda} {(\lambda x)^{k/2}} I_{k/2-1}(\lambda x) with `x \geq 0`. Here, `I_\nu (x)` is the :ref:`modified Bessel function of the first kind <besseli>`. Parameters ========== k : A positive Integer, $k > 0$ The number of degrees of freedom. lambda : Real number, `\lambda > 0` Shift parameter. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import ChiNoncentral, density >>> from sympy import Symbol >>> k = Symbol("k", integer=True) >>> l = Symbol("l") >>> z = Symbol("z") >>> X = ChiNoncentral("x", k, l) >>> density(X)(z) l*z**k*exp(-l**2/2 - z**2/2)*besseli(k/2 - 1, l*z)/(l*z)**(k/2) References ========== .. [1] https://en.wikipedia.org/wiki/Noncentral_chi_distribution """ return rv(name, ChiNoncentralDistribution, (k, l)) #------------------------------------------------------------------------------- # Chi squared distribution ----------------------------------------------------- class ChiSquaredDistribution(SingleContinuousDistribution): _argnames = ('k',) @staticmethod def check(k): _value_check(k > 0, "Number of degrees of freedom (k) must be positive.") _value_check(k.is_integer, "Number of degrees of freedom (k) must be an integer.") set = Interval(0, oo) def pdf(self, x): k = self.k return 1/(2**(k/2)*gamma(k/2))*x**(k/2 - 1)*exp(-x/2) def _cdf(self, x): k = self.k return Piecewise( (S.One/gamma(k/2)*lowergamma(k/2, x/2), x >= 0), (0, True) ) def _characteristic_function(self, t): return (1 - 2*I*t)**(-self.k/2) def _moment_generating_function(self, t): return (1 - 2*t)**(-self.k/2) def ChiSquared(name, k): r""" Create a continuous random variable with a Chi-squared distribution. Explanation =========== The density of the Chi-squared distribution is given by .. math:: f(x) := \frac{1}{2^{\frac{k}{2}}\Gamma\left(\frac{k}{2}\right)} x^{\frac{k}{2}-1} e^{-\frac{x}{2}} with :math:`x \geq 0`. Parameters ========== k : Positive integer The number of degrees of freedom. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import ChiSquared, density, E, variance, moment >>> from sympy import Symbol >>> k = Symbol("k", integer=True, positive=True) >>> z = Symbol("z") >>> X = ChiSquared("x", k) >>> density(X)(z) z**(k/2 - 1)*exp(-z/2)/(2**(k/2)*gamma(k/2)) >>> E(X) k >>> variance(X) 2*k >>> moment(X, 3) k**3 + 6*k**2 + 8*k References ========== .. [1] https://en.wikipedia.org/wiki/Chi_squared_distribution .. [2] http://mathworld.wolfram.com/Chi-SquaredDistribution.html """ return rv(name, ChiSquaredDistribution, (k, )) #------------------------------------------------------------------------------- # Dagum distribution ----------------------------------------------------------- class DagumDistribution(SingleContinuousDistribution): _argnames = ('p', 'a', 'b') set = Interval(0, oo) @staticmethod def check(p, a, b): _value_check(p > 0, "Shape parameter p must be positive.") _value_check(a > 0, "Shape parameter a must be positive.") _value_check(b > 0, "Scale parameter b must be positive.") def pdf(self, x): p, a, b = self.p, self.a, self.b return a*p/x*((x/b)**(a*p)/(((x/b)**a + 1)**(p + 1))) def _cdf(self, x): p, a, b = self.p, self.a, self.b return Piecewise(((S.One + (S(x)/b)**-a)**-p, x>=0), (S.Zero, True)) def Dagum(name, p, a, b): r""" Create a continuous random variable with a Dagum distribution. Explanation =========== The density of the Dagum distribution is given by .. math:: f(x) := \frac{a p}{x} \left( \frac{\left(\tfrac{x}{b}\right)^{a p}} {\left(\left(\tfrac{x}{b}\right)^a + 1 \right)^{p+1}} \right) with :math:`x > 0`. Parameters ========== p : Real number ``p > 0``, a shape. a : Real number ``a > 0``, a shape. b : Real number ``b > 0``, a scale. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Dagum, density, cdf >>> from sympy import Symbol >>> p = Symbol("p", positive=True) >>> a = Symbol("a", positive=True) >>> b = Symbol("b", positive=True) >>> z = Symbol("z") >>> X = Dagum("x", p, a, b) >>> density(X)(z) a*p*(z/b)**(a*p)*((z/b)**a + 1)**(-p - 1)/z >>> cdf(X)(z) Piecewise(((1 + (z/b)**(-a))**(-p), z >= 0), (0, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Dagum_distribution """ return rv(name, DagumDistribution, (p, a, b)) #------------------------------------------------------------------------------- # Erlang distribution ---------------------------------------------------------- def Erlang(name, k, l): r""" Create a continuous random variable with an Erlang distribution. Explanation =========== The density of the Erlang distribution is given by .. math:: f(x) := \frac{\lambda^k x^{k-1} e^{-\lambda x}}{(k-1)!} with :math:`x \in [0,\infty]`. Parameters ========== k : Positive integer l : Real number, `\lambda > 0`, the rate Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Erlang, density, cdf, E, variance >>> from sympy import Symbol, simplify, pprint >>> k = Symbol("k", integer=True, positive=True) >>> l = Symbol("l", positive=True) >>> z = Symbol("z") >>> X = Erlang("x", k, l) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) k k - 1 -l*z l *z *e --------------- Gamma(k) >>> C = cdf(X)(z) >>> pprint(C, use_unicode=False) /lowergamma(k, l*z) |------------------ for z > 0 < Gamma(k) | \ 0 otherwise >>> E(X) k/l >>> simplify(variance(X)) k/l**2 References ========== .. [1] https://en.wikipedia.org/wiki/Erlang_distribution .. [2] http://mathworld.wolfram.com/ErlangDistribution.html """ return rv(name, GammaDistribution, (k, S.One/l)) # ------------------------------------------------------------------------------- # ExGaussian distribution ----------------------------------------------------- class ExGaussianDistribution(SingleContinuousDistribution): _argnames = ('mean', 'std', 'rate') set = Interval(-oo, oo) @staticmethod def check(mean, std, rate): _value_check( std > 0, "Standard deviation of ExGaussian must be positive.") _value_check(rate > 0, "Rate of ExGaussian must be positive.") def pdf(self, x): mean, std, rate = self.mean, self.std, self.rate term1 = rate/2 term2 = exp(rate * (2 * mean + rate * std**2 - 2*x)/2) term3 = erfc((mean + rate*std**2 - x)/(sqrt(2)*std)) return term1*term2*term3 def _cdf(self, x): from sympy.stats import cdf mean, std, rate = self.mean, self.std, self.rate u = rate*(x - mean) v = rate*std GaussianCDF1 = cdf(Normal('x', 0, v))(u) GaussianCDF2 = cdf(Normal('x', v**2, v))(u) return GaussianCDF1 - exp(-u + (v**2/2) + log(GaussianCDF2)) def _characteristic_function(self, t): mean, std, rate = self.mean, self.std, self.rate term1 = (1 - I*t/rate)**(-1) term2 = exp(I*mean*t - std**2*t**2/2) return term1 * term2 def _moment_generating_function(self, t): mean, std, rate = self.mean, self.std, self.rate term1 = (1 - t/rate)**(-1) term2 = exp(mean*t + std**2*t**2/2) return term1*term2 def ExGaussian(name, mean, std, rate): r""" Create a continuous random variable with an Exponentially modified Gaussian (EMG) distribution. Explanation =========== The density of the exponentially modified Gaussian distribution is given by .. math:: f(x) := \frac{\lambda}{2}e^{\frac{\lambda}{2}(2\mu+\lambda\sigma^2-2x)} \text{erfc}(\frac{\mu + \lambda\sigma^2 - x}{\sqrt{2}\sigma}) with $x > 0$. Note that the expected value is `1/\lambda`. Parameters ========== mu : A Real number, the mean of Gaussian component std: A positive Real number, :math: `\sigma^2 > 0` the variance of Gaussian component lambda: A positive Real number, :math: `\lambda > 0` the rate of Exponential component Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import ExGaussian, density, cdf, E >>> from sympy.stats import variance, skewness >>> from sympy import Symbol, pprint, simplify >>> mean = Symbol("mu") >>> std = Symbol("sigma", positive=True) >>> rate = Symbol("lamda", positive=True) >>> z = Symbol("z") >>> X = ExGaussian("x", mean, std, rate) >>> pprint(density(X)(z), use_unicode=False) / 2 \ lamda*\lamda*sigma + 2*mu - 2*z/ --------------------------------- / ___ / 2 \\ 2 |\/ 2 *\lamda*sigma + mu - z/| lamda*e *erfc|-----------------------------| \ 2*sigma / ---------------------------------------------------------------------------- 2 >>> cdf(X)(z) -(erf(sqrt(2)*(-lamda**2*sigma**2 + lamda*(-mu + z))/(2*lamda*sigma))/2 + 1/2)*exp(lamda**2*sigma**2/2 - lamda*(-mu + z)) + erf(sqrt(2)*(-mu + z)/(2*sigma))/2 + 1/2 >>> E(X) (lamda*mu + 1)/lamda >>> simplify(variance(X)) sigma**2 + lamda**(-2) >>> simplify(skewness(X)) 2/(lamda**2*sigma**2 + 1)**(3/2) References ========== .. [1] https://en.wikipedia.org/wiki/Exponentially_modified_Gaussian_distribution """ return rv(name, ExGaussianDistribution, (mean, std, rate)) #------------------------------------------------------------------------------- # Exponential distribution ----------------------------------------------------- class ExponentialDistribution(SingleContinuousDistribution): _argnames = ('rate',) set = Interval(0, oo) @staticmethod def check(rate): _value_check(rate > 0, "Rate must be positive.") def pdf(self, x): return self.rate * exp(-self.rate*x) def _cdf(self, x): return Piecewise( (S.One - exp(-self.rate*x), x >= 0), (0, True), ) def _characteristic_function(self, t): rate = self.rate return rate / (rate - I*t) def _moment_generating_function(self, t): rate = self.rate return rate / (rate - t) def _quantile(self, p): return -log(1-p)/self.rate def Exponential(name, rate): r""" Create a continuous random variable with an Exponential distribution. Explanation =========== The density of the exponential distribution is given by .. math:: f(x) := \lambda \exp(-\lambda x) with $x > 0$. Note that the expected value is `1/\lambda`. Parameters ========== rate : A positive Real number, `\lambda > 0`, the rate (or inverse scale/inverse mean) Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Exponential, density, cdf, E >>> from sympy.stats import variance, std, skewness, quantile >>> from sympy import Symbol >>> l = Symbol("lambda", positive=True) >>> z = Symbol("z") >>> p = Symbol("p") >>> X = Exponential("x", l) >>> density(X)(z) lambda*exp(-lambda*z) >>> cdf(X)(z) Piecewise((1 - exp(-lambda*z), z >= 0), (0, True)) >>> quantile(X)(p) -log(1 - p)/lambda >>> E(X) 1/lambda >>> variance(X) lambda**(-2) >>> skewness(X) 2 >>> X = Exponential('x', 10) >>> density(X)(z) 10*exp(-10*z) >>> E(X) 1/10 >>> std(X) 1/10 References ========== .. [1] https://en.wikipedia.org/wiki/Exponential_distribution .. [2] http://mathworld.wolfram.com/ExponentialDistribution.html """ return rv(name, ExponentialDistribution, (rate, )) # ------------------------------------------------------------------------------- # Exponential Power distribution ----------------------------------------------------- class ExponentialPowerDistribution(SingleContinuousDistribution): _argnames = ('mu', 'alpha', 'beta') set = Interval(-oo, oo) @staticmethod def check(mu, alpha, beta): _value_check(alpha > 0, "Scale parameter alpha must be positive.") _value_check(beta > 0, "Shape parameter beta must be positive.") def pdf(self, x): mu, alpha, beta = self.mu, self.alpha, self.beta num = beta*exp(-(Abs(x - mu)/alpha)**beta) den = 2*alpha*gamma(1/beta) return num/den def _cdf(self, x): mu, alpha, beta = self.mu, self.alpha, self.beta num = lowergamma(1/beta, (Abs(x - mu) / alpha)**beta) den = 2*gamma(1/beta) return sign(x - mu)*num/den + S.Half def ExponentialPower(name, mu, alpha, beta): r""" Create a Continuous Random Variable with Exponential Power distribution. This distribution is known also as Generalized Normal distribution version 1. Explanation =========== The density of the Exponential Power distribution is given by .. math:: f(x) := \frac{\beta}{2\alpha\Gamma(\frac{1}{\beta})} e^{{-(\frac{|x - \mu|}{\alpha})^{\beta}}} with :math:`x \in [ - \infty, \infty ]`. Parameters ========== mu : Real number A location. alpha : Real number,``alpha > 0`` A scale. beta : Real number, ``beta > 0`` A shape. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import ExponentialPower, density, cdf >>> from sympy import Symbol, pprint >>> z = Symbol("z") >>> mu = Symbol("mu") >>> alpha = Symbol("alpha", positive=True) >>> beta = Symbol("beta", positive=True) >>> X = ExponentialPower("x", mu, alpha, beta) >>> pprint(density(X)(z), use_unicode=False) beta /|mu - z|\ -|--------| \ alpha / beta*e --------------------- / 1 \ 2*alpha*Gamma|----| \beta/ >>> cdf(X)(z) 1/2 + lowergamma(1/beta, (Abs(mu - z)/alpha)**beta)*sign(-mu + z)/(2*gamma(1/beta)) References ========== .. [1] https://reference.wolfram.com/language/ref/ExponentialPowerDistribution.html .. [2] https://en.wikipedia.org/wiki/Generalized_normal_distribution#Version_1 """ return rv(name, ExponentialPowerDistribution, (mu, alpha, beta)) #------------------------------------------------------------------------------- # F distribution --------------------------------------------------------------- class FDistributionDistribution(SingleContinuousDistribution): _argnames = ('d1', 'd2') set = Interval(0, oo) @staticmethod def check(d1, d2): _value_check((d1 > 0, d1.is_integer), "Degrees of freedom d1 must be positive integer.") _value_check((d2 > 0, d2.is_integer), "Degrees of freedom d2 must be positive integer.") def pdf(self, x): d1, d2 = self.d1, self.d2 return (sqrt((d1*x)**d1*d2**d2 / (d1*x+d2)**(d1+d2)) / (x * beta_fn(d1/2, d2/2))) def _moment_generating_function(self, t): raise NotImplementedError('The moment generating function for the ' 'F-distribution does not exist.') def FDistribution(name, d1, d2): r""" Create a continuous random variable with a F distribution. Explanation =========== The density of the F distribution is given by .. math:: f(x) := \frac{\sqrt{\frac{(d_1 x)^{d_1} d_2^{d_2}} {(d_1 x + d_2)^{d_1 + d_2}}}} {x \mathrm{B} \left(\frac{d_1}{2}, \frac{d_2}{2}\right)} with :math:`x > 0`. Parameters ========== d1 : `d_1 > 0`, where d_1 is the degrees of freedom (n_1 - 1) d2 : `d_2 > 0`, where d_2 is the degrees of freedom (n_2 - 1) Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import FDistribution, density >>> from sympy import Symbol, pprint >>> d1 = Symbol("d1", positive=True) >>> d2 = Symbol("d2", positive=True) >>> z = Symbol("z") >>> X = FDistribution("x", d1, d2) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) d2 -- ______________________________ 2 / d1 -d1 - d2 d2 *\/ (d1*z) *(d1*z + d2) -------------------------------------- /d1 d2\ z*B|--, --| \2 2 / References ========== .. [1] https://en.wikipedia.org/wiki/F-distribution .. [2] http://mathworld.wolfram.com/F-Distribution.html """ return rv(name, FDistributionDistribution, (d1, d2)) #------------------------------------------------------------------------------- # Fisher Z distribution -------------------------------------------------------- class FisherZDistribution(SingleContinuousDistribution): _argnames = ('d1', 'd2') set = Interval(-oo, oo) @staticmethod def check(d1, d2): _value_check(d1 > 0, "Degree of freedom d1 must be positive.") _value_check(d2 > 0, "Degree of freedom d2 must be positive.") def pdf(self, x): d1, d2 = self.d1, self.d2 return (2*d1**(d1/2)*d2**(d2/2) / beta_fn(d1/2, d2/2) * exp(d1*x) / (d1*exp(2*x)+d2)**((d1+d2)/2)) def FisherZ(name, d1, d2): r""" Create a Continuous Random Variable with an Fisher's Z distribution. Explanation =========== The density of the Fisher's Z distribution is given by .. math:: f(x) := \frac{2d_1^{d_1/2} d_2^{d_2/2}} {\mathrm{B}(d_1/2, d_2/2)} \frac{e^{d_1z}}{\left(d_1e^{2z}+d_2\right)^{\left(d_1+d_2\right)/2}} .. TODO - What is the difference between these degrees of freedom? Parameters ========== d1 : ``d_1 > 0`` Degree of freedom. d2 : ``d_2 > 0`` Degree of freedom. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import FisherZ, density >>> from sympy import Symbol, pprint >>> d1 = Symbol("d1", positive=True) >>> d2 = Symbol("d2", positive=True) >>> z = Symbol("z") >>> X = FisherZ("x", d1, d2) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) d1 d2 d1 d2 - -- - -- -- -- 2 2 2 2 / 2*z \ d1*z 2*d1 *d2 *\d1*e + d2/ *e ----------------------------------------- /d1 d2\ B|--, --| \2 2 / References ========== .. [1] https://en.wikipedia.org/wiki/Fisher%27s_z-distribution .. [2] http://mathworld.wolfram.com/Fishersz-Distribution.html """ return rv(name, FisherZDistribution, (d1, d2)) #------------------------------------------------------------------------------- # Frechet distribution --------------------------------------------------------- class FrechetDistribution(SingleContinuousDistribution): _argnames = ('a', 's', 'm') set = Interval(0, oo) @staticmethod def check(a, s, m): _value_check(a > 0, "Shape parameter alpha must be positive.") _value_check(s > 0, "Scale parameter s must be positive.") def __new__(cls, a, s=1, m=0): a, s, m = list(map(sympify, (a, s, m))) return Basic.__new__(cls, a, s, m) def pdf(self, x): a, s, m = self.a, self.s, self.m return a/s * ((x-m)/s)**(-1-a) * exp(-((x-m)/s)**(-a)) def _cdf(self, x): a, s, m = self.a, self.s, self.m return Piecewise((exp(-((x-m)/s)**(-a)), x >= m), (S.Zero, True)) def Frechet(name, a, s=1, m=0): r""" Create a continuous random variable with a Frechet distribution. Explanation =========== The density of the Frechet distribution is given by .. math:: f(x) := \frac{\alpha}{s} \left(\frac{x-m}{s}\right)^{-1-\alpha} e^{-(\frac{x-m}{s})^{-\alpha}} with :math:`x \geq m`. Parameters ========== a : Real number, :math:`a \in \left(0, \infty\right)` the shape s : Real number, :math:`s \in \left(0, \infty\right)` the scale m : Real number, :math:`m \in \left(-\infty, \infty\right)` the minimum Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Frechet, density, cdf >>> from sympy import Symbol >>> a = Symbol("a", positive=True) >>> s = Symbol("s", positive=True) >>> m = Symbol("m", real=True) >>> z = Symbol("z") >>> X = Frechet("x", a, s, m) >>> density(X)(z) a*((-m + z)/s)**(-a - 1)*exp(-1/((-m + z)/s)**a)/s >>> cdf(X)(z) Piecewise((exp(-1/((-m + z)/s)**a), m <= z), (0, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Fr%C3%A9chet_distribution """ return rv(name, FrechetDistribution, (a, s, m)) #------------------------------------------------------------------------------- # Gamma distribution ----------------------------------------------------------- class GammaDistribution(SingleContinuousDistribution): _argnames = ('k', 'theta') set = Interval(0, oo) @staticmethod def check(k, theta): _value_check(k > 0, "k must be positive") _value_check(theta > 0, "Theta must be positive") def pdf(self, x): k, theta = self.k, self.theta return x**(k - 1) * exp(-x/theta) / (gamma(k)*theta**k) def _cdf(self, x): k, theta = self.k, self.theta return Piecewise( (lowergamma(k, S(x)/theta)/gamma(k), x > 0), (S.Zero, True)) def _characteristic_function(self, t): return (1 - self.theta*I*t)**(-self.k) def _moment_generating_function(self, t): return (1- self.theta*t)**(-self.k) def Gamma(name, k, theta): r""" Create a continuous random variable with a Gamma distribution. Explanation =========== The density of the Gamma distribution is given by .. math:: f(x) := \frac{1}{\Gamma(k) \theta^k} x^{k - 1} e^{-\frac{x}{\theta}} with :math:`x \in [0,1]`. Parameters ========== k : Real number, ``k > 0``, a shape theta : Real number, `\theta > 0`, a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Gamma, density, cdf, E, variance >>> from sympy import Symbol, pprint, simplify >>> k = Symbol("k", positive=True) >>> theta = Symbol("theta", positive=True) >>> z = Symbol("z") >>> X = Gamma("x", k, theta) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) -z ----- -k k - 1 theta theta *z *e --------------------- Gamma(k) >>> C = cdf(X, meijerg=True)(z) >>> pprint(C, use_unicode=False) / / z \ |k*lowergamma|k, -----| | \ theta/ <---------------------- for z >= 0 | Gamma(k + 1) | \ 0 otherwise >>> E(X) k*theta >>> V = simplify(variance(X)) >>> pprint(V, use_unicode=False) 2 k*theta References ========== .. [1] https://en.wikipedia.org/wiki/Gamma_distribution .. [2] http://mathworld.wolfram.com/GammaDistribution.html """ return rv(name, GammaDistribution, (k, theta)) #------------------------------------------------------------------------------- # Inverse Gamma distribution --------------------------------------------------- class GammaInverseDistribution(SingleContinuousDistribution): _argnames = ('a', 'b') set = Interval(0, oo) @staticmethod def check(a, b): _value_check(a > 0, "alpha must be positive") _value_check(b > 0, "beta must be positive") def pdf(self, x): a, b = self.a, self.b return b**a/gamma(a) * x**(-a-1) * exp(-b/x) def _cdf(self, x): a, b = self.a, self.b return Piecewise((uppergamma(a,b/x)/gamma(a), x > 0), (S.Zero, True)) def _characteristic_function(self, t): a, b = self.a, self.b return 2 * (-I*b*t)**(a/2) * besselk(a, sqrt(-4*I*b*t)) / gamma(a) def _moment_generating_function(self, t): raise NotImplementedError('The moment generating function for the ' 'gamma inverse distribution does not exist.') def GammaInverse(name, a, b): r""" Create a continuous random variable with an inverse Gamma distribution. Explanation =========== The density of the inverse Gamma distribution is given by .. math:: f(x) := \frac{\beta^\alpha}{\Gamma(\alpha)} x^{-\alpha - 1} \exp\left(\frac{-\beta}{x}\right) with :math:`x > 0`. Parameters ========== a : Real number, `a > 0` a shape b : Real number, `b > 0` a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import GammaInverse, density, cdf >>> from sympy import Symbol, pprint >>> a = Symbol("a", positive=True) >>> b = Symbol("b", positive=True) >>> z = Symbol("z") >>> X = GammaInverse("x", a, b) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) -b --- a -a - 1 z b *z *e --------------- Gamma(a) >>> cdf(X)(z) Piecewise((uppergamma(a, b/z)/gamma(a), z > 0), (0, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Inverse-gamma_distribution """ return rv(name, GammaInverseDistribution, (a, b)) #------------------------------------------------------------------------------- # Gumbel distribution (Maximum and Minimum) -------------------------------------------------------- class GumbelDistribution(SingleContinuousDistribution): _argnames = ('beta', 'mu', 'minimum') set = Interval(-oo, oo) @staticmethod def check(beta, mu, minimum): _value_check(beta > 0, "Scale parameter beta must be positive.") def pdf(self, x): beta, mu = self.beta, self.mu z = (x - mu)/beta f_max = (1/beta)*exp(-z - exp(-z)) f_min = (1/beta)*exp(z - exp(z)) return Piecewise((f_min, self.minimum), (f_max, not self.minimum)) def _cdf(self, x): beta, mu = self.beta, self.mu z = (x - mu)/beta F_max = exp(-exp(-z)) F_min = 1 - exp(-exp(z)) return Piecewise((F_min, self.minimum), (F_max, not self.minimum)) def _characteristic_function(self, t): cf_max = gamma(1 - I*self.beta*t) * exp(I*self.mu*t) cf_min = gamma(1 + I*self.beta*t) * exp(I*self.mu*t) return Piecewise((cf_min, self.minimum), (cf_max, not self.minimum)) def _moment_generating_function(self, t): mgf_max = gamma(1 - self.beta*t) * exp(self.mu*t) mgf_min = gamma(1 + self.beta*t) * exp(self.mu*t) return Piecewise((mgf_min, self.minimum), (mgf_max, not self.minimum)) def Gumbel(name, beta, mu, minimum=False): r""" Create a Continuous Random Variable with Gumbel distribution. Explanation =========== The density of the Gumbel distribution is given by For Maximum .. math:: f(x) := \dfrac{1}{\beta} \exp \left( -\dfrac{x-\mu}{\beta} - \exp \left( -\dfrac{x - \mu}{\beta} \right) \right) with :math:`x \in [ - \infty, \infty ]`. For Minimum .. math:: f(x) := \frac{e^{- e^{\frac{- \mu + x}{\beta}} + \frac{- \mu + x}{\beta}}}{\beta} with :math:`x \in [ - \infty, \infty ]`. Parameters ========== mu : Real number, 'mu' is a location beta : Real number, 'beta > 0' is a scale minimum : Boolean, by default, False, set to True for enabling minimum distribution Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Gumbel, density, cdf >>> from sympy import Symbol >>> x = Symbol("x") >>> mu = Symbol("mu") >>> beta = Symbol("beta", positive=True) >>> X = Gumbel("x", beta, mu) >>> density(X)(x) exp(-exp(-(-mu + x)/beta) - (-mu + x)/beta)/beta >>> cdf(X)(x) exp(-exp(-(-mu + x)/beta)) References ========== .. [1] http://mathworld.wolfram.com/GumbelDistribution.html .. [2] https://en.wikipedia.org/wiki/Gumbel_distribution .. [3] http://www.mathwave.com/help/easyfit/html/analyses/distributions/gumbel_max.html .. [4] http://www.mathwave.com/help/easyfit/html/analyses/distributions/gumbel_min.html """ return rv(name, GumbelDistribution, (beta, mu, minimum)) #------------------------------------------------------------------------------- # Gompertz distribution -------------------------------------------------------- class GompertzDistribution(SingleContinuousDistribution): _argnames = ('b', 'eta') set = Interval(0, oo) @staticmethod def check(b, eta): _value_check(b > 0, "b must be positive") _value_check(eta > 0, "eta must be positive") def pdf(self, x): eta, b = self.eta, self.b return b*eta*exp(b*x)*exp(eta)*exp(-eta*exp(b*x)) def _cdf(self, x): eta, b = self.eta, self.b return 1 - exp(eta)*exp(-eta*exp(b*x)) def _moment_generating_function(self, t): eta, b = self.eta, self.b return eta * exp(eta) * expint(t/b, eta) def Gompertz(name, b, eta): r""" Create a Continuous Random Variable with Gompertz distribution. Explanation =========== The density of the Gompertz distribution is given by .. math:: f(x) := b \eta e^{b x} e^{\eta} \exp \left(-\eta e^{bx} \right) with :math: 'x \in [0, \inf)'. Parameters ========== b: Real number, 'b > 0' a scale eta: Real number, 'eta > 0' a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Gompertz, density >>> from sympy import Symbol >>> b = Symbol("b", positive=True) >>> eta = Symbol("eta", positive=True) >>> z = Symbol("z") >>> X = Gompertz("x", b, eta) >>> density(X)(z) b*eta*exp(eta)*exp(b*z)*exp(-eta*exp(b*z)) References ========== .. [1] https://en.wikipedia.org/wiki/Gompertz_distribution """ return rv(name, GompertzDistribution, (b, eta)) #------------------------------------------------------------------------------- # Kumaraswamy distribution ----------------------------------------------------- class KumaraswamyDistribution(SingleContinuousDistribution): _argnames = ('a', 'b') set = Interval(0, oo) @staticmethod def check(a, b): _value_check(a > 0, "a must be positive") _value_check(b > 0, "b must be positive") def pdf(self, x): a, b = self.a, self.b return a * b * x**(a-1) * (1-x**a)**(b-1) def _cdf(self, x): a, b = self.a, self.b return Piecewise( (S.Zero, x < S.Zero), (1 - (1 - x**a)**b, x <= S.One), (S.One, True)) def Kumaraswamy(name, a, b): r""" Create a Continuous Random Variable with a Kumaraswamy distribution. Explanation =========== The density of the Kumaraswamy distribution is given by .. math:: f(x) := a b x^{a-1} (1-x^a)^{b-1} with :math:`x \in [0,1]`. Parameters ========== a : Real number, ``a > 0`` a shape b : Real number, ``b > 0`` a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Kumaraswamy, density, cdf >>> from sympy import Symbol, pprint >>> a = Symbol("a", positive=True) >>> b = Symbol("b", positive=True) >>> z = Symbol("z") >>> X = Kumaraswamy("x", a, b) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) b - 1 a - 1 / a\ a*b*z *\1 - z / >>> cdf(X)(z) Piecewise((0, z < 0), (1 - (1 - z**a)**b, z <= 1), (1, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Kumaraswamy_distribution """ return rv(name, KumaraswamyDistribution, (a, b)) #------------------------------------------------------------------------------- # Laplace distribution --------------------------------------------------------- class LaplaceDistribution(SingleContinuousDistribution): _argnames = ('mu', 'b') set = Interval(-oo, oo) @staticmethod def check(mu, b): _value_check(b > 0, "Scale parameter b must be positive.") _value_check(mu.is_real, "Location parameter mu should be real") def pdf(self, x): mu, b = self.mu, self.b return 1/(2*b)*exp(-Abs(x - mu)/b) def _cdf(self, x): mu, b = self.mu, self.b return Piecewise( (S.Half*exp((x - mu)/b), x < mu), (S.One - S.Half*exp(-(x - mu)/b), x >= mu) ) def _characteristic_function(self, t): return exp(self.mu*I*t) / (1 + self.b**2*t**2) def _moment_generating_function(self, t): return exp(self.mu*t) / (1 - self.b**2*t**2) def Laplace(name, mu, b): r""" Create a continuous random variable with a Laplace distribution. Explanation =========== The density of the Laplace distribution is given by .. math:: f(x) := \frac{1}{2 b} \exp \left(-\frac{|x-\mu|}b \right) Parameters ========== mu : Real number or a list/matrix, the location (mean) or the location vector b : Real number or a positive definite matrix, representing a scale or the covariance matrix. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Laplace, density, cdf >>> from sympy import Symbol, pprint >>> mu = Symbol("mu") >>> b = Symbol("b", positive=True) >>> z = Symbol("z") >>> X = Laplace("x", mu, b) >>> density(X)(z) exp(-Abs(mu - z)/b)/(2*b) >>> cdf(X)(z) Piecewise((exp((-mu + z)/b)/2, mu > z), (1 - exp((mu - z)/b)/2, True)) >>> L = Laplace('L', [1, 2], [[1, 0], [0, 1]]) >>> pprint(density(L)(1, 2), use_unicode=False) 5 / ____\ e *besselk\0, \/ 35 / --------------------- pi References ========== .. [1] https://en.wikipedia.org/wiki/Laplace_distribution .. [2] http://mathworld.wolfram.com/LaplaceDistribution.html """ if isinstance(mu, (list, MatrixBase)) and\ isinstance(b, (list, MatrixBase)): from sympy.stats.joint_rv_types import MultivariateLaplace return MultivariateLaplace(name, mu, b) return rv(name, LaplaceDistribution, (mu, b)) #------------------------------------------------------------------------------- # Levy distribution --------------------------------------------------------- class LevyDistribution(SingleContinuousDistribution): _argnames = ('mu', 'c') @property def set(self): return Interval(self.mu, oo) @staticmethod def check(mu, c): _value_check(c > 0, "c (scale parameter) must be positive") _value_check(mu.is_real, "mu (location paramater) must be real") def pdf(self, x): mu, c = self.mu, self.c return sqrt(c/(2*pi))*exp(-c/(2*(x - mu)))/((x - mu)**(S.One + S.Half)) def _cdf(self, x): mu, c = self.mu, self.c return erfc(sqrt(c/(2*(x - mu)))) def _characteristic_function(self, t): mu, c = self.mu, self.c return exp(I * mu * t - sqrt(-2 * I * c * t)) def _moment_generating_function(self, t): raise NotImplementedError('The moment generating function of Levy distribution does not exist.') def Levy(name, mu, c): r""" Create a continuous random variable with a Levy distribution. The density of the Levy distribution is given by .. math:: f(x) := \sqrt(\frac{c}{2 \pi}) \frac{\exp -\frac{c}{2 (x - \mu)}}{(x - \mu)^{3/2}} Parameters ========== mu : Real number The location parameter. c : Real number, ``c > 0`` A scale parameter. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Levy, density, cdf >>> from sympy import Symbol >>> mu = Symbol("mu", real=True) >>> c = Symbol("c", positive=True) >>> z = Symbol("z") >>> X = Levy("x", mu, c) >>> density(X)(z) sqrt(2)*sqrt(c)*exp(-c/(-2*mu + 2*z))/(2*sqrt(pi)*(-mu + z)**(3/2)) >>> cdf(X)(z) erfc(sqrt(c)*sqrt(1/(-2*mu + 2*z))) References ========== .. [1] https://en.wikipedia.org/wiki/L%C3%A9vy_distribution .. [2] http://mathworld.wolfram.com/LevyDistribution.html """ return rv(name, LevyDistribution, (mu, c)) #------------------------------------------------------------------------------- # Log-Cauchy distribution -------------------------------------------------------- class LogCauchyDistribution(SingleContinuousDistribution): _argnames = ('mu', 'sigma') set = Interval.open(0, oo) @staticmethod def check(mu, sigma): _value_check((sigma > 0) != False, "Scale parameter Gamma must be positive.") _value_check(mu.is_real != False, "Location parameter must be real.") def pdf(self, x): mu, sigma = self.mu, self.sigma return 1/(x*pi)*(sigma/((log(x) - mu)**2 + sigma**2)) def _cdf(self, x): mu, sigma = self.mu, self.sigma return (1/pi)*atan((log(x) - mu)/sigma) + S.Half def _characteristic_function(self, t): raise NotImplementedError("The characteristic function for the " "Log-Cauchy distribution does not exist.") def _moment_generating_function(self, t): raise NotImplementedError("The moment generating function for the " "Log-Cauchy distribution does not exist.") def LogCauchy(name, mu, sigma): r""" Create a continuous random variable with a Log-Cauchy distribution. The density of the Log-Cauchy distribution is given by .. math:: f(x) := \frac{1}{\pi x} \frac{\sigma}{(log(x)-\mu^2) + \sigma^2} Parameters ========== mu : Real number, the location sigma : Real number, `\sigma > 0`, a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import LogCauchy, density, cdf >>> from sympy import Symbol, S >>> mu = 2 >>> sigma = S.One / 5 >>> z = Symbol("z") >>> X = LogCauchy("x", mu, sigma) >>> density(X)(z) 1/(5*pi*z*((log(z) - 2)**2 + 1/25)) >>> cdf(X)(z) atan(5*log(z) - 10)/pi + 1/2 References ========== .. [1] https://en.wikipedia.org/wiki/Log-Cauchy_distribution """ return rv(name, LogCauchyDistribution, (mu, sigma)) #------------------------------------------------------------------------------- # Logistic distribution -------------------------------------------------------- class LogisticDistribution(SingleContinuousDistribution): _argnames = ('mu', 's') set = Interval(-oo, oo) @staticmethod def check(mu, s): _value_check(s > 0, "Scale parameter s must be positive.") def pdf(self, x): mu, s = self.mu, self.s return exp(-(x - mu)/s)/(s*(1 + exp(-(x - mu)/s))**2) def _cdf(self, x): mu, s = self.mu, self.s return S.One/(1 + exp(-(x - mu)/s)) def _characteristic_function(self, t): return Piecewise((exp(I*t*self.mu) * pi*self.s*t / sinh(pi*self.s*t), Ne(t, 0)), (S.One, True)) def _moment_generating_function(self, t): return exp(self.mu*t) * beta_fn(1 - self.s*t, 1 + self.s*t) def _quantile(self, p): return self.mu - self.s*log(-S.One + S.One/p) def Logistic(name, mu, s): r""" Create a continuous random variable with a logistic distribution. Explanation =========== The density of the logistic distribution is given by .. math:: f(x) := \frac{e^{-(x-\mu)/s}} {s\left(1+e^{-(x-\mu)/s}\right)^2} Parameters ========== mu : Real number, the location (mean) s : Real number, `s > 0` a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Logistic, density, cdf >>> from sympy import Symbol >>> mu = Symbol("mu", real=True) >>> s = Symbol("s", positive=True) >>> z = Symbol("z") >>> X = Logistic("x", mu, s) >>> density(X)(z) exp((mu - z)/s)/(s*(exp((mu - z)/s) + 1)**2) >>> cdf(X)(z) 1/(exp((mu - z)/s) + 1) References ========== .. [1] https://en.wikipedia.org/wiki/Logistic_distribution .. [2] http://mathworld.wolfram.com/LogisticDistribution.html """ return rv(name, LogisticDistribution, (mu, s)) #------------------------------------------------------------------------------- # Log-logistic distribution -------------------------------------------------------- class LogLogisticDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta') set = Interval(0, oo) @staticmethod def check(alpha, beta): _value_check(alpha > 0, "Scale parameter Alpha must be positive.") _value_check(beta > 0, "Shape parameter Beta must be positive.") def pdf(self, x): a, b = self.alpha, self.beta return ((b/a)*(x/a)**(b - 1))/(1 + (x/a)**b)**2 def _cdf(self, x): a, b = self.alpha, self.beta return 1/(1 + (x/a)**(-b)) def _quantile(self, p): a, b = self.alpha, self.beta return a*((p/(1 - p))**(1/b)) def expectation(self, expr, var, **kwargs): a, b = self.args return Piecewise((S.NaN, b <= 1), (pi*a/(b*sin(pi/b)), True)) def LogLogistic(name, alpha, beta): r""" Create a continuous random variable with a log-logistic distribution. The distribution is unimodal when ``beta > 1``. Explanation =========== The density of the log-logistic distribution is given by .. math:: f(x) := \frac{(\frac{\beta}{\alpha})(\frac{x}{\alpha})^{\beta - 1}} {(1 + (\frac{x}{\alpha})^{\beta})^2} Parameters ========== alpha : Real number, `\alpha > 0`, scale parameter and median of distribution beta : Real number, `\beta > 0` a shape parameter Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import LogLogistic, density, cdf, quantile >>> from sympy import Symbol, pprint >>> alpha = Symbol("alpha", positive=True) >>> beta = Symbol("beta", positive=True) >>> p = Symbol("p") >>> z = Symbol("z", positive=True) >>> X = LogLogistic("x", alpha, beta) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) beta - 1 / z \ beta*|-----| \alpha/ ------------------------ 2 / beta \ |/ z \ | alpha*||-----| + 1| \\alpha/ / >>> cdf(X)(z) 1/(1 + (z/alpha)**(-beta)) >>> quantile(X)(p) alpha*(p/(1 - p))**(1/beta) References ========== .. [1] https://en.wikipedia.org/wiki/Log-logistic_distribution """ return rv(name, LogLogisticDistribution, (alpha, beta)) #------------------------------------------------------------------------------- #Logit-Normal distribution------------------------------------------------------ class LogitNormalDistribution(SingleContinuousDistribution): _argnames = ('mu', 's') set = Interval.open(0, 1) @staticmethod def check(mu, s): _value_check((s ** 2).is_real is not False and s ** 2 > 0, "Squared scale parameter s must be positive.") _value_check(mu.is_real is not False, "Location parameter must be real") def _logit(self, x): return log(x / (1 - x)) def pdf(self, x): mu, s = self.mu, self.s return exp(-(self._logit(x) - mu)**2/(2*s**2))*(S.One/sqrt(2*pi*(s**2)))*(1/(x*(1 - x))) def _cdf(self, x): mu, s = self.mu, self.s return (S.One/2)*(1 + erf((self._logit(x) - mu)/(sqrt(2*s**2)))) def LogitNormal(name, mu, s): r""" Create a continuous random variable with a Logit-Normal distribution. The density of the logistic distribution is given by .. math:: f(x) := \frac{1}{s \sqrt{2 \pi}} \frac{1}{x(1 - x)} e^{- \frac{(logit(x) - \mu)^2}{s^2}} where logit(x) = \log(\frac{x}{1 - x}) Parameters ========== mu : Real number, the location (mean) s : Real number, `s > 0` a scale Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import LogitNormal, density, cdf >>> from sympy import Symbol,pprint >>> mu = Symbol("mu", real=True) >>> s = Symbol("s", positive=True) >>> z = Symbol("z") >>> X = LogitNormal("x",mu,s) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) 2 / / z \\ -|-mu + log|-----|| \ \1 - z// --------------------- 2 ___ 2*s \/ 2 *e ---------------------------- ____ 2*\/ pi *s*z*(1 - z) >>> density(X)(z) sqrt(2)*exp(-(-mu + log(z/(1 - z)))**2/(2*s**2))/(2*sqrt(pi)*s*z*(1 - z)) >>> cdf(X)(z) erf(sqrt(2)*(-mu + log(z/(1 - z)))/(2*s))/2 + 1/2 References ========== .. [1] https://en.wikipedia.org/wiki/Logit-normal_distribution """ return rv(name, LogitNormalDistribution, (mu, s)) #------------------------------------------------------------------------------- # Log Normal distribution ------------------------------------------------------ class LogNormalDistribution(SingleContinuousDistribution): _argnames = ('mean', 'std') set = Interval(0, oo) @staticmethod def check(mean, std): _value_check(std > 0, "Parameter std must be positive.") def pdf(self, x): mean, std = self.mean, self.std return exp(-(log(x) - mean)**2 / (2*std**2)) / (x*sqrt(2*pi)*std) def _cdf(self, x): mean, std = self.mean, self.std return Piecewise( (S.Half + S.Half*erf((log(x) - mean)/sqrt(2)/std), x > 0), (S.Zero, True) ) def _moment_generating_function(self, t): raise NotImplementedError('Moment generating function of the log-normal distribution is not defined.') def LogNormal(name, mean, std): r""" Create a continuous random variable with a log-normal distribution. Explanation =========== The density of the log-normal distribution is given by .. math:: f(x) := \frac{1}{x\sqrt{2\pi\sigma^2}} e^{-\frac{\left(\ln x-\mu\right)^2}{2\sigma^2}} with :math:`x \geq 0`. Parameters ========== mu : Real number The log-scale. sigma : Real number A shape. ($\sigma^2 > 0$) Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import LogNormal, density >>> from sympy import Symbol, pprint >>> mu = Symbol("mu", real=True) >>> sigma = Symbol("sigma", positive=True) >>> z = Symbol("z") >>> X = LogNormal("x", mu, sigma) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) 2 -(-mu + log(z)) ----------------- 2 ___ 2*sigma \/ 2 *e ------------------------ ____ 2*\/ pi *sigma*z >>> X = LogNormal('x', 0, 1) # Mean 0, standard deviation 1 >>> density(X)(z) sqrt(2)*exp(-log(z)**2/2)/(2*sqrt(pi)*z) References ========== .. [1] https://en.wikipedia.org/wiki/Lognormal .. [2] http://mathworld.wolfram.com/LogNormalDistribution.html """ return rv(name, LogNormalDistribution, (mean, std)) #------------------------------------------------------------------------------- # Lomax Distribution ----------------------------------------------------------- class LomaxDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'lamda',) set = Interval(0, oo) @staticmethod def check(alpha, lamda): _value_check(alpha.is_real, "Shape parameter should be real.") _value_check(lamda.is_real, "Scale parameter should be real.") _value_check(alpha.is_positive, "Shape parameter should be positive.") _value_check(lamda.is_positive, "Scale parameter should be positive.") def pdf(self, x): lamba, alpha = self.lamda, self.alpha return (alpha/lamba) * (S.One + x/lamba)**(-alpha-1) def Lomax(name, alpha, lamda): r""" Create a continuous random variable with a Lomax distribution. Explanation =========== The density of the Lomax distribution is given by .. math:: f(x) := \frac{\alpha}{\lambda}\left[1+\frac{x}{\lambda}\right]^{-(\alpha+1)} Parameters ========== alpha : Real Number, `alpha > 0` Shape parameter lamda : Real Number, `lamda > 0` Scale parameter Examples ======== >>> from sympy.stats import Lomax, density, cdf, E >>> from sympy import symbols >>> a, l = symbols('a, l', positive=True) >>> X = Lomax('X', a, l) >>> x = symbols('x') >>> density(X)(x) a*(1 + x/l)**(-a - 1)/l >>> cdf(X)(x) Piecewise((1 - 1/(1 + x/l)**a, x >= 0), (0, True)) >>> a = 2 >>> X = Lomax('X', a, l) >>> E(X) l Returns ======= RandomSymbol References ========== .. [1] https://en.wikipedia.org/wiki/Lomax_distribution """ return rv(name, LomaxDistribution, (alpha, lamda)) #------------------------------------------------------------------------------- # Maxwell distribution --------------------------------------------------------- class MaxwellDistribution(SingleContinuousDistribution): _argnames = ('a',) set = Interval(0, oo) @staticmethod def check(a): _value_check(a > 0, "Parameter a must be positive.") def pdf(self, x): a = self.a return sqrt(2/pi)*x**2*exp(-x**2/(2*a**2))/a**3 def _cdf(self, x): a = self.a return erf(sqrt(2)*x/(2*a)) - sqrt(2)*x*exp(-x**2/(2*a**2))/(sqrt(pi)*a) def Maxwell(name, a): r""" Create a continuous random variable with a Maxwell distribution. Explanation =========== The density of the Maxwell distribution is given by .. math:: f(x) := \sqrt{\frac{2}{\pi}} \frac{x^2 e^{-x^2/(2a^2)}}{a^3} with :math:`x \geq 0`. .. TODO - what does the parameter mean? Parameters ========== a : Real number, `a > 0` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Maxwell, density, E, variance >>> from sympy import Symbol, simplify >>> a = Symbol("a", positive=True) >>> z = Symbol("z") >>> X = Maxwell("x", a) >>> density(X)(z) sqrt(2)*z**2*exp(-z**2/(2*a**2))/(sqrt(pi)*a**3) >>> E(X) 2*sqrt(2)*a/sqrt(pi) >>> simplify(variance(X)) a**2*(-8 + 3*pi)/pi References ========== .. [1] https://en.wikipedia.org/wiki/Maxwell_distribution .. [2] http://mathworld.wolfram.com/MaxwellDistribution.html """ return rv(name, MaxwellDistribution, (a, )) #------------------------------------------------------------------------------- # Moyal Distribution ----------------------------------------------------------- class MoyalDistribution(SingleContinuousDistribution): _argnames = ('mu', 'sigma') @staticmethod def check(mu, sigma): _value_check(mu.is_real, "Location parameter must be real.") _value_check(sigma.is_real and sigma > 0, "Scale parameter must be real\ and positive.") def pdf(self, x): mu, sigma = self.mu, self.sigma num = exp(-(exp(-(x - mu)/sigma) + (x - mu)/(sigma))/2) den = (sqrt(2*pi) * sigma) return num/den def _characteristic_function(self, t): mu, sigma = self.mu, self.sigma term1 = exp(I*t*mu) term2 = (2**(-I*sigma*t) * gamma(Rational(1, 2) - I*t*sigma)) return (term1 * term2)/sqrt(pi) def _moment_generating_function(self, t): mu, sigma = self.mu, self.sigma term1 = exp(t*mu) term2 = (2**(-1*sigma*t) * gamma(Rational(1, 2) - t*sigma)) return (term1 * term2)/sqrt(pi) def Moyal(name, mu, sigma): r""" Create a continuous random variable with a Moyal distribution. Explanation =========== The density of the Moyal distribution is given by .. math:: f(x) := \frac{\exp-\frac{1}{2}\exp-\frac{x-\mu}{\sigma}-\frac{x-\mu}{2\sigma}}{\sqrt{2\pi}\sigma} with :math:`x \in \mathbb{R}`. Parameters ========== mu : Real number Location parameter sigma : Real positive number Scale parameter Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Moyal, density, cdf >>> from sympy import Symbol, simplify >>> mu = Symbol("mu", real=True) >>> sigma = Symbol("sigma", positive=True, real=True) >>> z = Symbol("z") >>> X = Moyal("x", mu, sigma) >>> density(X)(z) sqrt(2)*exp(-exp((mu - z)/sigma)/2 - (-mu + z)/(2*sigma))/(2*sqrt(pi)*sigma) >>> simplify(cdf(X)(z)) 1 - erf(sqrt(2)*exp((mu - z)/(2*sigma))/2) References ========== .. [1] https://reference.wolfram.com/language/ref/MoyalDistribution.html .. [2] http://www.stat.rice.edu/~dobelman/textfiles/DistributionsHandbook.pdf """ return rv(name, MoyalDistribution, (mu, sigma)) #------------------------------------------------------------------------------- # Nakagami distribution -------------------------------------------------------- class NakagamiDistribution(SingleContinuousDistribution): _argnames = ('mu', 'omega') set = Interval(0, oo) @staticmethod def check(mu, omega): _value_check(mu >= S.Half, "Shape parameter mu must be greater than equal to 1/2.") _value_check(omega > 0, "Spread parameter omega must be positive.") def pdf(self, x): mu, omega = self.mu, self.omega return 2*mu**mu/(gamma(mu)*omega**mu)*x**(2*mu - 1)*exp(-mu/omega*x**2) def _cdf(self, x): mu, omega = self.mu, self.omega return Piecewise( (lowergamma(mu, (mu/omega)*x**2)/gamma(mu), x > 0), (S.Zero, True)) def Nakagami(name, mu, omega): r""" Create a continuous random variable with a Nakagami distribution. Explanation =========== The density of the Nakagami distribution is given by .. math:: f(x) := \frac{2\mu^\mu}{\Gamma(\mu)\omega^\mu} x^{2\mu-1} \exp\left(-\frac{\mu}{\omega}x^2 \right) with :math:`x > 0`. Parameters ========== mu : Real number, `\mu \geq \frac{1}{2}` a shape omega : Real number, `\omega > 0`, the spread Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Nakagami, density, E, variance, cdf >>> from sympy import Symbol, simplify, pprint >>> mu = Symbol("mu", positive=True) >>> omega = Symbol("omega", positive=True) >>> z = Symbol("z") >>> X = Nakagami("x", mu, omega) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) 2 -mu*z ------- mu -mu 2*mu - 1 omega 2*mu *omega *z *e ---------------------------------- Gamma(mu) >>> simplify(E(X)) sqrt(mu)*sqrt(omega)*gamma(mu + 1/2)/gamma(mu + 1) >>> V = simplify(variance(X)) >>> pprint(V, use_unicode=False) 2 omega*Gamma (mu + 1/2) omega - ----------------------- Gamma(mu)*Gamma(mu + 1) >>> cdf(X)(z) Piecewise((lowergamma(mu, mu*z**2/omega)/gamma(mu), z > 0), (0, True)) References ========== .. [1] https://en.wikipedia.org/wiki/Nakagami_distribution """ return rv(name, NakagamiDistribution, (mu, omega)) #------------------------------------------------------------------------------- # Normal distribution ---------------------------------------------------------- class NormalDistribution(SingleContinuousDistribution): _argnames = ('mean', 'std') @staticmethod def check(mean, std): _value_check(std > 0, "Standard deviation must be positive") def pdf(self, x): return exp(-(x - self.mean)**2 / (2*self.std**2)) / (sqrt(2*pi)*self.std) def _cdf(self, x): mean, std = self.mean, self.std return erf(sqrt(2)*(-mean + x)/(2*std))/2 + S.Half def _characteristic_function(self, t): mean, std = self.mean, self.std return exp(I*mean*t - std**2*t**2/2) def _moment_generating_function(self, t): mean, std = self.mean, self.std return exp(mean*t + std**2*t**2/2) def _quantile(self, p): mean, std = self.mean, self.std return mean + std*sqrt(2)*erfinv(2*p - 1) def Normal(name, mean, std): r""" Create a continuous random variable with a Normal distribution. Explanation =========== The density of the Normal distribution is given by .. math:: f(x) := \frac{1}{\sigma\sqrt{2\pi}} e^{ -\frac{(x-\mu)^2}{2\sigma^2} } Parameters ========== mu : Real number or a list representing the mean or the mean vector sigma : Real number or a positive definite square matrix, :math:`\sigma^2 > 0` the variance Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Normal, density, E, std, cdf, skewness, quantile, marginal_distribution >>> from sympy import Symbol, simplify, pprint >>> mu = Symbol("mu") >>> sigma = Symbol("sigma", positive=True) >>> z = Symbol("z") >>> y = Symbol("y") >>> p = Symbol("p") >>> X = Normal("x", mu, sigma) >>> density(X)(z) sqrt(2)*exp(-(-mu + z)**2/(2*sigma**2))/(2*sqrt(pi)*sigma) >>> C = simplify(cdf(X))(z) # it needs a little more help... >>> pprint(C, use_unicode=False) / ___ \ |\/ 2 *(-mu + z)| erf|---------------| \ 2*sigma / 1 -------------------- + - 2 2 >>> quantile(X)(p) mu + sqrt(2)*sigma*erfinv(2*p - 1) >>> simplify(skewness(X)) 0 >>> X = Normal("x", 0, 1) # Mean 0, standard deviation 1 >>> density(X)(z) sqrt(2)*exp(-z**2/2)/(2*sqrt(pi)) >>> E(2*X + 1) 1 >>> simplify(std(2*X + 1)) 2 >>> m = Normal('X', [1, 2], [[2, 1], [1, 2]]) >>> pprint(density(m)(y, z), use_unicode=False) 2 2 y y*z z - -- + --- - -- + z - 1 ___ 3 3 3 \/ 3 *e ------------------------------ 6*pi >>> marginal_distribution(m, m[0])(1) 1/(2*sqrt(pi)) References ========== .. [1] https://en.wikipedia.org/wiki/Normal_distribution .. [2] http://mathworld.wolfram.com/NormalDistributionFunction.html """ if isinstance(mean, list) or getattr(mean, 'is_Matrix', False) and\ isinstance(std, list) or getattr(std, 'is_Matrix', False): from sympy.stats.joint_rv_types import MultivariateNormal return MultivariateNormal(name, mean, std) return rv(name, NormalDistribution, (mean, std)) #------------------------------------------------------------------------------- # Inverse Gaussian distribution ---------------------------------------------------------- class GaussianInverseDistribution(SingleContinuousDistribution): _argnames = ('mean', 'shape') @property def set(self): return Interval(0, oo) @staticmethod def check(mean, shape): _value_check(shape > 0, "Shape parameter must be positive") _value_check(mean > 0, "Mean must be positive") def pdf(self, x): mu, s = self.mean, self.shape return exp(-s*(x - mu)**2 / (2*x*mu**2)) * sqrt(s/(2*pi*x**3)) def _cdf(self, x): from sympy.stats import cdf mu, s = self.mean, self.shape stdNormalcdf = cdf(Normal('x', 0, 1)) first_term = stdNormalcdf(sqrt(s/x) * ((x/mu) - S.One)) second_term = exp(2*s/mu) * stdNormalcdf(-sqrt(s/x)*(x/mu + S.One)) return first_term + second_term def _characteristic_function(self, t): mu, s = self.mean, self.shape return exp((s/mu)*(1 - sqrt(1 - (2*mu**2*I*t)/s))) def _moment_generating_function(self, t): mu, s = self.mean, self.shape return exp((s/mu)*(1 - sqrt(1 - (2*mu**2*t)/s))) def GaussianInverse(name, mean, shape): r""" Create a continuous random variable with an Inverse Gaussian distribution. Inverse Gaussian distribution is also known as Wald distribution. Explanation =========== The density of the Inverse Gaussian distribution is given by .. math:: f(x) := \sqrt{\frac{\lambda}{2\pi x^3}} e^{-\frac{\lambda(x-\mu)^2}{2x\mu^2}} Parameters ========== mu : Positive number representing the mean. lambda : Positive number representing the shape parameter. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import GaussianInverse, density, E, std, skewness >>> from sympy import Symbol, pprint >>> mu = Symbol("mu", positive=True) >>> lamda = Symbol("lambda", positive=True) >>> z = Symbol("z", positive=True) >>> X = GaussianInverse("x", mu, lamda) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) 2 -lambda*(-mu + z) ------------------- 2 ___ ________ 2*mu *z \/ 2 *\/ lambda *e ------------------------------------- ____ 3/2 2*\/ pi *z >>> E(X) mu >>> std(X).expand() mu**(3/2)/sqrt(lambda) >>> skewness(X).expand() 3*sqrt(mu)/sqrt(lambda) References ========== .. [1] https://en.wikipedia.org/wiki/Inverse_Gaussian_distribution .. [2] http://mathworld.wolfram.com/InverseGaussianDistribution.html """ return rv(name, GaussianInverseDistribution, (mean, shape)) Wald = GaussianInverse #------------------------------------------------------------------------------- # Pareto distribution ---------------------------------------------------------- class ParetoDistribution(SingleContinuousDistribution): _argnames = ('xm', 'alpha') @property def set(self): return Interval(self.xm, oo) @staticmethod def check(xm, alpha): _value_check(xm > 0, "Xm must be positive") _value_check(alpha > 0, "Alpha must be positive") def pdf(self, x): xm, alpha = self.xm, self.alpha return alpha * xm**alpha / x**(alpha + 1) def _cdf(self, x): xm, alpha = self.xm, self.alpha return Piecewise( (S.One - xm**alpha/x**alpha, x>=xm), (0, True), ) def _moment_generating_function(self, t): xm, alpha = self.xm, self.alpha return alpha * (-xm*t)**alpha * uppergamma(-alpha, -xm*t) def _characteristic_function(self, t): xm, alpha = self.xm, self.alpha return alpha * (-I * xm * t) ** alpha * uppergamma(-alpha, -I * xm * t) def Pareto(name, xm, alpha): r""" Create a continuous random variable with the Pareto distribution. Explanation =========== The density of the Pareto distribution is given by .. math:: f(x) := \frac{\alpha\,x_m^\alpha}{x^{\alpha+1}} with :math:`x \in [x_m,\infty]`. Parameters ========== xm : Real number, `x_m > 0`, a scale alpha : Real number, `\alpha > 0`, a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Pareto, density >>> from sympy import Symbol >>> xm = Symbol("xm", positive=True) >>> beta = Symbol("beta", positive=True) >>> z = Symbol("z") >>> X = Pareto("x", xm, beta) >>> density(X)(z) beta*xm**beta*z**(-beta - 1) References ========== .. [1] https://en.wikipedia.org/wiki/Pareto_distribution .. [2] http://mathworld.wolfram.com/ParetoDistribution.html """ return rv(name, ParetoDistribution, (xm, alpha)) #------------------------------------------------------------------------------- # PowerFunction distribution --------------------------------------------------- class PowerFunctionDistribution(SingleContinuousDistribution): _argnames=('alpha','a','b') @property def set(self): return Interval(self.a, self.b) @staticmethod def check(alpha, a, b): _value_check(a.is_real, "Continuous Boundary parameter should be real.") _value_check(b.is_real, "Continuous Boundary parameter should be real.") _value_check(a < b, " 'a' the left Boundary must be smaller than 'b' the right Boundary." ) _value_check(alpha.is_positive, "Continuous Shape parameter should be positive.") def pdf(self, x): alpha, a, b = self.alpha, self.a, self.b num = alpha*(x - a)**(alpha - 1) den = (b - a)**alpha return num/den def PowerFunction(name, alpha, a, b): r""" Creates a continuous random variable with a Power Function Distribution. Explanation =========== The density of PowerFunction distribution is given by .. math:: f(x) := \frac{{\alpha}(x - a)^{\alpha - 1}}{(b - a)^{\alpha}} with :math:`x \in [a,b]`. Parameters ========== alpha: Positive number, `0 < alpha` the shape paramater a : Real number, :math:`-\infty < a` the left boundary b : Real number, :math:`a < b < \infty` the right boundary Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import PowerFunction, density, cdf, E, variance >>> from sympy import Symbol >>> alpha = Symbol("alpha", positive=True) >>> a = Symbol("a", real=True) >>> b = Symbol("b", real=True) >>> z = Symbol("z") >>> X = PowerFunction("X", 2, a, b) >>> density(X)(z) (-2*a + 2*z)/(-a + b)**2 >>> cdf(X)(z) Piecewise((a**2/(a**2 - 2*a*b + b**2) - 2*a*z/(a**2 - 2*a*b + b**2) + z**2/(a**2 - 2*a*b + b**2), a <= z), (0, True)) >>> alpha = 2 >>> a = 0 >>> b = 1 >>> Y = PowerFunction("Y", alpha, a, b) >>> E(Y) 2/3 >>> variance(Y) 1/18 References ========== .. [1] http://www.mathwave.com/help/easyfit/html/analyses/distributions/power_func.html """ return rv(name, PowerFunctionDistribution, (alpha, a, b)) #------------------------------------------------------------------------------- # QuadraticU distribution ------------------------------------------------------ class QuadraticUDistribution(SingleContinuousDistribution): _argnames = ('a', 'b') @property def set(self): return Interval(self.a, self.b) @staticmethod def check(a, b): _value_check(b > a, "Parameter b must be in range (%s, oo)."%(a)) def pdf(self, x): a, b = self.a, self.b alpha = 12 / (b-a)**3 beta = (a+b) / 2 return Piecewise( (alpha * (x-beta)**2, And(a<=x, x<=b)), (S.Zero, True)) def _moment_generating_function(self, t): a, b = self.a, self.b return -3 * (exp(a*t) * (4 + (a**2 + 2*a*(-2 + b) + b**2) * t) \ - exp(b*t) * (4 + (-4*b + (a + b)**2) * t)) / ((a-b)**3 * t**2) def _characteristic_function(self, t): a, b = self.a, self.b return -3*I*(exp(I*a*t*exp(I*b*t)) * (4*I - (-4*b + (a+b)**2)*t)) \ / ((a-b)**3 * t**2) def QuadraticU(name, a, b): r""" Create a Continuous Random Variable with a U-quadratic distribution. Explanation =========== The density of the U-quadratic distribution is given by .. math:: f(x) := \alpha (x-\beta)^2 with :math:`x \in [a,b]`. Parameters ========== a : Real number b : Real number, :math:`a < b` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import QuadraticU, density >>> from sympy import Symbol, pprint >>> a = Symbol("a", real=True) >>> b = Symbol("b", real=True) >>> z = Symbol("z") >>> X = QuadraticU("x", a, b) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) / 2 | / a b \ |12*|- - - - + z| | \ 2 2 / <----------------- for And(b >= z, a <= z) | 3 | (-a + b) | \ 0 otherwise References ========== .. [1] https://en.wikipedia.org/wiki/U-quadratic_distribution """ return rv(name, QuadraticUDistribution, (a, b)) #------------------------------------------------------------------------------- # RaisedCosine distribution ---------------------------------------------------- class RaisedCosineDistribution(SingleContinuousDistribution): _argnames = ('mu', 's') @property def set(self): return Interval(self.mu - self.s, self.mu + self.s) @staticmethod def check(mu, s): _value_check(s > 0, "s must be positive") def pdf(self, x): mu, s = self.mu, self.s return Piecewise( ((1+cos(pi*(x-mu)/s)) / (2*s), And(mu-s<=x, x<=mu+s)), (S.Zero, True)) def _characteristic_function(self, t): mu, s = self.mu, self.s return Piecewise((exp(-I*pi*mu/s)/2, Eq(t, -pi/s)), (exp(I*pi*mu/s)/2, Eq(t, pi/s)), (pi**2*sin(s*t)*exp(I*mu*t) / (s*t*(pi**2 - s**2*t**2)), True)) def _moment_generating_function(self, t): mu, s = self.mu, self.s return pi**2 * sinh(s*t) * exp(mu*t) / (s*t*(pi**2 + s**2*t**2)) def RaisedCosine(name, mu, s): r""" Create a Continuous Random Variable with a raised cosine distribution. Explanation =========== The density of the raised cosine distribution is given by .. math:: f(x) := \frac{1}{2s}\left(1+\cos\left(\frac{x-\mu}{s}\pi\right)\right) with :math:`x \in [\mu-s,\mu+s]`. Parameters ========== mu : Real number s : Real number, `s > 0` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import RaisedCosine, density >>> from sympy import Symbol, pprint >>> mu = Symbol("mu", real=True) >>> s = Symbol("s", positive=True) >>> z = Symbol("z") >>> X = RaisedCosine("x", mu, s) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) / /pi*(-mu + z)\ |cos|------------| + 1 | \ s / <--------------------- for And(z >= mu - s, z <= mu + s) | 2*s | \ 0 otherwise References ========== .. [1] https://en.wikipedia.org/wiki/Raised_cosine_distribution """ return rv(name, RaisedCosineDistribution, (mu, s)) #------------------------------------------------------------------------------- # Rayleigh distribution -------------------------------------------------------- class RayleighDistribution(SingleContinuousDistribution): _argnames = ('sigma',) set = Interval(0, oo) @staticmethod def check(sigma): _value_check(sigma > 0, "Scale parameter sigma must be positive.") def pdf(self, x): sigma = self.sigma return x/sigma**2*exp(-x**2/(2*sigma**2)) def _cdf(self, x): sigma = self.sigma return 1 - exp(-(x**2/(2*sigma**2))) def _characteristic_function(self, t): sigma = self.sigma return 1 - sigma*t*exp(-sigma**2*t**2/2) * sqrt(pi/2) * (erfi(sigma*t/sqrt(2)) - I) def _moment_generating_function(self, t): sigma = self.sigma return 1 + sigma*t*exp(sigma**2*t**2/2) * sqrt(pi/2) * (erf(sigma*t/sqrt(2)) + 1) def Rayleigh(name, sigma): r""" Create a continuous random variable with a Rayleigh distribution. Explanation =========== The density of the Rayleigh distribution is given by .. math :: f(x) := \frac{x}{\sigma^2} e^{-x^2/2\sigma^2} with :math:`x > 0`. Parameters ========== sigma : Real number, `\sigma > 0` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Rayleigh, density, E, variance >>> from sympy import Symbol >>> sigma = Symbol("sigma", positive=True) >>> z = Symbol("z") >>> X = Rayleigh("x", sigma) >>> density(X)(z) z*exp(-z**2/(2*sigma**2))/sigma**2 >>> E(X) sqrt(2)*sqrt(pi)*sigma/2 >>> variance(X) -pi*sigma**2/2 + 2*sigma**2 References ========== .. [1] https://en.wikipedia.org/wiki/Rayleigh_distribution .. [2] http://mathworld.wolfram.com/RayleighDistribution.html """ return rv(name, RayleighDistribution, (sigma, )) #------------------------------------------------------------------------------- # Reciprocal distribution -------------------------------------------------------- class ReciprocalDistribution(SingleContinuousDistribution): _argnames = ('a', 'b') @property def set(self): return Interval(self.a, self.b) @staticmethod def check(a, b): _value_check(a > 0, "Parameter > 0. a = %s"%a) _value_check((a < b), "Parameter b must be in range (%s, +oo]. b = %s"%(a, b)) def pdf(self, x): a, b = self.a, self.b return 1/(x*(log(b) - log(a))) def Reciprocal(name, a, b): r"""Creates a continuous random variable with a reciprocal distribution. Parameters ========== a : Real number, :math:`0 < a` b : Real number, :math:`a < b` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Reciprocal, density, cdf >>> from sympy import symbols >>> a, b, x = symbols('a, b, x', positive=True) >>> R = Reciprocal('R', a, b) >>> density(R)(x) 1/(x*(-log(a) + log(b))) >>> cdf(R)(x) Piecewise((log(a)/(log(a) - log(b)) - log(x)/(log(a) - log(b)), a <= x), (0, True)) Reference ========= .. [1] https://en.wikipedia.org/wiki/Reciprocal_distribution """ return rv(name, ReciprocalDistribution, (a, b)) #------------------------------------------------------------------------------- # Shifted Gompertz distribution ------------------------------------------------ class ShiftedGompertzDistribution(SingleContinuousDistribution): _argnames = ('b', 'eta') set = Interval(0, oo) @staticmethod def check(b, eta): _value_check(b > 0, "b must be positive") _value_check(eta > 0, "eta must be positive") def pdf(self, x): b, eta = self.b, self.eta return b*exp(-b*x)*exp(-eta*exp(-b*x))*(1+eta*(1-exp(-b*x))) def ShiftedGompertz(name, b, eta): r""" Create a continuous random variable with a Shifted Gompertz distribution. Explanation =========== The density of the Shifted Gompertz distribution is given by .. math:: f(x) := b e^{-b x} e^{-\eta \exp(-b x)} \left[1 + \eta(1 - e^(-bx)) \right] with :math: 'x \in [0, \inf)'. Parameters ========== b: Real number, 'b > 0' a scale eta: Real number, 'eta > 0' a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import ShiftedGompertz, density >>> from sympy import Symbol >>> b = Symbol("b", positive=True) >>> eta = Symbol("eta", positive=True) >>> x = Symbol("x") >>> X = ShiftedGompertz("x", b, eta) >>> density(X)(x) b*(eta*(1 - exp(-b*x)) + 1)*exp(-b*x)*exp(-eta*exp(-b*x)) References ========== .. [1] https://en.wikipedia.org/wiki/Shifted_Gompertz_distribution """ return rv(name, ShiftedGompertzDistribution, (b, eta)) #------------------------------------------------------------------------------- # StudentT distribution -------------------------------------------------------- class StudentTDistribution(SingleContinuousDistribution): _argnames = ('nu',) set = Interval(-oo, oo) @staticmethod def check(nu): _value_check(nu > 0, "Degrees of freedom nu must be positive.") def pdf(self, x): nu = self.nu return 1/(sqrt(nu)*beta_fn(S.Half, nu/2))*(1 + x**2/nu)**(-(nu + 1)/2) def _cdf(self, x): nu = self.nu return S.Half + x*gamma((nu+1)/2)*hyper((S.Half, (nu+1)/2), (Rational(3, 2),), -x**2/nu)/(sqrt(pi*nu)*gamma(nu/2)) def _moment_generating_function(self, t): raise NotImplementedError('The moment generating function for the Student-T distribution is undefined.') def StudentT(name, nu): r""" Create a continuous random variable with a student's t distribution. Explanation =========== The density of the student's t distribution is given by .. math:: f(x) := \frac{\Gamma \left(\frac{\nu+1}{2} \right)} {\sqrt{\nu\pi}\Gamma \left(\frac{\nu}{2} \right)} \left(1+\frac{x^2}{\nu} \right)^{-\frac{\nu+1}{2}} Parameters ========== nu : Real number, `\nu > 0`, the degrees of freedom Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import StudentT, density, cdf >>> from sympy import Symbol, pprint >>> nu = Symbol("nu", positive=True) >>> z = Symbol("z") >>> X = StudentT("x", nu) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) nu 1 - -- - - 2 2 / 2\ | z | |1 + --| \ nu/ ----------------- ____ / nu\ \/ nu *B|1/2, --| \ 2 / >>> cdf(X)(z) 1/2 + z*gamma(nu/2 + 1/2)*hyper((1/2, nu/2 + 1/2), (3/2,), -z**2/nu)/(sqrt(pi)*sqrt(nu)*gamma(nu/2)) References ========== .. [1] https://en.wikipedia.org/wiki/Student_t-distribution .. [2] http://mathworld.wolfram.com/Studentst-Distribution.html """ return rv(name, StudentTDistribution, (nu, )) #------------------------------------------------------------------------------- # Trapezoidal distribution ------------------------------------------------------ class TrapezoidalDistribution(SingleContinuousDistribution): _argnames = ('a', 'b', 'c', 'd') @property def set(self): return Interval(self.a, self.d) @staticmethod def check(a, b, c, d): _value_check(a < d, "Lower bound parameter a < %s. a = %s"%(d, a)) _value_check((a <= b, b < c), "Level start parameter b must be in range [%s, %s). b = %s"%(a, c, b)) _value_check((b < c, c <= d), "Level end parameter c must be in range (%s, %s]. c = %s"%(b, d, c)) _value_check(d >= c, "Upper bound parameter d > %s. d = %s"%(c, d)) def pdf(self, x): a, b, c, d = self.a, self.b, self.c, self.d return Piecewise( (2*(x-a) / ((b-a)*(d+c-a-b)), And(a <= x, x < b)), (2 / (d+c-a-b), And(b <= x, x < c)), (2*(d-x) / ((d-c)*(d+c-a-b)), And(c <= x, x <= d)), (S.Zero, True)) def Trapezoidal(name, a, b, c, d): r""" Create a continuous random variable with a trapezoidal distribution. Explanation =========== The density of the trapezoidal distribution is given by .. math:: f(x) := \begin{cases} 0 & \mathrm{for\ } x < a, \\ \frac{2(x-a)}{(b-a)(d+c-a-b)} & \mathrm{for\ } a \le x < b, \\ \frac{2}{d+c-a-b} & \mathrm{for\ } b \le x < c, \\ \frac{2(d-x)}{(d-c)(d+c-a-b)} & \mathrm{for\ } c \le x < d, \\ 0 & \mathrm{for\ } d < x. \end{cases} Parameters ========== a : Real number, :math:`a < d` b : Real number, :math:`a <= b < c` c : Real number, :math:`b < c <= d` d : Real number Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Trapezoidal, density >>> from sympy import Symbol, pprint >>> a = Symbol("a") >>> b = Symbol("b") >>> c = Symbol("c") >>> d = Symbol("d") >>> z = Symbol("z") >>> X = Trapezoidal("x", a,b,c,d) >>> pprint(density(X)(z), use_unicode=False) / -2*a + 2*z |------------------------- for And(a <= z, b > z) |(-a + b)*(-a - b + c + d) | | 2 | -------------- for And(b <= z, c > z) < -a - b + c + d | | 2*d - 2*z |------------------------- for And(d >= z, c <= z) |(-c + d)*(-a - b + c + d) | \ 0 otherwise References ========== .. [1] https://en.wikipedia.org/wiki/Trapezoidal_distribution """ return rv(name, TrapezoidalDistribution, (a, b, c, d)) #------------------------------------------------------------------------------- # Triangular distribution ------------------------------------------------------ class TriangularDistribution(SingleContinuousDistribution): _argnames = ('a', 'b', 'c') @property def set(self): return Interval(self.a, self.b) @staticmethod def check(a, b, c): _value_check(b > a, "Parameter b > %s. b = %s"%(a, b)) _value_check((a <= c, c <= b), "Parameter c must be in range [%s, %s]. c = %s"%(a, b, c)) def pdf(self, x): a, b, c = self.a, self.b, self.c return Piecewise( (2*(x - a)/((b - a)*(c - a)), And(a <= x, x < c)), (2/(b - a), Eq(x, c)), (2*(b - x)/((b - a)*(b - c)), And(c < x, x <= b)), (S.Zero, True)) def _characteristic_function(self, t): a, b, c = self.a, self.b, self.c return -2 *((b-c) * exp(I*a*t) - (b-a) * exp(I*c*t) + (c-a) * exp(I*b*t)) / ((b-a)*(c-a)*(b-c)*t**2) def _moment_generating_function(self, t): a, b, c = self.a, self.b, self.c return 2 * ((b - c) * exp(a * t) - (b - a) * exp(c * t) + (c - a) * exp(b * t)) / ( (b - a) * (c - a) * (b - c) * t ** 2) def Triangular(name, a, b, c): r""" Create a continuous random variable with a triangular distribution. Explanation =========== The density of the triangular distribution is given by .. math:: f(x) := \begin{cases} 0 & \mathrm{for\ } x < a, \\ \frac{2(x-a)}{(b-a)(c-a)} & \mathrm{for\ } a \le x < c, \\ \frac{2}{b-a} & \mathrm{for\ } x = c, \\ \frac{2(b-x)}{(b-a)(b-c)} & \mathrm{for\ } c < x \le b, \\ 0 & \mathrm{for\ } b < x. \end{cases} Parameters ========== a : Real number, :math:`a \in \left(-\infty, \infty\right)` b : Real number, :math:`a < b` c : Real number, :math:`a \leq c \leq b` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Triangular, density >>> from sympy import Symbol, pprint >>> a = Symbol("a") >>> b = Symbol("b") >>> c = Symbol("c") >>> z = Symbol("z") >>> X = Triangular("x", a,b,c) >>> pprint(density(X)(z), use_unicode=False) / -2*a + 2*z |----------------- for And(a <= z, c > z) |(-a + b)*(-a + c) | | 2 | ------ for c = z < -a + b | | 2*b - 2*z |---------------- for And(b >= z, c < z) |(-a + b)*(b - c) | \ 0 otherwise References ========== .. [1] https://en.wikipedia.org/wiki/Triangular_distribution .. [2] http://mathworld.wolfram.com/TriangularDistribution.html """ return rv(name, TriangularDistribution, (a, b, c)) #------------------------------------------------------------------------------- # Uniform distribution --------------------------------------------------------- class UniformDistribution(SingleContinuousDistribution): _argnames = ('left', 'right') @property def set(self): return Interval(self.left, self.right) @staticmethod def check(left, right): _value_check(left < right, "Lower limit should be less than Upper limit.") def pdf(self, x): left, right = self.left, self.right return Piecewise( (S.One/(right - left), And(left <= x, x <= right)), (S.Zero, True) ) def _cdf(self, x): left, right = self.left, self.right return Piecewise( (S.Zero, x < left), ((x - left)/(right - left), x <= right), (S.One, True) ) def _characteristic_function(self, t): left, right = self.left, self.right return Piecewise(((exp(I*t*right) - exp(I*t*left)) / (I*t*(right - left)), Ne(t, 0)), (S.One, True)) def _moment_generating_function(self, t): left, right = self.left, self.right return Piecewise(((exp(t*right) - exp(t*left)) / (t * (right - left)), Ne(t, 0)), (S.One, True)) def expectation(self, expr, var, **kwargs): from sympy.functions.elementary.miscellaneous import (Max, Min) kwargs['evaluate'] = True result = SingleContinuousDistribution.expectation(self, expr, var, **kwargs) result = result.subs({Max(self.left, self.right): self.right, Min(self.left, self.right): self.left}) return result def Uniform(name, left, right): r""" Create a continuous random variable with a uniform distribution. Explanation =========== The density of the uniform distribution is given by .. math:: f(x) := \begin{cases} \frac{1}{b - a} & \text{for } x \in [a,b] \\ 0 & \text{otherwise} \end{cases} with :math:`x \in [a,b]`. Parameters ========== a : Real number, :math:`-\infty < a` the left boundary b : Real number, :math:`a < b < \infty` the right boundary Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Uniform, density, cdf, E, variance >>> from sympy import Symbol, simplify >>> a = Symbol("a", negative=True) >>> b = Symbol("b", positive=True) >>> z = Symbol("z") >>> X = Uniform("x", a, b) >>> density(X)(z) Piecewise((1/(-a + b), (b >= z) & (a <= z)), (0, True)) >>> cdf(X)(z) Piecewise((0, a > z), ((-a + z)/(-a + b), b >= z), (1, True)) >>> E(X) a/2 + b/2 >>> simplify(variance(X)) a**2/12 - a*b/6 + b**2/12 References ========== .. [1] https://en.wikipedia.org/wiki/Uniform_distribution_%28continuous%29 .. [2] http://mathworld.wolfram.com/UniformDistribution.html """ return rv(name, UniformDistribution, (left, right)) #------------------------------------------------------------------------------- # UniformSum distribution ------------------------------------------------------ class UniformSumDistribution(SingleContinuousDistribution): _argnames = ('n',) @property def set(self): return Interval(0, self.n) @staticmethod def check(n): _value_check((n > 0, n.is_integer), "Parameter n must be positive integer.") def pdf(self, x): n = self.n k = Dummy("k") return 1/factorial( n - 1)*Sum((-1)**k*binomial(n, k)*(x - k)**(n - 1), (k, 0, floor(x))) def _cdf(self, x): n = self.n k = Dummy("k") return Piecewise((S.Zero, x < 0), (1/factorial(n)*Sum((-1)**k*binomial(n, k)*(x - k)**(n), (k, 0, floor(x))), x <= n), (S.One, True)) def _characteristic_function(self, t): return ((exp(I*t) - 1) / (I*t))**self.n def _moment_generating_function(self, t): return ((exp(t) - 1) / t)**self.n def UniformSum(name, n): r""" Create a continuous random variable with an Irwin-Hall distribution. Explanation =========== The probability distribution function depends on a single parameter $n$ which is an integer. The density of the Irwin-Hall distribution is given by .. math :: f(x) := \frac{1}{(n-1)!}\sum_{k=0}^{\left\lfloor x\right\rfloor}(-1)^k \binom{n}{k}(x-k)^{n-1} Parameters ========== n : A positive Integer, `n > 0` Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import UniformSum, density, cdf >>> from sympy import Symbol, pprint >>> n = Symbol("n", integer=True) >>> z = Symbol("z") >>> X = UniformSum("x", n) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) floor(z) ___ \ ` \ k n - 1 /n\ ) (-1) *(-k + z) *| | / \k/ /__, k = 0 -------------------------------- (n - 1)! >>> cdf(X)(z) Piecewise((0, z < 0), (Sum((-1)**_k*(-_k + z)**n*binomial(n, _k), (_k, 0, floor(z)))/factorial(n), n >= z), (1, True)) Compute cdf with specific 'x' and 'n' values as follows : >>> cdf(UniformSum("x", 5), evaluate=False)(2).doit() 9/40 The argument evaluate=False prevents an attempt at evaluation of the sum for general n, before the argument 2 is passed. References ========== .. [1] https://en.wikipedia.org/wiki/Uniform_sum_distribution .. [2] http://mathworld.wolfram.com/UniformSumDistribution.html """ return rv(name, UniformSumDistribution, (n, )) #------------------------------------------------------------------------------- # VonMises distribution -------------------------------------------------------- class VonMisesDistribution(SingleContinuousDistribution): _argnames = ('mu', 'k') set = Interval(0, 2*pi) @staticmethod def check(mu, k): _value_check(k > 0, "k must be positive") def pdf(self, x): mu, k = self.mu, self.k return exp(k*cos(x-mu)) / (2*pi*besseli(0, k)) def VonMises(name, mu, k): r""" Create a Continuous Random Variable with a von Mises distribution. Explanation =========== The density of the von Mises distribution is given by .. math:: f(x) := \frac{e^{\kappa\cos(x-\mu)}}{2\pi I_0(\kappa)} with :math:`x \in [0,2\pi]`. Parameters ========== mu : Real number Measure of location. k : Real number Measure of concentration. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import VonMises, density >>> from sympy import Symbol, pprint >>> mu = Symbol("mu") >>> k = Symbol("k", positive=True) >>> z = Symbol("z") >>> X = VonMises("x", mu, k) >>> D = density(X)(z) >>> pprint(D, use_unicode=False) k*cos(mu - z) e ------------------ 2*pi*besseli(0, k) References ========== .. [1] https://en.wikipedia.org/wiki/Von_Mises_distribution .. [2] http://mathworld.wolfram.com/vonMisesDistribution.html """ return rv(name, VonMisesDistribution, (mu, k)) #------------------------------------------------------------------------------- # Weibull distribution --------------------------------------------------------- class WeibullDistribution(SingleContinuousDistribution): _argnames = ('alpha', 'beta') set = Interval(0, oo) @staticmethod def check(alpha, beta): _value_check(alpha > 0, "Alpha must be positive") _value_check(beta > 0, "Beta must be positive") def pdf(self, x): alpha, beta = self.alpha, self.beta return beta * (x/alpha)**(beta - 1) * exp(-(x/alpha)**beta) / alpha def Weibull(name, alpha, beta): r""" Create a continuous random variable with a Weibull distribution. Explanation =========== The density of the Weibull distribution is given by .. math:: f(x) := \begin{cases} \frac{k}{\lambda}\left(\frac{x}{\lambda}\right)^{k-1} e^{-(x/\lambda)^{k}} & x\geq0\\ 0 & x<0 \end{cases} Parameters ========== lambda : Real number, :math:`\lambda > 0` a scale k : Real number, ``k > 0`` a shape Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import Weibull, density, E, variance >>> from sympy import Symbol, simplify >>> l = Symbol("lambda", positive=True) >>> k = Symbol("k", positive=True) >>> z = Symbol("z") >>> X = Weibull("x", l, k) >>> density(X)(z) k*(z/lambda)**(k - 1)*exp(-(z/lambda)**k)/lambda >>> simplify(E(X)) lambda*gamma(1 + 1/k) >>> simplify(variance(X)) lambda**2*(-gamma(1 + 1/k)**2 + gamma(1 + 2/k)) References ========== .. [1] https://en.wikipedia.org/wiki/Weibull_distribution .. [2] http://mathworld.wolfram.com/WeibullDistribution.html """ return rv(name, WeibullDistribution, (alpha, beta)) #------------------------------------------------------------------------------- # Wigner semicircle distribution ----------------------------------------------- class WignerSemicircleDistribution(SingleContinuousDistribution): _argnames = ('R',) @property def set(self): return Interval(-self.R, self.R) @staticmethod def check(R): _value_check(R > 0, "Radius R must be positive.") def pdf(self, x): R = self.R return 2/(pi*R**2)*sqrt(R**2 - x**2) def _characteristic_function(self, t): return Piecewise((2 * besselj(1, self.R*t) / (self.R*t), Ne(t, 0)), (S.One, True)) def _moment_generating_function(self, t): return Piecewise((2 * besseli(1, self.R*t) / (self.R*t), Ne(t, 0)), (S.One, True)) def WignerSemicircle(name, R): r""" Create a continuous random variable with a Wigner semicircle distribution. Explanation =========== The density of the Wigner semicircle distribution is given by .. math:: f(x) := \frac2{\pi R^2}\,\sqrt{R^2-x^2} with :math:`x \in [-R,R]`. Parameters ========== R : Real number, `R > 0`, the radius Returns ======= A `RandomSymbol`. Examples ======== >>> from sympy.stats import WignerSemicircle, density, E >>> from sympy import Symbol >>> R = Symbol("R", positive=True) >>> z = Symbol("z") >>> X = WignerSemicircle("x", R) >>> density(X)(z) 2*sqrt(R**2 - z**2)/(pi*R**2) >>> E(X) 0 References ========== .. [1] https://en.wikipedia.org/wiki/Wigner_semicircle_distribution .. [2] http://mathworld.wolfram.com/WignersSemicircleLaw.html """ return rv(name, WignerSemicircleDistribution, (R,))
755378d5fe88927c5795e9b0f58fdd5daced2454e517bf06f39b15624362f12a
from __future__ import print_function, division import random import itertools from typing import (Sequence as tSequence, Union as tUnion, List as tList, Tuple as tTuple, Set as tSet) from sympy.concrete.summations import Sum 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.expr import Expr from sympy.core.function import (Function, Lambda) from sympy.core.mul import Mul from sympy.core.numbers import (Integer, Rational, igcd, oo, pi) from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol) 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.gamma_functions import gamma from sympy.logic.boolalg import (And, Not, Or) from sympy.matrices.common import NonSquareMatrixError from sympy.matrices.dense import (Matrix, eye, ones, zeros) from sympy.matrices.expressions.blockmatrix import BlockMatrix from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.matrices.expressions.special import Identity from sympy.matrices.immutable import ImmutableMatrix from sympy.sets.conditionset import ConditionSet from sympy.sets.contains import Contains from sympy.sets.fancysets import Range from sympy.sets.sets import (FiniteSet, Intersection, Interval, Set, Union) from sympy.solvers.solveset import linsolve from sympy.tensor.indexed import (Indexed, IndexedBase) from sympy.core.relational import Relational from sympy.logic.boolalg import Boolean from sympy.utilities.exceptions import SymPyDeprecationWarning from sympy.utilities.iterables import strongly_connected_components from sympy.stats.joint_rv import JointDistribution from sympy.stats.joint_rv_types import JointDistributionHandmade from sympy.stats.rv import (RandomIndexedSymbol, random_symbols, RandomSymbol, _symbol_converter, _value_check, pspace, given, dependent, is_random, sample_iter, Distribution, Density) from sympy.stats.stochastic_process import StochasticPSpace from sympy.stats.symbolic_probability import Probability, Expectation from sympy.stats.frv_types import Bernoulli, BernoulliDistribution, FiniteRV from sympy.stats.drv_types import Poisson, PoissonDistribution from sympy.stats.crv_types import Normal, NormalDistribution, Gamma, GammaDistribution from sympy.core.sympify import _sympify, sympify EmptySet = S.EmptySet __all__ = [ 'StochasticProcess', 'DiscreteTimeStochasticProcess', 'DiscreteMarkovChain', 'TransitionMatrixOf', 'StochasticStateSpaceOf', 'GeneratorMatrixOf', 'ContinuousMarkovChain', 'BernoulliProcess', 'PoissonProcess', 'WienerProcess', 'GammaProcess' ] @is_random.register(Indexed) def _(x): return is_random(x.base) @is_random.register(RandomIndexedSymbol) # type: ignore def _(x): return True def _set_converter(itr): """ Helper function for converting list/tuple/set to Set. If parameter is not an instance of list/tuple/set then no operation is performed. Returns ======= Set The argument converted to Set. Raises ====== TypeError If the argument is not an instance of list/tuple/set. """ if isinstance(itr, (list, tuple, set)): itr = FiniteSet(*itr) if not isinstance(itr, Set): raise TypeError("%s is not an instance of list/tuple/set."%(itr)) return itr def _state_converter(itr: tSequence) -> tUnion[Tuple, Range]: """ Helper function for converting list/tuple/set/Range/Tuple/FiniteSet to tuple/Range. """ itr_ret: tUnion[Tuple, Range] if isinstance(itr, (Tuple, set, FiniteSet)): itr_ret = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr)) elif isinstance(itr, (list, tuple)): # check if states are unique if len(set(itr)) != len(itr): raise ValueError('The state space must have unique elements.') itr_ret = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr)) elif isinstance(itr, Range): # the only ordered set in SymPy I know of # try to convert to tuple try: itr_ret = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr)) except (TypeError, ValueError): itr_ret = itr else: raise TypeError("%s is not an instance of list/tuple/set/Range/Tuple/FiniteSet." % (itr)) return itr_ret def _sym_sympify(arg): """ Converts an arbitrary expression to a type that can be used inside SymPy. As generally strings are unwise to use in the expressions, it returns the Symbol of argument if the string type argument is passed. Parameters ========= arg: The parameter to be converted to be used in SymPy. Returns ======= The converted parameter. """ if isinstance(arg, str): return Symbol(arg) else: return _sympify(arg) def _matrix_checks(matrix): if not isinstance(matrix, (Matrix, MatrixSymbol, ImmutableMatrix)): raise TypeError("Transition probabilities either should " "be a Matrix or a MatrixSymbol.") if matrix.shape[0] != matrix.shape[1]: raise NonSquareMatrixError("%s is not a square matrix"%(matrix)) if isinstance(matrix, Matrix): matrix = ImmutableMatrix(matrix.tolist()) return matrix class StochasticProcess(Basic): """ Base class for all the stochastic processes whether discrete or continuous. Parameters ========== sym: Symbol or str state_space: Set The state space of the stochastic process, by default S.Reals. For discrete sets it is zero indexed. See Also ======== DiscreteTimeStochasticProcess """ index_set = S.Reals def __new__(cls, sym, state_space=S.Reals, **kwargs): sym = _symbol_converter(sym) state_space = _set_converter(state_space) return Basic.__new__(cls, sym, state_space) @property def symbol(self): return self.args[0] @property def state_space(self) -> tUnion[FiniteSet, Range]: if not isinstance(self.args[1], (FiniteSet, Range)): assert isinstance(self.args[1], Tuple) return FiniteSet(*self.args[1]) return self.args[1] def _deprecation_warn_distribution(self): SymPyDeprecationWarning( feature="Calling distribution with RandomIndexedSymbol", useinstead="distribution with just timestamp as argument", issue=20078, deprecated_since_version="1.7.1" ).warn() def distribution(self, key=None): if key is None: self._deprecation_warn_distribution() return Distribution() def density(self, x): return Density() def __call__(self, time): """ Overridden in ContinuousTimeStochasticProcess. """ raise NotImplementedError("Use [] for indexing discrete time stochastic process.") def __getitem__(self, time): """ Overridden in DiscreteTimeStochasticProcess. """ raise NotImplementedError("Use () for indexing continuous time stochastic process.") def probability(self, condition): raise NotImplementedError() def joint_distribution(self, *args): """ Computes the joint distribution of the random indexed variables. Parameters ========== args: iterable The finite list of random indexed variables/the key of a stochastic process whose joint distribution has to be computed. Returns ======= JointDistribution The joint distribution of the list of random indexed variables. An unevaluated object is returned if it is not possible to compute the joint distribution. Raises ====== ValueError: When the arguments passed are not of type RandomIndexSymbol or Number. """ args = list(args) for i, arg in enumerate(args): if S(arg).is_Number: if self.index_set.is_subset(S.Integers): args[i] = self.__getitem__(arg) else: args[i] = self.__call__(arg) elif not isinstance(arg, RandomIndexedSymbol): raise ValueError("Expected a RandomIndexedSymbol or " "key not %s"%(type(arg))) if args[0].pspace.distribution == Distribution(): return JointDistribution(*args) density = Lambda(tuple(args), expr=Mul.fromiter(arg.pspace.process.density(arg) for arg in args)) return JointDistributionHandmade(density) def expectation(self, condition, given_condition): raise NotImplementedError("Abstract method for expectation queries.") def sample(self): raise NotImplementedError("Abstract method for sampling queries.") class DiscreteTimeStochasticProcess(StochasticProcess): """ Base class for all discrete stochastic processes. """ def __getitem__(self, time): """ For indexing discrete time stochastic processes. Returns ======= RandomIndexedSymbol """ time = sympify(time) if not time.is_symbol and time not in self.index_set: raise IndexError("%s is not in the index set of %s"%(time, self.symbol)) idx_obj = Indexed(self.symbol, time) pspace_obj = StochasticPSpace(self.symbol, self, self.distribution(time)) return RandomIndexedSymbol(idx_obj, pspace_obj) class ContinuousTimeStochasticProcess(StochasticProcess): """ Base class for all continuous time stochastic process. """ def __call__(self, time): """ For indexing continuous time stochastic processes. Returns ======= RandomIndexedSymbol """ time = sympify(time) if not time.is_symbol and time not in self.index_set: raise IndexError("%s is not in the index set of %s"%(time, self.symbol)) func_obj = Function(self.symbol)(time) pspace_obj = StochasticPSpace(self.symbol, self, self.distribution(time)) return RandomIndexedSymbol(func_obj, pspace_obj) class TransitionMatrixOf(Boolean): """ Assumes that the matrix is the transition matrix of the process. """ def __new__(cls, process, matrix): if not isinstance(process, DiscreteMarkovChain): raise ValueError("Currently only DiscreteMarkovChain " "support TransitionMatrixOf.") matrix = _matrix_checks(matrix) return Basic.__new__(cls, process, matrix) process = property(lambda self: self.args[0]) matrix = property(lambda self: self.args[1]) class GeneratorMatrixOf(TransitionMatrixOf): """ Assumes that the matrix is the generator matrix of the process. """ def __new__(cls, process, matrix): if not isinstance(process, ContinuousMarkovChain): raise ValueError("Currently only ContinuousMarkovChain " "support GeneratorMatrixOf.") matrix = _matrix_checks(matrix) return Basic.__new__(cls, process, matrix) class StochasticStateSpaceOf(Boolean): def __new__(cls, process, state_space): if not isinstance(process, (DiscreteMarkovChain, ContinuousMarkovChain)): raise ValueError("Currently only DiscreteMarkovChain and ContinuousMarkovChain " "support StochasticStateSpaceOf.") state_space = _state_converter(state_space) if isinstance(state_space, Range): ss_size = ceiling((state_space.stop - state_space.start) / state_space.step) else: ss_size = len(state_space) state_index = Range(ss_size) return Basic.__new__(cls, process, state_index) process = property(lambda self: self.args[0]) state_index = property(lambda self: self.args[1]) class MarkovProcess(StochasticProcess): """ Contains methods that handle queries common to Markov processes. """ @property def number_of_states(self) -> tUnion[Integer, Symbol]: """ The number of states in the Markov Chain. """ return _sympify(self.args[2].shape[0]) # type: ignore @property def _state_index(self): """ Returns state index as Range. """ return self.args[1] @classmethod def _sanity_checks(cls, state_space, trans_probs): # Try to never have None as state_space or trans_probs. # This helps a lot if we get it done at the start. if (state_space is None) and (trans_probs is None): _n = Dummy('n', integer=True, nonnegative=True) state_space = _state_converter(Range(_n)) trans_probs = _matrix_checks(MatrixSymbol('_T', _n, _n)) elif state_space is None: trans_probs = _matrix_checks(trans_probs) state_space = _state_converter(Range(trans_probs.shape[0])) elif trans_probs is None: state_space = _state_converter(state_space) if isinstance(state_space, Range): _n = ceiling((state_space.stop - state_space.start) / state_space.step) else: _n = len(state_space) trans_probs = MatrixSymbol('_T', _n, _n) else: state_space = _state_converter(state_space) trans_probs = _matrix_checks(trans_probs) # Range object doesn't want to give a symbolic size # so we do it ourselves. if isinstance(state_space, Range): ss_size = ceiling((state_space.stop - state_space.start) / state_space.step) else: ss_size = len(state_space) if ss_size != trans_probs.shape[0]: raise ValueError('The size of the state space and the number of ' 'rows of the transition matrix must be the same.') return state_space, trans_probs def _extract_information(self, given_condition): """ Helper function to extract information, like, transition matrix/generator matrix, state space, etc. """ if isinstance(self, DiscreteMarkovChain): trans_probs = self.transition_probabilities state_index = self._state_index elif isinstance(self, ContinuousMarkovChain): trans_probs = self.generator_matrix state_index = self._state_index if isinstance(given_condition, And): gcs = given_condition.args given_condition = S.true for gc in gcs: if isinstance(gc, TransitionMatrixOf): trans_probs = gc.matrix if isinstance(gc, StochasticStateSpaceOf): state_index = gc.state_index if isinstance(gc, Relational): given_condition = given_condition & gc if isinstance(given_condition, TransitionMatrixOf): trans_probs = given_condition.matrix given_condition = S.true if isinstance(given_condition, StochasticStateSpaceOf): state_index = given_condition.state_index given_condition = S.true return trans_probs, state_index, given_condition def _check_trans_probs(self, trans_probs, row_sum=1): """ Helper function for checking the validity of transition probabilities. """ if not isinstance(trans_probs, MatrixSymbol): rows = trans_probs.tolist() for row in rows: if (sum(row) - row_sum) != 0: raise ValueError("Values in a row must sum to %s. " "If you are using Float or floats then please use Rational."%(row_sum)) def _work_out_state_index(self, state_index, given_condition, trans_probs): """ Helper function to extract state space if there is a random symbol in the given condition. """ # if given condition is None, then there is no need to work out # state_space from random variables if given_condition != None: rand_var = list(given_condition.atoms(RandomSymbol) - given_condition.atoms(RandomIndexedSymbol)) if len(rand_var) == 1: state_index = rand_var[0].pspace.set # `not None` is `True`. So the old test fails for symbolic sizes. # Need to build the statement differently. sym_cond = not self.number_of_states.is_Integer cond1 = not sym_cond and len(state_index) != trans_probs.shape[0] if cond1: raise ValueError("state space is not compatible with the transition probabilities.") if not isinstance(trans_probs.shape[0], Symbol): state_index = FiniteSet(*[i for i in range(trans_probs.shape[0])]) return state_index @cacheit def _preprocess(self, given_condition, evaluate): """ Helper function for pre-processing the information. """ is_insufficient = False if not evaluate: # avoid pre-processing if the result is not to be evaluated return (True, None, None, None) # extracting transition matrix and state space trans_probs, state_index, given_condition = self._extract_information(given_condition) # given_condition does not have sufficient information # for computations if trans_probs is None or \ given_condition is None: is_insufficient = True else: # checking transition probabilities if isinstance(self, DiscreteMarkovChain): self._check_trans_probs(trans_probs, row_sum=1) elif isinstance(self, ContinuousMarkovChain): self._check_trans_probs(trans_probs, row_sum=0) # working out state space state_index = self._work_out_state_index(state_index, given_condition, trans_probs) return is_insufficient, trans_probs, state_index, given_condition def replace_with_index(self, condition): if isinstance(condition, Relational): lhs, rhs = condition.lhs, condition.rhs if not isinstance(lhs, RandomIndexedSymbol): lhs, rhs = rhs, lhs condition = type(condition)(self.index_of.get(lhs, lhs), self.index_of.get(rhs, rhs)) return condition def probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Handles probability queries for Markov process. Parameters ========== condition: Relational given_condition: Relational/And Returns ======= Probability If the information is not sufficient. Expr In all other cases. Note ==== Any information passed at the time of query overrides any information passed at the time of object creation like transition probabilities, state space. Pass the transition matrix using TransitionMatrixOf, generator matrix using GeneratorMatrixOf and state space using StochasticStateSpaceOf in given_condition using & or And. """ check, mat, state_index, new_given_condition = \ self._preprocess(given_condition, evaluate) rv = list(condition.atoms(RandomIndexedSymbol)) symbolic = False for sym in rv: if sym.key.is_symbol: symbolic = True break if check: return Probability(condition, new_given_condition) if isinstance(self, ContinuousMarkovChain): trans_probs = self.transition_probabilities(mat) elif isinstance(self, DiscreteMarkovChain): trans_probs = mat condition = self.replace_with_index(condition) given_condition = self.replace_with_index(given_condition) new_given_condition = self.replace_with_index(new_given_condition) if isinstance(condition, Relational): if isinstance(new_given_condition, And): gcs = new_given_condition.args else: gcs = (new_given_condition, ) min_key_rv = list(new_given_condition.atoms(RandomIndexedSymbol)) if len(min_key_rv): min_key_rv = min_key_rv[0] for r in rv: if min_key_rv.key.is_symbol or r.key.is_symbol: continue if min_key_rv.key > r.key: return Probability(condition) else: min_key_rv = None return Probability(condition) if symbolic: return self._symbolic_probability(condition, new_given_condition, rv, min_key_rv) if len(rv) > 1: rv[0] = condition.lhs rv[1] = condition.rhs if rv[0].key < rv[1].key: rv[0], rv[1] = rv[1], rv[0] if isinstance(condition, Gt): condition = Lt(condition.lhs, condition.rhs) elif isinstance(condition, Lt): condition = Gt(condition.lhs, condition.rhs) elif isinstance(condition, Ge): condition = Le(condition.lhs, condition.rhs) elif isinstance(condition, Le): condition = Ge(condition.lhs, condition.rhs) s = Rational(0, 1) n = len(self.state_space) if isinstance(condition, (Eq, Ne)): for i in range(0, n): s += self.probability(Eq(rv[0], i), Eq(rv[1], i)) * self.probability(Eq(rv[1], i), new_given_condition) return s if isinstance(condition, Eq) else 1 - s else: upper = 0 greater = False if isinstance(condition, (Ge, Lt)): upper = 1 if isinstance(condition, (Ge, Gt)): greater = True for i in range(0, n): if i <= n//2: for j in range(0, i + upper): s += self.probability(Eq(rv[0], i), Eq(rv[1], j)) * self.probability(Eq(rv[1], j), new_given_condition) else: s += self.probability(Eq(rv[0], i), new_given_condition) for j in range(i + upper, n): s -= self.probability(Eq(rv[0], i), Eq(rv[1], j)) * self.probability(Eq(rv[1], j), new_given_condition) return s if greater else 1 - s rv = rv[0] states = condition.as_set() prob, gstate = dict(), None for gc in gcs: if gc.has(min_key_rv): if gc.has(Probability): p, gp = (gc.rhs, gc.lhs) if isinstance(gc.lhs, Probability) \ else (gc.lhs, gc.rhs) gr = gp.args[0] gset = Intersection(gr.as_set(), state_index) gstate = list(gset)[0] prob[gset] = p else: _, gstate = (gc.lhs.key, gc.rhs) if isinstance(gc.lhs, RandomIndexedSymbol) \ else (gc.rhs.key, gc.lhs) if not all(k in self.index_set for k in (rv.key, min_key_rv.key)): raise IndexError("The timestamps of the process are not in it's index set.") states = Intersection(states, state_index) if not isinstance(self.number_of_states, Symbol) else states for state in Union(states, FiniteSet(gstate)): if not state.is_Integer or Ge(state, mat.shape[0]) is True: raise IndexError("No information is available for (%s, %s) in " "transition probabilities of shape, (%s, %s). " "State space is zero indexed." %(gstate, state, mat.shape[0], mat.shape[1])) if prob: gstates = Union(*prob.keys()) if len(gstates) == 1: gstate = list(gstates)[0] gprob = list(prob.values())[0] prob[gstates] = gprob elif len(gstates) == len(state_index) - 1: gstate = list(state_index - gstates)[0] gprob = S.One - sum(prob.values()) prob[state_index - gstates] = gprob else: raise ValueError("Conflicting information.") else: gprob = S.One if min_key_rv == rv: return sum([prob[FiniteSet(state)] for state in states]) if isinstance(self, ContinuousMarkovChain): return gprob * sum([trans_probs(rv.key - min_key_rv.key).__getitem__((gstate, state)) for state in states]) if isinstance(self, DiscreteMarkovChain): return gprob * sum([(trans_probs**(rv.key - min_key_rv.key)).__getitem__((gstate, state)) for state in states]) if isinstance(condition, Not): expr = condition.args[0] return S.One - self.probability(expr, given_condition, evaluate, **kwargs) if isinstance(condition, And): compute_later, state2cond, conds = [], dict(), condition.args for expr in conds: if isinstance(expr, Relational): ris = list(expr.atoms(RandomIndexedSymbol))[0] if state2cond.get(ris, None) is None: state2cond[ris] = S.true state2cond[ris] &= expr else: compute_later.append(expr) ris = [] for ri in state2cond: ris.append(ri) cset = Intersection(state2cond[ri].as_set(), state_index) if len(cset) == 0: return S.Zero state2cond[ri] = cset.as_relational(ri) sorted_ris = sorted(ris, key=lambda ri: ri.key) prod = self.probability(state2cond[sorted_ris[0]], given_condition, evaluate, **kwargs) for i in range(1, len(sorted_ris)): ri, prev_ri = sorted_ris[i], sorted_ris[i-1] if not isinstance(state2cond[ri], Eq): raise ValueError("The process is in multiple states at %s, unable to determine the probability."%(ri)) mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat) prod *= self.probability(state2cond[ri], state2cond[prev_ri] & mat_of & StochasticStateSpaceOf(self, state_index), evaluate, **kwargs) for expr in compute_later: prod *= self.probability(expr, given_condition, evaluate, **kwargs) return prod if isinstance(condition, Or): return sum([self.probability(expr, given_condition, evaluate, **kwargs) for expr in condition.args]) raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been " "implemented yet."%(condition, given_condition)) def _symbolic_probability(self, condition, new_given_condition, rv, min_key_rv): #Function to calculate probability for queries with symbols if isinstance(condition, Relational): curr_state = new_given_condition.rhs if isinstance(new_given_condition.lhs, RandomIndexedSymbol) \ else new_given_condition.lhs next_state = condition.rhs if isinstance(condition.lhs, RandomIndexedSymbol) \ else condition.lhs if isinstance(condition, (Eq, Ne)): if isinstance(self, DiscreteMarkovChain): P = self.transition_probabilities**(rv[0].key - min_key_rv.key) else: P = exp(self.generator_matrix*(rv[0].key - min_key_rv.key)) prob = P[curr_state, next_state] if isinstance(condition, Eq) else 1 - P[curr_state, next_state] return Piecewise((prob, rv[0].key > min_key_rv.key), (Probability(condition), True)) else: upper = 1 greater = False if isinstance(condition, (Ge, Lt)): upper = 0 if isinstance(condition, (Ge, Gt)): greater = True k = Dummy('k') condition = Eq(condition.lhs, k) if isinstance(condition.lhs, RandomIndexedSymbol)\ else Eq(condition.rhs, k) total = Sum(self.probability(condition, new_given_condition), (k, next_state + upper, self.state_space._sup)) return Piecewise((total, rv[0].key > min_key_rv.key), (Probability(condition), True)) if greater\ else Piecewise((1 - total, rv[0].key > min_key_rv.key), (Probability(condition), True)) else: return Probability(condition, new_given_condition) def expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Handles expectation queries for markov process. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. Returns ======= Expectation Unevaluated object if computations cannot be done due to insufficient information. Expr In all other cases when the computations are successful. Note ==== Any information passed at the time of query overrides any information passed at the time of object creation like transition probabilities, state space. Pass the transition matrix using TransitionMatrixOf, generator matrix using GeneratorMatrixOf and state space using StochasticStateSpaceOf in given_condition using & or And. """ check, mat, state_index, condition = \ self._preprocess(condition, evaluate) if check: return Expectation(expr, condition) rvs = random_symbols(expr) if isinstance(expr, Expr) and isinstance(condition, Eq) \ and len(rvs) == 1: # handle queries similar to E(f(X[i]), Eq(X[i-m], <some-state>)) condition=self.replace_with_index(condition) state_index=self.replace_with_index(state_index) rv = list(rvs)[0] lhsg, rhsg = condition.lhs, condition.rhs if not isinstance(lhsg, RandomIndexedSymbol): lhsg, rhsg = (rhsg, lhsg) if rhsg not in state_index: raise ValueError("%s state is not in the state space."%(rhsg)) if rv.key < lhsg.key: raise ValueError("Incorrect given condition is given, expectation " "time %s < time %s"%(rv.key, rv.key)) mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat) cond = condition & mat_of & \ StochasticStateSpaceOf(self, state_index) func = lambda s: self.probability(Eq(rv, s), cond) * expr.subs(rv, self._state_index[s]) return sum([func(s) for s in state_index]) raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been " "implemented yet."%(expr, condition)) class DiscreteMarkovChain(DiscreteTimeStochasticProcess, MarkovProcess): """ Represents a finite discrete time-homogeneous Markov chain. This type of Markov Chain can be uniquely characterised by its (ordered) state space and its one-step transition probability matrix. Parameters ========== sym: The name given to the Markov Chain state_space: Optional, by default, Range(n) trans_probs: Optional, by default, MatrixSymbol('_T', n, n) Examples ======== >>> from sympy.stats import DiscreteMarkovChain, TransitionMatrixOf, P, E >>> from sympy import Matrix, MatrixSymbol, Eq, symbols >>> T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]]) >>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T) >>> YS = DiscreteMarkovChain("Y") >>> Y.state_space {0, 1, 2} >>> Y.transition_probabilities Matrix([ [0.5, 0.2, 0.3], [0.2, 0.5, 0.3], [0.2, 0.3, 0.5]]) >>> TS = MatrixSymbol('T', 3, 3) >>> P(Eq(YS[3], 2), Eq(YS[1], 1) & TransitionMatrixOf(YS, TS)) T[0, 2]*T[1, 0] + T[1, 1]*T[1, 2] + T[1, 2]*T[2, 2] >>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2) 0.36 Probabilities will be calculated based on indexes rather than state names. For example, with the Sunny-Cloudy-Rainy model with string state names: >>> from sympy.core.symbol import Str >>> Y = DiscreteMarkovChain("Y", [Str('Sunny'), Str('Cloudy'), Str('Rainy')], T) >>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2) 0.36 This gives the same answer as the ``[0, 1, 2]`` state space. Currently, there is no support for state names within probability and expectation statements. Here is a work-around using ``Str``: >>> P(Eq(Str('Rainy'), Y[3]), Eq(Y[1], Str('Cloudy'))).round(2) 0.36 Symbol state names can also be used: >>> sunny, cloudy, rainy = symbols('Sunny, Cloudy, Rainy') >>> Y = DiscreteMarkovChain("Y", [sunny, cloudy, rainy], T) >>> P(Eq(Y[3], rainy), Eq(Y[1], cloudy)).round(2) 0.36 Expectations will be calculated as follows: >>> E(Y[3], Eq(Y[1], cloudy)) 0.38*Cloudy + 0.36*Rainy + 0.26*Sunny Probability of expressions with multiple RandomIndexedSymbols can also be calculated provided there is only 1 RandomIndexedSymbol in the given condition. It is always better to use Rational instead of floating point numbers for the probabilities in the transition matrix to avoid errors. >>> from sympy import Gt, Le, Rational >>> T = Matrix([[Rational(5, 10), Rational(3, 10), Rational(2, 10)], [Rational(2, 10), Rational(7, 10), Rational(1, 10)], [Rational(3, 10), Rational(3, 10), Rational(4, 10)]]) >>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T) >>> P(Eq(Y[3], Y[1]), Eq(Y[0], 0)).round(3) 0.409 >>> P(Gt(Y[3], Y[1]), Eq(Y[0], 0)).round(2) 0.36 >>> P(Le(Y[15], Y[10]), Eq(Y[8], 2)).round(7) 0.6963328 Symbolic probability queries are also supported >>> from sympy import symbols, Matrix, Rational, Eq, Gt >>> from sympy.stats import P, DiscreteMarkovChain >>> a, b, c, d = symbols('a b c d') >>> T = Matrix([[Rational(1, 10), Rational(4, 10), Rational(5, 10)], [Rational(3, 10), Rational(4, 10), Rational(3, 10)], [Rational(7, 10), Rational(2, 10), Rational(1, 10)]]) >>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T) >>> query = P(Eq(Y[a], b), Eq(Y[c], d)) >>> query.subs({a:10, b:2, c:5, d:1}).round(4) 0.3096 >>> P(Eq(Y[10], 2), Eq(Y[5], 1)).evalf().round(4) 0.3096 >>> query_gt = P(Gt(Y[a], b), Eq(Y[c], d)) >>> query_gt.subs({a:21, b:0, c:5, d:0}).evalf().round(5) 0.64705 >>> P(Gt(Y[21], 0), Eq(Y[5], 0)).round(5) 0.64705 There is limited support for arbitrarily sized states: >>> n = symbols('n', nonnegative=True, integer=True) >>> T = MatrixSymbol('T', n, n) >>> Y = DiscreteMarkovChain("Y", trans_probs=T) >>> Y.state_space Range(0, n, 1) >>> query = P(Eq(Y[a], b), Eq(Y[c], d)) >>> query.subs({a:10, b:2, c:5, d:1}) (T**5)[1, 2] References ========== .. [1] https://en.wikipedia.org/wiki/Markov_chain#Discrete-time_Markov_chain .. [2] https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf """ index_set = S.Naturals0 def __new__(cls, sym, state_space=None, trans_probs=None): sym = _symbol_converter(sym) state_space, trans_probs = MarkovProcess._sanity_checks(state_space, trans_probs) obj = Basic.__new__(cls, sym, state_space, trans_probs) # type: ignore indices = dict() if isinstance(obj.number_of_states, Integer): for index, state in enumerate(obj._state_index): indices[state] = index obj.index_of = indices return obj @property def transition_probabilities(self): """ Transition probabilities of discrete Markov chain, either an instance of Matrix or MatrixSymbol. """ return self.args[2] def communication_classes(self) -> tList[tTuple[tList[Basic], Boolean, Integer]]: """ Returns the list of communication classes that partition the states of the markov chain. A communication class is defined to be a set of states such that every state in that set is reachable from every other state in that set. Due to its properties this forms a class in the mathematical sense. Communication classes are also known as recurrence classes. Returns ======= classes The ``classes`` are a list of tuples. Each tuple represents a single communication class with its properties. The first element in the tuple is the list of states in the class, the second element is whether the class is recurrent and the third element is the period of the communication class. Examples ======== >>> from sympy.stats import DiscreteMarkovChain >>> from sympy import Matrix >>> T = Matrix([[0, 1, 0], ... [1, 0, 0], ... [1, 0, 0]]) >>> X = DiscreteMarkovChain('X', [1, 2, 3], T) >>> classes = X.communication_classes() >>> for states, is_recurrent, period in classes: ... states, is_recurrent, period ([1, 2], True, 2) ([3], False, 1) From this we can see that states ``1`` and ``2`` communicate, are recurrent and have a period of 2. We can also see state ``3`` is transient with a period of 1. Notes ===== The algorithm used is of order ``O(n**2)`` where ``n`` is the number of states in the markov chain. It uses Tarjan's algorithm to find the classes themselves and then it uses a breadth-first search algorithm to find each class's periodicity. Most of the algorithm's components approach ``O(n)`` as the matrix becomes more and more sparse. References ========== .. [1] http://www.columbia.edu/~ww2040/4701Sum07/4701-06-Notes-MCII.pdf .. [2] http://cecas.clemson.edu/~shierd/Shier/markov.pdf .. [3] https://ujcontent.uj.ac.za/vital/access/services/Download/uj:7506/CONTENT1 .. [4] https://www.mathworks.com/help/econ/dtmc.classify.html """ n = self.number_of_states T = self.transition_probabilities if isinstance(T, MatrixSymbol): raise NotImplementedError("Cannot perform the operation with a symbolic matrix.") # begin Tarjan's algorithm V = Range(n) # don't use state names. Rather use state # indexes since we use them for matrix # indexing here and later onward E = [(i, j) for i in V for j in V if T[i, j] != 0] classes = strongly_connected_components((V, E)) # end Tarjan's algorithm recurrence = [] periods = [] for class_ in classes: # begin recurrent check (similar to self._check_trans_probs()) submatrix = T[class_, class_] # get the submatrix with those states is_recurrent = S.true rows = submatrix.tolist() for row in rows: if (sum(row) - 1) != 0: is_recurrent = S.false break recurrence.append(is_recurrent) # end recurrent check # begin breadth-first search non_tree_edge_values: tSet[int] = set() visited = {class_[0]} newly_visited = {class_[0]} level = {class_[0]: 0} current_level = 0 done = False # imitate a do-while loop while not done: # runs at most len(class_) times done = len(visited) == len(class_) current_level += 1 # this loop and the while loop above run a combined len(class_) number of times. # so this triple nested loop runs through each of the n states once. for i in newly_visited: # the loop below runs len(class_) number of times # complexity is around about O(n * avg(len(class_))) newly_visited = {j for j in class_ if T[i, j] != 0} new_tree_edges = newly_visited.difference(visited) for j in new_tree_edges: level[j] = current_level new_non_tree_edges = newly_visited.intersection(visited) new_non_tree_edge_values = {level[i]-level[j]+1 for j in new_non_tree_edges} non_tree_edge_values = non_tree_edge_values.union(new_non_tree_edge_values) visited = visited.union(new_tree_edges) # igcd needs at least 2 arguments positive_ntev = {val_e for val_e in non_tree_edge_values if val_e > 0} if len(positive_ntev) == 0: periods.append(len(class_)) elif len(positive_ntev) == 1: periods.append(positive_ntev.pop()) else: periods.append(igcd(*positive_ntev)) # end breadth-first search # convert back to the user's state names classes = [[_sympify(self._state_index[i]) for i in class_] for class_ in classes] return list(zip(classes, recurrence, map(Integer,periods))) def fundamental_matrix(self): """ Each entry fundamental matrix can be interpreted as the expected number of times the chains is in state j if it started in state i. References ========== .. [1] https://lips.cs.princeton.edu/the-fundamental-matrix-of-a-finite-markov-chain/ """ _, _, _, Q = self.decompose() if Q.shape[0] > 0: # if non-ergodic I = eye(Q.shape[0]) if (I - Q).det() == 0: raise ValueError("The fundamental matrix doesn't exist.") return (I - Q).inv().as_immutable() else: # if ergodic P = self.transition_probabilities I = eye(P.shape[0]) w = self.fixed_row_vector() W = Matrix([list(w) for i in range(0, P.shape[0])]) if (I - P + W).det() == 0: raise ValueError("The fundamental matrix doesn't exist.") return (I - P + W).inv().as_immutable() def absorbing_probabilities(self): """ Computes the absorbing probabilities, i.e., the ij-th entry of the matrix denotes the probability of Markov chain being absorbed in state j starting from state i. """ _, _, R, _ = self.decompose() N = self.fundamental_matrix() if R is None or N is None: return None return N*R def absorbing_probabilites(self): SymPyDeprecationWarning( feature="absorbing_probabilites", useinstead="absorbing_probabilities", issue=20042, deprecated_since_version="1.7" ).warn() return self.absorbing_probabilities() def is_regular(self): tuples = self.communication_classes() if len(tuples) == 0: return S.false # not defined for a 0x0 matrix classes, _, periods = list(zip(*tuples)) return And(len(classes) == 1, periods[0] == 1) def is_ergodic(self): tuples = self.communication_classes() if len(tuples) == 0: return S.false # not defined for a 0x0 matrix classes, _, _ = list(zip(*tuples)) return S(len(classes) == 1) def is_absorbing_state(self, state): trans_probs = self.transition_probabilities if isinstance(trans_probs, ImmutableMatrix) and \ state < trans_probs.shape[0]: return S(trans_probs[state, state]) is S.One def is_absorbing_chain(self): states, A, B, C = self.decompose() r = A.shape[0] return And(r > 0, A == Identity(r).as_explicit()) def stationary_distribution(self, condition_set=False) -> tUnion[ImmutableMatrix, ConditionSet, Lambda]: r""" The stationary distribution is any row vector, p, that solves p = pP, is row stochastic and each element in p must be nonnegative. That means in matrix form: :math:`(P-I)^T p^T = 0` and :math:`(1, \dots, 1) p = 1` where ``P`` is the one-step transition matrix. All time-homogeneous Markov Chains with a finite state space have at least one stationary distribution. In addition, if a finite time-homogeneous Markov Chain is irreducible, the stationary distribution is unique. Parameters ========== condition_set : bool If the chain has a symbolic size or transition matrix, it will return a ``Lambda`` if ``False`` and return a ``ConditionSet`` if ``True``. Examples ======== >>> from sympy.stats import DiscreteMarkovChain >>> from sympy import Matrix, S An irreducible Markov Chain >>> T = Matrix([[S(1)/2, S(1)/2, 0], ... [S(4)/5, S(1)/5, 0], ... [1, 0, 0]]) >>> X = DiscreteMarkovChain('X', trans_probs=T) >>> X.stationary_distribution() Matrix([[8/13, 5/13, 0]]) A reducible Markov Chain >>> T = Matrix([[S(1)/2, S(1)/2, 0], ... [S(4)/5, S(1)/5, 0], ... [0, 0, 1]]) >>> X = DiscreteMarkovChain('X', trans_probs=T) >>> X.stationary_distribution() Matrix([[8/13 - 8*tau0/13, 5/13 - 5*tau0/13, tau0]]) >>> Y = DiscreteMarkovChain('Y') >>> Y.stationary_distribution() Lambda((wm, _T), Eq(wm*_T, wm)) >>> Y.stationary_distribution(condition_set=True) ConditionSet(wm, Eq(wm*_T, wm)) References ========== .. [1] https://www.probabilitycourse.com/chapter11/11_2_6_stationary_and_limiting_distributions.php .. [2] https://galton.uchicago.edu/~yibi/teaching/stat317/2014/Lectures/Lecture4_6up.pdf See Also ======== sympy.stats.DiscreteMarkovChain.limiting_distribution """ trans_probs = self.transition_probabilities n = self.number_of_states if n == 0: return ImmutableMatrix(Matrix([[]])) # symbolic matrix version if isinstance(trans_probs, MatrixSymbol): wm = MatrixSymbol('wm', 1, n) if condition_set: return ConditionSet(wm, Eq(wm * trans_probs, wm)) else: return Lambda((wm, trans_probs), Eq(wm * trans_probs, wm)) # numeric matrix version a = Matrix(trans_probs - Identity(n)).T a[0, 0:n] = ones(1, n) # type: ignore b = zeros(n, 1) b[0, 0] = 1 soln = list(linsolve((a, b)))[0] return ImmutableMatrix([[sol for sol in soln]]) def fixed_row_vector(self): """ A wrapper for ``stationary_distribution()``. """ return self.stationary_distribution() @property def limiting_distribution(self): """ The fixed row vector is the limiting distribution of a discrete Markov chain. """ return self.fixed_row_vector() def decompose(self) -> tTuple[tList[Basic], ImmutableMatrix, ImmutableMatrix, ImmutableMatrix]: """ Decomposes the transition matrix into submatrices with special properties. The transition matrix can be decomposed into 4 submatrices: - A - the submatrix from recurrent states to recurrent states. - B - the submatrix from transient to recurrent states. - C - the submatrix from transient to transient states. - O - the submatrix of zeros for recurrent to transient states. Returns ======= states, A, B, C ``states`` - a list of state names with the first being the recurrent states and the last being the transient states in the order of the row names of A and then the row names of C. ``A`` - the submatrix from recurrent states to recurrent states. ``B`` - the submatrix from transient to recurrent states. ``C`` - the submatrix from transient to transient states. Examples ======== >>> from sympy.stats import DiscreteMarkovChain >>> from sympy import Matrix, S One can decompose this chain for example: >>> T = Matrix([[S(1)/2, S(1)/2, 0, 0, 0], ... [S(2)/5, S(1)/5, S(2)/5, 0, 0], ... [0, 0, 1, 0, 0], ... [0, 0, S(1)/2, S(1)/2, 0], ... [S(1)/2, 0, 0, 0, S(1)/2]]) >>> X = DiscreteMarkovChain('X', trans_probs=T) >>> states, A, B, C = X.decompose() >>> states [2, 0, 1, 3, 4] >>> A # recurrent to recurrent Matrix([[1]]) >>> B # transient to recurrent Matrix([ [ 0], [2/5], [1/2], [ 0]]) >>> C # transient to transient Matrix([ [1/2, 1/2, 0, 0], [2/5, 1/5, 0, 0], [ 0, 0, 1/2, 0], [1/2, 0, 0, 1/2]]) This means that state 2 is the only absorbing state (since A is a 1x1 matrix). B is a 4x1 matrix since the 4 remaining transient states all merge into reccurent state 2. And C is the 4x4 matrix that shows how the transient states 0, 1, 3, 4 all interact. See Also ======== sympy.stats.DiscreteMarkovChain.communication_classes sympy.stats.DiscreteMarkovChain.canonical_form References ========== .. [1] https://en.wikipedia.org/wiki/Absorbing_Markov_chain .. [2] http://people.brandeis.edu/~igusa/Math56aS08/Math56a_S08_notes015.pdf """ trans_probs = self.transition_probabilities classes = self.communication_classes() r_states = [] t_states = [] for states, recurrent, period in classes: if recurrent: r_states += states else: t_states += states states = r_states + t_states indexes = [self.index_of[state] for state in states] # type: ignore A = Matrix(len(r_states), len(r_states), lambda i, j: trans_probs[indexes[i], indexes[j]]) B = Matrix(len(t_states), len(r_states), lambda i, j: trans_probs[indexes[len(r_states) + i], indexes[j]]) C = Matrix(len(t_states), len(t_states), lambda i, j: trans_probs[indexes[len(r_states) + i], indexes[len(r_states) + j]]) return states, A.as_immutable(), B.as_immutable(), C.as_immutable() def canonical_form(self) -> tTuple[tList[Basic], ImmutableMatrix]: """ Reorders the one-step transition matrix so that recurrent states appear first and transient states appear last. Other representations include inserting transient states first and recurrent states last. Returns ======= states, P_new ``states`` is the list that describes the order of the new states in the matrix so that the ith element in ``states`` is the state of the ith row of A. ``P_new`` is the new transition matrix in canonical form. Examples ======== >>> from sympy.stats import DiscreteMarkovChain >>> from sympy import Matrix, S You can convert your chain into canonical form: >>> T = Matrix([[S(1)/2, S(1)/2, 0, 0, 0], ... [S(2)/5, S(1)/5, S(2)/5, 0, 0], ... [0, 0, 1, 0, 0], ... [0, 0, S(1)/2, S(1)/2, 0], ... [S(1)/2, 0, 0, 0, S(1)/2]]) >>> X = DiscreteMarkovChain('X', list(range(1, 6)), trans_probs=T) >>> states, new_matrix = X.canonical_form() >>> states [3, 1, 2, 4, 5] >>> new_matrix Matrix([ [ 1, 0, 0, 0, 0], [ 0, 1/2, 1/2, 0, 0], [2/5, 2/5, 1/5, 0, 0], [1/2, 0, 0, 1/2, 0], [ 0, 1/2, 0, 0, 1/2]]) The new states are [3, 1, 2, 4, 5] and you can create a new chain with this and its canonical form will remain the same (since it is already in canonical form). >>> X = DiscreteMarkovChain('X', states, new_matrix) >>> states, new_matrix = X.canonical_form() >>> states [3, 1, 2, 4, 5] >>> new_matrix Matrix([ [ 1, 0, 0, 0, 0], [ 0, 1/2, 1/2, 0, 0], [2/5, 2/5, 1/5, 0, 0], [1/2, 0, 0, 1/2, 0], [ 0, 1/2, 0, 0, 1/2]]) This is not limited to absorbing chains: >>> T = Matrix([[0, 5, 5, 0, 0], ... [0, 0, 0, 10, 0], ... [5, 0, 5, 0, 0], ... [0, 10, 0, 0, 0], ... [0, 3, 0, 3, 4]])/10 >>> X = DiscreteMarkovChain('X', trans_probs=T) >>> states, new_matrix = X.canonical_form() >>> states [1, 3, 0, 2, 4] >>> new_matrix Matrix([ [ 0, 1, 0, 0, 0], [ 1, 0, 0, 0, 0], [ 1/2, 0, 0, 1/2, 0], [ 0, 0, 1/2, 1/2, 0], [3/10, 3/10, 0, 0, 2/5]]) See Also ======== sympy.stats.DiscreteMarkovChain.communication_classes sympy.stats.DiscreteMarkovChain.decompose References ========== .. [1] https://onlinelibrary.wiley.com/doi/pdf/10.1002/9780470316887.app1 .. [2] http://www.columbia.edu/~ww2040/6711F12/lect1023big.pdf """ states, A, B, C = self.decompose() O = zeros(A.shape[0], C.shape[1]) return states, BlockMatrix([[A, O], [B, C]]).as_explicit() def sample(self): """ Returns ======= sample: iterator object iterator object containing the sample """ if not isinstance(self.transition_probabilities, (Matrix, ImmutableMatrix)): raise ValueError("Transition Matrix must be provided for sampling") Tlist = self.transition_probabilities.tolist() samps = [random.choice(list(self.state_space))] yield samps[0] time = 1 densities = {} for state in self.state_space: states = list(self.state_space) densities[state] = {states[i]: Tlist[state][i] for i in range(len(states))} while time < S.Infinity: samps.append((next(sample_iter(FiniteRV("_", densities[samps[time - 1]]))))) yield samps[time] time += 1 class ContinuousMarkovChain(ContinuousTimeStochasticProcess, MarkovProcess): """ Represents continuous time Markov chain. Parameters ========== sym: Symbol/str state_space: Set Optional, by default, S.Reals gen_mat: Matrix/ImmutableMatrix/MatrixSymbol Optional, by default, None Examples ======== >>> from sympy.stats import ContinuousMarkovChain, P >>> from sympy import Matrix, S, Eq, Gt >>> G = Matrix([[-S(1), S(1)], [S(1), -S(1)]]) >>> C = ContinuousMarkovChain('C', state_space=[0, 1], gen_mat=G) >>> C.limiting_distribution() Matrix([[1/2, 1/2]]) >>> C.state_space {0, 1} >>> C.generator_matrix Matrix([ [-1, 1], [ 1, -1]]) Probability queries are supported >>> P(Eq(C(1.96), 0), Eq(C(0.78), 1)).round(5) 0.45279 >>> P(Gt(C(1.7), 0), Eq(C(0.82), 1)).round(5) 0.58602 Probability of expressions with multiple RandomIndexedSymbols can also be calculated provided there is only 1 RandomIndexedSymbol in the given condition. It is always better to use Rational instead of floating point numbers for the probabilities in the generator matrix to avoid errors. >>> from sympy import Gt, Le, Rational >>> G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]]) >>> C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G) >>> P(Eq(C(3.92), C(1.75)), Eq(C(0.46), 0)).round(5) 0.37933 >>> P(Gt(C(3.92), C(1.75)), Eq(C(0.46), 0)).round(5) 0.34211 >>> P(Le(C(1.57), C(3.14)), Eq(C(1.22), 1)).round(4) 0.7143 Symbolic probability queries are also supported >>> from sympy import S, symbols, Matrix, Rational, Eq, Gt >>> from sympy.stats import P, ContinuousMarkovChain >>> a,b,c,d = symbols('a b c d') >>> G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]]) >>> C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G) >>> query = P(Eq(C(a), b), Eq(C(c), d)) >>> query.subs({a:3.65, b:2, c:1.78, d:1}).evalf().round(10) 0.4002723175 >>> P(Eq(C(3.65), 2), Eq(C(1.78), 1)).round(10) 0.4002723175 >>> query_gt = P(Gt(C(a), b), Eq(C(c), d)) >>> query_gt.subs({a:43.2, b:0, c:3.29, d:2}).evalf().round(10) 0.6832579186 >>> P(Gt(C(43.2), 0), Eq(C(3.29), 2)).round(10) 0.6832579186 References ========== .. [1] https://en.wikipedia.org/wiki/Markov_chain#Continuous-time_Markov_chain .. [2] http://u.math.biu.ac.il/~amirgi/CTMCnotes.pdf """ index_set = S.Reals def __new__(cls, sym, state_space=None, gen_mat=None): sym = _symbol_converter(sym) state_space, gen_mat = MarkovProcess._sanity_checks(state_space, gen_mat) obj = Basic.__new__(cls, sym, state_space, gen_mat) indices = dict() if isinstance(obj.number_of_states, Integer): for index, state in enumerate(obj.state_space): indices[state] = index obj.index_of = indices return obj @property def generator_matrix(self): return self.args[2] @cacheit def transition_probabilities(self, gen_mat=None): t = Dummy('t') if isinstance(gen_mat, (Matrix, ImmutableMatrix)) and \ gen_mat.is_diagonalizable(): # for faster computation use diagonalized generator matrix Q, D = gen_mat.diagonalize() return Lambda(t, Q*exp(t*D)*Q.inv()) if gen_mat != None: return Lambda(t, exp(t*gen_mat)) def limiting_distribution(self): gen_mat = self.generator_matrix if gen_mat is None: return None if isinstance(gen_mat, MatrixSymbol): wm = MatrixSymbol('wm', 1, gen_mat.shape[0]) return Lambda((wm, gen_mat), Eq(wm*gen_mat, wm)) w = IndexedBase('w') wi = [w[i] for i in range(gen_mat.shape[0])] wm = Matrix([wi]) eqs = (wm*gen_mat).tolist()[0] eqs.append(sum(wi) - 1) soln = list(linsolve(eqs, wi))[0] return ImmutableMatrix([[sol for sol in soln]]) class BernoulliProcess(DiscreteTimeStochasticProcess): """ The Bernoulli process consists of repeated independent Bernoulli process trials with the same parameter `p`. It's assumed that the probability `p` applies to every trial and that the outcomes of each trial are independent of all the rest. Therefore Bernoulli Processs is Discrete State and Discrete Time Stochastic Process. Parameters ========== sym: Symbol/str success: Integer/str The event which is considered to be success, by default is 1. failure: Integer/str The event which is considered to be failure, by default is 0. p: Real Number between 0 and 1 Represents the probability of getting success. Examples ======== >>> from sympy.stats import BernoulliProcess, P, E >>> from sympy import Eq, Gt >>> B = BernoulliProcess("B", p=0.7, success=1, failure=0) >>> B.state_space {0, 1} >>> (B.p).round(2) 0.70 >>> B.success 1 >>> B.failure 0 >>> X = B[1] + B[2] + B[3] >>> P(Eq(X, 0)).round(2) 0.03 >>> P(Eq(X, 2)).round(2) 0.44 >>> P(Eq(X, 4)).round(2) 0 >>> P(Gt(X, 1)).round(2) 0.78 >>> P(Eq(B[1], 0) & Eq(B[2], 1) & Eq(B[3], 0) & Eq(B[4], 1)).round(2) 0.04 >>> B.joint_distribution(B[1], B[2]) JointDistributionHandmade(Lambda((B[1], B[2]), Piecewise((0.7, Eq(B[1], 1)), (0.3, Eq(B[1], 0)), (0, True))*Piecewise((0.7, Eq(B[2], 1)), (0.3, Eq(B[2], 0)), (0, True)))) >>> E(2*B[1] + B[2]).round(2) 2.10 >>> P(B[1] < 1).round(2) 0.30 References ========== .. [1] https://en.wikipedia.org/wiki/Bernoulli_process .. [2] https://mathcs.clarku.edu/~djoyce/ma217/bernoulli.pdf """ index_set = S.Naturals0 def __new__(cls, sym, p, success=1, failure=0): _value_check(p >= 0 and p <= 1, 'Value of p must be between 0 and 1.') sym = _symbol_converter(sym) p = _sympify(p) success = _sym_sympify(success) failure = _sym_sympify(failure) return Basic.__new__(cls, sym, p, success, failure) @property def symbol(self): return self.args[0] @property def p(self): return self.args[1] @property def success(self): return self.args[2] @property def failure(self): return self.args[3] @property def state_space(self): return _set_converter([self.success, self.failure]) def distribution(self, key=None): if key is None: self._deprecation_warn_distribution() return BernoulliDistribution(self.p) return BernoulliDistribution(self.p, self.success, self.failure) def simple_rv(self, rv): return Bernoulli(rv.name, p=self.p, succ=self.success, fail=self.failure) def expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Computes expectation. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. Returns ======= Expectation of the RandomIndexedSymbol. """ return _SubstituteRV._expectation(expr, condition, evaluate, **kwargs) def probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Computes probability. Parameters ========== condition: Relational Condition for which probability has to be computed. Must contain a RandomIndexedSymbol of the process. given_condition: Relational/And The given conditions under which computations should be done. Returns ======= Probability of the condition. """ return _SubstituteRV._probability(condition, given_condition, evaluate, **kwargs) def density(self, x): return Piecewise((self.p, Eq(x, self.success)), (1 - self.p, Eq(x, self.failure)), (S.Zero, True)) class _SubstituteRV: """ Internal class to handle the queries of expectation and probability by substitution. """ @staticmethod def _rvindexed_subs(expr, condition=None): """ Substitutes the RandomIndexedSymbol with the RandomSymbol with same name, distribution and probability as RandomIndexedSymbol. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. """ rvs_expr = random_symbols(expr) if len(rvs_expr) != 0: swapdict_expr = {} for rv in rvs_expr: if isinstance(rv, RandomIndexedSymbol): newrv = rv.pspace.process.simple_rv(rv) # substitute with equivalent simple rv swapdict_expr[rv] = newrv expr = expr.subs(swapdict_expr) rvs_cond = random_symbols(condition) if len(rvs_cond)!=0: swapdict_cond = {} for rv in rvs_cond: if isinstance(rv, RandomIndexedSymbol): newrv = rv.pspace.process.simple_rv(rv) swapdict_cond[rv] = newrv condition = condition.subs(swapdict_cond) return expr, condition @classmethod def _expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Internal method for computing expectation of indexed RV. Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Logic The given conditions under which computations should be done. Returns ======= Expectation of the RandomIndexedSymbol. """ new_expr, new_condition = self._rvindexed_subs(expr, condition) if not is_random(new_expr): return new_expr new_pspace = pspace(new_expr) if new_condition is not None: new_expr = given(new_expr, new_condition) if new_expr.is_Add: # As E is Linear return Add(*[new_pspace.compute_expectation( expr=arg, evaluate=evaluate, **kwargs) for arg in new_expr.args]) return new_pspace.compute_expectation( new_expr, evaluate=evaluate, **kwargs) @classmethod def _probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Internal method for computing probability of indexed RV Parameters ========== condition: Relational Condition for which probability has to be computed. Must contain a RandomIndexedSymbol of the process. given_condition: Relational/And The given conditions under which computations should be done. Returns ======= Probability of the condition. """ new_condition, new_givencondition = self._rvindexed_subs(condition, given_condition) if isinstance(new_givencondition, RandomSymbol): condrv = random_symbols(new_condition) if len(condrv) == 1 and condrv[0] == new_givencondition: return BernoulliDistribution(self._probability(new_condition), 0, 1) if any(dependent(rv, new_givencondition) for rv in condrv): return Probability(new_condition, new_givencondition) else: return self._probability(new_condition) if new_givencondition is not None and \ not isinstance(new_givencondition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (new_givencondition)) if new_givencondition == False or new_condition == False: return S.Zero if new_condition == True: return S.One if not isinstance(new_condition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (new_condition)) if new_givencondition is not None: # If there is a condition # Recompute on new conditional expr return self._probability(given(new_condition, new_givencondition, **kwargs), **kwargs) result = pspace(new_condition).probability(new_condition, **kwargs) if evaluate and hasattr(result, 'doit'): return result.doit() else: return result def get_timerv_swaps(expr, condition): """ Finds the appropriate interval for each time stamp in expr by parsing the given condition and returns intervals for each timestamp and dictionary that maps variable time-stamped Random Indexed Symbol to its corresponding Random Indexed variable with fixed time stamp. Parameters ========== expr: SymPy Expression Expression containing Random Indexed Symbols with variable time stamps condition: Relational/Boolean Expression Expression containing time bounds of variable time stamps in expr Examples ======== >>> from sympy.stats.stochastic_process_types import get_timerv_swaps, PoissonProcess >>> from sympy import symbols, Contains, Interval >>> x, t, d = symbols('x t d', positive=True) >>> X = PoissonProcess("X", 3) >>> get_timerv_swaps(x*X(t), Contains(t, Interval.Lopen(0, 1))) ([Interval.Lopen(0, 1)], {X(t): X(1)}) >>> get_timerv_swaps((X(t)**2 + X(d)**2), Contains(t, Interval.Lopen(0, 1)) ... & Contains(d, Interval.Ropen(1, 4))) # doctest: +SKIP ([Interval.Ropen(1, 4), Interval.Lopen(0, 1)], {X(d): X(3), X(t): X(1)}) Returns ======= intervals: list List of Intervals/FiniteSet on which each time stamp is defined rv_swap: dict Dictionary mapping variable time Random Indexed Symbol to constant time Random Indexed Variable """ if not isinstance(condition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (condition)) expr_syms = list(expr.atoms(RandomIndexedSymbol)) if isinstance(condition, (And, Or)): given_cond_args = condition.args else: # single condition given_cond_args = (condition, ) rv_swap = {} intervals = [] for expr_sym in expr_syms: for arg in given_cond_args: if arg.has(expr_sym.key) and isinstance(expr_sym.key, Symbol): intv = _set_converter(arg.args[1]) diff_key = intv._sup - intv._inf if diff_key == oo: raise ValueError("%s should have finite bounds" % str(expr_sym.name)) elif diff_key == S.Zero: # has singleton set diff_key = intv._sup rv_swap[expr_sym] = expr_sym.subs({expr_sym.key: diff_key}) intervals.append(intv) return intervals, rv_swap class CountingProcess(ContinuousTimeStochasticProcess): """ This class handles the common methods of the Counting Processes such as Poisson, Wiener and Gamma Processes """ index_set = _set_converter(Interval(0, oo)) @property def symbol(self): return self.args[0] def expectation(self, expr, condition=None, evaluate=True, **kwargs): """ Computes expectation Parameters ========== expr: RandomIndexedSymbol, Relational, Logic Condition for which expectation has to be computed. Must contain a RandomIndexedSymbol of the process. condition: Relational, Boolean The given conditions under which computations should be done, i.e, the intervals on which each variable time stamp in expr is defined Returns ======= Expectation of the given expr """ if condition is not None: intervals, rv_swap = get_timerv_swaps(expr, condition) # they are independent when they have non-overlapping intervals if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet for intv_comb in itertools.combinations(intervals, 2)): if expr.is_Add: return Add.fromiter(self.expectation(arg, condition) for arg in expr.args) expr = expr.subs(rv_swap) else: return Expectation(expr, condition) return _SubstituteRV._expectation(expr, evaluate=evaluate, **kwargs) def _solve_argwith_tworvs(self, arg): if arg.args[0].key >= arg.args[1].key or isinstance(arg, Eq): diff_key = abs(arg.args[0].key - arg.args[1].key) rv = arg.args[0] arg = arg.__class__(rv.pspace.process(diff_key), 0) else: diff_key = arg.args[1].key - arg.args[0].key rv = arg.args[1] arg = arg.__class__(rv.pspace.process(diff_key), 0) return arg def _solve_numerical(self, condition, given_condition=None): if isinstance(condition, And): args_list = list(condition.args) else: args_list = [condition] if given_condition is not None: if isinstance(given_condition, And): args_list.extend(list(given_condition.args)) else: args_list.extend([given_condition]) # sort the args based on timestamp to get the independent increments in # each segment using all the condition args as well as given_condition args args_list = sorted(args_list, key=lambda x: x.args[0].key) result = [] cond_args = list(condition.args) if isinstance(condition, And) else [condition] if args_list[0] in cond_args and not (is_random(args_list[0].args[0]) and is_random(args_list[0].args[1])): result.append(_SubstituteRV._probability(args_list[0])) if is_random(args_list[0].args[0]) and is_random(args_list[0].args[1]): arg = self._solve_argwith_tworvs(args_list[0]) result.append(_SubstituteRV._probability(arg)) for i in range(len(args_list) - 1): curr, nex = args_list[i], args_list[i + 1] diff_key = nex.args[0].key - curr.args[0].key working_set = curr.args[0].pspace.process.state_space if curr.args[1] > nex.args[1]: #impossible condition so return 0 result.append(0) break if isinstance(curr, Eq): working_set = Intersection(working_set, Interval.Lopen(curr.args[1], oo)) else: working_set = Intersection(working_set, curr.as_set()) if isinstance(nex, Eq): working_set = Intersection(working_set, Interval(-oo, nex.args[1])) else: working_set = Intersection(working_set, nex.as_set()) if working_set == EmptySet: rv = Eq(curr.args[0].pspace.process(diff_key), 0) result.append(_SubstituteRV._probability(rv)) else: if working_set.is_finite_set: if isinstance(curr, Eq) and isinstance(nex, Eq): rv = Eq(curr.args[0].pspace.process(diff_key), len(working_set)) result.append(_SubstituteRV._probability(rv)) elif isinstance(curr, Eq) ^ isinstance(nex, Eq): result.append(Add.fromiter(_SubstituteRV._probability(Eq( curr.args[0].pspace.process(diff_key), x)) for x in range(len(working_set)))) else: n = len(working_set) result.append(Add.fromiter((n - x)*_SubstituteRV._probability(Eq( curr.args[0].pspace.process(diff_key), x)) for x in range(n))) else: result.append(_SubstituteRV._probability( curr.args[0].pspace.process(diff_key) <= working_set._sup - working_set._inf)) return Mul.fromiter(result) def probability(self, condition, given_condition=None, evaluate=True, **kwargs): """ Computes probability. Parameters ========== condition: Relational Condition for which probability has to be computed. Must contain a RandomIndexedSymbol of the process. given_condition: Relational, Boolean The given conditions under which computations should be done, i.e, the intervals on which each variable time stamp in expr is defined Returns ======= Probability of the condition """ check_numeric = True if isinstance(condition, (And, Or)): cond_args = condition.args else: cond_args = (condition, ) # check that condition args are numeric or not if not all(arg.args[0].key.is_number for arg in cond_args): check_numeric = False if given_condition is not None: check_given_numeric = True if isinstance(given_condition, (And, Or)): given_cond_args = given_condition.args else: given_cond_args = (given_condition, ) # check that given condition args are numeric or not if given_condition.has(Contains): check_given_numeric = False # Handle numerical queries if check_numeric and check_given_numeric: res = [] if isinstance(condition, Or): res.append(Add.fromiter(self._solve_numerical(arg, given_condition) for arg in condition.args)) if isinstance(given_condition, Or): res.append(Add.fromiter(self._solve_numerical(condition, arg) for arg in given_condition.args)) if res: return Add.fromiter(res) return self._solve_numerical(condition, given_condition) # No numeric queries, go by Contains?... then check that all the # given condition are in form of `Contains` if not all(arg.has(Contains) for arg in given_cond_args): raise ValueError("If given condition is passed with `Contains`, then " "please pass the evaluated condition with its corresponding information " "in terms of intervals of each time stamp to be passed in given condition.") intervals, rv_swap = get_timerv_swaps(condition, given_condition) # they are independent when they have non-overlapping intervals if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet for intv_comb in itertools.combinations(intervals, 2)): if isinstance(condition, And): return Mul.fromiter(self.probability(arg, given_condition) for arg in condition.args) elif isinstance(condition, Or): return Add.fromiter(self.probability(arg, given_condition) for arg in condition.args) condition = condition.subs(rv_swap) else: return Probability(condition, given_condition) if check_numeric: return self._solve_numerical(condition) return _SubstituteRV._probability(condition, evaluate=evaluate, **kwargs) class PoissonProcess(CountingProcess): """ The Poisson process is a counting process. It is usually used in scenarios where we are counting the occurrences of certain events that appear to happen at a certain rate, but completely at random. Parameters ========== sym: Symbol/str lamda: Positive number Rate of the process, ``lamda > 0`` Examples ======== >>> from sympy.stats import PoissonProcess, P, E >>> from sympy import symbols, Eq, Ne, Contains, Interval >>> X = PoissonProcess("X", lamda=3) >>> X.state_space Naturals0 >>> X.lamda 3 >>> t1, t2 = symbols('t1 t2', positive=True) >>> P(X(t1) < 4) (9*t1**3/2 + 9*t1**2/2 + 3*t1 + 1)*exp(-3*t1) >>> P(Eq(X(t1), 2) | Ne(X(t1), 4), Contains(t1, Interval.Ropen(2, 4))) 1 - 36*exp(-6) >>> P(Eq(X(t1), 2) & Eq(X(t2), 3), Contains(t1, Interval.Lopen(0, 2)) ... & Contains(t2, Interval.Lopen(2, 4))) 648*exp(-12) >>> E(X(t1)) 3*t1 >>> E(X(t1)**2 + 2*X(t2), Contains(t1, Interval.Lopen(0, 1)) ... & Contains(t2, Interval.Lopen(1, 2))) 18 >>> P(X(3) < 1, Eq(X(1), 0)) exp(-6) >>> P(Eq(X(4), 3), Eq(X(2), 3)) exp(-6) >>> P(X(2) <= 3, X(1) > 1) 5*exp(-3) Merging two Poisson Processes >>> Y = PoissonProcess("Y", lamda=4) >>> Z = X + Y >>> Z.lamda 7 Splitting a Poisson Process into two independent Poisson Processes >>> N, M = Z.split(l1=2, l2=5) >>> N.lamda, M.lamda (2, 5) References ========== .. [1] https://www.probabilitycourse.com/chapter11/11_0_0_intro.php .. [2] https://en.wikipedia.org/wiki/Poisson_point_process """ def __new__(cls, sym, lamda): _value_check(lamda > 0, 'lamda should be a positive number.') sym = _symbol_converter(sym) lamda = _sympify(lamda) return Basic.__new__(cls, sym, lamda) @property def lamda(self): return self.args[1] @property def state_space(self): return S.Naturals0 def distribution(self, key): if isinstance(key, RandomIndexedSymbol): self._deprecation_warn_distribution() return PoissonDistribution(self.lamda*key.key) return PoissonDistribution(self.lamda*key) def density(self, x): return (self.lamda*x.key)**x / factorial(x) * exp(-(self.lamda*x.key)) def simple_rv(self, rv): return Poisson(rv.name, lamda=self.lamda*rv.key) def __add__(self, other): if not isinstance(other, PoissonProcess): raise ValueError("Only instances of Poisson Process can be merged") return PoissonProcess(Dummy(self.symbol.name + other.symbol.name), self.lamda + other.lamda) def split(self, l1, l2): if _sympify(l1 + l2) != self.lamda: raise ValueError("Sum of l1 and l2 should be %s" % str(self.lamda)) return PoissonProcess(Dummy("l1"), l1), PoissonProcess(Dummy("l2"), l2) class WienerProcess(CountingProcess): """ The Wiener process is a real valued continuous-time stochastic process. In physics it is used to study Brownian motion and therefore also known as Brownian Motion. Parameters ========== sym: Symbol/str Examples ======== >>> from sympy.stats import WienerProcess, P, E >>> from sympy import symbols, Contains, Interval >>> X = WienerProcess("X") >>> X.state_space Reals >>> t1, t2 = symbols('t1 t2', positive=True) >>> P(X(t1) < 7).simplify() erf(7*sqrt(2)/(2*sqrt(t1)))/2 + 1/2 >>> P((X(t1) > 2) | (X(t1) < 4), Contains(t1, Interval.Ropen(2, 4))).simplify() -erf(1)/2 + erf(2)/2 + 1 >>> E(X(t1)) 0 >>> E(X(t1) + 2*X(t2), Contains(t1, Interval.Lopen(0, 1)) ... & Contains(t2, Interval.Lopen(1, 2))) 0 References ========== .. [1] https://www.probabilitycourse.com/chapter11/11_4_0_brownian_motion_wiener_process.php .. [2] https://en.wikipedia.org/wiki/Wiener_process """ def __new__(cls, sym): sym = _symbol_converter(sym) return Basic.__new__(cls, sym) @property def state_space(self): return S.Reals def distribution(self, key): if isinstance(key, RandomIndexedSymbol): self._deprecation_warn_distribution() return NormalDistribution(0, sqrt(key.key)) return NormalDistribution(0, sqrt(key)) def density(self, x): return exp(-x**2/(2*x.key)) / (sqrt(2*pi)*sqrt(x.key)) def simple_rv(self, rv): return Normal(rv.name, 0, sqrt(rv.key)) class GammaProcess(CountingProcess): """ A Gamma process is a random process with independent gamma distributed increments. It is a pure-jump increasing Levy process. Parameters ========== sym: Symbol/str lamda: Positive number Jump size of the process, ``lamda > 0`` gamma: Positive number Rate of jump arrivals, ``gamma > 0`` Examples ======== >>> from sympy.stats import GammaProcess, E, P, variance >>> from sympy import symbols, Contains, Interval, Not >>> t, d, x, l, g = symbols('t d x l g', positive=True) >>> X = GammaProcess("X", l, g) >>> E(X(t)) g*t/l >>> variance(X(t)).simplify() g*t/l**2 >>> X = GammaProcess('X', 1, 2) >>> P(X(t) < 1).simplify() lowergamma(2*t, 1)/gamma(2*t) >>> P(Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) & ... Contains(d, Interval.Lopen(7, 8))).simplify() -4*exp(-3) + 472*exp(-8)/3 + 1 >>> E(X(2) + x*E(X(5))) 10*x + 4 References ========== .. [1] https://en.wikipedia.org/wiki/Gamma_process """ def __new__(cls, sym, lamda, gamma): _value_check(lamda > 0, 'lamda should be a positive number') _value_check(gamma > 0, 'gamma should be a positive number') sym = _symbol_converter(sym) gamma = _sympify(gamma) lamda = _sympify(lamda) return Basic.__new__(cls, sym, lamda, gamma) @property def lamda(self): return self.args[1] @property def gamma(self): return self.args[2] @property def state_space(self): return _set_converter(Interval(0, oo)) def distribution(self, key): if isinstance(key, RandomIndexedSymbol): self._deprecation_warn_distribution() return GammaDistribution(self.gamma*key.key, 1/self.lamda) return GammaDistribution(self.gamma*key, 1/self.lamda) def density(self, x): k = self.gamma*x.key theta = 1/self.lamda return x**(k - 1) * exp(-x/theta) / (gamma(k)*theta**k) def simple_rv(self, rv): return Gamma(rv.name, self.gamma*rv.key, 1/self.lamda)
73e738911dd1c2d1e17bf2646cd4547d6ccd21cfe8b5c6116403e0492409355d
from sympy.core.basic import Basic from sympy.core.mul import prod from sympy.core.numbers import pi from sympy.core.singleton import S from sympy.functions.elementary.exponential import exp from sympy.functions.special.gamma_functions import multigamma from sympy.core.sympify import sympify, _sympify from sympy.matrices import (ImmutableMatrix, Inverse, Trace, Determinant, MatrixSymbol, MatrixBase, Transpose, MatrixSet, matrix2numpy) from sympy.stats.rv import (_value_check, RandomMatrixSymbol, NamedArgsMixin, PSpace, _symbol_converter, MatrixDomain, Distribution) from sympy.external import import_module ################################################################################ #------------------------Matrix Probability Space------------------------------# ################################################################################ class MatrixPSpace(PSpace): """ Represents probability space for Matrix Distributions. """ def __new__(cls, sym, distribution, dim_n, dim_m): sym = _symbol_converter(sym) dim_n, dim_m = _sympify(dim_n), _sympify(dim_m) if not (dim_n.is_integer and dim_m.is_integer): raise ValueError("Dimensions should be integers") return Basic.__new__(cls, sym, distribution, dim_n, dim_m) distribution = property(lambda self: self.args[1]) symbol = property(lambda self: self.args[0]) @property def domain(self): return MatrixDomain(self.symbol, self.distribution.set) @property def value(self): return RandomMatrixSymbol(self.symbol, self.args[2], self.args[3], self) @property def values(self): return {self.value} def compute_density(self, expr, *args): rms = expr.atoms(RandomMatrixSymbol) if len(rms) > 1 or (not isinstance(expr, RandomMatrixSymbol)): raise NotImplementedError("Currently, no algorithm has been " "implemented to handle general expressions containing " "multiple matrix distributions.") return self.distribution.pdf(expr) def sample(self, size=(), library='scipy', seed=None): """ Internal sample method Returns dictionary mapping RandomMatrixSymbol to realization value. """ return {self.value: self.distribution.sample(size, library=library, seed=seed)} def rv(symbol, cls, args): args = list(map(sympify, args)) dist = cls(*args) dist.check(*args) dim = dist.dimension pspace = MatrixPSpace(symbol, dist, dim[0], dim[1]) return pspace.value class SampleMatrixScipy: """Returns the sample from scipy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_scipy(dist, size, seed) @classmethod def _sample_scipy(cls, dist, size, seed): """Sample from SciPy.""" from scipy import stats as scipy_stats import numpy scipy_rv_map = { 'WishartDistribution': lambda dist, size, rand_state: scipy_stats.wishart.rvs( df=int(dist.n), scale=matrix2numpy(dist.scale_matrix, float), size=size), 'MatrixNormalDistribution': lambda dist, size, rand_state: scipy_stats.matrix_normal.rvs( mean=matrix2numpy(dist.location_matrix, float), rowcov=matrix2numpy(dist.scale_matrix_1, float), colcov=matrix2numpy(dist.scale_matrix_2, float), size=size, random_state=rand_state) } sample_shape = { 'WishartDistribution': lambda dist: dist.scale_matrix.shape, 'MatrixNormalDistribution' : lambda dist: dist.location_matrix.shape } dist_list = scipy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed samp = scipy_rv_map[dist.__class__.__name__](dist, prod(size), rand_state) return samp.reshape(size + sample_shape[dist.__class__.__name__](dist)) class SampleMatrixNumpy: """Returns the sample from numpy of the given distribution""" ### TODO: Add tests after adding matrix distributions in numpy_rv_map def __new__(cls, dist, size, seed=None): return cls._sample_numpy(dist, size, seed) @classmethod def _sample_numpy(cls, dist, size, seed): """Sample from NumPy.""" numpy_rv_map = { } sample_shape = { } dist_list = numpy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed samp = numpy_rv_map[dist.__class__.__name__](dist, prod(size), rand_state) return samp.reshape(size + sample_shape[dist.__class__.__name__](dist)) class SampleMatrixPymc: """Returns the sample from pymc3 of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_pymc3(dist, size, seed) @classmethod def _sample_pymc3(cls, dist, size, seed): """Sample from PyMC3.""" import pymc3 pymc3_rv_map = { 'MatrixNormalDistribution': lambda dist: pymc3.MatrixNormal('X', mu=matrix2numpy(dist.location_matrix, float), rowcov=matrix2numpy(dist.scale_matrix_1, float), colcov=matrix2numpy(dist.scale_matrix_2, float), shape=dist.location_matrix.shape), 'WishartDistribution': lambda dist: pymc3.WishartBartlett('X', nu=int(dist.n), S=matrix2numpy(dist.scale_matrix, float)) } sample_shape = { 'WishartDistribution': lambda dist: dist.scale_matrix.shape, 'MatrixNormalDistribution' : lambda dist: dist.location_matrix.shape } dist_list = pymc3_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None import logging logging.getLogger("pymc3").setLevel(logging.ERROR) with pymc3.Model(): pymc3_rv_map[dist.__class__.__name__](dist) samps = pymc3.sample(draws=prod(size), chains=1, progressbar=False, random_seed=seed, return_inferencedata=False, compute_convergence_checks=False)['X'] return samps.reshape(size + sample_shape[dist.__class__.__name__](dist)) _get_sample_class_matrixrv = { 'scipy': SampleMatrixScipy, 'pymc3': SampleMatrixPymc, 'numpy': SampleMatrixNumpy } ################################################################################ #-------------------------Matrix Distribution----------------------------------# ################################################################################ class MatrixDistribution(Distribution, NamedArgsMixin): """ Abstract class for Matrix Distribution. """ def __new__(cls, *args): args = [ImmutableMatrix(arg) if isinstance(arg, list) else _sympify(arg) for arg in args] return Basic.__new__(cls, *args) @staticmethod def check(*args): pass def __call__(self, expr): if isinstance(expr, list): expr = ImmutableMatrix(expr) return self.pdf(expr) def sample(self, size=(), library='scipy', seed=None): """ Internal sample method Returns dictionary mapping RandomSymbol to realization value. """ libraries = ['scipy', 'numpy', 'pymc3'] if library not in libraries: raise NotImplementedError("Sampling from %s is not supported yet." % str(library)) if not import_module(library): raise ValueError("Failed to import %s" % library) samps = _get_sample_class_matrixrv[library](self, size, seed) if samps is not None: return samps raise NotImplementedError( "Sampling for %s is not currently implemented from %s" % (self.__class__.__name__, library) ) ################################################################################ #------------------------Matrix Distribution Types-----------------------------# ################################################################################ #------------------------------------------------------------------------------- # Matrix Gamma distribution ---------------------------------------------------- class MatrixGammaDistribution(MatrixDistribution): _argnames = ('alpha', 'beta', 'scale_matrix') @staticmethod def check(alpha, beta, scale_matrix): if not isinstance(scale_matrix, MatrixSymbol): _value_check(scale_matrix.is_positive_definite, "The shape " "matrix must be positive definite.") _value_check(scale_matrix.is_square, "Should " "be square matrix") _value_check(alpha.is_positive, "Shape parameter should be positive.") _value_check(beta.is_positive, "Scale parameter should be positive.") @property def set(self): k = self.scale_matrix.shape[0] return MatrixSet(k, k, S.Reals) @property def dimension(self): return self.scale_matrix.shape def pdf(self, x): alpha, beta, scale_matrix = self.alpha, self.beta, self.scale_matrix p = scale_matrix.shape[0] if isinstance(x, list): x = ImmutableMatrix(x) if not isinstance(x, (MatrixBase, MatrixSymbol)): raise ValueError("%s should be an isinstance of Matrix " "or MatrixSymbol" % str(x)) sigma_inv_x = - Inverse(scale_matrix)*x / beta term1 = exp(Trace(sigma_inv_x))/((beta**(p*alpha)) * multigamma(alpha, p)) term2 = (Determinant(scale_matrix))**(-alpha) term3 = (Determinant(x))**(alpha - S(p + 1)/2) return term1 * term2 * term3 def MatrixGamma(symbol, alpha, beta, scale_matrix): """ Creates a random variable with Matrix Gamma Distribution. The density of the said distribution can be found at [1]. Parameters ========== alpha: Positive Real number Shape Parameter beta: Positive Real number Scale Parameter scale_matrix: Positive definite real square matrix Scale Matrix Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import density, MatrixGamma >>> from sympy import MatrixSymbol, symbols >>> a, b = symbols('a b', positive=True) >>> M = MatrixGamma('M', a, b, [[2, 1], [1, 2]]) >>> X = MatrixSymbol('X', 2, 2) >>> density(M)(X).doit() exp(Trace(Matrix([ [-2/3, 1/3], [ 1/3, -2/3]])*X)/b)*Determinant(X)**(a - 3/2)/(3**a*sqrt(pi)*b**(2*a)*gamma(a)*gamma(a - 1/2)) >>> density(M)([[1, 0], [0, 1]]).doit() exp(-4/(3*b))/(3**a*sqrt(pi)*b**(2*a)*gamma(a)*gamma(a - 1/2)) References ========== .. [1] https://en.wikipedia.org/wiki/Matrix_gamma_distribution """ if isinstance(scale_matrix, list): scale_matrix = ImmutableMatrix(scale_matrix) return rv(symbol, MatrixGammaDistribution, (alpha, beta, scale_matrix)) #------------------------------------------------------------------------------- # Wishart Distribution --------------------------------------------------------- class WishartDistribution(MatrixDistribution): _argnames = ('n', 'scale_matrix') @staticmethod def check(n, scale_matrix): if not isinstance(scale_matrix, MatrixSymbol): _value_check(scale_matrix.is_positive_definite, "The shape " "matrix must be positive definite.") _value_check(scale_matrix.is_square, "Should " "be square matrix") _value_check(n.is_positive, "Shape parameter should be positive.") @property def set(self): k = self.scale_matrix.shape[0] return MatrixSet(k, k, S.Reals) @property def dimension(self): return self.scale_matrix.shape def pdf(self, x): n, scale_matrix = self.n, self.scale_matrix p = scale_matrix.shape[0] if isinstance(x, list): x = ImmutableMatrix(x) if not isinstance(x, (MatrixBase, MatrixSymbol)): raise ValueError("%s should be an isinstance of Matrix " "or MatrixSymbol" % str(x)) sigma_inv_x = - Inverse(scale_matrix)*x / S(2) term1 = exp(Trace(sigma_inv_x))/((2**(p*n/S(2))) * multigamma(n/S(2), p)) term2 = (Determinant(scale_matrix))**(-n/S(2)) term3 = (Determinant(x))**(S(n - p - 1)/2) return term1 * term2 * term3 def Wishart(symbol, n, scale_matrix): """ Creates a random variable with Wishart Distribution. The density of the said distribution can be found at [1]. Parameters ========== n: Positive Real number Represents degrees of freedom scale_matrix: Positive definite real square matrix Scale Matrix Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import density, Wishart >>> from sympy import MatrixSymbol, symbols >>> n = symbols('n', positive=True) >>> W = Wishart('W', n, [[2, 1], [1, 2]]) >>> X = MatrixSymbol('X', 2, 2) >>> density(W)(X).doit() exp(Trace(Matrix([ [-1/3, 1/6], [ 1/6, -1/3]])*X))*Determinant(X)**(n/2 - 3/2)/(2**n*3**(n/2)*sqrt(pi)*gamma(n/2)*gamma(n/2 - 1/2)) >>> density(W)([[1, 0], [0, 1]]).doit() exp(-2/3)/(2**n*3**(n/2)*sqrt(pi)*gamma(n/2)*gamma(n/2 - 1/2)) References ========== .. [1] https://en.wikipedia.org/wiki/Wishart_distribution """ if isinstance(scale_matrix, list): scale_matrix = ImmutableMatrix(scale_matrix) return rv(symbol, WishartDistribution, (n, scale_matrix)) #------------------------------------------------------------------------------- # Matrix Normal distribution --------------------------------------------------- class MatrixNormalDistribution(MatrixDistribution): _argnames = ('location_matrix', 'scale_matrix_1', 'scale_matrix_2') @staticmethod def check(location_matrix, scale_matrix_1, scale_matrix_2): if not isinstance(scale_matrix_1, MatrixSymbol): _value_check(scale_matrix_1.is_positive_definite, "The shape " "matrix must be positive definite.") if not isinstance(scale_matrix_2, MatrixSymbol): _value_check(scale_matrix_2.is_positive_definite, "The shape " "matrix must be positive definite.") _value_check(scale_matrix_1.is_square, "Scale matrix 1 should be " "be square matrix") _value_check(scale_matrix_2.is_square, "Scale matrix 2 should be " "be square matrix") n = location_matrix.shape[0] p = location_matrix.shape[1] _value_check(scale_matrix_1.shape[0] == n, "Scale matrix 1 should be" " of shape %s x %s"% (str(n), str(n))) _value_check(scale_matrix_2.shape[0] == p, "Scale matrix 2 should be" " of shape %s x %s"% (str(p), str(p))) @property def set(self): n, p = self.location_matrix.shape return MatrixSet(n, p, S.Reals) @property def dimension(self): return self.location_matrix.shape def pdf(self, x): M, U, V = self.location_matrix, self.scale_matrix_1, self.scale_matrix_2 n, p = M.shape if isinstance(x, list): x = ImmutableMatrix(x) if not isinstance(x, (MatrixBase, MatrixSymbol)): raise ValueError("%s should be an isinstance of Matrix " "or MatrixSymbol" % str(x)) term1 = Inverse(V)*Transpose(x - M)*Inverse(U)*(x - M) num = exp(-Trace(term1)/S(2)) den = (2*pi)**(S(n*p)/2) * Determinant(U)**S(p)/2 * Determinant(V)**S(n)/2 return num/den def MatrixNormal(symbol, location_matrix, scale_matrix_1, scale_matrix_2): """ Creates a random variable with Matrix Normal Distribution. The density of the said distribution can be found at [1]. Parameters ========== location_matrix: Real ``n x p`` matrix Represents degrees of freedom scale_matrix_1: Positive definite matrix Scale Matrix of shape ``n x n`` scale_matrix_2: Positive definite matrix Scale Matrix of shape ``p x p`` Returns ======= RandomSymbol Examples ======== >>> from sympy import MatrixSymbol >>> from sympy.stats import density, MatrixNormal >>> M = MatrixNormal('M', [[1, 2]], [1], [[1, 0], [0, 1]]) >>> X = MatrixSymbol('X', 1, 2) >>> density(M)(X).doit() 2*exp(-Trace((Matrix([ [-1], [-2]]) + X.T)*(Matrix([[-1, -2]]) + X))/2)/pi >>> density(M)([[3, 4]]).doit() 2*exp(-4)/pi References ========== .. [1] https://en.wikipedia.org/wiki/Matrix_normal_distribution """ if isinstance(location_matrix, list): location_matrix = ImmutableMatrix(location_matrix) if isinstance(scale_matrix_1, list): scale_matrix_1 = ImmutableMatrix(scale_matrix_1) if isinstance(scale_matrix_2, list): scale_matrix_2 = ImmutableMatrix(scale_matrix_2) args = (location_matrix, scale_matrix_1, scale_matrix_2) return rv(symbol, MatrixNormalDistribution, args) #------------------------------------------------------------------------------- # Matrix Student's T distribution --------------------------------------------------- class MatrixStudentTDistribution(MatrixDistribution): _argnames = ('nu', 'location_matrix', 'scale_matrix_1', 'scale_matrix_2') @staticmethod def check(nu, location_matrix, scale_matrix_1, scale_matrix_2): if not isinstance(scale_matrix_1, MatrixSymbol): _value_check(scale_matrix_1.is_positive_definite != False, "The shape " "matrix must be positive definite.") if not isinstance(scale_matrix_2, MatrixSymbol): _value_check(scale_matrix_2.is_positive_definite != False, "The shape " "matrix must be positive definite.") _value_check(scale_matrix_1.is_square != False, "Scale matrix 1 should be " "be square matrix") _value_check(scale_matrix_2.is_square != False, "Scale matrix 2 should be " "be square matrix") n = location_matrix.shape[0] p = location_matrix.shape[1] _value_check(scale_matrix_1.shape[0] == p, "Scale matrix 1 should be" " of shape %s x %s" % (str(p), str(p))) _value_check(scale_matrix_2.shape[0] == n, "Scale matrix 2 should be" " of shape %s x %s" % (str(n), str(n))) _value_check(nu.is_positive != False, "Degrees of freedom must be positive") @property def set(self): n, p = self.location_matrix.shape return MatrixSet(n, p, S.Reals) @property def dimension(self): return self.location_matrix.shape def pdf(self, x): from sympy.matrices.dense import eye if isinstance(x, list): x = ImmutableMatrix(x) if not isinstance(x, (MatrixBase, MatrixSymbol)): raise ValueError("%s should be an isinstance of Matrix " "or MatrixSymbol" % str(x)) nu, M, Omega, Sigma = self.nu, self.location_matrix, self.scale_matrix_1, self.scale_matrix_2 n, p = M.shape K = multigamma((nu + n + p - 1)/2, p) * Determinant(Omega)**(-n/2) * Determinant(Sigma)**(-p/2) \ / ((pi)**(n*p/2) * multigamma((nu + p - 1)/2, p)) return K * (Determinant(eye(n) + Inverse(Sigma)*(x - M)*Inverse(Omega)*Transpose(x - M))) \ **(-(nu + n + p -1)/2) def MatrixStudentT(symbol, nu, location_matrix, scale_matrix_1, scale_matrix_2): """ Creates a random variable with Matrix Gamma Distribution. The density of the said distribution can be found at [1]. Parameters ========== nu: Positive Real number degrees of freedom location_matrix: Positive definite real square matrix Location Matrix of shape ``n x p`` scale_matrix_1: Positive definite real square matrix Scale Matrix of shape ``p x p`` scale_matrix_2: Positive definite real square matrix Scale Matrix of shape ``n x n`` Returns ======= RandomSymbol Examples ======== >>> from sympy import MatrixSymbol,symbols >>> from sympy.stats import density, MatrixStudentT >>> v = symbols('v',positive=True) >>> M = MatrixStudentT('M', v, [[1, 2]], [[1, 0], [0, 1]], [1]) >>> X = MatrixSymbol('X', 1, 2) >>> density(M)(X) gamma(v/2 + 1)*Determinant((Matrix([[-1, -2]]) + X)*(Matrix([ [-1], [-2]]) + X.T) + Matrix([[1]]))**(-v/2 - 1)/(pi**1.0*gamma(v/2)*Determinant(Matrix([[1]]))**1.0*Determinant(Matrix([ [1, 0], [0, 1]]))**0.5) References ========== .. [1] https://en.wikipedia.org/wiki/Matrix_t-distribution """ if isinstance(location_matrix, list): location_matrix = ImmutableMatrix(location_matrix) if isinstance(scale_matrix_1, list): scale_matrix_1 = ImmutableMatrix(scale_matrix_1) if isinstance(scale_matrix_2, list): scale_matrix_2 = ImmutableMatrix(scale_matrix_2) args = (nu, location_matrix, scale_matrix_1, scale_matrix_2) return rv(symbol, MatrixStudentTDistribution, args)
366ccb0b924c0d62364ef1fcb58ea0a3c958c879aa719f81eec4883bbcfba009
from sympy.core.basic import Basic from sympy.stats.rv import PSpace, _symbol_converter, RandomMatrixSymbol class RandomMatrixPSpace(PSpace): """ Represents probability space for random matrices. It contains the mechanics for handling the API calls for random matrices. """ def __new__(cls, sym, model=None): sym = _symbol_converter(sym) if model: return Basic.__new__(cls, sym, model) else: return Basic.__new__(cls, sym) @property def model(self): try: return self.args[1] except IndexError: return None def compute_density(self, expr, *args): rms = expr.atoms(RandomMatrixSymbol) if len(rms) > 2 or (not isinstance(expr, RandomMatrixSymbol)): raise NotImplementedError("Currently, no algorithm has been " "implemented to handle general expressions containing " "multiple random matrices.") return self.model.density(expr)
186f0449ab86abfd03a2e95d74ca813aff0fbb444ebada80b8682cf32c0a4124
from sympy.sets import FiniteSet from sympy.core.numbers import Rational from sympy.core.relational import Eq from sympy.core.symbol import Dummy from sympy.functions.combinatorial.factorials import FallingFactorial from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import piecewise_fold from sympy.integrals.integrals import Integral from sympy.solvers.solveset import solveset from .rv import (probability, expectation, density, where, given, pspace, cdf, PSpace, characteristic_function, sample, sample_iter, random_symbols, independent, dependent, sampling_density, moment_generating_function, quantile, is_random, sample_stochastic_process) __all__ = ['P', 'E', 'H', 'density', 'where', 'given', 'sample', 'cdf', 'characteristic_function', 'pspace', 'sample_iter', 'variance', 'std', 'skewness', 'kurtosis', 'covariance', 'dependent', 'entropy', 'median', 'independent', 'random_symbols', 'correlation', 'factorial_moment', 'moment', 'cmoment', 'sampling_density', 'moment_generating_function', 'smoment', 'quantile', 'sample_stochastic_process'] def moment(X, n, c=0, condition=None, *, evaluate=True, **kwargs): """ Return the nth moment of a random expression about c. .. math:: moment(X, c, n) = E((X-c)^{n}) Default value of c is 0. Examples ======== >>> from sympy.stats import Die, moment, E >>> X = Die('X', 6) >>> moment(X, 1, 6) -5/2 >>> moment(X, 2) 91/6 >>> moment(X, 1) == E(X) True """ from sympy.stats.symbolic_probability import Moment if evaluate: return Moment(X, n, c, condition).doit() return Moment(X, n, c, condition).rewrite(Integral) def variance(X, condition=None, **kwargs): """ Variance of a random expression. .. math:: variance(X) = E((X-E(X))^{2}) Examples ======== >>> from sympy.stats import Die, Bernoulli, variance >>> from sympy import simplify, Symbol >>> X = Die('X', 6) >>> p = Symbol('p') >>> B = Bernoulli('B', p, 1, 0) >>> variance(2*X) 35/3 >>> simplify(variance(B)) p*(1 - p) """ if is_random(X) and pspace(X) == PSpace(): from sympy.stats.symbolic_probability import Variance return Variance(X, condition) return cmoment(X, 2, condition, **kwargs) def standard_deviation(X, condition=None, **kwargs): r""" Standard Deviation of a random expression .. math:: std(X) = \sqrt(E((X-E(X))^{2})) Examples ======== >>> from sympy.stats import Bernoulli, std >>> from sympy import Symbol, simplify >>> p = Symbol('p') >>> B = Bernoulli('B', p, 1, 0) >>> simplify(std(B)) sqrt(p*(1 - p)) """ return sqrt(variance(X, condition, **kwargs)) std = standard_deviation def entropy(expr, condition=None, **kwargs): """ Calculuates entropy of a probability distribution. Parameters ========== expression : the random expression whose entropy is to be calculated condition : optional, to specify conditions on random expression b: base of the logarithm, optional By default, it is taken as Euler's number Returns ======= result : Entropy of the expression, a constant Examples ======== >>> from sympy.stats import Normal, Die, entropy >>> X = Normal('X', 0, 1) >>> entropy(X) log(2)/2 + 1/2 + log(pi)/2 >>> D = Die('D', 4) >>> entropy(D) log(4) References ========== .. [1] https://en.wikipedia.org/wiki/Entropy_(information_theory) .. [2] https://www.crmarsh.com/static/pdf/Charles_Marsh_Continuous_Entropy.pdf .. [3] http://www.math.uconn.edu/~kconrad/blurbs/analysis/entropypost.pdf """ pdf = density(expr, condition, **kwargs) base = kwargs.get('b', exp(1)) if isinstance(pdf, dict): return sum([-prob*log(prob, base) for prob in pdf.values()]) return expectation(-log(pdf(expr), base)) def covariance(X, Y, condition=None, **kwargs): """ Covariance of two random expressions. Explanation =========== The expectation that the two variables will rise and fall together .. math:: covariance(X,Y) = E((X-E(X)) (Y-E(Y))) Examples ======== >>> from sympy.stats import Exponential, covariance >>> from sympy import Symbol >>> rate = Symbol('lambda', positive=True, real=True) >>> X = Exponential('X', rate) >>> Y = Exponential('Y', rate) >>> covariance(X, X) lambda**(-2) >>> covariance(X, Y) 0 >>> covariance(X, Y + rate*X) 1/lambda """ if (is_random(X) and pspace(X) == PSpace()) or (is_random(Y) and pspace(Y) == PSpace()): from sympy.stats.symbolic_probability import Covariance return Covariance(X, Y, condition) return expectation( (X - expectation(X, condition, **kwargs)) * (Y - expectation(Y, condition, **kwargs)), condition, **kwargs) def correlation(X, Y, condition=None, **kwargs): r""" Correlation of two random expressions, also known as correlation coefficient or Pearson's correlation. Explanation =========== The normalized expectation that the two variables will rise and fall together .. math:: correlation(X,Y) = E((X-E(X))(Y-E(Y)) / (\sigma_x \sigma_y)) Examples ======== >>> from sympy.stats import Exponential, correlation >>> from sympy import Symbol >>> rate = Symbol('lambda', positive=True, real=True) >>> X = Exponential('X', rate) >>> Y = Exponential('Y', rate) >>> correlation(X, X) 1 >>> correlation(X, Y) 0 >>> correlation(X, Y + rate*X) 1/sqrt(1 + lambda**(-2)) """ return covariance(X, Y, condition, **kwargs)/(std(X, condition, **kwargs) * std(Y, condition, **kwargs)) def cmoment(X, n, condition=None, *, evaluate=True, **kwargs): """ Return the nth central moment of a random expression about its mean. .. math:: cmoment(X, n) = E((X - E(X))^{n}) Examples ======== >>> from sympy.stats import Die, cmoment, variance >>> X = Die('X', 6) >>> cmoment(X, 3) 0 >>> cmoment(X, 2) 35/12 >>> cmoment(X, 2) == variance(X) True """ from sympy.stats.symbolic_probability import CentralMoment if evaluate: return CentralMoment(X, n, condition).doit() return CentralMoment(X, n, condition).rewrite(Integral) def smoment(X, n, condition=None, **kwargs): r""" Return the nth Standardized moment of a random expression. .. math:: smoment(X, n) = E(((X - \mu)/\sigma_X)^{n}) Examples ======== >>> from sympy.stats import skewness, Exponential, smoment >>> from sympy import Symbol >>> rate = Symbol('lambda', positive=True, real=True) >>> Y = Exponential('Y', rate) >>> smoment(Y, 4) 9 >>> smoment(Y, 4) == smoment(3*Y, 4) True >>> smoment(Y, 3) == skewness(Y) True """ sigma = std(X, condition, **kwargs) return (1/sigma)**n*cmoment(X, n, condition, **kwargs) def skewness(X, condition=None, **kwargs): r""" Measure of the asymmetry of the probability distribution. Explanation =========== Positive skew indicates that most of the values lie to the right of the mean. .. math:: skewness(X) = E(((X - E(X))/\sigma_X)^{3}) Parameters ========== condition : Expr containing RandomSymbols A conditional expression. skewness(X, X>0) is skewness of X given X > 0 Examples ======== >>> from sympy.stats import skewness, Exponential, Normal >>> from sympy import Symbol >>> X = Normal('X', 0, 1) >>> skewness(X) 0 >>> skewness(X, X > 0) # find skewness given X > 0 (-sqrt(2)/sqrt(pi) + 4*sqrt(2)/pi**(3/2))/(1 - 2/pi)**(3/2) >>> rate = Symbol('lambda', positive=True, real=True) >>> Y = Exponential('Y', rate) >>> skewness(Y) 2 """ return smoment(X, 3, condition=condition, **kwargs) def kurtosis(X, condition=None, **kwargs): r""" Characterizes the tails/outliers of a probability distribution. Explanation =========== Kurtosis of any univariate normal distribution is 3. Kurtosis less than 3 means that the distribution produces fewer and less extreme outliers than the normal distribution. .. math:: kurtosis(X) = E(((X - E(X))/\sigma_X)^{4}) Parameters ========== condition : Expr containing RandomSymbols A conditional expression. kurtosis(X, X>0) is kurtosis of X given X > 0 Examples ======== >>> from sympy.stats import kurtosis, Exponential, Normal >>> from sympy import Symbol >>> X = Normal('X', 0, 1) >>> kurtosis(X) 3 >>> kurtosis(X, X > 0) # find kurtosis given X > 0 (-4/pi - 12/pi**2 + 3)/(1 - 2/pi)**2 >>> rate = Symbol('lamda', positive=True, real=True) >>> Y = Exponential('Y', rate) >>> kurtosis(Y) 9 References ========== .. [1] https://en.wikipedia.org/wiki/Kurtosis .. [2] http://mathworld.wolfram.com/Kurtosis.html """ return smoment(X, 4, condition=condition, **kwargs) def factorial_moment(X, n, condition=None, **kwargs): """ The factorial moment is a mathematical quantity defined as the expectation or average of the falling factorial of a random variable. .. math:: factorial-moment(X, n) = E(X(X - 1)(X - 2)...(X - n + 1)) Parameters ========== n: A natural number, n-th factorial moment. condition : Expr containing RandomSymbols A conditional expression. Examples ======== >>> from sympy.stats import factorial_moment, Poisson, Binomial >>> from sympy import Symbol, S >>> lamda = Symbol('lamda') >>> X = Poisson('X', lamda) >>> factorial_moment(X, 2) lamda**2 >>> Y = Binomial('Y', 2, S.Half) >>> factorial_moment(Y, 2) 1/2 >>> factorial_moment(Y, 2, Y > 1) # find factorial moment for Y > 1 2 References ========== .. [1] https://en.wikipedia.org/wiki/Factorial_moment .. [2] http://mathworld.wolfram.com/FactorialMoment.html """ return expectation(FallingFactorial(X, n), condition=condition, **kwargs) def median(X, evaluate=True, **kwargs): r""" Calculuates the median of the probability distribution. Explanation =========== Mathematically, median of Probability distribution is defined as all those values of `m` for which the following condition is satisfied .. math:: P(X\leq m) \geq \frac{1}{2} \text{ and} \text{ } P(X\geq m)\geq \frac{1}{2} Parameters ========== X: The random expression whose median is to be calculated. Returns ======= The FiniteSet or an Interval which contains the median of the random expression. Examples ======== >>> from sympy.stats import Normal, Die, median >>> N = Normal('N', 3, 1) >>> median(N) {3} >>> D = Die('D') >>> median(D) {3, 4} References ========== .. [1] https://en.wikipedia.org/wiki/Median#Probability_distributions """ if not is_random(X): return X from sympy.stats.crv import ContinuousPSpace from sympy.stats.drv import DiscretePSpace from sympy.stats.frv import FinitePSpace if isinstance(pspace(X), FinitePSpace): cdf = pspace(X).compute_cdf(X) result = [] for key, value in cdf.items(): if value>= Rational(1, 2) and (1 - value) + \ pspace(X).probability(Eq(X, key)) >= Rational(1, 2): result.append(key) return FiniteSet(*result) if isinstance(pspace(X), (ContinuousPSpace, DiscretePSpace)): cdf = pspace(X).compute_cdf(X) x = Dummy('x') result = solveset(piecewise_fold(cdf(x) - Rational(1, 2)), x, pspace(X).set) return result raise NotImplementedError("The median of %s is not implemeted."%str(pspace(X))) def coskewness(X, Y, Z, condition=None, **kwargs): r""" Calculates the co-skewness of three random variables. Explanation =========== Mathematically Coskewness is defined as .. math:: coskewness(X,Y,Z)=\frac{E[(X-E[X]) * (Y-E[Y]) * (Z-E[Z])]} {\sigma_{X}\sigma_{Y}\sigma_{Z}} Parameters ========== X : RandomSymbol Random Variable used to calculate coskewness Y : RandomSymbol Random Variable used to calculate coskewness Z : RandomSymbol Random Variable used to calculate coskewness condition : Expr containing RandomSymbols A conditional expression Examples ======== >>> from sympy.stats import coskewness, Exponential, skewness >>> from sympy import symbols >>> p = symbols('p', positive=True) >>> X = Exponential('X', p) >>> Y = Exponential('Y', 2*p) >>> coskewness(X, Y, Y) 0 >>> coskewness(X, Y + X, Y + 2*X) 16*sqrt(85)/85 >>> coskewness(X + 2*Y, Y + X, Y + 2*X, X > 3) 9*sqrt(170)/85 >>> coskewness(Y, Y, Y) == skewness(Y) True >>> coskewness(X, Y + p*X, Y + 2*p*X) 4/(sqrt(1 + 1/(4*p**2))*sqrt(4 + 1/(4*p**2))) Returns ======= coskewness : The coskewness of the three random variables References ========== .. [1] https://en.wikipedia.org/wiki/Coskewness """ num = expectation((X - expectation(X, condition, **kwargs)) \ * (Y - expectation(Y, condition, **kwargs)) \ * (Z - expectation(Z, condition, **kwargs)), condition, **kwargs) den = std(X, condition, **kwargs) * std(Y, condition, **kwargs) \ * std(Z, condition, **kwargs) return num/den P = probability E = expectation H = entropy
b3aca7487015743fbda3221466553cf56cd642e95057c0e1879d9290df3882a7
""" Main Random Variables Module Defines abstract random variable type. Contains interfaces for probability space object (PSpace) as well as standard operators, P, E, sample, density, where, quantile See Also ======== sympy.stats.crv sympy.stats.frv sympy.stats.rv_interface """ from functools import singledispatch from typing import Tuple as tTuple from sympy.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.function import (Function, Lambda) from sympy.core.logic import fuzzy_and from sympy.core.mul import (Mul, prod) from sympy.core.relational import (Eq, Ne) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol) from sympy.core.sympify import sympify from sympy.functions.special.delta_functions import DiracDelta from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.logic.boolalg import (And, Or) from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.tensor.indexed import Indexed from sympy.utilities.lambdify import lambdify from sympy.core.relational import Relational from sympy.core.sympify import _sympify from sympy.sets.sets import FiniteSet, ProductSet, Intersection from sympy.solvers.solveset import solveset from sympy.external import import_module from sympy.utilities.misc import filldedent from sympy.utilities.decorator import doctest_depends_on from sympy.utilities.exceptions import SymPyDeprecationWarning from sympy.utilities.iterables import iterable import warnings x = Symbol('x') @singledispatch def is_random(x): return False @is_random.register(Basic) def _(x): atoms = x.free_symbols return any(is_random(i) for i in atoms) class RandomDomain(Basic): """ Represents a set of variables and the values which they can take. See Also ======== sympy.stats.crv.ContinuousDomain sympy.stats.frv.FiniteDomain """ is_ProductDomain = False is_Finite = False is_Continuous = False is_Discrete = False def __new__(cls, symbols, *args): symbols = FiniteSet(*symbols) return Basic.__new__(cls, symbols, *args) @property def symbols(self): return self.args[0] @property def set(self): return self.args[1] def __contains__(self, other): raise NotImplementedError() def compute_expectation(self, expr): raise NotImplementedError() class SingleDomain(RandomDomain): """ A single variable and its domain. See Also ======== sympy.stats.crv.SingleContinuousDomain sympy.stats.frv.SingleFiniteDomain """ def __new__(cls, symbol, set): assert symbol.is_Symbol return Basic.__new__(cls, symbol, set) @property def symbol(self): return self.args[0] @property def symbols(self): return FiniteSet(self.symbol) def __contains__(self, other): if len(other) != 1: return False sym, val = tuple(other)[0] return self.symbol == sym and val in self.set class MatrixDomain(RandomDomain): """ A Random Matrix variable and its domain. """ def __new__(cls, symbol, set): symbol, set = _symbol_converter(symbol), _sympify(set) return Basic.__new__(cls, symbol, set) @property def symbol(self): return self.args[0] @property def symbols(self): return FiniteSet(self.symbol) class ConditionalDomain(RandomDomain): """ A RandomDomain with an attached condition. See Also ======== sympy.stats.crv.ConditionalContinuousDomain sympy.stats.frv.ConditionalFiniteDomain """ def __new__(cls, fulldomain, condition): condition = condition.xreplace({rs: rs.symbol for rs in random_symbols(condition)}) return Basic.__new__(cls, fulldomain, condition) @property def symbols(self): return self.fulldomain.symbols @property def fulldomain(self): return self.args[0] @property def condition(self): return self.args[1] @property def set(self): raise NotImplementedError("Set of Conditional Domain not Implemented") def as_boolean(self): return And(self.fulldomain.as_boolean(), self.condition) class PSpace(Basic): """ A Probability Space. Explanation =========== Probability Spaces encode processes that equal different values probabilistically. These underly Random Symbols which occur in SymPy expressions and contain the mechanics to evaluate statistical statements. See Also ======== sympy.stats.crv.ContinuousPSpace sympy.stats.frv.FinitePSpace """ is_Finite = None # type: bool is_Continuous = None # type: bool is_Discrete = None # type: bool is_real = None # type: bool @property def domain(self): return self.args[0] @property def density(self): return self.args[1] @property def values(self): return frozenset(RandomSymbol(sym, self) for sym in self.symbols) @property def symbols(self): return self.domain.symbols def where(self, condition): raise NotImplementedError() def compute_density(self, expr): raise NotImplementedError() def sample(self, size=(), library='scipy', seed=None): raise NotImplementedError() def probability(self, condition): raise NotImplementedError() def compute_expectation(self, expr): raise NotImplementedError() class SinglePSpace(PSpace): """ Represents the probabilities of a set of random events that can be attributed to a single variable/symbol. """ def __new__(cls, s, distribution): s = _symbol_converter(s) return Basic.__new__(cls, s, distribution) @property def value(self): return RandomSymbol(self.symbol, self) @property def symbol(self): return self.args[0] @property def distribution(self): return self.args[1] @property def pdf(self): return self.distribution.pdf(self.symbol) class RandomSymbol(Expr): """ Random Symbols represent ProbabilitySpaces in SymPy Expressions. In principle they can take on any value that their symbol can take on within the associated PSpace with probability determined by the PSpace Density. Explanation =========== Random Symbols contain pspace and symbol properties. The pspace property points to the represented Probability Space The symbol is a standard SymPy Symbol that is used in that probability space for example in defining a density. You can form normal SymPy expressions using RandomSymbols and operate on those expressions with the Functions E - Expectation of a random expression P - Probability of a condition density - Probability Density of an expression given - A new random expression (with new random symbols) given a condition An object of the RandomSymbol type should almost never be created by the user. They tend to be created instead by the PSpace class's value method. Traditionally a user doesn't even do this but instead calls one of the convenience functions Normal, Exponential, Coin, Die, FiniteRV, etc.... """ def __new__(cls, symbol, pspace=None): from sympy.stats.joint_rv import JointRandomSymbol if pspace is None: # Allow single arg, representing pspace == PSpace() pspace = PSpace() symbol = _symbol_converter(symbol) if not isinstance(pspace, PSpace): raise TypeError("pspace variable should be of type PSpace") if cls == JointRandomSymbol and isinstance(pspace, SinglePSpace): cls = RandomSymbol return Basic.__new__(cls, symbol, pspace) is_finite = True is_symbol = True is_Atom = True _diff_wrt = True pspace = property(lambda self: self.args[1]) symbol = property(lambda self: self.args[0]) name = property(lambda self: self.symbol.name) def _eval_is_positive(self): return self.symbol.is_positive def _eval_is_integer(self): return self.symbol.is_integer def _eval_is_real(self): return self.symbol.is_real or self.pspace.is_real @property def is_commutative(self): return self.symbol.is_commutative @property def free_symbols(self): return {self} class RandomIndexedSymbol(RandomSymbol): def __new__(cls, idx_obj, pspace=None): if pspace is None: # Allow single arg, representing pspace == PSpace() pspace = PSpace() if not isinstance(idx_obj, (Indexed, Function)): raise TypeError("An Function or Indexed object is expected not %s"%(idx_obj)) return Basic.__new__(cls, idx_obj, pspace) symbol = property(lambda self: self.args[0]) name = property(lambda self: str(self.args[0])) @property def key(self): if isinstance(self.symbol, Indexed): return self.symbol.args[1] elif isinstance(self.symbol, Function): return self.symbol.args[0] @property def free_symbols(self): if self.key.free_symbols: free_syms = self.key.free_symbols free_syms.add(self) return free_syms return {self} @property def pspace(self): return self.args[1] class RandomMatrixSymbol(RandomSymbol, MatrixSymbol): # type: ignore def __new__(cls, symbol, n, m, pspace=None): n, m = _sympify(n), _sympify(m) symbol = _symbol_converter(symbol) if pspace is None: # Allow single arg, representing pspace == PSpace() pspace = PSpace() return Basic.__new__(cls, symbol, n, m, pspace) symbol = property(lambda self: self.args[0]) pspace = property(lambda self: self.args[3]) class ProductPSpace(PSpace): """ Abstract class for representing probability spaces with multiple random variables. See Also ======== sympy.stats.rv.IndependentProductPSpace sympy.stats.joint_rv.JointPSpace """ pass class IndependentProductPSpace(ProductPSpace): """ A probability space resulting from the merger of two independent probability spaces. Often created using the function, pspace. """ def __new__(cls, *spaces): rs_space_dict = {} for space in spaces: for value in space.values: rs_space_dict[value] = space symbols = FiniteSet(*[val.symbol for val in rs_space_dict.keys()]) # Overlapping symbols from sympy.stats.joint_rv import MarginalDistribution from sympy.stats.compound_rv import CompoundDistribution if len(symbols) < sum(len(space.symbols) for space in spaces if not isinstance(space.distribution, ( CompoundDistribution, MarginalDistribution))): raise ValueError("Overlapping Random Variables") if all(space.is_Finite for space in spaces): from sympy.stats.frv import ProductFinitePSpace cls = ProductFinitePSpace obj = Basic.__new__(cls, *FiniteSet(*spaces)) return obj @property def pdf(self): p = Mul(*[space.pdf for space in self.spaces]) return p.subs({rv: rv.symbol for rv in self.values}) @property def rs_space_dict(self): d = {} for space in self.spaces: for value in space.values: d[value] = space return d @property def symbols(self): return FiniteSet(*[val.symbol for val in self.rs_space_dict.keys()]) @property def spaces(self): return FiniteSet(*self.args) @property def values(self): return sumsets(space.values for space in self.spaces) def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs): rvs = rvs or self.values rvs = frozenset(rvs) for space in self.spaces: expr = space.compute_expectation(expr, rvs & space.values, evaluate=False, **kwargs) if evaluate and hasattr(expr, 'doit'): return expr.doit(**kwargs) return expr @property def domain(self): return ProductDomain(*[space.domain for space in self.spaces]) @property def density(self): raise NotImplementedError("Density not available for ProductSpaces") def sample(self, size=(), library='scipy', seed=None): return {k: v for space in self.spaces for k, v in space.sample(size=size, library=library, seed=seed).items()} def probability(self, condition, **kwargs): cond_inv = False if isinstance(condition, Ne): condition = Eq(condition.args[0], condition.args[1]) cond_inv = True elif isinstance(condition, And): # they are independent return Mul(*[self.probability(arg) for arg in condition.args]) elif isinstance(condition, Or): # they are independent return Add(*[self.probability(arg) for arg in condition.args]) expr = condition.lhs - condition.rhs rvs = random_symbols(expr) dens = self.compute_density(expr) if any(pspace(rv).is_Continuous for rv in rvs): from sympy.stats.crv import SingleContinuousPSpace from sympy.stats.crv_types import ContinuousDistributionHandmade if expr in self.values: # Marginalize all other random symbols out of the density randomsymbols = tuple(set(self.values) - frozenset([expr])) symbols = tuple(rs.symbol for rs in randomsymbols) pdf = self.domain.integrate(self.pdf, symbols, **kwargs) return Lambda(expr.symbol, pdf) dens = ContinuousDistributionHandmade(dens) z = Dummy('z', real=True) space = SingleContinuousPSpace(z, dens) result = space.probability(condition.__class__(space.value, 0)) else: from sympy.stats.drv import SingleDiscretePSpace from sympy.stats.drv_types import DiscreteDistributionHandmade dens = DiscreteDistributionHandmade(dens) z = Dummy('z', integer=True) space = SingleDiscretePSpace(z, dens) result = space.probability(condition.__class__(space.value, 0)) return result if not cond_inv else S.One - result def compute_density(self, expr, **kwargs): rvs = random_symbols(expr) if any(pspace(rv).is_Continuous for rv in rvs): z = Dummy('z', real=True) expr = self.compute_expectation(DiracDelta(expr - z), **kwargs) else: z = Dummy('z', integer=True) expr = self.compute_expectation(KroneckerDelta(expr, z), **kwargs) return Lambda(z, expr) def compute_cdf(self, expr, **kwargs): raise ValueError("CDF not well defined on multivariate expressions") def conditional_space(self, condition, normalize=True, **kwargs): rvs = random_symbols(condition) condition = condition.xreplace({rv: rv.symbol for rv in self.values}) pspaces = [pspace(rv) for rv in rvs] if any(ps.is_Continuous for ps in pspaces): from sympy.stats.crv import (ConditionalContinuousDomain, ContinuousPSpace) space = ContinuousPSpace domain = ConditionalContinuousDomain(self.domain, condition) elif any(ps.is_Discrete for ps in pspaces): from sympy.stats.drv import (ConditionalDiscreteDomain, DiscretePSpace) space = DiscretePSpace domain = ConditionalDiscreteDomain(self.domain, condition) elif all(ps.is_Finite for ps in pspaces): from sympy.stats.frv import FinitePSpace return FinitePSpace.conditional_space(self, condition) if normalize: replacement = {rv: Dummy(str(rv)) for rv in self.symbols} norm = domain.compute_expectation(self.pdf, **kwargs) pdf = self.pdf / norm.xreplace(replacement) # XXX: Converting symbols from set to tuple. The order matters to # Lambda though so we shouldn't be starting with a set here... density = Lambda(tuple(domain.symbols), pdf) return space(domain, density) class ProductDomain(RandomDomain): """ A domain resulting from the merger of two independent domains. See Also ======== sympy.stats.crv.ProductContinuousDomain sympy.stats.frv.ProductFiniteDomain """ is_ProductDomain = True def __new__(cls, *domains): # Flatten any product of products domains2 = [] for domain in domains: if not domain.is_ProductDomain: domains2.append(domain) else: domains2.extend(domain.domains) domains2 = FiniteSet(*domains2) if all(domain.is_Finite for domain in domains2): from sympy.stats.frv import ProductFiniteDomain cls = ProductFiniteDomain if all(domain.is_Continuous for domain in domains2): from sympy.stats.crv import ProductContinuousDomain cls = ProductContinuousDomain if all(domain.is_Discrete for domain in domains2): from sympy.stats.drv import ProductDiscreteDomain cls = ProductDiscreteDomain return Basic.__new__(cls, *domains2) @property def sym_domain_dict(self): return {symbol: domain for domain in self.domains for symbol in domain.symbols} @property def symbols(self): return FiniteSet(*[sym for domain in self.domains for sym in domain.symbols]) @property def domains(self): return self.args @property def set(self): return ProductSet(*(domain.set for domain in self.domains)) def __contains__(self, other): # Split event into each subdomain for domain in self.domains: # Collect the parts of this event which associate to this domain elem = frozenset([item for item in other if sympify(domain.symbols.contains(item[0])) is S.true]) # Test this sub-event if elem not in domain: return False # All subevents passed return True def as_boolean(self): return And(*[domain.as_boolean() for domain in self.domains]) def random_symbols(expr): """ Returns all RandomSymbols within a SymPy Expression. """ atoms = getattr(expr, 'atoms', None) if atoms is not None: comp = lambda rv: rv.symbol.name l = list(atoms(RandomSymbol)) return sorted(l, key=comp) else: return [] def pspace(expr): """ Returns the underlying Probability Space of a random expression. For internal use. Examples ======== >>> from sympy.stats import pspace, Normal >>> X = Normal('X', 0, 1) >>> pspace(2*X + 1) == X.pspace True """ expr = sympify(expr) if isinstance(expr, RandomSymbol) and expr.pspace is not None: return expr.pspace if expr.has(RandomMatrixSymbol): rm = list(expr.atoms(RandomMatrixSymbol))[0] return rm.pspace rvs = random_symbols(expr) if not rvs: raise ValueError("Expression containing Random Variable expected, not %s" % (expr)) # If only one space present if all(rv.pspace == rvs[0].pspace for rv in rvs): return rvs[0].pspace from sympy.stats.compound_rv import CompoundPSpace from sympy.stats.stochastic_process import StochasticPSpace for rv in rvs: if isinstance(rv.pspace, (CompoundPSpace, StochasticPSpace)): return rv.pspace # Otherwise make a product space return IndependentProductPSpace(*[rv.pspace for rv in rvs]) def sumsets(sets): """ Union of sets """ return frozenset().union(*sets) def rs_swap(a, b): """ Build a dictionary to swap RandomSymbols based on their underlying symbol. i.e. if ``X = ('x', pspace1)`` and ``Y = ('x', pspace2)`` then ``X`` and ``Y`` match and the key, value pair ``{X:Y}`` will appear in the result Inputs: collections a and b of random variables which share common symbols Output: dict mapping RVs in a to RVs in b """ d = {} for rsa in a: d[rsa] = [rsb for rsb in b if rsa.symbol == rsb.symbol][0] return d def given(expr, condition=None, **kwargs): r""" Conditional Random Expression. Explanation =========== From a random expression and a condition on that expression creates a new probability space from the condition and returns the same expression on that conditional probability space. Examples ======== >>> from sympy.stats import given, density, Die >>> X = Die('X', 6) >>> Y = given(X, X > 3) >>> density(Y).dict {4: 1/3, 5: 1/3, 6: 1/3} Following convention, if the condition is a random symbol then that symbol is considered fixed. >>> from sympy.stats import Normal >>> from sympy import pprint >>> from sympy.abc import z >>> X = Normal('X', 0, 1) >>> Y = Normal('Y', 0, 1) >>> pprint(density(X + Y, Y)(z), use_unicode=False) 2 -(-Y + z) ----------- ___ 2 \/ 2 *e ------------------ ____ 2*\/ pi """ if not is_random(condition) or pspace_independent(expr, condition): return expr if isinstance(condition, RandomSymbol): condition = Eq(condition, condition.symbol) condsymbols = random_symbols(condition) if (isinstance(condition, Eq) and len(condsymbols) == 1 and not isinstance(pspace(expr).domain, ConditionalDomain)): rv = tuple(condsymbols)[0] results = solveset(condition, rv) if isinstance(results, Intersection) and S.Reals in results.args: results = list(results.args[1]) sums = 0 for res in results: temp = expr.subs(rv, res) if temp == True: return True if temp != False: # XXX: This seems nonsensical but preserves existing behaviour # after the change that Relational is no longer a subclass of # Expr. Here expr is sometimes Relational and sometimes Expr # but we are trying to add them with +=. This needs to be # fixed somehow. if sums == 0 and isinstance(expr, Relational): sums = expr.subs(rv, res) else: sums += expr.subs(rv, res) if sums == 0: return False return sums # Get full probability space of both the expression and the condition fullspace = pspace(Tuple(expr, condition)) # Build new space given the condition space = fullspace.conditional_space(condition, **kwargs) # Dictionary to swap out RandomSymbols in expr with new RandomSymbols # That point to the new conditional space swapdict = rs_swap(fullspace.values, space.values) # Swap random variables in the expression expr = expr.xreplace(swapdict) return expr def expectation(expr, condition=None, numsamples=None, evaluate=True, **kwargs): """ Returns the expected value of a random expression. Parameters ========== expr : Expr containing RandomSymbols The expression of which you want to compute the expectation value given : Expr containing RandomSymbols A conditional expression. E(X, X>0) is expectation of X given X > 0 numsamples : int Enables sampling and approximates the expectation with this many samples evalf : Bool (defaults to True) If sampling return a number rather than a complex expression evaluate : Bool (defaults to True) In case of continuous systems return unevaluated integral Examples ======== >>> from sympy.stats import E, Die >>> X = Die('X', 6) >>> E(X) 7/2 >>> E(2*X + 1) 8 >>> E(X, X > 3) # Expectation of X given that it is above 3 5 """ if not is_random(expr): # expr isn't random? return expr kwargs['numsamples'] = numsamples from sympy.stats.symbolic_probability import Expectation if evaluate: return Expectation(expr, condition).doit(**kwargs) return Expectation(expr, condition) def probability(condition, given_condition=None, numsamples=None, evaluate=True, **kwargs): """ Probability that a condition is true, optionally given a second condition. Parameters ========== condition : Combination of Relationals containing RandomSymbols The condition of which you want to compute the probability given_condition : Combination of Relationals containing RandomSymbols A conditional expression. P(X > 1, X > 0) is expectation of X > 1 given X > 0 numsamples : int Enables sampling and approximates the probability with this many samples evaluate : Bool (defaults to True) In case of continuous systems return unevaluated integral Examples ======== >>> from sympy.stats import P, Die >>> from sympy import Eq >>> X, Y = Die('X', 6), Die('Y', 6) >>> P(X > 3) 1/2 >>> P(Eq(X, 5), X > 2) # Probability that X == 5 given that X > 2 1/4 >>> P(X > Y) 5/12 """ kwargs['numsamples'] = numsamples from sympy.stats.symbolic_probability import Probability if evaluate: return Probability(condition, given_condition).doit(**kwargs) ### TODO: Remove the user warnings in the future releases message = ("Since version 1.7, using `evaluate=False` returns `Probability` " "object. If you want unevaluated Integral/Sum use " "`P(condition, given_condition, evaluate=False).rewrite(Integral)`") warnings.warn(filldedent(message)) return Probability(condition, given_condition) class Density(Basic): expr = property(lambda self: self.args[0]) def __new__(cls, expr, condition = None): expr = _sympify(expr) if condition is None: obj = Basic.__new__(cls, expr) else: condition = _sympify(condition) obj = Basic.__new__(cls, expr, condition) return obj @property def condition(self): if len(self.args) > 1: return self.args[1] else: return None def doit(self, evaluate=True, **kwargs): from sympy.stats.random_matrix import RandomMatrixPSpace from sympy.stats.joint_rv import JointPSpace from sympy.stats.matrix_distributions import MatrixPSpace from sympy.stats.compound_rv import CompoundPSpace from sympy.stats.frv import SingleFiniteDistribution expr, condition = self.expr, self.condition if isinstance(expr, SingleFiniteDistribution): return expr.dict if condition is not None: # Recompute on new conditional expr expr = given(expr, condition, **kwargs) if not random_symbols(expr): return Lambda(x, DiracDelta(x - expr)) if isinstance(expr, RandomSymbol): if isinstance(expr.pspace, (SinglePSpace, JointPSpace, MatrixPSpace)) and \ hasattr(expr.pspace, 'distribution'): return expr.pspace.distribution elif isinstance(expr.pspace, RandomMatrixPSpace): return expr.pspace.model if isinstance(pspace(expr), CompoundPSpace): kwargs['compound_evaluate'] = evaluate result = pspace(expr).compute_density(expr, **kwargs) if evaluate and hasattr(result, 'doit'): return result.doit() else: return result def density(expr, condition=None, evaluate=True, numsamples=None, **kwargs): """ Probability density of a random expression, optionally given a second condition. Explanation =========== This density will take on different forms for different types of probability spaces. Discrete variables produce Dicts. Continuous variables produce Lambdas. Parameters ========== expr : Expr containing RandomSymbols The expression of which you want to compute the density value condition : Relational containing RandomSymbols A conditional expression. density(X > 1, X > 0) is density of X > 1 given X > 0 numsamples : int Enables sampling and approximates the density with this many samples Examples ======== >>> from sympy.stats import density, Die, Normal >>> from sympy import Symbol >>> x = Symbol('x') >>> D = Die('D', 6) >>> X = Normal(x, 0, 1) >>> density(D).dict {1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6} >>> density(2*D).dict {2: 1/6, 4: 1/6, 6: 1/6, 8: 1/6, 10: 1/6, 12: 1/6} >>> density(X)(x) sqrt(2)*exp(-x**2/2)/(2*sqrt(pi)) """ if numsamples: return sampling_density(expr, condition, numsamples=numsamples, **kwargs) return Density(expr, condition).doit(evaluate=evaluate, **kwargs) def cdf(expr, condition=None, evaluate=True, **kwargs): """ Cumulative Distribution Function of a random expression. optionally given a second condition. Explanation =========== This density will take on different forms for different types of probability spaces. Discrete variables produce Dicts. Continuous variables produce Lambdas. Examples ======== >>> from sympy.stats import density, Die, Normal, cdf >>> D = Die('D', 6) >>> X = Normal('X', 0, 1) >>> density(D).dict {1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6} >>> cdf(D) {1: 1/6, 2: 1/3, 3: 1/2, 4: 2/3, 5: 5/6, 6: 1} >>> cdf(3*D, D > 2) {9: 1/4, 12: 1/2, 15: 3/4, 18: 1} >>> cdf(X) Lambda(_z, erf(sqrt(2)*_z/2)/2 + 1/2) """ if condition is not None: # If there is a condition # Recompute on new conditional expr return cdf(given(expr, condition, **kwargs), **kwargs) # Otherwise pass work off to the ProbabilitySpace result = pspace(expr).compute_cdf(expr, **kwargs) if evaluate and hasattr(result, 'doit'): return result.doit() else: return result def characteristic_function(expr, condition=None, evaluate=True, **kwargs): """ Characteristic function of a random expression, optionally given a second condition. Returns a Lambda. Examples ======== >>> from sympy.stats import Normal, DiscreteUniform, Poisson, characteristic_function >>> X = Normal('X', 0, 1) >>> characteristic_function(X) Lambda(_t, exp(-_t**2/2)) >>> Y = DiscreteUniform('Y', [1, 2, 7]) >>> characteristic_function(Y) Lambda(_t, exp(7*_t*I)/3 + exp(2*_t*I)/3 + exp(_t*I)/3) >>> Z = Poisson('Z', 2) >>> characteristic_function(Z) Lambda(_t, exp(2*exp(_t*I) - 2)) """ if condition is not None: return characteristic_function(given(expr, condition, **kwargs), **kwargs) result = pspace(expr).compute_characteristic_function(expr, **kwargs) if evaluate and hasattr(result, 'doit'): return result.doit() else: return result def moment_generating_function(expr, condition=None, evaluate=True, **kwargs): if condition is not None: return moment_generating_function(given(expr, condition, **kwargs), **kwargs) result = pspace(expr).compute_moment_generating_function(expr, **kwargs) if evaluate and hasattr(result, 'doit'): return result.doit() else: return result def where(condition, given_condition=None, **kwargs): """ Returns the domain where a condition is True. Examples ======== >>> from sympy.stats import where, Die, Normal >>> from sympy import And >>> D1, D2 = Die('a', 6), Die('b', 6) >>> a, b = D1.symbol, D2.symbol >>> X = Normal('x', 0, 1) >>> where(X**2<1) Domain: (-1 < x) & (x < 1) >>> where(X**2<1).set Interval.open(-1, 1) >>> where(And(D1<=D2, D2<3)) Domain: (Eq(a, 1) & Eq(b, 1)) | (Eq(a, 1) & Eq(b, 2)) | (Eq(a, 2) & Eq(b, 2)) """ if given_condition is not None: # If there is a condition # Recompute on new conditional expr return where(given(condition, given_condition, **kwargs), **kwargs) # Otherwise pass work off to the ProbabilitySpace return pspace(condition).where(condition, **kwargs) @doctest_depends_on(modules=('scipy',)) def sample(expr, condition=None, size=(), library='scipy', numsamples=1, seed=None, **kwargs): """ A realization of the random expression. Parameters ========== expr : Expression of random variables Expression from which sample is extracted condition : Expr containing RandomSymbols A conditional expression size : int, tuple Represents size of each sample in numsamples library : str - 'scipy' : Sample using scipy - 'numpy' : Sample using numpy - 'pymc3' : Sample using PyMC3 Choose any of the available options to sample from as string, by default is 'scipy' numsamples : int Number of samples, each with size as ``size``. The ``numsamples`` parameter is deprecated and is only provided for compatibility with v1.8. Use a list comprehension or an additional dimension in ``size`` instead. seed : An object to be used as seed by the given external library for sampling `expr`. Following is the list of possible types of object for the supported libraries, - 'scipy': int, numpy.random.RandomState, numpy.random.Generator - 'numpy': int, numpy.random.RandomState, numpy.random.Generator - 'pymc3': int Optional, by default None, in which case seed settings related to the given library will be used. No modifications to environment's global seed settings are done by this argument. Returns ======= sample: float/list/numpy.ndarray one sample or a collection of samples of the random expression. - sample(X) returns float/numpy.float64/numpy.int64 object. - sample(X, size=int/tuple) returns numpy.ndarray object. Examples ======== >>> from sympy.stats import Die, sample, Normal, Geometric >>> X, Y, Z = Die('X', 6), Die('Y', 6), Die('Z', 6) # Finite Random Variable >>> die_roll = sample(X + Y + Z) >>> die_roll # doctest: +SKIP 3 >>> N = Normal('N', 3, 4) # Continuous Random Variable >>> samp = sample(N) >>> samp in N.pspace.domain.set True >>> samp = sample(N, N>0) >>> samp > 0 True >>> samp_list = sample(N, size=4) >>> [sam in N.pspace.domain.set for sam in samp_list] [True, True, True, True] >>> sample(N, size = (2,3)) # doctest: +SKIP array([[5.42519758, 6.40207856, 4.94991743], [1.85819627, 6.83403519, 1.9412172 ]]) >>> G = Geometric('G', 0.5) # Discrete Random Variable >>> samp_list = sample(G, size=3) >>> samp_list # doctest: +SKIP [1, 3, 2] >>> [sam in G.pspace.domain.set for sam in samp_list] [True, True, True] >>> MN = Normal("MN", [3, 4], [[2, 1], [1, 2]]) # Joint Random Variable >>> samp_list = sample(MN, size=4) >>> samp_list # doctest: +SKIP [array([2.85768055, 3.38954165]), array([4.11163337, 4.3176591 ]), array([0.79115232, 1.63232916]), array([4.01747268, 3.96716083])] >>> [tuple(sam) in MN.pspace.domain.set for sam in samp_list] [True, True, True, True] .. versionchanged:: 1.7.0 sample used to return an iterator containing the samples instead of value. .. versionchanged:: 1.9.0 sample returns values or array of values instead of an iterator and numsamples is deprecated. """ iterator = sample_iter(expr, condition, size=size, library=library, numsamples=numsamples, seed=seed) if numsamples != 1: SymPyDeprecationWarning( feature="numsamples parameter", issue=21723, deprecated_since_version="1.9", useinstead="a list comprehension or an additional dimension in ``size``").warn() return [next(iterator) for i in range(numsamples)] return next(iterator) def quantile(expr, evaluate=True, **kwargs): r""" Return the :math:`p^{th}` order quantile of a probability distribution. Explanation =========== Quantile is defined as the value at which the probability of the random variable is less than or equal to the given probability. ..math:: Q(p) = inf{x \in (-\infty, \infty) such that p <= F(x)} Examples ======== >>> from sympy.stats import quantile, Die, Exponential >>> from sympy import Symbol, pprint >>> p = Symbol("p") >>> l = Symbol("lambda", positive=True) >>> X = Exponential("x", l) >>> quantile(X)(p) -log(1 - p)/lambda >>> D = Die("d", 6) >>> pprint(quantile(D)(p), use_unicode=False) /nan for Or(p > 1, p < 0) | | 1 for p <= 1/6 | | 2 for p <= 1/3 | < 3 for p <= 1/2 | | 4 for p <= 2/3 | | 5 for p <= 5/6 | \ 6 for p <= 1 """ result = pspace(expr).compute_quantile(expr, **kwargs) if evaluate and hasattr(result, 'doit'): return result.doit() else: return result def sample_iter(expr, condition=None, size=(), library='scipy', numsamples=S.Infinity, seed=None, **kwargs): """ Returns an iterator of realizations from the expression given a condition. Parameters ========== expr: Expr Random expression to be realized condition: Expr, optional A conditional expression size : int, tuple Represents size of each sample in numsamples numsamples: integer, optional Length of the iterator (defaults to infinity) seed : An object to be used as seed by the given external library for sampling `expr`. Following is the list of possible types of object for the supported libraries, - 'scipy': int, numpy.random.RandomState, numpy.random.Generator - 'numpy': int, numpy.random.RandomState, numpy.random.Generator - 'pymc3': int Optional, by default None, in which case seed settings related to the given library will be used. No modifications to environment's global seed settings are done by this argument. Examples ======== >>> from sympy.stats import Normal, sample_iter >>> X = Normal('X', 0, 1) >>> expr = X*X + 3 >>> iterator = sample_iter(expr, numsamples=3) # doctest: +SKIP >>> list(iterator) # doctest: +SKIP [12, 4, 7] Returns ======= sample_iter: iterator object iterator object containing the sample/samples of given expr See Also ======== sample sampling_P sampling_E """ from sympy.stats.joint_rv import JointRandomSymbol if not import_module(library): raise ValueError("Failed to import %s" % library) if condition is not None: ps = pspace(Tuple(expr, condition)) else: ps = pspace(expr) rvs = list(ps.values) if isinstance(expr, JointRandomSymbol): expr = expr.subs({expr: RandomSymbol(expr.symbol, expr.pspace)}) else: sub = {} for arg in expr.args: if isinstance(arg, JointRandomSymbol): sub[arg] = RandomSymbol(arg.symbol, arg.pspace) expr = expr.subs(sub) def fn_subs(*args): return expr.subs({rv: arg for rv, arg in zip(rvs, args)}) def given_fn_subs(*args): if condition is not None: return condition.subs({rv: arg for rv, arg in zip(rvs, args)}) return False if library == 'pymc3': # Currently unable to lambdify in pymc3 # TODO : Remove 'pymc3' when lambdify accepts 'pymc3' as module fn = lambdify(rvs, expr, **kwargs) else: fn = lambdify(rvs, expr, modules=library, **kwargs) if condition is not None: given_fn = lambdify(rvs, condition, **kwargs) def return_generator_infinite(): count = 0 _size = (1,)+((size,) if isinstance(size, int) else size) while count < numsamples: d = ps.sample(size=_size, library=library, seed=seed) # a dictionary that maps RVs to values args = [d[rv][0] for rv in rvs] if condition is not None: # Check that these values satisfy the condition # TODO: Replace the try-except block with only given_fn(*args) # once lambdify works with unevaluated SymPy objects. try: gd = given_fn(*args) except (NameError, TypeError): gd = given_fn_subs(*args) if gd != True and gd != False: raise ValueError( "Conditions must not contain free symbols") if not gd: # If the values don't satisfy then try again continue yield fn(*args) count += 1 def return_generator_finite(): faulty = True while faulty: d = ps.sample(size=(numsamples,) + ((size,) if isinstance(size, int) else size), library=library, seed=seed) # a dictionary that maps RVs to values faulty = False count = 0 while count < numsamples and not faulty: args = [d[rv][count] for rv in rvs] if condition is not None: # Check that these values satisfy the condition # TODO: Replace the try-except block with only given_fn(*args) # once lambdify works with unevaluated SymPy objects. try: gd = given_fn(*args) except (NameError, TypeError): gd = given_fn_subs(*args) if gd != True and gd != False: raise ValueError( "Conditions must not contain free symbols") if not gd: # If the values don't satisfy then try again faulty = True count += 1 count = 0 while count < numsamples: args = [d[rv][count] for rv in rvs] # TODO: Replace the try-except block with only fn(*args) # once lambdify works with unevaluated SymPy objects. try: yield fn(*args) except (NameError, TypeError): yield fn_subs(*args) count += 1 if numsamples is S.Infinity: return return_generator_infinite() return return_generator_finite() def sample_iter_lambdify(expr, condition=None, size=(), numsamples=S.Infinity, seed=None, **kwargs): return sample_iter(expr, condition=condition, size=size, numsamples=numsamples, seed=seed, **kwargs) def sample_iter_subs(expr, condition=None, size=(), numsamples=S.Infinity, seed=None, **kwargs): return sample_iter(expr, condition=condition, size=size, numsamples=numsamples, seed=seed, **kwargs) def sampling_P(condition, given_condition=None, library='scipy', numsamples=1, evalf=True, seed=None, **kwargs): """ Sampling version of P. See Also ======== P sampling_E sampling_density """ count_true = 0 count_false = 0 samples = sample_iter(condition, given_condition, library=library, numsamples=numsamples, seed=seed, **kwargs) for sample in samples: if sample: count_true += 1 else: count_false += 1 result = S(count_true) / numsamples if evalf: return result.evalf() else: return result def sampling_E(expr, given_condition=None, library='scipy', numsamples=1, evalf=True, seed=None, **kwargs): """ Sampling version of E. See Also ======== P sampling_P sampling_density """ samples = list(sample_iter(expr, given_condition, library=library, numsamples=numsamples, seed=seed, **kwargs)) result = Add(*[samp for samp in samples]) / numsamples if evalf: return result.evalf() else: return result def sampling_density(expr, given_condition=None, library='scipy', numsamples=1, seed=None, **kwargs): """ Sampling version of density. See Also ======== density sampling_P sampling_E """ results = {} for result in sample_iter(expr, given_condition, library=library, numsamples=numsamples, seed=seed, **kwargs): results[result] = results.get(result, 0) + 1 return results def dependent(a, b): """ Dependence of two random expressions. Two expressions are independent if knowledge of one does not change computations on the other. Examples ======== >>> from sympy.stats import Normal, dependent, given >>> from sympy import Tuple, Eq >>> X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) >>> dependent(X, Y) False >>> dependent(2*X + Y, -Y) True >>> X, Y = given(Tuple(X, Y), Eq(X + Y, 3)) >>> dependent(X, Y) True See Also ======== independent """ if pspace_independent(a, b): return False z = Symbol('z', real=True) # Dependent if density is unchanged when one is given information about # the other return (density(a, Eq(b, z)) != density(a) or density(b, Eq(a, z)) != density(b)) def independent(a, b): """ Independence of two random expressions. Two expressions are independent if knowledge of one does not change computations on the other. Examples ======== >>> from sympy.stats import Normal, independent, given >>> from sympy import Tuple, Eq >>> X, Y = Normal('X', 0, 1), Normal('Y', 0, 1) >>> independent(X, Y) True >>> independent(2*X + Y, -Y) False >>> X, Y = given(Tuple(X, Y), Eq(X + Y, 3)) >>> independent(X, Y) False See Also ======== dependent """ return not dependent(a, b) def pspace_independent(a, b): """ Tests for independence between a and b by checking if their PSpaces have overlapping symbols. This is a sufficient but not necessary condition for independence and is intended to be used internally. Notes ===== pspace_independent(a, b) implies independent(a, b) independent(a, b) does not imply pspace_independent(a, b) """ a_symbols = set(pspace(b).symbols) b_symbols = set(pspace(a).symbols) if len(set(random_symbols(a)).intersection(random_symbols(b))) != 0: return False if len(a_symbols.intersection(b_symbols)) == 0: return True return None def rv_subs(expr, symbols=None): """ Given a random expression replace all random variables with their symbols. If symbols keyword is given restrict the swap to only the symbols listed. """ if symbols is None: symbols = random_symbols(expr) if not symbols: return expr swapdict = {rv: rv.symbol for rv in symbols} return expr.subs(swapdict) class NamedArgsMixin: _argnames = () # type: tTuple[str, ...] def __getattr__(self, attr): try: return self.args[self._argnames.index(attr)] except ValueError: raise AttributeError("'%s' object has no attribute '%s'" % ( type(self).__name__, attr)) class Distribution(Basic): def sample(self, size=(), library='scipy', seed=None): """ A random realization from the distribution """ module = import_module(library) if library in {'scipy', 'numpy', 'pymc3'} and module is None: raise ValueError("Failed to import %s" % library) if library == 'scipy': # scipy does not require map as it can handle using custom distributions. # However, we will still use a map where we can. # TODO: do this for drv.py and frv.py if necessary. # TODO: add more distributions here if there are more # See links below referring to sections beginning with "A common parametrization..." # I will remove all these comments if everything is ok. from sympy.stats.sampling.sample_scipy import do_sample_scipy import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed samps = do_sample_scipy(self, size, rand_state) elif library == 'numpy': from sympy.stats.sampling.sample_numpy import do_sample_numpy import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed _size = None if size == () else size samps = do_sample_numpy(self, _size, rand_state) elif library == 'pymc3': from sympy.stats.sampling.sample_pymc3 import do_sample_pymc3 import logging logging.getLogger("pymc3").setLevel(logging.ERROR) import pymc3 with pymc3.Model(): if do_sample_pymc3(self): samps = pymc3.sample(draws=prod(size), chains=1, compute_convergence_checks=False, progressbar=False, random_seed=seed, return_inferencedata=False)[:]['X'] samps = samps.reshape(size) else: samps = None else: raise NotImplementedError("Sampling from %s is not supported yet." % str(library)) if samps is not None: return samps raise NotImplementedError( "Sampling for %s is not currently implemented from %s" % (self, library)) def _value_check(condition, message): """ Raise a ValueError with message if condition is False, else return True if all conditions were True, else False. Examples ======== >>> from sympy.stats.rv import _value_check >>> from sympy.abc import a, b, c >>> from sympy import And, Dummy >>> _value_check(2 < 3, '') True Here, the condition is not False, but it doesn't evaluate to True so False is returned (but no error is raised). So checking if the return value is True or False will tell you if all conditions were evaluated. >>> _value_check(a < b, '') False In this case the condition is False so an error is raised: >>> r = Dummy(real=True) >>> _value_check(r < r - 1, 'condition is not true') Traceback (most recent call last): ... ValueError: condition is not true If no condition of many conditions must be False, they can be checked by passing them as an iterable: >>> _value_check((a < 0, b < 0, c < 0), '') False The iterable can be a generator, too: >>> _value_check((i < 0 for i in (a, b, c)), '') False The following are equivalent to the above but do not pass an iterable: >>> all(_value_check(i < 0, '') for i in (a, b, c)) False >>> _value_check(And(a < 0, b < 0, c < 0), '') False """ if not iterable(condition): condition = [condition] truth = fuzzy_and(condition) if truth == False: raise ValueError(message) return truth == True def _symbol_converter(sym): """ Casts the parameter to Symbol if it is 'str' otherwise no operation is performed on it. Parameters ========== sym The parameter to be converted. Returns ======= Symbol the parameter converted to Symbol. Raises ====== TypeError If the parameter is not an instance of both str and Symbol. Examples ======== >>> from sympy import Symbol >>> from sympy.stats.rv import _symbol_converter >>> s = _symbol_converter('s') >>> isinstance(s, Symbol) True >>> _symbol_converter(1) Traceback (most recent call last): ... TypeError: 1 is neither a Symbol nor a string >>> r = Symbol('r') >>> isinstance(r, Symbol) True """ if isinstance(sym, str): sym = Symbol(sym) if not isinstance(sym, Symbol): raise TypeError("%s is neither a Symbol nor a string"%(sym)) return sym def sample_stochastic_process(process): """ This function is used to sample from stochastic process. Parameters ========== process: StochasticProcess Process used to extract the samples. It must be an instance of StochasticProcess Examples ======== >>> from sympy.stats import sample_stochastic_process, DiscreteMarkovChain >>> from sympy import Matrix >>> T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]]) >>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T) >>> next(sample_stochastic_process(Y)) in Y.state_space # doctest: +SKIP True >>> next(sample_stochastic_process(Y)) # doctest: +SKIP 0 >>> next(sample_stochastic_process(Y)) # doctest: +SKIP 2 Returns ======= sample: iterator object iterator object containing the sample of given process """ from sympy.stats.stochastic_process_types import StochasticProcess if not isinstance(process, StochasticProcess): raise ValueError("Process must be an instance of Stochastic Process") return process.sample()
b2ff97f45fe5b52895416a025771667c762c1b104993bf6e09d5d4db6dedebe4
""" Joint Random Variables Module See Also ======== sympy.stats.rv sympy.stats.frv sympy.stats.crv sympy.stats.drv """ from sympy.core.basic import Basic from sympy.core.function import Lambda from sympy.core.mul import prod from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol) from sympy.core.sympify import sympify from sympy.sets.sets import ProductSet from sympy.tensor.indexed import Indexed from sympy.concrete.products import Product from sympy.concrete.summations import Sum, summation from sympy.core.containers import Tuple from sympy.integrals.integrals import Integral, integrate from sympy.matrices import ImmutableMatrix, matrix2numpy, list2numpy from sympy.stats.crv import SingleContinuousDistribution, SingleContinuousPSpace from sympy.stats.drv import SingleDiscreteDistribution, SingleDiscretePSpace from sympy.stats.rv import (ProductPSpace, NamedArgsMixin, Distribution, ProductDomain, RandomSymbol, random_symbols, SingleDomain, _symbol_converter) from sympy.utilities.iterables import iterable from sympy.utilities.misc import filldedent from sympy.external import import_module # __all__ = ['marginal_distribution'] class JointPSpace(ProductPSpace): """ Represents a joint probability space. Represented using symbols for each component and a distribution. """ def __new__(cls, sym, dist): if isinstance(dist, SingleContinuousDistribution): return SingleContinuousPSpace(sym, dist) if isinstance(dist, SingleDiscreteDistribution): return SingleDiscretePSpace(sym, dist) sym = _symbol_converter(sym) return Basic.__new__(cls, sym, dist) @property def set(self): return self.domain.set @property def symbol(self): return self.args[0] @property def distribution(self): return self.args[1] @property def value(self): return JointRandomSymbol(self.symbol, self) @property def component_count(self): _set = self.distribution.set if isinstance(_set, ProductSet): return S(len(_set.args)) elif isinstance(_set, Product): return _set.limits[0][-1] return S.One @property def pdf(self): sym = [Indexed(self.symbol, i) for i in range(self.component_count)] return self.distribution(*sym) @property def domain(self): rvs = random_symbols(self.distribution) if not rvs: return SingleDomain(self.symbol, self.distribution.set) return ProductDomain(*[rv.pspace.domain for rv in rvs]) def component_domain(self, index): return self.set.args[index] def marginal_distribution(self, *indices): count = self.component_count if count.atoms(Symbol): raise ValueError("Marginal distributions cannot be computed " "for symbolic dimensions. It is a work under progress.") orig = [Indexed(self.symbol, i) for i in range(count)] all_syms = [Symbol(str(i)) for i in orig] replace_dict = dict(zip(all_syms, orig)) sym = tuple(Symbol(str(Indexed(self.symbol, i))) for i in indices) limits = list([i,] for i in all_syms if i not in sym) index = 0 for i in range(count): if i not in indices: limits[index].append(self.distribution.set.args[i]) limits[index] = tuple(limits[index]) index += 1 if self.distribution.is_Continuous: f = Lambda(sym, integrate(self.distribution(*all_syms), *limits)) elif self.distribution.is_Discrete: f = Lambda(sym, summation(self.distribution(*all_syms), *limits)) return f.xreplace(replace_dict) def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs): syms = tuple(self.value[i] for i in range(self.component_count)) rvs = rvs or syms if not any(i in rvs for i in syms): return expr expr = expr*self.pdf for rv in rvs: if isinstance(rv, Indexed): expr = expr.xreplace({rv: Indexed(str(rv.base), rv.args[1])}) elif isinstance(rv, RandomSymbol): expr = expr.xreplace({rv: rv.symbol}) if self.value in random_symbols(expr): raise NotImplementedError(filldedent(''' Expectations of expression with unindexed joint random symbols cannot be calculated yet.''')) limits = tuple((Indexed(str(rv.base),rv.args[1]), self.distribution.set.args[rv.args[1]]) for rv in syms) return Integral(expr, *limits) def where(self, condition): raise NotImplementedError() def compute_density(self, expr): raise NotImplementedError() def sample(self, size=(), library='scipy', seed=None): """ Internal sample method Returns dictionary mapping RandomSymbol to realization value. """ return {RandomSymbol(self.symbol, self): self.distribution.sample(size, library=library, seed=seed)} def probability(self, condition): raise NotImplementedError() class SampleJointScipy: """Returns the sample from scipy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_scipy(dist, size, seed) @classmethod def _sample_scipy(cls, dist, size, seed): """Sample from SciPy.""" import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed from scipy import stats as scipy_stats scipy_rv_map = { 'MultivariateNormalDistribution': lambda dist, size: scipy_stats.multivariate_normal.rvs( mean=matrix2numpy(dist.mu).flatten(), cov=matrix2numpy(dist.sigma), size=size, random_state=rand_state), 'MultivariateBetaDistribution': lambda dist, size: scipy_stats.dirichlet.rvs( alpha=list2numpy(dist.alpha, float).flatten(), size=size, random_state=rand_state), 'MultinomialDistribution': lambda dist, size: scipy_stats.multinomial.rvs( n=int(dist.n), p=list2numpy(dist.p, float).flatten(), size=size, random_state=rand_state) } sample_shape = { 'MultivariateNormalDistribution': lambda dist: matrix2numpy(dist.mu).flatten().shape, 'MultivariateBetaDistribution': lambda dist: list2numpy(dist.alpha).flatten().shape, 'MultinomialDistribution': lambda dist: list2numpy(dist.p).flatten().shape } dist_list = scipy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None samples = scipy_rv_map[dist.__class__.__name__](dist, size) return samples.reshape(size + sample_shape[dist.__class__.__name__](dist)) class SampleJointNumpy: """Returns the sample from numpy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_numpy(dist, size, seed) @classmethod def _sample_numpy(cls, dist, size, seed): """Sample from NumPy.""" import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed numpy_rv_map = { 'MultivariateNormalDistribution': lambda dist, size: rand_state.multivariate_normal( mean=matrix2numpy(dist.mu, float).flatten(), cov=matrix2numpy(dist.sigma, float), size=size), 'MultivariateBetaDistribution': lambda dist, size: rand_state.dirichlet( alpha=list2numpy(dist.alpha, float).flatten(), size=size), 'MultinomialDistribution': lambda dist, size: rand_state.multinomial( n=int(dist.n), pvals=list2numpy(dist.p, float).flatten(), size=size) } sample_shape = { 'MultivariateNormalDistribution': lambda dist: matrix2numpy(dist.mu).flatten().shape, 'MultivariateBetaDistribution': lambda dist: list2numpy(dist.alpha).flatten().shape, 'MultinomialDistribution': lambda dist: list2numpy(dist.p).flatten().shape } dist_list = numpy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None samples = numpy_rv_map[dist.__class__.__name__](dist, prod(size)) return samples.reshape(size + sample_shape[dist.__class__.__name__](dist)) class SampleJointPymc: """Returns the sample from pymc3 of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_pymc3(dist, size, seed) @classmethod def _sample_pymc3(cls, dist, size, seed): """Sample from PyMC3.""" import pymc3 pymc3_rv_map = { 'MultivariateNormalDistribution': lambda dist: pymc3.MvNormal('X', mu=matrix2numpy(dist.mu, float).flatten(), cov=matrix2numpy(dist.sigma, float), shape=(1, dist.mu.shape[0])), 'MultivariateBetaDistribution': lambda dist: pymc3.Dirichlet('X', a=list2numpy(dist.alpha, float).flatten()), 'MultinomialDistribution': lambda dist: pymc3.Multinomial('X', n=int(dist.n), p=list2numpy(dist.p, float).flatten(), shape=(1, len(dist.p))) } sample_shape = { 'MultivariateNormalDistribution': lambda dist: matrix2numpy(dist.mu).flatten().shape, 'MultivariateBetaDistribution': lambda dist: list2numpy(dist.alpha).flatten().shape, 'MultinomialDistribution': lambda dist: list2numpy(dist.p).flatten().shape } dist_list = pymc3_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None import logging logging.getLogger("pymc3").setLevel(logging.ERROR) with pymc3.Model(): pymc3_rv_map[dist.__class__.__name__](dist) samples = pymc3.sample(draws=prod(size), chains=1, progressbar=False, random_seed=seed, return_inferencedata=False, compute_convergence_checks=False)[:]['X'] return samples.reshape(size + sample_shape[dist.__class__.__name__](dist)) _get_sample_class_jrv = { 'scipy': SampleJointScipy, 'pymc3': SampleJointPymc, 'numpy': SampleJointNumpy } class JointDistribution(Distribution, NamedArgsMixin): """ Represented by the random variables part of the joint distribution. Contains methods for PDF, CDF, sampling, marginal densities, etc. """ _argnames = ('pdf', ) def __new__(cls, *args): args = list(map(sympify, args)) for i in range(len(args)): if isinstance(args[i], list): args[i] = ImmutableMatrix(args[i]) return Basic.__new__(cls, *args) @property def domain(self): return ProductDomain(self.symbols) @property def pdf(self): return self.density.args[1] def cdf(self, other): if not isinstance(other, dict): raise ValueError("%s should be of type dict, got %s"%(other, type(other))) rvs = other.keys() _set = self.domain.set.sets expr = self.pdf(tuple(i.args[0] for i in self.symbols)) for i in range(len(other)): if rvs[i].is_Continuous: density = Integral(expr, (rvs[i], _set[i].inf, other[rvs[i]])) elif rvs[i].is_Discrete: density = Sum(expr, (rvs[i], _set[i].inf, other[rvs[i]])) return density def sample(self, size=(), library='scipy', seed=None): """ A random realization from the distribution """ libraries = ['scipy', 'numpy', 'pymc3'] if library not in libraries: raise NotImplementedError("Sampling from %s is not supported yet." % str(library)) if not import_module(library): raise ValueError("Failed to import %s" % library) samps = _get_sample_class_jrv[library](self, size, seed=seed) if samps is not None: return samps raise NotImplementedError( "Sampling for %s is not currently implemented from %s" % (self.__class__.__name__, library) ) def __call__(self, *args): return self.pdf(*args) class JointRandomSymbol(RandomSymbol): """ Representation of random symbols with joint probability distributions to allow indexing." """ def __getitem__(self, key): if isinstance(self.pspace, JointPSpace): if (self.pspace.component_count <= key) == True: raise ValueError("Index keys for %s can only up to %s." % (self.name, self.pspace.component_count - 1)) return Indexed(self, key) class MarginalDistribution(Distribution): """ Represents the marginal distribution of a joint probability space. Initialised using a probability distribution and random variables(or their indexed components) which should be a part of the resultant distribution. """ def __new__(cls, dist, *rvs): if len(rvs) == 1 and iterable(rvs[0]): rvs = tuple(rvs[0]) if not all(isinstance(rv, (Indexed, RandomSymbol)) for rv in rvs): raise ValueError(filldedent('''Marginal distribution can be intitialised only in terms of random variables or indexed random variables''')) rvs = Tuple.fromiter(rv for rv in rvs) if not isinstance(dist, JointDistribution) and len(random_symbols(dist)) == 0: return dist return Basic.__new__(cls, dist, rvs) def check(self): pass @property def set(self): rvs = [i for i in self.args[1] if isinstance(i, RandomSymbol)] return ProductSet(*[rv.pspace.set for rv in rvs]) @property def symbols(self): rvs = self.args[1] return {rv.pspace.symbol for rv in rvs} def pdf(self, *x): expr, rvs = self.args[0], self.args[1] marginalise_out = [i for i in random_symbols(expr) if i not in rvs] if isinstance(expr, JointDistribution): count = len(expr.domain.args) x = Dummy('x', real=True) syms = tuple(Indexed(x, i) for i in count) expr = expr.pdf(syms) else: syms = tuple(rv.pspace.symbol if isinstance(rv, RandomSymbol) else rv.args[0] for rv in rvs) return Lambda(syms, self.compute_pdf(expr, marginalise_out))(*x) def compute_pdf(self, expr, rvs): for rv in rvs: lpdf = 1 if isinstance(rv, RandomSymbol): lpdf = rv.pspace.pdf expr = self.marginalise_out(expr*lpdf, rv) return expr def marginalise_out(self, expr, rv): from sympy.concrete.summations import Sum if isinstance(rv, RandomSymbol): dom = rv.pspace.set elif isinstance(rv, Indexed): dom = rv.base.component_domain( rv.pspace.component_domain(rv.args[1])) expr = expr.xreplace({rv: rv.pspace.symbol}) if rv.pspace.is_Continuous: #TODO: Modify to support integration #for all kinds of sets. expr = Integral(expr, (rv.pspace.symbol, dom)) elif rv.pspace.is_Discrete: #incorporate this into `Sum`/`summation` if dom in (S.Integers, S.Naturals, S.Naturals0): dom = (dom.inf, dom.sup) expr = Sum(expr, (rv.pspace.symbol, dom)) return expr def __call__(self, *args): return self.pdf(*args)
cbb7808f73e55b847118c4c9e8d96fd8ff1c9df23d2628f58c776afb3a65bad3
import itertools from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.expr import Expr from sympy.core.function import expand as _expand from sympy.core.mul import Mul from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.integrals.integrals import Integral from sympy.logic.boolalg import Not from sympy.core.parameters import global_parameters from sympy.core.sorting import default_sort_key from sympy.core.sympify import _sympify from sympy.core.relational import Relational from sympy.logic.boolalg import Boolean from sympy.stats import variance, covariance from sympy.stats.rv import (RandomSymbol, pspace, dependent, given, sampling_E, RandomIndexedSymbol, is_random, PSpace, sampling_P, random_symbols) __all__ = ['Probability', 'Expectation', 'Variance', 'Covariance'] @is_random.register(Expr) def _(x): atoms = x.free_symbols if len(atoms) == 1 and next(iter(atoms)) == x: return False return any(is_random(i) for i in atoms) @is_random.register(RandomSymbol) # type: ignore def _(x): return True class Probability(Expr): """ Symbolic expression for the probability. Examples ======== >>> from sympy.stats import Probability, Normal >>> from sympy import Integral >>> X = Normal("X", 0, 1) >>> prob = Probability(X > 1) >>> prob Probability(X > 1) Integral representation: >>> prob.rewrite(Integral) Integral(sqrt(2)*exp(-_z**2/2)/(2*sqrt(pi)), (_z, 1, oo)) Evaluation of the integral: >>> prob.evaluate_integral() sqrt(2)*(-sqrt(2)*sqrt(pi)*erf(sqrt(2)/2) + sqrt(2)*sqrt(pi))/(4*sqrt(pi)) """ def __new__(cls, prob, condition=None, **kwargs): prob = _sympify(prob) if condition is None: obj = Expr.__new__(cls, prob) else: condition = _sympify(condition) obj = Expr.__new__(cls, prob, condition) obj._condition = condition return obj def doit(self, **hints): condition = self.args[0] given_condition = self._condition numsamples = hints.get('numsamples', False) for_rewrite = not hints.get('for_rewrite', False) if isinstance(condition, Not): return S.One - self.func(condition.args[0], given_condition, evaluate=for_rewrite).doit(**hints) if condition.has(RandomIndexedSymbol): return pspace(condition).probability(condition, given_condition, evaluate=for_rewrite) if isinstance(given_condition, RandomSymbol): condrv = random_symbols(condition) if len(condrv) == 1 and condrv[0] == given_condition: from sympy.stats.frv_types import BernoulliDistribution return BernoulliDistribution(self.func(condition).doit(**hints), 0, 1) if any(dependent(rv, given_condition) for rv in condrv): return Probability(condition, given_condition) else: return Probability(condition).doit() if given_condition is not None and \ not isinstance(given_condition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (given_condition)) if given_condition == False or condition is S.false: return S.Zero if not isinstance(condition, (Relational, Boolean)): raise ValueError("%s is not a relational or combination of relationals" % (condition)) if condition is S.true: return S.One if numsamples: return sampling_P(condition, given_condition, numsamples=numsamples) if given_condition is not None: # If there is a condition # Recompute on new conditional expr return Probability(given(condition, given_condition)).doit() # Otherwise pass work off to the ProbabilitySpace if pspace(condition) == PSpace(): return Probability(condition, given_condition) result = pspace(condition).probability(condition) if hasattr(result, 'doit') and for_rewrite: return result.doit() else: return result def _eval_rewrite_as_Integral(self, arg, condition=None, **kwargs): return self.func(arg, condition=condition).doit(for_rewrite=True) _eval_rewrite_as_Sum = _eval_rewrite_as_Integral def evaluate_integral(self): return self.rewrite(Integral).doit() class Expectation(Expr): """ Symbolic expression for the expectation. Examples ======== >>> from sympy.stats import Expectation, Normal, Probability, Poisson >>> from sympy import symbols, Integral, Sum >>> mu = symbols("mu") >>> sigma = symbols("sigma", positive=True) >>> X = Normal("X", mu, sigma) >>> Expectation(X) Expectation(X) >>> Expectation(X).evaluate_integral().simplify() mu To get the integral expression of the expectation: >>> Expectation(X).rewrite(Integral) Integral(sqrt(2)*X*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)) The same integral expression, in more abstract terms: >>> Expectation(X).rewrite(Probability) Integral(x*Probability(Eq(X, x)), (x, -oo, oo)) To get the Summation expression of the expectation for discrete random variables: >>> lamda = symbols('lamda', positive=True) >>> Z = Poisson('Z', lamda) >>> Expectation(Z).rewrite(Sum) Sum(Z*lamda**Z*exp(-lamda)/factorial(Z), (Z, 0, oo)) This class is aware of some properties of the expectation: >>> from sympy.abc import a >>> Expectation(a*X) Expectation(a*X) >>> Y = Normal("Y", 1, 2) >>> Expectation(X + Y) Expectation(X + Y) To expand the ``Expectation`` into its expression, use ``expand()``: >>> Expectation(X + Y).expand() Expectation(X) + Expectation(Y) >>> Expectation(a*X + Y).expand() a*Expectation(X) + Expectation(Y) >>> Expectation(a*X + Y) Expectation(a*X + Y) >>> Expectation((X + Y)*(X - Y)).expand() Expectation(X**2) - Expectation(Y**2) To evaluate the ``Expectation``, use ``doit()``: >>> Expectation(X + Y).doit() mu + 1 >>> Expectation(X + Expectation(Y + Expectation(2*X))).doit() 3*mu + 1 To prevent evaluating nested ``Expectation``, use ``doit(deep=False)`` >>> Expectation(X + Expectation(Y)).doit(deep=False) mu + Expectation(Expectation(Y)) >>> Expectation(X + Expectation(Y + Expectation(2*X))).doit(deep=False) mu + Expectation(Expectation(Y + Expectation(2*X))) """ def __new__(cls, expr, condition=None, **kwargs): expr = _sympify(expr) if expr.is_Matrix: from sympy.stats.symbolic_multivariate_probability import ExpectationMatrix return ExpectationMatrix(expr, condition) if condition is None: if not is_random(expr): return expr obj = Expr.__new__(cls, expr) else: condition = _sympify(condition) obj = Expr.__new__(cls, expr, condition) obj._condition = condition return obj def expand(self, **hints): expr = self.args[0] condition = self._condition if not is_random(expr): return expr if isinstance(expr, Add): return Add.fromiter(Expectation(a, condition=condition).expand() for a in expr.args) expand_expr = _expand(expr) if isinstance(expand_expr, Add): return Add.fromiter(Expectation(a, condition=condition).expand() for a in expand_expr.args) elif isinstance(expr, Mul): rv = [] nonrv = [] for a in expr.args: if is_random(a): rv.append(a) else: nonrv.append(a) return Mul.fromiter(nonrv)*Expectation(Mul.fromiter(rv), condition=condition) return self def doit(self, **hints): deep = hints.get('deep', True) condition = self._condition expr = self.args[0] numsamples = hints.get('numsamples', False) for_rewrite = not hints.get('for_rewrite', False) if deep: expr = expr.doit(**hints) if not is_random(expr) or isinstance(expr, Expectation): # expr isn't random? return expr if numsamples: # Computing by monte carlo sampling? evalf = hints.get('evalf', True) return sampling_E(expr, condition, numsamples=numsamples, evalf=evalf) if expr.has(RandomIndexedSymbol): return pspace(expr).compute_expectation(expr, condition) # Create new expr and recompute E if condition is not None: # If there is a condition return self.func(given(expr, condition)).doit(**hints) # A few known statements for efficiency if expr.is_Add: # We know that E is Linear return Add(*[self.func(arg, condition).doit(**hints) if not isinstance(arg, Expectation) else self.func(arg, condition) for arg in expr.args]) if expr.is_Mul: if expr.atoms(Expectation): return expr if pspace(expr) == PSpace(): return self.func(expr) # Otherwise case is simple, pass work off to the ProbabilitySpace result = pspace(expr).compute_expectation(expr, evaluate=for_rewrite) if hasattr(result, 'doit') and for_rewrite: return result.doit(**hints) else: return result def _eval_rewrite_as_Probability(self, arg, condition=None, **kwargs): rvs = arg.atoms(RandomSymbol) if len(rvs) > 1: raise NotImplementedError() if len(rvs) == 0: return arg rv = rvs.pop() if rv.pspace is None: raise ValueError("Probability space not known") symbol = rv.symbol if symbol.name[0].isupper(): symbol = Symbol(symbol.name.lower()) else : symbol = Symbol(symbol.name + "_1") if rv.pspace.is_Continuous: return Integral(arg.replace(rv, symbol)*Probability(Eq(rv, symbol), condition), (symbol, rv.pspace.domain.set.inf, rv.pspace.domain.set.sup)) else: if rv.pspace.is_Finite: raise NotImplementedError else: return Sum(arg.replace(rv, symbol)*Probability(Eq(rv, symbol), condition), (symbol, rv.pspace.domain.set.inf, rv.pspace.set.sup)) def _eval_rewrite_as_Integral(self, arg, condition=None, **kwargs): return self.func(arg, condition=condition).doit(deep=False, for_rewrite=True) _eval_rewrite_as_Sum = _eval_rewrite_as_Integral # For discrete this will be Sum def evaluate_integral(self): return self.rewrite(Integral).doit() evaluate_sum = evaluate_integral class Variance(Expr): """ Symbolic expression for the variance. Examples ======== >>> from sympy import symbols, Integral >>> from sympy.stats import Normal, Expectation, Variance, Probability >>> mu = symbols("mu", positive=True) >>> sigma = symbols("sigma", positive=True) >>> X = Normal("X", mu, sigma) >>> Variance(X) Variance(X) >>> Variance(X).evaluate_integral() sigma**2 Integral representation of the underlying calculations: >>> Variance(X).rewrite(Integral) Integral(sqrt(2)*(X - Integral(sqrt(2)*X*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)))**2*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)) Integral representation, without expanding the PDF: >>> Variance(X).rewrite(Probability) -Integral(x*Probability(Eq(X, x)), (x, -oo, oo))**2 + Integral(x**2*Probability(Eq(X, x)), (x, -oo, oo)) Rewrite the variance in terms of the expectation >>> Variance(X).rewrite(Expectation) -Expectation(X)**2 + Expectation(X**2) Some transformations based on the properties of the variance may happen: >>> from sympy.abc import a >>> Y = Normal("Y", 0, 1) >>> Variance(a*X) Variance(a*X) To expand the variance in its expression, use ``expand()``: >>> Variance(a*X).expand() a**2*Variance(X) >>> Variance(X + Y) Variance(X + Y) >>> Variance(X + Y).expand() 2*Covariance(X, Y) + Variance(X) + Variance(Y) """ def __new__(cls, arg, condition=None, **kwargs): arg = _sympify(arg) if arg.is_Matrix: from sympy.stats.symbolic_multivariate_probability import VarianceMatrix return VarianceMatrix(arg, condition) if condition is None: obj = Expr.__new__(cls, arg) else: condition = _sympify(condition) obj = Expr.__new__(cls, arg, condition) obj._condition = condition return obj def expand(self, **hints): arg = self.args[0] condition = self._condition if not is_random(arg): return S.Zero if isinstance(arg, RandomSymbol): return self elif isinstance(arg, Add): rv = [] for a in arg.args: if is_random(a): rv.append(a) variances = Add(*map(lambda xv: Variance(xv, condition).expand(), rv)) map_to_covar = lambda x: 2*Covariance(*x, condition=condition).expand() covariances = Add(*map(map_to_covar, itertools.combinations(rv, 2))) return variances + covariances elif isinstance(arg, Mul): nonrv = [] rv = [] for a in arg.args: if is_random(a): rv.append(a) else: nonrv.append(a**2) if len(rv) == 0: return S.Zero return Mul.fromiter(nonrv)*Variance(Mul.fromiter(rv), condition) # this expression contains a RandomSymbol somehow: return self def _eval_rewrite_as_Expectation(self, arg, condition=None, **kwargs): e1 = Expectation(arg**2, condition) e2 = Expectation(arg, condition)**2 return e1 - e2 def _eval_rewrite_as_Probability(self, arg, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Probability) def _eval_rewrite_as_Integral(self, arg, condition=None, **kwargs): return variance(self.args[0], self._condition, evaluate=False) _eval_rewrite_as_Sum = _eval_rewrite_as_Integral def evaluate_integral(self): return self.rewrite(Integral).doit() class Covariance(Expr): """ Symbolic expression for the covariance. Examples ======== >>> from sympy.stats import Covariance >>> from sympy.stats import Normal >>> X = Normal("X", 3, 2) >>> Y = Normal("Y", 0, 1) >>> Z = Normal("Z", 0, 1) >>> W = Normal("W", 0, 1) >>> cexpr = Covariance(X, Y) >>> cexpr Covariance(X, Y) Evaluate the covariance, `X` and `Y` are independent, therefore zero is the result: >>> cexpr.evaluate_integral() 0 Rewrite the covariance expression in terms of expectations: >>> from sympy.stats import Expectation >>> cexpr.rewrite(Expectation) Expectation(X*Y) - Expectation(X)*Expectation(Y) In order to expand the argument, use ``expand()``: >>> from sympy.abc import a, b, c, d >>> Covariance(a*X + b*Y, c*Z + d*W) Covariance(a*X + b*Y, c*Z + d*W) >>> Covariance(a*X + b*Y, c*Z + d*W).expand() a*c*Covariance(X, Z) + a*d*Covariance(W, X) + b*c*Covariance(Y, Z) + b*d*Covariance(W, Y) This class is aware of some properties of the covariance: >>> Covariance(X, X).expand() Variance(X) >>> Covariance(a*X, b*Y).expand() a*b*Covariance(X, Y) """ def __new__(cls, arg1, arg2, condition=None, **kwargs): arg1 = _sympify(arg1) arg2 = _sympify(arg2) if arg1.is_Matrix or arg2.is_Matrix: from sympy.stats.symbolic_multivariate_probability import CrossCovarianceMatrix return CrossCovarianceMatrix(arg1, arg2, condition) if kwargs.pop('evaluate', global_parameters.evaluate): arg1, arg2 = sorted([arg1, arg2], key=default_sort_key) if condition is None: obj = Expr.__new__(cls, arg1, arg2) else: condition = _sympify(condition) obj = Expr.__new__(cls, arg1, arg2, condition) obj._condition = condition return obj def expand(self, **hints): arg1 = self.args[0] arg2 = self.args[1] condition = self._condition if arg1 == arg2: return Variance(arg1, condition).expand() if not is_random(arg1): return S.Zero if not is_random(arg2): return S.Zero arg1, arg2 = sorted([arg1, arg2], key=default_sort_key) if isinstance(arg1, RandomSymbol) and isinstance(arg2, RandomSymbol): return Covariance(arg1, arg2, condition) coeff_rv_list1 = self._expand_single_argument(arg1.expand()) coeff_rv_list2 = self._expand_single_argument(arg2.expand()) addends = [a*b*Covariance(*sorted([r1, r2], key=default_sort_key), condition=condition) for (a, r1) in coeff_rv_list1 for (b, r2) in coeff_rv_list2] return Add.fromiter(addends) @classmethod def _expand_single_argument(cls, expr): # return (coefficient, random_symbol) pairs: if isinstance(expr, RandomSymbol): return [(S.One, expr)] elif isinstance(expr, Add): outval = [] for a in expr.args: if isinstance(a, Mul): outval.append(cls._get_mul_nonrv_rv_tuple(a)) elif is_random(a): outval.append((S.One, a)) return outval elif isinstance(expr, Mul): return [cls._get_mul_nonrv_rv_tuple(expr)] elif is_random(expr): return [(S.One, expr)] @classmethod def _get_mul_nonrv_rv_tuple(cls, m): rv = [] nonrv = [] for a in m.args: if is_random(a): rv.append(a) else: nonrv.append(a) return (Mul.fromiter(nonrv), Mul.fromiter(rv)) def _eval_rewrite_as_Expectation(self, arg1, arg2, condition=None, **kwargs): e1 = Expectation(arg1*arg2, condition) e2 = Expectation(arg1, condition)*Expectation(arg2, condition) return e1 - e2 def _eval_rewrite_as_Probability(self, arg1, arg2, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Probability) def _eval_rewrite_as_Integral(self, arg1, arg2, condition=None, **kwargs): return covariance(self.args[0], self.args[1], self._condition, evaluate=False) _eval_rewrite_as_Sum = _eval_rewrite_as_Integral def evaluate_integral(self): return self.rewrite(Integral).doit() class Moment(Expr): """ Symbolic class for Moment Examples ======== >>> from sympy import Symbol, Integral >>> from sympy.stats import Normal, Expectation, Probability, Moment >>> mu = Symbol('mu', real=True) >>> sigma = Symbol('sigma', positive=True) >>> X = Normal('X', mu, sigma) >>> M = Moment(X, 3, 1) To evaluate the result of Moment use `doit`: >>> M.doit() mu**3 - 3*mu**2 + 3*mu*sigma**2 + 3*mu - 3*sigma**2 - 1 Rewrite the Moment expression in terms of Expectation: >>> M.rewrite(Expectation) Expectation((X - 1)**3) Rewrite the Moment expression in terms of Probability: >>> M.rewrite(Probability) Integral((x - 1)**3*Probability(Eq(X, x)), (x, -oo, oo)) Rewrite the Moment expression in terms of Integral: >>> M.rewrite(Integral) Integral(sqrt(2)*(X - 1)**3*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)) """ def __new__(cls, X, n, c=0, condition=None, **kwargs): X = _sympify(X) n = _sympify(n) c = _sympify(c) if condition is not None: condition = _sympify(condition) return super().__new__(cls, X, n, c, condition) else: return super().__new__(cls, X, n, c) def doit(self, **hints): return self.rewrite(Expectation).doit(**hints) def _eval_rewrite_as_Expectation(self, X, n, c=0, condition=None, **kwargs): return Expectation((X - c)**n, condition) def _eval_rewrite_as_Probability(self, X, n, c=0, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Probability) def _eval_rewrite_as_Integral(self, X, n, c=0, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Integral) class CentralMoment(Expr): """ Symbolic class Central Moment Examples ======== >>> from sympy import Symbol, Integral >>> from sympy.stats import Normal, Expectation, Probability, CentralMoment >>> mu = Symbol('mu', real=True) >>> sigma = Symbol('sigma', positive=True) >>> X = Normal('X', mu, sigma) >>> CM = CentralMoment(X, 4) To evaluate the result of CentralMoment use `doit`: >>> CM.doit().simplify() 3*sigma**4 Rewrite the CentralMoment expression in terms of Expectation: >>> CM.rewrite(Expectation) Expectation((X - Expectation(X))**4) Rewrite the CentralMoment expression in terms of Probability: >>> CM.rewrite(Probability) Integral((x - Integral(x*Probability(True), (x, -oo, oo)))**4*Probability(Eq(X, x)), (x, -oo, oo)) Rewrite the CentralMoment expression in terms of Integral: >>> CM.rewrite(Integral) Integral(sqrt(2)*(X - Integral(sqrt(2)*X*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)))**4*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)) """ def __new__(cls, X, n, condition=None, **kwargs): X = _sympify(X) n = _sympify(n) if condition is not None: condition = _sympify(condition) return super().__new__(cls, X, n, condition) else: return super().__new__(cls, X, n) def doit(self, **hints): return self.rewrite(Expectation).doit(**hints) def _eval_rewrite_as_Expectation(self, X, n, condition=None, **kwargs): mu = Expectation(X, condition, **kwargs) return Moment(X, n, mu, condition, **kwargs).rewrite(Expectation) def _eval_rewrite_as_Probability(self, X, n, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Probability) def _eval_rewrite_as_Integral(self, X, n, condition=None, **kwargs): return self.rewrite(Expectation).rewrite(Integral)
50c0f77987ff3e886dd2ac63747dbf6b11b0c0e37a719a354a9ef4d028b53353
#!/usr/bin/env python from sympy.core.random import random from sympy.core.numbers import (I, Integer, pi) from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin from sympy.polys.polytools import factor from sympy.simplify.simplify import simplify from sympy.abc import x, y, z from timeit import default_timer as clock def bench_R1(): "real(f(f(f(f(f(f(f(f(f(f(i/2)))))))))))" def f(z): return sqrt(Integer(1)/3)*z**2 + I/3 f(f(f(f(f(f(f(f(f(f(I/2)))))))))).as_real_imag()[0] def bench_R2(): "Hermite polynomial hermite(15, y)" def hermite(n, y): if n == 1: return 2*y if n == 0: return 1 return (2*y*hermite(n - 1, y) - 2*(n - 1)*hermite(n - 2, y)).expand() hermite(15, y) def bench_R3(): "a = [bool(f==f) for _ in range(10)]" f = x + y + z [bool(f == f) for _ in range(10)] def bench_R4(): # we don't have Tuples pass def bench_R5(): "blowup(L, 8); L=uniq(L)" def blowup(L, n): for i in range(n): L.append( (L[i] + L[i + 1]) * L[i + 2] ) def uniq(x): v = set(x) return v L = [x, y, z] blowup(L, 8) L = uniq(L) def bench_R6(): "sum(simplify((x+sin(i))/x+(x-sin(i))/x) for i in range(100))" sum(simplify((x + sin(i))/x + (x - sin(i))/x) for i in range(100)) def bench_R7(): "[f.subs(x, random()) for _ in range(10**4)]" f = x**24 + 34*x**12 + 45*x**3 + 9*x**18 + 34*x**10 + 32*x**21 [f.subs(x, random()) for _ in range(10**4)] def bench_R8(): "right(x^2,0,5,10^4)" def right(f, a, b, n): a = sympify(a) b = sympify(b) n = sympify(n) x = f.atoms(Symbol).pop() Deltax = (b - a)/n c = a est = 0 for i in range(n): c += Deltax est += f.subs(x, c) return est*Deltax right(x**2, 0, 5, 10**4) def _bench_R9(): "factor(x^20 - pi^5*y^20)" factor(x**20 - pi**5*y**20) def bench_R10(): "v = [-pi,-pi+1/10..,pi]" def srange(min, max, step): v = [min] while (max - v[-1]).evalf() > 0: v.append(v[-1] + step) return v[:-1] srange(-pi, pi, sympify(1)/10) def bench_R11(): "a = [random() + random()*I for w in [0..1000]]" [random() + random()*I for w in range(1000)] def bench_S1(): "e=(x+y+z+1)**7;f=e*(e+1);f.expand()" e = (x + y + z + 1)**7 f = e*(e + 1) f.expand() if __name__ == '__main__': benchmarks = [ bench_R1, bench_R2, bench_R3, bench_R5, bench_R6, bench_R7, bench_R8, #_bench_R9, bench_R10, bench_R11, #bench_S1, ] report = [] for b in benchmarks: t = clock() b() t = clock() - t print("%s%65s: %f" % (b.__name__, b.__doc__, t))
75235d661a1cf1ae21e74c11b5b3b12f0a668148ae305a5eeb2b532d445ca656
# conceal the implicit import from the code quality tester from sympy.core.numbers import (oo, pi) from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.special.bessel import besseli from sympy.functions.special.gamma_functions import gamma from sympy.integrals.integrals import integrate from sympy.integrals.transforms import (mellin_transform, inverse_fourier_transform, inverse_mellin_transform, laplace_transform, inverse_laplace_transform, fourier_transform) LT = laplace_transform FT = fourier_transform MT = mellin_transform IFT = inverse_fourier_transform ILT = inverse_laplace_transform IMT = inverse_mellin_transform from sympy.abc import x, y nu, beta, rho = symbols('nu beta rho') apos, bpos, cpos, dpos, posk, p = symbols('a b c d k p', positive=True) k = Symbol('k', real=True) negk = Symbol('k', negative=True) mu1, mu2 = symbols('mu1 mu2', real=True, nonzero=True, finite=True) sigma1, sigma2 = symbols('sigma1 sigma2', real=True, nonzero=True, finite=True, positive=True) rate = Symbol('lambda', positive=True) def normal(x, mu, sigma): return 1/sqrt(2*pi*sigma**2)*exp(-(x - mu)**2/2/sigma**2) def exponential(x, rate): return rate*exp(-rate*x) alpha, beta = symbols('alpha beta', positive=True) betadist = x**(alpha - 1)*(1 + x)**(-alpha - beta)*gamma(alpha + beta) \ /gamma(alpha)/gamma(beta) kint = Symbol('k', integer=True, positive=True) chi = 2**(1 - kint/2)*x**(kint - 1)*exp(-x**2/2)/gamma(kint/2) chisquared = 2**(-k/2)/gamma(k/2)*x**(k/2 - 1)*exp(-x/2) dagum = apos*p/x*(x/bpos)**(apos*p)/(1 + x**apos/bpos**apos)**(p + 1) d1, d2 = symbols('d1 d2', positive=True) f = sqrt(((d1*x)**d1 * d2**d2)/(d1*x + d2)**(d1 + d2))/x \ /gamma(d1/2)/gamma(d2/2)*gamma((d1 + d2)/2) nupos, sigmapos = symbols('nu sigma', positive=True) rice = x/sigmapos**2*exp(-(x**2 + nupos**2)/2/sigmapos**2)*besseli(0, x* nupos/sigmapos**2) mu = Symbol('mu', real=True) laplace = exp(-abs(x - mu)/bpos)/2/bpos u = Symbol('u', polar=True) tpos = Symbol('t', positive=True) def E(expr): integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1), (x, 0, oo), (y, -oo, oo), meijerg=True) integrate(expr*exponential(x, rate)*normal(y, mu1, sigma1), (y, -oo, oo), (x, 0, oo), meijerg=True) bench = [ 'MT(x**nu*Heaviside(x - 1), x, s)', 'MT(x**nu*Heaviside(1 - x), x, s)', 'MT((1-x)**(beta - 1)*Heaviside(1-x), x, s)', 'MT((x-1)**(beta - 1)*Heaviside(x-1), x, s)', 'MT((1+x)**(-rho), x, s)', 'MT(abs(1-x)**(-rho), x, s)', 'MT((1-x)**(beta-1)*Heaviside(1-x) + a*(x-1)**(beta-1)*Heaviside(x-1), x, s)', 'MT((x**a-b**a)/(x-b), x, s)', 'MT((x**a-bpos**a)/(x-bpos), x, s)', 'MT(exp(-x), x, s)', 'MT(exp(-1/x), x, s)', 'MT(log(x)**4*Heaviside(1-x), x, s)', 'MT(log(x)**3*Heaviside(x-1), x, s)', 'MT(log(x + 1), x, s)', 'MT(log(1/x + 1), x, s)', 'MT(log(abs(1 - x)), x, s)', 'MT(log(abs(1 - 1/x)), x, s)', 'MT(log(x)/(x+1), x, s)', 'MT(log(x)**2/(x+1), x, s)', 'MT(log(x)/(x+1)**2, x, s)', 'MT(erf(sqrt(x)), x, s)', 'MT(besselj(a, 2*sqrt(x)), x, s)', 'MT(sin(sqrt(x))*besselj(a, sqrt(x)), x, s)', 'MT(cos(sqrt(x))*besselj(a, sqrt(x)), x, s)', 'MT(besselj(a, sqrt(x))**2, x, s)', 'MT(besselj(a, sqrt(x))*besselj(-a, sqrt(x)), x, s)', 'MT(besselj(a - 1, sqrt(x))*besselj(a, sqrt(x)), x, s)', 'MT(besselj(a, sqrt(x))*besselj(b, sqrt(x)), x, s)', 'MT(besselj(a, sqrt(x))**2 + besselj(-a, sqrt(x))**2, x, s)', 'MT(bessely(a, 2*sqrt(x)), x, s)', 'MT(sin(sqrt(x))*bessely(a, sqrt(x)), x, s)', 'MT(cos(sqrt(x))*bessely(a, sqrt(x)), x, s)', 'MT(besselj(a, sqrt(x))*bessely(a, sqrt(x)), x, s)', 'MT(besselj(a, sqrt(x))*bessely(b, sqrt(x)), x, s)', 'MT(bessely(a, sqrt(x))**2, x, s)', 'MT(besselk(a, 2*sqrt(x)), x, s)', 'MT(besselj(a, 2*sqrt(2*sqrt(x)))*besselk(a, 2*sqrt(2*sqrt(x))), x, s)', 'MT(besseli(a, sqrt(x))*besselk(a, sqrt(x)), x, s)', 'MT(besseli(b, sqrt(x))*besselk(a, sqrt(x)), x, s)', 'MT(exp(-x/2)*besselk(a, x/2), x, s)', # later: ILT, IMT 'LT((t-apos)**bpos*exp(-cpos*(t-apos))*Heaviside(t-apos), t, s)', 'LT(t**apos, t, s)', 'LT(Heaviside(t), t, s)', 'LT(Heaviside(t - apos), t, s)', 'LT(1 - exp(-apos*t), t, s)', 'LT((exp(2*t)-1)*exp(-bpos - t)*Heaviside(t)/2, t, s, noconds=True)', 'LT(exp(t), t, s)', 'LT(exp(2*t), t, s)', 'LT(exp(apos*t), t, s)', 'LT(log(t/apos), t, s)', 'LT(erf(t), t, s)', 'LT(sin(apos*t), t, s)', 'LT(cos(apos*t), t, s)', 'LT(exp(-apos*t)*sin(bpos*t), t, s)', 'LT(exp(-apos*t)*cos(bpos*t), t, s)', 'LT(besselj(0, t), t, s, noconds=True)', 'LT(besselj(1, t), t, s, noconds=True)', 'FT(Heaviside(1 - abs(2*apos*x)), x, k)', 'FT(Heaviside(1-abs(apos*x))*(1-abs(apos*x)), x, k)', 'FT(exp(-apos*x)*Heaviside(x), x, k)', 'IFT(1/(apos + 2*pi*I*x), x, posk, noconds=False)', 'IFT(1/(apos + 2*pi*I*x), x, -posk, noconds=False)', 'IFT(1/(apos + 2*pi*I*x), x, negk)', 'FT(x*exp(-apos*x)*Heaviside(x), x, k)', 'FT(exp(-apos*x)*sin(bpos*x)*Heaviside(x), x, k)', 'FT(exp(-apos*x**2), x, k)', 'IFT(sqrt(pi/apos)*exp(-(pi*k)**2/apos), k, x)', 'FT(exp(-apos*abs(x)), x, k)', 'integrate(normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)', 'integrate(x*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)', 'integrate(x**2*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)', 'integrate(x**3*normal(x, mu1, sigma1), (x, -oo, oo), meijerg=True)', 'integrate(normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', 'integrate(x*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', 'integrate(y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', 'integrate(x*y*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', 'integrate((x+y+1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', 'integrate((x+y-1)*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', 'integrate(x**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', 'integrate(y**2*normal(x, mu1, sigma1)*normal(y, mu2, sigma2),' ' (x, -oo, oo), (y, -oo, oo), meijerg=True)', 'integrate(exponential(x, rate), (x, 0, oo), meijerg=True)', 'integrate(x*exponential(x, rate), (x, 0, oo), meijerg=True)', 'integrate(x**2*exponential(x, rate), (x, 0, oo), meijerg=True)', 'E(1)', 'E(x*y)', 'E(x*y**2)', 'E((x+y+1)**2)', 'E(x+y+1)', 'E((x+y-1)**2)', 'integrate(betadist, (x, 0, oo), meijerg=True)', 'integrate(x*betadist, (x, 0, oo), meijerg=True)', 'integrate(x**2*betadist, (x, 0, oo), meijerg=True)', 'integrate(chi, (x, 0, oo), meijerg=True)', 'integrate(x*chi, (x, 0, oo), meijerg=True)', 'integrate(x**2*chi, (x, 0, oo), meijerg=True)', 'integrate(chisquared, (x, 0, oo), meijerg=True)', 'integrate(x*chisquared, (x, 0, oo), meijerg=True)', 'integrate(x**2*chisquared, (x, 0, oo), meijerg=True)', 'integrate(((x-k)/sqrt(2*k))**3*chisquared, (x, 0, oo), meijerg=True)', 'integrate(dagum, (x, 0, oo), meijerg=True)', 'integrate(x*dagum, (x, 0, oo), meijerg=True)', 'integrate(x**2*dagum, (x, 0, oo), meijerg=True)', 'integrate(f, (x, 0, oo), meijerg=True)', 'integrate(x*f, (x, 0, oo), meijerg=True)', 'integrate(x**2*f, (x, 0, oo), meijerg=True)', 'integrate(rice, (x, 0, oo), meijerg=True)', 'integrate(laplace, (x, -oo, oo), meijerg=True)', 'integrate(x*laplace, (x, -oo, oo), meijerg=True)', 'integrate(x**2*laplace, (x, -oo, oo), meijerg=True)', 'integrate(log(x) * x**(k-1) * exp(-x) / gamma(k), (x, 0, oo))', 'integrate(sin(z*x)*(x**2-1)**(-(y+S(1)/2)), (x, 1, oo), meijerg=True)', 'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)', 'integrate(besselj(0,x)*besselj(1,x)*besselk(0,x), (x, 0, oo), meijerg=True)', 'integrate(besselj(0,x)*besselj(1,x)*exp(-x**2), (x, 0, oo), meijerg=True)', 'integrate(besselj(a,x)*besselj(b,x)/x, (x,0,oo), meijerg=True)', 'hyperexpand(meijerg((-s - a/2 + 1, -s + a/2 + 1), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), (a/2, -a/2), (-a/2 - S(1)/2, -s + a/2 + S(3)/2), 1))', "gammasimp(S('2**(2*s)*(-pi*gamma(-a + 1)*gamma(a + 1)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 3/2)*gamma(a + s + 1)/(a*(a + s)) - gamma(-a - 1/2)*gamma(-a + 1)*gamma(a + 1)*gamma(a + 3/2)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a + s + 1)*gamma(a - s + 1)/(a*(-a + s)))*gamma(-2*s + 1)*gamma(s + 1)/(pi*s*gamma(-a - 1/2)*gamma(a + 3/2)*gamma(-s + 1)*gamma(-s + 3/2)*gamma(s - 1/2)*gamma(-a - s + 1)*gamma(-a + s - 1/2)*gamma(a - s + 1)*gamma(a - s + 3/2))'))", 'mellin_transform(E1(x), x, s)', 'inverse_mellin_transform(gamma(s)/s, s, x, (0, oo))', 'mellin_transform(expint(a, x), x, s)', 'mellin_transform(Si(x), x, s)', 'inverse_mellin_transform(-2**s*sqrt(pi)*gamma((s + 1)/2)/(2*s*gamma(-s/2 + 1)), s, x, (-1, 0))', 'mellin_transform(Ci(sqrt(x)), x, s)', 'inverse_mellin_transform(-4**s*sqrt(pi)*gamma(s)/(2*s*gamma(-s + S(1)/2)),s, u, (0, 1))', 'laplace_transform(Ci(x), x, s)', 'laplace_transform(expint(a, x), x, s)', 'laplace_transform(expint(1, x), x, s)', 'laplace_transform(expint(2, x), x, s)', 'inverse_laplace_transform(-log(1 + s**2)/2/s, s, u)', 'inverse_laplace_transform(log(s + 1)/s, s, x)', 'inverse_laplace_transform((s - log(s + 1))/s**2, s, x)', 'laplace_transform(Chi(x), x, s)', 'laplace_transform(Shi(x), x, s)', 'integrate(exp(-z*x)/x, (x, 1, oo), meijerg=True, conds="none")', 'integrate(exp(-z*x)/x**2, (x, 1, oo), meijerg=True, conds="none")', 'integrate(exp(-z*x)/x**3, (x, 1, oo), meijerg=True,conds="none")', 'integrate(-cos(x)/x, (x, tpos, oo), meijerg=True)', 'integrate(-sin(x)/x, (x, tpos, oo), meijerg=True)', 'integrate(sin(x)/x, (x, 0, z), meijerg=True)', 'integrate(sinh(x)/x, (x, 0, z), meijerg=True)', 'integrate(exp(-x)/x, x, meijerg=True)', 'integrate(exp(-x)/x**2, x, meijerg=True)', 'integrate(cos(u)/u, u, meijerg=True)', 'integrate(cosh(u)/u, u, meijerg=True)', 'integrate(expint(1, x), x, meijerg=True)', 'integrate(expint(2, x), x, meijerg=True)', 'integrate(Si(x), x, meijerg=True)', 'integrate(Ci(u), u, meijerg=True)', 'integrate(Shi(x), x, meijerg=True)', 'integrate(Chi(u), u, meijerg=True)', 'integrate(Si(x)*exp(-x), (x, 0, oo), meijerg=True)', 'integrate(expint(1, x)*sin(x), (x, 0, oo), meijerg=True)' ] from time import time from sympy.core.cache import clear_cache import sys timings = [] if __name__ == '__main__': for n, string in enumerate(bench): clear_cache() _t = time() exec(string) _t = time() - _t timings += [(_t, string)] sys.stdout.write('.') sys.stdout.flush() if n % (len(bench) // 10) == 0: sys.stdout.write('%s' % (10*n // len(bench))) print() timings.sort(key=lambda x: -x[0]) for ti, string in timings: print('%.2fs %s' % (ti, string))
d7e0200a080a32c35aae8e9500114d2a0249206af83c3b3c05998ff4ebba8ef5
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.domains import ZZ 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] """ from sympy.polys.galoistools import gf_crt1, gf_crt2 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)]). 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): """Returns True if ``x**n == a (mod m)`` 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 = f // igcd(f, n) return pow(a, k, m) == 1 def _is_nthpow_residue_bign_prime_power(a, n, p, k): """Returns True/False if a solution for ``x**n == a (mod(p**k))`` does/doesn't 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): """ 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 = set() for i in range(p // 2 + 1): r.add(pow(i, 2, p)) return sorted(list(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 if m < 0: m = -m if n % 4 == 3: j = -j 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 if n != 1: j = 0 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 = dict() 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 a : integer b : integer c : integer p : positive integer """ from sympy.polys.galoistools import linear_congruence 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") from sympy.polys import Poly 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))
871208216d9e35e5db21dbb18d62c050f6134617c71e99c90e602802080ffbfa
""" Integer factorization """ from collections import defaultdict import random import math from sympy.core import sympify from sympy.core.containers import Dict from sympy.core.evalf import bitcount from sympy.core.expr import Expr from sympy.core.function import Function from sympy.core.logic import fuzzy_and from sympy.core.mul import Mul, prod from sympy.core.numbers import igcd, ilcm, Rational, Integer from sympy.core.power import integer_nthroot, Pow, integer_log from sympy.core.singleton import S from sympy.external.gmpy import SYMPY_INTS from .primetest import isprime from .generate import sieve, primerange, nextprime from .digits import digits from sympy.utilities.iterables import flatten from sympy.utilities.misc import as_int, filldedent from .ecm import _ecm_one_factor # Note: This list should be updated whenever new Mersenne primes are found. # Refer: https://www.mersenne.org/ MERSENNE_PRIME_EXPONENTS = (2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583, 25964951, 30402457, 32582657, 37156667, 42643801, 43112609, 57885161, 74207281, 77232917, 82589933) # compute more when needed for i in Mersenne prime exponents PERFECT = [6] # 2**(i-1)*(2**i-1) MERSENNES = [3] # 2**i - 1 def _ismersenneprime(n): global MERSENNES j = len(MERSENNES) while n > MERSENNES[-1] and j < len(MERSENNE_PRIME_EXPONENTS): # conservatively grow the list MERSENNES.append(2**MERSENNE_PRIME_EXPONENTS[j] - 1) j += 1 return n in MERSENNES def _isperfect(n): global PERFECT if n % 2 == 0: j = len(PERFECT) while n > PERFECT[-1] and j < len(MERSENNE_PRIME_EXPONENTS): # conservatively grow the list t = 2**(MERSENNE_PRIME_EXPONENTS[j] - 1) PERFECT.append(t*(2*t - 1)) j += 1 return n in PERFECT small_trailing = [0] * 256 for j in range(1,8): small_trailing[1<<j::1<<(j+1)] = [j] * (1<<(7-j)) def smoothness(n): """ Return the B-smooth and B-power smooth values of n. The smoothness of n is the largest prime factor of n; the power- smoothness is the largest divisor raised to its multiplicity. Examples ======== >>> from sympy.ntheory.factor_ import smoothness >>> smoothness(2**7*3**2) (3, 128) >>> smoothness(2**4*13) (13, 16) >>> smoothness(2) (2, 2) See Also ======== factorint, smoothness_p """ if n == 1: return (1, 1) # not prime, but otherwise this causes headaches facs = factorint(n) return max(facs), max(m**facs[m] for m in facs) def smoothness_p(n, m=-1, power=0, visual=None): """ Return a list of [m, (p, (M, sm(p + m), psm(p + m)))...] where: 1. p**M is the base-p divisor of n 2. sm(p + m) is the smoothness of p + m (m = -1 by default) 3. psm(p + m) is the power smoothness of p + m The list is sorted according to smoothness (default) or by power smoothness if power=1. The smoothness of the numbers to the left (m = -1) or right (m = 1) of a factor govern the results that are obtained from the p +/- 1 type factoring methods. >>> from sympy.ntheory.factor_ import smoothness_p, factorint >>> smoothness_p(10431, m=1) (1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))]) >>> smoothness_p(10431) (-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))]) >>> smoothness_p(10431, power=1) (-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))]) If visual=True then an annotated string will be returned: >>> print(smoothness_p(21477639576571, visual=1)) p**i=4410317**1 has p-1 B=1787, B-pow=1787 p**i=4869863**1 has p-1 B=2434931, B-pow=2434931 This string can also be generated directly from a factorization dictionary and vice versa: >>> factorint(17*9) {3: 2, 17: 1} >>> smoothness_p(_) 'p**i=3**2 has p-1 B=2, B-pow=2\\np**i=17**1 has p-1 B=2, B-pow=16' >>> smoothness_p(_) {3: 2, 17: 1} The table of the output logic is: ====== ====== ======= ======= | Visual ------ ---------------------- Input True False other ====== ====== ======= ======= dict str tuple str str str tuple dict tuple str tuple str n str tuple tuple mul str tuple tuple ====== ====== ======= ======= See Also ======== factorint, smoothness """ # visual must be True, False or other (stored as None) if visual in (1, 0): visual = bool(visual) elif visual not in (True, False): visual = None if isinstance(n, str): if visual: return n d = {} for li in n.splitlines(): k, v = [int(i) for i in li.split('has')[0].split('=')[1].split('**')] d[k] = v if visual is not True and visual is not False: return d return smoothness_p(d, visual=False) elif not isinstance(n, tuple): facs = factorint(n, visual=False) if power: k = -1 else: k = 1 if isinstance(n, tuple): rv = n else: rv = (m, sorted([(f, tuple([M] + list(smoothness(f + m)))) for f, M in [i for i in facs.items()]], key=lambda x: (x[1][k], x[0]))) if visual is False or (visual is not True) and (type(n) in [int, Mul]): return rv lines = [] for dat in rv[1]: dat = flatten(dat) dat.insert(2, m) lines.append('p**i=%i**%i has p%+i B=%i, B-pow=%i' % tuple(dat)) return '\n'.join(lines) def trailing(n): """Count the number of trailing zero digits in the binary representation of n, i.e. determine the largest power of 2 that divides n. Examples ======== >>> from sympy import trailing >>> trailing(128) 7 >>> trailing(63) 0 """ n = abs(int(n)) if not n: return 0 low_byte = n & 0xff if low_byte: return small_trailing[low_byte] # 2**m is quick for z up through 2**30 z = bitcount(n) - 1 if isinstance(z, SYMPY_INTS): if n == 1 << z: return z if z < 300: # fixed 8-byte reduction t = 8 n >>= 8 while not n & 0xff: n >>= 8 t += 8 return t + small_trailing[n & 0xff] # binary reduction important when there might be a large # number of trailing 0s t = 0 p = 8 while not n & 1: while not n & ((1 << p) - 1): n >>= p t += p p *= 2 p //= 2 return t def multiplicity(p, n): """ Find the greatest integer m such that p**m divides n. Examples ======== >>> from sympy import multiplicity, Rational >>> [multiplicity(5, n) for n in [8, 5, 25, 125, 250]] [0, 1, 2, 3, 3] >>> multiplicity(3, Rational(1, 9)) -2 Note: when checking for the multiplicity of a number in a large factorial it is most efficient to send it as an unevaluated factorial or to call ``multiplicity_in_factorial`` directly: >>> from sympy.ntheory import multiplicity_in_factorial >>> from sympy import factorial >>> p = factorial(25) >>> n = 2**100 >>> nfac = factorial(n, evaluate=False) >>> multiplicity(p, nfac) 52818775009509558395695966887 >>> _ == multiplicity_in_factorial(p, n) True """ from sympy.functions.combinatorial.factorials import factorial try: p, n = as_int(p), as_int(n) except ValueError: if all(isinstance(i, (SYMPY_INTS, Rational)) for i in (p, n)): p = Rational(p) n = Rational(n) if p.q == 1: if n.p == 1: return -multiplicity(p.p, n.q) return multiplicity(p.p, n.p) - multiplicity(p.p, n.q) elif p.p == 1: return multiplicity(p.q, n.q) else: like = min( multiplicity(p.p, n.p), multiplicity(p.q, n.q)) cross = min( multiplicity(p.q, n.p), multiplicity(p.p, n.q)) return like - cross elif (isinstance(p, (SYMPY_INTS, Integer)) and isinstance(n, factorial) and isinstance(n.args[0], Integer) and n.args[0] >= 0): return multiplicity_in_factorial(p, n.args[0]) raise ValueError('expecting ints or fractions, got %s and %s' % (p, n)) if n == 0: raise ValueError('no such integer exists: multiplicity of %s is not-defined' %(n)) if p == 2: return trailing(n) if p < 2: raise ValueError('p must be an integer, 2 or larger, but got %s' % p) if p == n: return 1 m = 0 n, rem = divmod(n, p) while not rem: m += 1 if m > 5: # The multiplicity could be very large. Better # to increment in powers of two e = 2 while 1: ppow = p**e if ppow < n: nnew, rem = divmod(n, ppow) if not rem: m += e e *= 2 n = nnew continue return m + multiplicity(p, n) n, rem = divmod(n, p) return m def multiplicity_in_factorial(p, n): """return the largest integer ``m`` such that ``p**m`` divides ``n!`` without calculating the factorial of ``n``. Examples ======== >>> from sympy.ntheory import multiplicity_in_factorial >>> from sympy import factorial >>> multiplicity_in_factorial(2, 3) 1 An instructive use of this is to tell how many trailing zeros a given factorial has. For example, there are 6 in 25!: >>> factorial(25) 15511210043330985984000000 >>> multiplicity_in_factorial(10, 25) 6 For large factorials, it is much faster/feasible to use this function rather than computing the actual factorial: >>> multiplicity_in_factorial(factorial(25), 2**100) 52818775009509558395695966887 """ p, n = as_int(p), as_int(n) if p <= 0: raise ValueError('expecting positive integer got %s' % p ) if n < 0: raise ValueError('expecting non-negative integer got %s' % n ) factors = factorint(p) # keep only the largest of a given multiplicity since those # of a given multiplicity will be goverened by the behavior # of the largest factor test = defaultdict(int) for k, v in factors.items(): test[v] = max(k, test[v]) keep = set(test.values()) # remove others from factors for k in list(factors.keys()): if k not in keep: factors.pop(k) mp = S.Infinity for i in factors: # multiplicity of i in n! is mi = (n - (sum(digits(n, i)) - i))//(i - 1) # multiplicity of p in n! depends on multiplicity # of prime `i` in p, so we floor divide by factors[i] # and keep it if smaller than the multiplicity of p # seen so far mp = min(mp, mi//factors[i]) return mp def perfect_power(n, candidates=None, big=True, factor=True): """ Return ``(b, e)`` such that ``n`` == ``b**e`` if ``n`` is a unique perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a perfect power). A ValueError is raised if ``n`` is not Rational. By default, the base is recursively decomposed and the exponents collected so the largest possible ``e`` is sought. If ``big=False`` then the smallest possible ``e`` (thus prime) will be chosen. If ``factor=True`` then simultaneous factorization of ``n`` is attempted since finding a factor indicates the only possible root for ``n``. This is True by default since only a few small factors will be tested in the course of searching for the perfect power. The use of ``candidates`` is primarily for internal use; if provided, False will be returned if ``n`` cannot be written as a power with one of the candidates as an exponent and factoring (beyond testing for a factor of 2) will not be attempted. Examples ======== >>> from sympy import perfect_power, Rational >>> perfect_power(16) (2, 4) >>> perfect_power(16, big=False) (4, 2) Negative numbers can only have odd perfect powers: >>> perfect_power(-4) False >>> perfect_power(-8) (-2, 3) Rationals are also recognized: >>> perfect_power(Rational(1, 2)**3) (1/2, 3) >>> perfect_power(Rational(-3, 2)**3) (-3/2, 3) Notes ===== To know whether an integer is a perfect power of 2 use >>> is2pow = lambda n: bool(n and not n & (n - 1)) >>> [(i, is2pow(i)) for i in range(5)] [(0, False), (1, True), (2, True), (3, False), (4, True)] It is not necessary to provide ``candidates``. When provided it will be assumed that they are ints. The first one that is larger than the computed maximum possible exponent will signal failure for the routine. >>> perfect_power(3**8, [9]) False >>> perfect_power(3**8, [2, 4, 8]) (3, 8) >>> perfect_power(3**8, [4, 8], big=False) (9, 4) See Also ======== sympy.core.power.integer_nthroot sympy.ntheory.primetest.is_square """ if isinstance(n, Rational) and not n.is_Integer: p, q = n.as_numer_denom() if p is S.One: pp = perfect_power(q) if pp: pp = (n.func(1, pp[0]), pp[1]) else: pp = perfect_power(p) if pp: num, e = pp pq = perfect_power(q, [e]) if pq: den, _ = pq pp = n.func(num, den), e return pp n = as_int(n) if n < 0: pp = perfect_power(-n) if pp: b, e = pp if e % 2: return -b, e return False if n <= 3: # no unique exponent for 0, 1 # 2 and 3 have exponents of 1 return False logn = math.log(n, 2) max_possible = int(logn) + 2 # only check values less than this not_square = n % 10 in [2, 3, 7, 8] # squares cannot end in 2, 3, 7, 8 min_possible = 2 + not_square if not candidates: candidates = primerange(min_possible, max_possible) else: candidates = sorted([i for i in candidates if min_possible <= i < max_possible]) if n%2 == 0: e = trailing(n) candidates = [i for i in candidates if e%i == 0] if big: candidates = reversed(candidates) for e in candidates: r, ok = integer_nthroot(n, e) if ok: return (r, e) return False def _factors(): rv = 2 + n % 2 while True: yield rv rv = nextprime(rv) for fac, e in zip(_factors(), candidates): # see if there is a factor present if factor and n % fac == 0: # find what the potential power is if fac == 2: e = trailing(n) else: e = multiplicity(fac, n) # if it's a trivial power we are done if e == 1: return False # maybe the e-th root of n is exact r, exact = integer_nthroot(n, e) if not exact: # Having a factor, we know that e is the maximal # possible value for a root of n. # If n = fac**e*m can be written as a perfect # power then see if m can be written as r**E where # gcd(e, E) != 1 so n = (fac**(e//E)*r)**E m = n//fac**e rE = perfect_power(m, candidates=divisors(e, generator=True)) if not rE: return False else: r, E = rE r, e = fac**(e//E)*r, E if not big: e0 = primefactors(e) if e0[0] != e: r, e = r**(e//e0[0]), e0[0] return r, e # Weed out downright impossible candidates if logn/e < 40: b = 2.0**(logn/e) if abs(int(b + 0.5) - b) > 0.01: continue # now see if the plausible e makes a perfect power r, exact = integer_nthroot(n, e) if exact: if big: m = perfect_power(r, big=big, factor=factor) if m: r, e = m[0], e*m[1] return int(r), e return False def pollard_rho(n, s=2, a=1, retries=5, seed=1234, max_steps=None, F=None): r""" Use Pollard's rho method to try to extract a nontrivial factor of ``n``. The returned factor may be a composite number. If no factor is found, ``None`` is returned. The algorithm generates pseudo-random values of x with a generator function, replacing x with F(x). If F is not supplied then the function x**2 + ``a`` is used. The first value supplied to F(x) is ``s``. Upon failure (if ``retries`` is > 0) a new ``a`` and ``s`` will be supplied; the ``a`` will be ignored if F was supplied. The sequence of numbers generated by such functions generally have a a lead-up to some number and then loop around back to that number and begin to repeat the sequence, e.g. 1, 2, 3, 4, 5, 3, 4, 5 -- this leader and loop look a bit like the Greek letter rho, and thus the name, 'rho'. For a given function, very different leader-loop values can be obtained so it is a good idea to allow for retries: >>> from sympy.ntheory.generate import cycle_length >>> n = 16843009 >>> F = lambda x:(2048*pow(x, 2, n) + 32767) % n >>> for s in range(5): ... print('loop length = %4i; leader length = %3i' % next(cycle_length(F, s))) ... loop length = 2489; leader length = 42 loop length = 78; leader length = 120 loop length = 1482; leader length = 99 loop length = 1482; leader length = 285 loop length = 1482; leader length = 100 Here is an explicit example where there is a two element leadup to a sequence of 3 numbers (11, 14, 4) that then repeat: >>> x=2 >>> for i in range(9): ... x=(x**2+12)%17 ... print(x) ... 16 13 11 14 4 11 14 4 11 >>> next(cycle_length(lambda x: (x**2+12)%17, 2)) (3, 2) >>> list(cycle_length(lambda x: (x**2+12)%17, 2, values=True)) [16, 13, 11, 14, 4] Instead of checking the differences of all generated values for a gcd with n, only the kth and 2*kth numbers are checked, e.g. 1st and 2nd, 2nd and 4th, 3rd and 6th until it has been detected that the loop has been traversed. Loops may be many thousands of steps long before rho finds a factor or reports failure. If ``max_steps`` is specified, the iteration is cancelled with a failure after the specified number of steps. Examples ======== >>> from sympy import pollard_rho >>> n=16843009 >>> F=lambda x:(2048*pow(x,2,n) + 32767) % n >>> pollard_rho(n, F=F) 257 Use the default setting with a bad value of ``a`` and no retries: >>> pollard_rho(n, a=n-2, retries=0) If retries is > 0 then perhaps the problem will correct itself when new values are generated for a: >>> pollard_rho(n, a=n-2, retries=1) 257 References ========== .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers: A Computational Perspective", Springer, 2nd edition, 229-231 """ n = int(n) if n < 5: raise ValueError('pollard_rho should receive n > 4') prng = random.Random(seed + retries) V = s for i in range(retries + 1): U = V if not F: F = lambda x: (pow(x, 2, n) + a) % n j = 0 while 1: if max_steps and (j > max_steps): break j += 1 U = F(U) V = F(F(V)) # V is 2x further along than U g = igcd(U - V, n) if g == 1: continue if g == n: break return int(g) V = prng.randint(0, n - 1) a = prng.randint(1, n - 3) # for x**2 + a, a%n should not be 0 or -2 F = None return None def pollard_pm1(n, B=10, a=2, retries=0, seed=1234): """ Use Pollard's p-1 method to try to extract a nontrivial factor of ``n``. Either a divisor (perhaps composite) or ``None`` is returned. The value of ``a`` is the base that is used in the test gcd(a**M - 1, n). The default is 2. If ``retries`` > 0 then if no factor is found after the first attempt, a new ``a`` will be generated randomly (using the ``seed``) and the process repeated. Note: the value of M is lcm(1..B) = reduce(ilcm, range(2, B + 1)). A search is made for factors next to even numbers having a power smoothness less than ``B``. Choosing a larger B increases the likelihood of finding a larger factor but takes longer. Whether a factor of n is found or not depends on ``a`` and the power smoothness of the even number just less than the factor p (hence the name p - 1). Although some discussion of what constitutes a good ``a`` some descriptions are hard to interpret. At the modular.math site referenced below it is stated that if gcd(a**M - 1, n) = N then a**M % q**r is 1 for every prime power divisor of N. But consider the following: >>> from sympy.ntheory.factor_ import smoothness_p, pollard_pm1 >>> n=257*1009 >>> smoothness_p(n) (-1, [(257, (1, 2, 256)), (1009, (1, 7, 16))]) So we should (and can) find a root with B=16: >>> pollard_pm1(n, B=16, a=3) 1009 If we attempt to increase B to 256 we find that it doesn't work: >>> pollard_pm1(n, B=256) >>> But if the value of ``a`` is changed we find that only multiples of 257 work, e.g.: >>> pollard_pm1(n, B=256, a=257) 1009 Checking different ``a`` values shows that all the ones that didn't work had a gcd value not equal to ``n`` but equal to one of the factors: >>> from sympy import ilcm, igcd, factorint, Pow >>> M = 1 >>> for i in range(2, 256): ... M = ilcm(M, i) ... >>> set([igcd(pow(a, M, n) - 1, n) for a in range(2, 256) if ... igcd(pow(a, M, n) - 1, n) != n]) {1009} But does aM % d for every divisor of n give 1? >>> aM = pow(255, M, n) >>> [(d, aM%Pow(*d.args)) for d in factorint(n, visual=True).args] [(257**1, 1), (1009**1, 1)] No, only one of them. So perhaps the principle is that a root will be found for a given value of B provided that: 1) the power smoothness of the p - 1 value next to the root does not exceed B 2) a**M % p != 1 for any of the divisors of n. By trying more than one ``a`` it is possible that one of them will yield a factor. Examples ======== With the default smoothness bound, this number cannot be cracked: >>> from sympy.ntheory import pollard_pm1 >>> pollard_pm1(21477639576571) Increasing the smoothness bound helps: >>> pollard_pm1(21477639576571, B=2000) 4410317 Looking at the smoothness of the factors of this number we find: >>> from sympy.ntheory.factor_ import smoothness_p, factorint >>> print(smoothness_p(21477639576571, visual=1)) p**i=4410317**1 has p-1 B=1787, B-pow=1787 p**i=4869863**1 has p-1 B=2434931, B-pow=2434931 The B and B-pow are the same for the p - 1 factorizations of the divisors because those factorizations had a very large prime factor: >>> factorint(4410317 - 1) {2: 2, 617: 1, 1787: 1} >>> factorint(4869863-1) {2: 1, 2434931: 1} Note that until B reaches the B-pow value of 1787, the number is not cracked; >>> pollard_pm1(21477639576571, B=1786) >>> pollard_pm1(21477639576571, B=1787) 4410317 The B value has to do with the factors of the number next to the divisor, not the divisors themselves. A worst case scenario is that the number next to the factor p has a large prime divisisor or is a perfect power. If these conditions apply then the power-smoothness will be about p/2 or p. The more realistic is that there will be a large prime factor next to p requiring a B value on the order of p/2. Although primes may have been searched for up to this level, the p/2 is a factor of p - 1, something that we do not know. The modular.math reference below states that 15% of numbers in the range of 10**15 to 15**15 + 10**4 are 10**6 power smooth so a B of 10**6 will fail 85% of the time in that range. From 10**8 to 10**8 + 10**3 the percentages are nearly reversed...but in that range the simple trial division is quite fast. References ========== .. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers: A Computational Perspective", Springer, 2nd edition, 236-238 .. [2] http://modular.math.washington.edu/edu/2007/spring/ent/ent-html/node81.html .. [3] https://www.cs.toronto.edu/~yuvalf/Factorization.pdf """ n = int(n) if n < 4 or B < 3: raise ValueError('pollard_pm1 should receive n > 3 and B > 2') prng = random.Random(seed + B) # computing a**lcm(1,2,3,..B) % n for B > 2 # it looks weird, but it's right: primes run [2, B] # and the answer's not right until the loop is done. for i in range(retries + 1): aM = a for p in sieve.primerange(2, B + 1): e = int(math.log(B, p)) aM = pow(aM, pow(p, e), n) g = igcd(aM - 1, n) if 1 < g < n: return int(g) # get a new a: # since the exponent, lcm(1..B), is even, if we allow 'a' to be 'n-1' # then (n - 1)**even % n will be 1 which will give a g of 0 and 1 will # give a zero, too, so we set the range as [2, n-2]. Some references # say 'a' should be coprime to n, but either will detect factors. a = prng.randint(2, n - 2) def _trial(factors, n, candidates, verbose=False): """ Helper function for integer factorization. Trial factors ``n` against all integers given in the sequence ``candidates`` and updates the dict ``factors`` in-place. Returns the reduced value of ``n`` and a flag indicating whether any factors were found. """ if verbose: factors0 = list(factors.keys()) nfactors = len(factors) for d in candidates: if n % d == 0: m = multiplicity(d, n) n //= d**m factors[d] = m if verbose: for k in sorted(set(factors).difference(set(factors0))): print(factor_msg % (k, factors[k])) return int(n), len(factors) != nfactors def _check_termination(factors, n, limitp1, use_trial, use_rho, use_pm1, verbose): """ Helper function for integer factorization. Checks if ``n`` is a prime or a perfect power, and in those cases updates the factorization and raises ``StopIteration``. """ if verbose: print('Check for termination') # since we've already been factoring there is no need to do # simultaneous factoring with the power check p = perfect_power(n, factor=False) if p is not False: base, exp = p if limitp1: limit = limitp1 - 1 else: limit = limitp1 facs = factorint(base, limit, use_trial, use_rho, use_pm1, verbose=False) for b, e in facs.items(): if verbose: print(factor_msg % (b, e)) factors[b] = exp*e raise StopIteration if isprime(n): factors[int(n)] = 1 raise StopIteration if n == 1: raise StopIteration trial_int_msg = "Trial division with ints [%i ... %i] and fail_max=%i" trial_msg = "Trial division with primes [%i ... %i]" rho_msg = "Pollard's rho with retries %i, max_steps %i and seed %i" pm1_msg = "Pollard's p-1 with smoothness bound %i and seed %i" ecm_msg = "Elliptic Curve with B1 bound %i, B2 bound %i, num_curves %i" factor_msg = '\t%i ** %i' fermat_msg = 'Close factors satisying Fermat condition found.' complete_msg = 'Factorization is complete.' def _factorint_small(factors, n, limit, fail_max): """ Return the value of n and either a 0 (indicating that factorization up to the limit was complete) or else the next near-prime that would have been tested. Factoring stops if there are fail_max unsuccessful tests in a row. If factors of n were found they will be in the factors dictionary as {factor: multiplicity} and the returned value of n will have had those factors removed. The factors dictionary is modified in-place. """ def done(n, d): """return n, d if the sqrt(n) wasn't reached yet, else n, 0 indicating that factoring is done. """ if d*d <= n: return n, d return n, 0 d = 2 m = trailing(n) if m: factors[d] = m n >>= m d = 3 if limit < d: if n > 1: factors[n] = 1 return done(n, d) # reduce m = 0 while n % d == 0: n //= d m += 1 if m == 20: mm = multiplicity(d, n) m += mm n //= d**mm break if m: factors[d] = m # when d*d exceeds maxx or n we are done; if limit**2 is greater # than n then maxx is set to zero so the value of n will flag the finish if limit*limit > n: maxx = 0 else: maxx = limit*limit dd = maxx or n d = 5 fails = 0 while fails < fail_max: if d*d > dd: break # d = 6*i - 1 # reduce m = 0 while n % d == 0: n //= d m += 1 if m == 20: mm = multiplicity(d, n) m += mm n //= d**mm break if m: factors[d] = m dd = maxx or n fails = 0 else: fails += 1 d += 2 if d*d > dd: break # d = 6*i - 1 # reduce m = 0 while n % d == 0: n //= d m += 1 if m == 20: mm = multiplicity(d, n) m += mm n //= d**mm break if m: factors[d] = m dd = maxx or n fails = 0 else: fails += 1 # d = 6*(i + 1) - 1 d += 4 return done(n, d) def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True, use_ecm=True, verbose=False, visual=None, multiple=False): r""" Given a positive integer ``n``, ``factorint(n)`` returns a dict containing the prime factors of ``n`` as keys and their respective multiplicities as values. For example: >>> from sympy.ntheory import factorint >>> factorint(2000) # 2000 = (2**4) * (5**3) {2: 4, 5: 3} >>> factorint(65537) # This number is prime {65537: 1} For input less than 2, factorint behaves as follows: - ``factorint(1)`` returns the empty factorization, ``{}`` - ``factorint(0)`` returns ``{0:1}`` - ``factorint(-n)`` adds ``-1:1`` to the factors and then factors ``n`` Partial Factorization: If ``limit`` (> 3) is specified, the search is stopped after performing trial division up to (and including) the limit (or taking a corresponding number of rho/p-1 steps). This is useful if one has a large number and only is interested in finding small factors (if any). Note that setting a limit does not prevent larger factors from being found early; it simply means that the largest factor may be composite. Since checking for perfect power is relatively cheap, it is done regardless of the limit setting. This number, for example, has two small factors and a huge semi-prime factor that cannot be reduced easily: >>> from sympy.ntheory import isprime >>> a = 1407633717262338957430697921446883 >>> f = factorint(a, limit=10000) >>> f == {991: 1, int(202916782076162456022877024859): 1, 7: 1} True >>> isprime(max(f)) False This number has a small factor and a residual perfect power whose base is greater than the limit: >>> factorint(3*101**7, limit=5) {3: 1, 101: 7} List of Factors: If ``multiple`` is set to ``True`` then a list containing the prime factors including multiplicities is returned. >>> factorint(24, multiple=True) [2, 2, 2, 3] Visual Factorization: If ``visual`` is set to ``True``, then it will return a visual factorization of the integer. For example: >>> from sympy import pprint >>> pprint(factorint(4200, visual=True)) 3 1 2 1 2 *3 *5 *7 Note that this is achieved by using the evaluate=False flag in Mul and Pow. If you do other manipulations with an expression where evaluate=False, it may evaluate. Therefore, you should use the visual option only for visualization, and use the normal dictionary returned by visual=False if you want to perform operations on the factors. You can easily switch between the two forms by sending them back to factorint: >>> from sympy import Mul >>> regular = factorint(1764); regular {2: 2, 3: 2, 7: 2} >>> pprint(factorint(regular)) 2 2 2 2 *3 *7 >>> visual = factorint(1764, visual=True); pprint(visual) 2 2 2 2 *3 *7 >>> print(factorint(visual)) {2: 2, 3: 2, 7: 2} If you want to send a number to be factored in a partially factored form you can do so with a dictionary or unevaluated expression: >>> factorint(factorint({4: 2, 12: 3})) # twice to toggle to dict form {2: 10, 3: 3} >>> factorint(Mul(4, 12, evaluate=False)) {2: 4, 3: 1} The table of the output logic is: ====== ====== ======= ======= Visual ------ ---------------------- Input True False other ====== ====== ======= ======= dict mul dict mul n mul dict dict mul mul dict dict ====== ====== ======= ======= Notes ===== Algorithm: The function switches between multiple algorithms. Trial division quickly finds small factors (of the order 1-5 digits), and finds all large factors if given enough time. The Pollard rho and p-1 algorithms are used to find large factors ahead of time; they will often find factors of the order of 10 digits within a few seconds: >>> factors = factorint(12345678910111213141516) >>> for base, exp in sorted(factors.items()): ... print('%s %s' % (base, exp)) ... 2 2 2507191691 1 1231026625769 1 Any of these methods can optionally be disabled with the following boolean parameters: - ``use_trial``: Toggle use of trial division - ``use_rho``: Toggle use of Pollard's rho method - ``use_pm1``: Toggle use of Pollard's p-1 method ``factorint`` also periodically checks if the remaining part is a prime number or a perfect power, and in those cases stops. For unevaluated factorial, it uses Legendre's formula(theorem). If ``verbose`` is set to ``True``, detailed progress is printed. See Also ======== smoothness, smoothness_p, divisors """ if isinstance(n, Dict): n = dict(n) if multiple: fac = factorint(n, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose, visual=False, multiple=False) factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p]) for p in sorted(fac)), []) return factorlist factordict = {} if visual and not isinstance(n, (Mul, dict)): factordict = factorint(n, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose, visual=False) elif isinstance(n, Mul): factordict = {int(k): int(v) for k, v in n.as_powers_dict().items()} elif isinstance(n, dict): factordict = n if factordict and isinstance(n, (Mul, dict)): # check it for key in list(factordict.keys()): if isprime(key): continue e = factordict.pop(key) d = factorint(key, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose, visual=False) for k, v in d.items(): if k in factordict: factordict[k] += v*e else: factordict[k] = v*e if visual or (type(n) is dict and visual is not True and visual is not False): if factordict == {}: return S.One if -1 in factordict: factordict.pop(-1) args = [S.NegativeOne] else: args = [] args.extend([Pow(*i, evaluate=False) for i in sorted(factordict.items())]) return Mul(*args, evaluate=False) elif isinstance(n, dict) or isinstance(n, Mul): return factordict assert use_trial or use_rho or use_pm1 or use_ecm from sympy.functions.combinatorial.factorials import factorial if isinstance(n, factorial): x = as_int(n.args[0]) if x >= 20: factors = {} m = 2 # to initialize the if condition below for p in sieve.primerange(2, x + 1): if m > 1: m, q = 0, x // p while q != 0: m += q q //= p factors[p] = m if factors and verbose: for k in sorted(factors): print(factor_msg % (k, factors[k])) if verbose: print(complete_msg) return factors else: # if n < 20!, direct computation is faster # since it uses a lookup table n = n.func(x) n = as_int(n) if limit: limit = int(limit) use_ecm = False # special cases if n < 0: factors = factorint( -n, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose, visual=False) factors[-1] = 1 return factors if limit and limit < 2: if n == 1: return {} return {n: 1} elif n < 10: # doing this we are assured of getting a limit > 2 # when we have to compute it later return [{0: 1}, {}, {2: 1}, {3: 1}, {2: 2}, {5: 1}, {2: 1, 3: 1}, {7: 1}, {2: 3}, {3: 2}][n] factors = {} # do simplistic factorization if verbose: sn = str(n) if len(sn) > 50: print('Factoring %s' % sn[:5] + \ '..(%i other digits)..' % (len(sn) - 10) + sn[-5:]) else: print('Factoring', n) if use_trial: # this is the preliminary factorization for small factors small = 2**15 fail_max = 600 small = min(small, limit or small) if verbose: print(trial_int_msg % (2, small, fail_max)) n, next_p = _factorint_small(factors, n, small, fail_max) else: next_p = 2 if factors and verbose: for k in sorted(factors): print(factor_msg % (k, factors[k])) if next_p == 0: if n > 1: factors[int(n)] = 1 if verbose: print(complete_msg) return factors # continue with more advanced factorization methods # first check if the simplistic run didn't finish # because of the limit and check for a perfect # power before exiting try: if limit and next_p > limit: if verbose: print('Exceeded limit:', limit) _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, verbose) if n > 1: factors[int(n)] = 1 return factors else: # Before quitting (or continuing on)... # ...do a Fermat test since it's so easy and we need the # square root anyway. Finding 2 factors is easy if they are # "close enough." This is the big root equivalent of dividing by # 2, 3, 5. sqrt_n = integer_nthroot(n, 2)[0] a = sqrt_n + 1 a2 = a**2 b2 = a2 - n for i in range(3): b, fermat = integer_nthroot(b2, 2) if fermat: break b2 += 2*a + 1 # equiv to (a + 1)**2 - n a += 1 if fermat: if verbose: print(fermat_msg) if limit: limit -= 1 for r in [a - b, a + b]: facs = factorint(r, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose) for k, v in facs.items(): factors[k] = factors.get(k, 0) + v raise StopIteration # ...see if factorization can be terminated _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, verbose) except StopIteration: if verbose: print(complete_msg) return factors # these are the limits for trial division which will # be attempted in parallel with pollard methods low, high = next_p, 2*next_p limit = limit or sqrt_n # add 1 to make sure limit is reached in primerange calls limit += 1 iteration = 0 while 1: try: high_ = high if limit < high_: high_ = limit # Trial division if use_trial: if verbose: print(trial_msg % (low, high_)) ps = sieve.primerange(low, high_) n, found_trial = _trial(factors, n, ps, verbose) if found_trial: _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, verbose) else: found_trial = False if high > limit: if verbose: print('Exceeded limit:', limit) if n > 1: factors[int(n)] = 1 raise StopIteration # Only used advanced methods when no small factors were found if not found_trial: if (use_pm1 or use_rho): high_root = max(int(math.log(high_**0.7)), low, 3) # Pollard p-1 if use_pm1: if verbose: print(pm1_msg % (high_root, high_)) c = pollard_pm1(n, B=high_root, seed=high_) if c: # factor it and let _trial do the update ps = factorint(c, limit=limit - 1, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, use_ecm=use_ecm, verbose=verbose) n, _ = _trial(factors, n, ps, verbose=False) _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, verbose) # Pollard rho if use_rho: max_steps = high_root if verbose: print(rho_msg % (1, max_steps, high_)) c = pollard_rho(n, retries=1, max_steps=max_steps, seed=high_) if c: # factor it and let _trial do the update ps = factorint(c, limit=limit - 1, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, use_ecm=use_ecm, verbose=verbose) n, _ = _trial(factors, n, ps, verbose=False) _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, verbose) except StopIteration: if verbose: print(complete_msg) return factors #Use subexponential algorithms if use_ecm #Use pollard algorithms for finding small factors for 3 iterations #if after small factors the number of digits of n is >= 20 then use ecm iteration += 1 if use_ecm and iteration >= 3 and len(str(n)) >= 25: break low, high = high, high*2 B1 = 10000 B2 = 100*B1 num_curves = 50 while(1): if verbose: print(ecm_msg % (B1, B2, num_curves)) while(1): try: factor = _ecm_one_factor(n, B1, B2, num_curves) ps = factorint(factor, limit=limit - 1, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, use_ecm=use_ecm, verbose=verbose) n, _ = _trial(factors, n, ps, verbose=False) _check_termination(factors, n, limit, use_trial, use_rho, use_pm1, verbose) except ValueError: break except StopIteration: if verbose: print(complete_msg) return factors B1 *= 5 B2 = 100*B1 num_curves *= 4 def factorrat(rat, limit=None, use_trial=True, use_rho=True, use_pm1=True, verbose=False, visual=None, multiple=False): r""" Given a Rational ``r``, ``factorrat(r)`` returns a dict containing the prime factors of ``r`` as keys and their respective multiplicities as values. For example: >>> from sympy import factorrat, S >>> factorrat(S(8)/9) # 8/9 = (2**3) * (3**-2) {2: 3, 3: -2} >>> factorrat(S(-1)/987) # -1/789 = -1 * (3**-1) * (7**-1) * (47**-1) {-1: 1, 3: -1, 7: -1, 47: -1} Please see the docstring for ``factorint`` for detailed explanations and examples of the following keywords: - ``limit``: Integer limit up to which trial division is done - ``use_trial``: Toggle use of trial division - ``use_rho``: Toggle use of Pollard's rho method - ``use_pm1``: Toggle use of Pollard's p-1 method - ``verbose``: Toggle detailed printing of progress - ``multiple``: Toggle returning a list of factors or dict - ``visual``: Toggle product form of output """ if multiple: fac = factorrat(rat, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose, visual=False, multiple=False) factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p]) for p, _ in sorted(fac.items(), key=lambda elem: elem[0] if elem[1] > 0 else 1/elem[0])), []) return factorlist f = factorint(rat.p, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose).copy() f = defaultdict(int, f) for p, e in factorint(rat.q, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose).items(): f[p] += -e if len(f) > 1 and 1 in f: del f[1] if not visual: return dict(f) else: if -1 in f: f.pop(-1) args = [S.NegativeOne] else: args = [] args.extend([Pow(*i, evaluate=False) for i in sorted(f.items())]) return Mul(*args, evaluate=False) def primefactors(n, limit=None, verbose=False): """Return a sorted list of n's prime factors, ignoring multiplicity and any composite factor that remains if the limit was set too low for complete factorization. Unlike factorint(), primefactors() does not return -1 or 0. Examples ======== >>> from sympy.ntheory import primefactors, factorint, isprime >>> primefactors(6) [2, 3] >>> primefactors(-5) [5] >>> sorted(factorint(123456).items()) [(2, 6), (3, 1), (643, 1)] >>> primefactors(123456) [2, 3, 643] >>> sorted(factorint(10000000001, limit=200).items()) [(101, 1), (99009901, 1)] >>> isprime(99009901) False >>> primefactors(10000000001, limit=300) [101] See Also ======== divisors """ n = int(n) factors = sorted(factorint(n, limit=limit, verbose=verbose).keys()) s = [f for f in factors[:-1:] if f not in [-1, 0, 1]] if factors and isprime(factors[-1]): s += [factors[-1]] return s def _divisors(n, proper=False): """Helper function for divisors which generates the divisors.""" factordict = factorint(n) ps = sorted(factordict.keys()) def rec_gen(n=0): if n == len(ps): yield 1 else: pows = [1] for j in range(factordict[ps[n]]): pows.append(pows[-1] * ps[n]) for q in rec_gen(n + 1): for p in pows: yield p * q if proper: for p in rec_gen(): if p != n: yield p else: yield from rec_gen() def divisors(n, generator=False, proper=False): r""" Return all divisors of n sorted from 1..n by default. If generator is ``True`` an unordered generator is returned. The number of divisors of n can be quite large if there are many prime factors (counting repeated factors). If only the number of factors is desired use divisor_count(n). Examples ======== >>> from sympy import divisors, divisor_count >>> divisors(24) [1, 2, 3, 4, 6, 8, 12, 24] >>> divisor_count(24) 8 >>> list(divisors(120, generator=True)) [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60, 120] Notes ===== This is a slightly modified version of Tim Peters referenced at: https://stackoverflow.com/questions/1010381/python-factorization See Also ======== primefactors, factorint, divisor_count """ n = as_int(abs(n)) if isprime(n): if proper: return [1] return [1, n] if n == 1: if proper: return [] return [1] if n == 0: return [] rv = _divisors(n, proper) if not generator: return sorted(rv) return rv def divisor_count(n, modulus=1, proper=False): """ Return the number of divisors of ``n``. If ``modulus`` is not 1 then only those that are divisible by ``modulus`` are counted. If ``proper`` is True then the divisor of ``n`` will not be counted. Examples ======== >>> from sympy import divisor_count >>> divisor_count(6) 4 >>> divisor_count(6, 2) 2 >>> divisor_count(6, proper=True) 3 See Also ======== factorint, divisors, totient, proper_divisor_count """ if not modulus: return 0 elif modulus != 1: n, r = divmod(n, modulus) if r: return 0 if n == 0: return 0 n = Mul(*[v + 1 for k, v in factorint(n).items() if k > 1]) if n and proper: n -= 1 return n def proper_divisors(n, generator=False): """ Return all divisors of n except n, sorted by default. If generator is ``True`` an unordered generator is returned. Examples ======== >>> from sympy import proper_divisors, proper_divisor_count >>> proper_divisors(24) [1, 2, 3, 4, 6, 8, 12] >>> proper_divisor_count(24) 7 >>> list(proper_divisors(120, generator=True)) [1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60] See Also ======== factorint, divisors, proper_divisor_count """ return divisors(n, generator=generator, proper=True) def proper_divisor_count(n, modulus=1): """ Return the number of proper divisors of ``n``. Examples ======== >>> from sympy import proper_divisor_count >>> proper_divisor_count(6) 3 >>> proper_divisor_count(6, modulus=2) 1 See Also ======== divisors, proper_divisors, divisor_count """ return divisor_count(n, modulus=modulus, proper=True) def _udivisors(n): """Helper function for udivisors which generates the unitary divisors.""" factorpows = [p**e for p, e in factorint(n).items()] for i in range(2**len(factorpows)): d, j, k = 1, i, 0 while j: if (j & 1): d *= factorpows[k] j >>= 1 k += 1 yield d def udivisors(n, generator=False): r""" Return all unitary divisors of n sorted from 1..n by default. If generator is ``True`` an unordered generator is returned. The number of unitary divisors of n can be quite large if there are many prime factors. If only the number of unitary divisors is desired use udivisor_count(n). Examples ======== >>> from sympy.ntheory.factor_ import udivisors, udivisor_count >>> udivisors(15) [1, 3, 5, 15] >>> udivisor_count(15) 4 >>> sorted(udivisors(120, generator=True)) [1, 3, 5, 8, 15, 24, 40, 120] See Also ======== primefactors, factorint, divisors, divisor_count, udivisor_count References ========== .. [1] https://en.wikipedia.org/wiki/Unitary_divisor .. [2] http://mathworld.wolfram.com/UnitaryDivisor.html """ n = as_int(abs(n)) if isprime(n): return [1, n] if n == 1: return [1] if n == 0: return [] rv = _udivisors(n) if not generator: return sorted(rv) return rv def udivisor_count(n): """ Return the number of unitary divisors of ``n``. Parameters ========== n : integer Examples ======== >>> from sympy.ntheory.factor_ import udivisor_count >>> udivisor_count(120) 8 See Also ======== factorint, divisors, udivisors, divisor_count, totient References ========== .. [1] http://mathworld.wolfram.com/UnitaryDivisorFunction.html """ if n == 0: return 0 return 2**len([p for p in factorint(n) if p > 1]) def _antidivisors(n): """Helper function for antidivisors which generates the antidivisors.""" for d in _divisors(n): y = 2*d if n > y and n % y: yield y for d in _divisors(2*n-1): if n > d >= 2 and n % d: yield d for d in _divisors(2*n+1): if n > d >= 2 and n % d: yield d def antidivisors(n, generator=False): r""" Return all antidivisors of n sorted from 1..n by default. Antidivisors [1]_ of n are numbers that do not divide n by the largest possible margin. If generator is True an unordered generator is returned. Examples ======== >>> from sympy.ntheory.factor_ import antidivisors >>> antidivisors(24) [7, 16] >>> sorted(antidivisors(128, generator=True)) [3, 5, 15, 17, 51, 85] See Also ======== primefactors, factorint, divisors, divisor_count, antidivisor_count References ========== .. [1] definition is described in https://oeis.org/A066272/a066272a.html """ n = as_int(abs(n)) if n <= 2: return [] rv = _antidivisors(n) if not generator: return sorted(rv) return rv def antidivisor_count(n): """ Return the number of antidivisors [1]_ of ``n``. Parameters ========== n : integer Examples ======== >>> from sympy.ntheory.factor_ import antidivisor_count >>> antidivisor_count(13) 4 >>> antidivisor_count(27) 5 See Also ======== factorint, divisors, antidivisors, divisor_count, totient References ========== .. [1] formula from https://oeis.org/A066272 """ n = as_int(abs(n)) if n <= 2: return 0 return divisor_count(2*n - 1) + divisor_count(2*n + 1) + \ divisor_count(n) - divisor_count(n, 2) - 5 class totient(Function): r""" Calculate the Euler totient function phi(n) ``totient(n)`` or `\phi(n)` is the number of positive integers `\leq` n that are relatively prime to n. Parameters ========== n : integer Examples ======== >>> from sympy.ntheory import totient >>> totient(1) 1 >>> totient(25) 20 >>> totient(45) == totient(5)*totient(9) True See Also ======== divisor_count References ========== .. [1] https://en.wikipedia.org/wiki/Euler%27s_totient_function .. [2] http://mathworld.wolfram.com/TotientFunction.html """ @classmethod def eval(cls, n): n = sympify(n) if n.is_Integer: if n < 1: raise ValueError("n must be a positive integer") factors = factorint(n) return cls._from_factors(factors) elif not isinstance(n, Expr) or (n.is_integer is False) or (n.is_positive is False): raise ValueError("n must be a positive integer") def _eval_is_integer(self): return fuzzy_and([self.args[0].is_integer, self.args[0].is_positive]) @classmethod def _from_distinct_primes(self, *args): """Subroutine to compute totient from the list of assumed distinct primes Examples ======== >>> from sympy.ntheory.factor_ import totient >>> totient._from_distinct_primes(5, 7) 24 """ from functools import reduce return reduce(lambda i, j: i * (j-1), args, 1) @classmethod def _from_factors(self, factors): """Subroutine to compute totient from already-computed factors Examples ======== >>> from sympy.ntheory.factor_ import totient >>> totient._from_factors({5: 2}) 20 """ t = 1 for p, k in factors.items(): t *= (p - 1) * p**(k - 1) return t class reduced_totient(Function): r""" Calculate the Carmichael reduced totient function lambda(n) ``reduced_totient(n)`` or `\lambda(n)` is the smallest m > 0 such that `k^m \equiv 1 \mod n` for all k relatively prime to n. Examples ======== >>> from sympy.ntheory import reduced_totient >>> reduced_totient(1) 1 >>> reduced_totient(8) 2 >>> reduced_totient(30) 4 See Also ======== totient References ========== .. [1] https://en.wikipedia.org/wiki/Carmichael_function .. [2] http://mathworld.wolfram.com/CarmichaelFunction.html """ @classmethod def eval(cls, n): n = sympify(n) if n.is_Integer: if n < 1: raise ValueError("n must be a positive integer") factors = factorint(n) return cls._from_factors(factors) @classmethod def _from_factors(self, factors): """Subroutine to compute totient from already-computed factors """ t = 1 for p, k in factors.items(): if p == 2 and k > 2: t = ilcm(t, 2**(k - 2)) else: t = ilcm(t, (p - 1) * p**(k - 1)) return t @classmethod def _from_distinct_primes(self, *args): """Subroutine to compute totient from the list of assumed distinct primes """ args = [p - 1 for p in args] return ilcm(*args) def _eval_is_integer(self): return fuzzy_and([self.args[0].is_integer, self.args[0].is_positive]) class divisor_sigma(Function): r""" Calculate the divisor function `\sigma_k(n)` for positive integer n ``divisor_sigma(n, k)`` is equal to ``sum([x**k for x in divisors(n)])`` If n's prime factorization is: .. math :: n = \prod_{i=1}^\omega p_i^{m_i}, then .. math :: \sigma_k(n) = \prod_{i=1}^\omega (1+p_i^k+p_i^{2k}+\cdots + p_i^{m_ik}). Parameters ========== n : integer k : integer, optional power of divisors in the sum for k = 0, 1: ``divisor_sigma(n, 0)`` is equal to ``divisor_count(n)`` ``divisor_sigma(n, 1)`` is equal to ``sum(divisors(n))`` Default for k is 1. Examples ======== >>> from sympy.ntheory import divisor_sigma >>> divisor_sigma(18, 0) 6 >>> divisor_sigma(39, 1) 56 >>> divisor_sigma(12, 2) 210 >>> divisor_sigma(37) 38 See Also ======== divisor_count, totient, divisors, factorint References ========== .. [1] https://en.wikipedia.org/wiki/Divisor_function """ @classmethod def eval(cls, n, k=1): n = sympify(n) k = sympify(k) if n.is_prime: return 1 + n**k if n.is_Integer: if n <= 0: raise ValueError("n must be a positive integer") elif k.is_Integer: k = int(k) return Integer(prod( (p**(k*(e + 1)) - 1)//(p**k - 1) if k != 0 else e + 1 for p, e in factorint(n).items())) else: return Mul(*[(p**(k*(e + 1)) - 1)/(p**k - 1) if k != 0 else e + 1 for p, e in factorint(n).items()]) if n.is_integer: # symbolic case args = [] for p, e in (_.as_base_exp() for _ in Mul.make_args(n)): if p.is_prime and e.is_positive: args.append((p**(k*(e + 1)) - 1)/(p**k - 1) if k != 0 else e + 1) else: return return Mul(*args) def core(n, t=2): r""" Calculate core(n, t) = `core_t(n)` of a positive integer n ``core_2(n)`` is equal to the squarefree part of n If n's prime factorization is: .. math :: n = \prod_{i=1}^\omega p_i^{m_i}, then .. math :: core_t(n) = \prod_{i=1}^\omega p_i^{m_i \mod t}. Parameters ========== n : integer t : integer core(n, t) calculates the t-th power free part of n ``core(n, 2)`` is the squarefree part of ``n`` ``core(n, 3)`` is the cubefree part of ``n`` Default for t is 2. Examples ======== >>> from sympy.ntheory.factor_ import core >>> core(24, 2) 6 >>> core(9424, 3) 1178 >>> core(379238) 379238 >>> core(15**11, 10) 15 See Also ======== factorint, sympy.solvers.diophantine.diophantine.square_factor References ========== .. [1] https://en.wikipedia.org/wiki/Square-free_integer#Squarefree_core """ n = as_int(n) t = as_int(t) if n <= 0: raise ValueError("n must be a positive integer") elif t <= 1: raise ValueError("t must be >= 2") else: y = 1 for p, e in factorint(n).items(): y *= p**(e % t) return y class udivisor_sigma(Function): r""" Calculate the unitary divisor function `\sigma_k^*(n)` for positive integer n ``udivisor_sigma(n, k)`` is equal to ``sum([x**k for x in udivisors(n)])`` If n's prime factorization is: .. math :: n = \prod_{i=1}^\omega p_i^{m_i}, then .. math :: \sigma_k^*(n) = \prod_{i=1}^\omega (1+ p_i^{m_ik}). Parameters ========== k : power of divisors in the sum for k = 0, 1: ``udivisor_sigma(n, 0)`` is equal to ``udivisor_count(n)`` ``udivisor_sigma(n, 1)`` is equal to ``sum(udivisors(n))`` Default for k is 1. Examples ======== >>> from sympy.ntheory.factor_ import udivisor_sigma >>> udivisor_sigma(18, 0) 4 >>> udivisor_sigma(74, 1) 114 >>> udivisor_sigma(36, 3) 47450 >>> udivisor_sigma(111) 152 See Also ======== divisor_count, totient, divisors, udivisors, udivisor_count, divisor_sigma, factorint References ========== .. [1] http://mathworld.wolfram.com/UnitaryDivisorFunction.html """ @classmethod def eval(cls, n, k=1): n = sympify(n) k = sympify(k) if n.is_prime: return 1 + n**k if n.is_Integer: if n <= 0: raise ValueError("n must be a positive integer") else: return Mul(*[1+p**(k*e) for p, e in factorint(n).items()]) class primenu(Function): r""" Calculate the number of distinct prime factors for a positive integer n. If n's prime factorization is: .. math :: n = \prod_{i=1}^k p_i^{m_i}, then ``primenu(n)`` or `\nu(n)` is: .. math :: \nu(n) = k. Examples ======== >>> from sympy.ntheory.factor_ import primenu >>> primenu(1) 0 >>> primenu(30) 3 See Also ======== factorint References ========== .. [1] http://mathworld.wolfram.com/PrimeFactor.html """ @classmethod def eval(cls, n): n = sympify(n) if n.is_Integer: if n <= 0: raise ValueError("n must be a positive integer") else: return len(factorint(n).keys()) class primeomega(Function): r""" Calculate the number of prime factors counting multiplicities for a positive integer n. If n's prime factorization is: .. math :: n = \prod_{i=1}^k p_i^{m_i}, then ``primeomega(n)`` or `\Omega(n)` is: .. math :: \Omega(n) = \sum_{i=1}^k m_i. Examples ======== >>> from sympy.ntheory.factor_ import primeomega >>> primeomega(1) 0 >>> primeomega(20) 3 See Also ======== factorint References ========== .. [1] http://mathworld.wolfram.com/PrimeFactor.html """ @classmethod def eval(cls, n): n = sympify(n) if n.is_Integer: if n <= 0: raise ValueError("n must be a positive integer") else: return sum(factorint(n).values()) def mersenne_prime_exponent(nth): """Returns the exponent ``i`` for the nth Mersenne prime (which has the form `2^i - 1`). Examples ======== >>> from sympy.ntheory.factor_ import mersenne_prime_exponent >>> mersenne_prime_exponent(1) 2 >>> mersenne_prime_exponent(20) 4423 """ n = as_int(nth) if n < 1: raise ValueError("nth must be a positive integer; mersenne_prime_exponent(1) == 2") if n > 51: raise ValueError("There are only 51 perfect numbers; nth must be less than or equal to 51") return MERSENNE_PRIME_EXPONENTS[n - 1] def is_perfect(n): """Returns True if ``n`` is a perfect number, else False. A perfect number is equal to the sum of its positive, proper divisors. Examples ======== >>> from sympy.ntheory.factor_ import is_perfect, divisors, divisor_sigma >>> is_perfect(20) False >>> is_perfect(6) True >>> 6 == divisor_sigma(6) - 6 == sum(divisors(6)[:-1]) True References ========== .. [1] http://mathworld.wolfram.com/PerfectNumber.html .. [2] https://en.wikipedia.org/wiki/Perfect_number """ n = as_int(n) if _isperfect(n): return True # all perfect numbers for Mersenne primes with exponents # less than or equal to 43112609 are known iknow = MERSENNE_PRIME_EXPONENTS.index(43112609) if iknow <= len(PERFECT) - 1 and n <= PERFECT[iknow]: # there may be gaps between this and larger known values # so only conclude in the range for which all values # are known return False if n%2 == 0: last2 = n % 100 if last2 != 28 and last2 % 10 != 6: return False r, b = integer_nthroot(1 + 8*n, 2) if not b: return False m, x = divmod(1 + r, 4) if x: return False e, b = integer_log(m, 2) if not b: return False else: if n < 10**2000: # http://www.lirmm.fr/~ochem/opn/ return False if n % 105 == 0: # not divis by 105 return False if not any(n%m == r for m, r in [(12, 1), (468, 117), (324, 81)]): return False # there are many criteria that the factor structure of n # must meet; since we will have to factor it to test the # structure we will have the factors and can then check # to see whether it is a perfect number or not. So we # skip the structure checks and go straight to the final # test below. rv = divisor_sigma(n) - n if rv == n: if n%2 == 0: raise ValueError(filldedent(''' This even number is perfect and is associated with a Mersenne Prime, 2^%s - 1. It should be added to SymPy.''' % (e + 1))) else: raise ValueError(filldedent('''In 1888, Sylvester stated: " ...a prolonged meditation on the subject has satisfied me that the existence of any one such [odd perfect number] -- its escape, so to say, from the complex web of conditions which hem it in on all sides -- would be little short of a miracle." I guess SymPy just found that miracle and it factors like this: %s''' % factorint(n))) def is_mersenne_prime(n): """Returns True if ``n`` is a Mersenne prime, else False. A Mersenne prime is a prime number having the form `2^i - 1`. Examples ======== >>> from sympy.ntheory.factor_ import is_mersenne_prime >>> is_mersenne_prime(6) False >>> is_mersenne_prime(127) True References ========== .. [1] http://mathworld.wolfram.com/MersennePrime.html """ n = as_int(n) if _ismersenneprime(n): return True if not isprime(n): return False r, b = integer_log(n + 1, 2) if not b: return False raise ValueError(filldedent(''' This Mersenne Prime, 2^%s - 1, should be added to SymPy's known values.''' % r)) def abundance(n): """Returns the difference between the sum of the positive proper divisors of a number and the number. Examples ======== >>> from sympy.ntheory import abundance, is_perfect, is_abundant >>> abundance(6) 0 >>> is_perfect(6) True >>> abundance(10) -2 >>> is_abundant(10) False """ return divisor_sigma(n, 1) - 2 * n def is_abundant(n): """Returns True if ``n`` is an abundant number, else False. A abundant number is smaller than the sum of its positive proper divisors. Examples ======== >>> from sympy.ntheory.factor_ import is_abundant >>> is_abundant(20) True >>> is_abundant(15) False References ========== .. [1] http://mathworld.wolfram.com/AbundantNumber.html """ n = as_int(n) if is_perfect(n): return False return n % 6 == 0 or bool(abundance(n) > 0) def is_deficient(n): """Returns True if ``n`` is a deficient number, else False. A deficient number is greater than the sum of its positive proper divisors. Examples ======== >>> from sympy.ntheory.factor_ import is_deficient >>> is_deficient(20) False >>> is_deficient(15) True References ========== .. [1] http://mathworld.wolfram.com/DeficientNumber.html """ n = as_int(n) if is_perfect(n): return False return bool(abundance(n) < 0) def is_amicable(m, n): """Returns True if the numbers `m` and `n` are "amicable", else False. Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to that of the other. Examples ======== >>> from sympy.ntheory.factor_ import is_amicable, divisor_sigma >>> is_amicable(220, 284) True >>> divisor_sigma(220) == divisor_sigma(284) True References ========== .. [1] https://en.wikipedia.org/wiki/Amicable_numbers """ if m == n: return False a, b = map(lambda i: divisor_sigma(i), (m, n)) return a == b == (m + n) def dra(n, b): """ Returns the additive digital root of a natural number ``n`` in base ``b`` which is a single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. Examples ======== >>> from sympy.ntheory.factor_ import dra >>> dra(3110, 12) 8 References ========== .. [1] https://en.wikipedia.org/wiki/Digital_root """ num = abs(as_int(n)) b = as_int(b) if b <= 1: raise ValueError("Base should be an integer greater than 1") if num == 0: return 0 return (1 + (num - 1) % (b - 1)) def drm(n, b): """ Returns the multiplicative digital root of a natural number ``n`` in a given base ``b`` which is a single digit value obtained by an iterative process of multiplying digits, on each iteration using the result from the previous iteration to compute the digit multiplication. Examples ======== >>> from sympy.ntheory.factor_ import drm >>> drm(9876, 10) 0 >>> drm(49, 10) 8 References ========== .. [1] http://mathworld.wolfram.com/MultiplicativeDigitalRoot.html """ n = abs(as_int(n)) b = as_int(b) if b <= 1: raise ValueError("Base should be an integer greater than 1") while n > b: mul = 1 while n > 1: n, r = divmod(n, b) if r == 0: return 0 mul *= r n = mul return n
23afdedfc33aea659daf86ff39acd5a992aec7909bbbf00b79bc7ee19090fe7b
from sympy.core.random import randrange, choice from math import log from sympy.ntheory import primefactors from sympy.core.symbol import Symbol from sympy.ntheory.factor_ import (factorint, multiplicity) from sympy.combinatorics import Permutation from sympy.combinatorics.permutations import (_af_commutes_with, _af_invert, _af_rmul, _af_rmuln, _af_pow, Cycle) from sympy.combinatorics.util import (_check_cycles_alt_sym, _distribute_gens_by_base, _orbits_transversals_from_bsgs, _handle_precomputed_bsgs, _base_ordering, _strong_gens_from_distr, _strip, _strip_af) from sympy.core import Basic from sympy.functions.combinatorial.factorials import factorial from sympy.ntheory import sieve from sympy.utilities.iterables import has_variety, is_sequence, uniq from sympy.core.random import _randrange from itertools import islice from sympy.core.sympify import _sympify rmul = Permutation.rmul_with_af _af_new = Permutation._af_new class PermutationGroup(Basic): r"""The class defining a Permutation group. Explanation =========== ``PermutationGroup([p1, p2, ..., pn])`` returns the permutation group generated by the list of permutations. This group can be supplied to Polyhedron if one desires to decorate the elements to which the indices of the permutation refer. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.polyhedron import Polyhedron >>> from sympy.combinatorics.perm_groups import PermutationGroup The permutations corresponding to motion of the front, right and bottom face of a $2 \times 2$ Rubik's cube are defined: >>> F = Permutation(2, 19, 21, 8)(3, 17, 20, 10)(4, 6, 7, 5) >>> R = Permutation(1, 5, 21, 14)(3, 7, 23, 12)(8, 10, 11, 9) >>> D = Permutation(6, 18, 14, 10)(7, 19, 15, 11)(20, 22, 23, 21) These are passed as permutations to PermutationGroup: >>> G = PermutationGroup(F, R, D) >>> G.order() 3674160 The group can be supplied to a Polyhedron in order to track the objects being moved. An example involving the $2 \times 2$ Rubik's cube is given there, but here is a simple demonstration: >>> a = Permutation(2, 1) >>> b = Permutation(1, 0) >>> G = PermutationGroup(a, b) >>> P = Polyhedron(list('ABC'), pgroup=G) >>> P.corners (A, B, C) >>> P.rotate(0) # apply permutation 0 >>> P.corners (A, C, B) >>> P.reset() >>> P.corners (A, B, C) Or one can make a permutation as a product of selected permutations and apply them to an iterable directly: >>> P10 = G.make_perm([0, 1]) >>> P10('ABC') ['C', 'A', 'B'] See Also ======== sympy.combinatorics.polyhedron.Polyhedron, sympy.combinatorics.permutations.Permutation References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" .. [2] Seress, A. "Permutation Group Algorithms" .. [3] https://en.wikipedia.org/wiki/Schreier_vector .. [4] https://en.wikipedia.org/wiki/Nielsen_transformation#Product_replacement_algorithm .. [5] Frank Celler, Charles R.Leedham-Green, Scott H.Murray, Alice C.Niemeyer, and E.A.O'Brien. "Generating Random Elements of a Finite Group" .. [6] https://en.wikipedia.org/wiki/Block_%28permutation_group_theory%29 .. [7] http://www.algorithmist.com/index.php/Union_Find .. [8] https://en.wikipedia.org/wiki/Multiply_transitive_group#Multiply_transitive_groups .. [9] https://en.wikipedia.org/wiki/Center_%28group_theory%29 .. [10] https://en.wikipedia.org/wiki/Centralizer_and_normalizer .. [11] http://groupprops.subwiki.org/wiki/Derived_subgroup .. [12] https://en.wikipedia.org/wiki/Nilpotent_group .. [13] http://www.math.colostate.edu/~hulpke/CGT/cgtnotes.pdf .. [14] https://www.gap-system.org/Manuals/doc/ref/manual.pdf """ is_group = True def __new__(cls, *args, dups=True, **kwargs): """The default constructor. Accepts Cycle and Permutation forms. Removes duplicates unless ``dups`` keyword is ``False``. """ if not args: args = [Permutation()] else: args = list(args[0] if is_sequence(args[0]) else args) if not args: args = [Permutation()] if any(isinstance(a, Cycle) for a in args): args = [Permutation(a) for a in args] if has_variety(a.size for a in args): degree = kwargs.pop('degree', None) if degree is None: degree = max(a.size for a in args) for i in range(len(args)): if args[i].size != degree: args[i] = Permutation(args[i], size=degree) if dups: args = list(uniq([_af_new(list(a)) for a in args])) if len(args) > 1: args = [g for g in args if not g.is_identity] return Basic.__new__(cls, *args, **kwargs) def __init__(self, *args, **kwargs): self._generators = list(self.args) self._order = None self._center = [] self._is_abelian = None self._is_transitive = None self._is_sym = None self._is_alt = None self._is_primitive = None self._is_nilpotent = None self._is_solvable = None self._is_trivial = None self._transitivity_degree = None self._max_div = None self._is_perfect = None self._is_cyclic = None self._r = len(self._generators) self._degree = self._generators[0].size # these attributes are assigned after running schreier_sims self._base = [] self._strong_gens = [] self._strong_gens_slp = [] self._basic_orbits = [] self._transversals = [] self._transversal_slp = [] # these attributes are assigned after running _random_pr_init self._random_gens = [] # finite presentation of the group as an instance of `FpGroup` self._fp_presentation = None def __getitem__(self, i): return self._generators[i] def __contains__(self, i): """Return ``True`` if *i* is contained in PermutationGroup. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> p = Permutation(1, 2, 3) >>> Permutation(3) in PermutationGroup(p) True """ if not isinstance(i, Permutation): raise TypeError("A PermutationGroup contains only Permutations as " "elements, not elements of type %s" % type(i)) return self.contains(i) def __len__(self): return len(self._generators) def equals(self, other): """Return ``True`` if PermutationGroup generated by elements in the group are same i.e they represent the same PermutationGroup. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> p = Permutation(0, 1, 2, 3, 4, 5) >>> G = PermutationGroup([p, p**2]) >>> H = PermutationGroup([p**2, p]) >>> G.generators == H.generators False >>> G.equals(H) True """ if not isinstance(other, PermutationGroup): return False set_self_gens = set(self.generators) set_other_gens = set(other.generators) # before reaching the general case there are also certain # optimisation and obvious cases requiring less or no actual # computation. if set_self_gens == set_other_gens: return True # in the most general case it will check that each generator of # one group belongs to the other PermutationGroup and vice-versa for gen1 in set_self_gens: if not other.contains(gen1): return False for gen2 in set_other_gens: if not self.contains(gen2): return False return True def __mul__(self, other): """ Return the direct product of two permutation groups as a permutation group. Explanation =========== This implementation realizes the direct product by shifting the index set for the generators of the second group: so if we have ``G`` acting on ``n1`` points and ``H`` acting on ``n2`` points, ``G*H`` acts on ``n1 + n2`` points. Examples ======== >>> from sympy.combinatorics.named_groups import CyclicGroup >>> G = CyclicGroup(5) >>> H = G*G >>> H PermutationGroup([ (9)(0 1 2 3 4), (5 6 7 8 9)]) >>> H.order() 25 """ if isinstance(other, Permutation): return Coset(other, self, dir='+') gens1 = [perm._array_form for perm in self.generators] gens2 = [perm._array_form for perm in other.generators] n1 = self._degree n2 = other._degree start = list(range(n1)) end = list(range(n1, n1 + n2)) for i in range(len(gens2)): gens2[i] = [x + n1 for x in gens2[i]] gens2 = [start + gen for gen in gens2] gens1 = [gen + end for gen in gens1] together = gens1 + gens2 gens = [_af_new(x) for x in together] return PermutationGroup(gens) def _random_pr_init(self, r, n, _random_prec_n=None): r"""Initialize random generators for the product replacement algorithm. Explanation =========== The implementation uses a modification of the original product replacement algorithm due to Leedham-Green, as described in [1], pp. 69-71; also, see [2], pp. 27-29 for a detailed theoretical analysis of the original product replacement algorithm, and [4]. The product replacement algorithm is used for producing random, uniformly distributed elements of a group `G` with a set of generators `S`. For the initialization ``_random_pr_init``, a list ``R`` of `\max\{r, |S|\}` group generators is created as the attribute ``G._random_gens``, repeating elements of `S` if necessary, and the identity element of `G` is appended to ``R`` - we shall refer to this last element as the accumulator. Then the function ``random_pr()`` is called ``n`` times, randomizing the list ``R`` while preserving the generation of `G` by ``R``. The function ``random_pr()`` itself takes two random elements ``g, h`` among all elements of ``R`` but the accumulator and replaces ``g`` with a randomly chosen element from `\{gh, g(~h), hg, (~h)g\}`. Then the accumulator is multiplied by whatever ``g`` was replaced by. The new value of the accumulator is then returned by ``random_pr()``. The elements returned will eventually (for ``n`` large enough) become uniformly distributed across `G` ([5]). For practical purposes however, the values ``n = 50, r = 11`` are suggested in [1]. Notes ===== THIS FUNCTION HAS SIDE EFFECTS: it changes the attribute self._random_gens See Also ======== random_pr """ deg = self.degree random_gens = [x._array_form for x in self.generators] k = len(random_gens) if k < r: for i in range(k, r): random_gens.append(random_gens[i - k]) acc = list(range(deg)) random_gens.append(acc) self._random_gens = random_gens # handle randomized input for testing purposes if _random_prec_n is None: for i in range(n): self.random_pr() else: for i in range(n): self.random_pr(_random_prec=_random_prec_n[i]) def _union_find_merge(self, first, second, ranks, parents, not_rep): """Merges two classes in a union-find data structure. Explanation =========== Used in the implementation of Atkinson's algorithm as suggested in [1], pp. 83-87. The class merging process uses union by rank as an optimization. ([7]) Notes ===== THIS FUNCTION HAS SIDE EFFECTS: the list of class representatives, ``parents``, the list of class sizes, ``ranks``, and the list of elements that are not representatives, ``not_rep``, are changed due to class merging. See Also ======== minimal_block, _union_find_rep References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory" .. [7] http://www.algorithmist.com/index.php/Union_Find """ rep_first = self._union_find_rep(first, parents) rep_second = self._union_find_rep(second, parents) if rep_first != rep_second: # union by rank if ranks[rep_first] >= ranks[rep_second]: new_1, new_2 = rep_first, rep_second else: new_1, new_2 = rep_second, rep_first total_rank = ranks[new_1] + ranks[new_2] if total_rank > self.max_div: return -1 parents[new_2] = new_1 ranks[new_1] = total_rank not_rep.append(new_2) return 1 return 0 def _union_find_rep(self, num, parents): """Find representative of a class in a union-find data structure. Explanation =========== Used in the implementation of Atkinson's algorithm as suggested in [1], pp. 83-87. After the representative of the class to which ``num`` belongs is found, path compression is performed as an optimization ([7]). Notes ===== THIS FUNCTION HAS SIDE EFFECTS: the list of class representatives, ``parents``, is altered due to path compression. See Also ======== minimal_block, _union_find_merge References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory" .. [7] http://www.algorithmist.com/index.php/Union_Find """ rep, parent = num, parents[num] while parent != rep: rep = parent parent = parents[rep] # path compression temp, parent = num, parents[num] while parent != rep: parents[temp] = rep temp = parent parent = parents[temp] return rep @property def base(self): r"""Return a base from the Schreier-Sims algorithm. Explanation =========== For a permutation group `G`, a base is a sequence of points `B = (b_1, b_2, \dots, b_k)` such that no element of `G` apart from the identity fixes all the points in `B`. The concepts of a base and strong generating set and their applications are discussed in depth in [1], pp. 87-89 and [2], pp. 55-57. An alternative way to think of `B` is that it gives the indices of the stabilizer cosets that contain more than the identity permutation. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> G = PermutationGroup([Permutation(0, 1, 3)(2, 4)]) >>> G.base [0, 2] See Also ======== strong_gens, basic_transversals, basic_orbits, basic_stabilizers """ if self._base == []: self.schreier_sims() return self._base def baseswap(self, base, strong_gens, pos, randomized=False, transversals=None, basic_orbits=None, strong_gens_distr=None): r"""Swap two consecutive base points in base and strong generating set. Explanation =========== If a base for a group `G` is given by `(b_1, b_2, \dots, b_k)`, this function returns a base `(b_1, b_2, \dots, b_{i+1}, b_i, \dots, b_k)`, where `i` is given by ``pos``, and a strong generating set relative to that base. The original base and strong generating set are not modified. The randomized version (default) is of Las Vegas type. Parameters ========== base, strong_gens The base and strong generating set. pos The position at which swapping is performed. randomized A switch between randomized and deterministic version. transversals The transversals for the basic orbits, if known. basic_orbits The basic orbits, if known. strong_gens_distr The strong generators distributed by basic stabilizers, if known. Returns ======= (base, strong_gens) ``base`` is the new base, and ``strong_gens`` is a generating set relative to it. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.testutil import _verify_bsgs >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> S = SymmetricGroup(4) >>> S.schreier_sims() >>> S.base [0, 1, 2] >>> base, gens = S.baseswap(S.base, S.strong_gens, 1, randomized=False) >>> base, gens ([0, 2, 1], [(0 1 2 3), (3)(0 1), (1 3 2), (2 3), (1 3)]) check that base, gens is a BSGS >>> S1 = PermutationGroup(gens) >>> _verify_bsgs(S1, base, gens) True See Also ======== schreier_sims Notes ===== The deterministic version of the algorithm is discussed in [1], pp. 102-103; the randomized version is discussed in [1], p.103, and [2], p.98. It is of Las Vegas type. Notice that [1] contains a mistake in the pseudocode and discussion of BASESWAP: on line 3 of the pseudocode, `|\beta_{i+1}^{\left\langle T\right\rangle}|` should be replaced by `|\beta_{i}^{\left\langle T\right\rangle}|`, and the same for the discussion of the algorithm. """ # construct the basic orbits, generators for the stabilizer chain # and transversal elements from whatever was provided transversals, basic_orbits, strong_gens_distr = \ _handle_precomputed_bsgs(base, strong_gens, transversals, basic_orbits, strong_gens_distr) base_len = len(base) degree = self.degree # size of orbit of base[pos] under the stabilizer we seek to insert # in the stabilizer chain at position pos + 1 size = len(basic_orbits[pos])*len(basic_orbits[pos + 1]) \ //len(_orbit(degree, strong_gens_distr[pos], base[pos + 1])) # initialize the wanted stabilizer by a subgroup if pos + 2 > base_len - 1: T = [] else: T = strong_gens_distr[pos + 2][:] # randomized version if randomized is True: stab_pos = PermutationGroup(strong_gens_distr[pos]) schreier_vector = stab_pos.schreier_vector(base[pos + 1]) # add random elements of the stabilizer until they generate it while len(_orbit(degree, T, base[pos])) != size: new = stab_pos.random_stab(base[pos + 1], schreier_vector=schreier_vector) T.append(new) # deterministic version else: Gamma = set(basic_orbits[pos]) Gamma.remove(base[pos]) if base[pos + 1] in Gamma: Gamma.remove(base[pos + 1]) # add elements of the stabilizer until they generate it by # ruling out member of the basic orbit of base[pos] along the way while len(_orbit(degree, T, base[pos])) != size: gamma = next(iter(Gamma)) x = transversals[pos][gamma] temp = x._array_form.index(base[pos + 1]) # (~x)(base[pos + 1]) if temp not in basic_orbits[pos + 1]: Gamma = Gamma - _orbit(degree, T, gamma) else: y = transversals[pos + 1][temp] el = rmul(x, y) if el(base[pos]) not in _orbit(degree, T, base[pos]): T.append(el) Gamma = Gamma - _orbit(degree, T, base[pos]) # build the new base and strong generating set strong_gens_new_distr = strong_gens_distr[:] strong_gens_new_distr[pos + 1] = T base_new = base[:] base_new[pos], base_new[pos + 1] = base_new[pos + 1], base_new[pos] strong_gens_new = _strong_gens_from_distr(strong_gens_new_distr) for gen in T: if gen not in strong_gens_new: strong_gens_new.append(gen) return base_new, strong_gens_new @property def basic_orbits(self): r""" Return the basic orbits relative to a base and strong generating set. Explanation =========== If `(b_1, b_2, \dots, b_k)` is a base for a group `G`, and `G^{(i)} = G_{b_1, b_2, \dots, b_{i-1}}` is the ``i``-th basic stabilizer (so that `G^{(1)} = G`), the ``i``-th basic orbit relative to this base is the orbit of `b_i` under `G^{(i)}`. See [1], pp. 87-89 for more information. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(4) >>> S.basic_orbits [[0, 1, 2, 3], [1, 2, 3], [2, 3]] See Also ======== base, strong_gens, basic_transversals, basic_stabilizers """ if self._basic_orbits == []: self.schreier_sims() return self._basic_orbits @property def basic_stabilizers(self): r""" Return a chain of stabilizers relative to a base and strong generating set. Explanation =========== The ``i``-th basic stabilizer `G^{(i)}` relative to a base `(b_1, b_2, \dots, b_k)` is `G_{b_1, b_2, \dots, b_{i-1}}`. For more information, see [1], pp. 87-89. Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> A = AlternatingGroup(4) >>> A.schreier_sims() >>> A.base [0, 1] >>> for g in A.basic_stabilizers: ... print(g) ... PermutationGroup([ (3)(0 1 2), (1 2 3)]) PermutationGroup([ (1 2 3)]) See Also ======== base, strong_gens, basic_orbits, basic_transversals """ if self._transversals == []: self.schreier_sims() strong_gens = self._strong_gens base = self._base if not base: # e.g. if self is trivial return [] strong_gens_distr = _distribute_gens_by_base(base, strong_gens) basic_stabilizers = [] for gens in strong_gens_distr: basic_stabilizers.append(PermutationGroup(gens)) return basic_stabilizers @property def basic_transversals(self): """ Return basic transversals relative to a base and strong generating set. Explanation =========== The basic transversals are transversals of the basic orbits. They are provided as a list of dictionaries, each dictionary having keys - the elements of one of the basic orbits, and values - the corresponding transversal elements. See [1], pp. 87-89 for more information. Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> A = AlternatingGroup(4) >>> A.basic_transversals [{0: (3), 1: (3)(0 1 2), 2: (3)(0 2 1), 3: (0 3 1)}, {1: (3), 2: (1 2 3), 3: (1 3 2)}] See Also ======== strong_gens, base, basic_orbits, basic_stabilizers """ if self._transversals == []: self.schreier_sims() return self._transversals def composition_series(self): r""" Return the composition series for a group as a list of permutation groups. Explanation =========== The composition series for a group `G` is defined as a subnormal series `G = H_0 > H_1 > H_2 \ldots` A composition series is a subnormal series such that each factor group `H(i+1) / H(i)` is simple. A subnormal series is a composition series only if it is of maximum length. The algorithm works as follows: Starting with the derived series the idea is to fill the gap between `G = der[i]` and `H = der[i+1]` for each `i` independently. Since, all subgroups of the abelian group `G/H` are normal so, first step is to take the generators `g` of `G` and add them to generators of `H` one by one. The factor groups formed are not simple in general. Each group is obtained from the previous one by adding one generator `g`, if the previous group is denoted by `H` then the next group `K` is generated by `g` and `H`. The factor group `K/H` is cyclic and it's order is `K.order()//G.order()`. The series is then extended between `K` and `H` by groups generated by powers of `g` and `H`. The series formed is then prepended to the already existing series. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.named_groups import CyclicGroup >>> S = SymmetricGroup(12) >>> G = S.sylow_subgroup(2) >>> C = G.composition_series() >>> [H.order() for H in C] [1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1] >>> G = S.sylow_subgroup(3) >>> C = G.composition_series() >>> [H.order() for H in C] [243, 81, 27, 9, 3, 1] >>> G = CyclicGroup(12) >>> C = G.composition_series() >>> [H.order() for H in C] [12, 6, 3, 1] """ der = self.derived_series() if not all(g.is_identity for g in der[-1].generators): raise NotImplementedError('Group should be solvable') series = [] for i in range(len(der)-1): H = der[i+1] up_seg = [] for g in der[i].generators: K = PermutationGroup([g] + H.generators) order = K.order() // H.order() down_seg = [] for p, e in factorint(order).items(): for _ in range(e): down_seg.append(PermutationGroup([g] + H.generators)) g = g**p up_seg = down_seg + up_seg H = K up_seg[0] = der[i] series.extend(up_seg) series.append(der[-1]) return series def coset_transversal(self, H): """Return a transversal of the right cosets of self by its subgroup H using the second method described in [1], Subsection 4.6.7 """ if not H.is_subgroup(self): raise ValueError("The argument must be a subgroup") if H.order() == 1: return self._elements self._schreier_sims(base=H.base) # make G.base an extension of H.base base = self.base base_ordering = _base_ordering(base, self.degree) identity = Permutation(self.degree - 1) transversals = self.basic_transversals[:] # transversals is a list of dictionaries. Get rid of the keys # so that it is a list of lists and sort each list in # the increasing order of base[l]^x for l, t in enumerate(transversals): transversals[l] = sorted(t.values(), key = lambda x: base_ordering[base[l]^x]) orbits = H.basic_orbits h_stabs = H.basic_stabilizers g_stabs = self.basic_stabilizers indices = [x.order()//y.order() for x, y in zip(g_stabs, h_stabs)] # T^(l) should be a right transversal of H^(l) in G^(l) for # 1<=l<=len(base). While H^(l) is the trivial group, T^(l) # contains all the elements of G^(l) so we might just as well # start with l = len(h_stabs)-1 if len(g_stabs) > len(h_stabs): T = g_stabs[len(h_stabs)]._elements else: T = [identity] l = len(h_stabs)-1 t_len = len(T) while l > -1: T_next = [] for u in transversals[l]: if u == identity: continue b = base_ordering[base[l]^u] for t in T: p = t*u if all(base_ordering[h^p] >= b for h in orbits[l]): T_next.append(p) if t_len + len(T_next) == indices[l]: break if t_len + len(T_next) == indices[l]: break T += T_next t_len += len(T_next) l -= 1 T.remove(identity) T = [identity] + T return T def _coset_representative(self, g, H): """Return the representative of Hg from the transversal that would be computed by ``self.coset_transversal(H)``. """ if H.order() == 1: return g # The base of self must be an extension of H.base. if not(self.base[:len(H.base)] == H.base): self._schreier_sims(base=H.base) orbits = H.basic_orbits[:] h_transversals = [list(_.values()) for _ in H.basic_transversals] transversals = [list(_.values()) for _ in self.basic_transversals] base = self.base base_ordering = _base_ordering(base, self.degree) def step(l, x): gamma = sorted(orbits[l], key = lambda y: base_ordering[y^x])[0] i = [base[l]^h for h in h_transversals[l]].index(gamma) x = h_transversals[l][i]*x if l < len(orbits)-1: for u in transversals[l]: if base[l]^u == base[l]^x: break x = step(l+1, x*u**-1)*u return x return step(0, g) def coset_table(self, H): """Return the standardised (right) coset table of self in H as a list of lists. """ # Maybe this should be made to return an instance of CosetTable # from fp_groups.py but the class would need to be changed first # to be compatible with PermutationGroups from itertools import chain, product if not H.is_subgroup(self): raise ValueError("The argument must be a subgroup") T = self.coset_transversal(H) n = len(T) A = list(chain.from_iterable((gen, gen**-1) for gen in self.generators)) table = [] for i in range(n): row = [self._coset_representative(T[i]*x, H) for x in A] row = [T.index(r) for r in row] table.append(row) # standardize (this is the same as the algorithm used in coset_table) # If CosetTable is made compatible with PermutationGroups, this # should be replaced by table.standardize() A = range(len(A)) gamma = 1 for alpha, a in product(range(n), A): beta = table[alpha][a] if beta >= gamma: if beta > gamma: for x in A: z = table[gamma][x] table[gamma][x] = table[beta][x] table[beta][x] = z for i in range(n): if table[i][x] == beta: table[i][x] = gamma elif table[i][x] == gamma: table[i][x] = beta gamma += 1 if gamma >= n-1: return table def center(self): r""" Return the center of a permutation group. Explanation =========== The center for a group `G` is defined as `Z(G) = \{z\in G | \forall g\in G, zg = gz \}`, the set of elements of `G` that commute with all elements of `G`. It is equal to the centralizer of `G` inside `G`, and is naturally a subgroup of `G` ([9]). Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(4) >>> G = D.center() >>> G.order() 2 See Also ======== centralizer Notes ===== This is a naive implementation that is a straightforward application of ``.centralizer()`` """ return self.centralizer(self) def centralizer(self, other): r""" Return the centralizer of a group/set/element. Explanation =========== The centralizer of a set of permutations ``S`` inside a group ``G`` is the set of elements of ``G`` that commute with all elements of ``S``:: `C_G(S) = \{ g \in G | gs = sg \forall s \in S\}` ([10]) Usually, ``S`` is a subset of ``G``, but if ``G`` is a proper subgroup of the full symmetric group, we allow for ``S`` to have elements outside ``G``. It is naturally a subgroup of ``G``; the centralizer of a permutation group is equal to the centralizer of any set of generators for that group, since any element commuting with the generators commutes with any product of the generators. Parameters ========== other a permutation group/list of permutations/single permutation Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... CyclicGroup) >>> S = SymmetricGroup(6) >>> C = CyclicGroup(6) >>> H = S.centralizer(C) >>> H.is_subgroup(C) True See Also ======== subgroup_search Notes ===== The implementation is an application of ``.subgroup_search()`` with tests using a specific base for the group ``G``. """ if hasattr(other, 'generators'): if other.is_trivial or self.is_trivial: return self degree = self.degree identity = _af_new(list(range(degree))) orbits = other.orbits() num_orbits = len(orbits) orbits.sort(key=lambda x: -len(x)) long_base = [] orbit_reps = [None]*num_orbits orbit_reps_indices = [None]*num_orbits orbit_descr = [None]*degree for i in range(num_orbits): orbit = list(orbits[i]) orbit_reps[i] = orbit[0] orbit_reps_indices[i] = len(long_base) for point in orbit: orbit_descr[point] = i long_base = long_base + orbit base, strong_gens = self.schreier_sims_incremental(base=long_base) strong_gens_distr = _distribute_gens_by_base(base, strong_gens) i = 0 for i in range(len(base)): if strong_gens_distr[i] == [identity]: break base = base[:i] base_len = i for j in range(num_orbits): if base[base_len - 1] in orbits[j]: break rel_orbits = orbits[: j + 1] num_rel_orbits = len(rel_orbits) transversals = [None]*num_rel_orbits for j in range(num_rel_orbits): rep = orbit_reps[j] transversals[j] = dict( other.orbit_transversal(rep, pairs=True)) trivial_test = lambda x: True tests = [None]*base_len for l in range(base_len): if base[l] in orbit_reps: tests[l] = trivial_test else: def test(computed_words, l=l): g = computed_words[l] rep_orb_index = orbit_descr[base[l]] rep = orbit_reps[rep_orb_index] im = g._array_form[base[l]] im_rep = g._array_form[rep] tr_el = transversals[rep_orb_index][base[l]] # using the definition of transversal, # base[l]^g = rep^(tr_el*g); # if g belongs to the centralizer, then # base[l]^g = (rep^g)^tr_el return im == tr_el._array_form[im_rep] tests[l] = test def prop(g): return [rmul(g, gen) for gen in other.generators] == \ [rmul(gen, g) for gen in other.generators] return self.subgroup_search(prop, base=base, strong_gens=strong_gens, tests=tests) elif hasattr(other, '__getitem__'): gens = list(other) return self.centralizer(PermutationGroup(gens)) elif hasattr(other, 'array_form'): return self.centralizer(PermutationGroup([other])) def commutator(self, G, H): """ Return the commutator of two subgroups. Explanation =========== For a permutation group ``K`` and subgroups ``G``, ``H``, the commutator of ``G`` and ``H`` is defined as the group generated by all the commutators `[g, h] = hgh^{-1}g^{-1}` for ``g`` in ``G`` and ``h`` in ``H``. It is naturally a subgroup of ``K`` ([1], p.27). Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup) >>> S = SymmetricGroup(5) >>> A = AlternatingGroup(5) >>> G = S.commutator(S, A) >>> G.is_subgroup(A) True See Also ======== derived_subgroup Notes ===== The commutator of two subgroups `H, G` is equal to the normal closure of the commutators of all the generators, i.e. `hgh^{-1}g^{-1}` for `h` a generator of `H` and `g` a generator of `G` ([1], p.28) """ ggens = G.generators hgens = H.generators commutators = [] for ggen in ggens: for hgen in hgens: commutator = rmul(hgen, ggen, ~hgen, ~ggen) if commutator not in commutators: commutators.append(commutator) res = self.normal_closure(commutators) return res def coset_factor(self, g, factor_index=False): """Return ``G``'s (self's) coset factorization of ``g`` Explanation =========== If ``g`` is an element of ``G`` then it can be written as the product of permutations drawn from the Schreier-Sims coset decomposition, The permutations returned in ``f`` are those for which the product gives ``g``: ``g = f[n]*...f[1]*f[0]`` where ``n = len(B)`` and ``B = G.base``. f[i] is one of the permutations in ``self._basic_orbits[i]``. If factor_index==True, returns a tuple ``[b[0],..,b[n]]``, where ``b[i]`` belongs to ``self._basic_orbits[i]`` Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation(0, 1, 3, 7, 6, 4)(2, 5) >>> b = Permutation(0, 1, 3, 2)(4, 5, 7, 6) >>> G = PermutationGroup([a, b]) Define g: >>> g = Permutation(7)(1, 2, 4)(3, 6, 5) Confirm that it is an element of G: >>> G.contains(g) True Thus, it can be written as a product of factors (up to 3) drawn from u. See below that a factor from u1 and u2 and the Identity permutation have been used: >>> f = G.coset_factor(g) >>> f[2]*f[1]*f[0] == g True >>> f1 = G.coset_factor(g, True); f1 [0, 4, 4] >>> tr = G.basic_transversals >>> f[0] == tr[0][f1[0]] True If g is not an element of G then [] is returned: >>> c = Permutation(5, 6, 7) >>> G.coset_factor(c) [] See Also ======== sympy.combinatorics.util._strip """ if isinstance(g, (Cycle, Permutation)): g = g.list() if len(g) != self._degree: # this could either adjust the size or return [] immediately # but we don't choose between the two and just signal a possible # error raise ValueError('g should be the same size as permutations of G') I = list(range(self._degree)) basic_orbits = self.basic_orbits transversals = self._transversals factors = [] base = self.base h = g for i in range(len(base)): beta = h[base[i]] if beta == base[i]: factors.append(beta) continue if beta not in basic_orbits[i]: return [] u = transversals[i][beta]._array_form h = _af_rmul(_af_invert(u), h) factors.append(beta) if h != I: return [] if factor_index: return factors tr = self.basic_transversals factors = [tr[i][factors[i]] for i in range(len(base))] return factors def generator_product(self, g, original=False): r''' Return a list of strong generators `[s1, \dots, sn]` s.t `g = sn \times \dots \times s1`. If ``original=True``, make the list contain only the original group generators ''' product = [] if g.is_identity: return [] if g in self.strong_gens: if not original or g in self.generators: return [g] else: slp = self._strong_gens_slp[g] for s in slp: product.extend(self.generator_product(s, original=True)) return product elif g**-1 in self.strong_gens: g = g**-1 if not original or g in self.generators: return [g**-1] else: slp = self._strong_gens_slp[g] for s in slp: product.extend(self.generator_product(s, original=True)) l = len(product) product = [product[l-i-1]**-1 for i in range(l)] return product f = self.coset_factor(g, True) for i, j in enumerate(f): slp = self._transversal_slp[i][j] for s in slp: if not original: product.append(self.strong_gens[s]) else: s = self.strong_gens[s] product.extend(self.generator_product(s, original=True)) return product def coset_rank(self, g): """rank using Schreier-Sims representation. Explanation =========== The coset rank of ``g`` is the ordering number in which it appears in the lexicographic listing according to the coset decomposition The ordering is the same as in G.generate(method='coset'). If ``g`` does not belong to the group it returns None. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation(0, 1, 3, 7, 6, 4)(2, 5) >>> b = Permutation(0, 1, 3, 2)(4, 5, 7, 6) >>> G = PermutationGroup([a, b]) >>> c = Permutation(7)(2, 4)(3, 5) >>> G.coset_rank(c) 16 >>> G.coset_unrank(16) (7)(2 4)(3 5) See Also ======== coset_factor """ factors = self.coset_factor(g, True) if not factors: return None rank = 0 b = 1 transversals = self._transversals base = self._base basic_orbits = self._basic_orbits for i in range(len(base)): k = factors[i] j = basic_orbits[i].index(k) rank += b*j b = b*len(transversals[i]) return rank def coset_unrank(self, rank, af=False): """unrank using Schreier-Sims representation coset_unrank is the inverse operation of coset_rank if 0 <= rank < order; otherwise it returns None. """ if rank < 0 or rank >= self.order(): return None base = self.base transversals = self.basic_transversals basic_orbits = self.basic_orbits m = len(base) v = [0]*m for i in range(m): rank, c = divmod(rank, len(transversals[i])) v[i] = basic_orbits[i][c] a = [transversals[i][v[i]]._array_form for i in range(m)] h = _af_rmuln(*a) if af: return h else: return _af_new(h) @property def degree(self): """Returns the size of the permutations in the group. Explanation =========== The number of permutations comprising the group is given by ``len(group)``; the number of permutations that can be generated by the group is given by ``group.order()``. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([1, 0, 2]) >>> G = PermutationGroup([a]) >>> G.degree 3 >>> len(G) 1 >>> G.order() 2 >>> list(G.generate()) [(2), (2)(0 1)] See Also ======== order """ return self._degree @property def identity(self): ''' Return the identity element of the permutation group. ''' return _af_new(list(range(self.degree))) @property def elements(self): """Returns all the elements of the permutation group as a set Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> p = PermutationGroup(Permutation(1, 3), Permutation(1, 2)) >>> p.elements {(1 2 3), (1 3 2), (1 3), (2 3), (3), (3)(1 2)} """ return set(self._elements) @property def _elements(self): """Returns all the elements of the permutation group as a list Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> p = PermutationGroup(Permutation(1, 3), Permutation(1, 2)) >>> p._elements [(3), (3)(1 2), (1 3), (2 3), (1 2 3), (1 3 2)] """ return list(islice(self.generate(), None)) def derived_series(self): r"""Return the derived series for the group. Explanation =========== The derived series for a group `G` is defined as `G = G_0 > G_1 > G_2 > \ldots` where `G_i = [G_{i-1}, G_{i-1}]`, i.e. `G_i` is the derived subgroup of `G_{i-1}`, for `i\in\mathbb{N}`. When we have `G_k = G_{k-1}` for some `k\in\mathbb{N}`, the series terminates. Returns ======= A list of permutation groups containing the members of the derived series in the order `G = G_0, G_1, G_2, \ldots`. Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup, DihedralGroup) >>> A = AlternatingGroup(5) >>> len(A.derived_series()) 1 >>> S = SymmetricGroup(4) >>> len(S.derived_series()) 4 >>> S.derived_series()[1].is_subgroup(AlternatingGroup(4)) True >>> S.derived_series()[2].is_subgroup(DihedralGroup(2)) True See Also ======== derived_subgroup """ res = [self] current = self nxt = self.derived_subgroup() while not current.is_subgroup(nxt): res.append(nxt) current = nxt nxt = nxt.derived_subgroup() return res def derived_subgroup(self): r"""Compute the derived subgroup. Explanation =========== The derived subgroup, or commutator subgroup is the subgroup generated by all commutators `[g, h] = hgh^{-1}g^{-1}` for `g, h\in G` ; it is equal to the normal closure of the set of commutators of the generators ([1], p.28, [11]). Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([1, 0, 2, 4, 3]) >>> b = Permutation([0, 1, 3, 2, 4]) >>> G = PermutationGroup([a, b]) >>> C = G.derived_subgroup() >>> list(C.generate(af=True)) [[0, 1, 2, 3, 4], [0, 1, 3, 4, 2], [0, 1, 4, 2, 3]] See Also ======== derived_series """ r = self._r gens = [p._array_form for p in self.generators] set_commutators = set() degree = self._degree rng = list(range(degree)) for i in range(r): for j in range(r): p1 = gens[i] p2 = gens[j] c = list(range(degree)) for k in rng: c[p2[p1[k]]] = p1[p2[k]] ct = tuple(c) if ct not in set_commutators: set_commutators.add(ct) cms = [_af_new(p) for p in set_commutators] G2 = self.normal_closure(cms) return G2 def generate(self, method="coset", af=False): """Return iterator to generate the elements of the group. Explanation =========== Iteration is done with one of these methods:: method='coset' using the Schreier-Sims coset representation method='dimino' using the Dimino method If ``af = True`` it yields the array form of the permutations Examples ======== >>> from sympy.combinatorics import PermutationGroup >>> from sympy.combinatorics.polyhedron import tetrahedron The permutation group given in the tetrahedron object is also true groups: >>> G = tetrahedron.pgroup >>> G.is_group True Also the group generated by the permutations in the tetrahedron pgroup -- even the first two -- is a proper group: >>> H = PermutationGroup(G[0], G[1]) >>> J = PermutationGroup(list(H.generate())); J PermutationGroup([ (0 1)(2 3), (1 2 3), (1 3 2), (0 3 1), (0 2 3), (0 3)(1 2), (0 1 3), (3)(0 2 1), (0 3 2), (3)(0 1 2), (0 2)(1 3)]) >>> _.is_group True """ if method == "coset": return self.generate_schreier_sims(af) elif method == "dimino": return self.generate_dimino(af) else: raise NotImplementedError('No generation defined for %s' % method) def generate_dimino(self, af=False): """Yield group elements using Dimino's algorithm. If ``af == True`` it yields the array form of the permutations. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([0, 2, 1, 3]) >>> b = Permutation([0, 2, 3, 1]) >>> g = PermutationGroup([a, b]) >>> list(g.generate_dimino(af=True)) [[0, 1, 2, 3], [0, 2, 1, 3], [0, 2, 3, 1], [0, 1, 3, 2], [0, 3, 2, 1], [0, 3, 1, 2]] References ========== .. [1] The Implementation of Various Algorithms for Permutation Groups in the Computer Algebra System: AXIOM, N.J. Doye, M.Sc. Thesis """ idn = list(range(self.degree)) order = 0 element_list = [idn] set_element_list = {tuple(idn)} if af: yield idn else: yield _af_new(idn) gens = [p._array_form for p in self.generators] for i in range(len(gens)): # D elements of the subgroup G_i generated by gens[:i] D = element_list[:] N = [idn] while N: A = N N = [] for a in A: for g in gens[:i + 1]: ag = _af_rmul(a, g) if tuple(ag) not in set_element_list: # produce G_i*g for d in D: order += 1 ap = _af_rmul(d, ag) if af: yield ap else: p = _af_new(ap) yield p element_list.append(ap) set_element_list.add(tuple(ap)) N.append(ap) self._order = len(element_list) def generate_schreier_sims(self, af=False): """Yield group elements using the Schreier-Sims representation in coset_rank order If ``af = True`` it yields the array form of the permutations Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([0, 2, 1, 3]) >>> b = Permutation([0, 2, 3, 1]) >>> g = PermutationGroup([a, b]) >>> list(g.generate_schreier_sims(af=True)) [[0, 1, 2, 3], [0, 2, 1, 3], [0, 3, 2, 1], [0, 1, 3, 2], [0, 2, 3, 1], [0, 3, 1, 2]] """ n = self._degree u = self.basic_transversals basic_orbits = self._basic_orbits if len(u) == 0: for x in self.generators: if af: yield x._array_form else: yield x return if len(u) == 1: for i in basic_orbits[0]: if af: yield u[0][i]._array_form else: yield u[0][i] return u = list(reversed(u)) basic_orbits = basic_orbits[::-1] # stg stack of group elements stg = [list(range(n))] posmax = [len(x) for x in u] n1 = len(posmax) - 1 pos = [0]*n1 h = 0 while 1: # backtrack when finished iterating over coset if pos[h] >= posmax[h]: if h == 0: return pos[h] = 0 h -= 1 stg.pop() continue p = _af_rmul(u[h][basic_orbits[h][pos[h]]]._array_form, stg[-1]) pos[h] += 1 stg.append(p) h += 1 if h == n1: if af: for i in basic_orbits[-1]: p = _af_rmul(u[-1][i]._array_form, stg[-1]) yield p else: for i in basic_orbits[-1]: p = _af_rmul(u[-1][i]._array_form, stg[-1]) p1 = _af_new(p) yield p1 stg.pop() h -= 1 @property def generators(self): """Returns the generators of the group. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.generators [(1 2), (2)(0 1)] """ return self._generators def contains(self, g, strict=True): """Test if permutation ``g`` belong to self, ``G``. Explanation =========== If ``g`` is an element of ``G`` it can be written as a product of factors drawn from the cosets of ``G``'s stabilizers. To see if ``g`` is one of the actual generators defining the group use ``G.has(g)``. If ``strict`` is not ``True``, ``g`` will be resized, if necessary, to match the size of permutations in ``self``. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation(1, 2) >>> b = Permutation(2, 3, 1) >>> G = PermutationGroup(a, b, degree=5) >>> G.contains(G[0]) # trivial check True >>> elem = Permutation([[2, 3]], size=5) >>> G.contains(elem) True >>> G.contains(Permutation(4)(0, 1, 2, 3)) False If strict is False, a permutation will be resized, if necessary: >>> H = PermutationGroup(Permutation(5)) >>> H.contains(Permutation(3)) False >>> H.contains(Permutation(3), strict=False) True To test if a given permutation is present in the group: >>> elem in G.generators False >>> G.has(elem) False See Also ======== coset_factor, sympy.core.basic.Basic.has, __contains__ """ if not isinstance(g, Permutation): return False if g.size != self.degree: if strict: return False g = Permutation(g, size=self.degree) if g in self.generators: return True return bool(self.coset_factor(g.array_form, True)) @property def is_perfect(self): """Return ``True`` if the group is perfect. A group is perfect if it equals to its derived subgroup. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation(1,2,3)(4,5) >>> b = Permutation(1,2,3,4,5) >>> G = PermutationGroup([a, b]) >>> G.is_perfect False """ if self._is_perfect is None: self._is_perfect = self.equals(self.derived_subgroup()) return self._is_perfect @property def is_abelian(self): """Test if the group is Abelian. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.is_abelian False >>> a = Permutation([0, 2, 1]) >>> G = PermutationGroup([a]) >>> G.is_abelian True """ if self._is_abelian is not None: return self._is_abelian self._is_abelian = True gens = [p._array_form for p in self.generators] for x in gens: for y in gens: if y <= x: continue if not _af_commutes_with(x, y): self._is_abelian = False return False return True def abelian_invariants(self): """ Returns the abelian invariants for the given group. Let ``G`` be a nontrivial finite abelian group. Then G is isomorphic to the direct product of finitely many nontrivial cyclic groups of prime-power order. Explanation =========== The prime-powers that occur as the orders of the factors are uniquely determined by G. More precisely, the primes that occur in the orders of the factors in any such decomposition of ``G`` are exactly the primes that divide ``|G|`` and for any such prime ``p``, if the orders of the factors that are p-groups in one such decomposition of ``G`` are ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``, then the orders of the factors that are p-groups in any such decomposition of ``G`` are ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``. The uniquely determined integers ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``, taken for all primes that divide ``|G|`` are called the invariants of the nontrivial group ``G`` as suggested in ([14], p. 542). Notes ===== We adopt the convention that the invariants of a trivial group are []. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.abelian_invariants() [2] >>> from sympy.combinatorics.named_groups import CyclicGroup >>> G = CyclicGroup(7) >>> G.abelian_invariants() [7] """ if self.is_trivial: return [] gns = self.generators inv = [] G = self H = G.derived_subgroup() Hgens = H.generators for p in primefactors(G.order()): ranks = [] while True: pows = [] for g in gns: elm = g**p if not H.contains(elm): pows.append(elm) K = PermutationGroup(Hgens + pows) if pows else H r = G.order()//K.order() G = K gns = pows if r == 1: break ranks.append(multiplicity(p, r)) if ranks: pows = [1]*ranks[0] for i in ranks: for j in range(0, i): pows[j] = pows[j]*p inv.extend(pows) inv.sort() return inv def is_elementary(self, p): """Return ``True`` if the group is elementary abelian. An elementary abelian group is a finite abelian group, where every nontrivial element has order `p`, where `p` is a prime. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([0, 2, 1]) >>> G = PermutationGroup([a]) >>> G.is_elementary(2) True >>> a = Permutation([0, 2, 1, 3]) >>> b = Permutation([3, 1, 2, 0]) >>> G = PermutationGroup([a, b]) >>> G.is_elementary(2) True >>> G.is_elementary(3) False """ return self.is_abelian and all(g.order() == p for g in self.generators) def _eval_is_alt_sym_naive(self, only_sym=False, only_alt=False): """A naive test using the group order.""" if only_sym and only_alt: raise ValueError( "Both {} and {} cannot be set to True" .format(only_sym, only_alt)) n = self.degree sym_order = 1 for i in range(2, n+1): sym_order *= i order = self.order() if order == sym_order: self._is_sym = True self._is_alt = False if only_alt: return False return True elif 2*order == sym_order: self._is_sym = False self._is_alt = True if only_sym: return False return True return False def _eval_is_alt_sym_monte_carlo(self, eps=0.05, perms=None): """A test using monte-carlo algorithm. Parameters ========== eps : float, optional The criterion for the incorrect ``False`` return. perms : list[Permutation], optional If explicitly given, it tests over the given candidats for testing. If ``None``, it randomly computes ``N_eps`` and chooses ``N_eps`` sample of the permutation from the group. See Also ======== _check_cycles_alt_sym """ if perms is None: n = self.degree if n < 17: c_n = 0.34 else: c_n = 0.57 d_n = (c_n*log(2))/log(n) N_eps = int(-log(eps)/d_n) perms = (self.random_pr() for i in range(N_eps)) return self._eval_is_alt_sym_monte_carlo(perms=perms) for perm in perms: if _check_cycles_alt_sym(perm): return True return False def is_alt_sym(self, eps=0.05, _random_prec=None): r"""Monte Carlo test for the symmetric/alternating group for degrees >= 8. Explanation =========== More specifically, it is one-sided Monte Carlo with the answer True (i.e., G is symmetric/alternating) guaranteed to be correct, and the answer False being incorrect with probability eps. For degree < 8, the order of the group is checked so the test is deterministic. Notes ===== The algorithm itself uses some nontrivial results from group theory and number theory: 1) If a transitive group ``G`` of degree ``n`` contains an element with a cycle of length ``n/2 < p < n-2`` for ``p`` a prime, ``G`` is the symmetric or alternating group ([1], pp. 81-82) 2) The proportion of elements in the symmetric/alternating group having the property described in 1) is approximately `\log(2)/\log(n)` ([1], p.82; [2], pp. 226-227). The helper function ``_check_cycles_alt_sym`` is used to go over the cycles in a permutation and look for ones satisfying 1). Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(10) >>> D.is_alt_sym() False See Also ======== _check_cycles_alt_sym """ if _random_prec is not None: N_eps = _random_prec['N_eps'] perms= (_random_prec[i] for i in range(N_eps)) return self._eval_is_alt_sym_monte_carlo(perms=perms) if self._is_sym or self._is_alt: return True if self._is_sym is False and self._is_alt is False: return False n = self.degree if n < 8: return self._eval_is_alt_sym_naive() elif self.is_transitive(): return self._eval_is_alt_sym_monte_carlo(eps=eps) self._is_sym, self._is_alt = False, False return False @property def is_nilpotent(self): """Test if the group is nilpotent. Explanation =========== A group `G` is nilpotent if it has a central series of finite length. Alternatively, `G` is nilpotent if its lower central series terminates with the trivial group. Every nilpotent group is also solvable ([1], p.29, [12]). Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... CyclicGroup) >>> C = CyclicGroup(6) >>> C.is_nilpotent True >>> S = SymmetricGroup(5) >>> S.is_nilpotent False See Also ======== lower_central_series, is_solvable """ if self._is_nilpotent is None: lcs = self.lower_central_series() terminator = lcs[len(lcs) - 1] gens = terminator.generators degree = self.degree identity = _af_new(list(range(degree))) if all(g == identity for g in gens): self._is_solvable = True self._is_nilpotent = True return True else: self._is_nilpotent = False return False else: return self._is_nilpotent def is_normal(self, gr, strict=True): """Test if ``G=self`` is a normal subgroup of ``gr``. Explanation =========== G is normal in gr if for each g2 in G, g1 in gr, ``g = g1*g2*g1**-1`` belongs to G It is sufficient to check this for each g1 in gr.generators and g2 in G.generators. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([1, 2, 0]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G1 = PermutationGroup([a, Permutation([2, 0, 1])]) >>> G1.is_normal(G) True """ if not self.is_subgroup(gr, strict=strict): return False d_self = self.degree d_gr = gr.degree if self.is_trivial and (d_self == d_gr or not strict): return True if self._is_abelian: return True new_self = self.copy() if not strict and d_self != d_gr: if d_self < d_gr: new_self = PermGroup(new_self.generators + [Permutation(d_gr - 1)]) else: gr = PermGroup(gr.generators + [Permutation(d_self - 1)]) gens2 = [p._array_form for p in new_self.generators] gens1 = [p._array_form for p in gr.generators] for g1 in gens1: for g2 in gens2: p = _af_rmuln(g1, g2, _af_invert(g1)) if not new_self.coset_factor(p, True): return False return True def is_primitive(self, randomized=True): r"""Test if a group is primitive. Explanation =========== A permutation group ``G`` acting on a set ``S`` is called primitive if ``S`` contains no nontrivial block under the action of ``G`` (a block is nontrivial if its cardinality is more than ``1``). Notes ===== The algorithm is described in [1], p.83, and uses the function minimal_block to search for blocks of the form `\{0, k\}` for ``k`` ranging over representatives for the orbits of `G_0`, the stabilizer of ``0``. This algorithm has complexity `O(n^2)` where ``n`` is the degree of the group, and will perform badly if `G_0` is small. There are two implementations offered: one finds `G_0` deterministically using the function ``stabilizer``, and the other (default) produces random elements of `G_0` using ``random_stab``, hoping that they generate a subgroup of `G_0` with not too many more orbits than `G_0` (this is suggested in [1], p.83). Behavior is changed by the ``randomized`` flag. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(10) >>> D.is_primitive() False See Also ======== minimal_block, random_stab """ if self._is_primitive is not None: return self._is_primitive if self.is_transitive() is False: return False if randomized: random_stab_gens = [] v = self.schreier_vector(0) for _ in range(len(self)): random_stab_gens.append(self.random_stab(0, v)) stab = PermutationGroup(random_stab_gens) else: stab = self.stabilizer(0) orbits = stab.orbits() for orb in orbits: x = orb.pop() if x != 0 and any(e != 0 for e in self.minimal_block([0, x])): self._is_primitive = False return False self._is_primitive = True return True def minimal_blocks(self, randomized=True): ''' For a transitive group, return the list of all minimal block systems. If a group is intransitive, return `False`. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.named_groups import DihedralGroup >>> DihedralGroup(6).minimal_blocks() [[0, 1, 0, 1, 0, 1], [0, 1, 2, 0, 1, 2]] >>> G = PermutationGroup(Permutation(1,2,5)) >>> G.minimal_blocks() False See Also ======== minimal_block, is_transitive, is_primitive ''' def _number_blocks(blocks): # number the blocks of a block system # in order and return the number of # blocks and the tuple with the # reordering n = len(blocks) appeared = {} m = 0 b = [None]*n for i in range(n): if blocks[i] not in appeared: appeared[blocks[i]] = m b[i] = m m += 1 else: b[i] = appeared[blocks[i]] return tuple(b), m if not self.is_transitive(): return False blocks = [] num_blocks = [] rep_blocks = [] if randomized: random_stab_gens = [] v = self.schreier_vector(0) for i in range(len(self)): random_stab_gens.append(self.random_stab(0, v)) stab = PermutationGroup(random_stab_gens) else: stab = self.stabilizer(0) orbits = stab.orbits() for orb in orbits: x = orb.pop() if x != 0: block = self.minimal_block([0, x]) num_block, _ = _number_blocks(block) # a representative block (containing 0) rep = {j for j in range(self.degree) if num_block[j] == 0} # check if the system is minimal with # respect to the already discovere ones minimal = True blocks_remove_mask = [False] * len(blocks) for i, r in enumerate(rep_blocks): if len(r) > len(rep) and rep.issubset(r): # i-th block system is not minimal blocks_remove_mask[i] = True elif len(r) < len(rep) and r.issubset(rep): # the system being checked is not minimal minimal = False break # remove non-minimal representative blocks blocks = [b for i, b in enumerate(blocks) if not blocks_remove_mask[i]] num_blocks = [n for i, n in enumerate(num_blocks) if not blocks_remove_mask[i]] rep_blocks = [r for i, r in enumerate(rep_blocks) if not blocks_remove_mask[i]] if minimal and num_block not in num_blocks: blocks.append(block) num_blocks.append(num_block) rep_blocks.append(rep) return blocks @property def is_solvable(self): """Test if the group is solvable. ``G`` is solvable if its derived series terminates with the trivial group ([1], p.29). Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(3) >>> S.is_solvable True See Also ======== is_nilpotent, derived_series """ if self._is_solvable is None: if self.order() % 2 != 0: return True ds = self.derived_series() terminator = ds[len(ds) - 1] gens = terminator.generators degree = self.degree identity = _af_new(list(range(degree))) if all(g == identity for g in gens): self._is_solvable = True return True else: self._is_solvable = False return False else: return self._is_solvable def is_subgroup(self, G, strict=True): """Return ``True`` if all elements of ``self`` belong to ``G``. If ``strict`` is ``False`` then if ``self``'s degree is smaller than ``G``'s, the elements will be resized to have the same degree. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... CyclicGroup) Testing is strict by default: the degree of each group must be the same: >>> p = Permutation(0, 1, 2, 3, 4, 5) >>> G1 = PermutationGroup([Permutation(0, 1, 2), Permutation(0, 1)]) >>> G2 = PermutationGroup([Permutation(0, 2), Permutation(0, 1, 2)]) >>> G3 = PermutationGroup([p, p**2]) >>> assert G1.order() == G2.order() == G3.order() == 6 >>> G1.is_subgroup(G2) True >>> G1.is_subgroup(G3) False >>> G3.is_subgroup(PermutationGroup(G3[1])) False >>> G3.is_subgroup(PermutationGroup(G3[0])) True To ignore the size, set ``strict`` to ``False``: >>> S3 = SymmetricGroup(3) >>> S5 = SymmetricGroup(5) >>> S3.is_subgroup(S5, strict=False) True >>> C7 = CyclicGroup(7) >>> G = S5*C7 >>> S5.is_subgroup(G, False) True >>> C7.is_subgroup(G, 0) False """ if isinstance(G, SymmetricPermutationGroup): if self.degree != G.degree: return False return True if not isinstance(G, PermutationGroup): return False if self == G or self.generators[0]==Permutation(): return True if G.order() % self.order() != 0: return False if self.degree == G.degree or \ (self.degree < G.degree and not strict): gens = self.generators else: return False return all(G.contains(g, strict=strict) for g in gens) @property def is_polycyclic(self): """Return ``True`` if a group is polycyclic. A group is polycyclic if it has a subnormal series with cyclic factors. For finite groups, this is the same as if the group is solvable. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> a = Permutation([0, 2, 1, 3]) >>> b = Permutation([2, 0, 1, 3]) >>> G = PermutationGroup([a, b]) >>> G.is_polycyclic True """ return self.is_solvable def is_transitive(self, strict=True): """Test if the group is transitive. Explanation =========== A group is transitive if it has a single orbit. If ``strict`` is ``False`` the group is transitive if it has a single orbit of length different from 1. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([0, 2, 1, 3]) >>> b = Permutation([2, 0, 1, 3]) >>> G1 = PermutationGroup([a, b]) >>> G1.is_transitive() False >>> G1.is_transitive(strict=False) True >>> c = Permutation([2, 3, 0, 1]) >>> G2 = PermutationGroup([a, c]) >>> G2.is_transitive() True >>> d = Permutation([1, 0, 2, 3]) >>> e = Permutation([0, 1, 3, 2]) >>> G3 = PermutationGroup([d, e]) >>> G3.is_transitive() or G3.is_transitive(strict=False) False """ if self._is_transitive: # strict or not, if True then True return self._is_transitive if strict: if self._is_transitive is not None: # we only store strict=True return self._is_transitive ans = len(self.orbit(0)) == self.degree self._is_transitive = ans return ans got_orb = False for x in self.orbits(): if len(x) > 1: if got_orb: return False got_orb = True return got_orb @property def is_trivial(self): """Test if the group is the trivial group. This is true if the group contains only the identity permutation. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> G = PermutationGroup([Permutation([0, 1, 2])]) >>> G.is_trivial True """ if self._is_trivial is None: self._is_trivial = len(self) == 1 and self[0].is_Identity return self._is_trivial def lower_central_series(self): r"""Return the lower central series for the group. The lower central series for a group `G` is the series `G = G_0 > G_1 > G_2 > \ldots` where `G_k = [G, G_{k-1}]`, i.e. every term after the first is equal to the commutator of `G` and the previous term in `G1` ([1], p.29). Returns ======= A list of permutation groups in the order `G = G_0, G_1, G_2, \ldots` Examples ======== >>> from sympy.combinatorics.named_groups import (AlternatingGroup, ... DihedralGroup) >>> A = AlternatingGroup(4) >>> len(A.lower_central_series()) 2 >>> A.lower_central_series()[1].is_subgroup(DihedralGroup(2)) True See Also ======== commutator, derived_series """ res = [self] current = self nxt = self.commutator(self, current) while not current.is_subgroup(nxt): res.append(nxt) current = nxt nxt = self.commutator(self, current) return res @property def max_div(self): """Maximum proper divisor of the degree of a permutation group. Explanation =========== Obviously, this is the degree divided by its minimal proper divisor (larger than ``1``, if one exists). As it is guaranteed to be prime, the ``sieve`` from ``sympy.ntheory`` is used. This function is also used as an optimization tool for the functions ``minimal_block`` and ``_union_find_merge``. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> G = PermutationGroup([Permutation([0, 2, 1, 3])]) >>> G.max_div 2 See Also ======== minimal_block, _union_find_merge """ if self._max_div is not None: return self._max_div n = self.degree if n == 1: return 1 for x in sieve: if n % x == 0: d = n//x self._max_div = d return d def minimal_block(self, points): r"""For a transitive group, finds the block system generated by ``points``. Explanation =========== If a group ``G`` acts on a set ``S``, a nonempty subset ``B`` of ``S`` is called a block under the action of ``G`` if for all ``g`` in ``G`` we have ``gB = B`` (``g`` fixes ``B``) or ``gB`` and ``B`` have no common points (``g`` moves ``B`` entirely). ([1], p.23; [6]). The distinct translates ``gB`` of a block ``B`` for ``g`` in ``G`` partition the set ``S`` and this set of translates is known as a block system. Moreover, we obviously have that all blocks in the partition have the same size, hence the block size divides ``|S|`` ([1], p.23). A ``G``-congruence is an equivalence relation ``~`` on the set ``S`` such that ``a ~ b`` implies ``g(a) ~ g(b)`` for all ``g`` in ``G``. For a transitive group, the equivalence classes of a ``G``-congruence and the blocks of a block system are the same thing ([1], p.23). The algorithm below checks the group for transitivity, and then finds the ``G``-congruence generated by the pairs ``(p_0, p_1), (p_0, p_2), ..., (p_0,p_{k-1})`` which is the same as finding the maximal block system (i.e., the one with minimum block size) such that ``p_0, ..., p_{k-1}`` are in the same block ([1], p.83). It is an implementation of Atkinson's algorithm, as suggested in [1], and manipulates an equivalence relation on the set ``S`` using a union-find data structure. The running time is just above `O(|points||S|)`. ([1], pp. 83-87; [7]). Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(10) >>> D.minimal_block([0, 5]) [0, 1, 2, 3, 4, 0, 1, 2, 3, 4] >>> D.minimal_block([0, 1]) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] See Also ======== _union_find_rep, _union_find_merge, is_transitive, is_primitive """ if not self.is_transitive(): return False n = self.degree gens = self.generators # initialize the list of equivalence class representatives parents = list(range(n)) ranks = [1]*n not_rep = [] k = len(points) # the block size must divide the degree of the group if k > self.max_div: return [0]*n for i in range(k - 1): parents[points[i + 1]] = points[0] not_rep.append(points[i + 1]) ranks[points[0]] = k i = 0 len_not_rep = k - 1 while i < len_not_rep: gamma = not_rep[i] i += 1 for gen in gens: # find has side effects: performs path compression on the list # of representatives delta = self._union_find_rep(gamma, parents) # union has side effects: performs union by rank on the list # of representatives temp = self._union_find_merge(gen(gamma), gen(delta), ranks, parents, not_rep) if temp == -1: return [0]*n len_not_rep += temp for i in range(n): # force path compression to get the final state of the equivalence # relation self._union_find_rep(i, parents) # rewrite result so that block representatives are minimal new_reps = {} return [new_reps.setdefault(r, i) for i, r in enumerate(parents)] def conjugacy_class(self, x): r"""Return the conjugacy class of an element in the group. Explanation =========== The conjugacy class of an element ``g`` in a group ``G`` is the set of elements ``x`` in ``G`` that are conjugate with ``g``, i.e. for which ``g = xax^{-1}`` for some ``a`` in ``G``. Note that conjugacy is an equivalence relation, and therefore that conjugacy classes are partitions of ``G``. For a list of all the conjugacy classes of the group, use the conjugacy_classes() method. In a permutation group, each conjugacy class corresponds to a particular `cycle structure': for example, in ``S_3``, the conjugacy classes are: * the identity class, ``{()}`` * all transpositions, ``{(1 2), (1 3), (2 3)}`` * all 3-cycles, ``{(1 2 3), (1 3 2)}`` Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S3 = SymmetricGroup(3) >>> S3.conjugacy_class(Permutation(0, 1, 2)) {(0 1 2), (0 2 1)} Notes ===== This procedure computes the conjugacy class directly by finding the orbit of the element under conjugation in G. This algorithm is only feasible for permutation groups of relatively small order, but is like the orbit() function itself in that respect. """ # Ref: "Computing the conjugacy classes of finite groups"; Butler, G. # Groups '93 Galway/St Andrews; edited by Campbell, C. M. new_class = {x} last_iteration = new_class while len(last_iteration) > 0: this_iteration = set() for y in last_iteration: for s in self.generators: conjugated = s * y * (~s) if conjugated not in new_class: this_iteration.add(conjugated) new_class.update(last_iteration) last_iteration = this_iteration return new_class def conjugacy_classes(self): r"""Return the conjugacy classes of the group. Explanation =========== As described in the documentation for the .conjugacy_class() function, conjugacy is an equivalence relation on a group G which partitions the set of elements. This method returns a list of all these conjugacy classes of G. Examples ======== >>> from sympy.combinatorics import SymmetricGroup >>> SymmetricGroup(3).conjugacy_classes() [{(2)}, {(0 1 2), (0 2 1)}, {(0 2), (1 2), (2)(0 1)}] """ identity = _af_new(list(range(self.degree))) known_elements = {identity} classes = [known_elements.copy()] for x in self.generate(): if x not in known_elements: new_class = self.conjugacy_class(x) classes.append(new_class) known_elements.update(new_class) return classes def normal_closure(self, other, k=10): r"""Return the normal closure of a subgroup/set of permutations. Explanation =========== If ``S`` is a subset of a group ``G``, the normal closure of ``A`` in ``G`` is defined as the intersection of all normal subgroups of ``G`` that contain ``A`` ([1], p.14). Alternatively, it is the group generated by the conjugates ``x^{-1}yx`` for ``x`` a generator of ``G`` and ``y`` a generator of the subgroup ``\left\langle S\right\rangle`` generated by ``S`` (for some chosen generating set for ``\left\langle S\right\rangle``) ([1], p.73). Parameters ========== other a subgroup/list of permutations/single permutation k an implementation-specific parameter that determines the number of conjugates that are adjoined to ``other`` at once Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... CyclicGroup, AlternatingGroup) >>> S = SymmetricGroup(5) >>> C = CyclicGroup(5) >>> G = S.normal_closure(C) >>> G.order() 60 >>> G.is_subgroup(AlternatingGroup(5)) True See Also ======== commutator, derived_subgroup, random_pr Notes ===== The algorithm is described in [1], pp. 73-74; it makes use of the generation of random elements for permutation groups by the product replacement algorithm. """ if hasattr(other, 'generators'): degree = self.degree identity = _af_new(list(range(degree))) if all(g == identity for g in other.generators): return other Z = PermutationGroup(other.generators[:]) base, strong_gens = Z.schreier_sims_incremental() strong_gens_distr = _distribute_gens_by_base(base, strong_gens) basic_orbits, basic_transversals = \ _orbits_transversals_from_bsgs(base, strong_gens_distr) self._random_pr_init(r=10, n=20) _loop = True while _loop: Z._random_pr_init(r=10, n=10) for _ in range(k): g = self.random_pr() h = Z.random_pr() conj = h^g res = _strip(conj, base, basic_orbits, basic_transversals) if res[0] != identity or res[1] != len(base) + 1: gens = Z.generators gens.append(conj) Z = PermutationGroup(gens) strong_gens.append(conj) temp_base, temp_strong_gens = \ Z.schreier_sims_incremental(base, strong_gens) base, strong_gens = temp_base, temp_strong_gens strong_gens_distr = \ _distribute_gens_by_base(base, strong_gens) basic_orbits, basic_transversals = \ _orbits_transversals_from_bsgs(base, strong_gens_distr) _loop = False for g in self.generators: for h in Z.generators: conj = h^g res = _strip(conj, base, basic_orbits, basic_transversals) if res[0] != identity or res[1] != len(base) + 1: _loop = True break if _loop: break return Z elif hasattr(other, '__getitem__'): return self.normal_closure(PermutationGroup(other)) elif hasattr(other, 'array_form'): return self.normal_closure(PermutationGroup([other])) def orbit(self, alpha, action='tuples'): r"""Compute the orbit of alpha `\{g(\alpha) | g \in G\}` as a set. Explanation =========== The time complexity of the algorithm used here is `O(|Orb|*r)` where `|Orb|` is the size of the orbit and ``r`` is the number of generators of the group. For a more detailed analysis, see [1], p.78, [2], pp. 19-21. Here alpha can be a single point, or a list of points. If alpha is a single point, the ordinary orbit is computed. if alpha is a list of points, there are three available options: 'union' - computes the union of the orbits of the points in the list 'tuples' - computes the orbit of the list interpreted as an ordered tuple under the group action ( i.e., g((1,2,3)) = (g(1), g(2), g(3)) ) 'sets' - computes the orbit of the list interpreted as a sets Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([1, 2, 0, 4, 5, 6, 3]) >>> G = PermutationGroup([a]) >>> G.orbit(0) {0, 1, 2} >>> G.orbit([0, 4], 'union') {0, 1, 2, 3, 4, 5, 6} See Also ======== orbit_transversal """ return _orbit(self.degree, self.generators, alpha, action) def orbit_rep(self, alpha, beta, schreier_vector=None): """Return a group element which sends ``alpha`` to ``beta``. Explanation =========== If ``beta`` is not in the orbit of ``alpha``, the function returns ``False``. This implementation makes use of the schreier vector. For a proof of correctness, see [1], p.80 Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> G = AlternatingGroup(5) >>> G.orbit_rep(0, 4) (0 4 1 2 3) See Also ======== schreier_vector """ if schreier_vector is None: schreier_vector = self.schreier_vector(alpha) if schreier_vector[beta] is None: return False k = schreier_vector[beta] gens = [x._array_form for x in self.generators] a = [] while k != -1: a.append(gens[k]) beta = gens[k].index(beta) # beta = (~gens[k])(beta) k = schreier_vector[beta] if a: return _af_new(_af_rmuln(*a)) else: return _af_new(list(range(self._degree))) def orbit_transversal(self, alpha, pairs=False): r"""Computes a transversal for the orbit of ``alpha`` as a set. Explanation =========== For a permutation group `G`, a transversal for the orbit `Orb = \{g(\alpha) | g \in G\}` is a set `\{g_\beta | g_\beta(\alpha) = \beta\}` for `\beta \in Orb`. Note that there may be more than one possible transversal. If ``pairs`` is set to ``True``, it returns the list of pairs `(\beta, g_\beta)`. For a proof of correctness, see [1], p.79 Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> G = DihedralGroup(6) >>> G.orbit_transversal(0) [(5), (0 1 2 3 4 5), (0 5)(1 4)(2 3), (0 2 4)(1 3 5), (5)(0 4)(1 3), (0 3)(1 4)(2 5)] See Also ======== orbit """ return _orbit_transversal(self._degree, self.generators, alpha, pairs) def orbits(self, rep=False): """Return the orbits of ``self``, ordered according to lowest element in each orbit. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation(1, 5)(2, 3)(4, 0, 6) >>> b = Permutation(1, 5)(3, 4)(2, 6, 0) >>> G = PermutationGroup([a, b]) >>> G.orbits() [{0, 2, 3, 4, 6}, {1, 5}] """ return _orbits(self._degree, self._generators) def order(self): """Return the order of the group: the number of permutations that can be generated from elements of the group. The number of permutations comprising the group is given by ``len(group)``; the length of each permutation in the group is given by ``group.size``. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([1, 0, 2]) >>> G = PermutationGroup([a]) >>> G.degree 3 >>> len(G) 1 >>> G.order() 2 >>> list(G.generate()) [(2), (2)(0 1)] >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.order() 6 See Also ======== degree """ if self._order is not None: return self._order if self._is_sym: n = self._degree self._order = factorial(n) return self._order if self._is_alt: n = self._degree self._order = factorial(n)/2 return self._order basic_transversals = self.basic_transversals m = 1 for x in basic_transversals: m *= len(x) self._order = m return m def index(self, H): """ Returns the index of a permutation group. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation(1,2,3) >>> b =Permutation(3) >>> G = PermutationGroup([a]) >>> H = PermutationGroup([b]) >>> G.index(H) 3 """ if H.is_subgroup(self): return self.order()//H.order() @property def is_symmetric(self): """Return ``True`` if the group is symmetric. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> g = SymmetricGroup(5) >>> g.is_symmetric True >>> from sympy.combinatorics import Permutation, PermutationGroup >>> g = PermutationGroup( ... Permutation(0, 1, 2, 3, 4), ... Permutation(2, 3)) >>> g.is_symmetric True Notes ===== This uses a naive test involving the computation of the full group order. If you need more quicker taxonomy for large groups, you can use :meth:`PermutationGroup.is_alt_sym`. However, :meth:`PermutationGroup.is_alt_sym` may not be accurate and is not able to distinguish between an alternating group and a symmetric group. See Also ======== is_alt_sym """ _is_sym = self._is_sym if _is_sym is not None: return _is_sym n = self.degree if n >= 8: if self.is_transitive(): _is_alt_sym = self._eval_is_alt_sym_monte_carlo() if _is_alt_sym: if any(g.is_odd for g in self.generators): self._is_sym, self._is_alt = True, False return True self._is_sym, self._is_alt = False, True return False return self._eval_is_alt_sym_naive(only_sym=True) self._is_sym, self._is_alt = False, False return False return self._eval_is_alt_sym_naive(only_sym=True) @property def is_alternating(self): """Return ``True`` if the group is alternating. Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> g = AlternatingGroup(5) >>> g.is_alternating True >>> from sympy.combinatorics import Permutation, PermutationGroup >>> g = PermutationGroup( ... Permutation(0, 1, 2, 3, 4), ... Permutation(2, 3, 4)) >>> g.is_alternating True Notes ===== This uses a naive test involving the computation of the full group order. If you need more quicker taxonomy for large groups, you can use :meth:`PermutationGroup.is_alt_sym`. However, :meth:`PermutationGroup.is_alt_sym` may not be accurate and is not able to distinguish between an alternating group and a symmetric group. See Also ======== is_alt_sym """ _is_alt = self._is_alt if _is_alt is not None: return _is_alt n = self.degree if n >= 8: if self.is_transitive(): _is_alt_sym = self._eval_is_alt_sym_monte_carlo() if _is_alt_sym: if all(g.is_even for g in self.generators): self._is_sym, self._is_alt = False, True return True self._is_sym, self._is_alt = True, False return False return self._eval_is_alt_sym_naive(only_alt=True) self._is_sym, self._is_alt = False, False return False return self._eval_is_alt_sym_naive(only_alt=True) @classmethod def _distinct_primes_lemma(cls, primes): """Subroutine to test if there is only one cyclic group for the order.""" primes = sorted(primes) l = len(primes) for i in range(l): for j in range(i+1, l): if primes[j] % primes[i] == 1: return None return True @property def is_cyclic(self): r""" Return ``True`` if the group is Cyclic. Examples ======== >>> from sympy.combinatorics.named_groups import AbelianGroup >>> G = AbelianGroup(3, 4) >>> G.is_cyclic True >>> G = AbelianGroup(4, 4) >>> G.is_cyclic False Notes ===== If the order of a group $n$ can be factored into the distinct primes $p_1, p_2, \dots , p_s$ and if .. math:: \forall i, j \in \{1, 2, \dots, s \}: p_i \not \equiv 1 \pmod {p_j} holds true, there is only one group of the order $n$ which is a cyclic group. [1]_ This is a generalization of the lemma that the group of order $15, 35, ...$ are cyclic. And also, these additional lemmas can be used to test if a group is cyclic if the order of the group is already found. - If the group is abelian and the order of the group is square-free, the group is cyclic. - If the order of the group is less than $6$ and is not $4$, the group is cyclic. - If the order of the group is prime, the group is cyclic. References ========== .. [1] 1978: John S. Rose: A Course on Group Theory, Introduction to Finite Group Theory: 1.4 """ if self._is_cyclic is not None: return self._is_cyclic if len(self.generators) == 1: self._is_cyclic = True self._is_abelian = True return True if self._is_abelian is False: self._is_cyclic = False return False order = self.order() if order < 6: self._is_abelian = True if order != 4: self._is_cyclic = True return True factors = factorint(order) if all(v == 1 for v in factors.values()): if self._is_abelian: self._is_cyclic = True return True primes = list(factors.keys()) if PermutationGroup._distinct_primes_lemma(primes) is True: self._is_cyclic = True self._is_abelian = True return True for p in factors: pgens = [] for g in self.generators: pgens.append(g**p) if self.index(self.subgroup(pgens)) != p: self._is_cyclic = False return False self._is_cyclic = True self._is_abelian = True return True def pointwise_stabilizer(self, points, incremental=True): r"""Return the pointwise stabilizer for a set of points. Explanation =========== For a permutation group `G` and a set of points `\{p_1, p_2,\ldots, p_k\}`, the pointwise stabilizer of `p_1, p_2, \ldots, p_k` is defined as `G_{p_1,\ldots, p_k} = \{g\in G | g(p_i) = p_i \forall i\in\{1, 2,\ldots,k\}\}` ([1],p20). It is a subgroup of `G`. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(7) >>> Stab = S.pointwise_stabilizer([2, 3, 5]) >>> Stab.is_subgroup(S.stabilizer(2).stabilizer(3).stabilizer(5)) True See Also ======== stabilizer, schreier_sims_incremental Notes ===== When incremental == True, rather than the obvious implementation using successive calls to ``.stabilizer()``, this uses the incremental Schreier-Sims algorithm to obtain a base with starting segment - the given points. """ if incremental: base, strong_gens = self.schreier_sims_incremental(base=points) stab_gens = [] degree = self.degree for gen in strong_gens: if [gen(point) for point in points] == points: stab_gens.append(gen) if not stab_gens: stab_gens = _af_new(list(range(degree))) return PermutationGroup(stab_gens) else: gens = self._generators degree = self.degree for x in points: gens = _stabilizer(degree, gens, x) return PermutationGroup(gens) def make_perm(self, n, seed=None): """ Multiply ``n`` randomly selected permutations from pgroup together, starting with the identity permutation. If ``n`` is a list of integers, those integers will be used to select the permutations and they will be applied in L to R order: make_perm((A, B, C)) will give CBA(I) where I is the identity permutation. ``seed`` is used to set the seed for the random selection of permutations from pgroup. If this is a list of integers, the corresponding permutations from pgroup will be selected in the order give. This is mainly used for testing purposes. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a, b = [Permutation([1, 0, 3, 2]), Permutation([1, 3, 0, 2])] >>> G = PermutationGroup([a, b]) >>> G.make_perm(1, [0]) (0 1)(2 3) >>> G.make_perm(3, [0, 1, 0]) (0 2 3 1) >>> G.make_perm([0, 1, 0]) (0 2 3 1) See Also ======== random """ if is_sequence(n): if seed is not None: raise ValueError('If n is a sequence, seed should be None') n, seed = len(n), n else: try: n = int(n) except TypeError: raise ValueError('n must be an integer or a sequence.') randomrange = _randrange(seed) # start with the identity permutation result = Permutation(list(range(self.degree))) m = len(self) for _ in range(n): p = self[randomrange(m)] result = rmul(result, p) return result def random(self, af=False): """Return a random group element """ rank = randrange(self.order()) return self.coset_unrank(rank, af) def random_pr(self, gen_count=11, iterations=50, _random_prec=None): """Return a random group element using product replacement. Explanation =========== For the details of the product replacement algorithm, see ``_random_pr_init`` In ``random_pr`` the actual 'product replacement' is performed. Notice that if the attribute ``_random_gens`` is empty, it needs to be initialized by ``_random_pr_init``. See Also ======== _random_pr_init """ if self._random_gens == []: self._random_pr_init(gen_count, iterations) random_gens = self._random_gens r = len(random_gens) - 1 # handle randomized input for testing purposes if _random_prec is None: s = randrange(r) t = randrange(r - 1) if t == s: t = r - 1 x = choice([1, 2]) e = choice([-1, 1]) else: s = _random_prec['s'] t = _random_prec['t'] if t == s: t = r - 1 x = _random_prec['x'] e = _random_prec['e'] if x == 1: random_gens[s] = _af_rmul(random_gens[s], _af_pow(random_gens[t], e)) random_gens[r] = _af_rmul(random_gens[r], random_gens[s]) else: random_gens[s] = _af_rmul(_af_pow(random_gens[t], e), random_gens[s]) random_gens[r] = _af_rmul(random_gens[s], random_gens[r]) return _af_new(random_gens[r]) def random_stab(self, alpha, schreier_vector=None, _random_prec=None): """Random element from the stabilizer of ``alpha``. The schreier vector for ``alpha`` is an optional argument used for speeding up repeated calls. The algorithm is described in [1], p.81 See Also ======== random_pr, orbit_rep """ if schreier_vector is None: schreier_vector = self.schreier_vector(alpha) if _random_prec is None: rand = self.random_pr() else: rand = _random_prec['rand'] beta = rand(alpha) h = self.orbit_rep(alpha, beta, schreier_vector) return rmul(~h, rand) def schreier_sims(self): """Schreier-Sims algorithm. Explanation =========== It computes the generators of the chain of stabilizers `G > G_{b_1} > .. > G_{b1,..,b_r} > 1` in which `G_{b_1,..,b_i}` stabilizes `b_1,..,b_i`, and the corresponding ``s`` cosets. An element of the group can be written as the product `h_1*..*h_s`. We use the incremental Schreier-Sims algorithm. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.schreier_sims() >>> G.basic_transversals [{0: (2)(0 1), 1: (2), 2: (1 2)}, {0: (2), 2: (0 2)}] """ if self._transversals: return self._schreier_sims() return def _schreier_sims(self, base=None): schreier = self.schreier_sims_incremental(base=base, slp_dict=True) base, strong_gens = schreier[:2] self._base = base self._strong_gens = strong_gens self._strong_gens_slp = schreier[2] if not base: self._transversals = [] self._basic_orbits = [] return strong_gens_distr = _distribute_gens_by_base(base, strong_gens) basic_orbits, transversals, slps = _orbits_transversals_from_bsgs(base,\ strong_gens_distr, slp=True) # rewrite the indices stored in slps in terms of strong_gens for i, slp in enumerate(slps): gens = strong_gens_distr[i] for k in slp: slp[k] = [strong_gens.index(gens[s]) for s in slp[k]] self._transversals = transversals self._basic_orbits = [sorted(x) for x in basic_orbits] self._transversal_slp = slps def schreier_sims_incremental(self, base=None, gens=None, slp_dict=False): """Extend a sequence of points and generating set to a base and strong generating set. Parameters ========== base The sequence of points to be extended to a base. Optional parameter with default value ``[]``. gens The generating set to be extended to a strong generating set relative to the base obtained. Optional parameter with default value ``self.generators``. slp_dict If `True`, return a dictionary `{g: gens}` for each strong generator `g` where `gens` is a list of strong generators coming before `g` in `strong_gens`, such that the product of the elements of `gens` is equal to `g`. Returns ======= (base, strong_gens) ``base`` is the base obtained, and ``strong_gens`` is the strong generating set relative to it. The original parameters ``base``, ``gens`` remain unchanged. Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> from sympy.combinatorics.testutil import _verify_bsgs >>> A = AlternatingGroup(7) >>> base = [2, 3] >>> seq = [2, 3] >>> base, strong_gens = A.schreier_sims_incremental(base=seq) >>> _verify_bsgs(A, base, strong_gens) True >>> base[:2] [2, 3] Notes ===== This version of the Schreier-Sims algorithm runs in polynomial time. There are certain assumptions in the implementation - if the trivial group is provided, ``base`` and ``gens`` are returned immediately, as any sequence of points is a base for the trivial group. If the identity is present in the generators ``gens``, it is removed as it is a redundant generator. The implementation is described in [1], pp. 90-93. See Also ======== schreier_sims, schreier_sims_random """ if base is None: base = [] if gens is None: gens = self.generators[:] degree = self.degree id_af = list(range(degree)) # handle the trivial group if len(gens) == 1 and gens[0].is_Identity: if slp_dict: return base, gens, {gens[0]: [gens[0]]} return base, gens # prevent side effects _base, _gens = base[:], gens[:] # remove the identity as a generator _gens = [x for x in _gens if not x.is_Identity] # make sure no generator fixes all base points for gen in _gens: if all(x == gen._array_form[x] for x in _base): for new in id_af: if gen._array_form[new] != new: break else: assert None # can this ever happen? _base.append(new) # distribute generators according to basic stabilizers strong_gens_distr = _distribute_gens_by_base(_base, _gens) strong_gens_slp = [] # initialize the basic stabilizers, basic orbits and basic transversals orbs = {} transversals = {} slps = {} base_len = len(_base) for i in range(base_len): transversals[i], slps[i] = _orbit_transversal(degree, strong_gens_distr[i], _base[i], pairs=True, af=True, slp=True) transversals[i] = dict(transversals[i]) orbs[i] = list(transversals[i].keys()) # main loop: amend the stabilizer chain until we have generators # for all stabilizers i = base_len - 1 while i >= 0: # this flag is used to continue with the main loop from inside # a nested loop continue_i = False # test the generators for being a strong generating set db = {} for beta, u_beta in list(transversals[i].items()): for j, gen in enumerate(strong_gens_distr[i]): gb = gen._array_form[beta] u1 = transversals[i][gb] g1 = _af_rmul(gen._array_form, u_beta) slp = [(i, g) for g in slps[i][beta]] slp = [(i, j)] + slp if g1 != u1: # test if the schreier generator is in the i+1-th # would-be basic stabilizer y = True try: u1_inv = db[gb] except KeyError: u1_inv = db[gb] = _af_invert(u1) schreier_gen = _af_rmul(u1_inv, g1) u1_inv_slp = slps[i][gb][:] u1_inv_slp.reverse() u1_inv_slp = [(i, (g,)) for g in u1_inv_slp] slp = u1_inv_slp + slp h, j, slp = _strip_af(schreier_gen, _base, orbs, transversals, i, slp=slp, slps=slps) if j <= base_len: # new strong generator h at level j y = False elif h: # h fixes all base points y = False moved = 0 while h[moved] == moved: moved += 1 _base.append(moved) base_len += 1 strong_gens_distr.append([]) if y is False: # if a new strong generator is found, update the # data structures and start over h = _af_new(h) strong_gens_slp.append((h, slp)) for l in range(i + 1, j): strong_gens_distr[l].append(h) transversals[l], slps[l] =\ _orbit_transversal(degree, strong_gens_distr[l], _base[l], pairs=True, af=True, slp=True) transversals[l] = dict(transversals[l]) orbs[l] = list(transversals[l].keys()) i = j - 1 # continue main loop using the flag continue_i = True if continue_i is True: break if continue_i is True: break if continue_i is True: continue i -= 1 strong_gens = _gens[:] if slp_dict: # create the list of the strong generators strong_gens and # rewrite the indices of strong_gens_slp in terms of the # elements of strong_gens for k, slp in strong_gens_slp: strong_gens.append(k) for i in range(len(slp)): s = slp[i] if isinstance(s[1], tuple): slp[i] = strong_gens_distr[s[0]][s[1][0]]**-1 else: slp[i] = strong_gens_distr[s[0]][s[1]] strong_gens_slp = dict(strong_gens_slp) # add the original generators for g in _gens: strong_gens_slp[g] = [g] return (_base, strong_gens, strong_gens_slp) strong_gens.extend([k for k, _ in strong_gens_slp]) return _base, strong_gens def schreier_sims_random(self, base=None, gens=None, consec_succ=10, _random_prec=None): r"""Randomized Schreier-Sims algorithm. Explanation =========== The randomized Schreier-Sims algorithm takes the sequence ``base`` and the generating set ``gens``, and extends ``base`` to a base, and ``gens`` to a strong generating set relative to that base with probability of a wrong answer at most `2^{-consec\_succ}`, provided the random generators are sufficiently random. Parameters ========== base The sequence to be extended to a base. gens The generating set to be extended to a strong generating set. consec_succ The parameter defining the probability of a wrong answer. _random_prec An internal parameter used for testing purposes. Returns ======= (base, strong_gens) ``base`` is the base and ``strong_gens`` is the strong generating set relative to it. Examples ======== >>> from sympy.combinatorics.testutil import _verify_bsgs >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(5) >>> base, strong_gens = S.schreier_sims_random(consec_succ=5) >>> _verify_bsgs(S, base, strong_gens) #doctest: +SKIP True Notes ===== The algorithm is described in detail in [1], pp. 97-98. It extends the orbits ``orbs`` and the permutation groups ``stabs`` to basic orbits and basic stabilizers for the base and strong generating set produced in the end. The idea of the extension process is to "sift" random group elements through the stabilizer chain and amend the stabilizers/orbits along the way when a sift is not successful. The helper function ``_strip`` is used to attempt to decompose a random group element according to the current state of the stabilizer chain and report whether the element was fully decomposed (successful sift) or not (unsuccessful sift). In the latter case, the level at which the sift failed is reported and used to amend ``stabs``, ``base``, ``gens`` and ``orbs`` accordingly. The halting condition is for ``consec_succ`` consecutive successful sifts to pass. This makes sure that the current ``base`` and ``gens`` form a BSGS with probability at least `1 - 1/\text{consec\_succ}`. See Also ======== schreier_sims """ if base is None: base = [] if gens is None: gens = self.generators base_len = len(base) n = self.degree # make sure no generator fixes all base points for gen in gens: if all(gen(x) == x for x in base): new = 0 while gen._array_form[new] == new: new += 1 base.append(new) base_len += 1 # distribute generators according to basic stabilizers strong_gens_distr = _distribute_gens_by_base(base, gens) # initialize the basic stabilizers, basic transversals and basic orbits transversals = {} orbs = {} for i in range(base_len): transversals[i] = dict(_orbit_transversal(n, strong_gens_distr[i], base[i], pairs=True)) orbs[i] = list(transversals[i].keys()) # initialize the number of consecutive elements sifted c = 0 # start sifting random elements while the number of consecutive sifts # is less than consec_succ while c < consec_succ: if _random_prec is None: g = self.random_pr() else: g = _random_prec['g'].pop() h, j = _strip(g, base, orbs, transversals) y = True # determine whether a new base point is needed if j <= base_len: y = False elif not h.is_Identity: y = False moved = 0 while h(moved) == moved: moved += 1 base.append(moved) base_len += 1 strong_gens_distr.append([]) # if the element doesn't sift, amend the strong generators and # associated stabilizers and orbits if y is False: for l in range(1, j): strong_gens_distr[l].append(h) transversals[l] = dict(_orbit_transversal(n, strong_gens_distr[l], base[l], pairs=True)) orbs[l] = list(transversals[l].keys()) c = 0 else: c += 1 # build the strong generating set strong_gens = strong_gens_distr[0][:] for gen in strong_gens_distr[1]: if gen not in strong_gens: strong_gens.append(gen) return base, strong_gens def schreier_vector(self, alpha): """Computes the schreier vector for ``alpha``. Explanation =========== The Schreier vector efficiently stores information about the orbit of ``alpha``. It can later be used to quickly obtain elements of the group that send ``alpha`` to a particular element in the orbit. Notice that the Schreier vector depends on the order in which the group generators are listed. For a definition, see [3]. Since list indices start from zero, we adopt the convention to use "None" instead of 0 to signify that an element doesn't belong to the orbit. For the algorithm and its correctness, see [2], pp.78-80. Examples ======== >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.permutations import Permutation >>> a = Permutation([2, 4, 6, 3, 1, 5, 0]) >>> b = Permutation([0, 1, 3, 5, 4, 6, 2]) >>> G = PermutationGroup([a, b]) >>> G.schreier_vector(0) [-1, None, 0, 1, None, 1, 0] See Also ======== orbit """ n = self.degree v = [None]*n v[alpha] = -1 orb = [alpha] used = [False]*n used[alpha] = True gens = self.generators r = len(gens) for b in orb: for i in range(r): temp = gens[i]._array_form[b] if used[temp] is False: orb.append(temp) used[temp] = True v[temp] = i return v def stabilizer(self, alpha): r"""Return the stabilizer subgroup of ``alpha``. Explanation =========== The stabilizer of `\alpha` is the group `G_\alpha = \{g \in G | g(\alpha) = \alpha\}`. For a proof of correctness, see [1], p.79. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> G = DihedralGroup(6) >>> G.stabilizer(5) PermutationGroup([ (5)(0 4)(1 3)]) See Also ======== orbit """ return PermGroup(_stabilizer(self._degree, self._generators, alpha)) @property def strong_gens(self): r"""Return a strong generating set from the Schreier-Sims algorithm. Explanation =========== A generating set `S = \{g_1, g_2, \dots, g_t\}` for a permutation group `G` is a strong generating set relative to the sequence of points (referred to as a "base") `(b_1, b_2, \dots, b_k)` if, for `1 \leq i \leq k` we have that the intersection of the pointwise stabilizer `G^{(i+1)} := G_{b_1, b_2, \dots, b_i}` with `S` generates the pointwise stabilizer `G^{(i+1)}`. The concepts of a base and strong generating set and their applications are discussed in depth in [1], pp. 87-89 and [2], pp. 55-57. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(4) >>> D.strong_gens [(0 1 2 3), (0 3)(1 2), (1 3)] >>> D.base [0, 1] See Also ======== base, basic_transversals, basic_orbits, basic_stabilizers """ if self._strong_gens == []: self.schreier_sims() return self._strong_gens def subgroup(self, gens): """ Return the subgroup generated by `gens` which is a list of elements of the group """ if not all(g in self for g in gens): raise ValueError("The group doesn't contain the supplied generators") G = PermutationGroup(gens) return G def subgroup_search(self, prop, base=None, strong_gens=None, tests=None, init_subgroup=None): """Find the subgroup of all elements satisfying the property ``prop``. Explanation =========== This is done by a depth-first search with respect to base images that uses several tests to prune the search tree. Parameters ========== prop The property to be used. Has to be callable on group elements and always return ``True`` or ``False``. It is assumed that all group elements satisfying ``prop`` indeed form a subgroup. base A base for the supergroup. strong_gens A strong generating set for the supergroup. tests A list of callables of length equal to the length of ``base``. These are used to rule out group elements by partial base images, so that ``tests[l](g)`` returns False if the element ``g`` is known not to satisfy prop base on where g sends the first ``l + 1`` base points. init_subgroup if a subgroup of the sought group is known in advance, it can be passed to the function as this parameter. Returns ======= res The subgroup of all elements satisfying ``prop``. The generating set for this group is guaranteed to be a strong generating set relative to the base ``base``. Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup) >>> from sympy.combinatorics.testutil import _verify_bsgs >>> S = SymmetricGroup(7) >>> prop_even = lambda x: x.is_even >>> base, strong_gens = S.schreier_sims_incremental() >>> G = S.subgroup_search(prop_even, base=base, strong_gens=strong_gens) >>> G.is_subgroup(AlternatingGroup(7)) True >>> _verify_bsgs(G, base, G.generators) True Notes ===== This function is extremely lengthy and complicated and will require some careful attention. The implementation is described in [1], pp. 114-117, and the comments for the code here follow the lines of the pseudocode in the book for clarity. The complexity is exponential in general, since the search process by itself visits all members of the supergroup. However, there are a lot of tests which are used to prune the search tree, and users can define their own tests via the ``tests`` parameter, so in practice, and for some computations, it's not terrible. A crucial part in the procedure is the frequent base change performed (this is line 11 in the pseudocode) in order to obtain a new basic stabilizer. The book mentiones that this can be done by using ``.baseswap(...)``, however the current implementation uses a more straightforward way to find the next basic stabilizer - calling the function ``.stabilizer(...)`` on the previous basic stabilizer. """ # initialize BSGS and basic group properties def get_reps(orbits): # get the minimal element in the base ordering return [min(orbit, key = lambda x: base_ordering[x]) \ for orbit in orbits] def update_nu(l): temp_index = len(basic_orbits[l]) + 1 -\ len(res_basic_orbits_init_base[l]) # this corresponds to the element larger than all points if temp_index >= len(sorted_orbits[l]): nu[l] = base_ordering[degree] else: nu[l] = sorted_orbits[l][temp_index] if base is None: base, strong_gens = self.schreier_sims_incremental() base_len = len(base) degree = self.degree identity = _af_new(list(range(degree))) base_ordering = _base_ordering(base, degree) # add an element larger than all points base_ordering.append(degree) # add an element smaller than all points base_ordering.append(-1) # compute BSGS-related structures strong_gens_distr = _distribute_gens_by_base(base, strong_gens) basic_orbits, transversals = _orbits_transversals_from_bsgs(base, strong_gens_distr) # handle subgroup initialization and tests if init_subgroup is None: init_subgroup = PermutationGroup([identity]) if tests is None: trivial_test = lambda x: True tests = [] for i in range(base_len): tests.append(trivial_test) # line 1: more initializations. res = init_subgroup f = base_len - 1 l = base_len - 1 # line 2: set the base for K to the base for G res_base = base[:] # line 3: compute BSGS and related structures for K res_base, res_strong_gens = res.schreier_sims_incremental( base=res_base) res_strong_gens_distr = _distribute_gens_by_base(res_base, res_strong_gens) res_generators = res.generators res_basic_orbits_init_base = \ [_orbit(degree, res_strong_gens_distr[i], res_base[i])\ for i in range(base_len)] # initialize orbit representatives orbit_reps = [None]*base_len # line 4: orbit representatives for f-th basic stabilizer of K orbits = _orbits(degree, res_strong_gens_distr[f]) orbit_reps[f] = get_reps(orbits) # line 5: remove the base point from the representatives to avoid # getting the identity element as a generator for K orbit_reps[f].remove(base[f]) # line 6: more initializations c = [0]*base_len u = [identity]*base_len sorted_orbits = [None]*base_len for i in range(base_len): sorted_orbits[i] = basic_orbits[i][:] sorted_orbits[i].sort(key=lambda point: base_ordering[point]) # line 7: initializations mu = [None]*base_len nu = [None]*base_len # this corresponds to the element smaller than all points mu[l] = degree + 1 update_nu(l) # initialize computed words computed_words = [identity]*base_len # line 8: main loop while True: # apply all the tests while l < base_len - 1 and \ computed_words[l](base[l]) in orbit_reps[l] and \ base_ordering[mu[l]] < \ base_ordering[computed_words[l](base[l])] < \ base_ordering[nu[l]] and \ tests[l](computed_words): # line 11: change the (partial) base of K new_point = computed_words[l](base[l]) res_base[l] = new_point new_stab_gens = _stabilizer(degree, res_strong_gens_distr[l], new_point) res_strong_gens_distr[l + 1] = new_stab_gens # line 12: calculate minimal orbit representatives for the # l+1-th basic stabilizer orbits = _orbits(degree, new_stab_gens) orbit_reps[l + 1] = get_reps(orbits) # line 13: amend sorted orbits l += 1 temp_orbit = [computed_words[l - 1](point) for point in basic_orbits[l]] temp_orbit.sort(key=lambda point: base_ordering[point]) sorted_orbits[l] = temp_orbit # lines 14 and 15: update variables used minimality tests new_mu = degree + 1 for i in range(l): if base[l] in res_basic_orbits_init_base[i]: candidate = computed_words[i](base[i]) if base_ordering[candidate] > base_ordering[new_mu]: new_mu = candidate mu[l] = new_mu update_nu(l) # line 16: determine the new transversal element c[l] = 0 temp_point = sorted_orbits[l][c[l]] gamma = computed_words[l - 1]._array_form.index(temp_point) u[l] = transversals[l][gamma] # update computed words computed_words[l] = rmul(computed_words[l - 1], u[l]) # lines 17 & 18: apply the tests to the group element found g = computed_words[l] temp_point = g(base[l]) if l == base_len - 1 and \ base_ordering[mu[l]] < \ base_ordering[temp_point] < base_ordering[nu[l]] and \ temp_point in orbit_reps[l] and \ tests[l](computed_words) and \ prop(g): # line 19: reset the base of K res_generators.append(g) res_base = base[:] # line 20: recalculate basic orbits (and transversals) res_strong_gens.append(g) res_strong_gens_distr = _distribute_gens_by_base(res_base, res_strong_gens) res_basic_orbits_init_base = \ [_orbit(degree, res_strong_gens_distr[i], res_base[i]) \ for i in range(base_len)] # line 21: recalculate orbit representatives # line 22: reset the search depth orbit_reps[f] = get_reps(orbits) l = f # line 23: go up the tree until in the first branch not fully # searched while l >= 0 and c[l] == len(basic_orbits[l]) - 1: l = l - 1 # line 24: if the entire tree is traversed, return K if l == -1: return PermutationGroup(res_generators) # lines 25-27: update orbit representatives if l < f: # line 26 f = l c[l] = 0 # line 27 temp_orbits = _orbits(degree, res_strong_gens_distr[f]) orbit_reps[f] = get_reps(temp_orbits) # line 28: update variables used for minimality testing mu[l] = degree + 1 temp_index = len(basic_orbits[l]) + 1 - \ len(res_basic_orbits_init_base[l]) if temp_index >= len(sorted_orbits[l]): nu[l] = base_ordering[degree] else: nu[l] = sorted_orbits[l][temp_index] # line 29: set the next element from the current branch and update # accordingly c[l] += 1 if l == 0: gamma = sorted_orbits[l][c[l]] else: gamma = computed_words[l - 1]._array_form.index(sorted_orbits[l][c[l]]) u[l] = transversals[l][gamma] if l == 0: computed_words[l] = u[l] else: computed_words[l] = rmul(computed_words[l - 1], u[l]) @property def transitivity_degree(self): r"""Compute the degree of transitivity of the group. Explanation =========== A permutation group `G` acting on `\Omega = \{0, 1, \dots, n-1\}` is ``k``-fold transitive, if, for any `k` points `(a_1, a_2, \dots, a_k) \in \Omega` and any `k` points `(b_1, b_2, \dots, b_k) \in \Omega` there exists `g \in G` such that `g(a_1) = b_1, g(a_2) = b_2, \dots, g(a_k) = b_k` The degree of transitivity of `G` is the maximum ``k`` such that `G` is ``k``-fold transitive. ([8]) Examples ======== >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.permutations import Permutation >>> a = Permutation([1, 2, 0]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.transitivity_degree 3 See Also ======== is_transitive, orbit """ if self._transitivity_degree is None: n = self.degree G = self # if G is k-transitive, a tuple (a_0,..,a_k) # can be brought to (b_0,...,b_(k-1), b_k) # where b_0,...,b_(k-1) are fixed points; # consider the group G_k which stabilizes b_0,...,b_(k-1) # if G_k is transitive on the subset excluding b_0,...,b_(k-1) # then G is (k+1)-transitive for i in range(n): orb = G.orbit(i) if len(orb) != n - i: self._transitivity_degree = i return i G = G.stabilizer(i) self._transitivity_degree = n return n else: return self._transitivity_degree def _p_elements_group(self, p): ''' For an abelian p-group, return the subgroup consisting of all elements of order p (and the identity) ''' gens = self.generators[:] gens = sorted(gens, key=lambda x: x.order(), reverse=True) gens_p = [g**(g.order()/p) for g in gens] gens_r = [] for i in range(len(gens)): x = gens[i] x_order = x.order() # x_p has order p x_p = x**(x_order/p) if i > 0: P = PermutationGroup(gens_p[:i]) else: P = PermutationGroup(self.identity) if x**(x_order/p) not in P: gens_r.append(x**(x_order/p)) else: # replace x by an element of order (x.order()/p) # so that gens still generates G g = P.generator_product(x_p, original=True) for s in g: x = x*s**-1 x_order = x_order/p # insert x to gens so that the sorting is preserved del gens[i] del gens_p[i] j = i - 1 while j < len(gens) and gens[j].order() >= x_order: j += 1 gens = gens[:j] + [x] + gens[j:] gens_p = gens_p[:j] + [x] + gens_p[j:] return PermutationGroup(gens_r) def _sylow_alt_sym(self, p): ''' Return a p-Sylow subgroup of a symmetric or an alternating group. Explanation =========== The algorithm for this is hinted at in [1], Chapter 4, Exercise 4. For Sym(n) with n = p^i, the idea is as follows. Partition the interval [0..n-1] into p equal parts, each of length p^(i-1): [0..p^(i-1)-1], [p^(i-1)..2*p^(i-1)-1]...[(p-1)*p^(i-1)..p^i-1]. Find a p-Sylow subgroup of Sym(p^(i-1)) (treated as a subgroup of ``self``) acting on each of the parts. Call the subgroups P_1, P_2...P_p. The generators for the subgroups P_2...P_p can be obtained from those of P_1 by applying a "shifting" permutation to them, that is, a permutation mapping [0..p^(i-1)-1] to the second part (the other parts are obtained by using the shift multiple times). The union of this permutation and the generators of P_1 is a p-Sylow subgroup of ``self``. For n not equal to a power of p, partition [0..n-1] in accordance with how n would be written in base p. E.g. for p=2 and n=11, 11 = 2^3 + 2^2 + 1 so the partition is [[0..7], [8..9], {10}]. To generate a p-Sylow subgroup, take the union of the generators for each of the parts. For the above example, {(0 1), (0 2)(1 3), (0 4), (1 5)(2 7)} from the first part, {(8 9)} from the second part and nothing from the third. This gives 4 generators in total, and the subgroup they generate is p-Sylow. Alternating groups are treated the same except when p=2. In this case, (0 1)(s s+1) should be added for an appropriate s (the start of a part) for each part in the partitions. See Also ======== sylow_subgroup, is_alt_sym ''' n = self.degree gens = [] identity = Permutation(n-1) # the case of 2-sylow subgroups of alternating groups # needs special treatment alt = p == 2 and all(g.is_even for g in self.generators) # find the presentation of n in base p coeffs = [] m = n while m > 0: coeffs.append(m % p) m = m // p power = len(coeffs)-1 # for a symmetric group, gens[:i] is the generating # set for a p-Sylow subgroup on [0..p**(i-1)-1]. For # alternating groups, the same is given by gens[:2*(i-1)] for i in range(1, power+1): if i == 1 and alt: # (0 1) shouldn't be added for alternating groups continue gen = Permutation([(j + p**(i-1)) % p**i for j in range(p**i)]) gens.append(identity*gen) if alt: gen = Permutation(0, 1)*gen*Permutation(0, 1)*gen gens.append(gen) # the first point in the current part (see the algorithm # description in the docstring) start = 0 while power > 0: a = coeffs[power] # make the permutation shifting the start of the first # part ([0..p^i-1] for some i) to the current one for _ in range(a): shift = Permutation() if start > 0: for i in range(p**power): shift = shift(i, start + i) if alt: gen = Permutation(0, 1)*shift*Permutation(0, 1)*shift gens.append(gen) j = 2*(power - 1) else: j = power for i, gen in enumerate(gens[:j]): if alt and i % 2 == 1: continue # shift the generator to the start of the # partition part gen = shift*gen*shift gens.append(gen) start += p**power power = power-1 return gens def sylow_subgroup(self, p): ''' Return a p-Sylow subgroup of the group. The algorithm is described in [1], Chapter 4, Section 7 Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> D = DihedralGroup(6) >>> S = D.sylow_subgroup(2) >>> S.order() 4 >>> G = SymmetricGroup(6) >>> S = G.sylow_subgroup(5) >>> S.order() 5 >>> G1 = AlternatingGroup(3) >>> G2 = AlternatingGroup(5) >>> G3 = AlternatingGroup(9) >>> S1 = G1.sylow_subgroup(3) >>> S2 = G2.sylow_subgroup(3) >>> S3 = G3.sylow_subgroup(3) >>> len1 = len(S1.lower_central_series()) >>> len2 = len(S2.lower_central_series()) >>> len3 = len(S3.lower_central_series()) >>> len1 == len2 True >>> len1 < len3 True ''' from sympy.combinatorics.homomorphisms import ( orbit_homomorphism, block_homomorphism) from sympy.ntheory.primetest import isprime if not isprime(p): raise ValueError("p must be a prime") def is_p_group(G): # check if the order of G is a power of p # and return the power m = G.order() n = 0 while m % p == 0: m = m/p n += 1 if m == 1: return True, n return False, n def _sylow_reduce(mu, nu): # reduction based on two homomorphisms # mu and nu with trivially intersecting # kernels Q = mu.image().sylow_subgroup(p) Q = mu.invert_subgroup(Q) nu = nu.restrict_to(Q) R = nu.image().sylow_subgroup(p) return nu.invert_subgroup(R) order = self.order() if order % p != 0: return PermutationGroup([self.identity]) p_group, n = is_p_group(self) if p_group: return self if self.is_alt_sym(): return PermutationGroup(self._sylow_alt_sym(p)) # if there is a non-trivial orbit with size not divisible # by p, the sylow subgroup is contained in its stabilizer # (by orbit-stabilizer theorem) orbits = self.orbits() non_p_orbits = [o for o in orbits if len(o) % p != 0 and len(o) != 1] if non_p_orbits: G = self.stabilizer(list(non_p_orbits[0]).pop()) return G.sylow_subgroup(p) if not self.is_transitive(): # apply _sylow_reduce to orbit actions orbits = sorted(orbits, key=len) omega1 = orbits.pop() omega2 = orbits[0].union(*orbits) mu = orbit_homomorphism(self, omega1) nu = orbit_homomorphism(self, omega2) return _sylow_reduce(mu, nu) blocks = self.minimal_blocks() if len(blocks) > 1: # apply _sylow_reduce to block system actions mu = block_homomorphism(self, blocks[0]) nu = block_homomorphism(self, blocks[1]) return _sylow_reduce(mu, nu) elif len(blocks) == 1: block = list(blocks)[0] if any(e != 0 for e in block): # self is imprimitive mu = block_homomorphism(self, block) if not is_p_group(mu.image())[0]: S = mu.image().sylow_subgroup(p) return mu.invert_subgroup(S).sylow_subgroup(p) # find an element of order p g = self.random() g_order = g.order() while g_order % p != 0 or g_order == 0: g = self.random() g_order = g.order() g = g**(g_order // p) if order % p**2 != 0: return PermutationGroup(g) C = self.centralizer(g) while C.order() % p**n != 0: S = C.sylow_subgroup(p) s_order = S.order() Z = S.center() P = Z._p_elements_group(p) h = P.random() C_h = self.centralizer(h) while C_h.order() % p*s_order != 0: h = P.random() C_h = self.centralizer(h) C = C_h return C.sylow_subgroup(p) def _block_verify(self, L, alpha): delta = sorted(list(self.orbit(alpha))) # p[i] will be the number of the block # delta[i] belongs to p = [-1]*len(delta) blocks = [-1]*len(delta) B = [[]] # future list of blocks u = [0]*len(delta) # u[i] in L s.t. alpha^u[i] = B[0][i] t = L.orbit_transversal(alpha, pairs=True) for a, beta in t: B[0].append(a) i_a = delta.index(a) p[i_a] = 0 blocks[i_a] = alpha u[i_a] = beta rho = 0 m = 0 # number of blocks - 1 while rho <= m: beta = B[rho][0] for g in self.generators: d = beta^g i_d = delta.index(d) sigma = p[i_d] if sigma < 0: # define a new block m += 1 sigma = m u[i_d] = u[delta.index(beta)]*g p[i_d] = sigma rep = d blocks[i_d] = rep newb = [rep] for gamma in B[rho][1:]: i_gamma = delta.index(gamma) d = gamma^g i_d = delta.index(d) if p[i_d] < 0: u[i_d] = u[i_gamma]*g p[i_d] = sigma blocks[i_d] = rep newb.append(d) else: # B[rho] is not a block s = u[i_gamma]*g*u[i_d]**(-1) return False, s B.append(newb) else: for h in B[rho][1:]: if h^g not in B[sigma]: # B[rho] is not a block s = u[delta.index(beta)]*g*u[i_d]**(-1) return False, s rho += 1 return True, blocks def _verify(H, K, phi, z, alpha): ''' Return a list of relators ``rels`` in generators ``gens`_h` that are mapped to ``H.generators`` by ``phi`` so that given a finite presentation <gens_k | rels_k> of ``K`` on a subset of ``gens_h`` <gens_h | rels_k + rels> is a finite presentation of ``H``. Explanation =========== ``H`` should be generated by the union of ``K.generators`` and ``z`` (a single generator), and ``H.stabilizer(alpha) == K``; ``phi`` is a canonical injection from a free group into a permutation group containing ``H``. The algorithm is described in [1], Chapter 6. Examples ======== >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.homomorphisms import homomorphism >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup >>> H = PermutationGroup(Permutation(0, 2), Permutation (1, 5)) >>> K = PermutationGroup(Permutation(5)(0, 2)) >>> F = free_group("x_0 x_1")[0] >>> gens = F.generators >>> phi = homomorphism(F, H, F.generators, H.generators) >>> rels_k = [gens[0]**2] # relators for presentation of K >>> z= Permutation(1, 5) >>> check, rels_h = H._verify(K, phi, z, 1) >>> check True >>> rels = rels_k + rels_h >>> G = FpGroup(F, rels) # presentation of H >>> G.order() == H.order() True See also ======== strong_presentation, presentation, stabilizer ''' orbit = H.orbit(alpha) beta = alpha^(z**-1) K_beta = K.stabilizer(beta) # orbit representatives of K_beta gammas = [alpha, beta] orbits = list({tuple(K_beta.orbit(o)) for o in orbit}) orbit_reps = [orb[0] for orb in orbits] for rep in orbit_reps: if rep not in gammas: gammas.append(rep) # orbit transversal of K betas = [alpha, beta] transversal = {alpha: phi.invert(H.identity), beta: phi.invert(z**-1)} for s, g in K.orbit_transversal(beta, pairs=True): if s not in transversal: transversal[s] = transversal[beta]*phi.invert(g) union = K.orbit(alpha).union(K.orbit(beta)) while (len(union) < len(orbit)): for gamma in gammas: if gamma in union: r = gamma^z if r not in union: betas.append(r) transversal[r] = transversal[gamma]*phi.invert(z) for s, g in K.orbit_transversal(r, pairs=True): if s not in transversal: transversal[s] = transversal[r]*phi.invert(g) union = union.union(K.orbit(r)) break # compute relators rels = [] for b in betas: k_gens = K.stabilizer(b).generators for y in k_gens: new_rel = transversal[b] gens = K.generator_product(y, original=True) for g in gens[::-1]: new_rel = new_rel*phi.invert(g) new_rel = new_rel*transversal[b]**-1 perm = phi(new_rel) try: gens = K.generator_product(perm, original=True) except ValueError: return False, perm for g in gens: new_rel = new_rel*phi.invert(g)**-1 if new_rel not in rels: rels.append(new_rel) for gamma in gammas: new_rel = transversal[gamma]*phi.invert(z)*transversal[gamma^z]**-1 perm = phi(new_rel) try: gens = K.generator_product(perm, original=True) except ValueError: return False, perm for g in gens: new_rel = new_rel*phi.invert(g)**-1 if new_rel not in rels: rels.append(new_rel) return True, rels def strong_presentation(self): ''' Return a strong finite presentation of group. The generators of the returned group are in the same order as the strong generators of group. The algorithm is based on Sims' Verify algorithm described in [1], Chapter 6. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> P = DihedralGroup(4) >>> G = P.strong_presentation() >>> P.order() == G.order() True See Also ======== presentation, _verify ''' from sympy.combinatorics.fp_groups import (FpGroup, simplify_presentation) from sympy.combinatorics.free_groups import free_group from sympy.combinatorics.homomorphisms import (block_homomorphism, homomorphism, GroupHomomorphism) strong_gens = self.strong_gens[:] stabs = self.basic_stabilizers[:] base = self.base[:] # injection from a free group on len(strong_gens) # generators into G gen_syms = [('x_%d'%i) for i in range(len(strong_gens))] F = free_group(', '.join(gen_syms))[0] phi = homomorphism(F, self, F.generators, strong_gens) H = PermutationGroup(self.identity) while stabs: alpha = base.pop() K = H H = stabs.pop() new_gens = [g for g in H.generators if g not in K] if K.order() == 1: z = new_gens.pop() rels = [F.generators[-1]**z.order()] intermediate_gens = [z] K = PermutationGroup(intermediate_gens) # add generators one at a time building up from K to H while new_gens: z = new_gens.pop() intermediate_gens = [z] + intermediate_gens K_s = PermutationGroup(intermediate_gens) orbit = K_s.orbit(alpha) orbit_k = K.orbit(alpha) # split into cases based on the orbit of K_s if orbit_k == orbit: if z in K: rel = phi.invert(z) perm = z else: t = K.orbit_rep(alpha, alpha^z) rel = phi.invert(z)*phi.invert(t)**-1 perm = z*t**-1 for g in K.generator_product(perm, original=True): rel = rel*phi.invert(g)**-1 new_rels = [rel] elif len(orbit_k) == 1: # `success` is always true because `strong_gens` # and `base` are already a verified BSGS. Later # this could be changed to start with a randomly # generated (potential) BSGS, and then new elements # would have to be appended to it when `success` # is false. success, new_rels = K_s._verify(K, phi, z, alpha) else: # K.orbit(alpha) should be a block # under the action of K_s on K_s.orbit(alpha) check, block = K_s._block_verify(K, alpha) if check: # apply _verify to the action of K_s # on the block system; for convenience, # add the blocks as additional points # that K_s should act on t = block_homomorphism(K_s, block) m = t.codomain.degree # number of blocks d = K_s.degree # conjugating with p will shift # permutations in t.image() to # higher numbers, e.g. # p*(0 1)*p = (m m+1) p = Permutation() for i in range(m): p *= Permutation(i, i+d) t_img = t.images # combine generators of K_s with their # action on the block system images = {g: g*p*t_img[g]*p for g in t_img} for g in self.strong_gens[:-len(K_s.generators)]: images[g] = g K_s_act = PermutationGroup(list(images.values())) f = GroupHomomorphism(self, K_s_act, images) K_act = PermutationGroup([f(g) for g in K.generators]) success, new_rels = K_s_act._verify(K_act, f.compose(phi), f(z), d) for n in new_rels: if n not in rels: rels.append(n) K = K_s group = FpGroup(F, rels) return simplify_presentation(group) def presentation(self, eliminate_gens=True): ''' Return an `FpGroup` presentation of the group. The algorithm is described in [1], Chapter 6.1. ''' from sympy.combinatorics.fp_groups import (FpGroup, simplify_presentation) from sympy.combinatorics.coset_table import CosetTable from sympy.combinatorics.free_groups import free_group from sympy.combinatorics.homomorphisms import homomorphism from itertools import product if self._fp_presentation: return self._fp_presentation def _factor_group_by_rels(G, rels): if isinstance(G, FpGroup): rels.extend(G.relators) return FpGroup(G.free_group, list(set(rels))) return FpGroup(G, rels) gens = self.generators len_g = len(gens) if len_g == 1: order = gens[0].order() # handle the trivial group if order == 1: return free_group([])[0] F, x = free_group('x') return FpGroup(F, [x**order]) if self.order() > 20: half_gens = self.generators[0:(len_g+1)//2] else: half_gens = [] H = PermutationGroup(half_gens) H_p = H.presentation() len_h = len(H_p.generators) C = self.coset_table(H) n = len(C) # subgroup index gen_syms = [('x_%d'%i) for i in range(len(gens))] F = free_group(', '.join(gen_syms))[0] # mapping generators of H_p to those of F images = [F.generators[i] for i in range(len_h)] R = homomorphism(H_p, F, H_p.generators, images, check=False) # rewrite relators rels = R(H_p.relators) G_p = FpGroup(F, rels) # injective homomorphism from G_p into self T = homomorphism(G_p, self, G_p.generators, gens) C_p = CosetTable(G_p, []) C_p.table = [[None]*(2*len_g) for i in range(n)] # initiate the coset transversal transversal = [None]*n transversal[0] = G_p.identity # fill in the coset table as much as possible for i in range(2*len_h): C_p.table[0][i] = 0 gamma = 1 for alpha, x in product(range(0, n), range(2*len_g)): beta = C[alpha][x] if beta == gamma: gen = G_p.generators[x//2]**((-1)**(x % 2)) transversal[beta] = transversal[alpha]*gen C_p.table[alpha][x] = beta C_p.table[beta][x + (-1)**(x % 2)] = alpha gamma += 1 if gamma == n: break C_p.p = list(range(n)) beta = x = 0 while not C_p.is_complete(): # find the first undefined entry while C_p.table[beta][x] == C[beta][x]: x = (x + 1) % (2*len_g) if x == 0: beta = (beta + 1) % n # define a new relator gen = G_p.generators[x//2]**((-1)**(x % 2)) new_rel = transversal[beta]*gen*transversal[C[beta][x]]**-1 perm = T(new_rel) nxt = G_p.identity for s in H.generator_product(perm, original=True): nxt = nxt*T.invert(s)**-1 new_rel = new_rel*nxt # continue coset enumeration G_p = _factor_group_by_rels(G_p, [new_rel]) C_p.scan_and_fill(0, new_rel) C_p = G_p.coset_enumeration([], strategy="coset_table", draft=C_p, max_cosets=n, incomplete=True) self._fp_presentation = simplify_presentation(G_p) return self._fp_presentation def polycyclic_group(self): """ Return the PolycyclicGroup instance with below parameters: Explanation =========== * ``pc_sequence`` : Polycyclic sequence is formed by collecting all the missing generators between the adjacent groups in the derived series of given permutation group. * ``pc_series`` : Polycyclic series is formed by adding all the missing generators of ``der[i+1]`` in ``der[i]``, where ``der`` represents the derived series. * ``relative_order`` : A list, computed by the ratio of adjacent groups in pc_series. """ from sympy.combinatorics.pc_groups import PolycyclicGroup if not self.is_polycyclic: raise ValueError("The group must be solvable") der = self.derived_series() pc_series = [] pc_sequence = [] relative_order = [] pc_series.append(der[-1]) der.reverse() for i in range(len(der)-1): H = der[i] for g in der[i+1].generators: if g not in H: H = PermutationGroup([g] + H.generators) pc_series.insert(0, H) pc_sequence.insert(0, g) G1 = pc_series[0].order() G2 = pc_series[1].order() relative_order.insert(0, G1 // G2) return PolycyclicGroup(pc_sequence, pc_series, relative_order, collector=None) def _orbit(degree, generators, alpha, action='tuples'): r"""Compute the orbit of alpha `\{g(\alpha) | g \in G\}` as a set. Explanation =========== The time complexity of the algorithm used here is `O(|Orb|*r)` where `|Orb|` is the size of the orbit and ``r`` is the number of generators of the group. For a more detailed analysis, see [1], p.78, [2], pp. 19-21. Here alpha can be a single point, or a list of points. If alpha is a single point, the ordinary orbit is computed. if alpha is a list of points, there are three available options: 'union' - computes the union of the orbits of the points in the list 'tuples' - computes the orbit of the list interpreted as an ordered tuple under the group action ( i.e., g((1, 2, 3)) = (g(1), g(2), g(3)) ) 'sets' - computes the orbit of the list interpreted as a sets Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup, _orbit >>> a = Permutation([1, 2, 0, 4, 5, 6, 3]) >>> G = PermutationGroup([a]) >>> _orbit(G.degree, G.generators, 0) {0, 1, 2} >>> _orbit(G.degree, G.generators, [0, 4], 'union') {0, 1, 2, 3, 4, 5, 6} See Also ======== orbit, orbit_transversal """ if not hasattr(alpha, '__getitem__'): alpha = [alpha] gens = [x._array_form for x in generators] if len(alpha) == 1 or action == 'union': orb = alpha used = [False]*degree for el in alpha: used[el] = True for b in orb: for gen in gens: temp = gen[b] if used[temp] == False: orb.append(temp) used[temp] = True return set(orb) elif action == 'tuples': alpha = tuple(alpha) orb = [alpha] used = {alpha} for b in orb: for gen in gens: temp = tuple([gen[x] for x in b]) if temp not in used: orb.append(temp) used.add(temp) return set(orb) elif action == 'sets': alpha = frozenset(alpha) orb = [alpha] used = {alpha} for b in orb: for gen in gens: temp = frozenset([gen[x] for x in b]) if temp not in used: orb.append(temp) used.add(temp) return {tuple(x) for x in orb} def _orbits(degree, generators): """Compute the orbits of G. If ``rep=False`` it returns a list of sets else it returns a list of representatives of the orbits Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.perm_groups import _orbits >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> _orbits(a.size, [a, b]) [{0, 1, 2}] """ orbs = [] sorted_I = list(range(degree)) I = set(sorted_I) while I: i = sorted_I[0] orb = _orbit(degree, generators, i) orbs.append(orb) # remove all indices that are in this orbit I -= orb sorted_I = [i for i in sorted_I if i not in orb] return orbs def _orbit_transversal(degree, generators, alpha, pairs, af=False, slp=False): r"""Computes a transversal for the orbit of ``alpha`` as a set. Explanation =========== generators generators of the group ``G`` For a permutation group ``G``, a transversal for the orbit `Orb = \{g(\alpha) | g \in G\}` is a set `\{g_\beta | g_\beta(\alpha) = \beta\}` for `\beta \in Orb`. Note that there may be more than one possible transversal. If ``pairs`` is set to ``True``, it returns the list of pairs `(\beta, g_\beta)`. For a proof of correctness, see [1], p.79 if ``af`` is ``True``, the transversal elements are given in array form. If `slp` is `True`, a dictionary `{beta: slp_beta}` is returned for `\beta \in Orb` where `slp_beta` is a list of indices of the generators in `generators` s.t. if `slp_beta = [i_1 \dots i_n]` `g_\beta = generators[i_n] \times \dots \times generators[i_1]`. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> from sympy.combinatorics.perm_groups import _orbit_transversal >>> G = DihedralGroup(6) >>> _orbit_transversal(G.degree, G.generators, 0, False) [(5), (0 1 2 3 4 5), (0 5)(1 4)(2 3), (0 2 4)(1 3 5), (5)(0 4)(1 3), (0 3)(1 4)(2 5)] """ tr = [(alpha, list(range(degree)))] slp_dict = {alpha: []} used = [False]*degree used[alpha] = True gens = [x._array_form for x in generators] for x, px in tr: px_slp = slp_dict[x] for gen in gens: temp = gen[x] if used[temp] == False: slp_dict[temp] = [gens.index(gen)] + px_slp tr.append((temp, _af_rmul(gen, px))) used[temp] = True if pairs: if not af: tr = [(x, _af_new(y)) for x, y in tr] if not slp: return tr return tr, slp_dict if af: tr = [y for _, y in tr] if not slp: return tr return tr, slp_dict tr = [_af_new(y) for _, y in tr] if not slp: return tr return tr, slp_dict def _stabilizer(degree, generators, alpha): r"""Return the stabilizer subgroup of ``alpha``. Explanation =========== The stabilizer of `\alpha` is the group `G_\alpha = \{g \in G | g(\alpha) = \alpha\}`. For a proof of correctness, see [1], p.79. degree : degree of G generators : generators of G Examples ======== >>> from sympy.combinatorics.perm_groups import _stabilizer >>> from sympy.combinatorics.named_groups import DihedralGroup >>> G = DihedralGroup(6) >>> _stabilizer(G.degree, G.generators, 5) [(5)(0 4)(1 3), (5)] See Also ======== orbit """ orb = [alpha] table = {alpha: list(range(degree))} table_inv = {alpha: list(range(degree))} used = [False]*degree used[alpha] = True gens = [x._array_form for x in generators] stab_gens = [] for b in orb: for gen in gens: temp = gen[b] if used[temp] is False: gen_temp = _af_rmul(gen, table[b]) orb.append(temp) table[temp] = gen_temp table_inv[temp] = _af_invert(gen_temp) used[temp] = True else: schreier_gen = _af_rmuln(table_inv[temp], gen, table[b]) if schreier_gen not in stab_gens: stab_gens.append(schreier_gen) return [_af_new(x) for x in stab_gens] PermGroup = PermutationGroup class SymmetricPermutationGroup(Basic): """ The class defining the lazy form of SymmetricGroup. deg : int """ def __new__(cls, deg): deg = _sympify(deg) obj = Basic.__new__(cls, deg) return obj def __init__(self, *args, **kwargs): self._deg = self.args[0] self._order = None def __contains__(self, i): """Return ``True`` if *i* is contained in SymmetricPermutationGroup. Examples ======== >>> from sympy.combinatorics import Permutation, SymmetricPermutationGroup >>> G = SymmetricPermutationGroup(4) >>> Permutation(1, 2, 3) in G True """ if not isinstance(i, Permutation): raise TypeError("A SymmetricPermutationGroup contains only Permutations as " "elements, not elements of type %s" % type(i)) return i.size == self.degree def order(self): """ Return the order of the SymmetricPermutationGroup. Examples ======== >>> from sympy.combinatorics import SymmetricPermutationGroup >>> G = SymmetricPermutationGroup(4) >>> G.order() 24 """ if self._order is not None: return self._order n = self._deg self._order = factorial(n) return self._order @property def degree(self): """ Return the degree of the SymmetricPermutationGroup. Examples ======== >>> from sympy.combinatorics import SymmetricPermutationGroup >>> G = SymmetricPermutationGroup(4) >>> G.degree 4 """ return self._deg @property def identity(self): ''' Return the identity element of the SymmetricPermutationGroup. Examples ======== >>> from sympy.combinatorics import SymmetricPermutationGroup >>> G = SymmetricPermutationGroup(4) >>> G.identity() (3) ''' return _af_new(list(range(self._deg))) class Coset(Basic): """A left coset of a permutation group with respect to an element. Parameters ========== g : Permutation H : PermutationGroup dir : "+" or "-", If not specified by default it will be "+" here ``dir`` specified the type of coset "+" represent the right coset and "-" represent the left coset. G : PermutationGroup, optional The group which contains *H* as its subgroup and *g* as its element. If not specified, it would automatically become a symmetric group ``SymmetricPermutationGroup(g.size)`` and ``SymmetricPermutationGroup(H.degree)`` if ``g.size`` and ``H.degree`` are matching.``SymmetricPermutationGroup`` is a lazy form of SymmetricGroup used for representation purpose. """ def __new__(cls, g, H, G=None, dir="+"): g = _sympify(g) if not isinstance(g, Permutation): raise NotImplementedError H = _sympify(H) if not isinstance(H, PermutationGroup): raise NotImplementedError if G is not None: G = _sympify(G) if not isinstance(G, PermutationGroup) and not isinstance(G, SymmetricPermutationGroup): raise NotImplementedError if not H.is_subgroup(G): raise ValueError("{} must be a subgroup of {}.".format(H, G)) if g not in G: raise ValueError("{} must be an element of {}.".format(g, G)) else: g_size = g.size h_degree = H.degree if g_size != h_degree: raise ValueError( "The size of the permutation {} and the degree of " "the permutation group {} should be matching " .format(g, H)) G = SymmetricPermutationGroup(g.size) if isinstance(dir, str): dir = Symbol(dir) elif not isinstance(dir, Symbol): raise TypeError("dir must be of type basestring or " "Symbol, not %s" % type(dir)) if str(dir) not in ('+', '-'): raise ValueError("dir must be one of '+' or '-' not %s" % dir) obj = Basic.__new__(cls, g, H, G, dir) return obj def __init__(self, *args, **kwargs): self._dir = self.args[3] @property def is_left_coset(self): """ Check if the coset is left coset that is ``gH``. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup, Coset >>> a = Permutation(1, 2) >>> b = Permutation(0, 1) >>> G = PermutationGroup([a, b]) >>> cst = Coset(a, G, dir="-") >>> cst.is_left_coset True """ return str(self._dir) == '-' @property def is_right_coset(self): """ Check if the coset is right coset that is ``Hg``. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup, Coset >>> a = Permutation(1, 2) >>> b = Permutation(0, 1) >>> G = PermutationGroup([a, b]) >>> cst = Coset(a, G, dir="+") >>> cst.is_right_coset True """ return str(self._dir) == '+' def as_list(self): """ Return all the elements of coset in the form of list. """ g = self.args[0] H = self.args[1] cst = [] if str(self._dir) == '+': for h in H.elements: cst.append(h*g) else: for h in H.elements: cst.append(g*h) return cst
c3c8ee4ee1f0b473c8af790896e2824a5605185904ec54a23acbc7a34a2bfd95
from sympy.core import Basic, Integer import random class GrayCode(Basic): """ A Gray code is essentially a Hamiltonian walk on a n-dimensional cube with edge length of one. The vertices of the cube are represented by vectors whose values are binary. The Hamilton walk visits each vertex exactly once. The Gray code for a 3d cube is ['000','100','110','010','011','111','101', '001']. A Gray code solves the problem of sequentially generating all possible subsets of n objects in such a way that each subset is obtained from the previous one by either deleting or adding a single object. In the above example, 1 indicates that the object is present, and 0 indicates that its absent. Gray codes have applications in statistics as well when we want to compute various statistics related to subsets in an efficient manner. Examples ======== >>> from sympy.combinatorics.graycode import GrayCode >>> a = GrayCode(3) >>> list(a.generate_gray()) ['000', '001', '011', '010', '110', '111', '101', '100'] >>> a = GrayCode(4) >>> list(a.generate_gray()) ['0000', '0001', '0011', '0010', '0110', '0111', '0101', '0100', \ '1100', '1101', '1111', '1110', '1010', '1011', '1001', '1000'] References ========== .. [1] Nijenhuis,A. and Wilf,H.S.(1978). Combinatorial Algorithms. Academic Press. .. [2] Knuth, D. (2011). The Art of Computer Programming, Vol 4 Addison Wesley """ _skip = False _current = 0 _rank = None def __new__(cls, n, *args, **kw_args): """ Default constructor. It takes a single argument ``n`` which gives the dimension of the Gray code. The starting Gray code string (``start``) or the starting ``rank`` may also be given; the default is to start at rank = 0 ('0...0'). Examples ======== >>> from sympy.combinatorics.graycode import GrayCode >>> a = GrayCode(3) >>> a GrayCode(3) >>> a.n 3 >>> a = GrayCode(3, start='100') >>> a.current '100' >>> a = GrayCode(4, rank=4) >>> a.current '0110' >>> a.rank 4 """ if n < 1 or int(n) != n: raise ValueError( 'Gray code dimension must be a positive integer, not %i' % n) n = Integer(n) args = (n,) + args obj = Basic.__new__(cls, *args) if 'start' in kw_args: obj._current = kw_args["start"] if len(obj._current) > n: raise ValueError('Gray code start has length %i but ' 'should not be greater than %i' % (len(obj._current), n)) elif 'rank' in kw_args: if int(kw_args["rank"]) != kw_args["rank"]: raise ValueError('Gray code rank must be a positive integer, ' 'not %i' % kw_args["rank"]) obj._rank = int(kw_args["rank"]) % obj.selections obj._current = obj.unrank(n, obj._rank) return obj def next(self, delta=1): """ Returns the Gray code a distance ``delta`` (default = 1) from the current value in canonical order. Examples ======== >>> from sympy.combinatorics.graycode import GrayCode >>> a = GrayCode(3, start='110') >>> a.next().current '111' >>> a.next(-1).current '010' """ return GrayCode(self.n, rank=(self.rank + delta) % self.selections) @property def selections(self): """ Returns the number of bit vectors in the Gray code. Examples ======== >>> from sympy.combinatorics.graycode import GrayCode >>> a = GrayCode(3) >>> a.selections 8 """ return 2**self.n @property def n(self): """ Returns the dimension of the Gray code. Examples ======== >>> from sympy.combinatorics.graycode import GrayCode >>> a = GrayCode(5) >>> a.n 5 """ return self.args[0] def generate_gray(self, **hints): """ Generates the sequence of bit vectors of a Gray Code. Examples ======== >>> from sympy.combinatorics.graycode import GrayCode >>> a = GrayCode(3) >>> list(a.generate_gray()) ['000', '001', '011', '010', '110', '111', '101', '100'] >>> list(a.generate_gray(start='011')) ['011', '010', '110', '111', '101', '100'] >>> list(a.generate_gray(rank=4)) ['110', '111', '101', '100'] See Also ======== skip References ========== .. [1] Knuth, D. (2011). The Art of Computer Programming, Vol 4, Addison Wesley """ bits = self.n start = None if "start" in hints: start = hints["start"] elif "rank" in hints: start = GrayCode.unrank(self.n, hints["rank"]) if start is not None: self._current = start current = self.current graycode_bin = gray_to_bin(current) if len(graycode_bin) > self.n: raise ValueError('Gray code start has length %i but should ' 'not be greater than %i' % (len(graycode_bin), bits)) self._current = int(current, 2) graycode_int = int(''.join(graycode_bin), 2) for i in range(graycode_int, 1 << bits): if self._skip: self._skip = False else: yield self.current bbtc = (i ^ (i + 1)) gbtc = (bbtc ^ (bbtc >> 1)) self._current = (self._current ^ gbtc) self._current = 0 def skip(self): """ Skips the bit generation. Examples ======== >>> from sympy.combinatorics.graycode import GrayCode >>> a = GrayCode(3) >>> for i in a.generate_gray(): ... if i == '010': ... a.skip() ... print(i) ... 000 001 011 010 111 101 100 See Also ======== generate_gray """ self._skip = True @property def rank(self): """ Ranks the Gray code. A ranking algorithm determines the position (or rank) of a combinatorial object among all the objects w.r.t. a given order. For example, the 4 bit binary reflected Gray code (BRGC) '0101' has a rank of 6 as it appears in the 6th position in the canonical ordering of the family of 4 bit Gray codes. Examples ======== >>> from sympy.combinatorics.graycode import GrayCode >>> a = GrayCode(3) >>> list(a.generate_gray()) ['000', '001', '011', '010', '110', '111', '101', '100'] >>> GrayCode(3, start='100').rank 7 >>> GrayCode(3, rank=7).current '100' See Also ======== unrank References ========== .. [1] http://statweb.stanford.edu/~susan/courses/s208/node12.html """ if self._rank is None: self._rank = int(gray_to_bin(self.current), 2) return self._rank @property def current(self): """ Returns the currently referenced Gray code as a bit string. Examples ======== >>> from sympy.combinatorics.graycode import GrayCode >>> GrayCode(3, start='100').current '100' """ rv = self._current or '0' if not isinstance(rv, str): rv = bin(rv)[2:] return rv.rjust(self.n, '0') @classmethod def unrank(self, n, rank): """ Unranks an n-bit sized Gray code of rank k. This method exists so that a derivative GrayCode class can define its own code of a given rank. The string here is generated in reverse order to allow for tail-call optimization. Examples ======== >>> from sympy.combinatorics.graycode import GrayCode >>> GrayCode(5, rank=3).current '00010' >>> GrayCode.unrank(5, 3) '00010' See Also ======== rank """ def _unrank(k, n): if n == 1: return str(k % 2) m = 2**(n - 1) if k < m: return '0' + _unrank(k, n - 1) return '1' + _unrank(m - (k % m) - 1, n - 1) return _unrank(rank, n) def random_bitstring(n): """ Generates a random bitlist of length n. Examples ======== >>> from sympy.combinatorics.graycode import random_bitstring >>> random_bitstring(3) # doctest: +SKIP 100 """ return ''.join([random.choice('01') for i in range(n)]) def gray_to_bin(bin_list): """ Convert from Gray coding to binary coding. We assume big endian encoding. Examples ======== >>> from sympy.combinatorics.graycode import gray_to_bin >>> gray_to_bin('100') '111' See Also ======== bin_to_gray """ b = [bin_list[0]] for i in range(1, len(bin_list)): b += str(int(b[i - 1] != bin_list[i])) return ''.join(b) def bin_to_gray(bin_list): """ Convert from binary coding to gray coding. We assume big endian encoding. Examples ======== >>> from sympy.combinatorics.graycode import bin_to_gray >>> bin_to_gray('111') '100' See Also ======== gray_to_bin """ b = [bin_list[0]] for i in range(1, len(bin_list)): b += str(int(bin_list[i]) ^ int(bin_list[i - 1])) return ''.join(b) def get_subset_from_bitstring(super_set, bitstring): """ Gets the subset defined by the bitstring. Examples ======== >>> from sympy.combinatorics.graycode import get_subset_from_bitstring >>> get_subset_from_bitstring(['a', 'b', 'c', 'd'], '0011') ['c', 'd'] >>> get_subset_from_bitstring(['c', 'a', 'c', 'c'], '1100') ['c', 'a'] See Also ======== graycode_subsets """ if len(super_set) != len(bitstring): raise ValueError("The sizes of the lists are not equal") return [super_set[i] for i, j in enumerate(bitstring) if bitstring[i] == '1'] def graycode_subsets(gray_code_set): """ Generates the subsets as enumerated by a Gray code. Examples ======== >>> from sympy.combinatorics.graycode import graycode_subsets >>> list(graycode_subsets(['a', 'b', 'c'])) [[], ['c'], ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'], \ ['a', 'c'], ['a']] >>> list(graycode_subsets(['a', 'b', 'c', 'c'])) [[], ['c'], ['c', 'c'], ['c'], ['b', 'c'], ['b', 'c', 'c'], \ ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'b', 'c', 'c'], \ ['a', 'b', 'c'], ['a', 'c'], ['a', 'c', 'c'], ['a', 'c'], ['a']] See Also ======== get_subset_from_bitstring """ for bitstring in list(GrayCode(len(gray_code_set)).generate_gray()): yield get_subset_from_bitstring(gray_code_set, bitstring)
33350f8ae91d4f58418d958eaa68852a713e2d5144f9af90d755c30113daab16
from sympy.combinatorics.rewritingsystem_fsm import StateMachine class RewritingSystem: ''' A class implementing rewriting systems for `FpGroup`s. References ========== .. [1] Epstein, D., Holt, D. and Rees, S. (1991). The use of Knuth-Bendix methods to solve the word problem in automatic groups. Journal of Symbolic Computation, 12(4-5), pp.397-414. .. [2] GAP's Manual on its KBMAG package https://www.gap-system.org/Manuals/pkg/kbmag-1.5.3/doc/manual.pdf ''' def __init__(self, group): from collections import deque self.group = group self.alphabet = group.generators self._is_confluent = None # these values are taken from [2] self.maxeqns = 32767 # max rules self.tidyint = 100 # rules before tidying # _max_exceeded is True if maxeqns is exceeded # at any point self._max_exceeded = False # Reduction automaton self.reduction_automaton = None self._new_rules = {} # dictionary of reductions self.rules = {} self.rules_cache = deque([], 50) self._init_rules() # All the transition symbols in the automaton generators = list(self.alphabet) generators += [gen**-1 for gen in generators] # Create a finite state machine as an instance of the StateMachine object self.reduction_automaton = StateMachine('Reduction automaton for '+ repr(self.group), generators) self.construct_automaton() def set_max(self, n): ''' Set the maximum number of rules that can be defined ''' if n > self.maxeqns: self._max_exceeded = False self.maxeqns = n return @property def is_confluent(self): ''' Return `True` if the system is confluent ''' if self._is_confluent is None: self._is_confluent = self._check_confluence() return self._is_confluent def _init_rules(self): identity = self.group.free_group.identity for r in self.group.relators: self.add_rule(r, identity) self._remove_redundancies() return def _add_rule(self, r1, r2): ''' Add the rule r1 -> r2 with no checking or further deductions ''' if len(self.rules) + 1 > self.maxeqns: self._is_confluent = self._check_confluence() self._max_exceeded = True raise RuntimeError("Too many rules were defined.") self.rules[r1] = r2 # Add the newly added rule to the `new_rules` dictionary. if self.reduction_automaton: self._new_rules[r1] = r2 def add_rule(self, w1, w2, check=False): new_keys = set() if w1 == w2: return new_keys if w1 < w2: w1, w2 = w2, w1 if (w1, w2) in self.rules_cache: return new_keys self.rules_cache.append((w1, w2)) s1, s2 = w1, w2 # The following is the equivalent of checking # s1 for overlaps with the implicit reductions # {g*g**-1 -> <identity>} and {g**-1*g -> <identity>} # for any generator g without installing the # redundant rules that would result from processing # the overlaps. See [1], Section 3 for details. if len(s1) - len(s2) < 3: if s1 not in self.rules: new_keys.add(s1) if not check: self._add_rule(s1, s2) if s2**-1 > s1**-1 and s2**-1 not in self.rules: new_keys.add(s2**-1) if not check: self._add_rule(s2**-1, s1**-1) # overlaps on the right while len(s1) - len(s2) > -1: g = s1[len(s1)-1] s1 = s1.subword(0, len(s1)-1) s2 = s2*g**-1 if len(s1) - len(s2) < 0: if s2 not in self.rules: if not check: self._add_rule(s2, s1) new_keys.add(s2) elif len(s1) - len(s2) < 3: new = self.add_rule(s1, s2, check) new_keys.update(new) # overlaps on the left while len(w1) - len(w2) > -1: g = w1[0] w1 = w1.subword(1, len(w1)) w2 = g**-1*w2 if len(w1) - len(w2) < 0: if w2 not in self.rules: if not check: self._add_rule(w2, w1) new_keys.add(w2) elif len(w1) - len(w2) < 3: new = self.add_rule(w1, w2, check) new_keys.update(new) return new_keys def _remove_redundancies(self, changes=False): ''' Reduce left- and right-hand sides of reduction rules and remove redundant equations (i.e. those for which lhs == rhs). If `changes` is `True`, return a set containing the removed keys and a set containing the added keys ''' removed = set() added = set() rules = self.rules.copy() for r in rules: v = self.reduce(r, exclude=r) w = self.reduce(rules[r]) if v != r: del self.rules[r] removed.add(r) if v > w: added.add(v) self.rules[v] = w elif v < w: added.add(w) self.rules[w] = v else: self.rules[v] = w if changes: return removed, added return def make_confluent(self, check=False): ''' Try to make the system confluent using the Knuth-Bendix completion algorithm ''' if self._max_exceeded: return self._is_confluent lhs = list(self.rules.keys()) def _overlaps(r1, r2): len1 = len(r1) len2 = len(r2) result = [] for j in range(1, len1 + len2): if (r1.subword(len1 - j, len1 + len2 - j, strict=False) == r2.subword(j - len1, j, strict=False)): a = r1.subword(0, len1-j, strict=False) a = a*r2.subword(0, j-len1, strict=False) b = r2.subword(j-len1, j, strict=False) c = r2.subword(j, len2, strict=False) c = c*r1.subword(len1 + len2 - j, len1, strict=False) result.append(a*b*c) return result def _process_overlap(w, r1, r2, check): s = w.eliminate_word(r1, self.rules[r1]) s = self.reduce(s) t = w.eliminate_word(r2, self.rules[r2]) t = self.reduce(t) if s != t: if check: # system not confluent return [0] try: new_keys = self.add_rule(t, s, check) return new_keys except RuntimeError: return False return added = 0 i = 0 while i < len(lhs): r1 = lhs[i] i += 1 # j could be i+1 to not # check each pair twice but lhs # is extended in the loop and the new # elements have to be checked with the # preceding ones. there is probably a better way # to handle this j = 0 while j < len(lhs): r2 = lhs[j] j += 1 if r1 == r2: continue overlaps = _overlaps(r1, r2) overlaps.extend(_overlaps(r1**-1, r2)) if not overlaps: continue for w in overlaps: new_keys = _process_overlap(w, r1, r2, check) if new_keys: if check: return False lhs.extend(new_keys) added += len(new_keys) elif new_keys == False: # too many rules were added so the process # couldn't complete return self._is_confluent if added > self.tidyint and not check: # tidy up r, a = self._remove_redundancies(changes=True) added = 0 if r: # reset i since some elements were removed i = min([lhs.index(s) for s in r]) lhs = [l for l in lhs if l not in r] lhs.extend(a) if r1 in r: # r1 was removed as redundant break self._is_confluent = True if not check: self._remove_redundancies() return True def _check_confluence(self): return self.make_confluent(check=True) def reduce(self, word, exclude=None): ''' Apply reduction rules to `word` excluding the reduction rule for the lhs equal to `exclude` ''' rules = {r: self.rules[r] for r in self.rules if r != exclude} # the following is essentially `eliminate_words()` code from the # `FreeGroupElement` class, the only difference being the first # "if" statement again = True new = word while again: again = False for r in rules: prev = new if rules[r]**-1 > r**-1: new = new.eliminate_word(r, rules[r], _all=True, inverse=False) else: new = new.eliminate_word(r, rules[r], _all=True) if new != prev: again = True return new def _compute_inverse_rules(self, rules): ''' Compute the inverse rules for a given set of rules. The inverse rules are used in the automaton for word reduction. Arguments: rules (dictionary): Rules for which the inverse rules are to computed. Returns: Dictionary of inverse_rules. ''' inverse_rules = {} for r in rules: rule_key_inverse = r**-1 rule_value_inverse = (rules[r])**-1 if (rule_value_inverse < rule_key_inverse): inverse_rules[rule_key_inverse] = rule_value_inverse else: inverse_rules[rule_value_inverse] = rule_key_inverse return inverse_rules def construct_automaton(self): ''' Construct the automaton based on the set of reduction rules of the system. Automata Design: The accept states of the automaton are the proper prefixes of the left hand side of the rules. The complete left hand side of the rules are the dead states of the automaton. ''' self._add_to_automaton(self.rules) def _add_to_automaton(self, rules): ''' Add new states and transitions to the automaton. Summary: States corresponding to the new rules added to the system are computed and added to the automaton. Transitions in the previously added states are also modified if necessary. Arguments: rules (dictionary) -- Dictionary of the newly added rules. ''' # Automaton variables automaton_alphabet = [] proper_prefixes = {} # compute the inverses of all the new rules added all_rules = rules inverse_rules = self._compute_inverse_rules(all_rules) all_rules.update(inverse_rules) # Keep track of the accept_states. accept_states = [] for rule in all_rules: # The symbols present in the new rules are the symbols to be verified at each state. # computes the automaton_alphabet, as the transitions solely depend upon the new states. automaton_alphabet += rule.letter_form_elm # Compute the proper prefixes for every rule. proper_prefixes[rule] = [] letter_word_array = [s for s in rule.letter_form_elm] len_letter_word_array = len(letter_word_array) for i in range (1, len_letter_word_array): letter_word_array[i] = letter_word_array[i-1]*letter_word_array[i] # Add accept states. elem = letter_word_array[i-1] if elem not in self.reduction_automaton.states: self.reduction_automaton.add_state(elem, state_type='a') accept_states.append(elem) proper_prefixes[rule] = letter_word_array # Check for overlaps between dead and accept states. if rule in accept_states: self.reduction_automaton.states[rule].state_type = 'd' self.reduction_automaton.states[rule].rh_rule = all_rules[rule] accept_states.remove(rule) # Add dead states if rule not in self.reduction_automaton.states: self.reduction_automaton.add_state(rule, state_type='d', rh_rule=all_rules[rule]) automaton_alphabet = set(automaton_alphabet) # Add new transitions for every state. for state in self.reduction_automaton.states: current_state_name = state current_state_type = self.reduction_automaton.states[state].state_type # Transitions will be modified only when suffixes of the current_state # belongs to the proper_prefixes of the new rules. # The rest are ignored if they cannot lead to a dead state after a finite number of transisitons. if current_state_type == 's': for letter in automaton_alphabet: if letter in self.reduction_automaton.states: self.reduction_automaton.states[state].add_transition(letter, letter) else: self.reduction_automaton.states[state].add_transition(letter, current_state_name) elif current_state_type == 'a': # Check if the transition to any new state in possible. for letter in automaton_alphabet: _next = current_state_name*letter while len(_next) and _next not in self.reduction_automaton.states: _next = _next.subword(1, len(_next)) if not len(_next): _next = 'start' self.reduction_automaton.states[state].add_transition(letter, _next) # Add transitions for new states. All symbols used in the automaton are considered here. # Ignore this if `reduction_automaton.automaton_alphabet` = `automaton_alphabet`. if len(self.reduction_automaton.automaton_alphabet) != len(automaton_alphabet): for state in accept_states: current_state_name = state for letter in self.reduction_automaton.automaton_alphabet: _next = current_state_name*letter while len(_next) and _next not in self.reduction_automaton.states: _next = _next.subword(1, len(_next)) if not len(_next): _next = 'start' self.reduction_automaton.states[state].add_transition(letter, _next) def reduce_using_automaton(self, word): ''' Reduce a word using an automaton. Summary: All the symbols of the word are stored in an array and are given as the input to the automaton. If the automaton reaches a dead state that subword is replaced and the automaton is run from the beginning. The complete word has to be replaced when the word is read and the automaton reaches a dead state. So, this process is repeated until the word is read completely and the automaton reaches the accept state. Arguments: word (instance of FreeGroupElement) -- Word that needs to be reduced. ''' # Modify the automaton if new rules are found. if self._new_rules: self._add_to_automaton(self._new_rules) self._new_rules = {} flag = 1 while flag: flag = 0 current_state = self.reduction_automaton.states['start'] word_array = [s for s in word.letter_form_elm] for i in range (0, len(word_array)): next_state_name = current_state.transitions[word_array[i]] next_state = self.reduction_automaton.states[next_state_name] if next_state.state_type == 'd': subst = next_state.rh_rule word = word.substituted_word(i - len(next_state_name) + 1, i+1, subst) flag = 1 break current_state = next_state return word
bab6c06c711f35bbfa4e6a09513553745da9a7ed53f4041a286d454cde128f7d
import random from collections import defaultdict from collections.abc import Iterable from functools import reduce from sympy.core.parameters import global_parameters from sympy.core.basic import Atom from sympy.core.expr import Expr from sympy.core.numbers import Integer from sympy.core.sympify import _sympify from sympy.matrices import zeros from sympy.polys.polytools import lcm from sympy.utilities.iterables import (flatten, has_variety, minlex, has_dups, runs, is_sequence) from sympy.utilities.misc import as_int from mpmath.libmp.libintmath import ifac from sympy.multipledispatch import dispatch def _af_rmul(a, b): """ Return the product b*a; input and output are array forms. The ith value is a[b[i]]. Examples ======== >>> from sympy.combinatorics.permutations import _af_rmul, Permutation >>> a, b = [1, 0, 2], [0, 2, 1] >>> _af_rmul(a, b) [1, 2, 0] >>> [a[b[i]] for i in range(3)] [1, 2, 0] This handles the operands in reverse order compared to the ``*`` operator: >>> a = Permutation(a) >>> b = Permutation(b) >>> list(a*b) [2, 0, 1] >>> [b(a(i)) for i in range(3)] [2, 0, 1] See Also ======== rmul, _af_rmuln """ return [a[i] for i in b] def _af_rmuln(*abc): """ Given [a, b, c, ...] return the product of ...*c*b*a using array forms. The ith value is a[b[c[i]]]. Examples ======== >>> from sympy.combinatorics.permutations import _af_rmul, Permutation >>> a, b = [1, 0, 2], [0, 2, 1] >>> _af_rmul(a, b) [1, 2, 0] >>> [a[b[i]] for i in range(3)] [1, 2, 0] This handles the operands in reverse order compared to the ``*`` operator: >>> a = Permutation(a); b = Permutation(b) >>> list(a*b) [2, 0, 1] >>> [b(a(i)) for i in range(3)] [2, 0, 1] See Also ======== rmul, _af_rmul """ a = abc m = len(a) if m == 3: p0, p1, p2 = a return [p0[p1[i]] for i in p2] if m == 4: p0, p1, p2, p3 = a return [p0[p1[p2[i]]] for i in p3] if m == 5: p0, p1, p2, p3, p4 = a return [p0[p1[p2[p3[i]]]] for i in p4] if m == 6: p0, p1, p2, p3, p4, p5 = a return [p0[p1[p2[p3[p4[i]]]]] for i in p5] if m == 7: p0, p1, p2, p3, p4, p5, p6 = a return [p0[p1[p2[p3[p4[p5[i]]]]]] for i in p6] if m == 8: p0, p1, p2, p3, p4, p5, p6, p7 = a return [p0[p1[p2[p3[p4[p5[p6[i]]]]]]] for i in p7] if m == 1: return a[0][:] if m == 2: a, b = a return [a[i] for i in b] if m == 0: raise ValueError("String must not be empty") p0 = _af_rmuln(*a[:m//2]) p1 = _af_rmuln(*a[m//2:]) return [p0[i] for i in p1] def _af_parity(pi): """ Computes the parity of a permutation in array form. Explanation =========== The parity of a permutation reflects the parity of the number of inversions in the permutation, i.e., the number of pairs of x and y such that x > y but p[x] < p[y]. Examples ======== >>> from sympy.combinatorics.permutations import _af_parity >>> _af_parity([0, 1, 2, 3]) 0 >>> _af_parity([3, 2, 0, 1]) 1 See Also ======== Permutation """ n = len(pi) a = [0] * n c = 0 for j in range(n): if a[j] == 0: c += 1 a[j] = 1 i = j while pi[i] != j: i = pi[i] a[i] = 1 return (n - c) % 2 def _af_invert(a): """ Finds the inverse, ~A, of a permutation, A, given in array form. Examples ======== >>> from sympy.combinatorics.permutations import _af_invert, _af_rmul >>> A = [1, 2, 0, 3] >>> _af_invert(A) [2, 0, 1, 3] >>> _af_rmul(_, A) [0, 1, 2, 3] See Also ======== Permutation, __invert__ """ inv_form = [0] * len(a) for i, ai in enumerate(a): inv_form[ai] = i return inv_form def _af_pow(a, n): """ Routine for finding powers of a permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation, _af_pow >>> p = Permutation([2, 0, 3, 1]) >>> p.order() 4 >>> _af_pow(p._array_form, 4) [0, 1, 2, 3] """ if n == 0: return list(range(len(a))) if n < 0: return _af_pow(_af_invert(a), -n) if n == 1: return a[:] elif n == 2: b = [a[i] for i in a] elif n == 3: b = [a[a[i]] for i in a] elif n == 4: b = [a[a[a[i]]] for i in a] else: # use binary multiplication b = list(range(len(a))) while 1: if n & 1: b = [b[i] for i in a] n -= 1 if not n: break if n % 4 == 0: a = [a[a[a[i]]] for i in a] n = n // 4 elif n % 2 == 0: a = [a[i] for i in a] n = n // 2 return b def _af_commutes_with(a, b): """ Checks if the two permutations with array forms given by ``a`` and ``b`` commute. Examples ======== >>> from sympy.combinatorics.permutations import _af_commutes_with >>> _af_commutes_with([1, 2, 0], [0, 2, 1]) False See Also ======== Permutation, commutes_with """ return not any(a[b[i]] != b[a[i]] for i in range(len(a) - 1)) class Cycle(dict): """ Wrapper around dict which provides the functionality of a disjoint cycle. Explanation =========== A cycle shows the rule to use to move subsets of elements to obtain a permutation. The Cycle class is more flexible than Permutation in that 1) all elements need not be present in order to investigate how multiple cycles act in sequence and 2) it can contain singletons: >>> from sympy.combinatorics.permutations import Perm, Cycle A Cycle will automatically parse a cycle given as a tuple on the rhs: >>> Cycle(1, 2)(2, 3) (1 3 2) The identity cycle, Cycle(), can be used to start a product: >>> Cycle()(1, 2)(2, 3) (1 3 2) The array form of a Cycle can be obtained by calling the list method (or passing it to the list function) and all elements from 0 will be shown: >>> a = Cycle(1, 2) >>> a.list() [0, 2, 1] >>> list(a) [0, 2, 1] If a larger (or smaller) range is desired use the list method and provide the desired size -- but the Cycle cannot be truncated to a size smaller than the largest element that is out of place: >>> b = Cycle(2, 4)(1, 2)(3, 1, 4)(1, 3) >>> b.list() [0, 2, 1, 3, 4] >>> b.list(b.size + 1) [0, 2, 1, 3, 4, 5] >>> b.list(-1) [0, 2, 1] Singletons are not shown when printing with one exception: the largest element is always shown -- as a singleton if necessary: >>> Cycle(1, 4, 10)(4, 5) (1 5 4 10) >>> Cycle(1, 2)(4)(5)(10) (1 2)(10) The array form can be used to instantiate a Permutation so other properties of the permutation can be investigated: >>> Perm(Cycle(1, 2)(3, 4).list()).transpositions() [(1, 2), (3, 4)] Notes ===== The underlying structure of the Cycle is a dictionary and although the __iter__ method has been redefined to give the array form of the cycle, the underlying dictionary items are still available with the such methods as items(): >>> list(Cycle(1, 2).items()) [(1, 2), (2, 1)] See Also ======== Permutation """ def __missing__(self, arg): """Enter arg into dictionary and return arg.""" return as_int(arg) def __iter__(self): yield from self.list() def __call__(self, *other): """Return product of cycles processed from R to L. Examples ======== >>> from sympy.combinatorics.permutations import Cycle as C >>> C(1, 2)(2, 3) (1 3 2) An instance of a Cycle will automatically parse list-like objects and Permutations that are on the right. It is more flexible than the Permutation in that all elements need not be present: >>> a = C(1, 2) >>> a(2, 3) (1 3 2) >>> a(2, 3)(4, 5) (1 3 2)(4 5) """ rv = Cycle(*other) for k, v in zip(list(self.keys()), [rv[self[k]] for k in self.keys()]): rv[k] = v return rv def list(self, size=None): """Return the cycles as an explicit list starting from 0 up to the greater of the largest value in the cycles and size. Truncation of trailing unmoved items will occur when size is less than the maximum element in the cycle; if this is desired, setting ``size=-1`` will guarantee such trimming. Examples ======== >>> from sympy.combinatorics.permutations import Cycle >>> p = Cycle(2, 3)(4, 5) >>> p.list() [0, 1, 3, 2, 5, 4] >>> p.list(10) [0, 1, 3, 2, 5, 4, 6, 7, 8, 9] Passing a length too small will trim trailing, unchanged elements in the permutation: >>> Cycle(2, 4)(1, 2, 4).list(-1) [0, 2, 1] """ if not self and size is None: raise ValueError('must give size for empty Cycle') if size is not None: big = max([i for i in self.keys() if self[i] != i] + [0]) size = max(size, big + 1) else: size = self.size return [self[i] for i in range(size)] def __repr__(self): """We want it to print as a Cycle, not as a dict. Examples ======== >>> from sympy.combinatorics import Cycle >>> Cycle(1, 2) (1 2) >>> print(_) (1 2) >>> list(Cycle(1, 2).items()) [(1, 2), (2, 1)] """ if not self: return 'Cycle()' cycles = Permutation(self).cyclic_form s = ''.join(str(tuple(c)) for c in cycles) big = self.size - 1 if not any(i == big for c in cycles for i in c): s += '(%s)' % big return 'Cycle%s' % s def __str__(self): """We want it to be printed in a Cycle notation with no comma in-between. Examples ======== >>> from sympy.combinatorics import Cycle >>> Cycle(1, 2) (1 2) >>> Cycle(1, 2, 4)(5, 6) (1 2 4)(5 6) """ if not self: return '()' cycles = Permutation(self).cyclic_form s = ''.join(str(tuple(c)) for c in cycles) big = self.size - 1 if not any(i == big for c in cycles for i in c): s += '(%s)' % big s = s.replace(',', '') return s def __init__(self, *args): """Load up a Cycle instance with the values for the cycle. Examples ======== >>> from sympy.combinatorics.permutations import Cycle >>> Cycle(1, 2, 6) (1 2 6) """ if not args: return if len(args) == 1: if isinstance(args[0], Permutation): for c in args[0].cyclic_form: self.update(self(*c)) return elif isinstance(args[0], Cycle): for k, v in args[0].items(): self[k] = v return args = [as_int(a) for a in args] if any(i < 0 for i in args): raise ValueError('negative integers are not allowed in a cycle.') if has_dups(args): raise ValueError('All elements must be unique in a cycle.') for i in range(-len(args), 0): self[args[i]] = args[i + 1] @property def size(self): if not self: return 0 return max(self.keys()) + 1 def copy(self): return Cycle(self) class Permutation(Atom): """ A permutation, alternatively known as an 'arrangement number' or 'ordering' is an arrangement of the elements of an ordered list into a one-to-one mapping with itself. The permutation of a given arrangement is given by indicating the positions of the elements after re-arrangement [2]_. For example, if one started with elements [x, y, a, b] (in that order) and they were reordered as [x, y, b, a] then the permutation would be [0, 1, 3, 2]. Notice that (in SymPy) the first element is always referred to as 0 and the permutation uses the indices of the elements in the original ordering, not the elements (a, b, etc...) themselves. >>> from sympy.combinatorics import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) Permutations Notation ===================== Permutations are commonly represented in disjoint cycle or array forms. Array Notation and 2-line Form ------------------------------------ In the 2-line form, the elements and their final positions are shown as a matrix with 2 rows: [0 1 2 ... n-1] [p(0) p(1) p(2) ... p(n-1)] Since the first line is always range(n), where n is the size of p, it is sufficient to represent the permutation by the second line, referred to as the "array form" of the permutation. This is entered in brackets as the argument to the Permutation class: >>> p = Permutation([0, 2, 1]); p Permutation([0, 2, 1]) Given i in range(p.size), the permutation maps i to i^p >>> [i^p for i in range(p.size)] [0, 2, 1] The composite of two permutations p*q means first apply p, then q, so i^(p*q) = (i^p)^q which is i^p^q according to Python precedence rules: >>> q = Permutation([2, 1, 0]) >>> [i^p^q for i in range(3)] [2, 0, 1] >>> [i^(p*q) for i in range(3)] [2, 0, 1] One can use also the notation p(i) = i^p, but then the composition rule is (p*q)(i) = q(p(i)), not p(q(i)): >>> [(p*q)(i) for i in range(p.size)] [2, 0, 1] >>> [q(p(i)) for i in range(p.size)] [2, 0, 1] >>> [p(q(i)) for i in range(p.size)] [1, 2, 0] Disjoint Cycle Notation ----------------------- In disjoint cycle notation, only the elements that have shifted are indicated. For example, [1, 3, 2, 0] can be represented as (0, 1, 3)(2). This can be understood from the 2 line format of the given permutation. In the 2-line form, [0 1 2 3] [1 3 2 0] The element in the 0th position is 1, so 0 -> 1. The element in the 1st position is three, so 1 -> 3. And the element in the third position is again 0, so 3 -> 0. Thus, 0 -> 1 -> 3 -> 0, and 2 -> 2. Thus, this can be represented as 2 cycles: (0, 1, 3)(2). In common notation, singular cycles are not explicitly written as they can be inferred implicitly. Only the relative ordering of elements in a cycle matter: >>> Permutation(1,2,3) == Permutation(2,3,1) == Permutation(3,1,2) True The disjoint cycle notation is convenient when representing permutations that have several cycles in them: >>> Permutation(1, 2)(3, 5) == Permutation([[1, 2], [3, 5]]) True It also provides some economy in entry when computing products of permutations that are written in disjoint cycle notation: >>> Permutation(1, 2)(1, 3)(2, 3) Permutation([0, 3, 2, 1]) >>> _ == Permutation([[1, 2]])*Permutation([[1, 3]])*Permutation([[2, 3]]) True Caution: when the cycles have common elements between them then the order in which the permutations are applied matters. This module applies the permutations from *left to right*. >>> Permutation(1, 2)(2, 3) == Permutation([(1, 2), (2, 3)]) True >>> Permutation(1, 2)(2, 3).list() [0, 3, 1, 2] In the above case, (1,2) is computed before (2,3). As 0 -> 0, 0 -> 0, element in position 0 is 0. As 1 -> 2, 2 -> 3, element in position 1 is 3. As 2 -> 1, 1 -> 1, element in position 2 is 1. As 3 -> 3, 3 -> 2, element in position 3 is 2. If the first and second elements had been swapped first, followed by the swapping of the second and third, the result would have been [0, 2, 3, 1]. If, you want to apply the cycles in the conventional right to left order, call the function with arguments in reverse order as demonstrated below: >>> Permutation([(1, 2), (2, 3)][::-1]).list() [0, 2, 3, 1] Entering a singleton in a permutation is a way to indicate the size of the permutation. The ``size`` keyword can also be used. Array-form entry: >>> Permutation([[1, 2], [9]]) Permutation([0, 2, 1], size=10) >>> Permutation([[1, 2]], size=10) Permutation([0, 2, 1], size=10) Cyclic-form entry: >>> Permutation(1, 2, size=10) Permutation([0, 2, 1], size=10) >>> Permutation(9)(1, 2) Permutation([0, 2, 1], size=10) Caution: no singleton containing an element larger than the largest in any previous cycle can be entered. This is an important difference in how Permutation and Cycle handle the __call__ syntax. A singleton argument at the start of a Permutation performs instantiation of the Permutation and is permitted: >>> Permutation(5) Permutation([], size=6) A singleton entered after instantiation is a call to the permutation -- a function call -- and if the argument is out of range it will trigger an error. For this reason, it is better to start the cycle with the singleton: The following fails because there is no element 3: >>> Permutation(1, 2)(3) Traceback (most recent call last): ... IndexError: list index out of range This is ok: only the call to an out of range singleton is prohibited; otherwise the permutation autosizes: >>> Permutation(3)(1, 2) Permutation([0, 2, 1, 3]) >>> Permutation(1, 2)(3, 4) == Permutation(3, 4)(1, 2) True Equality testing ---------------- The array forms must be the same in order for permutations to be equal: >>> Permutation([1, 0, 2, 3]) == Permutation([1, 0]) False Identity Permutation -------------------- The identity permutation is a permutation in which no element is out of place. It can be entered in a variety of ways. All the following create an identity permutation of size 4: >>> I = Permutation([0, 1, 2, 3]) >>> all(p == I for p in [ ... Permutation(3), ... Permutation(range(4)), ... Permutation([], size=4), ... Permutation(size=4)]) True Watch out for entering the range *inside* a set of brackets (which is cycle notation): >>> I == Permutation([range(4)]) False Permutation Printing ==================== There are a few things to note about how Permutations are printed. 1) If you prefer one form (array or cycle) over another, you can set ``init_printing`` with the ``perm_cyclic`` flag. >>> from sympy import init_printing >>> p = Permutation(1, 2)(4, 5)(3, 4) >>> p Permutation([0, 2, 1, 4, 5, 3]) >>> init_printing(perm_cyclic=True, pretty_print=False) >>> p (1 2)(3 4 5) 2) Regardless of the setting, a list of elements in the array for cyclic form can be obtained and either of those can be copied and supplied as the argument to Permutation: >>> p.array_form [0, 2, 1, 4, 5, 3] >>> p.cyclic_form [[1, 2], [3, 4, 5]] >>> Permutation(_) == p True 3) Printing is economical in that as little as possible is printed while retaining all information about the size of the permutation: >>> init_printing(perm_cyclic=False, pretty_print=False) >>> Permutation([1, 0, 2, 3]) Permutation([1, 0, 2, 3]) >>> Permutation([1, 0, 2, 3], size=20) Permutation([1, 0], size=20) >>> Permutation([1, 0, 2, 4, 3, 5, 6], size=20) Permutation([1, 0, 2, 4, 3], size=20) >>> p = Permutation([1, 0, 2, 3]) >>> init_printing(perm_cyclic=True, pretty_print=False) >>> p (3)(0 1) >>> init_printing(perm_cyclic=False, pretty_print=False) The 2 was not printed but it is still there as can be seen with the array_form and size methods: >>> p.array_form [1, 0, 2, 3] >>> p.size 4 Short introduction to other methods =================================== The permutation can act as a bijective function, telling what element is located at a given position >>> q = Permutation([5, 2, 3, 4, 1, 0]) >>> q.array_form[1] # the hard way 2 >>> q(1) # the easy way 2 >>> {i: q(i) for i in range(q.size)} # showing the bijection {0: 5, 1: 2, 2: 3, 3: 4, 4: 1, 5: 0} The full cyclic form (including singletons) can be obtained: >>> p.full_cyclic_form [[0, 1], [2], [3]] Any permutation can be factored into transpositions of pairs of elements: >>> Permutation([[1, 2], [3, 4, 5]]).transpositions() [(1, 2), (3, 5), (3, 4)] >>> Permutation.rmul(*[Permutation([ti], size=6) for ti in _]).cyclic_form [[1, 2], [3, 4, 5]] The number of permutations on a set of n elements is given by n! and is called the cardinality. >>> p.size 4 >>> p.cardinality 24 A given permutation has a rank among all the possible permutations of the same elements, but what that rank is depends on how the permutations are enumerated. (There are a number of different methods of doing so.) The lexicographic rank is given by the rank method and this rank is used to increment a permutation with addition/subtraction: >>> p.rank() 6 >>> p + 1 Permutation([1, 0, 3, 2]) >>> p.next_lex() Permutation([1, 0, 3, 2]) >>> _.rank() 7 >>> p.unrank_lex(p.size, rank=7) Permutation([1, 0, 3, 2]) The product of two permutations p and q is defined as their composition as functions, (p*q)(i) = q(p(i)) [6]_. >>> p = Permutation([1, 0, 2, 3]) >>> q = Permutation([2, 3, 1, 0]) >>> list(q*p) [2, 3, 0, 1] >>> list(p*q) [3, 2, 1, 0] >>> [q(p(i)) for i in range(p.size)] [3, 2, 1, 0] The permutation can be 'applied' to any list-like object, not only Permutations: >>> p(['zero', 'one', 'four', 'two']) ['one', 'zero', 'four', 'two'] >>> p('zo42') ['o', 'z', '4', '2'] If you have a list of arbitrary elements, the corresponding permutation can be found with the from_sequence method: >>> Permutation.from_sequence('SymPy') Permutation([1, 3, 2, 0, 4]) Checking if a Permutation is contained in a Group ================================================= Generally if you have a group of permutations G on n symbols, and you're checking if a permutation on less than n symbols is part of that group, the check will fail. Here is an example for n=5 and we check if the cycle (1,2,3) is in G: >>> from sympy import init_printing >>> init_printing(perm_cyclic=True, pretty_print=False) >>> from sympy.combinatorics import Cycle, Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> G = PermutationGroup(Cycle(2, 3)(4, 5), Cycle(1, 2, 3, 4, 5)) >>> p1 = Permutation(Cycle(2, 5, 3)) >>> p2 = Permutation(Cycle(1, 2, 3)) >>> a1 = Permutation(Cycle(1, 2, 3).list(6)) >>> a2 = Permutation(Cycle(1, 2, 3)(5)) >>> a3 = Permutation(Cycle(1, 2, 3),size=6) >>> for p in [p1,p2,a1,a2,a3]: p, G.contains(p) ((2 5 3), True) ((1 2 3), False) ((5)(1 2 3), True) ((5)(1 2 3), True) ((5)(1 2 3), True) The check for p2 above will fail. Checking if p1 is in G works because SymPy knows G is a group on 5 symbols, and p1 is also on 5 symbols (its largest element is 5). For ``a1``, the ``.list(6)`` call will extend the permutation to 5 symbols, so the test will work as well. In the case of ``a2`` the permutation is being extended to 5 symbols by using a singleton, and in the case of ``a3`` it's extended through the constructor argument ``size=6``. There is another way to do this, which is to tell the ``contains`` method that the number of symbols the group is on doesn't need to match perfectly the number of symbols for the permutation: >>> G.contains(p2,strict=False) True This can be via the ``strict`` argument to the ``contains`` method, and SymPy will try to extend the permutation on its own and then perform the containment check. See Also ======== Cycle References ========== .. [1] Skiena, S. 'Permutations.' 1.1 in Implementing Discrete Mathematics Combinatorics and Graph Theory with Mathematica. Reading, MA: Addison-Wesley, pp. 3-16, 1990. .. [2] Knuth, D. E. The Art of Computer Programming, Vol. 4: Combinatorial Algorithms, 1st ed. Reading, MA: Addison-Wesley, 2011. .. [3] Wendy Myrvold and Frank Ruskey. 2001. Ranking and unranking permutations in linear time. Inf. Process. Lett. 79, 6 (September 2001), 281-284. DOI=10.1016/S0020-0190(01)00141-7 .. [4] D. L. Kreher, D. R. Stinson 'Combinatorial Algorithms' CRC Press, 1999 .. [5] Graham, R. L.; Knuth, D. E.; and Patashnik, O. Concrete Mathematics: A Foundation for Computer Science, 2nd ed. Reading, MA: Addison-Wesley, 1994. .. [6] https://en.wikipedia.org/wiki/Permutation#Product_and_inverse .. [7] https://en.wikipedia.org/wiki/Lehmer_code """ is_Permutation = True _array_form = None _cyclic_form = None _cycle_structure = None _size = None _rank = None def __new__(cls, *args, size=None, **kwargs): """ Constructor for the Permutation object from a list or a list of lists in which all elements of the permutation may appear only once. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) Permutations entered in array-form are left unaltered: >>> Permutation([0, 2, 1]) Permutation([0, 2, 1]) Permutations entered in cyclic form are converted to array form; singletons need not be entered, but can be entered to indicate the largest element: >>> Permutation([[4, 5, 6], [0, 1]]) Permutation([1, 0, 2, 3, 5, 6, 4]) >>> Permutation([[4, 5, 6], [0, 1], [19]]) Permutation([1, 0, 2, 3, 5, 6, 4], size=20) All manipulation of permutations assumes that the smallest element is 0 (in keeping with 0-based indexing in Python) so if the 0 is missing when entering a permutation in array form, an error will be raised: >>> Permutation([2, 1]) Traceback (most recent call last): ... ValueError: Integers 0 through 2 must be present. If a permutation is entered in cyclic form, it can be entered without singletons and the ``size`` specified so those values can be filled in, otherwise the array form will only extend to the maximum value in the cycles: >>> Permutation([[1, 4], [3, 5, 2]], size=10) Permutation([0, 4, 3, 5, 1, 2], size=10) >>> _.array_form [0, 4, 3, 5, 1, 2, 6, 7, 8, 9] """ if size is not None: size = int(size) #a) () #b) (1) = identity #c) (1, 2) = cycle #d) ([1, 2, 3]) = array form #e) ([[1, 2]]) = cyclic form #f) (Cycle) = conversion to permutation #g) (Permutation) = adjust size or return copy ok = True if not args: # a return cls._af_new(list(range(size or 0))) elif len(args) > 1: # c return cls._af_new(Cycle(*args).list(size)) if len(args) == 1: a = args[0] if isinstance(a, cls): # g if size is None or size == a.size: return a return cls(a.array_form, size=size) if isinstance(a, Cycle): # f return cls._af_new(a.list(size)) if not is_sequence(a): # b if size is not None and a + 1 > size: raise ValueError('size is too small when max is %s' % a) return cls._af_new(list(range(a + 1))) if has_variety(is_sequence(ai) for ai in a): ok = False else: ok = False if not ok: raise ValueError("Permutation argument must be a list of ints, " "a list of lists, Permutation or Cycle.") # safe to assume args are valid; this also makes a copy # of the args args = list(args[0]) is_cycle = args and is_sequence(args[0]) if is_cycle: # e args = [[int(i) for i in c] for c in args] else: # d args = [int(i) for i in args] # if there are n elements present, 0, 1, ..., n-1 should be present # unless a cycle notation has been provided. A 0 will be added # for convenience in case one wants to enter permutations where # counting starts from 1. temp = flatten(args) if has_dups(temp) and not is_cycle: raise ValueError('there were repeated elements.') temp = set(temp) if not is_cycle: if temp != set(range(len(temp))): raise ValueError('Integers 0 through %s must be present.' % max(temp)) if size is not None and temp and max(temp) + 1 > size: raise ValueError('max element should not exceed %s' % (size - 1)) if is_cycle: # it's not necessarily canonical so we won't store # it -- use the array form instead c = Cycle() for ci in args: c = c(*ci) aform = c.list() else: aform = list(args) if size and size > len(aform): # don't allow for truncation of permutation which # might split a cycle and lead to an invalid aform # but do allow the permutation size to be increased aform.extend(list(range(len(aform), size))) return cls._af_new(aform) @classmethod def _af_new(cls, perm): """A method to produce a Permutation object from a list; the list is bound to the _array_form attribute, so it must not be modified; this method is meant for internal use only; the list ``a`` is supposed to be generated as a temporary value in a method, so p = Perm._af_new(a) is the only object to hold a reference to ``a``:: Examples ======== >>> from sympy.combinatorics.permutations import Perm >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> a = [2, 1, 3, 0] >>> p = Perm._af_new(a) >>> p Permutation([2, 1, 3, 0]) """ p = super().__new__(cls) p._array_form = perm p._size = len(perm) return p def _hashable_content(self): # the array_form (a list) is the Permutation arg, so we need to # return a tuple, instead return tuple(self.array_form) @property def array_form(self): """ Return a copy of the attribute _array_form Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([[2, 0], [3, 1]]) >>> p.array_form [2, 3, 0, 1] >>> Permutation([[2, 0, 3, 1]]).array_form [3, 2, 0, 1] >>> Permutation([2, 0, 3, 1]).array_form [2, 0, 3, 1] >>> Permutation([[1, 2], [4, 5]]).array_form [0, 2, 1, 3, 5, 4] """ return self._array_form[:] def list(self, size=None): """Return the permutation as an explicit list, possibly trimming unmoved elements if size is less than the maximum element in the permutation; if this is desired, setting ``size=-1`` will guarantee such trimming. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation(2, 3)(4, 5) >>> p.list() [0, 1, 3, 2, 5, 4] >>> p.list(10) [0, 1, 3, 2, 5, 4, 6, 7, 8, 9] Passing a length too small will trim trailing, unchanged elements in the permutation: >>> Permutation(2, 4)(1, 2, 4).list(-1) [0, 2, 1] >>> Permutation(3).list(-1) [] """ if not self and size is None: raise ValueError('must give size for empty Cycle') rv = self.array_form if size is not None: if size > self.size: rv.extend(list(range(self.size, size))) else: # find first value from rhs where rv[i] != i i = self.size - 1 while rv: if rv[-1] != i: break rv.pop() i -= 1 return rv @property def cyclic_form(self): """ This is used to convert to the cyclic notation from the canonical notation. Singletons are omitted. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 3, 1, 2]) >>> p.cyclic_form [[1, 3, 2]] >>> Permutation([1, 0, 2, 4, 3, 5]).cyclic_form [[0, 1], [3, 4]] See Also ======== array_form, full_cyclic_form """ if self._cyclic_form is not None: return list(self._cyclic_form) array_form = self.array_form unchecked = [True] * len(array_form) cyclic_form = [] for i in range(len(array_form)): if unchecked[i]: cycle = [] cycle.append(i) unchecked[i] = False j = i while unchecked[array_form[j]]: j = array_form[j] cycle.append(j) unchecked[j] = False if len(cycle) > 1: cyclic_form.append(cycle) assert cycle == list(minlex(cycle)) cyclic_form.sort() self._cyclic_form = cyclic_form[:] return cyclic_form @property def full_cyclic_form(self): """Return permutation in cyclic form including singletons. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> Permutation([0, 2, 1]).full_cyclic_form [[0], [1, 2]] """ need = set(range(self.size)) - set(flatten(self.cyclic_form)) rv = self.cyclic_form + [[i] for i in need] rv.sort() return rv @property def size(self): """ Returns the number of elements in the permutation. Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation([[3, 2], [0, 1]]).size 4 See Also ======== cardinality, length, order, rank """ return self._size def support(self): """Return the elements in permutation, P, for which P[i] != i. Examples ======== >>> from sympy.combinatorics import Permutation >>> p = Permutation([[3, 2], [0, 1], [4]]) >>> p.array_form [1, 0, 3, 2, 4] >>> p.support() [0, 1, 2, 3] """ a = self.array_form return [i for i, e in enumerate(a) if a[i] != i] def __add__(self, other): """Return permutation that is other higher in rank than self. The rank is the lexicographical rank, with the identity permutation having rank of 0. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> I = Permutation([0, 1, 2, 3]) >>> a = Permutation([2, 1, 3, 0]) >>> I + a.rank() == a True See Also ======== __sub__, inversion_vector """ rank = (self.rank() + other) % self.cardinality rv = self.unrank_lex(self.size, rank) rv._rank = rank return rv def __sub__(self, other): """Return the permutation that is other lower in rank than self. See Also ======== __add__ """ return self.__add__(-other) @staticmethod def rmul(*args): """ Return product of Permutations [a, b, c, ...] as the Permutation whose ith value is a(b(c(i))). a, b, c, ... can be Permutation objects or tuples. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> a, b = [1, 0, 2], [0, 2, 1] >>> a = Permutation(a); b = Permutation(b) >>> list(Permutation.rmul(a, b)) [1, 2, 0] >>> [a(b(i)) for i in range(3)] [1, 2, 0] This handles the operands in reverse order compared to the ``*`` operator: >>> a = Permutation(a); b = Permutation(b) >>> list(a*b) [2, 0, 1] >>> [b(a(i)) for i in range(3)] [2, 0, 1] Notes ===== All items in the sequence will be parsed by Permutation as necessary as long as the first item is a Permutation: >>> Permutation.rmul(a, [0, 2, 1]) == Permutation.rmul(a, b) True The reverse order of arguments will raise a TypeError. """ rv = args[0] for i in range(1, len(args)): rv = args[i]*rv return rv @classmethod def rmul_with_af(cls, *args): """ same as rmul, but the elements of args are Permutation objects which have _array_form """ a = [x._array_form for x in args] rv = cls._af_new(_af_rmuln(*a)) return rv def mul_inv(self, other): """ other*~self, self and other have _array_form """ a = _af_invert(self._array_form) b = other._array_form return self._af_new(_af_rmul(a, b)) def __rmul__(self, other): """This is needed to coerce other to Permutation in rmul.""" cls = type(self) return cls(other)*self def __mul__(self, other): """ Return the product a*b as a Permutation; the ith value is b(a(i)). Examples ======== >>> from sympy.combinatorics.permutations import _af_rmul, Permutation >>> a, b = [1, 0, 2], [0, 2, 1] >>> a = Permutation(a); b = Permutation(b) >>> list(a*b) [2, 0, 1] >>> [b(a(i)) for i in range(3)] [2, 0, 1] This handles operands in reverse order compared to _af_rmul and rmul: >>> al = list(a); bl = list(b) >>> _af_rmul(al, bl) [1, 2, 0] >>> [al[bl[i]] for i in range(3)] [1, 2, 0] It is acceptable for the arrays to have different lengths; the shorter one will be padded to match the longer one: >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> b*Permutation([1, 0]) Permutation([1, 2, 0]) >>> Permutation([1, 0])*b Permutation([2, 0, 1]) It is also acceptable to allow coercion to handle conversion of a single list to the left of a Permutation: >>> [0, 1]*a # no change: 2-element identity Permutation([1, 0, 2]) >>> [[0, 1]]*a # exchange first two elements Permutation([0, 1, 2]) You cannot use more than 1 cycle notation in a product of cycles since coercion can only handle one argument to the left. To handle multiple cycles it is convenient to use Cycle instead of Permutation: >>> [[1, 2]]*[[2, 3]]*Permutation([]) # doctest: +SKIP >>> from sympy.combinatorics.permutations import Cycle >>> Cycle(1, 2)(2, 3) (1 3 2) """ from sympy.combinatorics.perm_groups import PermutationGroup, Coset if isinstance(other, PermutationGroup): return Coset(self, other, dir='-') a = self.array_form # __rmul__ makes sure the other is a Permutation b = other.array_form if not b: perm = a else: b.extend(list(range(len(b), len(a)))) perm = [b[i] for i in a] + b[len(a):] return self._af_new(perm) def commutes_with(self, other): """ Checks if the elements are commuting. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> a = Permutation([1, 4, 3, 0, 2, 5]) >>> b = Permutation([0, 1, 2, 3, 4, 5]) >>> a.commutes_with(b) True >>> b = Permutation([2, 3, 5, 4, 1, 0]) >>> a.commutes_with(b) False """ a = self.array_form b = other.array_form return _af_commutes_with(a, b) def __pow__(self, n): """ Routine for finding powers of a permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([2, 0, 3, 1]) >>> p.order() 4 >>> p**4 Permutation([0, 1, 2, 3]) """ if isinstance(n, Permutation): raise NotImplementedError( 'p**p is not defined; do you mean p^p (conjugate)?') n = int(n) return self._af_new(_af_pow(self.array_form, n)) def __rxor__(self, i): """Return self(i) when ``i`` is an int. Examples ======== >>> from sympy.combinatorics import Permutation >>> p = Permutation(1, 2, 9) >>> 2^p == p(2) == 9 True """ if int(i) == i: return self(i) else: raise NotImplementedError( "i^p = p(i) when i is an integer, not %s." % i) def __xor__(self, h): """Return the conjugate permutation ``~h*self*h` `. Explanation =========== If ``a`` and ``b`` are conjugates, ``a = h*b*~h`` and ``b = ~h*a*h`` and both have the same cycle structure. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation(1, 2, 9) >>> q = Permutation(6, 9, 8) >>> p*q != q*p True Calculate and check properties of the conjugate: >>> c = p^q >>> c == ~q*p*q and p == q*c*~q True The expression q^p^r is equivalent to q^(p*r): >>> r = Permutation(9)(4, 6, 8) >>> q^p^r == q^(p*r) True If the term to the left of the conjugate operator, i, is an integer then this is interpreted as selecting the ith element from the permutation to the right: >>> all(i^p == p(i) for i in range(p.size)) True Note that the * operator as higher precedence than the ^ operator: >>> q^r*p^r == q^(r*p)^r == Permutation(9)(1, 6, 4) True Notes ===== In Python the precedence rule is p^q^r = (p^q)^r which differs in general from p^(q^r) >>> q^p^r (9)(1 4 8) >>> q^(p^r) (9)(1 8 6) For a given r and p, both of the following are conjugates of p: ~r*p*r and r*p*~r. But these are not necessarily the same: >>> ~r*p*r == r*p*~r True >>> p = Permutation(1, 2, 9)(5, 6) >>> ~r*p*r == r*p*~r False The conjugate ~r*p*r was chosen so that ``p^q^r`` would be equivalent to ``p^(q*r)`` rather than ``p^(r*q)``. To obtain r*p*~r, pass ~r to this method: >>> p^~r == r*p*~r True """ if self.size != h.size: raise ValueError("The permutations must be of equal size.") a = [None]*self.size h = h._array_form p = self._array_form for i in range(self.size): a[h[i]] = h[p[i]] return self._af_new(a) def transpositions(self): """ Return the permutation decomposed into a list of transpositions. Explanation =========== It is always possible to express a permutation as the product of transpositions, see [1] Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([[1, 2, 3], [0, 4, 5, 6, 7]]) >>> t = p.transpositions() >>> t [(0, 7), (0, 6), (0, 5), (0, 4), (1, 3), (1, 2)] >>> print(''.join(str(c) for c in t)) (0, 7)(0, 6)(0, 5)(0, 4)(1, 3)(1, 2) >>> Permutation.rmul(*[Permutation([ti], size=p.size) for ti in t]) == p True References ========== .. [1] https://en.wikipedia.org/wiki/Transposition_%28mathematics%29#Properties """ a = self.cyclic_form res = [] for x in a: nx = len(x) if nx == 2: res.append(tuple(x)) elif nx > 2: first = x[0] for y in x[nx - 1:0:-1]: res.append((first, y)) return res @classmethod def from_sequence(self, i, key=None): """Return the permutation needed to obtain ``i`` from the sorted elements of ``i``. If custom sorting is desired, a key can be given. Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation.from_sequence('SymPy') (4)(0 1 3) >>> _(sorted("SymPy")) ['S', 'y', 'm', 'P', 'y'] >>> Permutation.from_sequence('SymPy', key=lambda x: x.lower()) (4)(0 2)(1 3) """ ic = list(zip(i, list(range(len(i))))) if key: ic.sort(key=lambda x: key(x[0])) else: ic.sort() return ~Permutation([i[1] for i in ic]) def __invert__(self): """ Return the inverse of the permutation. A permutation multiplied by its inverse is the identity permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([[2, 0], [3, 1]]) >>> ~p Permutation([2, 3, 0, 1]) >>> _ == p**-1 True >>> p*~p == ~p*p == Permutation([0, 1, 2, 3]) True """ return self._af_new(_af_invert(self._array_form)) def __iter__(self): """Yield elements from array form. Examples ======== >>> from sympy.combinatorics import Permutation >>> list(Permutation(range(3))) [0, 1, 2] """ yield from self.array_form def __repr__(self): from sympy.printing.repr import srepr return srepr(self) def __call__(self, *i): """ Allows applying a permutation instance as a bijective function. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([[2, 0], [3, 1]]) >>> p.array_form [2, 3, 0, 1] >>> [p(i) for i in range(4)] [2, 3, 0, 1] If an array is given then the permutation selects the items from the array (i.e. the permutation is applied to the array): >>> from sympy.abc import x >>> p([x, 1, 0, x**2]) [0, x**2, x, 1] """ # list indices can be Integer or int; leave this # as it is (don't test or convert it) because this # gets called a lot and should be fast if len(i) == 1: i = i[0] if not isinstance(i, Iterable): i = as_int(i) if i < 0 or i > self.size: raise TypeError( "{} should be an integer between 0 and {}" .format(i, self.size-1)) return self._array_form[i] # P([a, b, c]) if len(i) != self.size: raise TypeError( "{} should have the length {}.".format(i, self.size)) return [i[j] for j in self._array_form] # P(1, 2, 3) return self*Permutation(Cycle(*i), size=self.size) def atoms(self): """ Returns all the elements of a permutation Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation([0, 1, 2, 3, 4, 5]).atoms() {0, 1, 2, 3, 4, 5} >>> Permutation([[0, 1], [2, 3], [4, 5]]).atoms() {0, 1, 2, 3, 4, 5} """ return set(self.array_form) def apply(self, i): r"""Apply the permutation to an expression. Parameters ========== i : Expr It should be an integer between $0$ and $n-1$ where $n$ is the size of the permutation. If it is a symbol or a symbolic expression that can have integer values, an ``AppliedPermutation`` object will be returned which can represent an unevaluated function. Notes ===== Any permutation can be defined as a bijective function $\sigma : \{ 0, 1, \dots, n-1 \} \rightarrow \{ 0, 1, \dots, n-1 \}$ where $n$ denotes the size of the permutation. The definition may even be extended for any set with distinctive elements, such that the permutation can even be applied for real numbers or such, however, it is not implemented for now for computational reasons and the integrity with the group theory module. This function is similar to the ``__call__`` magic, however, ``__call__`` magic already has some other applications like permuting an array or attatching new cycles, which would not always be mathematically consistent. This also guarantees that the return type is a SymPy integer, which guarantees the safety to use assumptions. """ i = _sympify(i) if i.is_integer is False: raise NotImplementedError("{} should be an integer.".format(i)) n = self.size if (i < 0) == True or (i >= n) == True: raise NotImplementedError( "{} should be an integer between 0 and {}".format(i, n-1)) if i.is_Integer: return Integer(self._array_form[i]) return AppliedPermutation(self, i) def next_lex(self): """ Returns the next permutation in lexicographical order. If self is the last permutation in lexicographical order it returns None. See [4] section 2.4. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([2, 3, 1, 0]) >>> p = Permutation([2, 3, 1, 0]); p.rank() 17 >>> p = p.next_lex(); p.rank() 18 See Also ======== rank, unrank_lex """ perm = self.array_form[:] n = len(perm) i = n - 2 while perm[i + 1] < perm[i]: i -= 1 if i == -1: return None else: j = n - 1 while perm[j] < perm[i]: j -= 1 perm[j], perm[i] = perm[i], perm[j] i += 1 j = n - 1 while i < j: perm[j], perm[i] = perm[i], perm[j] i += 1 j -= 1 return self._af_new(perm) @classmethod def unrank_nonlex(self, n, r): """ This is a linear time unranking algorithm that does not respect lexicographic order [3]. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> Permutation.unrank_nonlex(4, 5) Permutation([2, 0, 3, 1]) >>> Permutation.unrank_nonlex(4, -1) Permutation([0, 1, 2, 3]) See Also ======== next_nonlex, rank_nonlex """ def _unrank1(n, r, a): if n > 0: a[n - 1], a[r % n] = a[r % n], a[n - 1] _unrank1(n - 1, r//n, a) id_perm = list(range(n)) n = int(n) r = r % ifac(n) _unrank1(n, r, id_perm) return self._af_new(id_perm) def rank_nonlex(self, inv_perm=None): """ This is a linear time ranking algorithm that does not enforce lexicographic order [3]. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.rank_nonlex() 23 See Also ======== next_nonlex, unrank_nonlex """ def _rank1(n, perm, inv_perm): if n == 1: return 0 s = perm[n - 1] t = inv_perm[n - 1] perm[n - 1], perm[t] = perm[t], s inv_perm[n - 1], inv_perm[s] = inv_perm[s], t return s + n*_rank1(n - 1, perm, inv_perm) if inv_perm is None: inv_perm = (~self).array_form if not inv_perm: return 0 perm = self.array_form[:] r = _rank1(len(perm), perm, inv_perm) return r def next_nonlex(self): """ Returns the next permutation in nonlex order [3]. If self is the last permutation in this order it returns None. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([2, 0, 3, 1]); p.rank_nonlex() 5 >>> p = p.next_nonlex(); p Permutation([3, 0, 1, 2]) >>> p.rank_nonlex() 6 See Also ======== rank_nonlex, unrank_nonlex """ r = self.rank_nonlex() if r == ifac(self.size) - 1: return None return self.unrank_nonlex(self.size, r + 1) def rank(self): """ Returns the lexicographic rank of the permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.rank() 0 >>> p = Permutation([3, 2, 1, 0]) >>> p.rank() 23 See Also ======== next_lex, unrank_lex, cardinality, length, order, size """ if self._rank is not None: return self._rank rank = 0 rho = self.array_form[:] n = self.size - 1 size = n + 1 psize = int(ifac(n)) for j in range(size - 1): rank += rho[j]*psize for i in range(j + 1, size): if rho[i] > rho[j]: rho[i] -= 1 psize //= n n -= 1 self._rank = rank return rank @property def cardinality(self): """ Returns the number of all possible permutations. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.cardinality 24 See Also ======== length, order, rank, size """ return int(ifac(self.size)) def parity(self): """ Computes the parity of a permutation. Explanation =========== The parity of a permutation reflects the parity of the number of inversions in the permutation, i.e., the number of pairs of x and y such that ``x > y`` but ``p[x] < p[y]``. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.parity() 0 >>> p = Permutation([3, 2, 0, 1]) >>> p.parity() 1 See Also ======== _af_parity """ if self._cyclic_form is not None: return (self.size - self.cycles) % 2 return _af_parity(self.array_form) @property def is_even(self): """ Checks if a permutation is even. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.is_even True >>> p = Permutation([3, 2, 1, 0]) >>> p.is_even True See Also ======== is_odd """ return not self.is_odd @property def is_odd(self): """ Checks if a permutation is odd. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.is_odd False >>> p = Permutation([3, 2, 0, 1]) >>> p.is_odd True See Also ======== is_even """ return bool(self.parity() % 2) @property def is_Singleton(self): """ Checks to see if the permutation contains only one number and is thus the only possible permutation of this set of numbers Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation([0]).is_Singleton True >>> Permutation([0, 1]).is_Singleton False See Also ======== is_Empty """ return self.size == 1 @property def is_Empty(self): """ Checks to see if the permutation is a set with zero elements Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation([]).is_Empty True >>> Permutation([0]).is_Empty False See Also ======== is_Singleton """ return self.size == 0 @property def is_identity(self): return self.is_Identity @property def is_Identity(self): """ Returns True if the Permutation is an identity permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([]) >>> p.is_Identity True >>> p = Permutation([[0], [1], [2]]) >>> p.is_Identity True >>> p = Permutation([0, 1, 2]) >>> p.is_Identity True >>> p = Permutation([0, 2, 1]) >>> p.is_Identity False See Also ======== order """ af = self.array_form return not af or all(i == af[i] for i in range(self.size)) def ascents(self): """ Returns the positions of ascents in a permutation, ie, the location where p[i] < p[i+1] Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([4, 0, 1, 3, 2]) >>> p.ascents() [1, 2] See Also ======== descents, inversions, min, max """ a = self.array_form pos = [i for i in range(len(a) - 1) if a[i] < a[i + 1]] return pos def descents(self): """ Returns the positions of descents in a permutation, ie, the location where p[i] > p[i+1] Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([4, 0, 1, 3, 2]) >>> p.descents() [0, 3] See Also ======== ascents, inversions, min, max """ a = self.array_form pos = [i for i in range(len(a) - 1) if a[i] > a[i + 1]] return pos def max(self): """ The maximum element moved by the permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([1, 0, 2, 3, 4]) >>> p.max() 1 See Also ======== min, descents, ascents, inversions """ max = 0 a = self.array_form for i in range(len(a)): if a[i] != i and a[i] > max: max = a[i] return max def min(self): """ The minimum element moved by the permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 4, 3, 2]) >>> p.min() 2 See Also ======== max, descents, ascents, inversions """ a = self.array_form min = len(a) for i in range(len(a)): if a[i] != i and a[i] < min: min = a[i] return min def inversions(self): """ Computes the number of inversions of a permutation. Explanation =========== An inversion is where i > j but p[i] < p[j]. For small length of p, it iterates over all i and j values and calculates the number of inversions. For large length of p, it uses a variation of merge sort to calculate the number of inversions. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2, 3, 4, 5]) >>> p.inversions() 0 >>> Permutation([3, 2, 1, 0]).inversions() 6 See Also ======== descents, ascents, min, max References ========== .. [1] http://www.cp.eng.chula.ac.th/~piak/teaching/algo/algo2008/count-inv.htm """ inversions = 0 a = self.array_form n = len(a) if n < 130: for i in range(n - 1): b = a[i] for c in a[i + 1:]: if b > c: inversions += 1 else: k = 1 right = 0 arr = a[:] temp = a[:] while k < n: i = 0 while i + k < n: right = i + k * 2 - 1 if right >= n: right = n - 1 inversions += _merge(arr, temp, i, i + k, right) i = i + k * 2 k = k * 2 return inversions def commutator(self, x): """Return the commutator of ``self`` and ``x``: ``~x*~self*x*self`` If f and g are part of a group, G, then the commutator of f and g is the group identity iff f and g commute, i.e. fg == gf. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([0, 2, 3, 1]) >>> x = Permutation([2, 0, 3, 1]) >>> c = p.commutator(x); c Permutation([2, 1, 3, 0]) >>> c == ~x*~p*x*p True >>> I = Permutation(3) >>> p = [I + i for i in range(6)] >>> for i in range(len(p)): ... for j in range(len(p)): ... c = p[i].commutator(p[j]) ... if p[i]*p[j] == p[j]*p[i]: ... assert c == I ... else: ... assert c != I ... References ========== .. [1] https://en.wikipedia.org/wiki/Commutator """ a = self.array_form b = x.array_form n = len(a) if len(b) != n: raise ValueError("The permutations must be of equal size.") inva = [None]*n for i in range(n): inva[a[i]] = i invb = [None]*n for i in range(n): invb[b[i]] = i return self._af_new([a[b[inva[i]]] for i in invb]) def signature(self): """ Gives the signature of the permutation needed to place the elements of the permutation in canonical order. The signature is calculated as (-1)^<number of inversions> Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2]) >>> p.inversions() 0 >>> p.signature() 1 >>> q = Permutation([0,2,1]) >>> q.inversions() 1 >>> q.signature() -1 See Also ======== inversions """ if self.is_even: return 1 return -1 def order(self): """ Computes the order of a permutation. When the permutation is raised to the power of its order it equals the identity permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([3, 1, 5, 2, 4, 0]) >>> p.order() 4 >>> (p**(p.order())) Permutation([], size=6) See Also ======== identity, cardinality, length, rank, size """ return reduce(lcm, [len(cycle) for cycle in self.cyclic_form], 1) def length(self): """ Returns the number of integers moved by a permutation. Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation([0, 3, 2, 1]).length() 2 >>> Permutation([[0, 1], [2, 3]]).length() 4 See Also ======== min, max, support, cardinality, order, rank, size """ return len(self.support()) @property def cycle_structure(self): """Return the cycle structure of the permutation as a dictionary indicating the multiplicity of each cycle length. Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation(3).cycle_structure {1: 4} >>> Permutation(0, 4, 3)(1, 2)(5, 6).cycle_structure {2: 2, 3: 1} """ if self._cycle_structure: rv = self._cycle_structure else: rv = defaultdict(int) singletons = self.size for c in self.cyclic_form: rv[len(c)] += 1 singletons -= len(c) if singletons: rv[1] = singletons self._cycle_structure = rv return dict(rv) # make a copy @property def cycles(self): """ Returns the number of cycles contained in the permutation (including singletons). Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation([0, 1, 2]).cycles 3 >>> Permutation([0, 1, 2]).full_cyclic_form [[0], [1], [2]] >>> Permutation(0, 1)(2, 3).cycles 2 See Also ======== sympy.functions.combinatorial.numbers.stirling """ return len(self.full_cyclic_form) def index(self): """ Returns the index of a permutation. The index of a permutation is the sum of all subscripts j such that p[j] is greater than p[j+1]. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([3, 0, 2, 1, 4]) >>> p.index() 2 """ a = self.array_form return sum([j for j in range(len(a) - 1) if a[j] > a[j + 1]]) def runs(self): """ Returns the runs of a permutation. An ascending sequence in a permutation is called a run [5]. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([2, 5, 7, 3, 6, 0, 1, 4, 8]) >>> p.runs() [[2, 5, 7], [3, 6], [0, 1, 4, 8]] >>> q = Permutation([1,3,2,0]) >>> q.runs() [[1, 3], [2], [0]] """ return runs(self.array_form) def inversion_vector(self): """Return the inversion vector of the permutation. The inversion vector consists of elements whose value indicates the number of elements in the permutation that are lesser than it and lie on its right hand side. The inversion vector is the same as the Lehmer encoding of a permutation. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([4, 8, 0, 7, 1, 5, 3, 6, 2]) >>> p.inversion_vector() [4, 7, 0, 5, 0, 2, 1, 1] >>> p = Permutation([3, 2, 1, 0]) >>> p.inversion_vector() [3, 2, 1] The inversion vector increases lexicographically with the rank of the permutation, the -ith element cycling through 0..i. >>> p = Permutation(2) >>> while p: ... print('%s %s %s' % (p, p.inversion_vector(), p.rank())) ... p = p.next_lex() (2) [0, 0] 0 (1 2) [0, 1] 1 (2)(0 1) [1, 0] 2 (0 1 2) [1, 1] 3 (0 2 1) [2, 0] 4 (0 2) [2, 1] 5 See Also ======== from_inversion_vector """ self_array_form = self.array_form n = len(self_array_form) inversion_vector = [0] * (n - 1) for i in range(n - 1): val = 0 for j in range(i + 1, n): if self_array_form[j] < self_array_form[i]: val += 1 inversion_vector[i] = val return inversion_vector def rank_trotterjohnson(self): """ Returns the Trotter Johnson rank, which we get from the minimal change algorithm. See [4] section 2.4. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.rank_trotterjohnson() 0 >>> p = Permutation([0, 2, 1, 3]) >>> p.rank_trotterjohnson() 7 See Also ======== unrank_trotterjohnson, next_trotterjohnson """ if self.array_form == [] or self.is_Identity: return 0 if self.array_form == [1, 0]: return 1 perm = self.array_form n = self.size rank = 0 for j in range(1, n): k = 1 i = 0 while perm[i] != j: if perm[i] < j: k += 1 i += 1 j1 = j + 1 if rank % 2 == 0: rank = j1*rank + j1 - k else: rank = j1*rank + k - 1 return rank @classmethod def unrank_trotterjohnson(cls, size, rank): """ Trotter Johnson permutation unranking. See [4] section 2.4. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> Permutation.unrank_trotterjohnson(5, 10) Permutation([0, 3, 1, 2, 4]) See Also ======== rank_trotterjohnson, next_trotterjohnson """ perm = [0]*size r2 = 0 n = ifac(size) pj = 1 for j in range(2, size + 1): pj *= j r1 = (rank * pj) // n k = r1 - j*r2 if r2 % 2 == 0: for i in range(j - 1, j - k - 1, -1): perm[i] = perm[i - 1] perm[j - k - 1] = j - 1 else: for i in range(j - 1, k, -1): perm[i] = perm[i - 1] perm[k] = j - 1 r2 = r1 return cls._af_new(perm) def next_trotterjohnson(self): """ Returns the next permutation in Trotter-Johnson order. If self is the last permutation it returns None. See [4] section 2.4. If it is desired to generate all such permutations, they can be generated in order more quickly with the ``generate_bell`` function. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([3, 0, 2, 1]) >>> p.rank_trotterjohnson() 4 >>> p = p.next_trotterjohnson(); p Permutation([0, 3, 2, 1]) >>> p.rank_trotterjohnson() 5 See Also ======== rank_trotterjohnson, unrank_trotterjohnson, sympy.utilities.iterables.generate_bell """ pi = self.array_form[:] n = len(pi) st = 0 rho = pi[:] done = False m = n-1 while m > 0 and not done: d = rho.index(m) for i in range(d, m): rho[i] = rho[i + 1] par = _af_parity(rho[:m]) if par == 1: if d == m: m -= 1 else: pi[st + d], pi[st + d + 1] = pi[st + d + 1], pi[st + d] done = True else: if d == 0: m -= 1 st += 1 else: pi[st + d], pi[st + d - 1] = pi[st + d - 1], pi[st + d] done = True if m == 0: return None return self._af_new(pi) def get_precedence_matrix(self): """ Gets the precedence matrix. This is used for computing the distance between two permutations. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation.josephus(3, 6, 1) >>> p Permutation([2, 5, 3, 1, 4, 0]) >>> p.get_precedence_matrix() Matrix([ [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 1, 0], [1, 1, 0, 1, 1, 1], [1, 1, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0], [1, 1, 0, 1, 1, 0]]) See Also ======== get_precedence_distance, get_adjacency_matrix, get_adjacency_distance """ m = zeros(self.size) perm = self.array_form for i in range(m.rows): for j in range(i + 1, m.cols): m[perm[i], perm[j]] = 1 return m def get_precedence_distance(self, other): """ Computes the precedence distance between two permutations. Explanation =========== Suppose p and p' represent n jobs. The precedence metric counts the number of times a job j is preceded by job i in both p and p'. This metric is commutative. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([2, 0, 4, 3, 1]) >>> q = Permutation([3, 1, 2, 4, 0]) >>> p.get_precedence_distance(q) 7 >>> q.get_precedence_distance(p) 7 See Also ======== get_precedence_matrix, get_adjacency_matrix, get_adjacency_distance """ if self.size != other.size: raise ValueError("The permutations must be of equal size.") self_prec_mat = self.get_precedence_matrix() other_prec_mat = other.get_precedence_matrix() n_prec = 0 for i in range(self.size): for j in range(self.size): if i == j: continue if self_prec_mat[i, j] * other_prec_mat[i, j] == 1: n_prec += 1 d = self.size * (self.size - 1)//2 - n_prec return d def get_adjacency_matrix(self): """ Computes the adjacency matrix of a permutation. Explanation =========== If job i is adjacent to job j in a permutation p then we set m[i, j] = 1 where m is the adjacency matrix of p. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation.josephus(3, 6, 1) >>> p.get_adjacency_matrix() Matrix([ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]]) >>> q = Permutation([0, 1, 2, 3]) >>> q.get_adjacency_matrix() Matrix([ [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, 0]]) See Also ======== get_precedence_matrix, get_precedence_distance, get_adjacency_distance """ m = zeros(self.size) perm = self.array_form for i in range(self.size - 1): m[perm[i], perm[i + 1]] = 1 return m def get_adjacency_distance(self, other): """ Computes the adjacency distance between two permutations. Explanation =========== This metric counts the number of times a pair i,j of jobs is adjacent in both p and p'. If n_adj is this quantity then the adjacency distance is n - n_adj - 1 [1] [1] Reeves, Colin R. Landscapes, Operators and Heuristic search, Annals of Operational Research, 86, pp 473-490. (1999) Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 3, 1, 2, 4]) >>> q = Permutation.josephus(4, 5, 2) >>> p.get_adjacency_distance(q) 3 >>> r = Permutation([0, 2, 1, 4, 3]) >>> p.get_adjacency_distance(r) 4 See Also ======== get_precedence_matrix, get_precedence_distance, get_adjacency_matrix """ if self.size != other.size: raise ValueError("The permutations must be of the same size.") self_adj_mat = self.get_adjacency_matrix() other_adj_mat = other.get_adjacency_matrix() n_adj = 0 for i in range(self.size): for j in range(self.size): if i == j: continue if self_adj_mat[i, j] * other_adj_mat[i, j] == 1: n_adj += 1 d = self.size - n_adj - 1 return d def get_positional_distance(self, other): """ Computes the positional distance between two permutations. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> p = Permutation([0, 3, 1, 2, 4]) >>> q = Permutation.josephus(4, 5, 2) >>> r = Permutation([3, 1, 4, 0, 2]) >>> p.get_positional_distance(q) 12 >>> p.get_positional_distance(r) 12 See Also ======== get_precedence_distance, get_adjacency_distance """ a = self.array_form b = other.array_form if len(a) != len(b): raise ValueError("The permutations must be of the same size.") return sum([abs(a[i] - b[i]) for i in range(len(a))]) @classmethod def josephus(cls, m, n, s=1): """Return as a permutation the shuffling of range(n) using the Josephus scheme in which every m-th item is selected until all have been chosen. The returned permutation has elements listed by the order in which they were selected. The parameter ``s`` stops the selection process when there are ``s`` items remaining and these are selected by continuing the selection, counting by 1 rather than by ``m``. Consider selecting every 3rd item from 6 until only 2 remain:: choices chosen ======== ====== 012345 01 345 2 01 34 25 01 4 253 0 4 2531 0 25314 253140 Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation.josephus(3, 6, 2).array_form [2, 5, 3, 1, 4, 0] References ========== .. [1] https://en.wikipedia.org/wiki/Flavius_Josephus .. [2] https://en.wikipedia.org/wiki/Josephus_problem .. [3] http://www.wou.edu/~burtonl/josephus.html """ from collections import deque m -= 1 Q = deque(list(range(n))) perm = [] while len(Q) > max(s, 1): for dp in range(m): Q.append(Q.popleft()) perm.append(Q.popleft()) perm.extend(list(Q)) return cls(perm) @classmethod def from_inversion_vector(cls, inversion): """ Calculates the permutation from the inversion vector. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> Permutation.from_inversion_vector([3, 2, 1, 0, 0]) Permutation([3, 2, 1, 0, 4, 5]) """ size = len(inversion) N = list(range(size + 1)) perm = [] try: for k in range(size): val = N[inversion[k]] perm.append(val) N.remove(val) except IndexError: raise ValueError("The inversion vector is not valid.") perm.extend(N) return cls._af_new(perm) @classmethod def random(cls, n): """ Generates a random permutation of length ``n``. Uses the underlying Python pseudo-random number generator. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> Permutation.random(2) in (Permutation([1, 0]), Permutation([0, 1])) True """ perm_array = list(range(n)) random.shuffle(perm_array) return cls._af_new(perm_array) @classmethod def unrank_lex(cls, size, rank): """ Lexicographic permutation unranking. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> a = Permutation.unrank_lex(5, 10) >>> a.rank() 10 >>> a Permutation([0, 2, 4, 1, 3]) See Also ======== rank, next_lex """ perm_array = [0] * size psize = 1 for i in range(size): new_psize = psize*(i + 1) d = (rank % new_psize) // psize rank -= d*psize perm_array[size - i - 1] = d for j in range(size - i, size): if perm_array[j] > d - 1: perm_array[j] += 1 psize = new_psize return cls._af_new(perm_array) def resize(self, n): """Resize the permutation to the new size ``n``. Parameters ========== n : int The new size of the permutation. Raises ====== ValueError If the permutation cannot be resized to the given size. This may only happen when resized to a smaller size than the original. Examples ======== >>> from sympy.combinatorics.permutations import Permutation Increasing the size of a permutation: >>> p = Permutation(0, 1, 2) >>> p = p.resize(5) >>> p (4)(0 1 2) Decreasing the size of the permutation: >>> p = p.resize(4) >>> p (3)(0 1 2) If resizing to the specific size breaks the cycles: >>> p.resize(2) Traceback (most recent call last): ... ValueError: The permutation cannot be resized to 2 because the cycle (0, 1, 2) may break. """ aform = self.array_form l = len(aform) if n > l: aform += list(range(l, n)) return Permutation._af_new(aform) elif n < l: cyclic_form = self.full_cyclic_form new_cyclic_form = [] for cycle in cyclic_form: cycle_min = min(cycle) cycle_max = max(cycle) if cycle_min <= n-1: if cycle_max > n-1: raise ValueError( "The permutation cannot be resized to {} " "because the cycle {} may break." .format(n, tuple(cycle))) new_cyclic_form.append(cycle) return Permutation(new_cyclic_form) return self # XXX Deprecated flag print_cyclic = None def _merge(arr, temp, left, mid, right): """ Merges two sorted arrays and calculates the inversion count. Helper function for calculating inversions. This method is for internal use only. """ i = k = left j = mid inv_count = 0 while i < mid and j <= right: if arr[i] < arr[j]: temp[k] = arr[i] k += 1 i += 1 else: temp[k] = arr[j] k += 1 j += 1 inv_count += (mid -i) while i < mid: temp[k] = arr[i] k += 1 i += 1 if j <= right: k += right - j + 1 j += right - j + 1 arr[left:k + 1] = temp[left:k + 1] else: arr[left:right + 1] = temp[left:right + 1] return inv_count Perm = Permutation _af_new = Perm._af_new class AppliedPermutation(Expr): """A permutation applied to a symbolic variable. Parameters ========== perm : Permutation x : Expr Examples ======== >>> from sympy import Symbol >>> from sympy.combinatorics import Permutation Creating a symbolic permutation function application: >>> x = Symbol('x') >>> p = Permutation(0, 1, 2) >>> p.apply(x) AppliedPermutation((0 1 2), x) >>> _.subs(x, 1) 2 """ def __new__(cls, perm, x, evaluate=None): if evaluate is None: evaluate = global_parameters.evaluate perm = _sympify(perm) x = _sympify(x) if not isinstance(perm, Permutation): raise ValueError("{} must be a Permutation instance." .format(perm)) if evaluate: if x.is_Integer: return perm.apply(x) obj = super().__new__(cls, perm, x) return obj @dispatch(Permutation, Permutation) def _eval_is_eq(lhs, rhs): if lhs._size != rhs._size: return None return lhs._array_form == rhs._array_form
fd2b6bf4faf83d8847cbfdd7675187fd65f1579dfb0cdfc469b7d751c4a7ae07
from itertools import combinations from sympy.combinatorics.graycode import GrayCode class Subset(): """ Represents a basic subset object. Explanation =========== We generate subsets using essentially two techniques, binary enumeration and lexicographic enumeration. The Subset class takes two arguments, the first one describes the initial subset to consider and the second describes the superset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.next_binary().subset ['b'] >>> a.prev_binary().subset ['c'] """ _rank_binary = None _rank_lex = None _rank_graycode = None _subset = None _superset = None def __new__(cls, subset, superset): """ Default constructor. It takes the ``subset`` and its ``superset`` as its parameters. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.subset ['c', 'd'] >>> a.superset ['a', 'b', 'c', 'd'] >>> a.size 2 """ if len(subset) > len(superset): raise ValueError('Invalid arguments have been provided. The ' 'superset must be larger than the subset.') for elem in subset: if elem not in superset: raise ValueError('The superset provided is invalid as it does ' 'not contain the element {}'.format(elem)) obj = object.__new__(cls) obj._subset = subset obj._superset = superset return obj def __eq__(self, other): """Return a boolean indicating whether a == b on the basis of whether both objects are of the class Subset and if the values of the subset and superset attributes are the same. """ if not isinstance(other, Subset): return NotImplemented return self.subset == other.subset and self.superset == other.superset def iterate_binary(self, k): """ This is a helper function. It iterates over the binary subsets by ``k`` steps. This variable can be both positive or negative. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.iterate_binary(-2).subset ['d'] >>> a = Subset(['a', 'b', 'c'], ['a', 'b', 'c', 'd']) >>> a.iterate_binary(2).subset [] See Also ======== next_binary, prev_binary """ bin_list = Subset.bitlist_from_subset(self.subset, self.superset) n = (int(''.join(bin_list), 2) + k) % 2**self.superset_size bits = bin(n)[2:].rjust(self.superset_size, '0') return Subset.subset_from_bitlist(self.superset, bits) def next_binary(self): """ Generates the next binary ordered subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.next_binary().subset ['b'] >>> a = Subset(['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']) >>> a.next_binary().subset [] See Also ======== prev_binary, iterate_binary """ return self.iterate_binary(1) def prev_binary(self): """ Generates the previous binary ordered subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset([], ['a', 'b', 'c', 'd']) >>> a.prev_binary().subset ['a', 'b', 'c', 'd'] >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.prev_binary().subset ['c'] See Also ======== next_binary, iterate_binary """ return self.iterate_binary(-1) def next_lexicographic(self): """ Generates the next lexicographically ordered subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.next_lexicographic().subset ['d'] >>> a = Subset(['d'], ['a', 'b', 'c', 'd']) >>> a.next_lexicographic().subset [] See Also ======== prev_lexicographic """ i = self.superset_size - 1 indices = Subset.subset_indices(self.subset, self.superset) if i in indices: if i - 1 in indices: indices.remove(i - 1) else: indices.remove(i) i = i - 1 while i >= 0 and i not in indices: i = i - 1 if i >= 0: indices.remove(i) indices.append(i+1) else: while i not in indices and i >= 0: i = i - 1 indices.append(i + 1) ret_set = [] super_set = self.superset for i in indices: ret_set.append(super_set[i]) return Subset(ret_set, super_set) def prev_lexicographic(self): """ Generates the previous lexicographically ordered subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset([], ['a', 'b', 'c', 'd']) >>> a.prev_lexicographic().subset ['d'] >>> a = Subset(['c','d'], ['a', 'b', 'c', 'd']) >>> a.prev_lexicographic().subset ['c'] See Also ======== next_lexicographic """ i = self.superset_size - 1 indices = Subset.subset_indices(self.subset, self.superset) while i >= 0 and i not in indices: i = i - 1 if i == 0 or i - 1 in indices: indices.remove(i) else: if i >= 0: indices.remove(i) indices.append(i - 1) indices.append(self.superset_size - 1) ret_set = [] super_set = self.superset for i in indices: ret_set.append(super_set[i]) return Subset(ret_set, super_set) def iterate_graycode(self, k): """ Helper function used for prev_gray and next_gray. It performs ``k`` step overs to get the respective Gray codes. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset([1, 2, 3], [1, 2, 3, 4]) >>> a.iterate_graycode(3).subset [1, 4] >>> a.iterate_graycode(-2).subset [1, 2, 4] See Also ======== next_gray, prev_gray """ unranked_code = GrayCode.unrank(self.superset_size, (self.rank_gray + k) % self.cardinality) return Subset.subset_from_bitlist(self.superset, unranked_code) def next_gray(self): """ Generates the next Gray code ordered subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset([1, 2, 3], [1, 2, 3, 4]) >>> a.next_gray().subset [1, 3] See Also ======== iterate_graycode, prev_gray """ return self.iterate_graycode(1) def prev_gray(self): """ Generates the previous Gray code ordered subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset([2, 3, 4], [1, 2, 3, 4, 5]) >>> a.prev_gray().subset [2, 3, 4, 5] See Also ======== iterate_graycode, next_gray """ return self.iterate_graycode(-1) @property def rank_binary(self): """ Computes the binary ordered rank. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset([], ['a','b','c','d']) >>> a.rank_binary 0 >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.rank_binary 3 See Also ======== iterate_binary, unrank_binary """ if self._rank_binary is None: self._rank_binary = int("".join( Subset.bitlist_from_subset(self.subset, self.superset)), 2) return self._rank_binary @property def rank_lexicographic(self): """ Computes the lexicographic ranking of the subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.rank_lexicographic 14 >>> a = Subset([2, 4, 5], [1, 2, 3, 4, 5, 6]) >>> a.rank_lexicographic 43 """ if self._rank_lex is None: def _ranklex(self, subset_index, i, n): if subset_index == [] or i > n: return 0 if i in subset_index: subset_index.remove(i) return 1 + _ranklex(self, subset_index, i + 1, n) return 2**(n - i - 1) + _ranklex(self, subset_index, i + 1, n) indices = Subset.subset_indices(self.subset, self.superset) self._rank_lex = _ranklex(self, indices, 0, self.superset_size) return self._rank_lex @property def rank_gray(self): """ Computes the Gray code ranking of the subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c','d'], ['a','b','c','d']) >>> a.rank_gray 2 >>> a = Subset([2, 4, 5], [1, 2, 3, 4, 5, 6]) >>> a.rank_gray 27 See Also ======== iterate_graycode, unrank_gray """ if self._rank_graycode is None: bits = Subset.bitlist_from_subset(self.subset, self.superset) self._rank_graycode = GrayCode(len(bits), start=bits).rank return self._rank_graycode @property def subset(self): """ Gets the subset represented by the current instance. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.subset ['c', 'd'] See Also ======== superset, size, superset_size, cardinality """ return self._subset @property def size(self): """ Gets the size of the subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.size 2 See Also ======== subset, superset, superset_size, cardinality """ return len(self.subset) @property def superset(self): """ Gets the superset of the subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.superset ['a', 'b', 'c', 'd'] See Also ======== subset, size, superset_size, cardinality """ return self._superset @property def superset_size(self): """ Returns the size of the superset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.superset_size 4 See Also ======== subset, superset, size, cardinality """ return len(self.superset) @property def cardinality(self): """ Returns the number of all possible subsets. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.cardinality 16 See Also ======== subset, superset, size, superset_size """ return 2**(self.superset_size) @classmethod def subset_from_bitlist(self, super_set, bitlist): """ Gets the subset defined by the bitlist. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> Subset.subset_from_bitlist(['a', 'b', 'c', 'd'], '0011').subset ['c', 'd'] See Also ======== bitlist_from_subset """ if len(super_set) != len(bitlist): raise ValueError("The sizes of the lists are not equal") ret_set = [] for i in range(len(bitlist)): if bitlist[i] == '1': ret_set.append(super_set[i]) return Subset(ret_set, super_set) @classmethod def bitlist_from_subset(self, subset, superset): """ Gets the bitlist corresponding to a subset. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> Subset.bitlist_from_subset(['c', 'd'], ['a', 'b', 'c', 'd']) '0011' See Also ======== subset_from_bitlist """ bitlist = ['0'] * len(superset) if isinstance(subset, Subset): subset = subset.subset for i in Subset.subset_indices(subset, superset): bitlist[i] = '1' return ''.join(bitlist) @classmethod def unrank_binary(self, rank, superset): """ Gets the binary ordered subset of the specified rank. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> Subset.unrank_binary(4, ['a', 'b', 'c', 'd']).subset ['b'] See Also ======== iterate_binary, rank_binary """ bits = bin(rank)[2:].rjust(len(superset), '0') return Subset.subset_from_bitlist(superset, bits) @classmethod def unrank_gray(self, rank, superset): """ Gets the Gray code ordered subset of the specified rank. Examples ======== >>> from sympy.combinatorics.subsets import Subset >>> Subset.unrank_gray(4, ['a', 'b', 'c']).subset ['a', 'b'] >>> Subset.unrank_gray(0, ['a', 'b', 'c']).subset [] See Also ======== iterate_graycode, rank_gray """ graycode_bitlist = GrayCode.unrank(len(superset), rank) return Subset.subset_from_bitlist(superset, graycode_bitlist) @classmethod def subset_indices(self, subset, superset): """Return indices of subset in superset in a list; the list is empty if all elements of ``subset`` are not in ``superset``. Examples ======== >>> from sympy.combinatorics import Subset >>> superset = [1, 3, 2, 5, 4] >>> Subset.subset_indices([3, 2, 1], superset) [1, 2, 0] >>> Subset.subset_indices([1, 6], superset) [] >>> Subset.subset_indices([], superset) [] """ a, b = superset, subset sb = set(b) d = {} for i, ai in enumerate(a): if ai in sb: d[ai] = i sb.remove(ai) if not sb: break else: return list() return [d[bi] for bi in b] def ksubsets(superset, k): """ Finds the subsets of size ``k`` in lexicographic order. This uses the itertools generator. Examples ======== >>> from sympy.combinatorics.subsets import ksubsets >>> list(ksubsets([1, 2, 3], 2)) [(1, 2), (1, 3), (2, 3)] >>> list(ksubsets([1, 2, 3, 4, 5], 2)) [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), \ (2, 5), (3, 4), (3, 5), (4, 5)] See Also ======== Subset """ return combinations(superset, k)
60117c31f998697fe9c486a82b53aea78a3934d759b40383aa8f7079ab713650
from sympy.combinatorics.permutations import Permutation, _af_rmul, \ _af_invert, _af_new from sympy.combinatorics.perm_groups import PermutationGroup, _orbit, \ _orbit_transversal from sympy.combinatorics.util import _distribute_gens_by_base, \ _orbits_transversals_from_bsgs """ References for tensor canonicalization: [1] R. Portugal "Algorithmic simplification of tensor expressions", J. Phys. A 32 (1999) 7779-7789 [2] R. Portugal, B.F. Svaiter "Group-theoretic Approach for Symbolic Tensor Manipulation: I. Free Indices" arXiv:math-ph/0107031v1 [3] L.R.U. Manssur, R. Portugal "Group-theoretic Approach for Symbolic Tensor Manipulation: II. Dummy Indices" arXiv:math-ph/0107032v1 [4] xperm.c part of XPerm written by J. M. Martin-Garcia http://www.xact.es/index.html """ def dummy_sgs(dummies, sym, n): """ Return the strong generators for dummy indices. Parameters ========== dummies : List of dummy indices. `dummies[2k], dummies[2k+1]` are paired indices. In base form, the dummy indices are always in consecutive positions. sym : symmetry under interchange of contracted dummies:: * None no symmetry * 0 commuting * 1 anticommuting n : number of indices Examples ======== >>> from sympy.combinatorics.tensor_can import dummy_sgs >>> dummy_sgs(list(range(2, 8)), 0, 8) [[0, 1, 3, 2, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 5, 4, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 7, 6, 8, 9], [0, 1, 4, 5, 2, 3, 6, 7, 8, 9], [0, 1, 2, 3, 6, 7, 4, 5, 8, 9]] """ if len(dummies) > n: raise ValueError("List too large") res = [] # exchange of contravariant and covariant indices if sym is not None: for j in dummies[::2]: a = list(range(n + 2)) if sym == 1: a[n] = n + 1 a[n + 1] = n a[j], a[j + 1] = a[j + 1], a[j] res.append(a) # rename dummy indices for j in dummies[:-3:2]: a = list(range(n + 2)) a[j:j + 4] = a[j + 2], a[j + 3], a[j], a[j + 1] res.append(a) return res def _min_dummies(dummies, sym, indices): """ Return list of minima of the orbits of indices in group of dummies. See ``double_coset_can_rep`` for the description of ``dummies`` and ``sym``. ``indices`` is the initial list of dummy indices. Examples ======== >>> from sympy.combinatorics.tensor_can import _min_dummies >>> _min_dummies([list(range(2, 8))], [0], list(range(10))) [0, 1, 2, 2, 2, 2, 2, 2, 8, 9] """ num_types = len(sym) m = [] for dx in dummies: if dx: m.append(min(dx)) else: m.append(None) res = indices[:] for i in range(num_types): for c, i in enumerate(indices): for j in range(num_types): if i in dummies[j]: res[c] = m[j] break return res def _trace_S(s, j, b, S_cosets): """ Return the representative h satisfying s[h[b]] == j If there is not such a representative return None """ for h in S_cosets[b]: if s[h[b]] == j: return h return None def _trace_D(gj, p_i, Dxtrav): """ Return the representative h satisfying h[gj] == p_i If there is not such a representative return None """ for h in Dxtrav: if h[gj] == p_i: return h return None def _dumx_remove(dumx, dumx_flat, p0): """ remove p0 from dumx """ res = [] for dx in dumx: if p0 not in dx: res.append(dx) continue k = dx.index(p0) if k % 2 == 0: p0_paired = dx[k + 1] else: p0_paired = dx[k - 1] dx.remove(p0) dx.remove(p0_paired) dumx_flat.remove(p0) dumx_flat.remove(p0_paired) res.append(dx) def transversal2coset(size, base, transversal): a = [] j = 0 for i in range(size): if i in base: a.append(sorted(transversal[j].values())) j += 1 else: a.append([list(range(size))]) j = len(a) - 1 while a[j] == [list(range(size))]: j -= 1 return a[:j + 1] def double_coset_can_rep(dummies, sym, b_S, sgens, S_transversals, g): r""" Butler-Portugal algorithm for tensor canonicalization with dummy indices. Parameters ========== dummies list of lists of dummy indices, one list for each type of index; the dummy indices are put in order contravariant, covariant [d0, -d0, d1, -d1, ...]. sym list of the symmetries of the index metric for each type. possible symmetries of the metrics * 0 symmetric * 1 antisymmetric * None no symmetry b_S base of a minimal slot symmetry BSGS. sgens generators of the slot symmetry BSGS. S_transversals transversals for the slot BSGS. g permutation representing the tensor. Returns ======= Return 0 if the tensor is zero, else return the array form of the permutation representing the canonical form of the tensor. Notes ===== A tensor with dummy indices can be represented in a number of equivalent ways which typically grows exponentially with the number of indices. To be able to establish if two tensors with many indices are equal becomes computationally very slow in absence of an efficient algorithm. The Butler-Portugal algorithm [3] is an efficient algorithm to put tensors in canonical form, solving the above problem. Portugal observed that a tensor can be represented by a permutation, and that the class of tensors equivalent to it under slot and dummy symmetries is equivalent to the double coset `D*g*S` (Note: in this documentation we use the conventions for multiplication of permutations p, q with (p*q)(i) = p[q[i]] which is opposite to the one used in the Permutation class) Using the algorithm by Butler to find a representative of the double coset one can find a canonical form for the tensor. To see this correspondence, let `g` be a permutation in array form; a tensor with indices `ind` (the indices including both the contravariant and the covariant ones) can be written as `t = T(ind[g[0]], \dots, ind[g[n-1]])`, where `n = len(ind)`; `g` has size `n + 2`, the last two indices for the sign of the tensor (trick introduced in [4]). A slot symmetry transformation `s` is a permutation acting on the slots `t \rightarrow T(ind[(g*s)[0]], \dots, ind[(g*s)[n-1]])` A dummy symmetry transformation acts on `ind` `t \rightarrow T(ind[(d*g)[0]], \dots, ind[(d*g)[n-1]])` Being interested only in the transformations of the tensor under these symmetries, one can represent the tensor by `g`, which transforms as `g -> d*g*s`, so it belongs to the coset `D*g*S`, or in other words to the set of all permutations allowed by the slot and dummy symmetries. Let us explain the conventions by an example. Given a tensor `T^{d3 d2 d1}{}_{d1 d2 d3}` with the slot symmetries `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}` `T^{a0 a1 a2 a3 a4 a5} = -T^{a4 a1 a2 a3 a0 a5}` and symmetric metric, find the tensor equivalent to it which is the lowest under the ordering of indices: lexicographic ordering `d1, d2, d3` and then contravariant before covariant index; that is the canonical form of the tensor. The canonical form is `-T^{d1 d2 d3}{}_{d1 d2 d3}` obtained using `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}`. To convert this problem in the input for this function, use the following ordering of the index names (- for covariant for short) `d1, -d1, d2, -d2, d3, -d3` `T^{d3 d2 d1}{}_{d1 d2 d3}` corresponds to `g = [4, 2, 0, 1, 3, 5, 6, 7]` where the last two indices are for the sign `sgens = [Permutation(0, 2)(6, 7), Permutation(0, 4)(6, 7)]` sgens[0] is the slot symmetry `-(0, 2)` `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}` sgens[1] is the slot symmetry `-(0, 4)` `T^{a0 a1 a2 a3 a4 a5} = -T^{a4 a1 a2 a3 a0 a5}` The dummy symmetry group D is generated by the strong base generators `[(0, 1), (2, 3), (4, 5), (0, 2)(1, 3), (0, 4)(1, 5)]` where the first three interchange covariant and contravariant positions of the same index (d1 <-> -d1) and the last two interchange the dummy indices themselves (d1 <-> d2). The dummy symmetry acts from the left `d = [1, 0, 2, 3, 4, 5, 6, 7]` exchange `d1 \leftrightarrow -d1` `T^{d3 d2 d1}{}_{d1 d2 d3} == T^{d3 d2}{}_{d1}{}^{d1}{}_{d2 d3}` `g=[4, 2, 0, 1, 3, 5, 6, 7] -> [4, 2, 1, 0, 3, 5, 6, 7] = _af_rmul(d, g)` which differs from `_af_rmul(g, d)`. The slot symmetry acts from the right `s = [2, 1, 0, 3, 4, 5, 7, 6]` exchanges slots 0 and 2 and changes sign `T^{d3 d2 d1}{}_{d1 d2 d3} == -T^{d1 d2 d3}{}_{d1 d2 d3}` `g=[4,2,0,1,3,5,6,7] -> [0, 2, 4, 1, 3, 5, 7, 6] = _af_rmul(g, s)` Example in which the tensor is zero, same slot symmetries as above: `T^{d2}{}_{d1 d3}{}^{d1 d3}{}_{d2}` `= -T^{d3}{}_{d1 d3}{}^{d1 d2}{}_{d2}` under slot symmetry `-(0,4)`; `= T_{d3 d1}{}^{d3}{}^{d1 d2}{}_{d2}` under slot symmetry `-(0,2)`; `= T^{d3}{}_{d1 d3}{}^{d1 d2}{}_{d2}` symmetric metric; `= 0` since two of these lines have tensors differ only for the sign. The double coset D*g*S consists of permutations `h = d*g*s` corresponding to equivalent tensors; if there are two `h` which are the same apart from the sign, return zero; otherwise choose as representative the tensor with indices ordered lexicographically according to `[d1, -d1, d2, -d2, d3, -d3]` that is ``rep = min(D*g*S) = min([d*g*s for d in D for s in S])`` The indices are fixed one by one; first choose the lowest index for slot 0, then the lowest remaining index for slot 1, etc. Doing this one obtains a chain of stabilizers `S \rightarrow S_{b0} \rightarrow S_{b0,b1} \rightarrow \dots` and `D \rightarrow D_{p0} \rightarrow D_{p0,p1} \rightarrow \dots` where ``[b0, b1, ...] = range(b)`` is a base of the symmetric group; the strong base `b_S` of S is an ordered sublist of it; therefore it is sufficient to compute once the strong base generators of S using the Schreier-Sims algorithm; the stabilizers of the strong base generators are the strong base generators of the stabilizer subgroup. ``dbase = [p0, p1, ...]`` is not in general in lexicographic order, so that one must recompute the strong base generators each time; however this is trivial, there is no need to use the Schreier-Sims algorithm for D. The algorithm keeps a TAB of elements `(s_i, d_i, h_i)` where `h_i = d_i \times g \times s_i` satisfying `h_i[j] = p_j` for `0 \le j < i` starting from `s_0 = id, d_0 = id, h_0 = g`. The equations `h_0[0] = p_0, h_1[1] = p_1, \dots` are solved in this order, choosing each time the lowest possible value of p_i For `j < i` `d_i*g*s_i*S_{b_0, \dots, b_{i-1}}*b_j = D_{p_0, \dots, p_{i-1}}*p_j` so that for dx in `D_{p_0,\dots,p_{i-1}}` and sx in `S_{base[0], \dots, base[i-1]}` one has `dx*d_i*g*s_i*sx*b_j = p_j` Search for dx, sx such that this equation holds for `j = i`; it can be written as `s_i*sx*b_j = J, dx*d_i*g*J = p_j` `sx*b_j = s_i**-1*J; sx = trace(s_i**-1, S_{b_0,...,b_{i-1}})` `dx**-1*p_j = d_i*g*J; dx = trace(d_i*g*J, D_{p_0,...,p_{i-1}})` `s_{i+1} = s_i*trace(s_i**-1*J, S_{b_0,...,b_{i-1}})` `d_{i+1} = trace(d_i*g*J, D_{p_0,...,p_{i-1}})**-1*d_i` `h_{i+1}*b_i = d_{i+1}*g*s_{i+1}*b_i = p_i` `h_n*b_j = p_j` for all j, so that `h_n` is the solution. Add the found `(s, d, h)` to TAB1. At the end of the iteration sort TAB1 with respect to the `h`; if there are two consecutive `h` in TAB1 which differ only for the sign, the tensor is zero, so return 0; if there are two consecutive `h` which are equal, keep only one. Then stabilize the slot generators under `i` and the dummy generators under `p_i`. Assign `TAB = TAB1` at the end of the iteration step. At the end `TAB` contains a unique `(s, d, h)`, since all the slots of the tensor `h` have been fixed to have the minimum value according to the symmetries. The algorithm returns `h`. It is important that the slot BSGS has lexicographic minimal base, otherwise there is an `i` which does not belong to the slot base for which `p_i` is fixed by the dummy symmetry only, while `i` is not invariant from the slot stabilizer, so `p_i` is not in general the minimal value. This algorithm differs slightly from the original algorithm [3]: the canonical form is minimal lexicographically, and the BSGS has minimal base under lexicographic order. Equal tensors `h` are eliminated from TAB. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.tensor_can import double_coset_can_rep, get_transversals >>> gens = [Permutation(x) for x in [[2, 1, 0, 3, 4, 5, 7, 6], [4, 1, 2, 3, 0, 5, 7, 6]]] >>> base = [0, 2] >>> g = Permutation([4, 2, 0, 1, 3, 5, 6, 7]) >>> transversals = get_transversals(base, gens) >>> double_coset_can_rep([list(range(6))], [0], base, gens, transversals, g) [0, 1, 2, 3, 4, 5, 7, 6] >>> g = Permutation([4, 1, 3, 0, 5, 2, 6, 7]) >>> double_coset_can_rep([list(range(6))], [0], base, gens, transversals, g) 0 """ size = g.size g = g.array_form num_dummies = size - 2 indices = list(range(num_dummies)) all_metrics_with_sym = not any(_ is None for _ in sym) num_types = len(sym) dumx = dummies[:] dumx_flat = [] for dx in dumx: dumx_flat.extend(dx) b_S = b_S[:] sgensx = [h._array_form for h in sgens] if b_S: S_transversals = transversal2coset(size, b_S, S_transversals) # strong generating set for D dsgsx = [] for i in range(num_types): dsgsx.extend(dummy_sgs(dumx[i], sym[i], num_dummies)) idn = list(range(size)) # TAB = list of entries (s, d, h) where h = _af_rmuln(d,g,s) # for short, in the following d*g*s means _af_rmuln(d,g,s) TAB = [(idn, idn, g)] for i in range(size - 2): b = i testb = b in b_S and sgensx if testb: sgensx1 = [_af_new(_) for _ in sgensx] deltab = _orbit(size, sgensx1, b) else: deltab = {b} # p1 = min(IMAGES) = min(Union D_p*h*deltab for h in TAB) if all_metrics_with_sym: md = _min_dummies(dumx, sym, indices) else: md = [min(_orbit(size, [_af_new( ddx) for ddx in dsgsx], ii)) for ii in range(size - 2)] p_i = min([min([md[h[x]] for x in deltab]) for s, d, h in TAB]) dsgsx1 = [_af_new(_) for _ in dsgsx] Dxtrav = _orbit_transversal(size, dsgsx1, p_i, False, af=True) \ if dsgsx else None if Dxtrav: Dxtrav = [_af_invert(x) for x in Dxtrav] # compute the orbit of p_i for ii in range(num_types): if p_i in dumx[ii]: # the orbit is made by all the indices in dum[ii] if sym[ii] is not None: deltap = dumx[ii] else: # the orbit is made by all the even indices if p_i # is even, by all the odd indices if p_i is odd p_i_index = dumx[ii].index(p_i) % 2 deltap = dumx[ii][p_i_index::2] break else: deltap = [p_i] TAB1 = [] while TAB: s, d, h = TAB.pop() if min([md[h[x]] for x in deltab]) != p_i: continue deltab1 = [x for x in deltab if md[h[x]] == p_i] # NEXT = s*deltab1 intersection (d*g)**-1*deltap dg = _af_rmul(d, g) dginv = _af_invert(dg) sdeltab = [s[x] for x in deltab1] gdeltap = [dginv[x] for x in deltap] NEXT = [x for x in sdeltab if x in gdeltap] # d, s satisfy # d*g*s*base[i-1] = p_{i-1}; using the stabilizers # d*g*s*S_{base[0],...,base[i-1]}*base[i-1] = # D_{p_0,...,p_{i-1}}*p_{i-1} # so that to find d1, s1 satisfying d1*g*s1*b = p_i # one can look for dx in D_{p_0,...,p_{i-1}} and # sx in S_{base[0],...,base[i-1]} # d1 = dx*d; s1 = s*sx # d1*g*s1*b = dx*d*g*s*sx*b = p_i for j in NEXT: if testb: # solve s1*b = j with s1 = s*sx for some element sx # of the stabilizer of ..., base[i-1] # sx*b = s**-1*j; sx = _trace_S(s, j,...) # s1 = s*trace_S(s**-1*j,...) s1 = _trace_S(s, j, b, S_transversals) if not s1: continue else: s1 = [s[ix] for ix in s1] else: s1 = s # assert s1[b] == j # invariant # solve d1*g*j = p_i with d1 = dx*d for some element dg # of the stabilizer of ..., p_{i-1} # dx**-1*p_i = d*g*j; dx**-1 = trace_D(d*g*j,...) # d1 = trace_D(d*g*j,...)**-1*d # to save an inversion in the inner loop; notice we did # Dxtrav = [perm_af_invert(x) for x in Dxtrav] out of the loop if Dxtrav: d1 = _trace_D(dg[j], p_i, Dxtrav) if not d1: continue else: if p_i != dg[j]: continue d1 = idn assert d1[dg[j]] == p_i # invariant d1 = [d1[ix] for ix in d] h1 = [d1[g[ix]] for ix in s1] # assert h1[b] == p_i # invariant TAB1.append((s1, d1, h1)) # if TAB contains equal permutations, keep only one of them; # if TAB contains equal permutations up to the sign, return 0 TAB1.sort(key=lambda x: x[-1]) prev = [0] * size while TAB1: s, d, h = TAB1.pop() if h[:-2] == prev[:-2]: if h[-1] != prev[-1]: return 0 else: TAB.append((s, d, h)) prev = h # stabilize the SGS sgensx = [h for h in sgensx if h[b] == b] if b in b_S: b_S.remove(b) _dumx_remove(dumx, dumx_flat, p_i) dsgsx = [] for i in range(num_types): dsgsx.extend(dummy_sgs(dumx[i], sym[i], num_dummies)) return TAB[0][-1] def canonical_free(base, gens, g, num_free): """ Canonicalization of a tensor with respect to free indices choosing the minimum with respect to lexicographical ordering in the free indices. Explanation =========== ``base``, ``gens`` BSGS for slot permutation group ``g`` permutation representing the tensor ``num_free`` number of free indices The indices must be ordered with first the free indices See explanation in double_coset_can_rep The algorithm is a variation of the one given in [2]. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.tensor_can import canonical_free >>> gens = [[1, 0, 2, 3, 5, 4], [2, 3, 0, 1, 4, 5],[0, 1, 3, 2, 5, 4]] >>> gens = [Permutation(h) for h in gens] >>> base = [0, 2] >>> g = Permutation([2, 1, 0, 3, 4, 5]) >>> canonical_free(base, gens, g, 4) [0, 3, 1, 2, 5, 4] Consider the product of Riemann tensors ``T = R^{a}_{d0}^{d1,d2}*R_{d2,d1}^{d0,b}`` The order of the indices is ``[a, b, d0, -d0, d1, -d1, d2, -d2]`` The permutation corresponding to the tensor is ``g = [0, 3, 4, 6, 7, 5, 2, 1, 8, 9]`` In particular ``a`` is position ``0``, ``b`` is in position ``9``. Use the slot symmetries to get `T` is a form which is the minimal in lexicographic order in the free indices ``a`` and ``b``, e.g. ``-R^{a}_{d0}^{d1,d2}*R^{b,d0}_{d2,d1}`` corresponding to ``[0, 3, 4, 6, 1, 2, 7, 5, 9, 8]`` >>> from sympy.combinatorics.tensor_can import riemann_bsgs, tensor_gens >>> base, gens = riemann_bsgs >>> size, sbase, sgens = tensor_gens(base, gens, [[], []], 0) >>> g = Permutation([0, 3, 4, 6, 7, 5, 2, 1, 8, 9]) >>> canonical_free(sbase, [Permutation(h) for h in sgens], g, 2) [0, 3, 4, 6, 1, 2, 7, 5, 9, 8] """ g = g.array_form size = len(g) if not base: return g[:] transversals = get_transversals(base, gens) for x in sorted(g[:-2]): if x not in base: base.append(x) h = g for i, transv in enumerate(transversals): h_i = [size]*num_free # find the element s in transversals[i] such that # _af_rmul(h, s) has its free elements with the lowest position in h s = None for sk in transv.values(): h1 = _af_rmul(h, sk) hi = [h1.index(ix) for ix in range(num_free)] if hi < h_i: h_i = hi s = sk if s: h = _af_rmul(h, s) return h def _get_map_slots(size, fixed_slots): res = list(range(size)) pos = 0 for i in range(size): if i in fixed_slots: continue res[i] = pos pos += 1 return res def _lift_sgens(size, fixed_slots, free, s): a = [] j = k = 0 fd = list(zip(fixed_slots, free)) fd = [y for x, y in sorted(fd)] num_free = len(free) for i in range(size): if i in fixed_slots: a.append(fd[k]) k += 1 else: a.append(s[j] + num_free) j += 1 return a def canonicalize(g, dummies, msym, *v): """ canonicalize tensor formed by tensors Parameters ========== g : permutation representing the tensor dummies : list representing the dummy indices it can be a list of dummy indices of the same type or a list of lists of dummy indices, one list for each type of index; the dummy indices must come after the free indices, and put in order contravariant, covariant [d0, -d0, d1,-d1,...] msym : symmetry of the metric(s) it can be an integer or a list; in the first case it is the symmetry of the dummy index metric; in the second case it is the list of the symmetries of the index metric for each type v : list, (base_i, gens_i, n_i, sym_i) for tensors of type `i` base_i, gens_i : BSGS for tensors of this type. The BSGS should have minimal base under lexicographic ordering; if not, an attempt is made do get the minimal BSGS; in case of failure, canonicalize_naive is used, which is much slower. n_i : number of tensors of type `i`. sym_i : symmetry under exchange of component tensors of type `i`. Both for msym and sym_i the cases are * None no symmetry * 0 commuting * 1 anticommuting Returns ======= 0 if the tensor is zero, else return the array form of the permutation representing the canonical form of the tensor. Algorithm ========= First one uses canonical_free to get the minimum tensor under lexicographic order, using only the slot symmetries. If the component tensors have not minimal BSGS, it is attempted to find it; if the attempt fails canonicalize_naive is used instead. Compute the residual slot symmetry keeping fixed the free indices using tensor_gens(base, gens, list_free_indices, sym). Reduce the problem eliminating the free indices. Then use double_coset_can_rep and lift back the result reintroducing the free indices. Examples ======== one type of index with commuting metric; `A_{a b}` and `B_{a b}` antisymmetric and commuting `T = A_{d0 d1} * B^{d0}{}_{d2} * B^{d2 d1}` `ord = [d0,-d0,d1,-d1,d2,-d2]` order of the indices g = [1, 3, 0, 5, 4, 2, 6, 7] `T_c = 0` >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, canonicalize, bsgs_direct_product >>> from sympy.combinatorics import Permutation >>> base2a, gens2a = get_symmetric_group_sgs(2, 1) >>> t0 = (base2a, gens2a, 1, 0) >>> t1 = (base2a, gens2a, 2, 0) >>> g = Permutation([1, 3, 0, 5, 4, 2, 6, 7]) >>> canonicalize(g, range(6), 0, t0, t1) 0 same as above, but with `B_{a b}` anticommuting `T_c = -A^{d0 d1} * B_{d0}{}^{d2} * B_{d1 d2}` can = [0,2,1,4,3,5,7,6] >>> t1 = (base2a, gens2a, 2, 1) >>> canonicalize(g, range(6), 0, t0, t1) [0, 2, 1, 4, 3, 5, 7, 6] two types of indices `[a,b,c,d,e,f]` and `[m,n]`, in this order, both with commuting metric `f^{a b c}` antisymmetric, commuting `A_{m a}` no symmetry, commuting `T = f^c{}_{d a} * f^f{}_{e b} * A_m{}^d * A^{m b} * A_n{}^a * A^{n e}` ord = [c,f,a,-a,b,-b,d,-d,e,-e,m,-m,n,-n] g = [0,7,3, 1,9,5, 11,6, 10,4, 13,2, 12,8, 14,15] The canonical tensor is `T_c = -f^{c a b} * f^{f d e} * A^m{}_a * A_{m d} * A^n{}_b * A_{n e}` can = [0,2,4, 1,6,8, 10,3, 11,7, 12,5, 13,9, 15,14] >>> base_f, gens_f = get_symmetric_group_sgs(3, 1) >>> base1, gens1 = get_symmetric_group_sgs(1) >>> base_A, gens_A = bsgs_direct_product(base1, gens1, base1, gens1) >>> t0 = (base_f, gens_f, 2, 0) >>> t1 = (base_A, gens_A, 4, 0) >>> dummies = [range(2, 10), range(10, 14)] >>> g = Permutation([0, 7, 3, 1, 9, 5, 11, 6, 10, 4, 13, 2, 12, 8, 14, 15]) >>> canonicalize(g, dummies, [0, 0], t0, t1) [0, 2, 4, 1, 6, 8, 10, 3, 11, 7, 12, 5, 13, 9, 15, 14] """ from sympy.combinatorics.testutil import canonicalize_naive if not isinstance(msym, list): if msym not in (0, 1, None): raise ValueError('msym must be 0, 1 or None') num_types = 1 else: num_types = len(msym) if not all(msymx in (0, 1, None) for msymx in msym): raise ValueError('msym entries must be 0, 1 or None') if len(dummies) != num_types: raise ValueError( 'dummies and msym must have the same number of elements') size = g.size num_tensors = 0 v1 = [] for i in range(len(v)): base_i, gens_i, n_i, sym_i = v[i] # check that the BSGS is minimal; # this property is used in double_coset_can_rep; # if it is not minimal use canonicalize_naive if not _is_minimal_bsgs(base_i, gens_i): mbsgs = get_minimal_bsgs(base_i, gens_i) if not mbsgs: can = canonicalize_naive(g, dummies, msym, *v) return can base_i, gens_i = mbsgs v1.append((base_i, gens_i, [[]] * n_i, sym_i)) num_tensors += n_i if num_types == 1 and not isinstance(msym, list): dummies = [dummies] msym = [msym] flat_dummies = [] for dumx in dummies: flat_dummies.extend(dumx) if flat_dummies and flat_dummies != list(range(flat_dummies[0], flat_dummies[-1] + 1)): raise ValueError('dummies is not valid') # slot symmetry of the tensor size1, sbase, sgens = gens_products(*v1) if size != size1: raise ValueError( 'g has size %d, generators have size %d' % (size, size1)) free = [i for i in range(size - 2) if i not in flat_dummies] num_free = len(free) # g1 minimal tensor under slot symmetry g1 = canonical_free(sbase, sgens, g, num_free) if not flat_dummies: return g1 # save the sign of g1 sign = 0 if g1[-1] == size - 1 else 1 # the free indices are kept fixed. # Determine free_i, the list of slots of tensors which are fixed # since they are occupied by free indices, which are fixed. start = 0 for i in range(len(v)): free_i = [] base_i, gens_i, n_i, sym_i = v[i] len_tens = gens_i[0].size - 2 # for each component tensor get a list od fixed islots for j in range(n_i): # get the elements corresponding to the component tensor h = g1[start:(start + len_tens)] fr = [] # get the positions of the fixed elements in h for k in free: if k in h: fr.append(h.index(k)) free_i.append(fr) start += len_tens v1[i] = (base_i, gens_i, free_i, sym_i) # BSGS of the tensor with fixed free indices # if tensor_gens fails in gens_product, use canonicalize_naive size, sbase, sgens = gens_products(*v1) # reduce the permutations getting rid of the free indices pos_free = [g1.index(x) for x in range(num_free)] size_red = size - num_free g1_red = [x - num_free for x in g1 if x in flat_dummies] if sign: g1_red.extend([size_red - 1, size_red - 2]) else: g1_red.extend([size_red - 2, size_red - 1]) map_slots = _get_map_slots(size, pos_free) sbase_red = [map_slots[i] for i in sbase if i not in pos_free] sgens_red = [_af_new([map_slots[i] for i in y._array_form if i not in pos_free]) for y in sgens] dummies_red = [[x - num_free for x in y] for y in dummies] transv_red = get_transversals(sbase_red, sgens_red) g1_red = _af_new(g1_red) g2 = double_coset_can_rep( dummies_red, msym, sbase_red, sgens_red, transv_red, g1_red) if g2 == 0: return 0 # lift to the case with the free indices g3 = _lift_sgens(size, pos_free, free, g2) return g3 def perm_af_direct_product(gens1, gens2, signed=True): """ Direct products of the generators gens1 and gens2. Examples ======== >>> from sympy.combinatorics.tensor_can import perm_af_direct_product >>> gens1 = [[1, 0, 2, 3], [0, 1, 3, 2]] >>> gens2 = [[1, 0]] >>> perm_af_direct_product(gens1, gens2, False) [[1, 0, 2, 3, 4, 5], [0, 1, 3, 2, 4, 5], [0, 1, 2, 3, 5, 4]] >>> gens1 = [[1, 0, 2, 3, 5, 4], [0, 1, 3, 2, 4, 5]] >>> gens2 = [[1, 0, 2, 3]] >>> perm_af_direct_product(gens1, gens2, True) [[1, 0, 2, 3, 4, 5, 7, 6], [0, 1, 3, 2, 4, 5, 6, 7], [0, 1, 2, 3, 5, 4, 6, 7]] """ gens1 = [list(x) for x in gens1] gens2 = [list(x) for x in gens2] s = 2 if signed else 0 n1 = len(gens1[0]) - s n2 = len(gens2[0]) - s start = list(range(n1)) end = list(range(n1, n1 + n2)) if signed: gens1 = [gen[:-2] + end + [gen[-2] + n2, gen[-1] + n2] for gen in gens1] gens2 = [start + [x + n1 for x in gen] for gen in gens2] else: gens1 = [gen + end for gen in gens1] gens2 = [start + [x + n1 for x in gen] for gen in gens2] res = gens1 + gens2 return res def bsgs_direct_product(base1, gens1, base2, gens2, signed=True): """ Direct product of two BSGS. Parameters ========== base1 : base of the first BSGS. gens1 : strong generating sequence of the first BSGS. base2, gens2 : similarly for the second BSGS. signed : flag for signed permutations. Examples ======== >>> from sympy.combinatorics.tensor_can import (get_symmetric_group_sgs, bsgs_direct_product) >>> base1, gens1 = get_symmetric_group_sgs(1) >>> base2, gens2 = get_symmetric_group_sgs(2) >>> bsgs_direct_product(base1, gens1, base2, gens2) ([1], [(4)(1 2)]) """ s = 2 if signed else 0 n1 = gens1[0].size - s base = list(base1) base += [x + n1 for x in base2] gens1 = [h._array_form for h in gens1] gens2 = [h._array_form for h in gens2] gens = perm_af_direct_product(gens1, gens2, signed) size = len(gens[0]) id_af = list(range(size)) gens = [h for h in gens if h != id_af] if not gens: gens = [id_af] return base, [_af_new(h) for h in gens] def get_symmetric_group_sgs(n, antisym=False): """ Return base, gens of the minimal BSGS for (anti)symmetric tensor Parameters ========== ``n``: rank of the tensor ``antisym`` : bool ``antisym = False`` symmetric tensor ``antisym = True`` antisymmetric tensor Examples ======== >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs >>> get_symmetric_group_sgs(3) ([0, 1], [(4)(0 1), (4)(1 2)]) """ if n == 1: return [], [_af_new(list(range(3)))] gens = [Permutation(n - 1)(i, i + 1)._array_form for i in range(n - 1)] if antisym == 0: gens = [x + [n, n + 1] for x in gens] else: gens = [x + [n + 1, n] for x in gens] base = list(range(n - 1)) return base, [_af_new(h) for h in gens] riemann_bsgs = [0, 2], [Permutation(0, 1)(4, 5), Permutation(2, 3)(4, 5), Permutation(5)(0, 2)(1, 3)] def get_transversals(base, gens): """ Return transversals for the group with BSGS base, gens """ if not base: return [] stabs = _distribute_gens_by_base(base, gens) orbits, transversals = _orbits_transversals_from_bsgs(base, stabs) transversals = [{x: h._array_form for x, h in y.items()} for y in transversals] return transversals def _is_minimal_bsgs(base, gens): """ Check if the BSGS has minimal base under lexigographic order. base, gens BSGS Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.tensor_can import riemann_bsgs, _is_minimal_bsgs >>> _is_minimal_bsgs(*riemann_bsgs) True >>> riemann_bsgs1 = ([2, 0], ([Permutation(5)(0, 1)(4, 5), Permutation(5)(0, 2)(1, 3)])) >>> _is_minimal_bsgs(*riemann_bsgs1) False """ base1 = [] sgs1 = gens[:] size = gens[0].size for i in range(size): if not all(h._array_form[i] == i for h in sgs1): base1.append(i) sgs1 = [h for h in sgs1 if h._array_form[i] == i] return base1 == base def get_minimal_bsgs(base, gens): """ Compute a minimal GSGS base, gens BSGS If base, gens is a minimal BSGS return it; else return a minimal BSGS if it fails in finding one, it returns None TODO: use baseswap in the case in which if it fails in finding a minimal BSGS Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.tensor_can import get_minimal_bsgs >>> riemann_bsgs1 = ([2, 0], ([Permutation(5)(0, 1)(4, 5), Permutation(5)(0, 2)(1, 3)])) >>> get_minimal_bsgs(*riemann_bsgs1) ([0, 2], [(0 1)(4 5), (5)(0 2)(1 3), (2 3)(4 5)]) """ G = PermutationGroup(gens) base, gens = G.schreier_sims_incremental() if not _is_minimal_bsgs(base, gens): return None return base, gens def tensor_gens(base, gens, list_free_indices, sym=0): """ Returns size, res_base, res_gens BSGS for n tensors of the same type. Explanation =========== base, gens BSGS for tensors of this type list_free_indices list of the slots occupied by fixed indices for each of the tensors sym symmetry under commutation of two tensors sym None no symmetry sym 0 commuting sym 1 anticommuting Examples ======== >>> from sympy.combinatorics.tensor_can import tensor_gens, get_symmetric_group_sgs two symmetric tensors with 3 indices without free indices >>> base, gens = get_symmetric_group_sgs(3) >>> tensor_gens(base, gens, [[], []]) (8, [0, 1, 3, 4], [(7)(0 1), (7)(1 2), (7)(3 4), (7)(4 5), (7)(0 3)(1 4)(2 5)]) two symmetric tensors with 3 indices with free indices in slot 1 and 0 >>> tensor_gens(base, gens, [[1], [0]]) (8, [0, 4], [(7)(0 2), (7)(4 5)]) four symmetric tensors with 3 indices, two of which with free indices """ def _get_bsgs(G, base, gens, free_indices): """ return the BSGS for G.pointwise_stabilizer(free_indices) """ if not free_indices: return base[:], gens[:] else: H = G.pointwise_stabilizer(free_indices) base, sgs = H.schreier_sims_incremental() return base, sgs # if not base there is no slot symmetry for the component tensors # if list_free_indices.count([]) < 2 there is no commutation symmetry # so there is no resulting slot symmetry if not base and list_free_indices.count([]) < 2: n = len(list_free_indices) size = gens[0].size size = n * (size - 2) + 2 return size, [], [_af_new(list(range(size)))] # if any(list_free_indices) one needs to compute the pointwise # stabilizer, so G is needed if any(list_free_indices): G = PermutationGroup(gens) else: G = None # no_free list of lists of indices for component tensors without fixed # indices no_free = [] size = gens[0].size id_af = list(range(size)) num_indices = size - 2 if not list_free_indices[0]: no_free.append(list(range(num_indices))) res_base, res_gens = _get_bsgs(G, base, gens, list_free_indices[0]) for i in range(1, len(list_free_indices)): base1, gens1 = _get_bsgs(G, base, gens, list_free_indices[i]) res_base, res_gens = bsgs_direct_product(res_base, res_gens, base1, gens1, 1) if not list_free_indices[i]: no_free.append(list(range(size - 2, size - 2 + num_indices))) size += num_indices nr = size - 2 res_gens = [h for h in res_gens if h._array_form != id_af] # if sym there are no commuting tensors stop here if sym is None or not no_free: if not res_gens: res_gens = [_af_new(id_af)] return size, res_base, res_gens # if the component tensors have moinimal BSGS, so is their direct # product P; the slot symmetry group is S = P*C, where C is the group # to (anti)commute the component tensors with no free indices # a stabilizer has the property S_i = P_i*C_i; # the BSGS of P*C has SGS_P + SGS_C and the base is # the ordered union of the bases of P and C. # If P has minimal BSGS, so has S with this base. base_comm = [] for i in range(len(no_free) - 1): ind1 = no_free[i] ind2 = no_free[i + 1] a = list(range(ind1[0])) a.extend(ind2) a.extend(ind1) base_comm.append(ind1[0]) a.extend(list(range(ind2[-1] + 1, nr))) if sym == 0: a.extend([nr, nr + 1]) else: a.extend([nr + 1, nr]) res_gens.append(_af_new(a)) res_base = list(res_base) # each base is ordered; order the union of the two bases for i in base_comm: if i not in res_base: res_base.append(i) res_base.sort() if not res_gens: res_gens = [_af_new(id_af)] return size, res_base, res_gens def gens_products(*v): """ Returns size, res_base, res_gens BSGS for n tensors of different types. Explanation =========== v is a sequence of (base_i, gens_i, free_i, sym_i) where base_i, gens_i BSGS of tensor of type `i` free_i list of the fixed slots for each of the tensors of type `i`; if there are `n_i` tensors of type `i` and none of them have fixed slots, `free = [[]]*n_i` sym 0 (1) if the tensors of type `i` (anti)commute among themselves Examples ======== >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, gens_products >>> base, gens = get_symmetric_group_sgs(2) >>> gens_products((base, gens, [[], []], 0)) (6, [0, 2], [(5)(0 1), (5)(2 3), (5)(0 2)(1 3)]) >>> gens_products((base, gens, [[1], []], 0)) (6, [2], [(5)(2 3)]) """ res_size, res_base, res_gens = tensor_gens(*v[0]) for i in range(1, len(v)): size, base, gens = tensor_gens(*v[i]) res_base, res_gens = bsgs_direct_product(res_base, res_gens, base, gens, 1) res_size = res_gens[0].size id_af = list(range(res_size)) res_gens = [h for h in res_gens if h != id_af] if not res_gens: res_gens = [id_af] return res_size, res_base, res_gens
5dcfb746b81dfb413e0bc1a79af1dd01c73ff7a51099924eb07dbdc223ce02a0
from sympy.ntheory.primetest import isprime from sympy.combinatorics.perm_groups import PermutationGroup from sympy.printing.defaults import DefaultPrinting from sympy.combinatorics.free_groups import free_group class PolycyclicGroup(DefaultPrinting): is_group = True is_solvable = True def __init__(self, pc_sequence, pc_series, relative_order, collector=None): """ Parameters ========== pc_sequence : list A sequence of elements whose classes generate the cyclic factor groups of pc_series. pc_series : list A subnormal sequence of subgroups where each factor group is cyclic. relative_order : list The orders of factor groups of pc_series. collector : Collector By default, it is None. Collector class provides the polycyclic presentation with various other functionalities. """ self.pcgs = pc_sequence self.pc_series = pc_series self.relative_order = relative_order self.collector = Collector(self.pcgs, pc_series, relative_order) if not collector else collector def is_prime_order(self): return all(isprime(order) for order in self.relative_order) def length(self): return len(self.pcgs) class Collector(DefaultPrinting): """ References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" Section 8.1.3 """ def __init__(self, pcgs, pc_series, relative_order, free_group_=None, pc_presentation=None): """ Most of the parameters for the Collector class are the same as for PolycyclicGroup. Others are described below. Parameters ========== free_group_ : tuple free_group_ provides the mapping of polycyclic generating sequence with the free group elements. pc_presentation : dict Provides the presentation of polycyclic groups with the help of power and conjugate relators. See Also ======== PolycyclicGroup """ self.pcgs = pcgs self.pc_series = pc_series self.relative_order = relative_order self.free_group = free_group('x:{}'.format(len(pcgs)))[0] if not free_group_ else free_group_ self.index = {s: i for i, s in enumerate(self.free_group.symbols)} self.pc_presentation = self.pc_relators() def minimal_uncollected_subword(self, word): r""" Returns the minimal uncollected subwords. Explanation =========== A word ``v`` defined on generators in ``X`` is a minimal uncollected subword of the word ``w`` if ``v`` is a subword of ``w`` and it has one of the following form * `v = {x_{i+1}}^{a_j}x_i` * `v = {x_{i+1}}^{a_j}{x_i}^{-1}` * `v = {x_i}^{a_j}` for `a_j` not in `\{1, \ldots, s-1\}`. Where, ``s`` is the power exponent of the corresponding generator. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.free_groups import free_group >>> G = SymmetricGroup(4) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> F, x1, x2 = free_group("x1, x2") >>> word = x2**2*x1**7 >>> collector.minimal_uncollected_subword(word) ((x2, 2),) """ # To handle the case word = <identity> if not word: return None array = word.array_form re = self.relative_order index = self.index for i in range(len(array)): s1, e1 = array[i] if re[index[s1]] and (e1 < 0 or e1 > re[index[s1]]-1): return ((s1, e1), ) for i in range(len(array)-1): s1, e1 = array[i] s2, e2 = array[i+1] if index[s1] > index[s2]: e = 1 if e2 > 0 else -1 return ((s1, e1), (s2, e)) return None def relations(self): """ Separates the given relators of pc presentation in power and conjugate relations. Returns ======= (power_rel, conj_rel) Separates pc presentation into power and conjugate relations. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> G = SymmetricGroup(3) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> power_rel, conj_rel = collector.relations() >>> power_rel {x0**2: (), x1**3: ()} >>> conj_rel {x0**-1*x1*x0: x1**2} See Also ======== pc_relators """ power_relators = {} conjugate_relators = {} for key, value in self.pc_presentation.items(): if len(key.array_form) == 1: power_relators[key] = value else: conjugate_relators[key] = value return power_relators, conjugate_relators def subword_index(self, word, w): """ Returns the start and ending index of a given subword in a word. Parameters ========== word : FreeGroupElement word defined on free group elements for a polycyclic group. w : FreeGroupElement subword of a given word, whose starting and ending index to be computed. Returns ======= (i, j) A tuple containing starting and ending index of ``w`` in the given word. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.free_groups import free_group >>> G = SymmetricGroup(4) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> F, x1, x2 = free_group("x1, x2") >>> word = x2**2*x1**7 >>> w = x2**2*x1 >>> collector.subword_index(word, w) (0, 3) >>> w = x1**7 >>> collector.subword_index(word, w) (2, 9) """ low = -1 high = -1 for i in range(len(word)-len(w)+1): if word.subword(i, i+len(w)) == w: low = i high = i+len(w) break if low == high == -1: return -1, -1 return low, high def map_relation(self, w): """ Return a conjugate relation. Explanation =========== Given a word formed by two free group elements, the corresponding conjugate relation with those free group elements is formed and mapped with the collected word in the polycyclic presentation. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.free_groups import free_group >>> G = SymmetricGroup(3) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> F, x0, x1 = free_group("x0, x1") >>> w = x1*x0 >>> collector.map_relation(w) x1**2 See Also ======== pc_presentation """ array = w.array_form s1 = array[0][0] s2 = array[1][0] key = ((s2, -1), (s1, 1), (s2, 1)) key = self.free_group.dtype(key) return self.pc_presentation[key] def collected_word(self, word): r""" Return the collected form of a word. Explanation =========== A word ``w`` is called collected, if `w = {x_{i_1}}^{a_1} * \ldots * {x_{i_r}}^{a_r}` with `i_1 < i_2< \ldots < i_r` and `a_j` is in `\{1, \ldots, {s_j}-1\}`. Otherwise w is uncollected. Parameters ========== word : FreeGroupElement An uncollected word. Returns ======= word A collected word of form `w = {x_{i_1}}^{a_1}, \ldots, {x_{i_r}}^{a_r}` with `i_1, i_2, \ldots, i_r` and `a_j \in \{1, \ldots, {s_j}-1\}`. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.free_groups import free_group >>> G = SymmetricGroup(4) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> F, x0, x1, x2, x3 = free_group("x0, x1, x2, x3") >>> word = x3*x2*x1*x0 >>> collected_word = collector.collected_word(word) >>> free_to_perm = {} >>> free_group = collector.free_group >>> for sym, gen in zip(free_group.symbols, collector.pcgs): ... free_to_perm[sym] = gen >>> G1 = PermutationGroup() >>> for w in word: ... sym = w[0] ... perm = free_to_perm[sym] ... G1 = PermutationGroup([perm] + G1.generators) >>> G2 = PermutationGroup() >>> for w in collected_word: ... sym = w[0] ... perm = free_to_perm[sym] ... G2 = PermutationGroup([perm] + G2.generators) The two are not identical, but they are equivalent: >>> G1.equals(G2), G1 == G2 (True, False) See Also ======== minimal_uncollected_subword """ free_group = self.free_group while True: w = self.minimal_uncollected_subword(word) if not w: break low, high = self.subword_index(word, free_group.dtype(w)) if low == -1: continue s1, e1 = w[0] if len(w) == 1: re = self.relative_order[self.index[s1]] q = e1 // re r = e1-q*re key = ((w[0][0], re), ) key = free_group.dtype(key) if self.pc_presentation[key]: presentation = self.pc_presentation[key].array_form sym, exp = presentation[0] word_ = ((w[0][0], r), (sym, q*exp)) word_ = free_group.dtype(word_) else: if r != 0: word_ = ((w[0][0], r), ) word_ = free_group.dtype(word_) else: word_ = None word = word.eliminate_word(free_group.dtype(w), word_) if len(w) == 2 and w[1][1] > 0: s2, e2 = w[1] s2 = ((s2, 1), ) s2 = free_group.dtype(s2) word_ = self.map_relation(free_group.dtype(w)) word_ = s2*word_**e1 word_ = free_group.dtype(word_) word = word.substituted_word(low, high, word_) elif len(w) == 2 and w[1][1] < 0: s2, e2 = w[1] s2 = ((s2, 1), ) s2 = free_group.dtype(s2) word_ = self.map_relation(free_group.dtype(w)) word_ = s2**-1*word_**e1 word_ = free_group.dtype(word_) word = word.substituted_word(low, high, word_) return word def pc_relators(self): r""" Return the polycyclic presentation. Explanation =========== There are two types of relations used in polycyclic presentation. * ``Power relations`` : Power relators are of the form `x_i^{re_i}`, where `i \in \{0, \ldots, \mathrm{len(pcgs)}\}`, ``x`` represents polycyclic generator and ``re`` is the corresponding relative order. * ``Conjugate relations`` : Conjugate relators are of the form `x_j^-1x_ix_j`, where `j < i \in \{0, \ldots, \mathrm{len(pcgs)}\}`. Returns ======= A dictionary with power and conjugate relations as key and their collected form as corresponding values. Notes ===== Identity Permutation is mapped with empty ``()``. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.permutations import Permutation >>> S = SymmetricGroup(49).sylow_subgroup(7) >>> der = S.derived_series() >>> G = der[len(der)-2] >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> pcgs = PcGroup.pcgs >>> len(pcgs) 6 >>> free_group = collector.free_group >>> pc_resentation = collector.pc_presentation >>> free_to_perm = {} >>> for s, g in zip(free_group.symbols, pcgs): ... free_to_perm[s] = g >>> for k, v in pc_resentation.items(): ... k_array = k.array_form ... if v != (): ... v_array = v.array_form ... lhs = Permutation() ... for gen in k_array: ... s = gen[0] ... e = gen[1] ... lhs = lhs*free_to_perm[s]**e ... if v == (): ... assert lhs.is_identity ... continue ... rhs = Permutation() ... for gen in v_array: ... s = gen[0] ... e = gen[1] ... rhs = rhs*free_to_perm[s]**e ... assert lhs == rhs """ free_group = self.free_group rel_order = self.relative_order pc_relators = {} perm_to_free = {} pcgs = self.pcgs for gen, s in zip(pcgs, free_group.generators): perm_to_free[gen**-1] = s**-1 perm_to_free[gen] = s pcgs = pcgs[::-1] series = self.pc_series[::-1] rel_order = rel_order[::-1] collected_gens = [] for i, gen in enumerate(pcgs): re = rel_order[i] relation = perm_to_free[gen]**re G = series[i] l = G.generator_product(gen**re, original = True) l.reverse() word = free_group.identity for g in l: word = word*perm_to_free[g] word = self.collected_word(word) pc_relators[relation] = word if word else () self.pc_presentation = pc_relators collected_gens.append(gen) if len(collected_gens) > 1: conj = collected_gens[len(collected_gens)-1] conjugator = perm_to_free[conj] for j in range(len(collected_gens)-1): conjugated = perm_to_free[collected_gens[j]] relation = conjugator**-1*conjugated*conjugator gens = conj**-1*collected_gens[j]*conj l = G.generator_product(gens, original = True) l.reverse() word = free_group.identity for g in l: word = word*perm_to_free[g] word = self.collected_word(word) pc_relators[relation] = word if word else () self.pc_presentation = pc_relators return pc_relators def exponent_vector(self, element): r""" Return the exponent vector of length equal to the length of polycyclic generating sequence. Explanation =========== For a given generator/element ``g`` of the polycyclic group, it can be represented as `g = {x_1}^{e_1}, \ldots, {x_n}^{e_n}`, where `x_i` represents polycyclic generators and ``n`` is the number of generators in the free_group equal to the length of pcgs. Parameters ========== element : Permutation Generator of a polycyclic group. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.permutations import Permutation >>> G = SymmetricGroup(4) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> pcgs = PcGroup.pcgs >>> collector.exponent_vector(G[0]) [1, 0, 0, 0] >>> exp = collector.exponent_vector(G[1]) >>> g = Permutation() >>> for i in range(len(exp)): ... g = g*pcgs[i]**exp[i] if exp[i] else g >>> assert g == G[1] References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" Section 8.1.1, Definition 8.4 """ free_group = self.free_group G = PermutationGroup() for g in self.pcgs: G = PermutationGroup([g] + G.generators) gens = G.generator_product(element, original = True) gens.reverse() perm_to_free = {} for sym, g in zip(free_group.generators, self.pcgs): perm_to_free[g**-1] = sym**-1 perm_to_free[g] = sym w = free_group.identity for g in gens: w = w*perm_to_free[g] word = self.collected_word(w) index = self.index exp_vector = [0]*len(free_group) word = word.array_form for t in word: exp_vector[index[t[0]]] = t[1] return exp_vector def depth(self, element): r""" Return the depth of a given element. Explanation =========== The depth of a given element ``g`` is defined by `\mathrm{dep}[g] = i` if `e_1 = e_2 = \ldots = e_{i-1} = 0` and `e_i != 0`, where ``e`` represents the exponent-vector. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> G = SymmetricGroup(3) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> collector.depth(G[0]) 2 >>> collector.depth(G[1]) 1 References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" Section 8.1.1, Definition 8.5 """ exp_vector = self.exponent_vector(element) return next((i+1 for i, x in enumerate(exp_vector) if x), len(self.pcgs)+1) def leading_exponent(self, element): r""" Return the leading non-zero exponent. Explanation =========== The leading exponent for a given element `g` is defined by `\mathrm{leading\_exponent}[g]` `= e_i`, if `\mathrm{depth}[g] = i`. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> G = SymmetricGroup(3) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> collector.leading_exponent(G[1]) 1 """ exp_vector = self.exponent_vector(element) depth = self.depth(element) if depth != len(self.pcgs)+1: return exp_vector[depth-1] return None def _sift(self, z, g): h = g d = self.depth(h) while d < len(self.pcgs) and z[d-1] != 1: k = z[d-1] e = self.leading_exponent(h)*(self.leading_exponent(k))**-1 e = e % self.relative_order[d-1] h = k**-e*h d = self.depth(h) return h def induced_pcgs(self, gens): """ Parameters ========== gens : list A list of generators on which polycyclic subgroup is to be defined. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(8) >>> G = S.sylow_subgroup(2) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> gens = [G[0], G[1]] >>> ipcgs = collector.induced_pcgs(gens) >>> [gen.order() for gen in ipcgs] [2, 2, 2] >>> G = S.sylow_subgroup(3) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> gens = [G[0], G[1]] >>> ipcgs = collector.induced_pcgs(gens) >>> [gen.order() for gen in ipcgs] [3] """ z = [1]*len(self.pcgs) G = gens while G: g = G.pop(0) h = self._sift(z, g) d = self.depth(h) if d < len(self.pcgs): for gen in z: if gen != 1: G.append(h**-1*gen**-1*h*gen) z[d-1] = h; z = [gen for gen in z if gen != 1] return z def constructive_membership_test(self, ipcgs, g): """ Return the exponent vector for induced pcgs. """ e = [0]*len(ipcgs) h = g d = self.depth(h) for i, gen in enumerate(ipcgs): while self.depth(gen) == d: f = self.leading_exponent(h)*self.leading_exponent(gen) f = f % self.relative_order[d-1] h = gen**(-f)*h e[i] = f d = self.depth(h) if h == 1: return e return False
183e339fa7341d569b0b03c70c422d643d7d9965b43ef49f6029a81b10783ba2
import itertools from sympy.combinatorics.fp_groups import FpGroup, FpSubgroup, simplify_presentation from sympy.combinatorics.free_groups import FreeGroup from sympy.combinatorics.perm_groups import PermutationGroup from sympy.core.numbers import igcd from sympy.ntheory.factor_ import totient from sympy.core.singleton import S class GroupHomomorphism: ''' A class representing group homomorphisms. Instantiate using `homomorphism()`. References ========== .. [1] Holt, D., Eick, B. and O'Brien, E. (2005). Handbook of computational group theory. ''' def __init__(self, domain, codomain, images): self.domain = domain self.codomain = codomain self.images = images self._inverses = None self._kernel = None self._image = None def _invs(self): ''' Return a dictionary with `{gen: inverse}` where `gen` is a rewriting generator of `codomain` (e.g. strong generator for permutation groups) and `inverse` is an element of its preimage ''' image = self.image() inverses = {} for k in list(self.images.keys()): v = self.images[k] if not (v in inverses or v.is_identity): inverses[v] = k if isinstance(self.codomain, PermutationGroup): gens = image.strong_gens else: gens = image.generators for g in gens: if g in inverses or g.is_identity: continue w = self.domain.identity if isinstance(self.codomain, PermutationGroup): parts = image._strong_gens_slp[g][::-1] else: parts = g for s in parts: if s in inverses: w = w*inverses[s] else: w = w*inverses[s**-1]**-1 inverses[g] = w return inverses def invert(self, g): ''' Return an element of the preimage of ``g`` or of each element of ``g`` if ``g`` is a list. Explanation =========== If the codomain is an FpGroup, the inverse for equal elements might not always be the same unless the FpGroup's rewriting system is confluent. However, making a system confluent can be time-consuming. If it's important, try `self.codomain.make_confluent()` first. ''' from sympy.combinatorics import Permutation from sympy.combinatorics.free_groups import FreeGroupElement if isinstance(g, (Permutation, FreeGroupElement)): if isinstance(self.codomain, FpGroup): g = self.codomain.reduce(g) if self._inverses is None: self._inverses = self._invs() image = self.image() w = self.domain.identity if isinstance(self.codomain, PermutationGroup): gens = image.generator_product(g)[::-1] else: gens = g # the following can't be "for s in gens:" # because that would be equivalent to # "for s in gens.array_form:" when g is # a FreeGroupElement. On the other hand, # when you call gens by index, the generator # (or inverse) at position i is returned. for i in range(len(gens)): s = gens[i] if s.is_identity: continue if s in self._inverses: w = w*self._inverses[s] else: w = w*self._inverses[s**-1]**-1 return w elif isinstance(g, list): return [self.invert(e) for e in g] def kernel(self): ''' Compute the kernel of `self`. ''' if self._kernel is None: self._kernel = self._compute_kernel() return self._kernel def _compute_kernel(self): G = self.domain G_order = G.order() if G_order is S.Infinity: raise NotImplementedError( "Kernel computation is not implemented for infinite groups") gens = [] if isinstance(G, PermutationGroup): K = PermutationGroup(G.identity) else: K = FpSubgroup(G, gens, normal=True) i = self.image().order() while K.order()*i != G_order: r = G.random() k = r*self.invert(self(r))**-1 if k not in K: gens.append(k) if isinstance(G, PermutationGroup): K = PermutationGroup(gens) else: K = FpSubgroup(G, gens, normal=True) return K def image(self): ''' Compute the image of `self`. ''' if self._image is None: values = list(set(self.images.values())) if isinstance(self.codomain, PermutationGroup): self._image = self.codomain.subgroup(values) else: self._image = FpSubgroup(self.codomain, values) return self._image def _apply(self, elem): ''' Apply `self` to `elem`. ''' if elem not in self.domain: if isinstance(elem, (list, tuple)): return [self._apply(e) for e in elem] raise ValueError("The supplied element doesn't belong to the domain") if elem.is_identity: return self.codomain.identity else: images = self.images value = self.codomain.identity if isinstance(self.domain, PermutationGroup): gens = self.domain.generator_product(elem, original=True) for g in gens: if g in self.images: value = images[g]*value else: value = images[g**-1]**-1*value else: i = 0 for _, p in elem.array_form: if p < 0: g = elem[i]**-1 else: g = elem[i] value = value*images[g]**p i += abs(p) return value def __call__(self, elem): return self._apply(elem) def is_injective(self): ''' Check if the homomorphism is injective ''' return self.kernel().order() == 1 def is_surjective(self): ''' Check if the homomorphism is surjective ''' im = self.image().order() oth = self.codomain.order() if im is S.Infinity and oth is S.Infinity: return None else: return im == oth def is_isomorphism(self): ''' Check if `self` is an isomorphism. ''' return self.is_injective() and self.is_surjective() def is_trivial(self): ''' Check is `self` is a trivial homomorphism, i.e. all elements are mapped to the identity. ''' return self.image().order() == 1 def compose(self, other): ''' Return the composition of `self` and `other`, i.e. the homomorphism phi such that for all g in the domain of `other`, phi(g) = self(other(g)) ''' if not other.image().is_subgroup(self.domain): raise ValueError("The image of `other` must be a subgroup of " "the domain of `self`") images = {g: self(other(g)) for g in other.images} return GroupHomomorphism(other.domain, self.codomain, images) def restrict_to(self, H): ''' Return the restriction of the homomorphism to the subgroup `H` of the domain. ''' if not isinstance(H, PermutationGroup) or not H.is_subgroup(self.domain): raise ValueError("Given H is not a subgroup of the domain") domain = H images = {g: self(g) for g in H.generators} return GroupHomomorphism(domain, self.codomain, images) def invert_subgroup(self, H): ''' Return the subgroup of the domain that is the inverse image of the subgroup ``H`` of the homomorphism image ''' if not H.is_subgroup(self.image()): raise ValueError("Given H is not a subgroup of the image") gens = [] P = PermutationGroup(self.image().identity) for h in H.generators: h_i = self.invert(h) if h_i not in P: gens.append(h_i) P = PermutationGroup(gens) for k in self.kernel().generators: if k*h_i not in P: gens.append(k*h_i) P = PermutationGroup(gens) return P def homomorphism(domain, codomain, gens, images=(), check=True): ''' Create (if possible) a group homomorphism from the group ``domain`` to the group ``codomain`` defined by the images of the domain's generators ``gens``. ``gens`` and ``images`` can be either lists or tuples of equal sizes. If ``gens`` is a proper subset of the group's generators, the unspecified generators will be mapped to the identity. If the images are not specified, a trivial homomorphism will be created. If the given images of the generators do not define a homomorphism, an exception is raised. If ``check`` is ``False``, do not check whether the given images actually define a homomorphism. ''' if not isinstance(domain, (PermutationGroup, FpGroup, FreeGroup)): raise TypeError("The domain must be a group") if not isinstance(codomain, (PermutationGroup, FpGroup, FreeGroup)): raise TypeError("The codomain must be a group") generators = domain.generators if not all(g in generators for g in gens): raise ValueError("The supplied generators must be a subset of the domain's generators") if not all(g in codomain for g in images): raise ValueError("The images must be elements of the codomain") if images and len(images) != len(gens): raise ValueError("The number of images must be equal to the number of generators") gens = list(gens) images = list(images) images.extend([codomain.identity]*(len(generators)-len(images))) gens.extend([g for g in generators if g not in gens]) images = dict(zip(gens,images)) if check and not _check_homomorphism(domain, codomain, images): raise ValueError("The given images do not define a homomorphism") return GroupHomomorphism(domain, codomain, images) def _check_homomorphism(domain, codomain, images): if hasattr(domain, 'relators'): rels = domain.relators else: gens = domain.presentation().generators rels = domain.presentation().relators identity = codomain.identity def _image(r): if r.is_identity: return identity else: w = identity r_arr = r.array_form i = 0 j = 0 # i is the index for r and j is for # r_arr. r_arr[j] is the tuple (sym, p) # where sym is the generator symbol # and p is the power to which it is # raised while r[i] is a generator # (not just its symbol) or the inverse of # a generator - hence the need for # both indices while i < len(r): power = r_arr[j][1] if isinstance(domain, PermutationGroup) and r[i] in gens: s = domain.generators[gens.index(r[i])] else: s = r[i] if s in images: w = w*images[s]**power elif s**-1 in images: w = w*images[s**-1]**power i += abs(power) j += 1 return w for r in rels: if isinstance(codomain, FpGroup): s = codomain.equals(_image(r), identity) if s is None: # only try to make the rewriting system # confluent when it can't determine the # truth of equality otherwise success = codomain.make_confluent() s = codomain.equals(_image(r), identity) if s is None and not success: raise RuntimeError("Can't determine if the images " "define a homomorphism. Try increasing " "the maximum number of rewriting rules " "(group._rewriting_system.set_max(new_value); " "the current value is stored in group._rewriting" "_system.maxeqns)") else: s = _image(r).is_identity if not s: return False return True def orbit_homomorphism(group, omega): ''' Return the homomorphism induced by the action of the permutation group ``group`` on the set ``omega`` that is closed under the action. ''' from sympy.combinatorics import Permutation from sympy.combinatorics.named_groups import SymmetricGroup codomain = SymmetricGroup(len(omega)) identity = codomain.identity omega = list(omega) images = {g: identity*Permutation([omega.index(o^g) for o in omega]) for g in group.generators} group._schreier_sims(base=omega) H = GroupHomomorphism(group, codomain, images) if len(group.basic_stabilizers) > len(omega): H._kernel = group.basic_stabilizers[len(omega)] else: H._kernel = PermutationGroup([group.identity]) return H def block_homomorphism(group, blocks): ''' Return the homomorphism induced by the action of the permutation group ``group`` on the block system ``blocks``. The latter should be of the same form as returned by the ``minimal_block`` method for permutation groups, namely a list of length ``group.degree`` where the i-th entry is a representative of the block i belongs to. ''' from sympy.combinatorics import Permutation from sympy.combinatorics.named_groups import SymmetricGroup n = len(blocks) # number the blocks; m is the total number, # b is such that b[i] is the number of the block i belongs to, # p is the list of length m such that p[i] is the representative # of the i-th block m = 0 p = [] b = [None]*n for i in range(n): if blocks[i] == i: p.append(i) b[i] = m m += 1 for i in range(n): b[i] = b[blocks[i]] codomain = SymmetricGroup(m) # the list corresponding to the identity permutation in codomain identity = range(m) images = {g: Permutation([b[p[i]^g] for i in identity]) for g in group.generators} H = GroupHomomorphism(group, codomain, images) return H def group_isomorphism(G, H, isomorphism=True): ''' Compute an isomorphism between 2 given groups. Parameters ========== G : A finite ``FpGroup`` or a ``PermutationGroup``. First group. H : A finite ``FpGroup`` or a ``PermutationGroup`` Second group. isomorphism : bool This is used to avoid the computation of homomorphism when the user only wants to check if there exists an isomorphism between the groups. Returns ======= If isomorphism = False -- Returns a boolean. If isomorphism = True -- Returns a boolean and an isomorphism between `G` and `H`. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup >>> from sympy.combinatorics.homomorphisms import group_isomorphism >>> from sympy.combinatorics.named_groups import DihedralGroup, AlternatingGroup >>> D = DihedralGroup(8) >>> p = Permutation(0, 1, 2, 3, 4, 5, 6, 7) >>> P = PermutationGroup(p) >>> group_isomorphism(D, P) (False, None) >>> F, a, b = free_group("a, b") >>> G = FpGroup(F, [a**3, b**3, (a*b)**2]) >>> H = AlternatingGroup(4) >>> (check, T) = group_isomorphism(G, H) >>> check True >>> T(b*a*b**-1*a**-1*b**-1) (0 2 3) Notes ===== Uses the approach suggested by Robert Tarjan to compute the isomorphism between two groups. First, the generators of ``G`` are mapped to the elements of ``H`` and we check if the mapping induces an isomorphism. ''' if not isinstance(G, (PermutationGroup, FpGroup)): raise TypeError("The group must be a PermutationGroup or an FpGroup") if not isinstance(H, (PermutationGroup, FpGroup)): raise TypeError("The group must be a PermutationGroup or an FpGroup") if isinstance(G, FpGroup) and isinstance(H, FpGroup): G = simplify_presentation(G) H = simplify_presentation(H) # Two infinite FpGroups with the same generators are isomorphic # when the relators are same but are ordered differently. if G.generators == H.generators and (G.relators).sort() == (H.relators).sort(): if not isomorphism: return True return (True, homomorphism(G, H, G.generators, H.generators)) # `_H` is the permutation group isomorphic to `H`. _H = H g_order = G.order() h_order = H.order() if g_order is S.Infinity: raise NotImplementedError("Isomorphism methods are not implemented for infinite groups.") if isinstance(H, FpGroup): if h_order is S.Infinity: raise NotImplementedError("Isomorphism methods are not implemented for infinite groups.") _H, h_isomorphism = H._to_perm_group() if (g_order != h_order) or (G.is_abelian != H.is_abelian): if not isomorphism: return False return (False, None) if not isomorphism: # Two groups of the same cyclic numbered order # are isomorphic to each other. n = g_order if (igcd(n, totient(n))) == 1: return True # Match the generators of `G` with subsets of `_H` gens = list(G.generators) for subset in itertools.permutations(_H, len(gens)): images = list(subset) images.extend([_H.identity]*(len(G.generators)-len(images))) _images = dict(zip(gens,images)) if _check_homomorphism(G, _H, _images): if isinstance(H, FpGroup): images = h_isomorphism.invert(images) T = homomorphism(G, H, G.generators, images, check=False) if T.is_isomorphism(): # It is a valid isomorphism if not isomorphism: return True return (True, T) if not isomorphism: return False return (False, None) def is_isomorphic(G, H): ''' Check if the groups are isomorphic to each other Parameters ========== G : A finite ``FpGroup`` or a ``PermutationGroup`` First group. H : A finite ``FpGroup`` or a ``PermutationGroup`` Second group. Returns ======= boolean ''' return group_isomorphism(G, H, isomorphism=False)
5b2b3f8fd0fe5e8a7b942c718273b75720eb490ecd540b84130564c8253eebdb
from sympy.core import Basic, Dict, sympify, Tuple from sympy.core.numbers import Integer from sympy.core.sorting import default_sort_key from sympy.core.sympify import _sympify from sympy.functions.combinatorial.numbers import bell from sympy.matrices import zeros from sympy.sets.sets import FiniteSet, Union from sympy.utilities.iterables import flatten, group from sympy.utilities.misc import as_int from collections import defaultdict class Partition(FiniteSet): """ This class represents an abstract partition. A partition is a set of disjoint sets whose union equals a given set. See Also ======== sympy.utilities.iterables.partitions, sympy.utilities.iterables.multiset_partitions """ _rank = None _partition = None def __new__(cls, *partition): """ Generates a new partition object. This method also verifies if the arguments passed are valid and raises a ValueError if they are not. Examples ======== Creating Partition from Python lists: >>> from sympy.combinatorics.partitions import Partition >>> a = Partition([1, 2], [3]) >>> a Partition({3}, {1, 2}) >>> a.partition [[1, 2], [3]] >>> len(a) 2 >>> a.members (1, 2, 3) Creating Partition from Python sets: >>> Partition({1, 2, 3}, {4, 5}) Partition({4, 5}, {1, 2, 3}) Creating Partition from SymPy finite sets: >>> from sympy import FiniteSet >>> a = FiniteSet(1, 2, 3) >>> b = FiniteSet(4, 5) >>> Partition(a, b) Partition({4, 5}, {1, 2, 3}) """ args = [] dups = False for arg in partition: if isinstance(arg, list): as_set = set(arg) if len(as_set) < len(arg): dups = True break # error below arg = as_set args.append(_sympify(arg)) if not all(isinstance(part, FiniteSet) for part in args): raise ValueError( "Each argument to Partition should be " \ "a list, set, or a FiniteSet") # sort so we have a canonical reference for RGS U = Union(*args) if dups or len(U) < sum(len(arg) for arg in args): raise ValueError("Partition contained duplicate elements.") obj = FiniteSet.__new__(cls, *args) obj.members = tuple(U) obj.size = len(U) return obj def sort_key(self, order=None): """Return a canonical key that can be used for sorting. Ordering is based on the size and sorted elements of the partition and ties are broken with the rank. Examples ======== >>> from sympy import default_sort_key >>> from sympy.combinatorics.partitions import Partition >>> from sympy.abc import x >>> a = Partition([1, 2]) >>> b = Partition([3, 4]) >>> c = Partition([1, x]) >>> d = Partition(list(range(4))) >>> l = [d, b, a + 1, a, c] >>> l.sort(key=default_sort_key); l [Partition({1, 2}), Partition({1}, {2}), Partition({1, x}), Partition({3, 4}), Partition({0, 1, 2, 3})] """ if order is None: members = self.members else: members = tuple(sorted(self.members, key=lambda w: default_sort_key(w, order))) return tuple(map(default_sort_key, (self.size, members, self.rank))) @property def partition(self): """Return partition as a sorted list of lists. Examples ======== >>> from sympy.combinatorics.partitions import Partition >>> Partition([1], [2, 3]).partition [[1], [2, 3]] """ if self._partition is None: self._partition = sorted([sorted(p, key=default_sort_key) for p in self.args]) return self._partition def __add__(self, other): """ Return permutation whose rank is ``other`` greater than current rank, (mod the maximum rank for the set). Examples ======== >>> from sympy.combinatorics.partitions import Partition >>> a = Partition([1, 2], [3]) >>> a.rank 1 >>> (a + 1).rank 2 >>> (a + 100).rank 1 """ other = as_int(other) offset = self.rank + other result = RGS_unrank((offset) % RGS_enum(self.size), self.size) return Partition.from_rgs(result, self.members) def __sub__(self, other): """ Return permutation whose rank is ``other`` less than current rank, (mod the maximum rank for the set). Examples ======== >>> from sympy.combinatorics.partitions import Partition >>> a = Partition([1, 2], [3]) >>> a.rank 1 >>> (a - 1).rank 0 >>> (a - 100).rank 1 """ return self.__add__(-other) def __le__(self, other): """ Checks if a partition is less than or equal to the other based on rank. Examples ======== >>> from sympy.combinatorics.partitions import Partition >>> a = Partition([1, 2], [3, 4, 5]) >>> b = Partition([1], [2, 3], [4], [5]) >>> a.rank, b.rank (9, 34) >>> a <= a True >>> a <= b True """ return self.sort_key() <= sympify(other).sort_key() def __lt__(self, other): """ Checks if a partition is less than the other. Examples ======== >>> from sympy.combinatorics.partitions import Partition >>> a = Partition([1, 2], [3, 4, 5]) >>> b = Partition([1], [2, 3], [4], [5]) >>> a.rank, b.rank (9, 34) >>> a < b True """ return self.sort_key() < sympify(other).sort_key() @property def rank(self): """ Gets the rank of a partition. Examples ======== >>> from sympy.combinatorics.partitions import Partition >>> a = Partition([1, 2], [3], [4, 5]) >>> a.rank 13 """ if self._rank is not None: return self._rank self._rank = RGS_rank(self.RGS) return self._rank @property def RGS(self): """ Returns the "restricted growth string" of the partition. Explanation =========== The RGS is returned as a list of indices, L, where L[i] indicates the block in which element i appears. For example, in a partition of 3 elements (a, b, c) into 2 blocks ([c], [a, b]) the RGS is [1, 1, 0]: "a" is in block 1, "b" is in block 1 and "c" is in block 0. Examples ======== >>> from sympy.combinatorics.partitions import Partition >>> a = Partition([1, 2], [3], [4, 5]) >>> a.members (1, 2, 3, 4, 5) >>> a.RGS (0, 0, 1, 2, 2) >>> a + 1 Partition({3}, {4}, {5}, {1, 2}) >>> _.RGS (0, 0, 1, 2, 3) """ rgs = {} partition = self.partition for i, part in enumerate(partition): for j in part: rgs[j] = i return tuple([rgs[i] for i in sorted( [i for p in partition for i in p], key=default_sort_key)]) @classmethod def from_rgs(self, rgs, elements): """ Creates a set partition from a restricted growth string. Explanation =========== The indices given in rgs are assumed to be the index of the element as given in elements *as provided* (the elements are not sorted by this routine). Block numbering starts from 0. If any block was not referenced in ``rgs`` an error will be raised. Examples ======== >>> from sympy.combinatorics.partitions import Partition >>> Partition.from_rgs([0, 1, 2, 0, 1], list('abcde')) Partition({c}, {a, d}, {b, e}) >>> Partition.from_rgs([0, 1, 2, 0, 1], list('cbead')) Partition({e}, {a, c}, {b, d}) >>> a = Partition([1, 4], [2], [3, 5]) >>> Partition.from_rgs(a.RGS, a.members) Partition({2}, {1, 4}, {3, 5}) """ if len(rgs) != len(elements): raise ValueError('mismatch in rgs and element lengths') max_elem = max(rgs) + 1 partition = [[] for i in range(max_elem)] j = 0 for i in rgs: partition[i].append(elements[j]) j += 1 if not all(p for p in partition): raise ValueError('some blocks of the partition were empty.') return Partition(*partition) class IntegerPartition(Basic): """ This class represents an integer partition. Explanation =========== In number theory and combinatorics, a partition of a positive integer, ``n``, also called an integer partition, is a way of writing ``n`` as a list of positive integers that sum to n. Two partitions that differ only in the order of summands are considered to be the same partition; if order matters then the partitions are referred to as compositions. For example, 4 has five partitions: [4], [3, 1], [2, 2], [2, 1, 1], and [1, 1, 1, 1]; the compositions [1, 2, 1] and [1, 1, 2] are the same as partition [2, 1, 1]. See Also ======== sympy.utilities.iterables.partitions, sympy.utilities.iterables.multiset_partitions References ========== .. [1] https://en.wikipedia.org/wiki/Partition_%28number_theory%29 """ _dict = None _keys = None def __new__(cls, partition, integer=None): """ Generates a new IntegerPartition object from a list or dictionary. Explantion ========== The partition can be given as a list of positive integers or a dictionary of (integer, multiplicity) items. If the partition is preceded by an integer an error will be raised if the partition does not sum to that given integer. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> a = IntegerPartition([5, 4, 3, 1, 1]) >>> a IntegerPartition(14, (5, 4, 3, 1, 1)) >>> print(a) [5, 4, 3, 1, 1] >>> IntegerPartition({1:3, 2:1}) IntegerPartition(5, (2, 1, 1, 1)) If the value that the partition should sum to is given first, a check will be made to see n error will be raised if there is a discrepancy: >>> IntegerPartition(10, [5, 4, 3, 1]) Traceback (most recent call last): ... ValueError: The partition is not valid """ if integer is not None: integer, partition = partition, integer if isinstance(partition, (dict, Dict)): _ = [] for k, v in sorted(list(partition.items()), reverse=True): if not v: continue k, v = as_int(k), as_int(v) _.extend([k]*v) partition = tuple(_) else: partition = tuple(sorted(map(as_int, partition), reverse=True)) sum_ok = False if integer is None: integer = sum(partition) sum_ok = True else: integer = as_int(integer) if not sum_ok and sum(partition) != integer: raise ValueError("Partition did not add to %s" % integer) if any(i < 1 for i in partition): raise ValueError("All integer summands must be greater than one") obj = Basic.__new__(cls, Integer(integer), Tuple(*partition)) obj.partition = list(partition) obj.integer = integer return obj def prev_lex(self): """Return the previous partition of the integer, n, in lexical order, wrapping around to [1, ..., 1] if the partition is [n]. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> p = IntegerPartition([4]) >>> print(p.prev_lex()) [3, 1] >>> p.partition > p.prev_lex().partition True """ d = defaultdict(int) d.update(self.as_dict()) keys = self._keys if keys == [1]: return IntegerPartition({self.integer: 1}) if keys[-1] != 1: d[keys[-1]] -= 1 if keys[-1] == 2: d[1] = 2 else: d[keys[-1] - 1] = d[1] = 1 else: d[keys[-2]] -= 1 left = d[1] + keys[-2] new = keys[-2] d[1] = 0 while left: new -= 1 if left - new >= 0: d[new] += left//new left -= d[new]*new return IntegerPartition(self.integer, d) def next_lex(self): """Return the next partition of the integer, n, in lexical order, wrapping around to [n] if the partition is [1, ..., 1]. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> p = IntegerPartition([3, 1]) >>> print(p.next_lex()) [4] >>> p.partition < p.next_lex().partition True """ d = defaultdict(int) d.update(self.as_dict()) key = self._keys a = key[-1] if a == self.integer: d.clear() d[1] = self.integer elif a == 1: if d[a] > 1: d[a + 1] += 1 d[a] -= 2 else: b = key[-2] d[b + 1] += 1 d[1] = (d[b] - 1)*b d[b] = 0 else: if d[a] > 1: if len(key) == 1: d.clear() d[a + 1] = 1 d[1] = self.integer - a - 1 else: a1 = a + 1 d[a1] += 1 d[1] = d[a]*a - a1 d[a] = 0 else: b = key[-2] b1 = b + 1 d[b1] += 1 need = d[b]*b + d[a]*a - b1 d[a] = d[b] = 0 d[1] = need return IntegerPartition(self.integer, d) def as_dict(self): """Return the partition as a dictionary whose keys are the partition integers and the values are the multiplicity of that integer. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> IntegerPartition([1]*3 + [2] + [3]*4).as_dict() {1: 3, 2: 1, 3: 4} """ if self._dict is None: groups = group(self.partition, multiple=False) self._keys = [g[0] for g in groups] self._dict = dict(groups) return self._dict @property def conjugate(self): """ Computes the conjugate partition of itself. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> a = IntegerPartition([6, 3, 3, 2, 1]) >>> a.conjugate [5, 4, 3, 1, 1, 1] """ j = 1 temp_arr = list(self.partition) + [0] k = temp_arr[0] b = [0]*k while k > 0: while k > temp_arr[j]: b[k - 1] = j k -= 1 j += 1 return b def __lt__(self, other): """Return True if self is less than other when the partition is listed from smallest to biggest. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> a = IntegerPartition([3, 1]) >>> a < a False >>> b = a.next_lex() >>> a < b True >>> a == b False """ return list(reversed(self.partition)) < list(reversed(other.partition)) def __le__(self, other): """Return True if self is less than other when the partition is listed from smallest to biggest. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> a = IntegerPartition([4]) >>> a <= a True """ return list(reversed(self.partition)) <= list(reversed(other.partition)) def as_ferrers(self, char='#'): """ Prints the ferrer diagram of a partition. Examples ======== >>> from sympy.combinatorics.partitions import IntegerPartition >>> print(IntegerPartition([1, 1, 5]).as_ferrers()) ##### # # """ return "\n".join([char*i for i in self.partition]) def __str__(self): return str(list(self.partition)) def random_integer_partition(n, seed=None): """ Generates a random integer partition summing to ``n`` as a list of reverse-sorted integers. Examples ======== >>> from sympy.combinatorics.partitions import random_integer_partition For the following, a seed is given so a known value can be shown; in practice, the seed would not be given. >>> random_integer_partition(100, seed=[1, 1, 12, 1, 2, 1, 85, 1]) [85, 12, 2, 1] >>> random_integer_partition(10, seed=[1, 2, 3, 1, 5, 1]) [5, 3, 1, 1] >>> random_integer_partition(1) [1] """ from sympy.core.random import _randint n = as_int(n) if n < 1: raise ValueError('n must be a positive integer') randint = _randint(seed) partition = [] while (n > 0): k = randint(1, n) mult = randint(1, n//k) partition.append((k, mult)) n -= k*mult partition.sort(reverse=True) partition = flatten([[k]*m for k, m in partition]) return partition def RGS_generalized(m): """ Computes the m + 1 generalized unrestricted growth strings and returns them as rows in matrix. Examples ======== >>> from sympy.combinatorics.partitions import RGS_generalized >>> RGS_generalized(6) Matrix([ [ 1, 1, 1, 1, 1, 1, 1], [ 1, 2, 3, 4, 5, 6, 0], [ 2, 5, 10, 17, 26, 0, 0], [ 5, 15, 37, 77, 0, 0, 0], [ 15, 52, 151, 0, 0, 0, 0], [ 52, 203, 0, 0, 0, 0, 0], [203, 0, 0, 0, 0, 0, 0]]) """ d = zeros(m + 1) for i in range(0, m + 1): d[0, i] = 1 for i in range(1, m + 1): for j in range(m): if j <= m - i: d[i, j] = j * d[i - 1, j] + d[i - 1, j + 1] else: d[i, j] = 0 return d def RGS_enum(m): """ RGS_enum computes the total number of restricted growth strings possible for a superset of size m. Examples ======== >>> from sympy.combinatorics.partitions import RGS_enum >>> from sympy.combinatorics.partitions import Partition >>> RGS_enum(4) 15 >>> RGS_enum(5) 52 >>> RGS_enum(6) 203 We can check that the enumeration is correct by actually generating the partitions. Here, the 15 partitions of 4 items are generated: >>> a = Partition(list(range(4))) >>> s = set() >>> for i in range(20): ... s.add(a) ... a += 1 ... >>> assert len(s) == 15 """ if (m < 1): return 0 elif (m == 1): return 1 else: return bell(m) def RGS_unrank(rank, m): """ Gives the unranked restricted growth string for a given superset size. Examples ======== >>> from sympy.combinatorics.partitions import RGS_unrank >>> RGS_unrank(14, 4) [0, 1, 2, 3] >>> RGS_unrank(0, 4) [0, 0, 0, 0] """ if m < 1: raise ValueError("The superset size must be >= 1") if rank < 0 or RGS_enum(m) <= rank: raise ValueError("Invalid arguments") L = [1] * (m + 1) j = 1 D = RGS_generalized(m) for i in range(2, m + 1): v = D[m - i, j] cr = j*v if cr <= rank: L[i] = j + 1 rank -= cr j += 1 else: L[i] = int(rank / v + 1) rank %= v return [x - 1 for x in L[1:]] def RGS_rank(rgs): """ Computes the rank of a restricted growth string. Examples ======== >>> from sympy.combinatorics.partitions import RGS_rank, RGS_unrank >>> RGS_rank([0, 1, 2, 1, 3]) 42 >>> RGS_rank(RGS_unrank(4, 7)) 4 """ rgs_size = len(rgs) rank = 0 D = RGS_generalized(rgs_size) for i in range(1, rgs_size): n = len(rgs[(i + 1):]) m = max(rgs[0:i]) rank += D[n, m + 1] * rgs[i] return rank
51f566a8449cf9a4a556f4f4031c24c33e8531a392e6efae19dcb9945dac3956
from sympy.combinatorics.permutations import Permutation, _af_invert, _af_rmul from sympy.ntheory import isprime rmul = Permutation.rmul _af_new = Permutation._af_new ############################################ # # Utilities for computational group theory # ############################################ def _base_ordering(base, degree): r""" Order `\{0, 1, \dots, n-1\}` so that base points come first and in order. Parameters ========== ``base`` : the base ``degree`` : the degree of the associated permutation group Returns ======= A list ``base_ordering`` such that ``base_ordering[point]`` is the number of ``point`` in the ordering. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.util import _base_ordering >>> S = SymmetricGroup(4) >>> S.schreier_sims() >>> _base_ordering(S.base, S.degree) [0, 1, 2, 3] Notes ===== This is used in backtrack searches, when we define a relation `\ll` on the underlying set for a permutation group of degree `n`, `\{0, 1, \dots, n-1\}`, so that if `(b_1, b_2, \dots, b_k)` is a base we have `b_i \ll b_j` whenever `i<j` and `b_i \ll a` for all `i\in\{1,2, \dots, k\}` and `a` is not in the base. The idea is developed and applied to backtracking algorithms in [1], pp.108-132. The points that are not in the base are taken in increasing order. References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory" """ base_len = len(base) ordering = [0]*degree for i in range(base_len): ordering[base[i]] = i current = base_len for i in range(degree): if i not in base: ordering[i] = current current += 1 return ordering def _check_cycles_alt_sym(perm): """ Checks for cycles of prime length p with n/2 < p < n-2. Explanation =========== Here `n` is the degree of the permutation. This is a helper function for the function is_alt_sym from sympy.combinatorics.perm_groups. Examples ======== >>> from sympy.combinatorics.util import _check_cycles_alt_sym >>> from sympy.combinatorics.permutations import Permutation >>> a = Permutation([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12]]) >>> _check_cycles_alt_sym(a) False >>> b = Permutation([[0, 1, 2, 3, 4, 5, 6], [7, 8, 9, 10]]) >>> _check_cycles_alt_sym(b) True See Also ======== sympy.combinatorics.perm_groups.PermutationGroup.is_alt_sym """ n = perm.size af = perm.array_form current_len = 0 total_len = 0 used = set() for i in range(n//2): if i not in used and i < n//2 - total_len: current_len = 1 used.add(i) j = i while af[j] != i: current_len += 1 j = af[j] used.add(j) total_len += current_len if current_len > n//2 and current_len < n - 2 and isprime(current_len): return True return False def _distribute_gens_by_base(base, gens): r""" Distribute the group elements ``gens`` by membership in basic stabilizers. Explanation =========== Notice that for a base `(b_1, b_2, \dots, b_k)`, the basic stabilizers are defined as `G^{(i)} = G_{b_1, \dots, b_{i-1}}` for `i \in\{1, 2, \dots, k\}`. Parameters ========== ``base`` : a sequence of points in `\{0, 1, \dots, n-1\}` ``gens`` : a list of elements of a permutation group of degree `n`. Returns ======= List of length `k`, where `k` is the length of ``base``. The `i`-th entry contains those elements in ``gens`` which fix the first `i` elements of ``base`` (so that the `0`-th entry is equal to ``gens`` itself). If no element fixes the first `i` elements of ``base``, the `i`-th element is set to a list containing the identity element. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> from sympy.combinatorics.util import _distribute_gens_by_base >>> D = DihedralGroup(3) >>> D.schreier_sims() >>> D.strong_gens [(0 1 2), (0 2), (1 2)] >>> D.base [0, 1] >>> _distribute_gens_by_base(D.base, D.strong_gens) [[(0 1 2), (0 2), (1 2)], [(1 2)]] See Also ======== _strong_gens_from_distr, _orbits_transversals_from_bsgs, _handle_precomputed_bsgs """ base_len = len(base) degree = gens[0].size stabs = [[] for _ in range(base_len)] max_stab_index = 0 for gen in gens: j = 0 while j < base_len - 1 and gen._array_form[base[j]] == base[j]: j += 1 if j > max_stab_index: max_stab_index = j for k in range(j + 1): stabs[k].append(gen) for i in range(max_stab_index + 1, base_len): stabs[i].append(_af_new(list(range(degree)))) return stabs def _handle_precomputed_bsgs(base, strong_gens, transversals=None, basic_orbits=None, strong_gens_distr=None): """ Calculate BSGS-related structures from those present. Explanation =========== The base and strong generating set must be provided; if any of the transversals, basic orbits or distributed strong generators are not provided, they will be calculated from the base and strong generating set. Parameters ========== ``base`` - the base ``strong_gens`` - the strong generators ``transversals`` - basic transversals ``basic_orbits`` - basic orbits ``strong_gens_distr`` - strong generators distributed by membership in basic stabilizers Returns ======= ``(transversals, basic_orbits, strong_gens_distr)`` where ``transversals`` are the basic transversals, ``basic_orbits`` are the basic orbits, and ``strong_gens_distr`` are the strong generators distributed by membership in basic stabilizers. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> from sympy.combinatorics.util import _handle_precomputed_bsgs >>> D = DihedralGroup(3) >>> D.schreier_sims() >>> _handle_precomputed_bsgs(D.base, D.strong_gens, ... basic_orbits=D.basic_orbits) ([{0: (2), 1: (0 1 2), 2: (0 2)}, {1: (2), 2: (1 2)}], [[0, 1, 2], [1, 2]], [[(0 1 2), (0 2), (1 2)], [(1 2)]]) See Also ======== _orbits_transversals_from_bsgs, _distribute_gens_by_base """ if strong_gens_distr is None: strong_gens_distr = _distribute_gens_by_base(base, strong_gens) if transversals is None: if basic_orbits is None: basic_orbits, transversals = \ _orbits_transversals_from_bsgs(base, strong_gens_distr) else: transversals = \ _orbits_transversals_from_bsgs(base, strong_gens_distr, transversals_only=True) else: if basic_orbits is None: base_len = len(base) basic_orbits = [None]*base_len for i in range(base_len): basic_orbits[i] = list(transversals[i].keys()) return transversals, basic_orbits, strong_gens_distr def _orbits_transversals_from_bsgs(base, strong_gens_distr, transversals_only=False, slp=False): """ Compute basic orbits and transversals from a base and strong generating set. Explanation =========== The generators are provided as distributed across the basic stabilizers. If the optional argument ``transversals_only`` is set to True, only the transversals are returned. Parameters ========== ``base`` - The base. ``strong_gens_distr`` - Strong generators distributed by membership in basic stabilizers. ``transversals_only`` - bool A flag switching between returning only the transversals and both orbits and transversals. ``slp`` - If ``True``, return a list of dictionaries containing the generator presentations of the elements of the transversals, i.e. the list of indices of generators from ``strong_gens_distr[i]`` such that their product is the relevant transversal element. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.util import _distribute_gens_by_base >>> S = SymmetricGroup(3) >>> S.schreier_sims() >>> strong_gens_distr = _distribute_gens_by_base(S.base, S.strong_gens) >>> (S.base, strong_gens_distr) ([0, 1], [[(0 1 2), (2)(0 1), (1 2)], [(1 2)]]) See Also ======== _distribute_gens_by_base, _handle_precomputed_bsgs """ from sympy.combinatorics.perm_groups import _orbit_transversal base_len = len(base) degree = strong_gens_distr[0][0].size transversals = [None]*base_len slps = [None]*base_len if transversals_only is False: basic_orbits = [None]*base_len for i in range(base_len): transversals[i], slps[i] = _orbit_transversal(degree, strong_gens_distr[i], base[i], pairs=True, slp=True) transversals[i] = dict(transversals[i]) if transversals_only is False: basic_orbits[i] = list(transversals[i].keys()) if transversals_only: return transversals else: if not slp: return basic_orbits, transversals return basic_orbits, transversals, slps def _remove_gens(base, strong_gens, basic_orbits=None, strong_gens_distr=None): """ Remove redundant generators from a strong generating set. Parameters ========== ``base`` - a base ``strong_gens`` - a strong generating set relative to ``base`` ``basic_orbits`` - basic orbits ``strong_gens_distr`` - strong generators distributed by membership in basic stabilizers Returns ======= A strong generating set with respect to ``base`` which is a subset of ``strong_gens``. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.util import _remove_gens >>> from sympy.combinatorics.testutil import _verify_bsgs >>> S = SymmetricGroup(15) >>> base, strong_gens = S.schreier_sims_incremental() >>> new_gens = _remove_gens(base, strong_gens) >>> len(new_gens) 14 >>> _verify_bsgs(S, base, new_gens) True Notes ===== This procedure is outlined in [1],p.95. References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory" """ from sympy.combinatorics.perm_groups import _orbit base_len = len(base) degree = strong_gens[0].size if strong_gens_distr is None: strong_gens_distr = _distribute_gens_by_base(base, strong_gens) if basic_orbits is None: basic_orbits = [] for i in range(base_len): basic_orbit = _orbit(degree, strong_gens_distr[i], base[i]) basic_orbits.append(basic_orbit) strong_gens_distr.append([]) res = strong_gens[:] for i in range(base_len - 1, -1, -1): gens_copy = strong_gens_distr[i][:] for gen in strong_gens_distr[i]: if gen not in strong_gens_distr[i + 1]: temp_gens = gens_copy[:] temp_gens.remove(gen) if temp_gens == []: continue temp_orbit = _orbit(degree, temp_gens, base[i]) if temp_orbit == basic_orbits[i]: gens_copy.remove(gen) res.remove(gen) return res def _strip(g, base, orbits, transversals): """ Attempt to decompose a permutation using a (possibly partial) BSGS structure. Explanation =========== This is done by treating the sequence ``base`` as an actual base, and the orbits ``orbits`` and transversals ``transversals`` as basic orbits and transversals relative to it. This process is called "sifting". A sift is unsuccessful when a certain orbit element is not found or when after the sift the decomposition doesn't end with the identity element. The argument ``transversals`` is a list of dictionaries that provides transversal elements for the orbits ``orbits``. Parameters ========== ``g`` - permutation to be decomposed ``base`` - sequence of points ``orbits`` - a list in which the ``i``-th entry is an orbit of ``base[i]`` under some subgroup of the pointwise stabilizer of ` `base[0], base[1], ..., base[i - 1]``. The groups themselves are implicit in this function since the only information we need is encoded in the orbits and transversals ``transversals`` - a list of orbit transversals associated with the orbits ``orbits``. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.util import _strip >>> S = SymmetricGroup(5) >>> S.schreier_sims() >>> g = Permutation([0, 2, 3, 1, 4]) >>> _strip(g, S.base, S.basic_orbits, S.basic_transversals) ((4), 5) Notes ===== The algorithm is described in [1],pp.89-90. The reason for returning both the current state of the element being decomposed and the level at which the sifting ends is that they provide important information for the randomized version of the Schreier-Sims algorithm. References ========== .. [1] Holt, D., Eick, B., O'Brien, E."Handbook of computational group theory" See Also ======== sympy.combinatorics.perm_groups.PermutationGroup.schreier_sims sympy.combinatorics.perm_groups.PermutationGroup.schreier_sims_random """ h = g._array_form base_len = len(base) for i in range(base_len): beta = h[base[i]] if beta == base[i]: continue if beta not in orbits[i]: return _af_new(h), i + 1 u = transversals[i][beta]._array_form h = _af_rmul(_af_invert(u), h) return _af_new(h), base_len + 1 def _strip_af(h, base, orbits, transversals, j, slp=[], slps={}): """ optimized _strip, with h, transversals and result in array form if the stripped elements is the identity, it returns False, base_len + 1 j h[base[i]] == base[i] for i <= j """ base_len = len(base) for i in range(j+1, base_len): beta = h[base[i]] if beta == base[i]: continue if beta not in orbits[i]: if not slp: return h, i + 1 return h, i + 1, slp u = transversals[i][beta] if h == u: if not slp: return False, base_len + 1 return False, base_len + 1, slp h = _af_rmul(_af_invert(u), h) if slp: u_slp = slps[i][beta][:] u_slp.reverse() u_slp = [(i, (g,)) for g in u_slp] slp = u_slp + slp if not slp: return h, base_len + 1 return h, base_len + 1, slp def _strong_gens_from_distr(strong_gens_distr): """ Retrieve strong generating set from generators of basic stabilizers. This is just the union of the generators of the first and second basic stabilizers. Parameters ========== ``strong_gens_distr`` - strong generators distributed by membership in basic stabilizers Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.util import (_strong_gens_from_distr, ... _distribute_gens_by_base) >>> S = SymmetricGroup(3) >>> S.schreier_sims() >>> S.strong_gens [(0 1 2), (2)(0 1), (1 2)] >>> strong_gens_distr = _distribute_gens_by_base(S.base, S.strong_gens) >>> _strong_gens_from_distr(strong_gens_distr) [(0 1 2), (2)(0 1), (1 2)] See Also ======== _distribute_gens_by_base """ if len(strong_gens_distr) == 1: return strong_gens_distr[0][:] else: result = strong_gens_distr[0] for gen in strong_gens_distr[1]: if gen not in result: result.append(gen) return result
41c464faa64730c96f5e6257b42dbeb1bf8042a853151f16329614b99337ac14
from sympy.combinatorics.free_groups import free_group from sympy.printing.defaults import DefaultPrinting from itertools import chain, product from bisect import bisect_left ############################################################################### # COSET TABLE # ############################################################################### class CosetTable(DefaultPrinting): # coset_table: Mathematically a coset table # represented using a list of lists # alpha: Mathematically a coset (precisely, a live coset) # represented by an integer between i with 1 <= i <= n # alpha in c # x: Mathematically an element of "A" (set of generators and # their inverses), represented using "FpGroupElement" # fp_grp: Finitely Presented Group with < X|R > as presentation. # H: subgroup of fp_grp. # NOTE: We start with H as being only a list of words in generators # of "fp_grp". Since `.subgroup` method has not been implemented. r""" Properties ========== [1] `0 \in \Omega` and `\tau(1) = \epsilon` [2] `\alpha^x = \beta \Leftrightarrow \beta^{x^{-1}} = \alpha` [3] If `\alpha^x = \beta`, then `H \tau(\alpha)x = H \tau(\beta)` [4] `\forall \alpha \in \Omega, 1^{\tau(\alpha)} = \alpha` References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" .. [2] John J. Cannon; Lucien A. Dimino; George Havas; Jane M. Watson Mathematics of Computation, Vol. 27, No. 123. (Jul., 1973), pp. 463-490. "Implementation and Analysis of the Todd-Coxeter Algorithm" """ # default limit for the number of cosets allowed in a # coset enumeration. coset_table_max_limit = 4096000 # limit for the current instance coset_table_limit = None # maximum size of deduction stack above or equal to # which it is emptied max_stack_size = 100 def __init__(self, fp_grp, subgroup, max_cosets=None): if not max_cosets: max_cosets = CosetTable.coset_table_max_limit self.fp_group = fp_grp self.subgroup = subgroup self.coset_table_limit = max_cosets # "p" is setup independent of Omega and n self.p = [0] # a list of the form `[gen_1, gen_1^{-1}, ... , gen_k, gen_k^{-1}]` self.A = list(chain.from_iterable((gen, gen**-1) \ for gen in self.fp_group.generators)) #P[alpha, x] Only defined when alpha^x is defined. self.P = [[None]*len(self.A)] # the mathematical coset table which is a list of lists self.table = [[None]*len(self.A)] self.A_dict = {x: self.A.index(x) for x in self.A} self.A_dict_inv = {} for x, index in self.A_dict.items(): if index % 2 == 0: self.A_dict_inv[x] = self.A_dict[x] + 1 else: self.A_dict_inv[x] = self.A_dict[x] - 1 # used in the coset-table based method of coset enumeration. Each of # the element is called a "deduction" which is the form (alpha, x) whenever # a value is assigned to alpha^x during a definition or "deduction process" self.deduction_stack = [] # Attributes for modified methods. H = self.subgroup self._grp = free_group(', ' .join(["a_%d" % i for i in range(len(H))]))[0] self.P = [[None]*len(self.A)] self.p_p = {} @property def omega(self): """Set of live cosets. """ return [coset for coset in range(len(self.p)) if self.p[coset] == coset] def copy(self): """ Return a shallow copy of Coset Table instance ``self``. """ self_copy = self.__class__(self.fp_group, self.subgroup) self_copy.table = [list(perm_rep) for perm_rep in self.table] self_copy.p = list(self.p) self_copy.deduction_stack = list(self.deduction_stack) return self_copy def __str__(self): return "Coset Table on %s with %s as subgroup generators" \ % (self.fp_group, self.subgroup) __repr__ = __str__ @property def n(self): """The number `n` represents the length of the sublist containing the live cosets. """ if not self.table: return 0 return max(self.omega) + 1 # Pg. 152 [1] def is_complete(self): r""" The coset table is called complete if it has no undefined entries on the live cosets; that is, `\alpha^x` is defined for all `\alpha \in \Omega` and `x \in A`. """ return not any(None in self.table[coset] for coset in self.omega) # Pg. 153 [1] def define(self, alpha, x, modified=False): r""" This routine is used in the relator-based strategy of Todd-Coxeter algorithm if some `\alpha^x` is undefined. We check whether there is space available for defining a new coset. If there is enough space then we remedy this by adjoining a new coset `\beta` to `\Omega` (i.e to set of live cosets) and put that equal to `\alpha^x`, then make an assignment satisfying Property[1]. If there is not enough space then we halt the Coset Table creation. The maximum amount of space that can be used by Coset Table can be manipulated using the class variable ``CosetTable.coset_table_max_limit``. See Also ======== define_c """ A = self.A table = self.table len_table = len(table) if len_table >= self.coset_table_limit: # abort the further generation of cosets raise ValueError("the coset enumeration has defined more than " "%s cosets. Try with a greater value max number of cosets " % self.coset_table_limit) table.append([None]*len(A)) self.P.append([None]*len(self.A)) # beta is the new coset generated beta = len_table self.p.append(beta) table[alpha][self.A_dict[x]] = beta table[beta][self.A_dict_inv[x]] = alpha # P[alpha][x] = epsilon, P[beta][x**-1] = epsilon if modified: self.P[alpha][self.A_dict[x]] = self._grp.identity self.P[beta][self.A_dict_inv[x]] = self._grp.identity self.p_p[beta] = self._grp.identity def define_c(self, alpha, x): r""" A variation of ``define`` routine, described on Pg. 165 [1], used in the coset table-based strategy of Todd-Coxeter algorithm. It differs from ``define`` routine in that for each definition it also adds the tuple `(\alpha, x)` to the deduction stack. See Also ======== define """ A = self.A table = self.table len_table = len(table) if len_table >= self.coset_table_limit: # abort the further generation of cosets raise ValueError("the coset enumeration has defined more than " "%s cosets. Try with a greater value max number of cosets " % self.coset_table_limit) table.append([None]*len(A)) # beta is the new coset generated beta = len_table self.p.append(beta) table[alpha][self.A_dict[x]] = beta table[beta][self.A_dict_inv[x]] = alpha # append to deduction stack self.deduction_stack.append((alpha, x)) def scan_c(self, alpha, word): """ A variation of ``scan`` routine, described on pg. 165 of [1], which puts at tuple, whenever a deduction occurs, to deduction stack. See Also ======== scan, scan_check, scan_and_fill, scan_and_fill_c """ # alpha is an integer representing a "coset" # since scanning can be in two cases # 1. for alpha=0 and w in Y (i.e generating set of H) # 2. alpha in Omega (set of live cosets), w in R (relators) A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table f = alpha i = 0 r = len(word) b = alpha j = r - 1 # list of union of generators and their inverses while i <= j and table[f][A_dict[word[i]]] is not None: f = table[f][A_dict[word[i]]] i += 1 if i > j: if f != b: self.coincidence_c(f, b) return while j >= i and table[b][A_dict_inv[word[j]]] is not None: b = table[b][A_dict_inv[word[j]]] j -= 1 if j < i: # we have an incorrect completed scan with coincidence f ~ b # run the "coincidence" routine self.coincidence_c(f, b) elif j == i: # deduction process table[f][A_dict[word[i]]] = b table[b][A_dict_inv[word[i]]] = f self.deduction_stack.append((f, word[i])) # otherwise scan is incomplete and yields no information # alpha, beta coincide, i.e. alpha, beta represent the pair of cosets where # coincidence occurs def coincidence_c(self, alpha, beta): """ A variation of ``coincidence`` routine used in the coset-table based method of coset enumeration. The only difference being on addition of a new coset in coset table(i.e new coset introduction), then it is appended to ``deduction_stack``. See Also ======== coincidence """ A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table # behaves as a queue q = [] self.merge(alpha, beta, q) while len(q) > 0: gamma = q.pop(0) for x in A_dict: delta = table[gamma][A_dict[x]] if delta is not None: table[delta][A_dict_inv[x]] = None # only line of difference from ``coincidence`` routine self.deduction_stack.append((delta, x**-1)) mu = self.rep(gamma) nu = self.rep(delta) if table[mu][A_dict[x]] is not None: self.merge(nu, table[mu][A_dict[x]], q) elif table[nu][A_dict_inv[x]] is not None: self.merge(mu, table[nu][A_dict_inv[x]], q) else: table[mu][A_dict[x]] = nu table[nu][A_dict_inv[x]] = mu def scan(self, alpha, word, y=None, fill=False, modified=False): r""" ``scan`` performs a scanning process on the input ``word``. It first locates the largest prefix ``s`` of ``word`` for which `\alpha^s` is defined (i.e is not ``None``), ``s`` may be empty. Let ``word=sv``, let ``t`` be the longest suffix of ``v`` for which `\alpha^{t^{-1}}` is defined, and let ``v=ut``. Then three possibilities are there: 1. If ``t=v``, then we say that the scan completes, and if, in addition `\alpha^s = \alpha^{t^{-1}}`, then we say that the scan completes correctly. 2. It can also happen that scan does not complete, but `|u|=1`; that is, the word ``u`` consists of a single generator `x \in A`. In that case, if `\alpha^s = \beta` and `\alpha^{t^{-1}} = \gamma`, then we can set `\beta^x = \gamma` and `\gamma^{x^{-1}} = \beta`. These assignments are known as deductions and enable the scan to complete correctly. 3. See ``coicidence`` routine for explanation of third condition. Notes ===== The code for the procedure of scanning `\alpha \in \Omega` under `w \in A*` is defined on pg. 155 [1] See Also ======== scan_c, scan_check, scan_and_fill, scan_and_fill_c Scan and Fill ============= Performed when the default argument fill=True. Modified Scan ============= Performed when the default argument modified=True """ # alpha is an integer representing a "coset" # since scanning can be in two cases # 1. for alpha=0 and w in Y (i.e generating set of H) # 2. alpha in Omega (set of live cosets), w in R (relators) A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table f = alpha i = 0 r = len(word) b = alpha j = r - 1 b_p = y if modified: f_p = self._grp.identity flag = 0 while fill or flag == 0: flag = 1 while i <= j and table[f][A_dict[word[i]]] is not None: if modified: f_p = f_p*self.P[f][A_dict[word[i]]] f = table[f][A_dict[word[i]]] i += 1 if i > j: if f != b: if modified: self.modified_coincidence(f, b, f_p**-1*y) else: self.coincidence(f, b) return while j >= i and table[b][A_dict_inv[word[j]]] is not None: if modified: b_p = b_p*self.P[b][self.A_dict_inv[word[j]]] b = table[b][A_dict_inv[word[j]]] j -= 1 if j < i: # we have an incorrect completed scan with coincidence f ~ b # run the "coincidence" routine if modified: self.modified_coincidence(f, b, f_p**-1*b_p) else: self.coincidence(f, b) elif j == i: # deduction process table[f][A_dict[word[i]]] = b table[b][A_dict_inv[word[i]]] = f if modified: self.P[f][self.A_dict[word[i]]] = f_p**-1*b_p self.P[b][self.A_dict_inv[word[i]]] = b_p**-1*f_p return elif fill: self.define(f, word[i], modified=modified) # otherwise scan is incomplete and yields no information # used in the low-index subgroups algorithm def scan_check(self, alpha, word): r""" Another version of ``scan`` routine, described on, it checks whether `\alpha` scans correctly under `word`, it is a straightforward modification of ``scan``. ``scan_check`` returns ``False`` (rather than calling ``coincidence``) if the scan completes incorrectly; otherwise it returns ``True``. See Also ======== scan, scan_c, scan_and_fill, scan_and_fill_c """ # alpha is an integer representing a "coset" # since scanning can be in two cases # 1. for alpha=0 and w in Y (i.e generating set of H) # 2. alpha in Omega (set of live cosets), w in R (relators) A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table f = alpha i = 0 r = len(word) b = alpha j = r - 1 while i <= j and table[f][A_dict[word[i]]] is not None: f = table[f][A_dict[word[i]]] i += 1 if i > j: return f == b while j >= i and table[b][A_dict_inv[word[j]]] is not None: b = table[b][A_dict_inv[word[j]]] j -= 1 if j < i: # we have an incorrect completed scan with coincidence f ~ b # return False, instead of calling coincidence routine return False elif j == i: # deduction process table[f][A_dict[word[i]]] = b table[b][A_dict_inv[word[i]]] = f return True def merge(self, k, lamda, q, w=None, modified=False): """ Merge two classes with representatives ``k`` and ``lamda``, described on Pg. 157 [1] (for pseudocode), start by putting ``p[k] = lamda``. It is more efficient to choose the new representative from the larger of the two classes being merged, i.e larger among ``k`` and ``lamda``. procedure ``merge`` performs the merging operation, adds the deleted class representative to the queue ``q``. Parameters ========== 'k', 'lamda' being the two class representatives to be merged. Notes ===== Pg. 86-87 [1] contains a description of this method. See Also ======== coincidence, rep """ p = self.p rep = self.rep phi = rep(k, modified=modified) psi = rep(lamda, modified=modified) if phi != psi: mu = min(phi, psi) v = max(phi, psi) p[v] = mu if modified: if v == phi: self.p_p[phi] = self.p_p[k]**-1*w*self.p_p[lamda] else: self.p_p[psi] = self.p_p[lamda]**-1*w**-1*self.p_p[k] q.append(v) def rep(self, k, modified=False): r""" Parameters ========== `k \in [0 \ldots n-1]`, as for ``self`` only array ``p`` is used Returns ======= Representative of the class containing ``k``. Returns the representative of `\sim` class containing ``k``, it also makes some modification to array ``p`` of ``self`` to ease further computations, described on Pg. 157 [1]. The information on classes under `\sim` is stored in array `p` of ``self`` argument, which will always satisfy the property: `p[\alpha] \sim \alpha` and `p[\alpha]=\alpha \iff \alpha=rep(\alpha)` `\forall \in [0 \ldots n-1]`. So, for `\alpha \in [0 \ldots n-1]`, we find `rep(self, \alpha)` by continually replacing `\alpha` by `p[\alpha]` until it becomes constant (i.e satisfies `p[\alpha] = \alpha`):w To increase the efficiency of later ``rep`` calculations, whenever we find `rep(self, \alpha)=\beta`, we set `p[\gamma] = \beta \forall \gamma \in p-chain` from `\alpha` to `\beta` Notes ===== ``rep`` routine is also described on Pg. 85-87 [1] in Atkinson's algorithm, this results from the fact that ``coincidence`` routine introduces functionality similar to that introduced by the ``minimal_block`` routine on Pg. 85-87 [1]. See Also ======== coincidence, merge """ p = self.p lamda = k rho = p[lamda] if modified: s = p[:] while rho != lamda: if modified: s[rho] = lamda lamda = rho rho = p[lamda] if modified: rho = s[lamda] while rho != k: mu = rho rho = s[mu] p[rho] = lamda self.p_p[rho] = self.p_p[rho]*self.p_p[mu] else: mu = k rho = p[mu] while rho != lamda: p[mu] = lamda mu = rho rho = p[mu] return lamda # alpha, beta coincide, i.e. alpha, beta represent the pair of cosets # where coincidence occurs def coincidence(self, alpha, beta, w=None, modified=False): r""" The third situation described in ``scan`` routine is handled by this routine, described on Pg. 156-161 [1]. The unfortunate situation when the scan completes but not correctly, then ``coincidence`` routine is run. i.e when for some `i` with `1 \le i \le r+1`, we have `w=st` with `s = x_1 x_2 \dots x_{i-1}`, `t = x_i x_{i+1} \dots x_r`, and `\beta = \alpha^s` and `\gamma = \alpha^{t-1}` are defined but unequal. This means that `\beta` and `\gamma` represent the same coset of `H` in `G`. Described on Pg. 156 [1]. ``rep`` See Also ======== scan """ A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table # behaves as a queue q = [] if modified: self.modified_merge(alpha, beta, w, q) else: self.merge(alpha, beta, q) while len(q) > 0: gamma = q.pop(0) for x in A_dict: delta = table[gamma][A_dict[x]] if delta is not None: table[delta][A_dict_inv[x]] = None mu = self.rep(gamma, modified=modified) nu = self.rep(delta, modified=modified) if table[mu][A_dict[x]] is not None: if modified: v = self.p_p[delta]**-1*self.P[gamma][self.A_dict[x]]**-1 v = v*self.p_p[gamma]*self.P[mu][self.A_dict[x]] self.modified_merge(nu, table[mu][self.A_dict[x]], v, q) else: self.merge(nu, table[mu][A_dict[x]], q) elif table[nu][A_dict_inv[x]] is not None: if modified: v = self.p_p[gamma]**-1*self.P[gamma][self.A_dict[x]] v = v*self.p_p[delta]*self.P[mu][self.A_dict_inv[x]] self.modified_merge(mu, table[nu][self.A_dict_inv[x]], v, q) else: self.merge(mu, table[nu][A_dict_inv[x]], q) else: table[mu][A_dict[x]] = nu table[nu][A_dict_inv[x]] = mu if modified: v = self.p_p[gamma]**-1*self.P[gamma][self.A_dict[x]]*self.p_p[delta] self.P[mu][self.A_dict[x]] = v self.P[nu][self.A_dict_inv[x]] = v**-1 # method used in the HLT strategy def scan_and_fill(self, alpha, word): """ A modified version of ``scan`` routine used in the relator-based method of coset enumeration, described on pg. 162-163 [1], which follows the idea that whenever the procedure is called and the scan is incomplete then it makes new definitions to enable the scan to complete; i.e it fills in the gaps in the scan of the relator or subgroup generator. """ self.scan(alpha, word, fill=True) def scan_and_fill_c(self, alpha, word): """ A modified version of ``scan`` routine, described on Pg. 165 second para. [1], with modification similar to that of ``scan_anf_fill`` the only difference being it calls the coincidence procedure used in the coset-table based method i.e. the routine ``coincidence_c`` is used. See Also ======== scan, scan_and_fill """ A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table r = len(word) f = alpha i = 0 b = alpha j = r - 1 # loop until it has filled the alpha row in the table. while True: # do the forward scanning while i <= j and table[f][A_dict[word[i]]] is not None: f = table[f][A_dict[word[i]]] i += 1 if i > j: if f != b: self.coincidence_c(f, b) return # forward scan was incomplete, scan backwards while j >= i and table[b][A_dict_inv[word[j]]] is not None: b = table[b][A_dict_inv[word[j]]] j -= 1 if j < i: self.coincidence_c(f, b) elif j == i: table[f][A_dict[word[i]]] = b table[b][A_dict_inv[word[i]]] = f self.deduction_stack.append((f, word[i])) else: self.define_c(f, word[i]) # method used in the HLT strategy def look_ahead(self): """ When combined with the HLT method this is known as HLT+Lookahead method of coset enumeration, described on pg. 164 [1]. Whenever ``define`` aborts due to lack of space available this procedure is executed. This routine helps in recovering space resulting from "coincidence" of cosets. """ R = self.fp_group.relators p = self.p # complete scan all relators under all cosets(obviously live) # without making new definitions for beta in self.omega: for w in R: self.scan(beta, w) if p[beta] < beta: break # Pg. 166 def process_deductions(self, R_c_x, R_c_x_inv): """ Processes the deductions that have been pushed onto ``deduction_stack``, described on Pg. 166 [1] and is used in coset-table based enumeration. See Also ======== deduction_stack """ p = self.p table = self.table while len(self.deduction_stack) > 0: if len(self.deduction_stack) >= CosetTable.max_stack_size: self.look_ahead() del self.deduction_stack[:] continue else: alpha, x = self.deduction_stack.pop() if p[alpha] == alpha: for w in R_c_x: self.scan_c(alpha, w) if p[alpha] < alpha: break beta = table[alpha][self.A_dict[x]] if beta is not None and p[beta] == beta: for w in R_c_x_inv: self.scan_c(beta, w) if p[beta] < beta: break def process_deductions_check(self, R_c_x, R_c_x_inv): """ A variation of ``process_deductions``, this calls ``scan_check`` wherever ``process_deductions`` calls ``scan``, described on Pg. [1]. See Also ======== process_deductions """ table = self.table while len(self.deduction_stack) > 0: alpha, x = self.deduction_stack.pop() for w in R_c_x: if not self.scan_check(alpha, w): return False beta = table[alpha][self.A_dict[x]] if beta is not None: for w in R_c_x_inv: if not self.scan_check(beta, w): return False return True def switch(self, beta, gamma): r"""Switch the elements `\beta, \gamma \in \Omega` of ``self``, used by the ``standardize`` procedure, described on Pg. 167 [1]. See Also ======== standardize """ A = self.A A_dict = self.A_dict table = self.table for x in A: z = table[gamma][A_dict[x]] table[gamma][A_dict[x]] = table[beta][A_dict[x]] table[beta][A_dict[x]] = z for alpha in range(len(self.p)): if self.p[alpha] == alpha: if table[alpha][A_dict[x]] == beta: table[alpha][A_dict[x]] = gamma elif table[alpha][A_dict[x]] == gamma: table[alpha][A_dict[x]] = beta def standardize(self): r""" A coset table is standardized if when running through the cosets and within each coset through the generator images (ignoring generator inverses), the cosets appear in order of the integers `0, 1, \dots, n`. "Standardize" reorders the elements of `\Omega` such that, if we scan the coset table first by elements of `\Omega` and then by elements of A, then the cosets occur in ascending order. ``standardize()`` is used at the end of an enumeration to permute the cosets so that they occur in some sort of standard order. Notes ===== procedure is described on pg. 167-168 [1], it also makes use of the ``switch`` routine to replace by smaller integer value. Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r >>> F, x, y = free_group("x, y") # Example 5.3 from [1] >>> f = FpGroup(F, [x**2*y**2, x**3*y**5]) >>> C = coset_enumeration_r(f, []) >>> C.compress() >>> C.table [[1, 3, 1, 3], [2, 0, 2, 0], [3, 1, 3, 1], [0, 2, 0, 2]] >>> C.standardize() >>> C.table [[1, 2, 1, 2], [3, 0, 3, 0], [0, 3, 0, 3], [2, 1, 2, 1]] """ A = self.A A_dict = self.A_dict gamma = 1 for alpha, x in product(range(self.n), A): beta = self.table[alpha][A_dict[x]] if beta >= gamma: if beta > gamma: self.switch(gamma, beta) gamma += 1 if gamma == self.n: return # Compression of a Coset Table def compress(self): """Removes the non-live cosets from the coset table, described on pg. 167 [1]. """ gamma = -1 A = self.A A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table chi = tuple([i for i in range(len(self.p)) if self.p[i] != i]) for alpha in self.omega: gamma += 1 if gamma != alpha: # replace alpha by gamma in coset table for x in A: beta = table[alpha][A_dict[x]] table[gamma][A_dict[x]] = beta table[beta][A_dict_inv[x]] == gamma # all the cosets in the table are live cosets self.p = list(range(gamma + 1)) # delete the useless columns del table[len(self.p):] # re-define values for row in table: for j in range(len(self.A)): row[j] -= bisect_left(chi, row[j]) def conjugates(self, R): R_c = list(chain.from_iterable((rel.cyclic_conjugates(), \ (rel**-1).cyclic_conjugates()) for rel in R)) R_set = set() for conjugate in R_c: R_set = R_set.union(conjugate) R_c_list = [] for x in self.A: r = {word for word in R_set if word[0] == x} R_c_list.append(r) R_set.difference_update(r) return R_c_list def coset_representative(self, coset): ''' Compute the coset representative of a given coset. Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) >>> C = coset_enumeration_r(f, [x]) >>> C.compress() >>> C.table [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1]] >>> C.coset_representative(0) <identity> >>> C.coset_representative(1) y >>> C.coset_representative(2) y**-1 ''' for x in self.A: gamma = self.table[coset][self.A_dict[x]] if coset == 0: return self.fp_group.identity if gamma < coset: return self.coset_representative(gamma)*x**-1 ############################## # Modified Methods # ############################## def modified_define(self, alpha, x): r""" Define a function p_p from from [1..n] to A* as an additional component of the modified coset table. Parameters ========== \alpha \in \Omega x \in A* See Also ======== define """ self.define(alpha, x, modified=True) def modified_scan(self, alpha, w, y, fill=False): r""" Parameters ========== \alpha \in \Omega w \in A* y \in (YUY^-1) fill -- `modified_scan_and_fill` when set to True. See Also ======== scan """ self.scan(alpha, w, y=y, fill=fill, modified=True) def modified_scan_and_fill(self, alpha, w, y): self.modified_scan(alpha, w, y, fill=True) def modified_merge(self, k, lamda, w, q): r""" Parameters ========== 'k', 'lamda' -- the two class representatives to be merged. q -- queue of length l of elements to be deleted from `\Omega` *. w -- Word in (YUY^-1) See Also ======== merge """ self.merge(k, lamda, q, w=w, modified=True) def modified_rep(self, k): r""" Parameters ========== `k \in [0 \ldots n-1]` See Also ======== rep """ self.rep(k, modified=True) def modified_coincidence(self, alpha, beta, w): r""" Parameters ========== A coincident pair `\alpha, \beta \in \Omega, w \in Y \cup Y^{-1}` See Also ======== coincidence """ self.coincidence(alpha, beta, w=w, modified=True) ############################################################################### # COSET ENUMERATION # ############################################################################### # relator-based method def coset_enumeration_r(fp_grp, Y, max_cosets=None, draft=None, incomplete=False, modified=False): """ This is easier of the two implemented methods of coset enumeration. and is often called the HLT method, after Hazelgrove, Leech, Trotter The idea is that we make use of ``scan_and_fill`` makes new definitions whenever the scan is incomplete to enable the scan to complete; this way we fill in the gaps in the scan of the relator or subgroup generator, that's why the name relator-based method. An instance of `CosetTable` for `fp_grp` can be passed as the keyword argument `draft` in which case the coset enumeration will start with that instance and attempt to complete it. When `incomplete` is `True` and the function is unable to complete for some reason, the partially complete table will be returned. # TODO: complete the docstring See Also ======== scan_and_fill, Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r >>> F, x, y = free_group("x, y") # Example 5.1 from [1] >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) >>> C = coset_enumeration_r(f, [x]) >>> for i in range(len(C.p)): ... if C.p[i] == i: ... print(C.table[i]) [0, 0, 1, 2] [1, 1, 2, 0] [2, 2, 0, 1] >>> C.p [0, 1, 2, 1, 1] # Example from exercises Q2 [1] >>> f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3]) >>> C = coset_enumeration_r(f, []) >>> C.compress(); C.standardize() >>> C.table [[1, 2, 3, 4], [5, 0, 6, 7], [0, 5, 7, 6], [7, 6, 5, 0], [6, 7, 0, 5], [2, 1, 4, 3], [3, 4, 2, 1], [4, 3, 1, 2]] # Example 5.2 >>> f = FpGroup(F, [x**2, y**3, (x*y)**3]) >>> Y = [x*y] >>> C = coset_enumeration_r(f, Y) >>> for i in range(len(C.p)): ... if C.p[i] == i: ... print(C.table[i]) [1, 1, 2, 1] [0, 0, 0, 2] [3, 3, 1, 0] [2, 2, 3, 3] # Example 5.3 >>> f = FpGroup(F, [x**2*y**2, x**3*y**5]) >>> Y = [] >>> C = coset_enumeration_r(f, Y) >>> for i in range(len(C.p)): ... if C.p[i] == i: ... print(C.table[i]) [1, 3, 1, 3] [2, 0, 2, 0] [3, 1, 3, 1] [0, 2, 0, 2] # Example 5.4 >>> F, a, b, c, d, e = free_group("a, b, c, d, e") >>> f = FpGroup(F, [a*b*c**-1, b*c*d**-1, c*d*e**-1, d*e*a**-1, e*a*b**-1]) >>> Y = [a] >>> C = coset_enumeration_r(f, Y) >>> for i in range(len(C.p)): ... if C.p[i] == i: ... print(C.table[i]) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # example of "compress" method >>> C.compress() >>> C.table [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] # Exercises Pg. 161, Q2. >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3]) >>> Y = [] >>> C = coset_enumeration_r(f, Y) >>> C.compress() >>> C.standardize() >>> C.table [[1, 2, 3, 4], [5, 0, 6, 7], [0, 5, 7, 6], [7, 6, 5, 0], [6, 7, 0, 5], [2, 1, 4, 3], [3, 4, 2, 1], [4, 3, 1, 2]] # John J. Cannon; Lucien A. Dimino; George Havas; Jane M. Watson # Mathematics of Computation, Vol. 27, No. 123. (Jul., 1973), pp. 463-490 # from 1973chwd.pdf # Table 1. Ex. 1 >>> F, r, s, t = free_group("r, s, t") >>> E1 = FpGroup(F, [t**-1*r*t*r**-2, r**-1*s*r*s**-2, s**-1*t*s*t**-2]) >>> C = coset_enumeration_r(E1, [r]) >>> for i in range(len(C.p)): ... if C.p[i] == i: ... print(C.table[i]) [0, 0, 0, 0, 0, 0] Ex. 2 >>> F, a, b = free_group("a, b") >>> Cox = FpGroup(F, [a**6, b**6, (a*b)**2, (a**2*b**2)**2, (a**3*b**3)**5]) >>> C = coset_enumeration_r(Cox, [a]) >>> index = 0 >>> for i in range(len(C.p)): ... if C.p[i] == i: ... index += 1 >>> index 500 # Ex. 3 >>> F, a, b = free_group("a, b") >>> B_2_4 = FpGroup(F, [a**4, b**4, (a*b)**4, (a**-1*b)**4, (a**2*b)**4, \ (a*b**2)**4, (a**2*b**2)**4, (a**-1*b*a*b)**4, (a*b**-1*a*b)**4]) >>> C = coset_enumeration_r(B_2_4, [a]) >>> index = 0 >>> for i in range(len(C.p)): ... if C.p[i] == i: ... index += 1 >>> index 1024 References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory" """ # 1. Initialize a coset table C for < X|R > C = CosetTable(fp_grp, Y, max_cosets=max_cosets) # Define coset table methods. if modified: _scan_and_fill = C.modified_scan_and_fill _define = C.modified_define else: _scan_and_fill = C.scan_and_fill _define = C.define if draft: C.table = draft.table[:] C.p = draft.p[:] R = fp_grp.relators A_dict = C.A_dict p = C.p for i in range(0, len(Y)): if modified: _scan_and_fill(0, Y[i], C._grp.generators[i]) else: _scan_and_fill(0, Y[i]) alpha = 0 while alpha < C.n: if p[alpha] == alpha: try: for w in R: if modified: _scan_and_fill(alpha, w, C._grp.identity) else: _scan_and_fill(alpha, w) # if alpha was eliminated during the scan then break if p[alpha] < alpha: break if p[alpha] == alpha: for x in A_dict: if C.table[alpha][A_dict[x]] is None: _define(alpha, x) except ValueError as e: if incomplete: return C raise e alpha += 1 return C def modified_coset_enumeration_r(fp_grp, Y, max_cosets=None, draft=None, incomplete=False): r""" Introduce a new set of symbols y \in Y that correspond to the generators of the subgroup. Store the elements of Y as a word P[\alpha, x] and compute the coset table similar to that of the regular coset enumeration methods. Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup >>> from sympy.combinatorics.coset_table import modified_coset_enumeration_r >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) >>> C = modified_coset_enumeration_r(f, [x]) >>> C.table [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1], [None, 1, None, None], [1, 3, None, None]] See Also ======== coset_enumertation_r References ========== .. [1] Holt, D., Eick, B., O'Brien, E., "Handbook of Computational Group Theory", Section 5.3.2 """ return coset_enumeration_r(fp_grp, Y, max_cosets=max_cosets, draft=draft, incomplete=incomplete, modified=True) # Pg. 166 # coset-table based method def coset_enumeration_c(fp_grp, Y, max_cosets=None, draft=None, incomplete=False): """ >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_c >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) >>> C = coset_enumeration_c(f, [x]) >>> C.table [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1]] """ # Initialize a coset table C for < X|R > X = fp_grp.generators R = fp_grp.relators C = CosetTable(fp_grp, Y, max_cosets=max_cosets) if draft: C.table = draft.table[:] C.p = draft.p[:] C.deduction_stack = draft.deduction_stack for alpha, x in product(range(len(C.table)), X): if C.table[alpha][C.A_dict[x]] is not None: C.deduction_stack.append((alpha, x)) A = C.A # replace all the elements by cyclic reductions R_cyc_red = [rel.identity_cyclic_reduction() for rel in R] R_c = list(chain.from_iterable((rel.cyclic_conjugates(), (rel**-1).cyclic_conjugates()) \ for rel in R_cyc_red)) R_set = set() for conjugate in R_c: R_set = R_set.union(conjugate) # a list of subsets of R_c whose words start with "x". R_c_list = [] for x in C.A: r = {word for word in R_set if word[0] == x} R_c_list.append(r) R_set.difference_update(r) for w in Y: C.scan_and_fill_c(0, w) for x in A: C.process_deductions(R_c_list[C.A_dict[x]], R_c_list[C.A_dict_inv[x]]) alpha = 0 while alpha < len(C.table): if C.p[alpha] == alpha: try: for x in C.A: if C.p[alpha] != alpha: break if C.table[alpha][C.A_dict[x]] is None: C.define_c(alpha, x) C.process_deductions(R_c_list[C.A_dict[x]], R_c_list[C.A_dict_inv[x]]) except ValueError as e: if incomplete: return C raise e alpha += 1 return C
bf069204a5e613d329e8b4ca4835709193f6d96f585c31b3412d2950c7ae1aa4
from sympy.core import Basic from sympy.core.containers import Tuple from sympy.tensor.array import Array from sympy.core.sympify import _sympify from sympy.utilities.iterables import flatten, iterable from sympy.utilities.misc import as_int from collections import defaultdict class Prufer(Basic): """ The Prufer correspondence is an algorithm that describes the bijection between labeled trees and the Prufer code. A Prufer code of a labeled tree is unique up to isomorphism and has a length of n - 2. Prufer sequences were first used by Heinz Prufer to give a proof of Cayley's formula. References ========== .. [1] http://mathworld.wolfram.com/LabeledTree.html """ _prufer_repr = None _tree_repr = None _nodes = None _rank = None @property def prufer_repr(self): """Returns Prufer sequence for the Prufer object. This sequence is found by removing the highest numbered vertex, recording the node it was attached to, and continuing until only two vertices remain. The Prufer sequence is the list of recorded nodes. Examples ======== >>> from sympy.combinatorics.prufer import Prufer >>> Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]).prufer_repr [3, 3, 3, 4] >>> Prufer([1, 0, 0]).prufer_repr [1, 0, 0] See Also ======== to_prufer """ if self._prufer_repr is None: self._prufer_repr = self.to_prufer(self._tree_repr[:], self.nodes) return self._prufer_repr @property def tree_repr(self): """Returns the tree representation of the Prufer object. Examples ======== >>> from sympy.combinatorics.prufer import Prufer >>> Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]).tree_repr [[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]] >>> Prufer([1, 0, 0]).tree_repr [[1, 2], [0, 1], [0, 3], [0, 4]] See Also ======== to_tree """ if self._tree_repr is None: self._tree_repr = self.to_tree(self._prufer_repr[:]) return self._tree_repr @property def nodes(self): """Returns the number of nodes in the tree. Examples ======== >>> from sympy.combinatorics.prufer import Prufer >>> Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]).nodes 6 >>> Prufer([1, 0, 0]).nodes 5 """ return self._nodes @property def rank(self): """Returns the rank of the Prufer sequence. Examples ======== >>> from sympy.combinatorics.prufer import Prufer >>> p = Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]) >>> p.rank 778 >>> p.next(1).rank 779 >>> p.prev().rank 777 See Also ======== prufer_rank, next, prev, size """ if self._rank is None: self._rank = self.prufer_rank() return self._rank @property def size(self): """Return the number of possible trees of this Prufer object. Examples ======== >>> from sympy.combinatorics.prufer import Prufer >>> Prufer([0]*4).size == Prufer([6]*4).size == 1296 True See Also ======== prufer_rank, rank, next, prev """ return self.prev(self.rank).prev().rank + 1 @staticmethod def to_prufer(tree, n): """Return the Prufer sequence for a tree given as a list of edges where ``n`` is the number of nodes in the tree. Examples ======== >>> from sympy.combinatorics.prufer import Prufer >>> a = Prufer([[0, 1], [0, 2], [0, 3]]) >>> a.prufer_repr [0, 0] >>> Prufer.to_prufer([[0, 1], [0, 2], [0, 3]], 4) [0, 0] See Also ======== prufer_repr: returns Prufer sequence of a Prufer object. """ d = defaultdict(int) L = [] for edge in tree: # Increment the value of the corresponding # node in the degree list as we encounter an # edge involving it. d[edge[0]] += 1 d[edge[1]] += 1 for i in range(n - 2): # find the smallest leaf for x in range(n): if d[x] == 1: break # find the node it was connected to y = None for edge in tree: if x == edge[0]: y = edge[1] elif x == edge[1]: y = edge[0] if y is not None: break # record and update L.append(y) for j in (x, y): d[j] -= 1 if not d[j]: d.pop(j) tree.remove(edge) return L @staticmethod def to_tree(prufer): """Return the tree (as a list of edges) of the given Prufer sequence. Examples ======== >>> from sympy.combinatorics.prufer import Prufer >>> a = Prufer([0, 2], 4) >>> a.tree_repr [[0, 1], [0, 2], [2, 3]] >>> Prufer.to_tree([0, 2]) [[0, 1], [0, 2], [2, 3]] References ========== .. [1] https://hamberg.no/erlend/posts/2010-11-06-prufer-sequence-compact-tree-representation.html See Also ======== tree_repr: returns tree representation of a Prufer object. """ tree = [] last = [] n = len(prufer) + 2 d = defaultdict(lambda: 1) for p in prufer: d[p] += 1 for i in prufer: for j in range(n): # find the smallest leaf (degree = 1) if d[j] == 1: break # (i, j) is the new edge that we append to the tree # and remove from the degree dictionary d[i] -= 1 d[j] -= 1 tree.append(sorted([i, j])) last = [i for i in range(n) if d[i] == 1] or [0, 1] tree.append(last) return tree @staticmethod def edges(*runs): """Return a list of edges and the number of nodes from the given runs that connect nodes in an integer-labelled tree. All node numbers will be shifted so that the minimum node is 0. It is not a problem if edges are repeated in the runs; only unique edges are returned. There is no assumption made about what the range of the node labels should be, but all nodes from the smallest through the largest must be present. Examples ======== >>> from sympy.combinatorics.prufer import Prufer >>> Prufer.edges([1, 2, 3], [2, 4, 5]) # a T ([[0, 1], [1, 2], [1, 3], [3, 4]], 5) Duplicate edges are removed: >>> Prufer.edges([0, 1, 2, 3], [1, 4, 5], [1, 4, 6]) # a K ([[0, 1], [1, 2], [1, 4], [2, 3], [4, 5], [4, 6]], 7) """ e = set() nmin = runs[0][0] for r in runs: for i in range(len(r) - 1): a, b = r[i: i + 2] if b < a: a, b = b, a e.add((a, b)) rv = [] got = set() nmin = nmax = None for ei in e: for i in ei: got.add(i) nmin = min(ei[0], nmin) if nmin is not None else ei[0] nmax = max(ei[1], nmax) if nmax is not None else ei[1] rv.append(list(ei)) missing = set(range(nmin, nmax + 1)) - got if missing: missing = [i + nmin for i in missing] if len(missing) == 1: msg = 'Node %s is missing.' % missing.pop() else: msg = 'Nodes %s are missing.' % list(sorted(missing)) raise ValueError(msg) if nmin != 0: for i, ei in enumerate(rv): rv[i] = [n - nmin for n in ei] nmax -= nmin return sorted(rv), nmax + 1 def prufer_rank(self): """Computes the rank of a Prufer sequence. Examples ======== >>> from sympy.combinatorics.prufer import Prufer >>> a = Prufer([[0, 1], [0, 2], [0, 3]]) >>> a.prufer_rank() 0 See Also ======== rank, next, prev, size """ r = 0 p = 1 for i in range(self.nodes - 3, -1, -1): r += p*self.prufer_repr[i] p *= self.nodes return r @classmethod def unrank(self, rank, n): """Finds the unranked Prufer sequence. Examples ======== >>> from sympy.combinatorics.prufer import Prufer >>> Prufer.unrank(0, 4) Prufer([0, 0]) """ n, rank = as_int(n), as_int(rank) L = defaultdict(int) for i in range(n - 3, -1, -1): L[i] = rank % n rank = (rank - L[i])//n return Prufer([L[i] for i in range(len(L))]) def __new__(cls, *args, **kw_args): """The constructor for the Prufer object. Examples ======== >>> from sympy.combinatorics.prufer import Prufer A Prufer object can be constructed from a list of edges: >>> a = Prufer([[0, 1], [0, 2], [0, 3]]) >>> a.prufer_repr [0, 0] If the number of nodes is given, no checking of the nodes will be performed; it will be assumed that nodes 0 through n - 1 are present: >>> Prufer([[0, 1], [0, 2], [0, 3]], 4) Prufer([[0, 1], [0, 2], [0, 3]], 4) A Prufer object can be constructed from a Prufer sequence: >>> b = Prufer([1, 3]) >>> b.tree_repr [[0, 1], [1, 3], [2, 3]] """ arg0 = Array(args[0]) if args[0] else Tuple() args = (arg0,) + tuple(_sympify(arg) for arg in args[1:]) ret_obj = Basic.__new__(cls, *args, **kw_args) args = [list(args[0])] if args[0] and iterable(args[0][0]): if not args[0][0]: raise ValueError( 'Prufer expects at least one edge in the tree.') if len(args) > 1: nnodes = args[1] else: nodes = set(flatten(args[0])) nnodes = max(nodes) + 1 if nnodes != len(nodes): missing = set(range(nnodes)) - nodes if len(missing) == 1: msg = 'Node %s is missing.' % missing.pop() else: msg = 'Nodes %s are missing.' % list(sorted(missing)) raise ValueError(msg) ret_obj._tree_repr = [list(i) for i in args[0]] ret_obj._nodes = nnodes else: ret_obj._prufer_repr = args[0] ret_obj._nodes = len(ret_obj._prufer_repr) + 2 return ret_obj def next(self, delta=1): """Generates the Prufer sequence that is delta beyond the current one. Examples ======== >>> from sympy.combinatorics.prufer import Prufer >>> a = Prufer([[0, 1], [0, 2], [0, 3]]) >>> b = a.next(1) # == a.next() >>> b.tree_repr [[0, 2], [0, 1], [1, 3]] >>> b.rank 1 See Also ======== prufer_rank, rank, prev, size """ return Prufer.unrank(self.rank + delta, self.nodes) def prev(self, delta=1): """Generates the Prufer sequence that is -delta before the current one. Examples ======== >>> from sympy.combinatorics.prufer import Prufer >>> a = Prufer([[0, 1], [1, 2], [2, 3], [1, 4]]) >>> a.rank 36 >>> b = a.prev() >>> b Prufer([1, 2, 0]) >>> b.rank 35 See Also ======== prufer_rank, rank, next, size """ return Prufer.unrank(self.rank -delta, self.nodes)
aca62d2d1139e252ce8a7e1705794cb0dc99c997cbcffa98fa8197ab3aff043d
"""Finitely Presented Groups and its algorithms. """ from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.combinatorics.free_groups import (FreeGroup, FreeGroupElement, free_group) from sympy.combinatorics.rewritingsystem import RewritingSystem from sympy.combinatorics.coset_table import (CosetTable, coset_enumeration_r, coset_enumeration_c) from sympy.combinatorics import PermutationGroup from sympy.printing.defaults import DefaultPrinting from sympy.utilities import public from sympy.utilities.magic import pollute from itertools import product @public def fp_group(fr_grp, relators=()): _fp_group = FpGroup(fr_grp, relators) return (_fp_group,) + tuple(_fp_group._generators) @public def xfp_group(fr_grp, relators=()): _fp_group = FpGroup(fr_grp, relators) return (_fp_group, _fp_group._generators) # Does not work. Both symbols and pollute are undefined. Never tested. @public def vfp_group(fr_grpm, relators): _fp_group = FpGroup(symbols, relators) pollute([sym.name for sym in _fp_group.symbols], _fp_group.generators) return _fp_group def _parse_relators(rels): """Parse the passed relators.""" return rels ############################################################################### # FINITELY PRESENTED GROUPS # ############################################################################### class FpGroup(DefaultPrinting): """ The FpGroup would take a FreeGroup and a list/tuple of relators, the relators would be specified in such a way that each of them be equal to the identity of the provided free group. """ is_group = True is_FpGroup = True is_PermutationGroup = False def __init__(self, fr_grp, relators): relators = _parse_relators(relators) self.free_group = fr_grp self.relators = relators self.generators = self._generators() self.dtype = type("FpGroupElement", (FpGroupElement,), {"group": self}) # CosetTable instance on identity subgroup self._coset_table = None # returns whether coset table on identity subgroup # has been standardized self._is_standardized = False self._order = None self._center = None self._rewriting_system = RewritingSystem(self) self._perm_isomorphism = None return def _generators(self): return self.free_group.generators def make_confluent(self): ''' Try to make the group's rewriting system confluent ''' self._rewriting_system.make_confluent() return def reduce(self, word): ''' Return the reduced form of `word` in `self` according to the group's rewriting system. If it's confluent, the reduced form is the unique normal form of the word in the group. ''' return self._rewriting_system.reduce(word) def equals(self, word1, word2): ''' Compare `word1` and `word2` for equality in the group using the group's rewriting system. If the system is confluent, the returned answer is necessarily correct. (If it isn't, `False` could be returned in some cases where in fact `word1 == word2`) ''' if self.reduce(word1*word2**-1) == self.identity: return True elif self._rewriting_system.is_confluent: return False return None @property def identity(self): return self.free_group.identity def __contains__(self, g): return g in self.free_group def subgroup(self, gens, C=None, homomorphism=False): ''' Return the subgroup generated by `gens` using the Reidemeister-Schreier algorithm homomorphism -- When set to True, return a dictionary containing the images of the presentation generators in the original group. Examples ======== >>> from sympy.combinatorics.fp_groups import FpGroup >>> from sympy.combinatorics.free_groups import free_group >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**3, y**5, (x*y)**2]) >>> H = [x*y, x**-1*y**-1*x*y*x] >>> K, T = f.subgroup(H, homomorphism=True) >>> T(K.generators) [x*y, x**-1*y**2*x**-1] ''' if not all(isinstance(g, FreeGroupElement) for g in gens): raise ValueError("Generators must be `FreeGroupElement`s") if not all(g.group == self.free_group for g in gens): raise ValueError("Given generators are not members of the group") if homomorphism: g, rels, _gens = reidemeister_presentation(self, gens, C=C, homomorphism=True) else: g, rels = reidemeister_presentation(self, gens, C=C) if g: g = FpGroup(g[0].group, rels) else: g = FpGroup(free_group('')[0], []) if homomorphism: from sympy.combinatorics.homomorphisms import homomorphism return g, homomorphism(g, self, g.generators, _gens, check=False) return g def coset_enumeration(self, H, strategy="relator_based", max_cosets=None, draft=None, incomplete=False): """ Return an instance of ``coset table``, when Todd-Coxeter algorithm is run over the ``self`` with ``H`` as subgroup, using ``strategy`` argument as strategy. The returned coset table is compressed but not standardized. An instance of `CosetTable` for `fp_grp` can be passed as the keyword argument `draft` in which case the coset enumeration will start with that instance and attempt to complete it. When `incomplete` is `True` and the function is unable to complete for some reason, the partially complete table will be returned. """ if not max_cosets: max_cosets = CosetTable.coset_table_max_limit if strategy == 'relator_based': C = coset_enumeration_r(self, H, max_cosets=max_cosets, draft=draft, incomplete=incomplete) else: C = coset_enumeration_c(self, H, max_cosets=max_cosets, draft=draft, incomplete=incomplete) if C.is_complete(): C.compress() return C def standardize_coset_table(self): """ Standardized the coset table ``self`` and makes the internal variable ``_is_standardized`` equal to ``True``. """ self._coset_table.standardize() self._is_standardized = True def coset_table(self, H, strategy="relator_based", max_cosets=None, draft=None, incomplete=False): """ Return the mathematical coset table of ``self`` in ``H``. """ if not H: if self._coset_table is not None: if not self._is_standardized: self.standardize_coset_table() else: C = self.coset_enumeration([], strategy, max_cosets=max_cosets, draft=draft, incomplete=incomplete) self._coset_table = C self.standardize_coset_table() return self._coset_table.table else: C = self.coset_enumeration(H, strategy, max_cosets=max_cosets, draft=draft, incomplete=incomplete) C.standardize() return C.table def order(self, strategy="relator_based"): """ Returns the order of the finitely presented group ``self``. It uses the coset enumeration with identity group as subgroup, i.e ``H=[]``. Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x, y**2]) >>> f.order(strategy="coset_table_based") 2 """ from sympy.polys.polytools import gcd if self._order is not None: return self._order if self._coset_table is not None: self._order = len(self._coset_table.table) elif len(self.relators) == 0: self._order = self.free_group.order() elif len(self.generators) == 1: self._order = abs(gcd([r.array_form[0][1] for r in self.relators])) elif self._is_infinite(): self._order = S.Infinity else: gens, C = self._finite_index_subgroup() if C: ind = len(C.table) self._order = ind*self.subgroup(gens, C=C).order() else: self._order = self.index([]) return self._order def _is_infinite(self): ''' Test if the group is infinite. Return `True` if the test succeeds and `None` otherwise ''' used_gens = set() for r in self.relators: used_gens.update(r.contains_generators()) if not set(self.generators) <= used_gens: return True # Abelianisation test: check is the abelianisation is infinite abelian_rels = [] from sympy.matrices.normalforms import invariant_factors from sympy.matrices import Matrix for rel in self.relators: abelian_rels.append([rel.exponent_sum(g) for g in self.generators]) m = Matrix(Matrix(abelian_rels)) if 0 in invariant_factors(m): return True else: return None def _finite_index_subgroup(self, s=None): ''' Find the elements of `self` that generate a finite index subgroup and, if found, return the list of elements and the coset table of `self` by the subgroup, otherwise return `(None, None)` ''' gen = self.most_frequent_generator() rels = list(self.generators) rels.extend(self.relators) if not s: if len(self.generators) == 2: s = [gen] + [g for g in self.generators if g != gen] else: rand = self.free_group.identity i = 0 while ((rand in rels or rand**-1 in rels or rand.is_identity) and i<10): rand = self.random() i += 1 s = [gen, rand] + [g for g in self.generators if g != gen] mid = (len(s)+1)//2 half1 = s[:mid] half2 = s[mid:] draft1 = None draft2 = None m = 200 C = None while not C and (m/2 < CosetTable.coset_table_max_limit): m = min(m, CosetTable.coset_table_max_limit) draft1 = self.coset_enumeration(half1, max_cosets=m, draft=draft1, incomplete=True) if draft1.is_complete(): C = draft1 half = half1 else: draft2 = self.coset_enumeration(half2, max_cosets=m, draft=draft2, incomplete=True) if draft2.is_complete(): C = draft2 half = half2 if not C: m *= 2 if not C: return None, None C.compress() return half, C def most_frequent_generator(self): gens = self.generators rels = self.relators freqs = [sum([r.generator_count(g) for r in rels]) for g in gens] return gens[freqs.index(max(freqs))] def random(self): import random r = self.free_group.identity for i in range(random.randint(2,3)): r = r*random.choice(self.generators)**random.choice([1,-1]) return r def index(self, H, strategy="relator_based"): """ Return the index of subgroup ``H`` in group ``self``. Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**5, y**4, y*x*y**3*x**3]) >>> f.index([x]) 4 """ # TODO: use |G:H| = |G|/|H| (currently H can't be made into a group) # when we know |G| and |H| if H == []: return self.order() else: C = self.coset_enumeration(H, strategy) return len(C.table) def __str__(self): if self.free_group.rank > 30: str_form = "<fp group with %s generators>" % self.free_group.rank else: str_form = "<fp group on the generators %s>" % str(self.generators) return str_form __repr__ = __str__ #============================================================================== # PERMUTATION GROUP METHODS #============================================================================== def _to_perm_group(self): ''' Return an isomorphic permutation group and the isomorphism. The implementation is dependent on coset enumeration so will only terminate for finite groups. ''' from sympy.combinatorics import Permutation from sympy.combinatorics.homomorphisms import homomorphism if self.order() is S.Infinity: raise NotImplementedError("Permutation presentation of infinite " "groups is not implemented") if self._perm_isomorphism: T = self._perm_isomorphism P = T.image() else: C = self.coset_table([]) gens = self.generators images = [[C[i][2*gens.index(g)] for i in range(len(C))] for g in gens] images = [Permutation(i) for i in images] P = PermutationGroup(images) T = homomorphism(self, P, gens, images, check=False) self._perm_isomorphism = T return P, T def _perm_group_list(self, method_name, *args): ''' Given the name of a `PermutationGroup` method (returning a subgroup or a list of subgroups) and (optionally) additional arguments it takes, return a list or a list of lists containing the generators of this (or these) subgroups in terms of the generators of `self`. ''' P, T = self._to_perm_group() perm_result = getattr(P, method_name)(*args) single = False if isinstance(perm_result, PermutationGroup): perm_result, single = [perm_result], True result = [] for group in perm_result: gens = group.generators result.append(T.invert(gens)) return result[0] if single else result def derived_series(self): ''' Return the list of lists containing the generators of the subgroups in the derived series of `self`. ''' return self._perm_group_list('derived_series') def lower_central_series(self): ''' Return the list of lists containing the generators of the subgroups in the lower central series of `self`. ''' return self._perm_group_list('lower_central_series') def center(self): ''' Return the list of generators of the center of `self`. ''' return self._perm_group_list('center') def derived_subgroup(self): ''' Return the list of generators of the derived subgroup of `self`. ''' return self._perm_group_list('derived_subgroup') def centralizer(self, other): ''' Return the list of generators of the centralizer of `other` (a list of elements of `self`) in `self`. ''' T = self._to_perm_group()[1] other = T(other) return self._perm_group_list('centralizer', other) def normal_closure(self, other): ''' Return the list of generators of the normal closure of `other` (a list of elements of `self`) in `self`. ''' T = self._to_perm_group()[1] other = T(other) return self._perm_group_list('normal_closure', other) def _perm_property(self, attr): ''' Given an attribute of a `PermutationGroup`, return its value for a permutation group isomorphic to `self`. ''' P = self._to_perm_group()[0] return getattr(P, attr) @property def is_abelian(self): ''' Check if `self` is abelian. ''' return self._perm_property("is_abelian") @property def is_nilpotent(self): ''' Check if `self` is nilpotent. ''' return self._perm_property("is_nilpotent") @property def is_solvable(self): ''' Check if `self` is solvable. ''' return self._perm_property("is_solvable") @property def elements(self): ''' List the elements of `self`. ''' P, T = self._to_perm_group() return T.invert(P._elements) @property def is_cyclic(self): """ Return ``True`` if group is Cyclic. """ if len(self.generators) <= 1: return True try: P, T = self._to_perm_group() except NotImplementedError: raise NotImplementedError("Check for infinite Cyclic group " "is not implemented") return P.is_cyclic def abelian_invariants(self): """ Return Abelian Invariants of a group. """ try: P, T = self._to_perm_group() except NotImplementedError: raise NotImplementedError("abelian invariants is not implemented" "for infinite group") return P.abelian_invariants() def composition_series(self): """ Return subnormal series of maximum length for a group. """ try: P, T = self._to_perm_group() except NotImplementedError: raise NotImplementedError("composition series is not implemented" "for infinite group") return P.composition_series() class FpSubgroup(DefaultPrinting): ''' The class implementing a subgroup of an FpGroup or a FreeGroup (only finite index subgroups are supported at this point). This is to be used if one wishes to check if an element of the original group belongs to the subgroup ''' def __init__(self, G, gens, normal=False): super().__init__() self.parent = G self.generators = list({g for g in gens if g != G.identity}) self._min_words = None #for use in __contains__ self.C = None self.normal = normal def __contains__(self, g): if isinstance(self.parent, FreeGroup): if self._min_words is None: # make _min_words - a list of subwords such that # g is in the subgroup if and only if it can be # partitioned into these subwords. Infinite families of # subwords are presented by tuples, e.g. (r, w) # stands for the family of subwords r*w**n*r**-1 def _process(w): # this is to be used before adding new words # into _min_words; if the word w is not cyclically # reduced, it will generate an infinite family of # subwords so should be written as a tuple; # if it is, w**-1 should be added to the list # as well p, r = w.cyclic_reduction(removed=True) if not r.is_identity: return [(r, p)] else: return [w, w**-1] # make the initial list gens = [] for w in self.generators: if self.normal: w = w.cyclic_reduction() gens.extend(_process(w)) for w1 in gens: for w2 in gens: # if w1 and w2 are equal or are inverses, continue if w1 == w2 or (not isinstance(w1, tuple) and w1**-1 == w2): continue # if the start of one word is the inverse of the # end of the other, their multiple should be added # to _min_words because of cancellation if isinstance(w1, tuple): # start, end s1, s2 = w1[0][0], w1[0][0]**-1 else: s1, s2 = w1[0], w1[len(w1)-1] if isinstance(w2, tuple): # start, end r1, r2 = w2[0][0], w2[0][0]**-1 else: r1, r2 = w2[0], w2[len(w1)-1] # p1 and p2 are w1 and w2 or, in case when # w1 or w2 is an infinite family, a representative p1, p2 = w1, w2 if isinstance(w1, tuple): p1 = w1[0]*w1[1]*w1[0]**-1 if isinstance(w2, tuple): p2 = w2[0]*w2[1]*w2[0]**-1 # add the product of the words to the list is necessary if r1**-1 == s2 and not (p1*p2).is_identity: new = _process(p1*p2) if new not in gens: gens.extend(new) if r2**-1 == s1 and not (p2*p1).is_identity: new = _process(p2*p1) if new not in gens: gens.extend(new) self._min_words = gens min_words = self._min_words def _is_subword(w): # check if w is a word in _min_words or one of # the infinite families in it w, r = w.cyclic_reduction(removed=True) if r.is_identity or self.normal: return w in min_words else: t = [s[1] for s in min_words if isinstance(s, tuple) and s[0] == r] return [s for s in t if w.power_of(s)] != [] # store the solution of words for which the result of # _word_break (below) is known known = {} def _word_break(w): # check if w can be written as a product of words # in min_words if len(w) == 0: return True i = 0 while i < len(w): i += 1 prefix = w.subword(0, i) if not _is_subword(prefix): continue rest = w.subword(i, len(w)) if rest not in known: known[rest] = _word_break(rest) if known[rest]: return True return False if self.normal: g = g.cyclic_reduction() return _word_break(g) else: if self.C is None: C = self.parent.coset_enumeration(self.generators) self.C = C i = 0 C = self.C for j in range(len(g)): i = C.table[i][C.A_dict[g[j]]] return i == 0 def order(self): if not self.generators: return S.One if isinstance(self.parent, FreeGroup): return S.Infinity if self.C is None: C = self.parent.coset_enumeration(self.generators) self.C = C # This is valid because `len(self.C.table)` (the index of the subgroup) # will always be finite - otherwise coset enumeration doesn't terminate return self.parent.order()/len(self.C.table) def to_FpGroup(self): if isinstance(self.parent, FreeGroup): gen_syms = [('x_%d'%i) for i in range(len(self.generators))] return free_group(', '.join(gen_syms))[0] return self.parent.subgroup(C=self.C) def __str__(self): if len(self.generators) > 30: str_form = "<fp subgroup with %s generators>" % len(self.generators) else: str_form = "<fp subgroup on the generators %s>" % str(self.generators) return str_form __repr__ = __str__ ############################################################################### # LOW INDEX SUBGROUPS # ############################################################################### def low_index_subgroups(G, N, Y=()): """ Implements the Low Index Subgroups algorithm, i.e find all subgroups of ``G`` upto a given index ``N``. This implements the method described in [Sim94]. This procedure involves a backtrack search over incomplete Coset Tables, rather than over forced coincidences. Parameters ========== G: An FpGroup < X|R > N: positive integer, representing the maximum index value for subgroups Y: (an optional argument) specifying a list of subgroup generators, such that each of the resulting subgroup contains the subgroup generated by Y. Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, low_index_subgroups >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**2, y**3, (x*y)**4]) >>> L = low_index_subgroups(f, 4) >>> for coset_table in L: ... print(coset_table.table) [[0, 0, 0, 0]] [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 3, 3]] [[0, 0, 1, 2], [2, 2, 2, 0], [1, 1, 0, 1]] [[1, 1, 0, 0], [0, 0, 1, 1]] References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" Section 5.4 .. [2] Marston Conder and Peter Dobcsanyi "Applications and Adaptions of the Low Index Subgroups Procedure" """ C = CosetTable(G, []) R = G.relators # length chosen for the length of the short relators len_short_rel = 5 # elements of R2 only checked at the last step for complete # coset tables R2 = {rel for rel in R if len(rel) > len_short_rel} # elements of R1 are used in inner parts of the process to prune # branches of the search tree, R1 = {rel.identity_cyclic_reduction() for rel in set(R) - R2} R1_c_list = C.conjugates(R1) S = [] descendant_subgroups(S, C, R1_c_list, C.A[0], R2, N, Y) return S def descendant_subgroups(S, C, R1_c_list, x, R2, N, Y): A_dict = C.A_dict A_dict_inv = C.A_dict_inv if C.is_complete(): # if C is complete then it only needs to test # whether the relators in R2 are satisfied for w, alpha in product(R2, C.omega): if not C.scan_check(alpha, w): return # relators in R2 are satisfied, append the table to list S.append(C) else: # find the first undefined entry in Coset Table for alpha, x in product(range(len(C.table)), C.A): if C.table[alpha][A_dict[x]] is None: # this is "x" in pseudo-code (using "y" makes it clear) undefined_coset, undefined_gen = alpha, x break # for filling up the undefine entry we try all possible values # of beta in Omega or beta = n where beta^(undefined_gen^-1) is undefined reach = C.omega + [C.n] for beta in reach: if beta < N: if beta == C.n or C.table[beta][A_dict_inv[undefined_gen]] is None: try_descendant(S, C, R1_c_list, R2, N, undefined_coset, \ undefined_gen, beta, Y) def try_descendant(S, C, R1_c_list, R2, N, alpha, x, beta, Y): r""" Solves the problem of trying out each individual possibility for `\alpha^x. """ D = C.copy() if beta == D.n and beta < N: D.table.append([None]*len(D.A)) D.p.append(beta) D.table[alpha][D.A_dict[x]] = beta D.table[beta][D.A_dict_inv[x]] = alpha D.deduction_stack.append((alpha, x)) if not D.process_deductions_check(R1_c_list[D.A_dict[x]], \ R1_c_list[D.A_dict_inv[x]]): return for w in Y: if not D.scan_check(0, w): return if first_in_class(D, Y): descendant_subgroups(S, D, R1_c_list, x, R2, N, Y) def first_in_class(C, Y=()): """ Checks whether the subgroup ``H=G1`` corresponding to the Coset Table could possibly be the canonical representative of its conjugacy class. Parameters ========== C: CosetTable Returns ======= bool: True/False If this returns False, then no descendant of C can have that property, and so we can abandon C. If it returns True, then we need to process further the node of the search tree corresponding to C, and so we call ``descendant_subgroups`` recursively on C. Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, CosetTable, first_in_class >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**2, y**3, (x*y)**4]) >>> C = CosetTable(f, []) >>> C.table = [[0, 0, None, None]] >>> first_in_class(C) True >>> C.table = [[1, 1, 1, None], [0, 0, None, 1]]; C.p = [0, 1] >>> first_in_class(C) True >>> C.table = [[1, 1, 2, 1], [0, 0, 0, None], [None, None, None, 0]] >>> C.p = [0, 1, 2] >>> first_in_class(C) False >>> C.table = [[1, 1, 1, 2], [0, 0, 2, 0], [2, None, 0, 1]] >>> first_in_class(C) False # TODO:: Sims points out in [Sim94] that performance can be improved by # remembering some of the information computed by ``first_in_class``. If # the ``continue alpha`` statement is executed at line 14, then the same thing # will happen for that value of alpha in any descendant of the table C, and so # the values the values of alpha for which this occurs could profitably be # stored and passed through to the descendants of C. Of course this would # make the code more complicated. # The code below is taken directly from the function on page 208 of [Sim94] # nu[alpha] """ n = C.n # lamda is the largest numbered point in Omega_c_alpha which is currently defined lamda = -1 # for alpha in Omega_c, nu[alpha] is the point in Omega_c_alpha corresponding to alpha nu = [None]*n # for alpha in Omega_c_alpha, mu[alpha] is the point in Omega_c corresponding to alpha mu = [None]*n # mutually nu and mu are the mutually-inverse equivalence maps between # Omega_c_alpha and Omega_c next_alpha = False # For each 0!=alpha in [0 .. nc-1], we start by constructing the equivalent # standardized coset table C_alpha corresponding to H_alpha for alpha in range(1, n): # reset nu to "None" after previous value of alpha for beta in range(lamda+1): nu[mu[beta]] = None # we only want to reject our current table in favour of a preceding # table in the ordering in which 1 is replaced by alpha, if the subgroup # G_alpha corresponding to this preceding table definitely contains the # given subgroup for w in Y: # TODO: this should support input of a list of general words # not just the words which are in "A" (i.e gen and gen^-1) if C.table[alpha][C.A_dict[w]] != alpha: # continue with alpha next_alpha = True break if next_alpha: next_alpha = False continue # try alpha as the new point 0 in Omega_C_alpha mu[0] = alpha nu[alpha] = 0 # compare corresponding entries in C and C_alpha lamda = 0 for beta in range(n): for x in C.A: gamma = C.table[beta][C.A_dict[x]] delta = C.table[mu[beta]][C.A_dict[x]] # if either of the entries is undefined, # we move with next alpha if gamma is None or delta is None: # continue with alpha next_alpha = True break if nu[delta] is None: # delta becomes the next point in Omega_C_alpha lamda += 1 nu[delta] = lamda mu[lamda] = delta if nu[delta] < gamma: return False if nu[delta] > gamma: # continue with alpha next_alpha = True break if next_alpha: next_alpha = False break return True #======================================================================== # Simplifying Presentation #======================================================================== def simplify_presentation(*args, change_gens=False): ''' For an instance of `FpGroup`, return a simplified isomorphic copy of the group (e.g. remove redundant generators or relators). Alternatively, a list of generators and relators can be passed in which case the simplified lists will be returned. By default, the generators of the group are unchanged. If you would like to remove redundant generators, set the keyword argument `change_gens = True`. ''' if len(args) == 1: if not isinstance(args[0], FpGroup): raise TypeError("The argument must be an instance of FpGroup") G = args[0] gens, rels = simplify_presentation(G.generators, G.relators, change_gens=change_gens) if gens: return FpGroup(gens[0].group, rels) return FpGroup(FreeGroup([]), []) elif len(args) == 2: gens, rels = args[0][:], args[1][:] if not gens: return gens, rels identity = gens[0].group.identity else: if len(args) == 0: m = "Not enough arguments" else: m = "Too many arguments" raise RuntimeError(m) prev_gens = [] prev_rels = [] while not set(prev_rels) == set(rels): prev_rels = rels while change_gens and not set(prev_gens) == set(gens): prev_gens = gens gens, rels = elimination_technique_1(gens, rels, identity) rels = _simplify_relators(rels, identity) if change_gens: syms = [g.array_form[0][0] for g in gens] F = free_group(syms)[0] identity = F.identity gens = F.generators subs = dict(zip(syms, gens)) for j, r in enumerate(rels): a = r.array_form rel = identity for sym, p in a: rel = rel*subs[sym]**p rels[j] = rel return gens, rels def _simplify_relators(rels, identity): """Relies upon ``_simplification_technique_1`` for its functioning. """ rels = rels[:] rels = list(set(_simplification_technique_1(rels))) rels.sort() rels = [r.identity_cyclic_reduction() for r in rels] try: rels.remove(identity) except ValueError: pass return rels # Pg 350, section 2.5.1 from [2] def elimination_technique_1(gens, rels, identity): rels = rels[:] # the shorter relators are examined first so that generators selected for # elimination will have shorter strings as equivalent rels.sort() gens = gens[:] redundant_gens = {} redundant_rels = [] used_gens = set() # examine each relator in relator list for any generator occurring exactly # once for rel in rels: # don't look for a redundant generator in a relator which # depends on previously found ones contained_gens = rel.contains_generators() if any(g in contained_gens for g in redundant_gens): continue contained_gens = list(contained_gens) contained_gens.sort(reverse = True) for gen in contained_gens: if rel.generator_count(gen) == 1 and gen not in used_gens: k = rel.exponent_sum(gen) gen_index = rel.index(gen**k) bk = rel.subword(gen_index + 1, len(rel)) fw = rel.subword(0, gen_index) chi = bk*fw redundant_gens[gen] = chi**(-1*k) used_gens.update(chi.contains_generators()) redundant_rels.append(rel) break rels = [r for r in rels if r not in redundant_rels] # eliminate the redundant generators from remaining relators rels = [r.eliminate_words(redundant_gens, _all = True).identity_cyclic_reduction() for r in rels] rels = list(set(rels)) try: rels.remove(identity) except ValueError: pass gens = [g for g in gens if g not in redundant_gens] return gens, rels def _simplification_technique_1(rels): """ All relators are checked to see if they are of the form `gen^n`. If any such relators are found then all other relators are processed for strings in the `gen` known order. Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import _simplification_technique_1 >>> F, x, y = free_group("x, y") >>> w1 = [x**2*y**4, x**3] >>> _simplification_technique_1(w1) [x**-1*y**4, x**3] >>> w2 = [x**2*y**-4*x**5, x**3, x**2*y**8, y**5] >>> _simplification_technique_1(w2) [x**-1*y*x**-1, x**3, x**-1*y**-2, y**5] >>> w3 = [x**6*y**4, x**4] >>> _simplification_technique_1(w3) [x**2*y**4, x**4] """ from sympy.polys.polytools import gcd rels = rels[:] # dictionary with "gen: n" where gen^n is one of the relators exps = {} for i in range(len(rels)): rel = rels[i] if rel.number_syllables() == 1: g = rel[0] exp = abs(rel.array_form[0][1]) if rel.array_form[0][1] < 0: rels[i] = rels[i]**-1 g = g**-1 if g in exps: exp = gcd(exp, exps[g].array_form[0][1]) exps[g] = g**exp one_syllables_words = exps.values() # decrease some of the exponents in relators, making use of the single # syllable relators for i in range(len(rels)): rel = rels[i] if rel in one_syllables_words: continue rel = rel.eliminate_words(one_syllables_words, _all = True) # if rels[i] contains g**n where abs(n) is greater than half of the power p # of g in exps, g**n can be replaced by g**(n-p) (or g**(p-n) if n<0) for g in rel.contains_generators(): if g in exps: exp = exps[g].array_form[0][1] max_exp = (exp + 1)//2 rel = rel.eliminate_word(g**(max_exp), g**(max_exp-exp), _all = True) rel = rel.eliminate_word(g**(-max_exp), g**(-(max_exp-exp)), _all = True) rels[i] = rel rels = [r.identity_cyclic_reduction() for r in rels] return rels ############################################################################### # SUBGROUP PRESENTATIONS # ############################################################################### # Pg 175 [1] def define_schreier_generators(C, homomorphism=False): ''' Parameters ========== C -- Coset table. homomorphism -- When set to True, return a dictionary containing the images of the presentation generators in the original group. ''' y = [] gamma = 1 f = C.fp_group X = f.generators if homomorphism: # `_gens` stores the elements of the parent group to # to which the schreier generators correspond to. _gens = {} # compute the schreier Traversal tau = {} tau[0] = f.identity C.P = [[None]*len(C.A) for i in range(C.n)] for alpha, x in product(C.omega, C.A): beta = C.table[alpha][C.A_dict[x]] if beta == gamma: C.P[alpha][C.A_dict[x]] = "<identity>" C.P[beta][C.A_dict_inv[x]] = "<identity>" gamma += 1 if homomorphism: tau[beta] = tau[alpha]*x elif x in X and C.P[alpha][C.A_dict[x]] is None: y_alpha_x = '%s_%s' % (x, alpha) y.append(y_alpha_x) C.P[alpha][C.A_dict[x]] = y_alpha_x if homomorphism: _gens[y_alpha_x] = tau[alpha]*x*tau[beta]**-1 grp_gens = list(free_group(', '.join(y))) C._schreier_free_group = grp_gens.pop(0) C._schreier_generators = grp_gens if homomorphism: C._schreier_gen_elem = _gens # replace all elements of P by, free group elements for i, j in product(range(len(C.P)), range(len(C.A))): # if equals "<identity>", replace by identity element if C.P[i][j] == "<identity>": C.P[i][j] = C._schreier_free_group.identity elif isinstance(C.P[i][j], str): r = C._schreier_generators[y.index(C.P[i][j])] C.P[i][j] = r beta = C.table[i][j] C.P[beta][j + 1] = r**-1 def reidemeister_relators(C): R = C.fp_group.relators rels = [rewrite(C, coset, word) for word in R for coset in range(C.n)] order_1_gens = {i for i in rels if len(i) == 1} # remove all the order 1 generators from relators rels = list(filter(lambda rel: rel not in order_1_gens, rels)) # replace order 1 generators by identity element in reidemeister relators for i in range(len(rels)): w = rels[i] w = w.eliminate_words(order_1_gens, _all=True) rels[i] = w C._schreier_generators = [i for i in C._schreier_generators if not (i in order_1_gens or i**-1 in order_1_gens)] # Tietze transformation 1 i.e TT_1 # remove cyclic conjugate elements from relators i = 0 while i < len(rels): w = rels[i] j = i + 1 while j < len(rels): if w.is_cyclic_conjugate(rels[j]): del rels[j] else: j += 1 i += 1 C._reidemeister_relators = rels def rewrite(C, alpha, w): """ Parameters ========== C: CosetTable alpha: A live coset w: A word in `A*` Returns ======= rho(tau(alpha), w) Examples ======== >>> from sympy.combinatorics.fp_groups import FpGroup, CosetTable, define_schreier_generators, rewrite >>> from sympy.combinatorics.free_groups import free_group >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**2, y**3, (x*y)**6]) >>> C = CosetTable(f, []) >>> C.table = [[1, 1, 2, 3], [0, 0, 4, 5], [4, 4, 3, 0], [5, 5, 0, 2], [2, 2, 5, 1], [3, 3, 1, 4]] >>> C.p = [0, 1, 2, 3, 4, 5] >>> define_schreier_generators(C) >>> rewrite(C, 0, (x*y)**6) x_4*y_2*x_3*x_1*x_2*y_4*x_5 """ v = C._schreier_free_group.identity for i in range(len(w)): x_i = w[i] v = v*C.P[alpha][C.A_dict[x_i]] alpha = C.table[alpha][C.A_dict[x_i]] return v # Pg 350, section 2.5.2 from [2] def elimination_technique_2(C): """ This technique eliminates one generator at a time. Heuristically this seems superior in that we may select for elimination the generator with shortest equivalent string at each stage. >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r, \ reidemeister_relators, define_schreier_generators, elimination_technique_2 >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**3, y**5, (x*y)**2]); H = [x*y, x**-1*y**-1*x*y*x] >>> C = coset_enumeration_r(f, H) >>> C.compress(); C.standardize() >>> define_schreier_generators(C) >>> reidemeister_relators(C) >>> elimination_technique_2(C) ([y_1, y_2], [y_2**-3, y_2*y_1*y_2*y_1*y_2*y_1, y_1**2]) """ rels = C._reidemeister_relators rels.sort(reverse=True) gens = C._schreier_generators for i in range(len(gens) - 1, -1, -1): rel = rels[i] for j in range(len(gens) - 1, -1, -1): gen = gens[j] if rel.generator_count(gen) == 1: k = rel.exponent_sum(gen) gen_index = rel.index(gen**k) bk = rel.subword(gen_index + 1, len(rel)) fw = rel.subword(0, gen_index) rep_by = (bk*fw)**(-1*k) del rels[i]; del gens[j] for l in range(len(rels)): rels[l] = rels[l].eliminate_word(gen, rep_by) break C._reidemeister_relators = rels C._schreier_generators = gens return C._schreier_generators, C._reidemeister_relators def reidemeister_presentation(fp_grp, H, C=None, homomorphism=False): """ Parameters ========== fp_group: A finitely presented group, an instance of FpGroup H: A subgroup whose presentation is to be found, given as a list of words in generators of `fp_grp` homomorphism: When set to True, return a homomorphism from the subgroup to the parent group Examples ======== >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, reidemeister_presentation >>> F, x, y = free_group("x, y") Example 5.6 Pg. 177 from [1] >>> f = FpGroup(F, [x**3, y**5, (x*y)**2]) >>> H = [x*y, x**-1*y**-1*x*y*x] >>> reidemeister_presentation(f, H) ((y_1, y_2), (y_1**2, y_2**3, y_2*y_1*y_2*y_1*y_2*y_1)) Example 5.8 Pg. 183 from [1] >>> f = FpGroup(F, [x**3, y**3, (x*y)**3]) >>> H = [x*y, x*y**-1] >>> reidemeister_presentation(f, H) ((x_0, y_0), (x_0**3, y_0**3, x_0*y_0*x_0*y_0*x_0*y_0)) Exercises Q2. Pg 187 from [1] >>> f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3]) >>> H = [x] >>> reidemeister_presentation(f, H) ((x_0,), (x_0**4,)) Example 5.9 Pg. 183 from [1] >>> f = FpGroup(F, [x**3*y**-3, (x*y)**3, (x*y**-1)**2]) >>> H = [x] >>> reidemeister_presentation(f, H) ((x_0,), (x_0**6,)) """ if not C: C = coset_enumeration_r(fp_grp, H) C.compress(); C.standardize() define_schreier_generators(C, homomorphism=homomorphism) reidemeister_relators(C) gens, rels = C._schreier_generators, C._reidemeister_relators gens, rels = simplify_presentation(gens, rels, change_gens=True) C.schreier_generators = tuple(gens) C.reidemeister_relators = tuple(rels) if homomorphism: _gens = [] for gen in gens: _gens.append(C._schreier_gen_elem[str(gen)]) return C.schreier_generators, C.reidemeister_relators, _gens return C.schreier_generators, C.reidemeister_relators FpGroupElement = FreeGroupElement
7daa54aac95910d61e560561dfc68412694b4c215d7598a09f42720b15b8bb9b
from sympy.core.add import Add from sympy.core.containers import Tuple from sympy.core.expr import Expr from sympy.core.function import AppliedUndef, UndefinedFunction from sympy.core.mul import Mul from sympy.core.relational import Equality, Relational from sympy.core.singleton import S from sympy.core.symbol import Symbol, Dummy from sympy.core.sympify import sympify from sympy.functions.elementary.piecewise import (piecewise_fold, Piecewise) from sympy.logic.boolalg import BooleanFunction from sympy.matrices.matrices import MatrixBase from sympy.sets.sets import Interval, Set from sympy.sets.fancysets import Range from sympy.tensor.indexed import Idx from sympy.utilities import flatten from sympy.utilities.iterables import sift, is_sequence from sympy.utilities.exceptions import SymPyDeprecationWarning def _common_new(cls, function, *symbols, discrete, **assumptions): """Return either a special return value or the tuple, (function, limits, orientation). This code is common to both ExprWithLimits and AddWithLimits.""" function = sympify(function) if isinstance(function, Equality): # This transforms e.g. Integral(Eq(x, y)) to Eq(Integral(x), Integral(y)) # but that is only valid for definite integrals. limits, orientation = _process_limits(*symbols, discrete=discrete) if not (limits and all(len(limit) == 3 for limit in limits)): SymPyDeprecationWarning( feature='Integral(Eq(x, y))', useinstead='Eq(Integral(x, z), Integral(y, z))', issue=18053, deprecated_since_version=1.6, ).warn() lhs = function.lhs rhs = function.rhs return Equality(cls(lhs, *symbols, **assumptions), \ cls(rhs, *symbols, **assumptions)) if function is S.NaN: return S.NaN if symbols: limits, orientation = _process_limits(*symbols, discrete=discrete) for i, li in enumerate(limits): if len(li) == 4: function = function.subs(li[0], li[-1]) limits[i] = Tuple(*li[:-1]) else: # symbol not provided -- we can still try to compute a general form free = function.free_symbols if len(free) != 1: raise ValueError( "specify dummy variables for %s" % function) limits, orientation = [Tuple(s) for s in free], 1 # denest any nested calls while cls == type(function): limits = list(function.limits) + limits function = function.function # Any embedded piecewise functions need to be brought out to the # top level. We only fold Piecewise that contain the integration # variable. reps = {} symbols_of_integration = {i[0] for i in limits} for p in function.atoms(Piecewise): if not p.has(*symbols_of_integration): reps[p] = Dummy() # mask off those that don't function = function.xreplace(reps) # do the fold function = piecewise_fold(function) # remove the masking function = function.xreplace({v: k for k, v in reps.items()}) return function, limits, orientation def _process_limits(*symbols, discrete=None): """Process the list of symbols and convert them to canonical limits, storing them as Tuple(symbol, lower, upper). The orientation of the function is also returned when the upper limit is missing so (x, 1, None) becomes (x, None, 1) and the orientation is changed. In the case that a limit is specified as (symbol, Range), a list of length 4 may be returned if a change of variables is needed; the expression that should replace the symbol in the expression is the fourth element in the list. """ limits = [] orientation = 1 if discrete is None: err_msg = 'discrete must be True or False' elif discrete: err_msg = 'use Range, not Interval or Relational' else: err_msg = 'use Interval or Relational, not Range' for V in symbols: if isinstance(V, (Relational, BooleanFunction)): if discrete: raise TypeError(err_msg) variable = V.atoms(Symbol).pop() V = (variable, V.as_set()) elif isinstance(V, Symbol) or getattr(V, '_diff_wrt', False): if isinstance(V, Idx): if V.lower is None or V.upper is None: limits.append(Tuple(V)) else: limits.append(Tuple(V, V.lower, V.upper)) else: limits.append(Tuple(V)) continue if is_sequence(V) and not isinstance(V, Set): if len(V) == 2 and isinstance(V[1], Set): V = list(V) if isinstance(V[1], Interval): # includes Reals if discrete: raise TypeError(err_msg) V[1:] = V[1].inf, V[1].sup elif isinstance(V[1], Range): if not discrete: raise TypeError(err_msg) lo = V[1].inf hi = V[1].sup dx = abs(V[1].step) # direction doesn't matter if dx == 1: V[1:] = [lo, hi] else: if lo is not S.NegativeInfinity: V = [V[0]] + [0, (hi - lo)//dx, dx*V[0] + lo] else: V = [V[0]] + [0, S.Infinity, -dx*V[0] + hi] else: # more complicated sets would require splitting, e.g. # Union(Interval(1, 3), interval(6,10)) raise NotImplementedError( 'expecting Range' if discrete else 'Relational or single Interval' ) V = sympify(flatten(V)) # list of sympified elements/None if isinstance(V[0], (Symbol, Idx)) or getattr(V[0], '_diff_wrt', False): newsymbol = V[0] if len(V) == 3: # general case if V[2] is None and V[1] is not None: orientation *= -1 V = [newsymbol] + [i for i in V[1:] if i is not None] lenV = len(V) if not isinstance(newsymbol, Idx) or lenV == 3: if lenV == 4: limits.append(Tuple(*V)) continue if lenV == 3: if isinstance(newsymbol, Idx): # Idx represents an integer which may have # specified values it can take on; if it is # given such a value, an error is raised here # if the summation would try to give it a larger # or smaller value than permitted. None and Symbolic # values will not raise an error. lo, hi = newsymbol.lower, newsymbol.upper try: if lo is not None and not bool(V[1] >= lo): raise ValueError("Summation will set Idx value too low.") except TypeError: pass try: if hi is not None and not bool(V[2] <= hi): raise ValueError("Summation will set Idx value too high.") except TypeError: pass limits.append(Tuple(*V)) continue if lenV == 1 or (lenV == 2 and V[1] is None): limits.append(Tuple(newsymbol)) continue elif lenV == 2: limits.append(Tuple(newsymbol, V[1])) continue raise ValueError('Invalid limits given: %s' % str(symbols)) return limits, orientation class ExprWithLimits(Expr): __slots__ = ('is_commutative',) def __new__(cls, function, *symbols, **assumptions): from sympy.concrete.products import Product pre = _common_new(cls, function, *symbols, discrete=issubclass(cls, Product), **assumptions) if isinstance(pre, tuple): function, limits, _ = pre else: return pre # limits must have upper and lower bounds; the indefinite form # is not supported. This restriction does not apply to AddWithLimits if any(len(l) != 3 or None in l for l in limits): raise ValueError('ExprWithLimits requires values for lower and upper bounds.') obj = Expr.__new__(cls, **assumptions) arglist = [function] arglist.extend(limits) obj._args = tuple(arglist) obj.is_commutative = function.is_commutative # limits already checked return obj @property def function(self): """Return the function applied across limits. Examples ======== >>> from sympy import Integral >>> from sympy.abc import x >>> Integral(x**2, (x,)).function x**2 See Also ======== limits, variables, free_symbols """ return self._args[0] @property def kind(self): return self.function.kind @property def limits(self): """Return the limits of expression. Examples ======== >>> from sympy import Integral >>> from sympy.abc import x, i >>> Integral(x**i, (i, 1, 3)).limits ((i, 1, 3),) See Also ======== function, variables, free_symbols """ return self._args[1:] @property def variables(self): """Return a list of the limit variables. >>> from sympy import Sum >>> from sympy.abc import x, i >>> Sum(x**i, (i, 1, 3)).variables [i] See Also ======== function, limits, free_symbols as_dummy : Rename dummy variables sympy.integrals.integrals.Integral.transform : Perform mapping on the dummy variable """ return [l[0] for l in self.limits] @property def bound_symbols(self): """Return only variables that are dummy variables. Examples ======== >>> from sympy import Integral >>> from sympy.abc import x, i, j, k >>> Integral(x**i, (i, 1, 3), (j, 2), k).bound_symbols [i, j] See Also ======== function, limits, free_symbols as_dummy : Rename dummy variables sympy.integrals.integrals.Integral.transform : Perform mapping on the dummy variable """ return [l[0] for l in self.limits if len(l) != 1] @property def free_symbols(self): """ This method returns the symbols in the object, excluding those that take on a specific value (i.e. the dummy symbols). Examples ======== >>> from sympy import Sum >>> from sympy.abc import x, y >>> Sum(x, (x, y, 1)).free_symbols {y} """ # don't test for any special values -- nominal free symbols # should be returned, e.g. don't return set() if the # function is zero -- treat it like an unevaluated expression. function, limits = self.function, self.limits # mask off non-symbol integration variables that have # more than themself as a free symbol reps = {i[0]: i[0] if i[0].free_symbols == {i[0]} else Dummy() for i in self.limits} function = function.xreplace(reps) isyms = function.free_symbols for xab in limits: v = reps[xab[0]] if len(xab) == 1: isyms.add(v) continue # take out the target symbol if v in isyms: isyms.remove(v) # add in the new symbols for i in xab[1:]: isyms.update(i.free_symbols) reps = {v: k for k, v in reps.items()} return set([reps.get(_, _) for _ in isyms]) @property def is_number(self): """Return True if the Sum has no free symbols, else False.""" return not self.free_symbols def _eval_interval(self, x, a, b): limits = [(i if i[0] != x else (x, a, b)) for i in self.limits] integrand = self.function return self.func(integrand, *limits) def _eval_subs(self, old, new): """ Perform substitutions over non-dummy variables of an expression with limits. Also, can be used to specify point-evaluation of an abstract antiderivative. Examples ======== >>> from sympy import Sum, oo >>> from sympy.abc import s, n >>> Sum(1/n**s, (n, 1, oo)).subs(s, 2) Sum(n**(-2), (n, 1, oo)) >>> from sympy import Integral >>> from sympy.abc import x, a >>> Integral(a*x**2, x).subs(x, 4) Integral(a*x**2, (x, 4)) See Also ======== variables : Lists the integration variables transform : Perform mapping on the dummy variable for integrals change_index : Perform mapping on the sum and product dummy variables """ func, limits = self.function, list(self.limits) # If one of the expressions we are replacing is used as a func index # one of two things happens. # - the old variable first appears as a free variable # so we perform all free substitutions before it becomes # a func index. # - the old variable first appears as a func index, in # which case we ignore. See change_index. # Reorder limits to match standard mathematical practice for scoping limits.reverse() if not isinstance(old, Symbol) or \ old.free_symbols.intersection(self.free_symbols): sub_into_func = True for i, xab in enumerate(limits): if 1 == len(xab) and old == xab[0]: if new._diff_wrt: xab = (new,) else: xab = (old, old) limits[i] = Tuple(xab[0], *[l._subs(old, new) for l in xab[1:]]) if len(xab[0].free_symbols.intersection(old.free_symbols)) != 0: sub_into_func = False break if isinstance(old, (AppliedUndef, UndefinedFunction)): sy2 = set(self.variables).intersection(set(new.atoms(Symbol))) sy1 = set(self.variables).intersection(set(old.args)) if not sy2.issubset(sy1): raise ValueError( "substitution cannot create dummy dependencies") sub_into_func = True if sub_into_func: func = func.subs(old, new) else: # old is a Symbol and a dummy variable of some limit for i, xab in enumerate(limits): if len(xab) == 3: limits[i] = Tuple(xab[0], *[l._subs(old, new) for l in xab[1:]]) if old == xab[0]: break # simplify redundant limits (x, x) to (x, ) for i, xab in enumerate(limits): if len(xab) == 2 and (xab[0] - xab[1]).is_zero: limits[i] = Tuple(xab[0], ) # Reorder limits back to representation-form limits.reverse() return self.func(func, *limits) @property def has_finite_limits(self): """ Returns True if the limits are known to be finite, either by the explicit bounds, assumptions on the bounds, or assumptions on the variables. False if known to be infinite, based on the bounds. None if not enough information is available to determine. Examples ======== >>> from sympy import Sum, Integral, Product, oo, Symbol >>> x = Symbol('x') >>> Sum(x, (x, 1, 8)).has_finite_limits True >>> Integral(x, (x, 1, oo)).has_finite_limits False >>> M = Symbol('M') >>> Sum(x, (x, 1, M)).has_finite_limits >>> N = Symbol('N', integer=True) >>> Product(x, (x, 1, N)).has_finite_limits True See Also ======== has_reversed_limits """ ret_None = False for lim in self.limits: if len(lim) == 3: if any(l.is_infinite for l in lim[1:]): # Any of the bounds are +/-oo return False elif any(l.is_infinite is None for l in lim[1:]): # Maybe there are assumptions on the variable? if lim[0].is_infinite is None: ret_None = True else: if lim[0].is_infinite is None: ret_None = True if ret_None: return None return True @property def has_reversed_limits(self): """ Returns True if the limits are known to be in reversed order, either by the explicit bounds, assumptions on the bounds, or assumptions on the variables. False if known to be in normal order, based on the bounds. None if not enough information is available to determine. Examples ======== >>> from sympy import Sum, Integral, Product, oo, Symbol >>> x = Symbol('x') >>> Sum(x, (x, 8, 1)).has_reversed_limits True >>> Sum(x, (x, 1, oo)).has_reversed_limits False >>> M = Symbol('M') >>> Integral(x, (x, 1, M)).has_reversed_limits >>> N = Symbol('N', integer=True, positive=True) >>> Sum(x, (x, 1, N)).has_reversed_limits False >>> Product(x, (x, 2, N)).has_reversed_limits >>> Product(x, (x, 2, N)).subs(N, N + 2).has_reversed_limits False See Also ======== sympy.concrete.expr_with_intlimits.ExprWithIntLimits.has_empty_sequence """ ret_None = False for lim in self.limits: if len(lim) == 3: var, a, b = lim dif = b - a if dif.is_extended_negative: return True elif dif.is_extended_nonnegative: continue else: ret_None = True else: return None if ret_None: return None return False class AddWithLimits(ExprWithLimits): r"""Represents unevaluated oriented additions. Parent class for Integral and Sum. """ def __new__(cls, function, *symbols, **assumptions): from sympy.concrete.summations import Sum pre = _common_new(cls, function, *symbols, discrete=issubclass(cls, Sum), **assumptions) if isinstance(pre, tuple): function, limits, orientation = pre else: return pre obj = Expr.__new__(cls, **assumptions) arglist = [orientation*function] # orientation not used in ExprWithLimits arglist.extend(limits) obj._args = tuple(arglist) obj.is_commutative = function.is_commutative # limits already checked return obj def _eval_adjoint(self): if all(x.is_real for x in flatten(self.limits)): return self.func(self.function.adjoint(), *self.limits) return None def _eval_conjugate(self): if all(x.is_real for x in flatten(self.limits)): return self.func(self.function.conjugate(), *self.limits) return None def _eval_transpose(self): if all(x.is_real for x in flatten(self.limits)): return self.func(self.function.transpose(), *self.limits) return None def _eval_factor(self, **hints): if 1 == len(self.limits): summand = self.function.factor(**hints) if summand.is_Mul: out = sift(summand.args, lambda w: w.is_commutative \ and not set(self.variables) & w.free_symbols) return Mul(*out[True])*self.func(Mul(*out[False]), \ *self.limits) else: summand = self.func(self.function, *self.limits[0:-1]).factor() if not summand.has(self.variables[-1]): return self.func(1, [self.limits[-1]]).doit()*summand elif isinstance(summand, Mul): return self.func(summand, self.limits[-1]).factor() return self def _eval_expand_basic(self, **hints): summand = self.function.expand(**hints) if summand.is_Add and summand.is_commutative: return Add(*[self.func(i, *self.limits) for i in summand.args]) elif isinstance(summand, MatrixBase): return summand.applyfunc(lambda x: self.func(x, *self.limits)) elif summand != self.function: return self.func(summand, *self.limits) return self
ebe4825aa7da4152cfb9d65f3a998854bc13e6a3b001302bd4ea8f75179c7c84
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 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 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.simplify.combsimp import combsimp from sympy.simplify.hyperexpand import hyperexpand from sympy.simplify.powsimp import powsimp from sympy.simplify.radsimp import denom, fraction from sympy.simplify.simplify import (factor_sum, sum_combine, simplify, nsimplify, hypersimp) from sympy.solvers.solvers import solve from sympy.solvers.solveset import solveset 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__ = ('is_commutative',) limits: tTuple[tTuple[Symbol, Expr, Expr]] def __new__(cls, function, *symbols, **assumptions): obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions) if not hasattr(obj, 'limits'): return obj if any(len(l) != 3 or None in l for l in obj.limits): raise ValueError('Sum requires values for lower and upper bounds.') return obj def _eval_is_zero(self): # a Sum is only zero if its function is zero or if all terms # cancel out. This only answers whether the summand is zero; if # not then None is returned since we don't analyze whether all # terms cancel out. if self.function.is_zero or self.has_empty_sequence: return True def _eval_is_extended_real(self): if self.has_empty_sequence: return True return self.function.is_extended_real def _eval_is_positive(self): if self.has_finite_limits and self.has_reversed_limits is False: return self.function.is_positive def _eval_is_negative(self): if self.has_finite_limits and self.has_reversed_limits is False: return self.function.is_negative def _eval_is_finite(self): if self.has_finite_limits and self.function.is_finite: return True def doit(self, **hints): if hints.get('deep', True): f = self.function.doit(**hints) else: f = self.function # first make sure any definite limits have summation # variables with matching assumptions reps = {} for xab in self.limits: d = _dummy_with_inherited_properties_concrete(xab) if d: reps[xab[0]] = d if reps: undo = {v: k for k, v in reps.items()} did = self.xreplace(reps).doit(**hints) if isinstance(did, tuple): # when separate=True did = tuple([i.xreplace(undo) for i in did]) elif did is not None: did = did.xreplace(undo) else: did = self return did if self.function.is_Matrix: expanded = self.expand() if self != expanded: return expanded.doit() return _eval_matrix_sum(self) for n, limit in enumerate(self.limits): i, a, b = limit dif = b - a if dif == -1: # Any summation over an empty set is zero return S.Zero if dif.is_integer and dif.is_negative: a, b = b + 1, a - 1 f = -f newf = eval_sum(f, (i, a, b)) if newf is None: if f == self.function: zeta_function = self.eval_zeta_function(f, (i, a, b)) if zeta_function is not None: return zeta_function return self else: return self.func(f, *self.limits[n:]) f = newf if hints.get('deep', True): # eval_sum could return partially unevaluated # result with Piecewise. In this case we won't # doit() recursively. if not isinstance(f, Piecewise): return f.doit(**hints) return f def eval_zeta_function(self, f, limits): """ Check whether the function matches with the zeta function. If it matches, then return a `Piecewise` expression because zeta function does not converge unless `s > 1` and `q > 0` """ i, a, b = limits w, y, z = Wild('w', exclude=[i]), Wild('y', exclude=[i]), Wild('z', exclude=[i]) result = f.match((w * i + y) ** (-z)) if result is not None and b is S.Infinity: coeff = 1 / result[w] ** result[z] s = result[z] q = result[y] / result[w] + a return Piecewise((coeff * zeta(s, q), And(q > 0, s > 1)), (self, True)) def _eval_derivative(self, x): """ Differentiate wrt x as long as x is not in the free symbols of any of the upper or lower limits. Explanation =========== Sum(a*b*x, (x, 1, a)) can be differentiated wrt x or b but not `a` since the value of the sum is discontinuous in `a`. In a case involving a limit variable, the unevaluated derivative is returned. """ # diff already confirmed that x is in the free symbols of self, but we # don't want to differentiate wrt any free symbol in the upper or lower # limits # XXX remove this test for free_symbols when the default _eval_derivative is in if isinstance(x, Symbol) and x not in self.free_symbols: return S.Zero # get limits and the function f, limits = self.function, list(self.limits) limit = limits.pop(-1) if limits: # f is the argument to a Sum f = self.func(f, *limits) _, a, b = limit if x in a.free_symbols or x in b.free_symbols: return None df = Derivative(f, x, evaluate=True) rv = self.func(df, limit) return rv def _eval_difference_delta(self, n, step): k, _, upper = self.args[-1] new_upper = upper.subs(n, n + step) if len(self.args) == 2: f = self.args[0] else: f = self.func(*self.args[:-1]) return Sum(f, (k, upper + 1, new_upper)).doit() def _eval_simplify(self, **kwargs): # split the function into adds terms = Add.make_args(expand(self.function)) s_t = [] # Sum Terms o_t = [] # Other Terms for term in terms: if term.has(Sum): # if there is an embedded sum here # it is of the form x * (Sum(whatever)) # hence we make a Mul out of it, and simplify all interior sum terms subterms = Mul.make_args(expand(term)) out_terms = [] for subterm in subterms: # go through each term if isinstance(subterm, Sum): # if it's a sum, simplify it out_terms.append(subterm._eval_simplify()) else: # otherwise, add it as is out_terms.append(subterm) # turn it back into a Mul s_t.append(Mul(*out_terms)) else: o_t.append(term) # next try to combine any interior sums for further simplification 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() sequence_term = simplify(sequence_term.xreplace({sym: -sym})) lower_limit = -upper_limit upper_limit = S.Infinity sym_ = Dummy(sym.name, integer=True, positive=True) sequence_term = sequence_term.xreplace({sym: sym_}) sym = sym_ interval = Interval(lower_limit, upper_limit) # Piecewise function handle if sequence_term.is_Piecewise: for func, cond in sequence_term.args: # see if it represents something going to oo if cond == True or cond.as_set().sup is S.Infinity: s = Sum(func, (sym, lower_limit, upper_limit)) return s.is_convergent() return S.true ### -------- Divergence test ----------- ### try: lim_val = limit_seq(sequence_term, sym) if lim_val is not None and lim_val.is_zero is False: return S.false except NotImplementedError: pass try: lim_val_abs = limit_seq(abs(sequence_term), sym) if lim_val_abs is not None and lim_val_abs.is_zero is False: return S.false except NotImplementedError: pass order = O(sequence_term, (sym, S.Infinity)) ### --------- p-series test (1/n**p) ---------- ### p_series_test = order.expr.match(sym**p) if p_series_test is not None: if p_series_test[p] < -1: return S.true if p_series_test[p] >= -1: return S.false ### ------------- comparison test ------------- ### # 1/(n**p*log(n)**q*log(log(n))**r) comparison n_log_test = order.expr.match(1/(sym**p*log(sym)**q*log(log(sym))**r)) if n_log_test is not None: if (n_log_test[p] > 1 or (n_log_test[p] == 1 and n_log_test[q] > 1) or (n_log_test[p] == n_log_test[q] == 1 and n_log_test[r] > 1)): return S.true return S.false ### ------------- Limit comparison test -----------### # (1/n) comparison try: lim_comp = limit_seq(sym*sequence_term, sym) if lim_comp is not None and lim_comp.is_number and lim_comp > 0: return S.false except NotImplementedError: pass ### ----------- ratio test ---------------- ### next_sequence_term = sequence_term.xreplace({sym: sym + 1}) ratio = combsimp(powsimp(next_sequence_term/sequence_term)) try: lim_ratio = limit_seq(ratio, sym) if lim_ratio is not None and lim_ratio.is_number: if abs(lim_ratio) > 1: return S.false if abs(lim_ratio) < 1: return S.true except NotImplementedError: lim_ratio = None ### ---------- Raabe's test -------------- ### if lim_ratio == 1: # ratio test inconclusive test_val = sym*(sequence_term/ sequence_term.subs(sym, sym + 1) - 1) test_val = test_val.gammasimp() try: lim_val = limit_seq(test_val, sym) if lim_val is not None and lim_val.is_number: if lim_val > 1: return S.true if lim_val < 1: return S.false except NotImplementedError: pass ### ----------- root test ---------------- ### # lim = Limit(abs(sequence_term)**(1/sym), sym, S.Infinity) try: lim_evaluated = limit_seq(abs(sequence_term)**(1/sym), sym) if lim_evaluated is not None and lim_evaluated.is_number: if lim_evaluated < 1: return S.true if lim_evaluated > 1: return S.false except NotImplementedError: pass ### ------------- alternating series test ----------- ### dict_val = sequence_term.match(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 maxima = solveset(sequence_term.diff(sym), sym, interval) if not maxima: check_interval = interval elif isinstance(maxima, FiniteSet) and maxima.sup.is_number: check_interval = Interval(maxima.sup, interval.sup) if (check_interval is not None and (is_decreasing(sequence_term, check_interval) or is_decreasing(-sequence_term, check_interval))): integral_val = Integral( sequence_term, (sym, lower_limit, upper_limit)) try: integral_val_evaluated = integral_val.doit() if integral_val_evaluated.is_number: return S(integral_val_evaluated.is_finite) except NotImplementedError: pass ### ----- Dirichlet and bounded times convergent tests ----- ### # TODO # # Dirichlet_test # https://en.wikipedia.org/wiki/Dirichlet%27s_test # # Bounded times convergent test # It is based on comparison theorems for series. # In particular, if the general term of a series can # be written as a product of two terms a_n and b_n # and if a_n is bounded and if Sum(b_n) is absolutely # convergent, then the original series Sum(a_n * b_n) # is absolutely convergent and so convergent. # # The following code can grows like 2**n where n is the # number of args in order.expr # Possibly combined with the potentially slow checks # inside the loop, could make this test extremely slow # for larger summation expressions. if order.expr.is_Mul: args = order.expr.args argset = set(args) ### -------------- Dirichlet tests -------------- ### m = Dummy('m', integer=True) def _dirichlet_test(g_n): try: ing_val = limit_seq(Sum(g_n, (sym, interval.inf, m)).doit(), m) if ing_val is not None and ing_val.is_finite: return S.true except NotImplementedError: pass ### -------- bounded times convergent test ---------### def _bounded_convergent_test(g1_n, g2_n): try: lim_val = limit_seq(g1_n, sym) if lim_val is not None and (lim_val.is_finite or ( isinstance(lim_val, AccumulationBounds) and (lim_val.max - lim_val.min).is_finite)): if Sum(g2_n, (sym, lower_limit, upper_limit)).is_absolutely_convergent(): return S.true except NotImplementedError: pass for n in range(1, len(argset)): for a_tuple in itertools.combinations(args, n): b_set = argset - set(a_tuple) a_n = Mul(*a_tuple) b_n = Mul(*b_set) if is_decreasing(a_n, interval): dirich = _dirichlet_test(b_n) if dirich is not None: return dirich bc_test = _bounded_convergent_test(a_n, b_n) if bc_test is not None: return bc_test _sym = self.limits[0][0] sequence_term = sequence_term.xreplace({sym: _sym}) raise NotImplementedError("The algorithm to find the Sum convergence of %s " "is not yet implemented" % (sequence_term)) def is_absolutely_convergent(self): """ Checks for the absolute convergence of an infinite series. Same as checking convergence of absolute value of sequence_term of an infinite series. References ========== .. [1] https://en.wikipedia.org/wiki/Absolute_convergence Examples ======== >>> from sympy import Sum, Symbol, oo >>> n = Symbol('n', integer=True) >>> Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent() False >>> Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent() True See Also ======== Sum.is_convergent() """ return Sum(abs(self.function), self.limits).is_convergent() def euler_maclaurin(self, m=0, n=0, eps=0, eval_integral=True): """ Return an Euler-Maclaurin approximation of self, where m is the number of leading terms to sum directly and n is the number of terms in the tail. With m = n = 0, this is simply the corresponding integral plus a first-order endpoint correction. Returns (s, e) where s is the Euler-Maclaurin approximation and e is the estimated error (taken to be the magnitude of the first omitted term in the tail): >>> from sympy.abc import k, a, b >>> from sympy import Sum >>> Sum(1/k, (k, 2, 5)).doit().evalf() 1.28333333333333 >>> s, e = Sum(1/k, (k, 2, 5)).euler_maclaurin() >>> s -log(2) + 7/20 + log(5) >>> from sympy import sstr >>> print(sstr((s.evalf(), e.evalf()), full_prec=True)) (1.26629073187415, 0.0175000000000000) The endpoints may be symbolic: >>> s, e = Sum(1/k, (k, a, b)).euler_maclaurin() >>> s -log(a) + log(b) + 1/(2*b) + 1/(2*a) >>> e Abs(1/(12*b**2) - 1/(12*a**2)) If the function is a polynomial of degree at most 2n+1, the Euler-Maclaurin formula becomes exact (and e = 0 is returned): >>> Sum(k, (k, 2, b)).euler_maclaurin() (b**2/2 + b/2 - 1, 0) >>> Sum(k, (k, 2, b)).doit() b**2/2 + b/2 - 1 With a nonzero eps specified, the summation is ended as soon as the remainder term is less than the epsilon. """ m = int(m) n = int(n) f = self.function if len(self.limits) != 1: raise ValueError("More than 1 limit") i, a, b = self.limits[0] if (a > b) == True: if a - b == 1: return S.Zero, S.Zero a, b = b + 1, a - 1 f = -f s = S.Zero if m: if b.is_Integer and a.is_Integer: m = min(m, b - a + 1) if not eps or f.is_polynomial(i): for k in range(m): s += f.subs(i, a + k) else: term = f.subs(i, a) if term: test = abs(term.evalf(3)) < eps if test == True: return s, abs(term) elif not (test == False): # a symbolic Relational class, can't go further return term, S.Zero s += term for k in range(1, m): term = f.subs(i, a + k) if abs(term.evalf(3)) < eps and term != 0: return s, abs(term) s += term if b - a + 1 == m: return s, S.Zero a += m x = Dummy('x') I = Integral(f.subs(i, x), (x, a, b)) if eval_integral: I = I.doit() s += I def fpoint(expr): if b is S.Infinity: return expr.subs(i, a), 0 return expr.subs(i, a), expr.subs(i, b) fa, fb = fpoint(f) iterm = (fa + fb)/2 g = f.diff(i) for k in range(1, n + 2): ga, gb = fpoint(g) term = bernoulli(2*k)/factorial(2*k)*(gb - ga) if k > n: break if eps and term: term_evalf = term.evalf(3) if term_evalf is S.NaN: return S.NaN, S.NaN if abs(term_evalf) < eps: break s += term g = g.diff(i, 2, simplify=False) return s + iterm, abs(term) def reverse_order(self, *indices): """ Reverse the order of a limit in a Sum. Explanation =========== ``reverse_order(self, *indices)`` reverses some limits in the expression ``self`` which can be either a ``Sum`` or a ``Product``. The selectors in the argument ``indices`` specify some indices whose limits get reversed. These selectors are either variable names or numerical indices counted starting from the inner-most limit tuple. Examples ======== >>> from sympy import Sum >>> from sympy.abc import x, y, a, b, c, d >>> Sum(x, (x, 0, 3)).reverse_order(x) Sum(-x, (x, 4, -1)) >>> Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(x, y) Sum(x*y, (x, 6, 0), (y, 7, -1)) >>> Sum(x, (x, a, b)).reverse_order(x) Sum(-x, (x, b + 1, a - 1)) >>> Sum(x, (x, a, b)).reverse_order(0) Sum(-x, (x, b + 1, a - 1)) While one should prefer variable names when specifying which limits to reverse, the index counting notation comes in handy in case there are several symbols with the same name. >>> S = Sum(x**2, (x, a, b), (x, c, d)) >>> S Sum(x**2, (x, a, b), (x, c, d)) >>> S0 = S.reverse_order(0) >>> S0 Sum(-x**2, (x, b + 1, a - 1), (x, c, d)) >>> S1 = S0.reverse_order(1) >>> S1 Sum(x**2, (x, b + 1, a - 1), (x, d + 1, c - 1)) Of course we can mix both notations: >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) See Also ======== sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index, reorder_limit, sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder References ========== .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM, Volume 28 Issue 2, April 1981, Pages 305-350 http://dl.acm.org/citation.cfm?doid=322248.322255 """ l_indices = list(indices) for i, indx in enumerate(l_indices): if not isinstance(indx, int): l_indices[i] = self.index(indx) e = 1 limits = [] for i, limit in enumerate(self.limits): l = limit if i in l_indices: e = -e l = (limit[0], limit[2] + 1, limit[1] - 1) limits.append(l) return Sum(e * self.function, *limits) def summation(f, *symbols, **kwargs): r""" Compute the summation of f with respect to symbols. Explanation =========== The notation for symbols is similar to the notation used in Integral. summation(f, (i, a, b)) computes the sum of f with respect to i from a to b, i.e., :: b ____ \ ` summation(f, (i, a, b)) = ) f /___, i = a If it cannot compute the sum, it returns an unevaluated Sum object. Repeated sums can be computed by introducing additional symbols tuples:: Examples ======== >>> from sympy import summation, oo, symbols, log >>> i, n, m = symbols('i n m', integer=True) >>> summation(2*i - 1, (i, 1, n)) n**2 >>> summation(1/2**i, (i, 0, oo)) 2 >>> summation(1/log(n)**n, (n, 2, oo)) Sum(log(n)**(-n), (n, 2, oo)) >>> summation(i, (i, 0, n), (n, 0, m)) m**3/6 + m**2/2 + m/3 >>> from sympy.abc import x >>> from sympy import factorial >>> summation(x**n/factorial(n), (n, 0, oo)) exp(x) See Also ======== Sum Product, sympy.concrete.products.product """ return Sum(f, *symbols, **kwargs).doit(deep=False) def telescopic_direct(L, R, n, limits): """ Returns the direct summation of the terms of a telescopic sum Explanation =========== L is the term with lower index R is the term with higher index n difference between the indexes of L and R Examples ======== >>> from sympy.concrete.summations import telescopic_direct >>> from sympy.abc import k, a, b >>> telescopic_direct(1/k, -1/(k+2), 2, (k, a, b)) -1/(b + 2) - 1/(b + 1) + 1/(a + 1) + 1/a """ (i, a, b) = limits s = 0 for m in range(n): s += L.subs(i, a + m) + R.subs(i, b - m) return s def telescopic(L, R, limits): ''' Tries to perform the summation using the telescopic property. Return None if not possible. ''' (i, a, b) = limits if L.is_Add or R.is_Add: return None # We want to solve(L.subs(i, i + m) + R, m) # First we try a simple match since this does things that # solve doesn't do, e.g. solve(f(k+m)-f(k), m) fails k = Wild("k") sol = (-R).match(L.subs(i, i + k)) s = None if sol and k in sol: s = sol[k] if not (s.is_Integer and L.subs(i, i + s) == -R): # sometimes match fail(f(x+2).match(-f(x+k))->{k: -2 - 2x})) s = None # But there are things that match doesn't do that solve # can do, e.g. determine that 1/(x + m) = 1/(1 - x) when m = 1 if s is None: m = Dummy('m') try: sol = solve(L.subs(i, i + m) + R, m) or [] except NotImplementedError: return None sol = [si for si in sol if si.is_Integer and (L.subs(i, i + si) + R).expand().is_zero] if len(sol) != 1: return None s = sol[0] if s < 0: return telescopic_direct(R, L, abs(s), (i, a, b)) elif s > 0: return telescopic_direct(L, R, s, (i, a, b)) def eval_sum(f, limits): (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. # We should try to transform to partial fractions value = eval_sum_symbolic(f.expand(), (i, a, b)) if value is not None: return value # Do it directly if definite: return eval_sum_direct(f, (i, a, b)) def eval_sum_direct(expr, limits): """ Evaluate expression directly, but perform some simple checks first to possibly result in a smaller expression and faster execution. """ (i, a, b) = limits dif = b - a # Linearity if expr.is_Mul: # Try factor out everything not including i without_i, with_i = expr.as_independent(i) if without_i != 1: s = eval_sum_direct(with_i, (i, a, b)) if s: r = without_i*s if r is not S.NaN: return r else: # Try term by term L, R = expr.as_two_terms() if not L.has(i): sR = eval_sum_direct(R, (i, a, b)) if sR: return L*sR if not R.has(i): sL = eval_sum_direct(L, (i, a, b)) if sL: return sL*R try: expr = apart(expr, i) # see if it becomes an Add except PolynomialError: pass if expr.is_Add: # Try factor out everything not including i without_i, with_i = expr.as_independent(i) if without_i != 0: s = eval_sum_direct(with_i, (i, a, b)) if s: r = without_i*(dif + 1) + s if r is not S.NaN: return r else: # Try term by term L, R = expr.as_two_terms() lsum = eval_sum_direct(L, (i, a, b)) rsum = eval_sum_direct(R, (i, a, b)) if None not in (lsum, rsum): r = lsum + rsum if r is not S.NaN: return r return Add(*[expr.subs(i, a + j) for j in range(dif + 1)]) def eval_sum_symbolic(f, limits): f_orig = f (i, a, b) = limits if not f.has(i): return f*(b - a + 1) # Linearity if f.is_Mul: # Try factor out everything not including i without_i, with_i = f.as_independent(i) if without_i != 1: s = eval_sum_symbolic(with_i, (i, a, b)) if s: r = without_i*s if r is not S.NaN: return r else: # Try term by term L, R = f.as_two_terms() if not L.has(i): sR = eval_sum_symbolic(R, (i, a, b)) if sR: return L*sR if not R.has(i): sL = eval_sum_symbolic(L, (i, a, b)) if sL: return sL*R try: f = apart(f, i) # see if it becomes an Add except PolynomialError: pass if f.is_Add: L, R = f.as_two_terms() lrsum = telescopic(L, R, (i, a, b)) if lrsum: return lrsum # Try factor out everything not including i without_i, with_i = f.as_independent(i) if without_i != 0: s = eval_sum_symbolic(with_i, (i, a, b)) if s: r = without_i*(b - a + 1) + s if r is not S.NaN: return r else: # Try term by term lsum = eval_sum_symbolic(L, (i, a, b)) rsum = eval_sum_symbolic(R, (i, a, b)) if None not in (lsum, rsum): r = lsum + rsum if r is not S.NaN: return r # Polynomial terms with Faulhaber's formula n = Wild('n') result = f.match(i**n) if result is not None: n = result[n] if n.is_Integer: if n >= 0: if (b is S.Infinity and 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)): 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: if simplify(f.subs(i, Dummy('i', integer=True, positive=True))) == 0: return S.Zero, True return _eval_sum_hyper(f.subs(i, i + 1), i, 0) hs = hypersimp(f, i) if hs is None: return None if isinstance(hs, Float): hs = nsimplify(hs) numer, denom = fraction(factor(hs)) top, topl = numer.as_coeff_mul(i) bot, botl = denom.as_coeff_mul(i) ab = [top, bot] factors = [topl, botl] params = [[], []] for k in range(2): for fac in factors[k]: mul = 1 if fac.is_Pow: mul = fac.exp fac = fac.base if not mul.is_Integer: return None p = Poly(fac, i) if p.degree() != 1: return None m, n = p.all_coeffs() ab[k] *= m**mul params[k] += [n/m]*mul # Add "1" to numerator parameters, to account for implicit n! in # hypergeometric series. ap = params[0] + [1] bq = params[1] x = ab[0]/ab[1] h = hyper(ap, bq, x) f = combsimp(f) return f.subs(i, 0)*hyperexpand(h), h.convergence_statement def eval_sum_hyper(f, i_a_b): i, a, b = i_a_b if (b - a).is_Integer: # We are never going to do better than doing the sum in the obvious way return None old_sum = Sum(f, (i, a, b)) if b != S.Infinity: if a is S.NegativeInfinity: res = _eval_sum_hyper(f.subs(i, -i), i, -b) if res is not None: return Piecewise(res, (old_sum, True)) else: res1 = _eval_sum_hyper(f, i, a) res2 = _eval_sum_hyper(f, i, b + 1) if res1 is None or res2 is None: return None (res1, cond1), (res2, cond2) = res1, res2 cond = And(cond1, cond2) if cond == False: return None return Piecewise((res1 - res2, cond), (old_sum, True)) if a is S.NegativeInfinity: res1 = _eval_sum_hyper(f.subs(i, -i), i, 1) res2 = _eval_sum_hyper(f, i, 0) if res1 is None or res2 is None: return None res1, cond1 = res1 res2, cond2 = res2 cond = And(cond1, cond2) if cond == False or cond.as_set() == S.EmptySet: return None return Piecewise((res1 + res2, cond), (old_sum, True)) # Now b == oo, a != -oo res = _eval_sum_hyper(f, i, a) if res is not None: r, c = res if c == False: if r.is_number: f = f.subs(i, Dummy('i', integer=True, positive=True) + a) if f.is_positive or f.is_zero: return S.Infinity elif f.is_negative: return S.NegativeInfinity return None return Piecewise(res, (old_sum, True)) def eval_sum_residue(f, i_a_b): r"""Compute the infinite summation with residues Notes ===== If $f(n), g(n)$ are polynomials with $\deg(g(n)) - \deg(f(n)) \ge 2$, some infinite summations can be computed by the following residue evaluations. .. math:: \sum_{n=-\infty, g(n) \ne 0}^{\infty} \frac{f(n)}{g(n)} = -\pi \sum_{\alpha|g(\alpha)=0} \text{Res}(\cot(\pi x) \frac{f(x)}{g(x)}, \alpha) .. math:: \sum_{n=-\infty, g(n) \ne 0}^{\infty} (-1)^n \frac{f(n)}{g(n)} = -\pi \sum_{\alpha|g(\alpha)=0} \text{Res}(\csc(\pi x) \frac{f(x)}{g(x)}, \alpha) Examples ======== >>> from sympy import Sum, oo, Symbol >>> x = Symbol('x') Doubly infinite series of rational functions. >>> Sum(1 / (x**2 + 1), (x, -oo, oo)).doit() pi/tanh(pi) Doubly infinite alternating series of rational functions. >>> Sum((-1)**x / (x**2 + 1), (x, -oo, oo)).doit() pi/sinh(pi) Infinite series of even rational functions. >>> Sum(1 / (x**2 + 1), (x, 0, oo)).doit() 1/2 + pi/(2*tanh(pi)) Infinite series of alternating even rational functions. >>> Sum((-1)**x / (x**2 + 1), (x, 0, oo)).doit() pi/(2*sinh(pi)) + 1/2 This also have heuristics to transform arbitrarily shifted summand or arbitrarily shifted summation range to the canonical problem the formula can handle. >>> Sum(1 / (x**2 + 2*x + 2), (x, -1, oo)).doit() 1/2 + pi/(2*tanh(pi)) >>> Sum(1 / (x**2 + 4*x + 5), (x, -2, oo)).doit() 1/2 + pi/(2*tanh(pi)) >>> Sum(1 / (x**2 + 1), (x, 1, oo)).doit() -1/2 + pi/(2*tanh(pi)) >>> Sum(1 / (x**2 + 1), (x, 2, oo)).doit() -1 + pi/(2*tanh(pi)) References ========== .. [#] http://www.supermath.info/InfiniteSeriesandtheResidueTheorem.pdf .. [#] Asmar N.H., Grafakos L. (2018) Residue Theory. In: Complex Analysis with Applications. Undergraduate Texts in Mathematics. Springer, Cham. https://doi.org/10.1007/978-3-319-94063-2_5 """ i, a, b = i_a_b def is_even_function(numer, denom): """Test if the rational function is an even function""" numer_even = all(i % 2 == 0 for (i,) in numer.monoms()) denom_even = all(i % 2 == 0 for (i,) in denom.monoms()) numer_odd = all(i % 2 == 1 for (i,) in numer.monoms()) denom_odd = all(i % 2 == 1 for (i,) in denom.monoms()) return (numer_even and denom_even) or (numer_odd and denom_odd) def match_rational(f, i): numer, denom = f.as_numer_denom() try: (numer, denom), opt = parallel_poly_from_expr((numer, denom), i) except (PolificationFailed, PolynomialError): return None return numer, denom def get_poles(denom): roots = denom.sqf_part().all_roots() roots = sift(roots, lambda x: x.is_integer) if None in roots: return None int_roots, nonint_roots = roots[True], roots[False] return int_roots, nonint_roots def get_shift(denom): n = denom.degree(i) a = denom.coeff_monomial(i**n) b = denom.coeff_monomial(i**(n-1)) shift = - b / a / n return shift def get_residue_factor(numer, denom, alternating): if not alternating: residue_factor = (numer.as_expr() / denom.as_expr()) * cot(S.Pi * i) else: residue_factor = (numer.as_expr() / denom.as_expr()) * csc(S.Pi * i) return residue_factor # We don't know how to deal with symbolic constants in summand if f.free_symbols - set([i]): return None if not (a.is_Integer or a in (S.Infinity, S.NegativeInfinity)): return None if not (b.is_Integer or b in (S.Infinity, S.NegativeInfinity)): return None # Quick exit heuristic for the sums which doesn't have infinite range if a != S.NegativeInfinity and b != S.Infinity: return None match = match_rational(f, i) if match: alternating = False numer, denom = match else: match = match_rational(f / S.NegativeOne**i, i) if match: alternating = True numer, denom = match else: return None if denom.degree(i) - numer.degree(i) < 2: return None if (a, b) == (S.NegativeInfinity, S.Infinity): poles = get_poles(denom) if poles is None: return None int_roots, nonint_roots = poles if int_roots: return None residue_factor = get_residue_factor(numer, denom, alternating) residues = [residue(residue_factor, i, root) for root in nonint_roots] return -S.Pi * sum(residues) if not (a.is_finite and b is S.Infinity): return None if not is_even_function(numer, denom): # Try shifting summation and check if the summand can be made # and even function from the origin. # Sum(f(n), (n, a, b)) => Sum(f(n + s), (n, a - s, b - s)) shift = get_shift(denom) if not shift.is_Integer: return None if shift == 0: return None numer = numer.shift(shift) denom = denom.shift(shift) if not is_even_function(numer, denom): return None if alternating: f = S.NegativeOne**i * (S.NegativeOne**shift * numer.as_expr() / denom.as_expr()) else: f = numer.as_expr() / denom.as_expr() return eval_sum_residue(f, (i, a-shift, b-shift)) poles = get_poles(denom) if poles is None: return None int_roots, nonint_roots = poles if int_roots: int_roots = [int(root) for root in int_roots] int_roots_max = max(int_roots) int_roots_min = min(int_roots) # Integer valued poles must be next to each other # and also symmetric from origin (Because the function is even) if not len(int_roots) == int_roots_max - int_roots_min + 1: return None # Check whether the summation indices contain poles if a <= max(int_roots): return None residue_factor = get_residue_factor(numer, denom, alternating) residues = [residue(residue_factor, i, root) for root in int_roots + nonint_roots] full_sum = -S.Pi * sum(residues) if not int_roots: # Compute Sum(f, (i, 0, oo)) by adding a extraneous evaluation # at the origin. half_sum = (full_sum + f.xreplace({i: 0})) / 2 # Add and subtract extraneous evaluations extraneous_neg = [f.xreplace({i: i0}) for i0 in range(int(a), 0)] extraneous_pos = [f.xreplace({i: i0}) for i0 in range(0, int(a))] result = half_sum + sum(extraneous_neg) - sum(extraneous_pos) return result # Compute Sum(f, (i, min(poles) + 1, oo)) half_sum = full_sum / 2 # Subtract extraneous evaluations extraneous = [f.xreplace({i: i0}) for i0 in range(max(int_roots) + 1, int(a))] result = half_sum - sum(extraneous) return result def _eval_matrix_sum(expression): f = expression.function for n, limit in enumerate(expression.limits): i, a, b = limit dif = b - a if dif.is_Integer: if (dif < 0) == True: a, b = b + 1, a - 1 f = -f newf = eval_sum_direct(f, (i, a, b)) if newf is not None: return newf.doit() def _dummy_with_inherited_properties_concrete(limits): """ Return a Dummy symbol that inherits as many assumptions as possible from the provided symbol and limits. If the symbol already has all True assumption shared by the limits then return None. """ x, a, b = limits l = [a, b] assumptions_to_consider = ['extended_nonnegative', 'nonnegative', 'extended_nonpositive', 'nonpositive', 'extended_positive', 'positive', 'extended_negative', 'negative', 'integer', 'rational', 'finite', 'zero', 'real', 'extended_real'] assumptions_to_keep = {} assumptions_to_add = {} for assum in assumptions_to_consider: assum_true = x._assumptions.get(assum, None) if assum_true: assumptions_to_keep[assum] = True elif all(getattr(i, 'is_' + assum) for i in l): assumptions_to_add[assum] = True if assumptions_to_add: assumptions_to_keep.update(assumptions_to_add) return Dummy('d', **assumptions_to_keep)
53cd5f150eccb306c98185b501688f656e0e81a3ad9947bdbe43a078c85b50c8
""" Limits ====== Implemented according to the PhD thesis http://www.cybertester.com/data/gruntz.pdf, which contains very thorough descriptions of the algorithm including many examples. We summarize here the gist of it. All functions are sorted according to how rapidly varying they are at infinity using the following rules. Any two functions f and g can be compared using the properties of L: L=lim log|f(x)| / log|g(x)| (for x -> oo) We define >, < ~ according to:: 1. f > g .... L=+-oo we say that: - f is greater than any power of g - f is more rapidly varying than g - f goes to infinity/zero faster than g 2. f < g .... L=0 we say that: - f is lower than any power of g 3. f ~ g .... L!=0, +-oo we say that: - both f and g are bounded from above and below by suitable integral powers of the other Examples ======== :: 2 < x < exp(x) < exp(x**2) < exp(exp(x)) 2 ~ 3 ~ -5 x ~ x**2 ~ x**3 ~ 1/x ~ x**m ~ -x exp(x) ~ exp(-x) ~ exp(2x) ~ exp(x)**2 ~ exp(x+exp(-x)) f ~ 1/f So we can divide all the functions into comparability classes (x and x^2 belong to one class, exp(x) and exp(-x) belong to some other class). In principle, we could compare any two functions, but in our algorithm, we do not compare anything below the class 2~3~-5 (for example log(x) is below this), so we set 2~3~-5 as the lowest comparability class. Given the function f, we find the list of most rapidly varying (mrv set) subexpressions of it. This list belongs to the same comparability class. Let's say it is {exp(x), exp(2x)}. Using the rule f ~ 1/f we find an element "w" (either from the list or a new one) from the same comparability class which goes to zero at infinity. In our example we set w=exp(-x) (but we could also set w=exp(-2x) or w=exp(-3x) ...). We rewrite the mrv set using w, in our case {1/w, 1/w^2}, and substitute it into f. Then we expand f into a series in w:: f = c0*w^e0 + c1*w^e1 + ... + O(w^en), where e0<e1<...<en, c0!=0 but for x->oo, lim f = lim c0*w^e0, because all the other terms go to zero, because w goes to zero faster than the ci and ei. So:: for e0>0, lim f = 0 for e0<0, lim f = +-oo (the sign depends on the sign of c0) for e0=0, lim f = lim c0 We need to recursively compute limits at several places of the algorithm, but as is shown in the PhD thesis, it always finishes. Important functions from the implementation: compare(a, b, x) compares "a" and "b" by computing the limit L. mrv(e, x) returns list of most rapidly varying (mrv) subexpressions of "e" rewrite(e, Omega, x, wsym) rewrites "e" in terms of w leadterm(f, x) returns the lowest power term in the series of f mrv_leadterm(e, x) returns the lead term (c0, e0) for e limitinf(e, x) computes lim e (for x->oo) limit(e, z, z0) computes any limit by converting it to the case x->oo All the functions are really simple and straightforward except rewrite(), which is the most difficult/complex part of the algorithm. When the algorithm fails, the bugs are usually in the series expansion (i.e. in SymPy) or in rewrite. This code is almost exact rewrite of the Maple code inside the Gruntz thesis. Debugging --------- Because the gruntz algorithm is highly recursive, it's difficult to figure out what went wrong inside a debugger. Instead, turn on nice debug prints by defining the environment variable SYMPY_DEBUG. For example: [user@localhost]: SYMPY_DEBUG=True ./bin/isympy In [1]: limit(sin(x)/x, x, 0) limitinf(_x*sin(1/_x), _x) = 1 +-mrv_leadterm(_x*sin(1/_x), _x) = (1, 0) | +-mrv(_x*sin(1/_x), _x) = set([_x]) | | +-mrv(_x, _x) = set([_x]) | | +-mrv(sin(1/_x), _x) = set([_x]) | | +-mrv(1/_x, _x) = set([_x]) | | +-mrv(_x, _x) = set([_x]) | +-mrv_leadterm(exp(_x)*sin(exp(-_x)), _x, set([exp(_x)])) = (1, 0) | +-rewrite(exp(_x)*sin(exp(-_x)), set([exp(_x)]), _x, _w) = (1/_w*sin(_w), -_x) | +-sign(_x, _x) = 1 | +-mrv_leadterm(1, _x) = (1, 0) +-sign(0, _x) = 0 +-limitinf(1, _x) = 1 And check manually which line is wrong. Then go to the source code and debug this function to figure out the exact problem. """ from functools import reduce from sympy.core import Basic, S, Mul, PoleError from sympy.core.cache import cacheit from sympy.core.numbers import ilcm, I, oo from sympy.core.symbol import Dummy, Wild from sympy.core.traversal import bottom_up from sympy.functions import log, exp, sign as _sign from sympy.series.order import Order from sympy.simplify import logcombine from sympy.simplify.powsimp import powsimp, powdenest from sympy.utilities.misc import debug_decorator as debug from sympy.utilities.timeutils import timethis timeit = timethis('gruntz') def compare(a, b, x): """Returns "<" if a<b, "=" for a == b, ">" for a>b""" # log(exp(...)) must always be simplified here for termination la, lb = log(a), log(b) if isinstance(a, Basic) and (isinstance(a, exp) or (a.is_Pow and a.base == S.Exp1)): la = a.exp if isinstance(b, Basic) and (isinstance(b, exp) or (b.is_Pow and b.base == S.Exp1)): lb = b.exp c = limitinf(la/lb, x) if c == 0: return "<" elif c.is_infinite: return ">" else: return "=" class SubsSet(dict): """ Stores (expr, dummy) pairs, and how to rewrite expr-s. Explanation =========== The gruntz algorithm needs to rewrite certain expressions in term of a new variable w. We cannot use subs, because it is just too smart for us. For example:: > Omega=[exp(exp(_p - exp(-_p))/(1 - 1/_p)), exp(exp(_p))] > O2=[exp(-exp(_p) + exp(-exp(-_p))*exp(_p)/(1 - 1/_p))/_w, 1/_w] > e = exp(exp(_p - exp(-_p))/(1 - 1/_p)) - exp(exp(_p)) > e.subs(Omega[0],O2[0]).subs(Omega[1],O2[1]) -1/w + exp(exp(p)*exp(-exp(-p))/(1 - 1/p)) is really not what we want! So we do it the hard way and keep track of all the things we potentially want to substitute by dummy variables. Consider the expression:: exp(x - exp(-x)) + exp(x) + x. The mrv set is {exp(x), exp(-x), exp(x - exp(-x))}. We introduce corresponding dummy variables d1, d2, d3 and rewrite:: d3 + d1 + x. This class first of all keeps track of the mapping expr->variable, i.e. will at this stage be a dictionary:: {exp(x): d1, exp(-x): d2, exp(x - exp(-x)): d3}. [It turns out to be more convenient this way round.] But sometimes expressions in the mrv set have other expressions from the mrv set as subexpressions, and we need to keep track of that as well. In this case, d3 is really exp(x - d2), so rewrites at this stage is:: {d3: exp(x-d2)}. The function rewrite uses all this information to correctly rewrite our expression in terms of w. In this case w can be chosen to be exp(-x), i.e. d2. The correct rewriting then is:: exp(-w)/w + 1/w + x. """ def __init__(self): self.rewrites = {} def __repr__(self): return super().__repr__() + ', ' + self.rewrites.__repr__() def __getitem__(self, key): if key not in self: self[key] = Dummy() return dict.__getitem__(self, key) def do_subs(self, e): """Substitute the variables with expressions""" for expr, var in self.items(): e = e.xreplace({var: expr}) return e def meets(self, s2): """Tell whether or not self and s2 have non-empty intersection""" return set(self.keys()).intersection(list(s2.keys())) != set() def union(self, s2, exps=None): """Compute the union of self and s2, adjusting exps""" res = self.copy() tr = {} for expr, var in s2.items(): if expr in self: if exps: exps = exps.xreplace({var: res[expr]}) tr[var] = res[expr] else: res[expr] = var for var, rewr in s2.rewrites.items(): res.rewrites[var] = rewr.xreplace(tr) return res, exps def copy(self): """Create a shallow copy of SubsSet""" r = SubsSet() r.rewrites = self.rewrites.copy() for expr, var in self.items(): r[expr] = var return r @debug def mrv(e, x): """Returns a SubsSet of most rapidly varying (mrv) subexpressions of 'e', and e rewritten in terms of these""" e = powsimp(e, deep=True, combine='exp') if not isinstance(e, Basic): raise TypeError("e should be an instance of Basic") if not e.has(x): return SubsSet(), e elif e == x: s = SubsSet() return s, s[x] elif e.is_Mul or e.is_Add: i, d = e.as_independent(x) # throw away x-independent terms if d.func != e.func: s, expr = mrv(d, x) return s, e.func(i, expr) a, b = d.as_two_terms() s1, e1 = mrv(a, x) s2, e2 = mrv(b, x) return mrv_max1(s1, s2, e.func(i, e1, e2), x) elif e.is_Pow and e.base != S.Exp1: e1 = S.One while e.is_Pow: b1 = e.base e1 *= e.exp e = b1 if b1 == 1: return SubsSet(), b1 if e1.has(x): base_lim = limitinf(b1, x) if base_lim is S.One: return mrv(exp(e1 * (b1 - 1)), x) return mrv(exp(e1 * log(b1)), x) else: s, expr = mrv(b1, x) return s, expr**e1 elif isinstance(e, log): s, expr = mrv(e.args[0], x) return s, log(expr) elif isinstance(e, exp) or (e.is_Pow and e.base == S.Exp1): # We know from the theory of this algorithm that exp(log(...)) may always # be simplified here, and doing so is vital for termination. if isinstance(e.exp, log): return mrv(e.exp.args[0], x) # if a product has an infinite factor the result will be # infinite if there is no zero, otherwise NaN; here, we # consider the result infinite if any factor is infinite li = limitinf(e.exp, x) if any(_.is_infinite for _ in Mul.make_args(li)): s1 = SubsSet() e1 = s1[e] s2, e2 = mrv(e.exp, x) su = s1.union(s2)[0] su.rewrites[e1] = exp(e2) return mrv_max3(s1, e1, s2, exp(e2), su, e1, x) else: s, expr = mrv(e.exp, x) return s, exp(expr) elif e.is_Function: l = [mrv(a, x) for a in e.args] l2 = [s for (s, _) in l if s != SubsSet()] if len(l2) != 1: # e.g. something like BesselJ(x, x) raise NotImplementedError("MRV set computation for functions in" " several variables not implemented.") s, ss = l2[0], SubsSet() args = [ss.do_subs(x[1]) for x in l] return s, e.func(*args) elif e.is_Derivative: raise NotImplementedError("MRV set computation for derviatives" " not implemented yet.") raise NotImplementedError( "Don't know how to calculate the mrv of '%s'" % e) def mrv_max3(f, expsf, g, expsg, union, expsboth, x): """ Computes the maximum of two sets of expressions f and g, which are in the same comparability class, i.e. max() compares (two elements of) f and g and returns either (f, expsf) [if f is larger], (g, expsg) [if g is larger] or (union, expsboth) [if f, g are of the same class]. """ if not isinstance(f, SubsSet): raise TypeError("f should be an instance of SubsSet") if not isinstance(g, SubsSet): raise TypeError("g should be an instance of SubsSet") if f == SubsSet(): return g, expsg elif g == SubsSet(): return f, expsf elif f.meets(g): return union, expsboth c = compare(list(f.keys())[0], list(g.keys())[0], x) if c == ">": return f, expsf elif c == "<": return g, expsg else: if c != "=": raise ValueError("c should be =") return union, expsboth def mrv_max1(f, g, exps, x): """Computes the maximum of two sets of expressions f and g, which are in the same comparability class, i.e. mrv_max1() compares (two elements of) f and g and returns the set, which is in the higher comparability class of the union of both, if they have the same order of variation. Also returns exps, with the appropriate substitutions made. """ u, b = f.union(g, exps) return mrv_max3(f, g.do_subs(exps), g, f.do_subs(exps), u, b, x) @debug @cacheit @timeit def sign(e, x): """ Returns a sign of an expression e(x) for x->oo. :: e > 0 for x sufficiently large ... 1 e == 0 for x sufficiently large ... 0 e < 0 for x sufficiently large ... -1 The result of this function is currently undefined if e changes sign arbitrarily often for arbitrarily large x (e.g. sin(x)). Note that this returns zero only if e is *constantly* zero for x sufficiently large. [If e is constant, of course, this is just the same thing as the sign of e.] """ if not isinstance(e, Basic): raise TypeError("e should be an instance of Basic") if e.is_positive: return 1 elif e.is_negative: return -1 elif e.is_zero: return 0 elif not e.has(x): e = logcombine(e) return _sign(e) elif e == x: return 1 elif e.is_Mul: a, b = e.as_two_terms() sa = sign(a, x) if not sa: return 0 return sa * sign(b, x) elif isinstance(e, exp): return 1 elif e.is_Pow: if e.base == S.Exp1: return 1 s = sign(e.base, x) if s == 1: return 1 if e.exp.is_Integer: return s**e.exp elif isinstance(e, log): return sign(e.args[0] - 1, x) # if all else fails, do it the hard way c0, e0 = mrv_leadterm(e, x) return sign(c0, x) @debug @timeit @cacheit def limitinf(e, x, leadsimp=False): """Limit e(x) for x-> oo. Explanation =========== If ``leadsimp`` is True, an attempt is made to simplify the leading term of the series expansion of ``e``. That may succeed even if ``e`` cannot be simplified. """ # rewrite e in terms of tractable functions only if not e.has(x): return e # e is a constant if e.has(Order): e = e.expand().removeO() if not x.is_positive or x.is_integer: # We make sure that x.is_positive is True and x.is_integer is None # so we get all the correct mathematical behavior from the expression. # We need a fresh variable. p = Dummy('p', positive=True) e = e.subs(x, p) x = p e = e.rewrite('tractable', deep=True, limitvar=x) e = powdenest(e) c0, e0 = mrv_leadterm(e, x) sig = sign(e0, x) if sig == 1: return S.Zero # e0>0: lim f = 0 elif sig == -1: # e0<0: lim f = +-oo (the sign depends on the sign of c0) if c0.match(I*Wild("a", exclude=[I])): return c0*oo s = sign(c0, x) # the leading term shouldn't be 0: if s == 0: raise ValueError("Leading term should not be 0") return s*oo elif sig == 0: if leadsimp: c0 = c0.simplify() return limitinf(c0, x, leadsimp) # e0=0: lim f = lim c0 else: raise ValueError("{} could not be evaluated".format(sig)) def moveup2(s, x): r = SubsSet() for expr, var in s.items(): r[expr.xreplace({x: exp(x)})] = var for var, expr in s.rewrites.items(): r.rewrites[var] = s.rewrites[var].xreplace({x: exp(x)}) return r def moveup(l, x): return [e.xreplace({x: exp(x)}) for e in l] @debug @timeit def calculate_series(e, x, logx=None): """ Calculates at least one term of the series of ``e`` in ``x``. This is a place that fails most often, so it is in its own function. """ for t in e.lseries(x, logx=logx): # bottom_up function is required for a specific case - when e is # -exp(p/(p + 1)) + exp(-p**2/(p + 1) + p) t = bottom_up(t, lambda w: getattr(w, 'normal', lambda: w)()) # And the expression # `(-sin(1/x) + sin((x + exp(x))*exp(-x)/x))*exp(x)` # from the first test of test_gruntz_eval_special needs to # be expanded. But other forms need to be have at least # factor_terms applied. `factor` accomplishes both and is # faster than using `factor_terms` for the gruntz suite. It # does not appear that use of `cancel` is necessary. # t = cancel(t, expand=False) t = t.factor() if t.has(exp) and t.has(log): t = powdenest(t) if not t.is_zero: break return t @debug @timeit @cacheit def mrv_leadterm(e, x): """Returns (c0, e0) for e.""" Omega = SubsSet() if not e.has(x): return (e, S.Zero) if Omega == SubsSet(): Omega, exps = mrv(e, x) if not Omega: # e really does not depend on x after simplification return exps, S.Zero if x in Omega: # move the whole omega up (exponentiate each term): Omega_up = moveup2(Omega, x) exps_up = moveup([exps], x)[0] # NOTE: there is no need to move this down! Omega = Omega_up exps = exps_up # # The positive dummy, w, is used here so log(w*2) etc. will expand; # a unique dummy is needed in this algorithm # # For limits of complex functions, the algorithm would have to be # improved, or just find limits of Re and Im components separately. # w = Dummy("w", positive=True) f, logw = rewrite(exps, Omega, x, w) series = calculate_series(f, w, logx=logw) try: lt = series.leadterm(w, logx=logw) except (ValueError, PoleError): lt = f.as_coeff_exponent(w) # as_coeff_exponent won't always split in required form. It may simply # return (f, 0) when a better form may be obtained. Example (-x)**(-pi) # can be written as (-1**(-pi), -pi) which as_coeff_exponent does not return if lt[0].has(w): base = f.as_base_exp()[0].as_coeff_exponent(w) ex = f.as_base_exp()[1] lt = (base[0]**ex, base[1]*ex) return (lt[0].subs(log(w), logw), lt[1]) def build_expression_tree(Omega, rewrites): r""" Helper function for rewrite. We need to sort Omega (mrv set) so that we replace an expression before we replace any expression in terms of which it has to be rewritten:: e1 ---> e2 ---> e3 \ -> e4 Here we can do e1, e2, e3, e4 or e1, e2, e4, e3. To do this we assemble the nodes into a tree, and sort them by height. This function builds the tree, rewrites then sorts the nodes. """ class Node: def __init__(self): self.before = [] self.expr = None self.var = None def ht(self): return reduce(lambda x, y: x + y, [x.ht() for x in self.before], 1) nodes = {} for expr, v in Omega: n = Node() n.var = v n.expr = expr nodes[v] = n for _, v in Omega: if v in rewrites: n = nodes[v] r = rewrites[v] for _, v2 in Omega: if r.has(v2): n.before.append(nodes[v2]) return nodes @debug @timeit def rewrite(e, Omega, x, wsym): """e(x) ... the function Omega ... the mrv set wsym ... the symbol which is going to be used for w Returns the rewritten e in terms of w and log(w). See test_rewrite1() for examples and correct results. """ if not isinstance(Omega, SubsSet): raise TypeError("Omega should be an instance of SubsSet") if len(Omega) == 0: raise ValueError("Length cannot be 0") # all items in Omega must be exponentials for t in Omega.keys(): if not isinstance(t, exp): raise ValueError("Value should be exp") rewrites = Omega.rewrites Omega = list(Omega.items()) nodes = build_expression_tree(Omega, rewrites) Omega.sort(key=lambda x: nodes[x[1]].ht(), reverse=True) # make sure we know the sign of each exp() term; after the loop, # g is going to be the "w" - the simplest one in the mrv set for g, _ in Omega: sig = sign(g.exp, x) if sig != 1 and sig != -1: raise NotImplementedError('Result depends on the sign of %s' % sig) if sig == 1: wsym = 1/wsym # if g goes to oo, substitute 1/w # O2 is a list, which results by rewriting each item in Omega using "w" O2 = [] denominators = [] for f, var in Omega: c = limitinf(f.exp/g.exp, x) if c.is_Rational: denominators.append(c.q) arg = f.exp if var in rewrites: if not isinstance(rewrites[var], exp): raise ValueError("Value should be exp") arg = rewrites[var].args[0] O2.append((var, exp((arg - c*g.exp).expand())*wsym**c)) # Remember that Omega contains subexpressions of "e". So now we find # them in "e" and substitute them for our rewriting, stored in O2 # the following powsimp is necessary to automatically combine exponentials, # so that the .xreplace() below succeeds: # TODO this should not be necessary f = powsimp(e, deep=True, combine='exp') for a, b in O2: f = f.xreplace({a: b}) for _, var in Omega: assert not f.has(var) # finally compute the logarithm of w (logw). logw = g.exp if sig == 1: logw = -logw # log(w)->log(1/w)=-log(w) # Some parts of SymPy have difficulty computing series expansions with # non-integral exponents. The following heuristic improves the situation: exponent = reduce(ilcm, denominators, 1) f = f.subs({wsym: wsym**exponent}) logw /= exponent return f, logw def gruntz(e, z, z0, dir="+"): """ Compute the limit of e(z) at the point z0 using the Gruntz algorithm. Explanation =========== ``z0`` can be any expression, including oo and -oo. For ``dir="+"`` (default) it calculates the limit from the right (z->z0+) and for ``dir="-"`` the limit from the left (z->z0-). For infinite z0 (oo or -oo), the dir argument doesn't matter. This algorithm is fully described in the module docstring in the gruntz.py file. It relies heavily on the series expansion. Most frequently, gruntz() is only used if the faster limit() function (which uses heuristics) fails. """ if not z.is_symbol: raise NotImplementedError("Second argument must be a Symbol") # convert all limits to the limit z->oo; sign of z is handled in limitinf r = None if z0 == oo: e0 = e elif z0 == -oo: e0 = e.subs(z, -z) else: if str(dir) == "-": e0 = e.subs(z, z0 - 1/z) elif str(dir) == "+": e0 = e.subs(z, z0 + 1/z) else: raise NotImplementedError("dir must be '+' or '-'") try: r = limitinf(e0, z) except ValueError: r = limitinf(e0, z, leadsimp=True) # This is a bit of a heuristic for nice results... we always rewrite # tractable functions in terms of familiar intractable ones. # It might be nicer to rewrite the exactly to what they were initially, # but that would take some work to implement. return r.rewrite('intractable', deep=True)
192244e760b1bf4b574a00229a8bff52d5c32fdff3083839c052f9691af52259
from sympy.calculus.accumulationbounds import AccumBounds from sympy.core import S, Symbol, Add, sympify, Expr, PoleError, Mul from sympy.core.exprtools import factor_terms from sympy.core.numbers import Float from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import (Abs, sign) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.special.gamma_functions import gamma from sympy.polys import PolynomialError, factor from sympy.series.order import Order from sympy.simplify.powsimp import powsimp from sympy.simplify.ratsimp import ratsimp from sympy.simplify.simplify import nsimplify, together from .gruntz import gruntz def limit(e, z, z0, dir="+"): """Computes the limit of ``e(z)`` at the point ``z0``. Parameters ========== e : expression, the limit of which is to be taken z : symbol representing the variable in the limit. Other symbols are treated as constants. Multivariate limits are not supported. z0 : the value toward which ``z`` tends. Can be any expression, including ``oo`` and ``-oo``. dir : string, optional (default: "+") The limit is bi-directional if ``dir="+-"``, from the right (z->z0+) if ``dir="+"``, and from the left (z->z0-) if ``dir="-"``. For infinite ``z0`` (``oo`` or ``-oo``), the ``dir`` argument is determined from the direction of the infinity (i.e., ``dir="-"`` for ``oo``). Examples ======== >>> from sympy import limit, sin, oo >>> from sympy.abc import x >>> limit(sin(x)/x, x, 0) 1 >>> limit(1/x, x, 0) # default dir='+' oo >>> limit(1/x, x, 0, dir="-") -oo >>> limit(1/x, x, 0, dir='+-') zoo >>> limit(1/x, x, oo) 0 Notes ===== First we try some heuristics for easy and frequent cases like "x", "1/x", "x**2" and similar, so that it's fast. For all other cases, we use the Gruntz algorithm (see the gruntz() function). See Also ======== limit_seq : returns the limit of a sequence. """ return Limit(e, z, z0, dir).doit(deep=False) def heuristics(e, z, z0, dir): """Computes the limit of an expression term-wise. Parameters are the same as for the ``limit`` function. Works with the arguments of expression ``e`` one by one, computing the limit of each and then combining the results. This approach works only for simple limits, but it is fast. """ rv = None if abs(z0) is S.Infinity: rv = limit(e.subs(z, 1/z), z, S.Zero, "+" if z0 is S.Infinity else "-") if isinstance(rv, Limit): return elif e.is_Mul or e.is_Add or e.is_Pow or e.is_Function: r = [] for a in e.args: l = limit(a, z, z0, dir) if l.has(S.Infinity) and l.is_finite is None: if isinstance(e, Add): m = factor_terms(e) if not isinstance(m, Mul): # try together m = together(m) if not isinstance(m, Mul): # try factor if the previous methods failed m = factor(e) if isinstance(m, Mul): return heuristics(m, z, z0, dir) return return elif isinstance(l, Limit): return elif l is S.NaN: return else: r.append(l) if r: rv = e.func(*r) if rv is S.NaN and e.is_Mul and any(isinstance(rr, AccumBounds) for rr in r): r2 = [] e2 = [] for ii in range(len(r)): if isinstance(r[ii], AccumBounds): r2.append(r[ii]) else: e2.append(e.args[ii]) if len(e2) > 0: e3 = Mul(*e2).simplify() l = limit(e3, z, z0, dir) rv = l * Mul(*r2) if rv is S.NaN: try: rat_e = ratsimp(e) except PolynomialError: return if rat_e is S.NaN or rat_e == e: return return limit(rat_e, z, z0, dir) return rv class Limit(Expr): """Represents an unevaluated limit. Examples ======== >>> from sympy import Limit, sin >>> from sympy.abc import x >>> Limit(sin(x)/x, x, 0) Limit(sin(x)/x, x, 0) >>> Limit(1/x, x, 0, dir="-") Limit(1/x, x, 0, dir='-') """ def __new__(cls, e, z, z0, dir="+"): e = sympify(e) z = sympify(z) z0 = sympify(z0) if z0 is S.Infinity: dir = "-" elif z0 is S.NegativeInfinity: dir = "+" if(z0.has(z)): raise NotImplementedError("Limits approaching a variable point are" " not supported (%s -> %s)" % (z, z0)) if isinstance(dir, str): dir = Symbol(dir) elif not isinstance(dir, Symbol): raise TypeError("direction must be of type basestring or " "Symbol, not %s" % type(dir)) if str(dir) not in ('+', '-', '+-'): raise ValueError("direction must be one of '+', '-' " "or '+-', not %s" % dir) obj = Expr.__new__(cls) obj._args = (e, z, z0, dir) return obj @property def free_symbols(self): e = self.args[0] isyms = e.free_symbols isyms.difference_update(self.args[1].free_symbols) isyms.update(self.args[2].free_symbols) return isyms def pow_heuristics(self, e): _, z, z0, _ = self.args b1, e1 = e.base, e.exp if not b1.has(z): res = limit(e1*log(b1), z, z0) return exp(res) ex_lim = limit(e1, z, z0) base_lim = limit(b1, z, z0) if base_lim is S.One: if ex_lim in (S.Infinity, S.NegativeInfinity): res = limit(e1*(b1 - 1), z, z0) return exp(res) if base_lim is S.NegativeInfinity and ex_lim is S.Infinity: return S.ComplexInfinity def doit(self, **hints): """Evaluates the limit. Parameters ========== deep : bool, optional (default: True) Invoke the ``doit`` method of the expressions involved before taking the limit. hints : optional keyword arguments To be passed to ``doit`` methods; only used if deep is True. """ e, z, z0, dir = self.args if z0 is S.ComplexInfinity: raise NotImplementedError("Limits at complex " "infinity are not implemented") if hints.get('deep', True): e = e.doit(**hints) z = z.doit(**hints) z0 = z0.doit(**hints) if e == z: return z0 if not e.has(z): return e if z0 is S.NaN: return S.NaN if e.has(S.Infinity, S.NegativeInfinity, S.ComplexInfinity, S.NaN): return self if e.is_Order: return Order(limit(e.expr, z, z0), *e.args[1:]) cdir = 0 if str(dir) == "+": cdir = 1 elif str(dir) == "-": cdir = -1 def set_signs(expr): if not expr.args: return expr newargs = tuple(set_signs(arg) for arg in expr.args) if newargs != expr.args: expr = expr.func(*newargs) abs_flag = isinstance(expr, Abs) sign_flag = isinstance(expr, sign) if abs_flag or sign_flag: sig = limit(expr.args[0], z, z0, dir) if sig.is_zero: sig = limit(1/expr.args[0], z, z0, dir) if sig.is_extended_real: if (sig < 0) == True: return -expr.args[0] if abs_flag else S.NegativeOne elif (sig > 0) == True: return expr.args[0] if abs_flag else S.One return expr if e.has(Float): # Convert floats like 0.5 to exact SymPy numbers like S.Half, to # prevent rounding errors which can lead to unexpected execution # of conditional blocks that work on comparisons # Also see comments in https://github.com/sympy/sympy/issues/19453 e = nsimplify(e) e = set_signs(e) if e.is_meromorphic(z, z0): if abs(z0) is S.Infinity: newe = e.subs(z, 1/z) # cdir changes sign as oo- should become 0+ cdir = -cdir else: newe = e.subs(z, z + z0) try: coeff, ex = newe.leadterm(z, cdir=cdir) except ValueError: pass else: if ex > 0: return S.Zero elif ex == 0: return coeff if cdir == 1 or not(int(ex) & 1): return S.Infinity*sign(coeff) elif cdir == -1: return S.NegativeInfinity*sign(coeff) else: return S.ComplexInfinity if abs(z0) is S.Infinity: if e.is_Mul: e = factor_terms(e) newe = e.subs(z, 1/z) # cdir changes sign as oo- should become 0+ cdir = -cdir else: newe = e.subs(z, z + z0) try: coeff, ex = newe.leadterm(z, cdir=cdir) except (ValueError, NotImplementedError, PoleError): # The NotImplementedError catching is for custom functions e = powsimp(e) if e.is_Pow: r = self.pow_heuristics(e) if r is not None: return r else: if coeff.has(S.Infinity, S.NegativeInfinity, S.ComplexInfinity): return self if not coeff.has(z): if ex.is_positive: return S.Zero elif ex == 0: return coeff elif ex.is_negative: if ex.is_integer: if cdir == 1 or ex.is_even: return S.Infinity*sign(coeff) elif cdir == -1: return S.NegativeInfinity*sign(coeff) else: return S.ComplexInfinity else: if cdir == 1: return S.Infinity*sign(coeff) elif cdir == -1: return S.Infinity*sign(coeff)*S.NegativeOne**ex else: return S.ComplexInfinity # gruntz fails on factorials but works with the gamma function # If no factorial term is present, e should remain unchanged. # factorial is defined to be zero for negative inputs (which # differs from gamma) so only rewrite for positive z0. if z0.is_extended_positive: e = e.rewrite(factorial, gamma) l = None try: if str(dir) == '+-': r = gruntz(e, z, z0, '+') l = gruntz(e, z, z0, '-') if l != r: raise ValueError("The limit does not exist since " "left hand limit = %s and right hand limit = %s" % (l, r)) else: r = gruntz(e, z, z0, dir) if r is S.NaN or l is S.NaN: raise PoleError() except (PoleError, ValueError): if l is not None: raise r = heuristics(e, z, z0, dir) if r is None: return self return r
58cd4b87745785264cd6041a26b8569d4b5812026e9cbba3204c35826b55858c
"""Limits of sequences""" from sympy.calculus.accumulationbounds import AccumulationBounds from sympy.core.add import Add from sympy.core.function import PoleError from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import Dummy from sympy.core.sympify import sympify from sympy.functions.combinatorial.numbers import fibonacci from sympy.functions.combinatorial.factorials import factorial, subfactorial from sympy.functions.special.gamma_functions import gamma from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.miscellaneous import Max, Min from sympy.functions.elementary.trigonometric import cos, sin from sympy.series.limits import Limit def difference_delta(expr, n=None, step=1): """Difference Operator. Explanation =========== Discrete analog of differential operator. Given a sequence x[n], returns the sequence x[n + step] - x[n]. Examples ======== >>> from sympy import difference_delta as dd >>> from sympy.abc import n >>> dd(n*(n + 1), n) 2*n + 2 >>> dd(n*(n + 1), n, 2) 4*n + 6 References ========== .. [1] https://reference.wolfram.com/language/ref/DifferenceDelta.html """ expr = sympify(expr) if n is None: f = expr.free_symbols if len(f) == 1: n = f.pop() elif len(f) == 0: return S.Zero else: raise ValueError("Since there is more than one variable in the" " expression, a variable must be supplied to" " take the difference of %s" % expr) step = sympify(step) if step.is_number is False or step.is_finite is False: raise ValueError("Step should be a finite number.") if hasattr(expr, '_eval_difference_delta'): result = expr._eval_difference_delta(n, step) if result: return result return expr.subs(n, n + step) - expr def dominant(expr, n): """Finds the dominant term in a sum, that is a term that dominates every other term. Explanation =========== If limit(a/b, n, oo) is oo then a dominates b. If limit(a/b, n, oo) is 0 then b dominates a. Otherwise, a and b are comparable. If there is no unique dominant term, then returns ``None``. Examples ======== >>> from sympy import Sum >>> from sympy.series.limitseq import dominant >>> from sympy.abc import n, k >>> dominant(5*n**3 + 4*n**2 + n + 1, n) 5*n**3 >>> dominant(2**n + Sum(k, (k, 0, n)), n) 2**n See Also ======== sympy.series.limitseq.dominant """ terms = Add.make_args(expr.expand(func=True)) term0 = terms[-1] comp = [term0] # comparable terms for t in terms[:-1]: r = term0/t e = r.gammasimp() if e == r: e = r.factor() l = limit_seq(e, n) if l is None: return None elif l.is_zero: term0 = t comp = [term0] elif l not in [S.Infinity, S.NegativeInfinity]: comp.append(t) if len(comp) > 1: return None return term0 def _limit_inf(expr, n): try: return Limit(expr, n, S.Infinity).doit(deep=False) except (NotImplementedError, PoleError): return None def _limit_seq(expr, n, trials): from sympy.concrete.summations import Sum for i in range(trials): if not expr.has(Sum): result = _limit_inf(expr, n) if result is not None: return result num, den = expr.as_numer_denom() if not den.has(n) or not num.has(n): result = _limit_inf(expr.doit(), n) if result is not None: return result return None num, den = (difference_delta(t.expand(), n) for t in [num, den]) expr = (num / den).gammasimp() if not expr.has(Sum): result = _limit_inf(expr, n) if result is not None: return result num, den = expr.as_numer_denom() num = dominant(num, n) if num is None: return None den = dominant(den, n) if den is None: return None expr = (num / den).gammasimp() def limit_seq(expr, n=None, trials=5): """Finds the limit of a sequence as index ``n`` tends to infinity. Parameters ========== expr : Expr SymPy expression for the ``n-th`` term of the sequence n : Symbol, optional The index of the sequence, an integer that tends to positive infinity. If None, inferred from the expression unless it has multiple symbols. trials: int, optional The algorithm is highly recursive. ``trials`` is a safeguard from infinite recursion in case the limit is not easily computed by the algorithm. Try increasing ``trials`` if the algorithm returns ``None``. Admissible Terms ================ The algorithm is designed for sequences built from rational functions, indefinite sums, and indefinite products over an indeterminate n. Terms of alternating sign are also allowed, but more complex oscillatory behavior is not supported. Examples ======== >>> from sympy import limit_seq, Sum, binomial >>> from sympy.abc import n, k, m >>> limit_seq((5*n**3 + 3*n**2 + 4) / (3*n**3 + 4*n - 5), n) 5/3 >>> limit_seq(binomial(2*n, n) / Sum(binomial(2*k, k), (k, 1, n)), n) 3/4 >>> limit_seq(Sum(k**2 * Sum(2**m/m, (m, 1, k)), (k, 1, n)) / (2**n*n), n) 4 See Also ======== sympy.series.limitseq.dominant References ========== .. [1] Computing Limits of Sequences - Manuel Kauers """ from sympy.concrete.summations import Sum if n is None: free = expr.free_symbols if len(free) == 1: n = free.pop() elif not free: return expr else: raise ValueError("Expression has more than one variable. " "Please specify a variable.") elif n not in expr.free_symbols: return expr expr = expr.rewrite(fibonacci, S.GoldenRatio) expr = expr.rewrite(factorial, subfactorial, gamma) n_ = Dummy("n", integer=True, positive=True) n1 = Dummy("n", odd=True, positive=True) n2 = Dummy("n", even=True, positive=True) # If there is a negative term raised to a power involving n, or a # trigonometric function, then consider even and odd n separately. powers = (p.as_base_exp() for p in expr.atoms(Pow)) if (any(b.is_negative and e.has(n) for b, e in powers) or expr.has(cos, sin)): L1 = _limit_seq(expr.xreplace({n: n1}), n1, trials) if L1 is not None: L2 = _limit_seq(expr.xreplace({n: n2}), n2, trials) if L1 != L2: if L1.is_comparable and L2.is_comparable: return AccumulationBounds(Min(L1, L2), Max(L1, L2)) else: return None else: L1 = _limit_seq(expr.xreplace({n: n_}), n_, trials) if L1 is not None: return L1 else: if expr.is_Add: limits = [limit_seq(term, n, trials) for term in expr.args] if any(result is None for result in limits): return None else: return Add(*limits) # Maybe the absolute value is easier to deal with (though not if # it has a Sum). If it tends to 0, the limit is 0. elif not expr.has(Sum): lim = _limit_seq(Abs(expr.xreplace({n: n_})), n_, trials) if lim is not None and lim.is_zero: return S.Zero
4dd03d5a9e66f258cb655611ebf10486d1c7adf9a2cfbae054a8efbd84f3d854
""" Expand Hypergeometric (and Meijer G) functions into named special functions. The algorithm for doing this uses a collection of lookup tables of hypergeometric functions, and various of their properties, to expand many hypergeometric functions in terms of special functions. It is based on the following paper: Kelly B. Roach. Meijer G Function Representations. In: Proceedings of the 1997 International Symposium on Symbolic and Algebraic Computation, pages 205-211, New York, 1997. ACM. It is described in great(er) detail in the Sphinx documentation. """ # SUMMARY OF EXTENSIONS FOR MEIJER G FUNCTIONS # # o z**rho G(ap, bq; z) = G(ap + rho, bq + rho; z) # # o denote z*d/dz by D # # o It is helpful to keep in mind that ap and bq play essentially symmetric # roles: G(1/z) has slightly altered parameters, with ap and bq interchanged. # # o There are four shift operators: # A_J = b_J - D, J = 1, ..., n # B_J = 1 - a_j + D, J = 1, ..., m # C_J = -b_J + D, J = m+1, ..., q # D_J = a_J - 1 - D, J = n+1, ..., p # # A_J, C_J increment b_J # B_J, D_J decrement a_J # # o The corresponding four inverse-shift operators are defined if there # is no cancellation. Thus e.g. an index a_J (upper or lower) can be # incremented if a_J != b_i for i = 1, ..., q. # # o Order reduction: if b_j - a_i is a non-negative integer, where # j <= m and i > n, the corresponding quotient of gamma functions reduces # to a polynomial. Hence the G function can be expressed using a G-function # of lower order. # Similarly if j > m and i <= n. # # Secondly, there are paired index theorems [Adamchik, The evaluation of # integrals of Bessel functions via G-function identities]. Suppose there # are three parameters a, b, c, where a is an a_i, i <= n, b is a b_j, # j <= m and c is a denominator parameter (i.e. a_i, i > n or b_j, j > m). # Suppose further all three differ by integers. # Then the order can be reduced. # TODO work this out in detail. # # o An index quadruple is called suitable if its order cannot be reduced. # If there exists a sequence of shift operators transforming one index # quadruple into another, we say one is reachable from the other. # # o Deciding if one index quadruple is reachable from another is tricky. For # this reason, we use hand-built routines to match and instantiate formulas. # from collections import defaultdict from itertools import product from functools import reduce from sympy import SYMPY_DEBUG from sympy.core import (S, Dummy, symbols, sympify, Tuple, expand, I, pi, Mul, EulerGamma, oo, zoo, expand_func, Add, nan, Expr, Rational) from sympy.core.mod import Mod from sympy.core.sorting import default_sort_key from sympy.functions import (exp, sqrt, root, log, lowergamma, cos, besseli, gamma, uppergamma, expint, erf, sin, besselj, Ei, Ci, Si, Shi, sinh, cosh, Chi, fresnels, fresnelc, polar_lift, exp_polar, floor, ceiling, rf, factorial, lerchphi, Piecewise, re, elliptic_k, elliptic_e) from sympy.functions.elementary.complexes import polarify, unpolarify from sympy.functions.special.hyper import (hyper, HyperRep_atanh, HyperRep_power1, HyperRep_power2, HyperRep_log1, HyperRep_asin1, HyperRep_asin2, HyperRep_sqrts1, HyperRep_sqrts2, HyperRep_log2, HyperRep_cosasin, HyperRep_sinasin, meijerg) from sympy.polys import poly, Poly from sympy.simplify.powsimp import powdenest from sympy.utilities.iterables import sift # function to define "buckets" def _mod1(x): # TODO see if this can work as Mod(x, 1); this will require # different handling of the "buckets" since these need to # be sorted and that fails when there is a mixture of # integers and expressions with parameters. With the current # Mod behavior, Mod(k, 1) == Mod(1, 1) == 0 if k is an integer. # Although the sorting can be done with Basic.compare, this may # still require different handling of the sorted buckets. if x.is_Number: return Mod(x, 1) c, x = x.as_coeff_Add() return Mod(c, 1) + x # leave add formulae at the top for easy reference def add_formulae(formulae): """ Create our knowledge base. """ from sympy.matrices import Matrix a, b, c, z = symbols('a b c, z', cls=Dummy) def add(ap, bq, res): func = Hyper_Function(ap, bq) formulae.append(Formula(func, z, res, (a, b, c))) def addb(ap, bq, B, C, M): func = Hyper_Function(ap, bq) formulae.append(Formula(func, z, None, (a, b, c), B, C, M)) # Luke, Y. L. (1969), The Special Functions and Their Approximations, # Volume 1, section 6.2 # 0F0 add((), (), exp(z)) # 1F0 add((a, ), (), HyperRep_power1(-a, z)) # 2F1 addb((a, a - S.Half), (2*a, ), Matrix([HyperRep_power2(a, z), HyperRep_power2(a + S.Half, z)/2]), Matrix([[1, 0]]), Matrix([[(a - S.Half)*z/(1 - z), (S.Half - a)*z/(1 - z)], [a/(1 - z), a*(z - 2)/(1 - z)]])) addb((1, 1), (2, ), Matrix([HyperRep_log1(z), 1]), Matrix([[-1/z, 0]]), Matrix([[0, z/(z - 1)], [0, 0]])) addb((S.Half, 1), (S('3/2'), ), Matrix([HyperRep_atanh(z), 1]), Matrix([[1, 0]]), Matrix([[Rational(-1, 2), 1/(1 - z)/2], [0, 0]])) addb((S.Half, S.Half), (S('3/2'), ), Matrix([HyperRep_asin1(z), HyperRep_power1(Rational(-1, 2), z)]), Matrix([[1, 0]]), Matrix([[Rational(-1, 2), S.Half], [0, z/(1 - z)/2]])) addb((a, S.Half + a), (S.Half, ), Matrix([HyperRep_sqrts1(-a, z), -HyperRep_sqrts2(-a - S.Half, z)]), Matrix([[1, 0]]), Matrix([[0, -a], [z*(-2*a - 1)/2/(1 - z), S.Half - z*(-2*a - 1)/(1 - z)]])) # A. P. Prudnikov, Yu. A. Brychkov and O. I. Marichev (1990). # Integrals and Series: More Special Functions, Vol. 3,. # Gordon and Breach Science Publisher addb([a, -a], [S.Half], Matrix([HyperRep_cosasin(a, z), HyperRep_sinasin(a, z)]), Matrix([[1, 0]]), Matrix([[0, -a], [a*z/(1 - z), 1/(1 - z)/2]])) addb([1, 1], [3*S.Half], Matrix([HyperRep_asin2(z), 1]), Matrix([[1, 0]]), Matrix([[(z - S.Half)/(1 - z), 1/(1 - z)/2], [0, 0]])) # Complete elliptic integrals K(z) and E(z), both a 2F1 function addb([S.Half, S.Half], [S.One], Matrix([elliptic_k(z), elliptic_e(z)]), Matrix([[2/pi, 0]]), Matrix([[Rational(-1, 2), -1/(2*z-2)], [Rational(-1, 2), S.Half]])) addb([Rational(-1, 2), S.Half], [S.One], Matrix([elliptic_k(z), elliptic_e(z)]), Matrix([[0, 2/pi]]), Matrix([[Rational(-1, 2), -1/(2*z-2)], [Rational(-1, 2), S.Half]])) # 3F2 addb([Rational(-1, 2), 1, 1], [S.Half, 2], Matrix([z*HyperRep_atanh(z), HyperRep_log1(z), 1]), Matrix([[Rational(-2, 3), -S.One/(3*z), Rational(2, 3)]]), Matrix([[S.Half, 0, z/(1 - z)/2], [0, 0, z/(z - 1)], [0, 0, 0]])) # actually the formula for 3/2 is much nicer ... addb([Rational(-1, 2), 1, 1], [2, 2], Matrix([HyperRep_power1(S.Half, z), HyperRep_log2(z), 1]), Matrix([[Rational(4, 9) - 16/(9*z), 4/(3*z), 16/(9*z)]]), Matrix([[z/2/(z - 1), 0, 0], [1/(2*(z - 1)), 0, S.Half], [0, 0, 0]])) # 1F1 addb([1], [b], Matrix([z**(1 - b) * exp(z) * lowergamma(b - 1, z), 1]), Matrix([[b - 1, 0]]), Matrix([[1 - b + z, 1], [0, 0]])) addb([a], [2*a], Matrix([z**(S.Half - a)*exp(z/2)*besseli(a - S.Half, z/2) * gamma(a + S.Half)/4**(S.Half - a), z**(S.Half - a)*exp(z/2)*besseli(a + S.Half, z/2) * gamma(a + S.Half)/4**(S.Half - a)]), Matrix([[1, 0]]), Matrix([[z/2, z/2], [z/2, (z/2 - 2*a)]])) mz = polar_lift(-1)*z addb([a], [a + 1], Matrix([mz**(-a)*a*lowergamma(a, mz), a*exp(z)]), Matrix([[1, 0]]), Matrix([[-a, 1], [0, z]])) # This one is redundant. add([Rational(-1, 2)], [S.Half], exp(z) - sqrt(pi*z)*(-I)*erf(I*sqrt(z))) # Added to get nice results for Laplace transform of Fresnel functions # http://functions.wolfram.com/07.22.03.6437.01 # Basic rule #add([1], [Rational(3, 4), Rational(5, 4)], # sqrt(pi) * (cos(2*sqrt(polar_lift(-1)*z))*fresnelc(2*root(polar_lift(-1)*z,4)/sqrt(pi)) + # sin(2*sqrt(polar_lift(-1)*z))*fresnels(2*root(polar_lift(-1)*z,4)/sqrt(pi))) # / (2*root(polar_lift(-1)*z,4))) # Manually tuned rule addb([1], [Rational(3, 4), Rational(5, 4)], Matrix([ sqrt(pi)*(I*sinh(2*sqrt(z))*fresnels(2*root(z, 4)*exp(I*pi/4)/sqrt(pi)) + cosh(2*sqrt(z))*fresnelc(2*root(z, 4)*exp(I*pi/4)/sqrt(pi))) * exp(-I*pi/4)/(2*root(z, 4)), sqrt(pi)*root(z, 4)*(sinh(2*sqrt(z))*fresnelc(2*root(z, 4)*exp(I*pi/4)/sqrt(pi)) + I*cosh(2*sqrt(z))*fresnels(2*root(z, 4)*exp(I*pi/4)/sqrt(pi))) *exp(-I*pi/4)/2, 1 ]), Matrix([[1, 0, 0]]), Matrix([[Rational(-1, 4), 1, Rational(1, 4)], [ z, Rational(1, 4), 0], [ 0, 0, 0]])) # 2F2 addb([S.Half, a], [Rational(3, 2), a + 1], Matrix([a/(2*a - 1)*(-I)*sqrt(pi/z)*erf(I*sqrt(z)), a/(2*a - 1)*(polar_lift(-1)*z)**(-a)* lowergamma(a, polar_lift(-1)*z), a/(2*a - 1)*exp(z)]), Matrix([[1, -1, 0]]), Matrix([[Rational(-1, 2), 0, 1], [0, -a, 1], [0, 0, z]])) # We make a "basis" of four functions instead of three, and give EulerGamma # an extra slot (it could just be a coefficient to 1). The advantage is # that this way Polys will not see multivariate polynomials (it treats # EulerGamma as an indeterminate), which is *way* faster. addb([1, 1], [2, 2], Matrix([Ei(z) - log(z), exp(z), 1, EulerGamma]), Matrix([[1/z, 0, 0, -1/z]]), Matrix([[0, 1, -1, 0], [0, z, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])) # 0F1 add((), (S.Half, ), cosh(2*sqrt(z))) addb([], [b], Matrix([gamma(b)*z**((1 - b)/2)*besseli(b - 1, 2*sqrt(z)), gamma(b)*z**(1 - b/2)*besseli(b, 2*sqrt(z))]), Matrix([[1, 0]]), Matrix([[0, 1], [z, (1 - b)]])) # 0F3 x = 4*z**Rational(1, 4) def fp(a, z): return besseli(a, x) + besselj(a, x) def fm(a, z): return besseli(a, x) - besselj(a, x) # TODO branching addb([], [S.Half, a, a + S.Half], Matrix([fp(2*a - 1, z), fm(2*a, z)*z**Rational(1, 4), fm(2*a - 1, z)*sqrt(z), fp(2*a, z)*z**Rational(3, 4)]) * 2**(-2*a)*gamma(2*a)*z**((1 - 2*a)/4), Matrix([[1, 0, 0, 0]]), Matrix([[0, 1, 0, 0], [0, S.Half - a, 1, 0], [0, 0, S.Half, 1], [z, 0, 0, 1 - a]])) x = 2*(4*z)**Rational(1, 4)*exp_polar(I*pi/4) addb([], [a, a + S.Half, 2*a], (2*sqrt(polar_lift(-1)*z))**(1 - 2*a)*gamma(2*a)**2 * Matrix([besselj(2*a - 1, x)*besseli(2*a - 1, x), x*(besseli(2*a, x)*besselj(2*a - 1, x) - besseli(2*a - 1, x)*besselj(2*a, x)), x**2*besseli(2*a, x)*besselj(2*a, x), x**3*(besseli(2*a, x)*besselj(2*a - 1, x) + besseli(2*a - 1, x)*besselj(2*a, x))]), Matrix([[1, 0, 0, 0]]), Matrix([[0, Rational(1, 4), 0, 0], [0, (1 - 2*a)/2, Rational(-1, 2), 0], [0, 0, 1 - 2*a, Rational(1, 4)], [-32*z, 0, 0, 1 - a]])) # 1F2 addb([a], [a - S.Half, 2*a], Matrix([z**(S.Half - a)*besseli(a - S.Half, sqrt(z))**2, z**(1 - a)*besseli(a - S.Half, sqrt(z)) *besseli(a - Rational(3, 2), sqrt(z)), z**(Rational(3, 2) - a)*besseli(a - Rational(3, 2), sqrt(z))**2]), Matrix([[-gamma(a + S.Half)**2/4**(S.Half - a), 2*gamma(a - S.Half)*gamma(a + S.Half)/4**(1 - a), 0]]), Matrix([[1 - 2*a, 1, 0], [z/2, S.Half - a, S.Half], [0, z, 0]])) addb([S.Half], [b, 2 - b], pi*(1 - b)/sin(pi*b)* Matrix([besseli(1 - b, sqrt(z))*besseli(b - 1, sqrt(z)), sqrt(z)*(besseli(-b, sqrt(z))*besseli(b - 1, sqrt(z)) + besseli(1 - b, sqrt(z))*besseli(b, sqrt(z))), besseli(-b, sqrt(z))*besseli(b, sqrt(z))]), Matrix([[1, 0, 0]]), Matrix([[b - 1, S.Half, 0], [z, 0, z], [0, S.Half, -b]])) addb([S.Half], [Rational(3, 2), Rational(3, 2)], Matrix([Shi(2*sqrt(z))/2/sqrt(z), sinh(2*sqrt(z))/2/sqrt(z), cosh(2*sqrt(z))]), Matrix([[1, 0, 0]]), Matrix([[Rational(-1, 2), S.Half, 0], [0, Rational(-1, 2), S.Half], [0, 2*z, 0]])) # FresnelS # Basic rule #add([Rational(3, 4)], [Rational(3, 2),Rational(7, 4)], 6*fresnels( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) / ( pi * (exp(pi*I/4)*root(z,4)*2/sqrt(pi))**3 ) ) # Manually tuned rule addb([Rational(3, 4)], [Rational(3, 2), Rational(7, 4)], Matrix( [ fresnels( exp( pi*I/4)*root( z, 4)*2/sqrt( pi) ) / ( pi * (exp(pi*I/4)*root(z, 4)*2/sqrt(pi))**3 ), sinh(2*sqrt(z))/sqrt(z), cosh(2*sqrt(z)) ]), Matrix([[6, 0, 0]]), Matrix([[Rational(-3, 4), Rational(1, 16), 0], [ 0, Rational(-1, 2), 1], [ 0, z, 0]])) # FresnelC # Basic rule #add([Rational(1, 4)], [S.Half,Rational(5, 4)], fresnelc( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) / ( exp(pi*I/4)*root(z,4)*2/sqrt(pi) ) ) # Manually tuned rule addb([Rational(1, 4)], [S.Half, Rational(5, 4)], Matrix( [ sqrt( pi)*exp( -I*pi/4)*fresnelc( 2*root(z, 4)*exp(I*pi/4)/sqrt(pi))/(2*root(z, 4)), cosh(2*sqrt(z)), sinh(2*sqrt(z))*sqrt(z) ]), Matrix([[1, 0, 0]]), Matrix([[Rational(-1, 4), Rational(1, 4), 0 ], [ 0, 0, 1 ], [ 0, z, S.Half]])) # 2F3 # XXX with this five-parameter formula is pretty slow with the current # Formula.find_instantiations (creates 2!*3!*3**(2+3) ~ 3000 # instantiations ... But it's not too bad. addb([a, a + S.Half], [2*a, b, 2*a - b + 1], gamma(b)*gamma(2*a - b + 1) * (sqrt(z)/2)**(1 - 2*a) * Matrix([besseli(b - 1, sqrt(z))*besseli(2*a - b, sqrt(z)), sqrt(z)*besseli(b, sqrt(z))*besseli(2*a - b, sqrt(z)), sqrt(z)*besseli(b - 1, sqrt(z))*besseli(2*a - b + 1, sqrt(z)), besseli(b, sqrt(z))*besseli(2*a - b + 1, sqrt(z))]), Matrix([[1, 0, 0, 0]]), Matrix([[0, S.Half, S.Half, 0], [z/2, 1 - b, 0, z/2], [z/2, 0, b - 2*a, z/2], [0, S.Half, S.Half, -2*a]])) # (C/f above comment about eulergamma in the basis). addb([1, 1], [2, 2, Rational(3, 2)], Matrix([Chi(2*sqrt(z)) - log(2*sqrt(z)), cosh(2*sqrt(z)), sqrt(z)*sinh(2*sqrt(z)), 1, EulerGamma]), Matrix([[1/z, 0, 0, 0, -1/z]]), Matrix([[0, S.Half, 0, Rational(-1, 2), 0], [0, 0, 1, 0, 0], [0, z, S.Half, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])) # 3F3 # This is rule: http://functions.wolfram.com/07.31.03.0134.01 # Initial reason to add it was a nice solution for # integrate(erf(a*z)/z**2, z) and same for erfc and erfi. # Basic rule # add([1, 1, a], [2, 2, a+1], (a/(z*(a-1)**2)) * # (1 - (-z)**(1-a) * (gamma(a) - uppergamma(a,-z)) # - (a-1) * (EulerGamma + uppergamma(0,-z) + log(-z)) # - exp(z))) # Manually tuned rule addb([1, 1, a], [2, 2, a+1], Matrix([a*(log(-z) + expint(1, -z) + EulerGamma)/(z*(a**2 - 2*a + 1)), a*(-z)**(-a)*(gamma(a) - uppergamma(a, -z))/(a - 1)**2, a*exp(z)/(a**2 - 2*a + 1), a/(z*(a**2 - 2*a + 1))]), Matrix([[1-a, 1, -1/z, 1]]), Matrix([[-1,0,-1/z,1], [0,-a,1,0], [0,0,z,0], [0,0,0,-1]])) def add_meijerg_formulae(formulae): from sympy.matrices import Matrix a, b, c, z = list(map(Dummy, 'abcz')) rho = Dummy('rho') def add(an, ap, bm, bq, B, C, M, matcher): formulae.append(MeijerFormula(an, ap, bm, bq, z, [a, b, c, rho], B, C, M, matcher)) def detect_uppergamma(func): x = func.an[0] y, z = func.bm swapped = False if not _mod1((x - y).simplify()): swapped = True (y, z) = (z, y) if _mod1((x - z).simplify()) or x - z > 0: return None l = [y, x] if swapped: l = [x, y] return {rho: y, a: x - y}, G_Function([x], [], l, []) add([a + rho], [], [rho, a + rho], [], Matrix([gamma(1 - a)*z**rho*exp(z)*uppergamma(a, z), gamma(1 - a)*z**(a + rho)]), Matrix([[1, 0]]), Matrix([[rho + z, -1], [0, a + rho]]), detect_uppergamma) def detect_3113(func): """http://functions.wolfram.com/07.34.03.0984.01""" x = func.an[0] u, v, w = func.bm if _mod1((u - v).simplify()) == 0: if _mod1((v - w).simplify()) == 0: return sig = (S.Half, S.Half, S.Zero) x1, x2, y = u, v, w else: if _mod1((x - u).simplify()) == 0: sig = (S.Half, S.Zero, S.Half) x1, y, x2 = u, v, w else: sig = (S.Zero, S.Half, S.Half) y, x1, x2 = u, v, w if (_mod1((x - x1).simplify()) != 0 or _mod1((x - x2).simplify()) != 0 or _mod1((x - y).simplify()) != S.Half or x - x1 > 0 or x - x2 > 0): return return {a: x}, G_Function([x], [], [x - S.Half + t for t in sig], []) s = sin(2*sqrt(z)) c_ = cos(2*sqrt(z)) S_ = Si(2*sqrt(z)) - pi/2 C = Ci(2*sqrt(z)) add([a], [], [a, a, a - S.Half], [], Matrix([sqrt(pi)*z**(a - S.Half)*(c_*S_ - s*C), sqrt(pi)*z**a*(s*S_ + c_*C), sqrt(pi)*z**a]), Matrix([[-2, 0, 0]]), Matrix([[a - S.Half, -1, 0], [z, a, S.Half], [0, 0, a]]), detect_3113) def make_simp(z): """ Create a function that simplifies rational functions in ``z``. """ def simp(expr): """ Efficiently simplify the rational function ``expr``. """ numer, denom = expr.as_numer_denom() numer = numer.expand() # denom = denom.expand() # is this needed? c, numer, denom = poly(numer, z).cancel(poly(denom, z)) return c * numer.as_expr() / denom.as_expr() return simp def debug(*args): if SYMPY_DEBUG: for a in args: print(a, end="") print() class Hyper_Function(Expr): """ A generalized hypergeometric function. """ def __new__(cls, ap, bq): obj = super().__new__(cls) obj.ap = Tuple(*list(map(expand, ap))) obj.bq = Tuple(*list(map(expand, bq))) return obj @property def args(self): return (self.ap, self.bq) @property def sizes(self): return (len(self.ap), len(self.bq)) @property def gamma(self): """ Number of upper parameters that are negative integers This is a transformation invariant. """ return sum(bool(x.is_integer and x.is_negative) for x in self.ap) def _hashable_content(self): return super()._hashable_content() + (self.ap, self.bq) def __call__(self, arg): return hyper(self.ap, self.bq, arg) def build_invariants(self): """ Compute the invariant vector. Explanation =========== The invariant vector is: (gamma, ((s1, n1), ..., (sk, nk)), ((t1, m1), ..., (tr, mr))) where gamma is the number of integer a < 0, s1 < ... < sk nl is the number of parameters a_i congruent to sl mod 1 t1 < ... < tr ml is the number of parameters b_i congruent to tl mod 1 If the index pair contains parameters, then this is not truly an invariant, since the parameters cannot be sorted uniquely mod1. Examples ======== >>> from sympy.simplify.hyperexpand import Hyper_Function >>> from sympy import S >>> ap = (S.Half, S.One/3, S(-1)/2, -2) >>> bq = (1, 2) Here gamma = 1, k = 3, s1 = 0, s2 = 1/3, s3 = 1/2 n1 = 1, n2 = 1, n2 = 2 r = 1, t1 = 0 m1 = 2: >>> Hyper_Function(ap, bq).build_invariants() (1, ((0, 1), (1/3, 1), (1/2, 2)), ((0, 2),)) """ abuckets, bbuckets = sift(self.ap, _mod1), sift(self.bq, _mod1) def tr(bucket): bucket = list(bucket.items()) if not any(isinstance(x[0], Mod) for x in bucket): bucket.sort(key=lambda x: default_sort_key(x[0])) bucket = tuple([(mod, len(values)) for mod, values in bucket if values]) return bucket return (self.gamma, tr(abuckets), tr(bbuckets)) def difficulty(self, func): """ Estimate how many steps it takes to reach ``func`` from self. Return -1 if impossible. """ if self.gamma != func.gamma: return -1 oabuckets, obbuckets, abuckets, bbuckets = [sift(params, _mod1) for params in (self.ap, self.bq, func.ap, func.bq)] diff = 0 for bucket, obucket in [(abuckets, oabuckets), (bbuckets, obbuckets)]: for mod in set(list(bucket.keys()) + list(obucket.keys())): if (mod not in bucket) or (mod not in obucket) \ or len(bucket[mod]) != len(obucket[mod]): return -1 l1 = list(bucket[mod]) l2 = list(obucket[mod]) l1.sort() l2.sort() for i, j in zip(l1, l2): diff += abs(i - j) return diff def _is_suitable_origin(self): """ Decide if ``self`` is a suitable origin. Explanation =========== A function is a suitable origin iff: * none of the ai equals bj + n, with n a non-negative integer * none of the ai is zero * none of the bj is a non-positive integer Note that this gives meaningful results only when none of the indices are symbolic. """ for a in self.ap: for b in self.bq: if (a - b).is_integer and (a - b).is_negative is False: return False for a in self.ap: if a == 0: return False for b in self.bq: if b.is_integer and b.is_nonpositive: return False return True class G_Function(Expr): """ A Meijer G-function. """ def __new__(cls, an, ap, bm, bq): obj = super().__new__(cls) obj.an = Tuple(*list(map(expand, an))) obj.ap = Tuple(*list(map(expand, ap))) obj.bm = Tuple(*list(map(expand, bm))) obj.bq = Tuple(*list(map(expand, bq))) return obj @property def args(self): return (self.an, self.ap, self.bm, self.bq) def _hashable_content(self): return super()._hashable_content() + self.args def __call__(self, z): return meijerg(self.an, self.ap, self.bm, self.bq, z) def compute_buckets(self): """ Compute buckets for the fours sets of parameters. Explanation =========== We guarantee that any two equal Mod objects returned are actually the same, and that the buckets are sorted by real part (an and bq descendending, bm and ap ascending). Examples ======== >>> from sympy.simplify.hyperexpand import G_Function >>> from sympy.abc import y >>> from sympy import S >>> a, b = [1, 3, 2, S(3)/2], [1 + y, y, 2, y + 3] >>> G_Function(a, b, [2], [y]).compute_buckets() ({0: [3, 2, 1], 1/2: [3/2]}, {0: [2], y: [y, y + 1, y + 3]}, {0: [2]}, {y: [y]}) """ dicts = pan, pap, pbm, pbq = [defaultdict(list) for i in range(4)] for dic, lis in zip(dicts, (self.an, self.ap, self.bm, self.bq)): for x in lis: dic[_mod1(x)].append(x) for dic, flip in zip(dicts, (True, False, False, True)): for m, items in dic.items(): x0 = items[0] items.sort(key=lambda x: x - x0, reverse=flip) dic[m] = items return tuple([dict(w) for w in dicts]) @property def signature(self): return (len(self.an), len(self.ap), len(self.bm), len(self.bq)) # Dummy variable. _x = Dummy('x') class Formula: """ This class represents hypergeometric formulae. Explanation =========== Its data members are: - z, the argument - closed_form, the closed form expression - symbols, the free symbols (parameters) in the formula - func, the function - B, C, M (see _compute_basis) Examples ======== >>> from sympy.abc import a, b, z >>> from sympy.simplify.hyperexpand import Formula, Hyper_Function >>> func = Hyper_Function((a/2, a/3 + b, (1+a)/2), (a, b, (a+b)/7)) >>> f = Formula(func, z, None, [a, b]) """ def _compute_basis(self, closed_form): """ Compute a set of functions B=(f1, ..., fn), a nxn matrix M and a 1xn matrix C such that: closed_form = C B z d/dz B = M B. """ from sympy.matrices import Matrix, eye, zeros afactors = [_x + a for a in self.func.ap] bfactors = [_x + b - 1 for b in self.func.bq] expr = _x*Mul(*bfactors) - self.z*Mul(*afactors) poly = Poly(expr, _x) n = poly.degree() - 1 b = [closed_form] for _ in range(n): b.append(self.z*b[-1].diff(self.z)) self.B = Matrix(b) self.C = Matrix([[1] + [0]*n]) m = eye(n) m = m.col_insert(0, zeros(n, 1)) l = poly.all_coeffs()[1:] l.reverse() self.M = m.row_insert(n, -Matrix([l])/poly.all_coeffs()[0]) def __init__(self, func, z, res, symbols, B=None, C=None, M=None): z = sympify(z) res = sympify(res) symbols = [x for x in sympify(symbols) if func.has(x)] self.z = z self.symbols = symbols self.B = B self.C = C self.M = M self.func = func # TODO with symbolic parameters, it could be advantageous # (for prettier answers) to compute a basis only *after* # instantiation if res is not None: self._compute_basis(res) @property def closed_form(self): return reduce(lambda s,m: s+m[0]*m[1], zip(self.C, self.B), S.Zero) def find_instantiations(self, func): """ Find substitutions of the free symbols that match ``func``. Return the substitution dictionaries as a list. Note that the returned instantiations need not actually match, or be valid! """ from sympy.solvers import solve ap = func.ap bq = func.bq if len(ap) != len(self.func.ap) or len(bq) != len(self.func.bq): raise TypeError('Cannot instantiate other number of parameters') symbol_values = [] for a in self.symbols: if a in self.func.ap.args: symbol_values.append(ap) elif a in self.func.bq.args: symbol_values.append(bq) else: raise ValueError("At least one of the parameters of the " "formula must be equal to %s" % (a,)) base_repl = [dict(list(zip(self.symbols, values))) for values in product(*symbol_values)] abuckets, bbuckets = [sift(params, _mod1) for params in [ap, bq]] a_inv, b_inv = [{a: len(vals) for a, vals in bucket.items()} for bucket in [abuckets, bbuckets]] critical_values = [[0] for _ in self.symbols] result = [] _n = Dummy() for repl in base_repl: symb_a, symb_b = [sift(params, lambda x: _mod1(x.xreplace(repl))) for params in [self.func.ap, self.func.bq]] for bucket, obucket in [(abuckets, symb_a), (bbuckets, symb_b)]: for mod in set(list(bucket.keys()) + list(obucket.keys())): if (mod not in bucket) or (mod not in obucket) \ or len(bucket[mod]) != len(obucket[mod]): break for a, vals in zip(self.symbols, critical_values): if repl[a].free_symbols: continue exprs = [expr for expr in obucket[mod] if expr.has(a)] repl0 = repl.copy() repl0[a] += _n for expr in exprs: for target in bucket[mod]: n0, = solve(expr.xreplace(repl0) - target, _n) if n0.free_symbols: raise ValueError("Value should not be true") vals.append(n0) else: values = [] for a, vals in zip(self.symbols, critical_values): a0 = repl[a] min_ = floor(min(vals)) max_ = ceiling(max(vals)) values.append([a0 + n for n in range(min_, max_ + 1)]) result.extend(dict(list(zip(self.symbols, l))) for l in product(*values)) return result class FormulaCollection: """ A collection of formulae to use as origins. """ def __init__(self): """ Doing this globally at module init time is a pain ... """ self.symbolic_formulae = {} self.concrete_formulae = {} self.formulae = [] add_formulae(self.formulae) # Now process the formulae into a helpful form. # These dicts are indexed by (p, q). for f in self.formulae: sizes = f.func.sizes if len(f.symbols) > 0: self.symbolic_formulae.setdefault(sizes, []).append(f) else: inv = f.func.build_invariants() self.concrete_formulae.setdefault(sizes, {})[inv] = f def lookup_origin(self, func): """ Given the suitable target ``func``, try to find an origin in our knowledge base. Examples ======== >>> from sympy.simplify.hyperexpand import (FormulaCollection, ... Hyper_Function) >>> f = FormulaCollection() >>> f.lookup_origin(Hyper_Function((), ())).closed_form exp(_z) >>> f.lookup_origin(Hyper_Function([1], ())).closed_form HyperRep_power1(-1, _z) >>> from sympy import S >>> i = Hyper_Function([S('1/4'), S('3/4 + 4')], [S.Half]) >>> f.lookup_origin(i).closed_form HyperRep_sqrts1(-1/4, _z) """ inv = func.build_invariants() sizes = func.sizes if sizes in self.concrete_formulae and \ inv in self.concrete_formulae[sizes]: return self.concrete_formulae[sizes][inv] # We don't have a concrete formula. Try to instantiate. if sizes not in self.symbolic_formulae: return None # Too bad... possible = [] for f in self.symbolic_formulae[sizes]: repls = f.find_instantiations(func) for repl in repls: func2 = f.func.xreplace(repl) if not func2._is_suitable_origin(): continue diff = func2.difficulty(func) if diff == -1: continue possible.append((diff, repl, f, func2)) # find the nearest origin possible.sort(key=lambda x: x[0]) for _, repl, f, func2 in possible: f2 = Formula(func2, f.z, None, [], f.B.subs(repl), f.C.subs(repl), f.M.subs(repl)) if not any(e.has(S.NaN, oo, -oo, zoo) for e in [f2.B, f2.M, f2.C]): return f2 return None class MeijerFormula: """ This class represents a Meijer G-function formula. Its data members are: - z, the argument - symbols, the free symbols (parameters) in the formula - func, the function - B, C, M (c/f ordinary Formula) """ def __init__(self, an, ap, bm, bq, z, symbols, B, C, M, matcher): an, ap, bm, bq = [Tuple(*list(map(expand, w))) for w in [an, ap, bm, bq]] self.func = G_Function(an, ap, bm, bq) self.z = z self.symbols = symbols self._matcher = matcher self.B = B self.C = C self.M = M @property def closed_form(self): return reduce(lambda s,m: s+m[0]*m[1], zip(self.C, self.B), S.Zero) def try_instantiate(self, func): """ Try to instantiate the current formula to (almost) match func. This uses the _matcher passed on init. """ if func.signature != self.func.signature: return None res = self._matcher(func) if res is not None: subs, newfunc = res return MeijerFormula(newfunc.an, newfunc.ap, newfunc.bm, newfunc.bq, self.z, [], self.B.subs(subs), self.C.subs(subs), self.M.subs(subs), None) class MeijerFormulaCollection: """ This class holds a collection of meijer g formulae. """ def __init__(self): formulae = [] add_meijerg_formulae(formulae) self.formulae = defaultdict(list) for formula in formulae: self.formulae[formula.func.signature].append(formula) self.formulae = dict(self.formulae) def lookup_origin(self, func): """ Try to find a formula that matches func. """ if func.signature not in self.formulae: return None for formula in self.formulae[func.signature]: res = formula.try_instantiate(func) if res is not None: return res class Operator: """ Base class for operators to be applied to our functions. Explanation =========== These operators are differential operators. They are by convention expressed in the variable D = z*d/dz (although this base class does not actually care). Note that when the operator is applied to an object, we typically do *not* blindly differentiate but instead use a different representation of the z*d/dz operator (see make_derivative_operator). To subclass from this, define a __init__ method that initializes a self._poly variable. This variable stores a polynomial. By convention the generator is z*d/dz, and acts to the right of all coefficients. Thus this poly x**2 + 2*z*x + 1 represents the differential operator (z*d/dz)**2 + 2*z**2*d/dz. This class is used only in the implementation of the hypergeometric function expansion algorithm. """ def apply(self, obj, op): """ Apply ``self`` to the object ``obj``, where the generator is ``op``. Examples ======== >>> from sympy.simplify.hyperexpand import Operator >>> from sympy.polys.polytools import Poly >>> from sympy.abc import x, y, z >>> op = Operator() >>> op._poly = Poly(x**2 + z*x + y, x) >>> op.apply(z**7, lambda f: f.diff(z)) y*z**7 + 7*z**7 + 42*z**5 """ coeffs = self._poly.all_coeffs() coeffs.reverse() diffs = [obj] for c in coeffs[1:]: diffs.append(op(diffs[-1])) r = coeffs[0]*diffs[0] for c, d in zip(coeffs[1:], diffs[1:]): r += c*d return r class MultOperator(Operator): """ Simply multiply by a "constant" """ def __init__(self, p): self._poly = Poly(p, _x) class ShiftA(Operator): """ Increment an upper index. """ def __init__(self, ai): ai = sympify(ai) if ai == 0: raise ValueError('Cannot increment zero upper index.') self._poly = Poly(_x/ai + 1, _x) def __str__(self): return '<Increment upper %s.>' % (1/self._poly.all_coeffs()[0]) class ShiftB(Operator): """ Decrement a lower index. """ def __init__(self, bi): bi = sympify(bi) if bi == 1: raise ValueError('Cannot decrement unit lower index.') self._poly = Poly(_x/(bi - 1) + 1, _x) def __str__(self): return '<Decrement lower %s.>' % (1/self._poly.all_coeffs()[0] + 1) class UnShiftA(Operator): """ Decrement an upper index. """ def __init__(self, ap, bq, i, z): """ Note: i counts from zero! """ ap, bq, i = list(map(sympify, [ap, bq, i])) self._ap = ap self._bq = bq self._i = i ap = list(ap) bq = list(bq) ai = ap.pop(i) - 1 if ai == 0: raise ValueError('Cannot decrement unit upper index.') m = Poly(z*ai, _x) for a in ap: m *= Poly(_x + a, _x) A = Dummy('A') n = D = Poly(ai*A - ai, A) for b in bq: n *= D + (b - 1).as_poly(A) b0 = -n.nth(0) if b0 == 0: raise ValueError('Cannot decrement upper index: ' 'cancels with lower') n = Poly(Poly(n.all_coeffs()[:-1], A).as_expr().subs(A, _x/ai + 1), _x) self._poly = Poly((n - m)/b0, _x) def __str__(self): return '<Decrement upper index #%s of %s, %s.>' % (self._i, self._ap, self._bq) class UnShiftB(Operator): """ Increment a lower index. """ def __init__(self, ap, bq, i, z): """ Note: i counts from zero! """ ap, bq, i = list(map(sympify, [ap, bq, i])) self._ap = ap self._bq = bq self._i = i ap = list(ap) bq = list(bq) bi = bq.pop(i) + 1 if bi == 0: raise ValueError('Cannot increment -1 lower index.') m = Poly(_x*(bi - 1), _x) for b in bq: m *= Poly(_x + b - 1, _x) B = Dummy('B') D = Poly((bi - 1)*B - bi + 1, B) n = Poly(z, B) for a in ap: n *= (D + a.as_poly(B)) b0 = n.nth(0) if b0 == 0: raise ValueError('Cannot increment index: cancels with upper') n = Poly(Poly(n.all_coeffs()[:-1], B).as_expr().subs( B, _x/(bi - 1) + 1), _x) self._poly = Poly((m - n)/b0, _x) def __str__(self): return '<Increment lower index #%s of %s, %s.>' % (self._i, self._ap, self._bq) class MeijerShiftA(Operator): """ Increment an upper b index. """ def __init__(self, bi): bi = sympify(bi) self._poly = Poly(bi - _x, _x) def __str__(self): return '<Increment upper b=%s.>' % (self._poly.all_coeffs()[1]) class MeijerShiftB(Operator): """ Decrement an upper a index. """ def __init__(self, bi): bi = sympify(bi) self._poly = Poly(1 - bi + _x, _x) def __str__(self): return '<Decrement upper a=%s.>' % (1 - self._poly.all_coeffs()[1]) class MeijerShiftC(Operator): """ Increment a lower b index. """ def __init__(self, bi): bi = sympify(bi) self._poly = Poly(-bi + _x, _x) def __str__(self): return '<Increment lower b=%s.>' % (-self._poly.all_coeffs()[1]) class MeijerShiftD(Operator): """ Decrement a lower a index. """ def __init__(self, bi): bi = sympify(bi) self._poly = Poly(bi - 1 - _x, _x) def __str__(self): return '<Decrement lower a=%s.>' % (self._poly.all_coeffs()[1] + 1) class MeijerUnShiftA(Operator): """ Decrement an upper b index. """ def __init__(self, an, ap, bm, bq, i, z): """ Note: i counts from zero! """ an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i])) self._an = an self._ap = ap self._bm = bm self._bq = bq self._i = i an = list(an) ap = list(ap) bm = list(bm) bq = list(bq) bi = bm.pop(i) - 1 m = Poly(1, _x) for b in bm: m *= Poly(b - _x, _x) for b in bq: m *= Poly(_x - b, _x) A = Dummy('A') D = Poly(bi - A, A) n = Poly(z, A) for a in an: n *= (D + 1 - a) for a in ap: n *= (-D + a - 1) b0 = n.nth(0) if b0 == 0: raise ValueError('Cannot decrement upper b index (cancels)') n = Poly(Poly(n.all_coeffs()[:-1], A).as_expr().subs(A, bi - _x), _x) self._poly = Poly((m - n)/b0, _x) def __str__(self): return '<Decrement upper b index #%s of %s, %s, %s, %s.>' % (self._i, self._an, self._ap, self._bm, self._bq) class MeijerUnShiftB(Operator): """ Increment an upper a index. """ def __init__(self, an, ap, bm, bq, i, z): """ Note: i counts from zero! """ an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i])) self._an = an self._ap = ap self._bm = bm self._bq = bq self._i = i an = list(an) ap = list(ap) bm = list(bm) bq = list(bq) ai = an.pop(i) + 1 m = Poly(z, _x) for a in an: m *= Poly(1 - a + _x, _x) for a in ap: m *= Poly(a - 1 - _x, _x) B = Dummy('B') D = Poly(B + ai - 1, B) n = Poly(1, B) for b in bm: n *= (-D + b) for b in bq: n *= (D - b) b0 = n.nth(0) if b0 == 0: raise ValueError('Cannot increment upper a index (cancels)') n = Poly(Poly(n.all_coeffs()[:-1], B).as_expr().subs( B, 1 - ai + _x), _x) self._poly = Poly((m - n)/b0, _x) def __str__(self): return '<Increment upper a index #%s of %s, %s, %s, %s.>' % (self._i, self._an, self._ap, self._bm, self._bq) class MeijerUnShiftC(Operator): """ Decrement a lower b index. """ # XXX this is "essentially" the same as MeijerUnShiftA. This "essentially" # can be made rigorous using the functional equation G(1/z) = G'(z), # where G' denotes a G function of slightly altered parameters. # However, sorting out the details seems harder than just coding it # again. def __init__(self, an, ap, bm, bq, i, z): """ Note: i counts from zero! """ an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i])) self._an = an self._ap = ap self._bm = bm self._bq = bq self._i = i an = list(an) ap = list(ap) bm = list(bm) bq = list(bq) bi = bq.pop(i) - 1 m = Poly(1, _x) for b in bm: m *= Poly(b - _x, _x) for b in bq: m *= Poly(_x - b, _x) C = Dummy('C') D = Poly(bi + C, C) n = Poly(z, C) for a in an: n *= (D + 1 - a) for a in ap: n *= (-D + a - 1) b0 = n.nth(0) if b0 == 0: raise ValueError('Cannot decrement lower b index (cancels)') n = Poly(Poly(n.all_coeffs()[:-1], C).as_expr().subs(C, _x - bi), _x) self._poly = Poly((m - n)/b0, _x) def __str__(self): return '<Decrement lower b index #%s of %s, %s, %s, %s.>' % (self._i, self._an, self._ap, self._bm, self._bq) class MeijerUnShiftD(Operator): """ Increment a lower a index. """ # XXX This is essentially the same as MeijerUnShiftA. # See comment at MeijerUnShiftC. def __init__(self, an, ap, bm, bq, i, z): """ Note: i counts from zero! """ an, ap, bm, bq, i = list(map(sympify, [an, ap, bm, bq, i])) self._an = an self._ap = ap self._bm = bm self._bq = bq self._i = i an = list(an) ap = list(ap) bm = list(bm) bq = list(bq) ai = ap.pop(i) + 1 m = Poly(z, _x) for a in an: m *= Poly(1 - a + _x, _x) for a in ap: m *= Poly(a - 1 - _x, _x) B = Dummy('B') # - this is the shift operator `D_I` D = Poly(ai - 1 - B, B) n = Poly(1, B) for b in bm: n *= (-D + b) for b in bq: n *= (D - b) b0 = n.nth(0) if b0 == 0: raise ValueError('Cannot increment lower a index (cancels)') n = Poly(Poly(n.all_coeffs()[:-1], B).as_expr().subs( B, ai - 1 - _x), _x) self._poly = Poly((m - n)/b0, _x) def __str__(self): return '<Increment lower a index #%s of %s, %s, %s, %s.>' % (self._i, self._an, self._ap, self._bm, self._bq) class ReduceOrder(Operator): """ Reduce Order by cancelling an upper and a lower index. """ def __new__(cls, ai, bj): """ For convenience if reduction is not possible, return None. """ ai = sympify(ai) bj = sympify(bj) n = ai - bj if not n.is_Integer or n < 0: return None if bj.is_integer and bj.is_nonpositive: return None expr = Operator.__new__(cls) p = S.One for k in range(n): p *= (_x + bj + k)/(bj + k) expr._poly = Poly(p, _x) expr._a = ai expr._b = bj return expr @classmethod def _meijer(cls, b, a, sign): """ Cancel b + sign*s and a + sign*s This is for meijer G functions. """ b = sympify(b) a = sympify(a) n = b - a if n.is_negative or not n.is_Integer: return None expr = Operator.__new__(cls) p = S.One for k in range(n): p *= (sign*_x + a + k) expr._poly = Poly(p, _x) if sign == -1: expr._a = b expr._b = a else: expr._b = Add(1, a - 1, evaluate=False) expr._a = Add(1, b - 1, evaluate=False) return expr @classmethod def meijer_minus(cls, b, a): return cls._meijer(b, a, -1) @classmethod def meijer_plus(cls, a, b): return cls._meijer(1 - a, 1 - b, 1) def __str__(self): return '<Reduce order by cancelling upper %s with lower %s.>' % \ (self._a, self._b) def _reduce_order(ap, bq, gen, key): """ Order reduction algorithm used in Hypergeometric and Meijer G """ ap = list(ap) bq = list(bq) ap.sort(key=key) bq.sort(key=key) nap = [] # we will edit bq in place operators = [] for a in ap: op = None for i in range(len(bq)): op = gen(a, bq[i]) if op is not None: bq.pop(i) break if op is None: nap.append(a) else: operators.append(op) return nap, bq, operators def reduce_order(func): """ Given the hypergeometric function ``func``, find a sequence of operators to reduces order as much as possible. Explanation =========== Return (newfunc, [operators]), where applying the operators to the hypergeometric function newfunc yields func. Examples ======== >>> from sympy.simplify.hyperexpand import reduce_order, Hyper_Function >>> reduce_order(Hyper_Function((1, 2), (3, 4))) (Hyper_Function((1, 2), (3, 4)), []) >>> reduce_order(Hyper_Function((1,), (1,))) (Hyper_Function((), ()), [<Reduce order by cancelling upper 1 with lower 1.>]) >>> reduce_order(Hyper_Function((2, 4), (3, 3))) (Hyper_Function((2,), (3,)), [<Reduce order by cancelling upper 4 with lower 3.>]) """ nap, nbq, operators = _reduce_order(func.ap, func.bq, ReduceOrder, default_sort_key) return Hyper_Function(Tuple(*nap), Tuple(*nbq)), operators def reduce_order_meijer(func): """ Given the Meijer G function parameters, ``func``, find a sequence of operators that reduces order as much as possible. Return newfunc, [operators]. Examples ======== >>> from sympy.simplify.hyperexpand import (reduce_order_meijer, ... G_Function) >>> reduce_order_meijer(G_Function([3, 4], [5, 6], [3, 4], [1, 2]))[0] G_Function((4, 3), (5, 6), (3, 4), (2, 1)) >>> reduce_order_meijer(G_Function([3, 4], [5, 6], [3, 4], [1, 8]))[0] G_Function((3,), (5, 6), (3, 4), (1,)) >>> reduce_order_meijer(G_Function([3, 4], [5, 6], [7, 5], [1, 5]))[0] G_Function((3,), (), (), (1,)) >>> reduce_order_meijer(G_Function([3, 4], [5, 6], [7, 5], [5, 3]))[0] G_Function((), (), (), ()) """ nan, nbq, ops1 = _reduce_order(func.an, func.bq, ReduceOrder.meijer_plus, lambda x: default_sort_key(-x)) nbm, nap, ops2 = _reduce_order(func.bm, func.ap, ReduceOrder.meijer_minus, default_sort_key) return G_Function(nan, nap, nbm, nbq), ops1 + ops2 def make_derivative_operator(M, z): """ Create a derivative operator, to be passed to Operator.apply. """ def doit(C): r = z*C.diff(z) + C*M r = r.applyfunc(make_simp(z)) return r return doit def apply_operators(obj, ops, op): """ Apply the list of operators ``ops`` to object ``obj``, substituting ``op`` for the generator. """ res = obj for o in reversed(ops): res = o.apply(res, op) return res def devise_plan(target, origin, z): """ Devise a plan (consisting of shift and un-shift operators) to be applied to the hypergeometric function ``target`` to yield ``origin``. Returns a list of operators. Examples ======== >>> from sympy.simplify.hyperexpand import devise_plan, Hyper_Function >>> from sympy.abc import z Nothing to do: >>> devise_plan(Hyper_Function((1, 2), ()), Hyper_Function((1, 2), ()), z) [] >>> devise_plan(Hyper_Function((), (1, 2)), Hyper_Function((), (1, 2)), z) [] Very simple plans: >>> devise_plan(Hyper_Function((2,), ()), Hyper_Function((1,), ()), z) [<Increment upper 1.>] >>> devise_plan(Hyper_Function((), (2,)), Hyper_Function((), (1,)), z) [<Increment lower index #0 of [], [1].>] Several buckets: >>> from sympy import S >>> devise_plan(Hyper_Function((1, S.Half), ()), ... Hyper_Function((2, S('3/2')), ()), z) #doctest: +NORMALIZE_WHITESPACE [<Decrement upper index #0 of [3/2, 1], [].>, <Decrement upper index #0 of [2, 3/2], [].>] A slightly more complicated plan: >>> devise_plan(Hyper_Function((1, 3), ()), Hyper_Function((2, 2), ()), z) [<Increment upper 2.>, <Decrement upper index #0 of [2, 2], [].>] Another more complicated plan: (note that the ap have to be shifted first!) >>> devise_plan(Hyper_Function((1, -1), (2,)), Hyper_Function((3, -2), (4,)), z) [<Decrement lower 3.>, <Decrement lower 4.>, <Decrement upper index #1 of [-1, 2], [4].>, <Decrement upper index #1 of [-1, 3], [4].>, <Increment upper -2.>] """ abuckets, bbuckets, nabuckets, nbbuckets = [sift(params, _mod1) for params in (target.ap, target.bq, origin.ap, origin.bq)] if len(list(abuckets.keys())) != len(list(nabuckets.keys())) or \ len(list(bbuckets.keys())) != len(list(nbbuckets.keys())): raise ValueError('%s not reachable from %s' % (target, origin)) ops = [] def do_shifts(fro, to, inc, dec): ops = [] for i in range(len(fro)): if to[i] - fro[i] > 0: sh = inc ch = 1 else: sh = dec ch = -1 while to[i] != fro[i]: ops += [sh(fro, i)] fro[i] += ch return ops def do_shifts_a(nal, nbk, al, aother, bother): """ Shift us from (nal, nbk) to (al, nbk). """ return do_shifts(nal, al, lambda p, i: ShiftA(p[i]), lambda p, i: UnShiftA(p + aother, nbk + bother, i, z)) def do_shifts_b(nal, nbk, bk, aother, bother): """ Shift us from (nal, nbk) to (nal, bk). """ return do_shifts(nbk, bk, lambda p, i: UnShiftB(nal + aother, p + bother, i, z), lambda p, i: ShiftB(p[i])) for r in sorted(list(abuckets.keys()) + list(bbuckets.keys()), key=default_sort_key): al = () nal = () bk = () nbk = () if r in abuckets: al = abuckets[r] nal = nabuckets[r] if r in bbuckets: bk = bbuckets[r] nbk = nbbuckets[r] if len(al) != len(nal) or len(bk) != len(nbk): raise ValueError('%s not reachable from %s' % (target, origin)) al, nal, bk, nbk = [sorted(list(w), key=default_sort_key) for w in [al, nal, bk, nbk]] def others(dic, key): l = [] for k, value in dic.items(): if k != key: l += list(dic[k]) return l aother = others(nabuckets, r) bother = others(nbbuckets, r) if len(al) == 0: # there can be no complications, just shift the bs as we please ops += do_shifts_b([], nbk, bk, aother, bother) elif len(bk) == 0: # there can be no complications, just shift the as as we please ops += do_shifts_a(nal, [], al, aother, bother) else: namax = nal[-1] amax = al[-1] if nbk[0] - namax <= 0 or bk[0] - amax <= 0: raise ValueError('Non-suitable parameters.') if namax - amax > 0: # we are going to shift down - first do the as, then the bs ops += do_shifts_a(nal, nbk, al, aother, bother) ops += do_shifts_b(al, nbk, bk, aother, bother) else: # we are going to shift up - first do the bs, then the as ops += do_shifts_b(nal, nbk, bk, aother, bother) ops += do_shifts_a(nal, bk, al, aother, bother) nabuckets[r] = al nbbuckets[r] = bk ops.reverse() return ops def try_shifted_sum(func, z): """ Try to recognise a hypergeometric sum that starts from k > 0. """ abuckets, bbuckets = sift(func.ap, _mod1), sift(func.bq, _mod1) if len(abuckets[S.Zero]) != 1: return None r = abuckets[S.Zero][0] if r <= 0: return None if S.Zero not in bbuckets: return None l = list(bbuckets[S.Zero]) l.sort() k = l[0] if k <= 0: return None nap = list(func.ap) nap.remove(r) nbq = list(func.bq) nbq.remove(k) k -= 1 nap = [x - k for x in nap] nbq = [x - k for x in nbq] ops = [] for n in range(r - 1): ops.append(ShiftA(n + 1)) ops.reverse() fac = factorial(k)/z**k for a in nap: fac /= rf(a, k) for b in nbq: fac *= rf(b, k) ops += [MultOperator(fac)] p = 0 for n in range(k): m = z**n/factorial(n) for a in nap: m *= rf(a, n) for b in nbq: m /= rf(b, n) p += m return Hyper_Function(nap, nbq), ops, -p def try_polynomial(func, z): """ Recognise polynomial cases. Returns None if not such a case. Requires order to be fully reduced. """ abuckets, bbuckets = sift(func.ap, _mod1), sift(func.bq, _mod1) a0 = abuckets[S.Zero] b0 = bbuckets[S.Zero] a0.sort() b0.sort() al0 = [x for x in a0 if x <= 0] bl0 = [x for x in b0 if x <= 0] if bl0 and all(a < bl0[-1] for a in al0): return oo if not al0: return None a = al0[-1] fac = 1 res = S.One for n in Tuple(*list(range(-a))): fac *= z fac /= n + 1 for a in func.ap: fac *= a + n for b in func.bq: fac /= b + n res += fac return res def try_lerchphi(func): """ Try to find an expression for Hyper_Function ``func`` in terms of Lerch Transcendents. Return None if no such expression can be found. """ # This is actually quite simple, and is described in Roach's paper, # section 18. # We don't need to implement the reduction to polylog here, this # is handled by expand_func. from sympy.matrices import Matrix, zeros from sympy.polys import apart # First we need to figure out if the summation coefficient is a rational # function of the summation index, and construct that rational function. abuckets, bbuckets = sift(func.ap, _mod1), sift(func.bq, _mod1) paired = {} for key, value in abuckets.items(): if key != 0 and key not in bbuckets: return None bvalue = bbuckets[key] paired[key] = (list(value), list(bvalue)) bbuckets.pop(key, None) if bbuckets != {}: return None if S.Zero not in abuckets: return None aints, bints = paired[S.Zero] # Account for the additional n! in denominator paired[S.Zero] = (aints, bints + [1]) t = Dummy('t') numer = S.One denom = S.One for key, (avalue, bvalue) in paired.items(): if len(avalue) != len(bvalue): return None # Note that since order has been reduced fully, all the b are # bigger than all the a they differ from by an integer. In particular # if there are any negative b left, this function is not well-defined. for a, b in zip(avalue, bvalue): if (a - b).is_positive: k = a - b numer *= rf(b + t, k) denom *= rf(b, k) else: k = b - a numer *= rf(a, k) denom *= rf(a + t, k) # Now do a partial fraction decomposition. # We assemble two structures: a list monomials of pairs (a, b) representing # a*t**b (b a non-negative integer), and a dict terms, where # terms[a] = [(b, c)] means that there is a term b/(t-a)**c. part = apart(numer/denom, t) args = Add.make_args(part) monomials = [] terms = {} for arg in args: numer, denom = arg.as_numer_denom() if not denom.has(t): p = Poly(numer, t) if not p.is_monomial: raise TypeError("p should be monomial") ((b, ), a) = p.LT() monomials += [(a/denom, b)] continue if numer.has(t): raise NotImplementedError('Need partial fraction decomposition' ' with linear denominators') indep, [dep] = denom.as_coeff_mul(t) n = 1 if dep.is_Pow: n = dep.exp dep = dep.base if dep == t: a == 0 elif dep.is_Add: a, tmp = dep.as_independent(t) b = 1 if tmp != t: b, _ = tmp.as_independent(t) if dep != b*t + a: raise NotImplementedError('unrecognised form %s' % dep) a /= b indep *= b**n else: raise NotImplementedError('unrecognised form of partial fraction') terms.setdefault(a, []).append((numer/indep, n)) # Now that we have this information, assemble our formula. All the # monomials yield rational functions and go into one basis element. # The terms[a] are related by differentiation. If the largest exponent is # n, we need lerchphi(z, k, a) for k = 1, 2, ..., n. # deriv maps a basis to its derivative, expressed as a C(z)-linear # combination of other basis elements. deriv = {} coeffs = {} z = Dummy('z') monomials.sort(key=lambda x: x[1]) mon = {0: 1/(1 - z)} if monomials: for k in range(monomials[-1][1]): mon[k + 1] = z*mon[k].diff(z) for a, n in monomials: coeffs.setdefault(S.One, []).append(a*mon[n]) for a, l in terms.items(): for c, k in l: coeffs.setdefault(lerchphi(z, k, a), []).append(c) l.sort(key=lambda x: x[1]) for k in range(2, l[-1][1] + 1): deriv[lerchphi(z, k, a)] = [(-a, lerchphi(z, k, a)), (1, lerchphi(z, k - 1, a))] deriv[lerchphi(z, 1, a)] = [(-a, lerchphi(z, 1, a)), (1/(1 - z), S.One)] trans = {} for n, b in enumerate([S.One] + list(deriv.keys())): trans[b] = n basis = [expand_func(b) for (b, _) in sorted(list(trans.items()), key=lambda x:x[1])] B = Matrix(basis) C = Matrix([[0]*len(B)]) for b, c in coeffs.items(): C[trans[b]] = Add(*c) M = zeros(len(B)) for b, l in deriv.items(): for c, b2 in l: M[trans[b], trans[b2]] = c return Formula(func, z, None, [], B, C, M) def build_hypergeometric_formula(func): """ Create a formula object representing the hypergeometric function ``func``. """ # We know that no `ap` are negative integers, otherwise "detect poly" # would have kicked in. However, `ap` could be empty. In this case we can # use a different basis. # I'm not aware of a basis that works in all cases. from sympy.matrices.dense import (Matrix, eye, zeros) z = Dummy('z') if func.ap: afactors = [_x + a for a in func.ap] bfactors = [_x + b - 1 for b in func.bq] expr = _x*Mul(*bfactors) - z*Mul(*afactors) poly = Poly(expr, _x) n = poly.degree() basis = [] M = zeros(n) for k in range(n): a = func.ap[0] + k basis += [hyper([a] + list(func.ap[1:]), func.bq, z)] if k < n - 1: M[k, k] = -a M[k, k + 1] = a B = Matrix(basis) C = Matrix([[1] + [0]*(n - 1)]) derivs = [eye(n)] for k in range(n): derivs.append(M*derivs[k]) l = poly.all_coeffs() l.reverse() res = [0]*n for k, c in enumerate(l): for r, d in enumerate(C*derivs[k]): res[r] += c*d for k, c in enumerate(res): M[n - 1, k] = -c/derivs[n - 1][0, n - 1]/poly.all_coeffs()[0] return Formula(func, z, None, [], B, C, M) else: # Since there are no `ap`, none of the `bq` can be non-positive # integers. basis = [] bq = list(func.bq[:]) for i in range(len(bq)): basis += [hyper([], bq, z)] bq[i] += 1 basis += [hyper([], bq, z)] B = Matrix(basis) n = len(B) C = Matrix([[1] + [0]*(n - 1)]) M = zeros(n) M[0, n - 1] = z/Mul(*func.bq) for k in range(1, n): M[k, k - 1] = func.bq[k - 1] M[k, k] = -func.bq[k - 1] return Formula(func, z, None, [], B, C, M) def hyperexpand_special(ap, bq, z): """ Try to find a closed-form expression for hyper(ap, bq, z), where ``z`` is supposed to be a "special" value, e.g. 1. This function tries various of the classical summation formulae (Gauss, Saalschuetz, etc). """ # This code is very ad-hoc. There are many clever algorithms # (notably Zeilberger's) related to this problem. # For now we just want a few simple cases to work. p, q = len(ap), len(bq) z_ = z z = unpolarify(z) if z == 0: return S.One from sympy.simplify.simplify import simplify if p == 2 and q == 1: # 2F1 a, b, c = ap + bq if z == 1: # Gauss return gamma(c - a - b)*gamma(c)/gamma(c - a)/gamma(c - b) if z == -1 and simplify(b - a + c) == 1: b, a = a, b if z == -1 and simplify(a - b + c) == 1: # Kummer if b.is_integer and b.is_negative: return 2*cos(pi*b/2)*gamma(-b)*gamma(b - a + 1) \ /gamma(-b/2)/gamma(b/2 - a + 1) else: return gamma(b/2 + 1)*gamma(b - a + 1) \ /gamma(b + 1)/gamma(b/2 - a + 1) # TODO tons of more formulae # investigate what algorithms exist return hyper(ap, bq, z_) _collection = None def _hyperexpand(func, z, ops0=[], z0=Dummy('z0'), premult=1, prem=0, rewrite='default'): """ Try to find an expression for the hypergeometric function ``func``. Explanation =========== The result is expressed in terms of a dummy variable ``z0``. Then it is multiplied by ``premult``. Then ``ops0`` is applied. ``premult`` must be a*z**prem for some a independent of ``z``. """ if z.is_zero: return S.One from sympy.simplify.simplify import simplify z = polarify(z, subs=False) if rewrite == 'default': rewrite = 'nonrepsmall' def carryout_plan(f, ops): C = apply_operators(f.C.subs(f.z, z0), ops, make_derivative_operator(f.M.subs(f.z, z0), z0)) from sympy.matrices.dense import eye C = apply_operators(C, ops0, make_derivative_operator(f.M.subs(f.z, z0) + prem*eye(f.M.shape[0]), z0)) if premult == 1: C = C.applyfunc(make_simp(z0)) r = reduce(lambda s,m: s+m[0]*m[1], zip(C, f.B.subs(f.z, z0)), S.Zero)*premult res = r.subs(z0, z) if rewrite: res = res.rewrite(rewrite) return res # TODO # The following would be possible: # *) PFD Duplication (see Kelly Roach's paper) # *) In a similar spirit, try_lerchphi() can be generalised considerably. global _collection if _collection is None: _collection = FormulaCollection() debug('Trying to expand hypergeometric function ', func) # First reduce order as much as possible. func, ops = reduce_order(func) if ops: debug(' Reduced order to ', func) else: debug(' Could not reduce order.') # Now try polynomial cases res = try_polynomial(func, z0) if res is not None: debug(' Recognised polynomial.') p = apply_operators(res, ops, lambda f: z0*f.diff(z0)) p = apply_operators(p*premult, ops0, lambda f: z0*f.diff(z0)) return unpolarify(simplify(p).subs(z0, z)) # Try to recognise a shifted sum. p = S.Zero res = try_shifted_sum(func, z0) if res is not None: func, nops, p = res debug(' Recognised shifted sum, reduced order to ', func) ops += nops # apply the plan for poly p = apply_operators(p, ops, lambda f: z0*f.diff(z0)) p = apply_operators(p*premult, ops0, lambda f: z0*f.diff(z0)) p = simplify(p).subs(z0, z) # Try special expansions early. if unpolarify(z) in [1, -1] and (len(func.ap), len(func.bq)) == (2, 1): f = build_hypergeometric_formula(func) r = carryout_plan(f, ops).replace(hyper, hyperexpand_special) if not r.has(hyper): return r + p # Try to find a formula in our collection formula = _collection.lookup_origin(func) # Now try a lerch phi formula if formula is None: formula = try_lerchphi(func) if formula is None: debug(' Could not find an origin. ', 'Will return answer in terms of ' 'simpler hypergeometric functions.') formula = build_hypergeometric_formula(func) debug(' Found an origin: ', formula.closed_form, ' ', formula.func) # We need to find the operators that convert formula into func. ops += devise_plan(func, formula.func, z0) # Now carry out the plan. r = carryout_plan(formula, ops) + p return powdenest(r, polar=True).replace(hyper, hyperexpand_special) def devise_plan_meijer(fro, to, z): """ Find operators to convert G-function ``fro`` into G-function ``to``. Explanation =========== It is assumed that ``fro`` and ``to`` have the same signatures, and that in fact any corresponding pair of parameters differs by integers, and a direct path is possible. I.e. if there are parameters a1 b1 c1 and a2 b2 c2 it is assumed that a1 can be shifted to a2, etc. The only thing this routine determines is the order of shifts to apply, nothing clever will be tried. It is also assumed that ``fro`` is suitable. Examples ======== >>> from sympy.simplify.hyperexpand import (devise_plan_meijer, ... G_Function) >>> from sympy.abc import z Empty plan: >>> devise_plan_meijer(G_Function([1], [2], [3], [4]), ... G_Function([1], [2], [3], [4]), z) [] Very simple plans: >>> devise_plan_meijer(G_Function([0], [], [], []), ... G_Function([1], [], [], []), z) [<Increment upper a index #0 of [0], [], [], [].>] >>> devise_plan_meijer(G_Function([0], [], [], []), ... G_Function([-1], [], [], []), z) [<Decrement upper a=0.>] >>> devise_plan_meijer(G_Function([], [1], [], []), ... G_Function([], [2], [], []), z) [<Increment lower a index #0 of [], [1], [], [].>] Slightly more complicated plans: >>> devise_plan_meijer(G_Function([0], [], [], []), ... G_Function([2], [], [], []), z) [<Increment upper a index #0 of [1], [], [], [].>, <Increment upper a index #0 of [0], [], [], [].>] >>> devise_plan_meijer(G_Function([0], [], [0], []), ... G_Function([-1], [], [1], []), z) [<Increment upper b=0.>, <Decrement upper a=0.>] Order matters: >>> devise_plan_meijer(G_Function([0], [], [0], []), ... G_Function([1], [], [1], []), z) [<Increment upper a index #0 of [0], [], [1], [].>, <Increment upper b=0.>] """ # TODO for now, we use the following simple heuristic: inverse-shift # when possible, shift otherwise. Give up if we cannot make progress. def try_shift(f, t, shifter, diff, counter): """ Try to apply ``shifter`` in order to bring some element in ``f`` nearer to its counterpart in ``to``. ``diff`` is +/- 1 and determines the effect of ``shifter``. Counter is a list of elements blocking the shift. Return an operator if change was possible, else None. """ for idx, (a, b) in enumerate(zip(f, t)): if ( (a - b).is_integer and (b - a)/diff > 0 and all(a != x for x in counter)): sh = shifter(idx) f[idx] += diff return sh fan = list(fro.an) fap = list(fro.ap) fbm = list(fro.bm) fbq = list(fro.bq) ops = [] change = True while change: change = False op = try_shift(fan, to.an, lambda i: MeijerUnShiftB(fan, fap, fbm, fbq, i, z), 1, fbm + fbq) if op is not None: ops += [op] change = True continue op = try_shift(fap, to.ap, lambda i: MeijerUnShiftD(fan, fap, fbm, fbq, i, z), 1, fbm + fbq) if op is not None: ops += [op] change = True continue op = try_shift(fbm, to.bm, lambda i: MeijerUnShiftA(fan, fap, fbm, fbq, i, z), -1, fan + fap) if op is not None: ops += [op] change = True continue op = try_shift(fbq, to.bq, lambda i: MeijerUnShiftC(fan, fap, fbm, fbq, i, z), -1, fan + fap) if op is not None: ops += [op] change = True continue op = try_shift(fan, to.an, lambda i: MeijerShiftB(fan[i]), -1, []) if op is not None: ops += [op] change = True continue op = try_shift(fap, to.ap, lambda i: MeijerShiftD(fap[i]), -1, []) if op is not None: ops += [op] change = True continue op = try_shift(fbm, to.bm, lambda i: MeijerShiftA(fbm[i]), 1, []) if op is not None: ops += [op] change = True continue op = try_shift(fbq, to.bq, lambda i: MeijerShiftC(fbq[i]), 1, []) if op is not None: ops += [op] change = True continue if fan != list(to.an) or fap != list(to.ap) or fbm != list(to.bm) or \ fbq != list(to.bq): raise NotImplementedError('Could not devise plan.') ops.reverse() return ops _meijercollection = None def _meijergexpand(func, z0, allow_hyper=False, rewrite='default', place=None): """ Try to find an expression for the Meijer G function specified by the G_Function ``func``. If ``allow_hyper`` is True, then returning an expression in terms of hypergeometric functions is allowed. Currently this just does Slater's theorem. If expansions exist both at zero and at infinity, ``place`` can be set to ``0`` or ``zoo`` for the preferred choice. """ global _meijercollection if _meijercollection is None: _meijercollection = MeijerFormulaCollection() if rewrite == 'default': rewrite = None func0 = func debug('Try to expand Meijer G function corresponding to ', func) # We will play games with analytic continuation - rather use a fresh symbol z = Dummy('z') func, ops = reduce_order_meijer(func) if ops: debug(' Reduced order to ', func) else: debug(' Could not reduce order.') # Try to find a direct formula f = _meijercollection.lookup_origin(func) if f is not None: debug(' Found a Meijer G formula: ', f.func) ops += devise_plan_meijer(f.func, func, z) # Now carry out the plan. C = apply_operators(f.C.subs(f.z, z), ops, make_derivative_operator(f.M.subs(f.z, z), z)) C = C.applyfunc(make_simp(z)) r = C*f.B.subs(f.z, z) r = r[0].subs(z, z0) return powdenest(r, polar=True) debug(" Could not find a direct formula. Trying Slater's theorem.") # TODO the following would be possible: # *) Paired Index Theorems # *) PFD Duplication # (See Kelly Roach's paper for details on either.) # # TODO Also, we tend to create combinations of gamma functions that can be # simplified. def can_do(pbm, pap): """ Test if slater applies. """ for i in pbm: if len(pbm[i]) > 1: l = 0 if i in pap: l = len(pap[i]) if l + 1 < len(pbm[i]): return False return True def do_slater(an, bm, ap, bq, z, zfinal): # zfinal is the value that will eventually be substituted for z. # We pass it to _hyperexpand to improve performance. from sympy.series import residue func = G_Function(an, bm, ap, bq) _, pbm, pap, _ = func.compute_buckets() if not can_do(pbm, pap): return S.Zero, False cond = len(an) + len(ap) < len(bm) + len(bq) if len(an) + len(ap) == len(bm) + len(bq): cond = abs(z) < 1 if cond is False: return S.Zero, False res = S.Zero for m in pbm: if len(pbm[m]) == 1: bh = pbm[m][0] fac = 1 bo = list(bm) bo.remove(bh) for bj in bo: fac *= gamma(bj - bh) for aj in an: fac *= gamma(1 + bh - aj) for bj in bq: fac /= gamma(1 + bh - bj) for aj in ap: fac /= gamma(aj - bh) nap = [1 + bh - a for a in list(an) + list(ap)] nbq = [1 + bh - b for b in list(bo) + list(bq)] k = polar_lift(S.NegativeOne**(len(ap) - len(bm))) harg = k*zfinal # NOTE even though k "is" +-1, this has to be t/k instead of # t*k ... we are using polar numbers for consistency! premult = (t/k)**bh hyp = _hyperexpand(Hyper_Function(nap, nbq), harg, ops, t, premult, bh, rewrite=None) res += fac * hyp else: b_ = pbm[m][0] ki = [bi - b_ for bi in pbm[m][1:]] u = len(ki) li = [ai - b_ for ai in pap[m][:u + 1]] bo = list(bm) for b in pbm[m]: bo.remove(b) ao = list(ap) for a in pap[m][:u]: ao.remove(a) lu = li[-1] di = [l - k for (l, k) in zip(li, ki)] # We first work out the integrand: s = Dummy('s') integrand = z**s for b in bm: if not Mod(b, 1) and b.is_Number: b = int(round(b)) integrand *= gamma(b - s) for a in an: integrand *= gamma(1 - a + s) for b in bq: integrand /= gamma(1 - b + s) for a in ap: integrand /= gamma(a - s) # Now sum the finitely many residues: # XXX This speeds up some cases - is it a good idea? integrand = expand_func(integrand) for r in range(int(round(lu))): resid = residue(integrand, s, b_ + r) resid = apply_operators(resid, ops, lambda f: z*f.diff(z)) res -= resid # Now the hypergeometric term. au = b_ + lu k = polar_lift(S.NegativeOne**(len(ao) + len(bo) + 1)) harg = k*zfinal premult = (t/k)**au nap = [1 + au - a for a in list(an) + list(ap)] + [1] nbq = [1 + au - b for b in list(bm) + list(bq)] hyp = _hyperexpand(Hyper_Function(nap, nbq), harg, ops, t, premult, au, rewrite=None) C = S.NegativeOne**(lu)/factorial(lu) for i in range(u): C *= S.NegativeOne**di[i]/rf(lu - li[i] + 1, di[i]) for a in an: C *= gamma(1 - a + au) for b in bo: C *= gamma(b - au) for a in ao: C /= gamma(a - au) for b in bq: C /= gamma(1 - b + au) res += C*hyp return res, cond t = Dummy('t') slater1, cond1 = do_slater(func.an, func.bm, func.ap, func.bq, z, z0) def tr(l): return [1 - x for x in l] for op in ops: op._poly = Poly(op._poly.subs({z: 1/t, _x: -_x}), _x) slater2, cond2 = do_slater(tr(func.bm), tr(func.an), tr(func.bq), tr(func.ap), t, 1/z0) slater1 = powdenest(slater1.subs(z, z0), polar=True) slater2 = powdenest(slater2.subs(t, 1/z0), polar=True) if not isinstance(cond2, bool): cond2 = cond2.subs(t, 1/z) m = func(z) if m.delta > 0 or \ (m.delta == 0 and len(m.ap) == len(m.bq) and (re(m.nu) < -1) is not False and polar_lift(z0) == polar_lift(1)): # The condition delta > 0 means that the convergence region is # connected. Any expression we find can be continued analytically # to the entire convergence region. # The conditions delta==0, p==q, re(nu) < -1 imply that G is continuous # on the positive reals, so the values at z=1 agree. if cond1 is not False: cond1 = True if cond2 is not False: cond2 = True if cond1 is True: slater1 = slater1.rewrite(rewrite or 'nonrep') else: slater1 = slater1.rewrite(rewrite or 'nonrepsmall') if cond2 is True: slater2 = slater2.rewrite(rewrite or 'nonrep') else: slater2 = slater2.rewrite(rewrite or 'nonrepsmall') if cond1 is not False and cond2 is not False: # If one condition is False, there is no choice. if place == 0: cond2 = False if place == zoo: cond1 = False if not isinstance(cond1, bool): cond1 = cond1.subs(z, z0) if not isinstance(cond2, bool): cond2 = cond2.subs(z, z0) def weight(expr, cond): if cond is True: c0 = 0 elif cond is False: c0 = 1 else: c0 = 2 if expr.has(oo, zoo, -oo, nan): # XXX this actually should not happen, but consider # S('meijerg(((0, -1/2, 0, -1/2, 1/2), ()), ((0,), # (-1/2, -1/2, -1/2, -1)), exp_polar(I*pi))/4') c0 = 3 return (c0, expr.count(hyper), expr.count_ops()) w1 = weight(slater1, cond1) w2 = weight(slater2, cond2) if min(w1, w2) <= (0, 1, oo): if w1 < w2: return slater1 else: return slater2 if max(w1[0], w2[0]) <= 1 and max(w1[1], w2[1]) <= 1: return Piecewise((slater1, cond1), (slater2, cond2), (func0(z0), True)) # We couldn't find an expression without hypergeometric functions. # TODO it would be helpful to give conditions under which the integral # is known to diverge. r = Piecewise((slater1, cond1), (slater2, cond2), (func0(z0), True)) if r.has(hyper) and not allow_hyper: debug(' Could express using hypergeometric functions, ' 'but not allowed.') if not r.has(hyper) or allow_hyper: return r return func0(z0) def hyperexpand(f, allow_hyper=False, rewrite='default', place=None): """ Expand hypergeometric functions. If allow_hyper is True, allow partial simplification (that is a result different from input, but still containing hypergeometric functions). If a G-function has expansions both at zero and at infinity, ``place`` can be set to ``0`` or ``zoo`` to indicate the preferred choice. Examples ======== >>> from sympy.simplify.hyperexpand import hyperexpand >>> from sympy.functions import hyper >>> from sympy.abc import z >>> hyperexpand(hyper([], [], z)) exp(z) Non-hyperegeometric parts of the expression and hypergeometric expressions that are not recognised are left unchanged: >>> hyperexpand(1 + hyper([1, 1, 1], [], z)) hyper((1, 1, 1), (), z) + 1 """ f = sympify(f) def do_replace(ap, bq, z): r = _hyperexpand(Hyper_Function(ap, bq), z, rewrite=rewrite) if r is None: return hyper(ap, bq, z) else: return r def do_meijer(ap, bq, z): r = _meijergexpand(G_Function(ap[0], ap[1], bq[0], bq[1]), z, allow_hyper, rewrite=rewrite, place=place) if not r.has(nan, zoo, oo, -oo): return r return f.replace(hyper, do_replace).replace(meijerg, do_meijer)
3340f518ee7a08546c8b1cc0e71f8e16e1cb62185a8df91c5bcfe83b6c9b178c
from collections import defaultdict from sympy.core import (Basic, S, Add, Mul, Pow, Symbol, sympify, expand_func, Function, Dummy, Expr, factor_terms, expand_power_exp, Eq) from sympy.core.exprtools import factor_nc from sympy.core.parameters import global_parameters from sympy.core.function import (expand_log, count_ops, _mexpand, nfloat, expand_mul, expand) from sympy.core.numbers import Float, I, pi, Rational from sympy.core.relational import Relational from sympy.core.rules import Transform from sympy.core.sorting import ordered from sympy.core.sympify import _sympify from sympy.core.traversal import bottom_up as _bottom_up, walk as _walk from sympy.functions import gamma, exp, sqrt, log, exp_polar, re from sympy.functions.combinatorial.factorials import CombinatorialFunction from sympy.functions.elementary.complexes import unpolarify, Abs, sign from sympy.functions.elementary.exponential import ExpBase from sympy.functions.elementary.hyperbolic import HyperbolicFunction from sympy.functions.elementary.integers import ceiling from sympy.functions.elementary.piecewise import Piecewise, piecewise_fold from sympy.functions.elementary.trigonometric import TrigonometricFunction from sympy.functions.special.bessel import (BesselBase, besselj, besseli, besselk, bessely, jn) from sympy.functions.special.tensor_functions import KroneckerDelta from sympy.polys import together, cancel, factor from sympy.simplify.combsimp import combsimp from sympy.simplify.cse_opts import sub_pre, sub_post from sympy.simplify.hyperexpand import hyperexpand from sympy.simplify.powsimp import powsimp from sympy.simplify.radsimp import radsimp, fraction, collect_abs from sympy.simplify.sqrtdenest import sqrtdenest from sympy.simplify.trigsimp import trigsimp, exptrigsimp from sympy.utilities.decorator import deprecated from sympy.utilities.iterables import has_variety, sift, subsets, iterable from sympy.utilities.misc import as_int import mpmath def separatevars(expr, symbols=[], dict=False, force=False): """ Separates variables in an expression, if possible. By default, it separates with respect to all symbols in an expression and collects constant coefficients that are independent of symbols. Explanation =========== If ``dict=True`` then the separated terms will be returned in a dictionary keyed to their corresponding symbols. By default, all symbols in the expression will appear as keys; if symbols are provided, then all those symbols will be used as keys, and any terms in the expression containing other symbols or non-symbols will be returned keyed to the string 'coeff'. (Passing None for symbols will return the expression in a dictionary keyed to 'coeff'.) If ``force=True``, then bases of powers will be separated regardless of assumptions on the symbols involved. Notes ===== The order of the factors is determined by Mul, so that the separated expressions may not necessarily be grouped together. Although factoring is necessary to separate variables in some expressions, it is not necessary in all cases, so one should not count on the returned factors being factored. Examples ======== >>> from sympy.abc import x, y, z, alpha >>> from sympy import separatevars, sin >>> separatevars((x*y)**y) (x*y)**y >>> separatevars((x*y)**y, force=True) x**y*y**y >>> e = 2*x**2*z*sin(y)+2*z*x**2 >>> separatevars(e) 2*x**2*z*(sin(y) + 1) >>> separatevars(e, symbols=(x, y), dict=True) {'coeff': 2*z, x: x**2, y: sin(y) + 1} >>> separatevars(e, [x, y, alpha], dict=True) {'coeff': 2*z, alpha: 1, x: x**2, y: sin(y) + 1} If the expression is not really separable, or is only partially separable, separatevars will do the best it can to separate it by using factoring. >>> separatevars(x + x*y - 3*x**2) -x*(3*x - y - 1) If the expression is not separable then expr is returned unchanged or (if dict=True) then None is returned. >>> eq = 2*x + y*sin(x) >>> separatevars(eq) == eq True >>> separatevars(2*x + y*sin(x), symbols=(x, y), dict=True) is None True """ expr = sympify(expr) if dict: return _separatevars_dict(_separatevars(expr, force), symbols) else: return _separatevars(expr, force) def _separatevars(expr, force): if isinstance(expr, Abs): arg = expr.args[0] if arg.is_Mul and not arg.is_number: s = separatevars(arg, dict=True, force=force) if s is not None: return Mul(*map(expr.func, s.values())) else: return expr if len(expr.free_symbols) < 2: return expr # don't destroy a Mul since much of the work may already be done if expr.is_Mul: args = list(expr.args) changed = False for i, a in enumerate(args): args[i] = separatevars(a, force) changed = changed or args[i] != a if changed: expr = expr.func(*args) return expr # get a Pow ready for expansion if expr.is_Pow and expr.base != S.Exp1: expr = Pow(separatevars(expr.base, force=force), expr.exp) # First try other expansion methods expr = expr.expand(mul=False, multinomial=False, force=force) _expr, reps = posify(expr) if force else (expr, {}) expr = factor(_expr).subs(reps) if not expr.is_Add: return expr # Find any common coefficients to pull out args = list(expr.args) commonc = args[0].args_cnc(cset=True, warn=False)[0] for i in args[1:]: commonc &= i.args_cnc(cset=True, warn=False)[0] commonc = Mul(*commonc) commonc = commonc.as_coeff_Mul()[1] # ignore constants commonc_set = commonc.args_cnc(cset=True, warn=False)[0] # remove them for i, a in enumerate(args): c, nc = a.args_cnc(cset=True, warn=False) c = c - commonc_set args[i] = Mul(*c)*Mul(*nc) nonsepar = Add(*args) if len(nonsepar.free_symbols) > 1: _expr = nonsepar _expr, reps = posify(_expr) if force else (_expr, {}) _expr = (factor(_expr)).subs(reps) if not _expr.is_Add: nonsepar = _expr return commonc*nonsepar def _separatevars_dict(expr, symbols): if symbols: if not all(t.is_Atom for t in symbols): raise ValueError("symbols must be Atoms.") symbols = list(symbols) elif symbols is None: return {'coeff': expr} else: symbols = list(expr.free_symbols) if not symbols: return None ret = {i: [] for i in symbols + ['coeff']} for i in Mul.make_args(expr): expsym = i.free_symbols intersection = set(symbols).intersection(expsym) if len(intersection) > 1: return None if len(intersection) == 0: # There are no symbols, so it is part of the coefficient ret['coeff'].append(i) else: ret[intersection.pop()].append(i) # rebuild for k, v in ret.items(): ret[k] = Mul(*v) return ret def _is_sum_surds(p): args = p.args if p.is_Add else [p] for y in args: if not ((y**2).is_Rational and y.is_extended_real): return False return True def posify(eq): """Return ``eq`` (with generic symbols made positive) and a dictionary containing the mapping between the old and new symbols. Explanation =========== Any symbol that has positive=None will be replaced with a positive dummy symbol having the same name. This replacement will allow more symbolic processing of expressions, especially those involving powers and logarithms. A dictionary that can be sent to subs to restore ``eq`` to its original symbols is also returned. >>> from sympy import posify, Symbol, log, solve >>> from sympy.abc import x >>> posify(x + Symbol('p', positive=True) + Symbol('n', negative=True)) (_x + n + p, {_x: x}) >>> eq = 1/x >>> log(eq).expand() log(1/x) >>> log(posify(eq)[0]).expand() -log(_x) >>> p, rep = posify(eq) >>> log(p).expand().subs(rep) -log(x) It is possible to apply the same transformations to an iterable of expressions: >>> eq = x**2 - 4 >>> solve(eq, x) [-2, 2] >>> eq_x, reps = posify([eq, x]); eq_x [_x**2 - 4, _x] >>> solve(*eq_x) [2] """ eq = sympify(eq) if iterable(eq): f = type(eq) eq = list(eq) syms = set() for e in eq: syms = syms.union(e.atoms(Symbol)) reps = {} for s in syms: reps.update({v: k for k, v in posify(s)[1].items()}) for i, e in enumerate(eq): eq[i] = e.subs(reps) return f(eq), {r: s for s, r in reps.items()} reps = {s: Dummy(s.name, positive=True, **s.assumptions0) for s in eq.free_symbols if s.is_positive is None} eq = eq.subs(reps) return eq, {r: s for s, r in reps.items()} def hypersimp(f, k): """Given combinatorial term f(k) simplify its consecutive term ratio i.e. f(k+1)/f(k). The input term can be composed of functions and integer sequences which have equivalent representation in terms of gamma special function. Explanation =========== The algorithm performs three basic steps: 1. Rewrite all functions in terms of gamma, if possible. 2. Rewrite all occurrences of gamma in terms of products of gamma and rising factorial with integer, absolute constant exponent. 3. Perform simplification of nested fractions, powers and if the resulting expression is a quotient of polynomials, reduce their total degree. If f(k) is hypergeometric then as result we arrive with a quotient of polynomials of minimal degree. Otherwise None is returned. For more information on the implemented algorithm refer to: 1. W. Koepf, Algorithms for m-fold Hypergeometric Summation, Journal of Symbolic Computation (1995) 20, 399-417 """ f = sympify(f) g = f.subs(k, k + 1) / f g = g.rewrite(gamma) if g.has(Piecewise): g = piecewise_fold(g) g = g.args[-1][0] g = expand_func(g) g = powsimp(g, deep=True, combine='exp') if g.is_rational_function(k): return simplify(g, ratio=S.Infinity) else: return None def hypersimilar(f, g, k): """ Returns True if ``f`` and ``g`` are hyper-similar. Explanation =========== Similarity in hypergeometric sense means that a quotient of f(k) and g(k) is a rational function in ``k``. This procedure is useful in solving recurrence relations. For more information see hypersimp(). """ f, g = list(map(sympify, (f, g))) h = (f/g).rewrite(gamma) h = h.expand(func=True, basic=False) return h.is_rational_function(k) def signsimp(expr, evaluate=None): """Make all Add sub-expressions canonical wrt sign. Explanation =========== If an Add subexpression, ``a``, can have a sign extracted, as determined by could_extract_minus_sign, it is replaced with Mul(-1, a, evaluate=False). This allows signs to be extracted from powers and products. Examples ======== >>> from sympy import signsimp, exp, symbols >>> from sympy.abc import x, y >>> i = symbols('i', odd=True) >>> n = -1 + 1/x >>> n/x/(-n)**2 - 1/n/x (-1 + 1/x)/(x*(1 - 1/x)**2) - 1/(x*(-1 + 1/x)) >>> signsimp(_) 0 >>> x*n + x*-n x*(-1 + 1/x) + x*(1 - 1/x) >>> signsimp(_) 0 Since powers automatically handle leading signs >>> (-2)**i -2**i signsimp can be used to put the base of a power with an integer exponent into canonical form: >>> n**i (-1 + 1/x)**i By default, signsimp doesn't leave behind any hollow simplification: if making an Add canonical wrt sign didn't change the expression, the original Add is restored. If this is not desired then the keyword ``evaluate`` can be set to False: >>> e = exp(y - x) >>> signsimp(e) == e True >>> signsimp(e, evaluate=False) exp(-(x - y)) """ if evaluate is None: evaluate = global_parameters.evaluate expr = sympify(expr) if not isinstance(expr, (Expr, Relational)) or expr.is_Atom: return expr # get rid of an pre-existing unevaluation regarding sign e = expr.replace(lambda x: x.is_Mul and -(-x) != x, lambda x: -(-x)) e = sub_post(sub_pre(e)) if not isinstance(e, (Expr, Relational)) or e.is_Atom: return e if e.is_Add: rv = e.func(*[signsimp(a) for a in e.args]) if not evaluate and isinstance(rv, Add ) and rv.could_extract_minus_sign(): return Mul(S.NegativeOne, -rv, evaluate=False) return rv if evaluate: e = e.replace(lambda x: x.is_Mul and -(-x) != x, lambda x: -(-x)) return e def simplify(expr, ratio=1.7, measure=count_ops, rational=False, inverse=False, doit=True, **kwargs): """Simplifies the given expression. Explanation =========== Simplification is not a well defined term and the exact strategies this function tries can change in the future versions of SymPy. If your algorithm relies on "simplification" (whatever it is), try to determine what you need exactly - is it powsimp()?, radsimp()?, together()?, logcombine()?, or something else? And use this particular function directly, because those are well defined and thus your algorithm will be robust. Nonetheless, especially for interactive use, or when you do not know anything about the structure of the expression, simplify() tries to apply intelligent heuristics to make the input expression "simpler". For example: >>> from sympy import simplify, cos, sin >>> from sympy.abc import x, y >>> a = (x + x**2)/(x*sin(y)**2 + x*cos(y)**2) >>> a (x**2 + x)/(x*sin(y)**2 + x*cos(y)**2) >>> simplify(a) x + 1 Note that we could have obtained the same result by using specific simplification functions: >>> from sympy import trigsimp, cancel >>> trigsimp(a) (x**2 + x)/x >>> cancel(_) x + 1 In some cases, applying :func:`simplify` may actually result in some more complicated expression. The default ``ratio=1.7`` prevents more extreme cases: if (result length)/(input length) > ratio, then input is returned unmodified. The ``measure`` parameter lets you specify the function used to determine how complex an expression is. The function should take a single argument as an expression and return a number such that if expression ``a`` is more complex than expression ``b``, then ``measure(a) > measure(b)``. The default measure function is :func:`~.count_ops`, which returns the total number of operations in the expression. For example, if ``ratio=1``, ``simplify`` output cannot be longer than input. :: >>> from sympy import sqrt, simplify, count_ops, oo >>> root = 1/(sqrt(2)+3) Since ``simplify(root)`` would result in a slightly longer expression, root is returned unchanged instead:: >>> simplify(root, ratio=1) == root True If ``ratio=oo``, simplify will be applied anyway:: >>> count_ops(simplify(root, ratio=oo)) > count_ops(root) True Note that the shortest expression is not necessary the simplest, so setting ``ratio`` to 1 may not be a good idea. Heuristically, the default value ``ratio=1.7`` seems like a reasonable choice. You can easily define your own measure function based on what you feel should represent the "size" or "complexity" of the input expression. Note that some choices, such as ``lambda expr: len(str(expr))`` may appear to be good metrics, but have other problems (in this case, the measure function may slow down simplify too much for very large expressions). If you do not know what a good metric would be, the default, ``count_ops``, is a good one. For example: >>> from sympy import symbols, log >>> a, b = symbols('a b', positive=True) >>> g = log(a) + log(b) + log(a)*log(1/b) >>> h = simplify(g) >>> h log(a*b**(1 - log(a))) >>> count_ops(g) 8 >>> count_ops(h) 5 So you can see that ``h`` is simpler than ``g`` using the count_ops metric. However, we may not like how ``simplify`` (in this case, using ``logcombine``) has created the ``b**(log(1/a) + 1)`` term. A simple way to reduce this would be to give more weight to powers as operations in ``count_ops``. We can do this by using the ``visual=True`` option: >>> print(count_ops(g, visual=True)) 2*ADD + DIV + 4*LOG + MUL >>> print(count_ops(h, visual=True)) 2*LOG + MUL + POW + SUB >>> from sympy import Symbol, S >>> def my_measure(expr): ... POW = Symbol('POW') ... # Discourage powers by giving POW a weight of 10 ... count = count_ops(expr, visual=True).subs(POW, 10) ... # Every other operation gets a weight of 1 (the default) ... count = count.replace(Symbol, type(S.One)) ... return count >>> my_measure(g) 8 >>> my_measure(h) 14 >>> 15./8 > 1.7 # 1.7 is the default ratio True >>> simplify(g, measure=my_measure) -log(a)*log(b) + log(a) + log(b) Note that because ``simplify()`` internally tries many different simplification strategies and then compares them using the measure function, we get a completely different result that is still different from the input expression by doing this. If ``rational=True``, Floats will be recast as Rationals before simplification. If ``rational=None``, Floats will be recast as Rationals but the result will be recast as Floats. If rational=False(default) then nothing will be done to the Floats. If ``inverse=True``, it will be assumed that a composition of inverse functions, such as sin and asin, can be cancelled in any order. For example, ``asin(sin(x))`` will yield ``x`` without checking whether x belongs to the set where this relation is true. The default is False. Note that ``simplify()`` automatically calls ``doit()`` on the final expression. You can avoid this behavior by passing ``doit=False`` as an argument. Also, it should be noted that simplifying the boolian expression is not well defined. If the expression prefers automatic evaluation (such as :obj:`~.Eq()` or :obj:`~.Or()`), simplification will return ``True`` or ``False`` if truth value can be determined. If the expression is not evaluated by default (such as :obj:`~.Predicate()`), simplification will not reduce it and you should use :func:`~.refine()` or :func:`~.ask()` function. This inconsistency will be resolved in future version. See Also ======== sympy.assumptions.refine.refine : Simplification using assumptions. sympy.assumptions.ask.ask : Query for boolean expressions using assumptions. """ def shorter(*choices): """ Return the choice that has the fewest ops. In case of a tie, the expression listed first is selected. """ if not has_variety(choices): return choices[0] return min(choices, key=measure) def done(e): rv = e.doit() if doit else e return shorter(rv, collect_abs(rv)) expr = sympify(expr, rational=rational) kwargs = dict( ratio=kwargs.get('ratio', ratio), measure=kwargs.get('measure', measure), rational=kwargs.get('rational', rational), inverse=kwargs.get('inverse', inverse), doit=kwargs.get('doit', doit)) # no routine for Expr needs to check for is_zero if isinstance(expr, Expr) and expr.is_zero: return S.Zero if not expr.is_Number else expr _eval_simplify = getattr(expr, '_eval_simplify', None) if _eval_simplify is not None: return _eval_simplify(**kwargs) original_expr = expr = collect_abs(signsimp(expr)) if not isinstance(expr, Basic) or not expr.args: # XXX: temporary hack return expr if inverse and expr.has(Function): expr = inversecombine(expr) if not expr.args: # simplified to atomic return expr # do deep simplification handled = Add, Mul, Pow, ExpBase expr = expr.replace( # here, checking for x.args is not enough because Basic has # args but Basic does not always play well with replace, e.g. # when simultaneous is True found expressions will be masked # off with a Dummy but not all Basic objects in an expression # can be replaced with a Dummy lambda x: isinstance(x, Expr) and x.args and not isinstance( x, handled), lambda x: x.func(*[simplify(i, **kwargs) for i in x.args]), simultaneous=False) if not isinstance(expr, handled): return done(expr) if not expr.is_commutative: expr = nc_simplify(expr) # TODO: Apply different strategies, considering expression pattern: # is it a purely rational function? Is there any trigonometric function?... # See also https://github.com/sympy/sympy/pull/185. # rationalize Floats floats = False if rational is not False and expr.has(Float): floats = True expr = nsimplify(expr, rational=True) expr = _bottom_up(expr, lambda w: getattr(w, 'normal', lambda: w)()) expr = Mul(*powsimp(expr).as_content_primitive()) _e = cancel(expr) expr1 = shorter(_e, _mexpand(_e).cancel()) # issue 6829 expr2 = shorter(together(expr, deep=True), together(expr1, deep=True)) if ratio is S.Infinity: expr = expr2 else: expr = shorter(expr2, expr1, expr) if not isinstance(expr, Basic): # XXX: temporary hack return expr expr = factor_terms(expr, sign=False) # must come before `Piecewise` since this introduces more `Piecewise` terms if expr.has(sign): expr = expr.rewrite(Abs) # Deal with Piecewise separately to avoid recursive growth of expressions if expr.has(Piecewise): # Fold into a single Piecewise expr = piecewise_fold(expr) # Apply doit, if doit=True expr = done(expr) # Still a Piecewise? if expr.has(Piecewise): # Fold into a single Piecewise, in case doit lead to some # expressions being Piecewise expr = piecewise_fold(expr) # kroneckersimp also affects Piecewise if expr.has(KroneckerDelta): expr = kroneckersimp(expr) # Still a Piecewise? if expr.has(Piecewise): from sympy.functions.elementary.piecewise import piecewise_simplify # Do not apply doit on the segments as it has already # been done above, but simplify expr = piecewise_simplify(expr, deep=True, doit=False) # Still a Piecewise? if expr.has(Piecewise): # Try factor common terms expr = shorter(expr, factor_terms(expr)) # As all expressions have been simplified above with the # complete simplify, nothing more needs to be done here return expr # hyperexpand automatically only works on hypergeometric terms # Do this after the Piecewise part to avoid recursive expansion expr = hyperexpand(expr) if expr.has(KroneckerDelta): expr = kroneckersimp(expr) if expr.has(BesselBase): expr = besselsimp(expr) if expr.has(TrigonometricFunction, HyperbolicFunction): expr = trigsimp(expr, deep=True) if expr.has(log): expr = shorter(expand_log(expr, deep=True), logcombine(expr)) if expr.has(CombinatorialFunction, gamma): # expression with gamma functions or non-integer arguments is # automatically passed to gammasimp expr = combsimp(expr) from sympy.concrete.products import Product from sympy.concrete.summations import Sum from sympy.integrals.integrals import Integral if expr.has(Sum): expr = sum_simplify(expr, **kwargs) if expr.has(Integral): expr = expr.xreplace({ i: factor_terms(i) for i in expr.atoms(Integral)}) if expr.has(Product): expr = product_simplify(expr) from sympy.physics.units import Quantity if expr.has(Quantity): from sympy.physics.units.util import quantity_simplify expr = quantity_simplify(expr) short = shorter(powsimp(expr, combine='exp', deep=True), powsimp(expr), expr) short = shorter(short, cancel(short)) short = shorter(short, factor_terms(short), expand_power_exp(expand_mul(short))) if short.has(TrigonometricFunction, HyperbolicFunction, ExpBase, exp): short = exptrigsimp(short) # get rid of hollow 2-arg Mul factorization hollow_mul = Transform( lambda x: Mul(*x.args), lambda x: x.is_Mul and len(x.args) == 2 and x.args[0].is_Number and x.args[1].is_Add and x.is_commutative) expr = short.xreplace(hollow_mul) numer, denom = expr.as_numer_denom() if denom.is_Add: n, d = fraction(radsimp(1/denom, symbolic=False, max_terms=1)) if n is not S.One: expr = (numer*n).expand()/d if expr.could_extract_minus_sign(): n, d = fraction(expr) if d != 0: expr = signsimp(-n/(-d)) if measure(expr) > ratio*measure(original_expr): expr = original_expr # restore floats if floats and rational is None: expr = nfloat(expr, exponent=False) return done(expr) def sum_simplify(s, **kwargs): """Main function for Sum simplification""" from sympy.concrete.summations import Sum if not isinstance(s, Add): s = s.xreplace({a: sum_simplify(a, **kwargs) for a in s.atoms(Add) if a.has(Sum)}) s = expand(s) if not isinstance(s, Add): return s terms = s.args s_t = [] # Sum Terms o_t = [] # Other Terms for term in terms: sum_terms, other = sift(Mul.make_args(term), lambda i: isinstance(i, Sum), binary=True) if not sum_terms: o_t.append(term) continue other = [Mul(*other)] s_t.append(Mul(*(other + [s._eval_simplify(**kwargs) for s in sum_terms]))) result = Add(sum_combine(s_t), *o_t) return result def sum_combine(s_t): """Helper function for Sum simplification Attempts to simplify a list of sums, by combining limits / sum function's returns the simplified sum """ from sympy.concrete.summations import Sum used = [False] * len(s_t) for method in range(2): for i, s_term1 in enumerate(s_t): if not used[i]: for j, s_term2 in enumerate(s_t): if not used[j] and i != j: temp = sum_add(s_term1, s_term2, method) if isinstance(temp, (Sum, Mul)): s_t[i] = temp s_term1 = s_t[i] used[j] = True result = S.Zero for i, s_term in enumerate(s_t): if not used[i]: result = Add(result, s_term) return result def factor_sum(self, limits=None, radical=False, clear=False, fraction=False, sign=True): """Return Sum with constant factors extracted. If ``limits`` is specified then ``self`` is the summand; the other keywords are passed to ``factor_terms``. Examples ======== >>> from sympy import Sum >>> from sympy.abc import x, y >>> from sympy.simplify.simplify import factor_sum >>> s = Sum(x*y, (x, 1, 3)) >>> factor_sum(s) y*Sum(x, (x, 1, 3)) >>> factor_sum(s.function, s.limits) y*Sum(x, (x, 1, 3)) """ # XXX deprecate in favor of direct call to factor_terms from sympy.concrete.summations import Sum kwargs = dict(radical=radical, clear=clear, fraction=fraction, sign=sign) expr = Sum(self, *limits) if limits else self return factor_terms(expr, **kwargs) def sum_add(self, other, method=0): """Helper function for Sum simplification""" from sympy.concrete.summations import Sum #we know this is something in terms of a constant * a sum #so we temporarily put the constants inside for simplification #then simplify the result def __refactor(val): args = Mul.make_args(val) sumv = next(x for x in args if isinstance(x, Sum)) constant = Mul(*[x for x in args if x != sumv]) return Sum(constant * sumv.function, *sumv.limits) if isinstance(self, Mul): rself = __refactor(self) else: rself = self if isinstance(other, Mul): rother = __refactor(other) else: rother = other if type(rself) == type(rother): if method == 0: if rself.limits == rother.limits: return factor_sum(Sum(rself.function + rother.function, *rself.limits)) elif method == 1: if simplify(rself.function - rother.function) == 0: if len(rself.limits) == len(rother.limits) == 1: i = rself.limits[0][0] x1 = rself.limits[0][1] y1 = rself.limits[0][2] j = rother.limits[0][0] x2 = rother.limits[0][1] y2 = rother.limits[0][2] if i == j: if x2 == y1 + 1: return factor_sum(Sum(rself.function, (i, x1, y2))) elif x1 == y2 + 1: return factor_sum(Sum(rself.function, (i, x2, y1))) return Add(self, other) def product_simplify(s): """Main function for Product simplification""" from sympy.concrete.products import Product terms = Mul.make_args(s) p_t = [] # Product Terms o_t = [] # Other Terms for term in terms: if isinstance(term, Product): p_t.append(term) else: o_t.append(term) used = [False] * len(p_t) for method in range(2): for i, p_term1 in enumerate(p_t): if not used[i]: for j, p_term2 in enumerate(p_t): if not used[j] and i != j: if isinstance(product_mul(p_term1, p_term2, method), Product): p_t[i] = product_mul(p_term1, p_term2, method) used[j] = True result = Mul(*o_t) for i, p_term in enumerate(p_t): if not used[i]: result = Mul(result, p_term) return result def product_mul(self, other, method=0): """Helper function for Product simplification""" from sympy.concrete.products import Product if type(self) == type(other): if method == 0: if self.limits == other.limits: return Product(self.function * other.function, *self.limits) elif method == 1: if simplify(self.function - other.function) == 0: if len(self.limits) == len(other.limits) == 1: i = self.limits[0][0] x1 = self.limits[0][1] y1 = self.limits[0][2] j = other.limits[0][0] x2 = other.limits[0][1] y2 = other.limits[0][2] if i == j: if x2 == y1 + 1: return Product(self.function, (i, x1, y2)) elif x1 == y2 + 1: return Product(self.function, (i, x2, y1)) return Mul(self, other) def _nthroot_solve(p, n, prec): """ helper function for ``nthroot`` It denests ``p**Rational(1, n)`` using its minimal polynomial """ from sympy.polys.numberfields.minpoly import _minimal_polynomial_sq from sympy.solvers import solve while n % 2 == 0: p = sqrtdenest(sqrt(p)) n = n // 2 if n == 1: return p pn = p**Rational(1, n) x = Symbol('x') f = _minimal_polynomial_sq(p, n, x) if f is None: return None sols = solve(f, x) for sol in sols: if abs(sol - pn).n() < 1./10**prec: sol = sqrtdenest(sol) if _mexpand(sol**n) == p: return sol def logcombine(expr, force=False): """ Takes logarithms and combines them using the following rules: - log(x) + log(y) == log(x*y) if both are positive - a*log(x) == log(x**a) if x is positive and a is real If ``force`` is ``True`` then the assumptions above will be assumed to hold if there is no assumption already in place on a quantity. For example, if ``a`` is imaginary or the argument negative, force will not perform a combination but if ``a`` is a symbol with no assumptions the change will take place. Examples ======== >>> from sympy import Symbol, symbols, log, logcombine, I >>> from sympy.abc import a, x, y, z >>> logcombine(a*log(x) + log(y) - log(z)) a*log(x) + log(y) - log(z) >>> logcombine(a*log(x) + log(y) - log(z), force=True) log(x**a*y/z) >>> x,y,z = symbols('x,y,z', positive=True) >>> a = Symbol('a', real=True) >>> logcombine(a*log(x) + log(y) - log(z)) log(x**a*y/z) The transformation is limited to factors and/or terms that contain logs, so the result depends on the initial state of expansion: >>> eq = (2 + 3*I)*log(x) >>> logcombine(eq, force=True) == eq True >>> logcombine(eq.expand(), force=True) log(x**2) + I*log(x**3) See Also ======== posify: replace all symbols with symbols having positive assumptions sympy.core.function.expand_log: expand the logarithms of products and powers; the opposite of logcombine """ def f(rv): if not (rv.is_Add or rv.is_Mul): return rv def gooda(a): # bool to tell whether the leading ``a`` in ``a*log(x)`` # could appear as log(x**a) return (a is not S.NegativeOne and # -1 *could* go, but we disallow (a.is_extended_real or force and a.is_extended_real is not False)) def goodlog(l): # bool to tell whether log ``l``'s argument can combine with others a = l.args[0] return a.is_positive or force and a.is_nonpositive is not False other = [] logs = [] log1 = defaultdict(list) for a in Add.make_args(rv): if isinstance(a, log) and goodlog(a): log1[()].append(([], a)) elif not a.is_Mul: other.append(a) else: ot = [] co = [] lo = [] for ai in a.args: if ai.is_Rational and ai < 0: ot.append(S.NegativeOne) co.append(-ai) elif isinstance(ai, log) and goodlog(ai): lo.append(ai) elif gooda(ai): co.append(ai) else: ot.append(ai) if len(lo) > 1: logs.append((ot, co, lo)) elif lo: log1[tuple(ot)].append((co, lo[0])) else: other.append(a) # if there is only one log in other, put it with the # good logs if len(other) == 1 and isinstance(other[0], log): log1[()].append(([], other.pop())) # if there is only one log at each coefficient and none have # an exponent to place inside the log then there is nothing to do if not logs and all(len(log1[k]) == 1 and log1[k][0] == [] for k in log1): return rv # collapse multi-logs as far as possible in a canonical way # TODO: see if x*log(a)+x*log(a)*log(b) -> x*log(a)*(1+log(b))? # -- in this case, it's unambiguous, but if it were were a log(c) in # each term then it's arbitrary whether they are grouped by log(a) or # by log(c). So for now, just leave this alone; it's probably better to # let the user decide for o, e, l in logs: l = list(ordered(l)) e = log(l.pop(0).args[0]**Mul(*e)) while l: li = l.pop(0) e = log(li.args[0]**e) c, l = Mul(*o), e if isinstance(l, log): # it should be, but check to be sure log1[(c,)].append(([], l)) else: other.append(c*l) # logs that have the same coefficient can multiply for k in list(log1.keys()): log1[Mul(*k)] = log(logcombine(Mul(*[ l.args[0]**Mul(*c) for c, l in log1.pop(k)]), force=force), evaluate=False) # logs that have oppositely signed coefficients can divide for k in ordered(list(log1.keys())): if k not in log1: # already popped as -k continue if -k in log1: # figure out which has the minus sign; the one with # more op counts should be the one num, den = k, -k if num.count_ops() > den.count_ops(): num, den = den, num other.append( num*log(log1.pop(num).args[0]/log1.pop(den).args[0], evaluate=False)) else: other.append(k*log1.pop(k)) return Add(*other) return _bottom_up(expr, f) def inversecombine(expr): """Simplify the composition of a function and its inverse. Explanation =========== No attention is paid to whether the inverse is a left inverse or a right inverse; thus, the result will in general not be equivalent to the original expression. Examples ======== >>> from sympy.simplify.simplify import inversecombine >>> from sympy import asin, sin, log, exp >>> from sympy.abc import x >>> inversecombine(asin(sin(x))) x >>> inversecombine(2*log(exp(3*x))) 6*x """ def f(rv): if isinstance(rv, log): if isinstance(rv.args[0], exp) or (rv.args[0].is_Pow and rv.args[0].base == S.Exp1): rv = rv.args[0].exp elif rv.is_Function and hasattr(rv, "inverse"): if (len(rv.args) == 1 and len(rv.args[0].args) == 1 and isinstance(rv.args[0], rv.inverse(argindex=1))): rv = rv.args[0].args[0] if rv.is_Pow and rv.base == S.Exp1: if isinstance(rv.exp, log): rv = rv.exp.args[0] return rv return _bottom_up(expr, f) def kroneckersimp(expr): """ Simplify expressions with KroneckerDelta. The only simplification currently attempted is to identify multiplicative cancellation: Examples ======== >>> from sympy import KroneckerDelta, kroneckersimp >>> from sympy.abc import i >>> kroneckersimp(1 + KroneckerDelta(0, i) * KroneckerDelta(1, i)) 1 """ def args_cancel(args1, args2): for i1 in range(2): for i2 in range(2): a1 = args1[i1] a2 = args2[i2] a3 = args1[(i1 + 1) % 2] a4 = args2[(i2 + 1) % 2] if Eq(a1, a2) is S.true and Eq(a3, a4) is S.false: return True return False def cancel_kronecker_mul(m): args = m.args deltas = [a for a in args if isinstance(a, KroneckerDelta)] for delta1, delta2 in subsets(deltas, 2): args1 = delta1.args args2 = delta2.args if args_cancel(args1, args2): return S.Zero * m # In case of oo etc return m if not expr.has(KroneckerDelta): return expr if expr.has(Piecewise): expr = expr.rewrite(KroneckerDelta) newexpr = expr expr = None while newexpr != expr: expr = newexpr newexpr = expr.replace(lambda e: isinstance(e, Mul), cancel_kronecker_mul) return expr def besselsimp(expr): """ Simplify bessel-type functions. Explanation =========== This routine tries to simplify bessel-type functions. Currently it only works on the Bessel J and I functions, however. It works by looking at all such functions in turn, and eliminating factors of "I" and "-1" (actually their polar equivalents) in front of the argument. Then, functions of half-integer order are rewritten using strigonometric functions and functions of integer order (> 1) are rewritten using functions of low order. Finally, if the expression was changed, compute factorization of the result with factor(). >>> from sympy import besselj, besseli, besselsimp, polar_lift, I, S >>> from sympy.abc import z, nu >>> besselsimp(besselj(nu, z*polar_lift(-1))) exp(I*pi*nu)*besselj(nu, z) >>> besselsimp(besseli(nu, z*polar_lift(-I))) exp(-I*pi*nu/2)*besselj(nu, z) >>> besselsimp(besseli(S(-1)/2, z)) sqrt(2)*cosh(z)/(sqrt(pi)*sqrt(z)) >>> besselsimp(z*besseli(0, z) + z*(besseli(2, z))/2 + besseli(1, z)) 3*z*besseli(0, z)/2 """ # TODO # - better algorithm? # - simplify (cos(pi*b)*besselj(b,z) - besselj(-b,z))/sin(pi*b) ... # - use contiguity relations? def replacer(fro, to, factors): factors = set(factors) def repl(nu, z): if factors.intersection(Mul.make_args(z)): return to(nu, z) return fro(nu, z) return repl def torewrite(fro, to): def tofunc(nu, z): return fro(nu, z).rewrite(to) return tofunc def tominus(fro): def tofunc(nu, z): return exp(I*pi*nu)*fro(nu, exp_polar(-I*pi)*z) return tofunc orig_expr = expr ifactors = [I, exp_polar(I*pi/2), exp_polar(-I*pi/2)] expr = expr.replace( besselj, replacer(besselj, torewrite(besselj, besseli), ifactors)) expr = expr.replace( besseli, replacer(besseli, torewrite(besseli, besselj), ifactors)) minusfactors = [-1, exp_polar(I*pi)] expr = expr.replace( besselj, replacer(besselj, tominus(besselj), minusfactors)) expr = expr.replace( besseli, replacer(besseli, tominus(besseli), minusfactors)) z0 = Dummy('z') def expander(fro): def repl(nu, z): if (nu % 1) == S.Half: return simplify(trigsimp(unpolarify( fro(nu, z0).rewrite(besselj).rewrite(jn).expand( func=True)).subs(z0, z))) elif nu.is_Integer and nu > 1: return fro(nu, z).expand(func=True) return fro(nu, z) return repl expr = expr.replace(besselj, expander(besselj)) expr = expr.replace(bessely, expander(bessely)) expr = expr.replace(besseli, expander(besseli)) expr = expr.replace(besselk, expander(besselk)) def _bessel_simp_recursion(expr): def _use_recursion(bessel, expr): while True: bessels = expr.find(lambda x: isinstance(x, bessel)) try: for ba in sorted(bessels, key=lambda x: re(x.args[0])): a, x = ba.args bap1 = bessel(a+1, x) bap2 = bessel(a+2, x) if expr.has(bap1) and expr.has(bap2): expr = expr.subs(ba, 2*(a+1)/x*bap1 - bap2) break else: return expr except (ValueError, TypeError): return expr if expr.has(besselj): expr = _use_recursion(besselj, expr) if expr.has(bessely): expr = _use_recursion(bessely, expr) return expr expr = _bessel_simp_recursion(expr) if expr != orig_expr: expr = expr.factor() return expr def nthroot(expr, n, max_len=4, prec=15): """ Compute a real nth-root of a sum of surds. Parameters ========== expr : sum of surds n : integer max_len : maximum number of surds passed as constants to ``nsimplify`` Algorithm ========= First ``nsimplify`` is used to get a candidate root; if it is not a root the minimal polynomial is computed; the answer is one of its roots. Examples ======== >>> from sympy.simplify.simplify import nthroot >>> from sympy import sqrt >>> nthroot(90 + 34*sqrt(7), 3) sqrt(7) + 3 """ expr = sympify(expr) n = sympify(n) p = expr**Rational(1, n) if not n.is_integer: return p if not _is_sum_surds(expr): return p surds = [] coeff_muls = [x.as_coeff_Mul() for x in expr.args] for x, y in coeff_muls: if not x.is_rational: return p if y is S.One: continue if not (y.is_Pow and y.exp == S.Half and y.base.is_integer): return p surds.append(y) surds.sort() surds = surds[:max_len] if expr < 0 and n % 2 == 1: p = (-expr)**Rational(1, n) a = nsimplify(p, constants=surds) res = a if _mexpand(a**n) == _mexpand(-expr) else p return -res a = nsimplify(p, constants=surds) if _mexpand(a) is not _mexpand(p) and _mexpand(a**n) == _mexpand(expr): return _mexpand(a) expr = _nthroot_solve(expr, n, prec) if expr is None: return p return expr def nsimplify(expr, constants=(), tolerance=None, full=False, rational=None, rational_conversion='base10'): """ Find a simple representation for a number or, if there are free symbols or if ``rational=True``, then replace Floats with their Rational equivalents. If no change is made and rational is not False then Floats will at least be converted to Rationals. Explanation =========== For numerical expressions, a simple formula that numerically matches the given numerical expression is sought (and the input should be possible to evalf to a precision of at least 30 digits). Optionally, a list of (rationally independent) constants to include in the formula may be given. A lower tolerance may be set to find less exact matches. If no tolerance is given then the least precise value will set the tolerance (e.g. Floats default to 15 digits of precision, so would be tolerance=10**-15). With ``full=True``, a more extensive search is performed (this is useful to find simpler numbers when the tolerance is set low). When converting to rational, if rational_conversion='base10' (the default), then convert floats to rationals using their base-10 (string) representation. When rational_conversion='exact' it uses the exact, base-2 representation. Examples ======== >>> from sympy import nsimplify, sqrt, GoldenRatio, exp, I, pi >>> nsimplify(4/(1+sqrt(5)), [GoldenRatio]) -2 + 2*GoldenRatio >>> nsimplify((1/(exp(3*pi*I/5)+1))) 1/2 - I*sqrt(sqrt(5)/10 + 1/4) >>> nsimplify(I**I, [pi]) exp(-pi/2) >>> nsimplify(pi, tolerance=0.01) 22/7 >>> nsimplify(0.333333333333333, rational=True, rational_conversion='exact') 6004799503160655/18014398509481984 >>> nsimplify(0.333333333333333, rational=True) 1/3 See Also ======== sympy.core.function.nfloat """ try: return sympify(as_int(expr)) except (TypeError, ValueError): pass expr = sympify(expr).xreplace({ Float('inf'): S.Infinity, Float('-inf'): S.NegativeInfinity, }) if expr is S.Infinity or expr is S.NegativeInfinity: return expr if rational or expr.free_symbols: return _real_to_rational(expr, tolerance, rational_conversion) # SymPy's default tolerance for Rationals is 15; other numbers may have # lower tolerances set, so use them to pick the largest tolerance if None # was given if tolerance is None: tolerance = 10**-min([15] + [mpmath.libmp.libmpf.prec_to_dps(n._prec) for n in expr.atoms(Float)]) # XXX should prec be set independent of tolerance or should it be computed # from tolerance? prec = 30 bprec = int(prec*3.33) constants_dict = {} for constant in constants: constant = sympify(constant) v = constant.evalf(prec) if not v.is_Float: raise ValueError("constants must be real-valued") constants_dict[str(constant)] = v._to_mpmath(bprec) exprval = expr.evalf(prec, chop=True) re, im = exprval.as_real_imag() # safety check to make sure that this evaluated to a number if not (re.is_Number and im.is_Number): return expr def nsimplify_real(x): orig = mpmath.mp.dps xv = x._to_mpmath(bprec) try: # We'll be happy with low precision if a simple fraction if not (tolerance or full): mpmath.mp.dps = 15 rat = mpmath.pslq([xv, 1]) if rat is not None: return Rational(-int(rat[1]), int(rat[0])) mpmath.mp.dps = prec newexpr = mpmath.identify(xv, constants=constants_dict, tol=tolerance, full=full) if not newexpr: raise ValueError if full: newexpr = newexpr[0] expr = sympify(newexpr) if x and not expr: # don't let x become 0 raise ValueError if expr.is_finite is False and xv not in [mpmath.inf, mpmath.ninf]: raise ValueError return expr finally: # even though there are returns above, this is executed # before leaving mpmath.mp.dps = orig try: if re: re = nsimplify_real(re) if im: im = nsimplify_real(im) except ValueError: if rational is None: return _real_to_rational(expr, rational_conversion=rational_conversion) return expr rv = re + im*S.ImaginaryUnit # if there was a change or rational is explicitly not wanted # return the value, else return the Rational representation if rv != expr or rational is False: return rv return _real_to_rational(expr, rational_conversion=rational_conversion) def _real_to_rational(expr, tolerance=None, rational_conversion='base10'): """ Replace all reals in expr with rationals. Examples ======== >>> from sympy.simplify.simplify import _real_to_rational >>> from sympy.abc import x >>> _real_to_rational(.76 + .1*x**.5) sqrt(x)/10 + 19/25 If rational_conversion='base10', this uses the base-10 string. If rational_conversion='exact', the exact, base-2 representation is used. >>> _real_to_rational(0.333333333333333, rational_conversion='exact') 6004799503160655/18014398509481984 >>> _real_to_rational(0.333333333333333) 1/3 """ expr = _sympify(expr) inf = Float('inf') p = expr reps = {} reduce_num = None if tolerance is not None and tolerance < 1: reduce_num = ceiling(1/tolerance) for fl in p.atoms(Float): key = fl if reduce_num is not None: r = Rational(fl).limit_denominator(reduce_num) elif (tolerance is not None and tolerance >= 1 and fl.is_Integer is False): r = Rational(tolerance*round(fl/tolerance) ).limit_denominator(int(tolerance)) else: if rational_conversion == 'exact': r = Rational(fl) reps[key] = r continue elif rational_conversion != 'base10': raise ValueError("rational_conversion must be 'base10' or 'exact'") r = nsimplify(fl, rational=False) # e.g. log(3).n() -> log(3) instead of a Rational if fl and not r: r = Rational(fl) elif not r.is_Rational: if fl in (inf, -inf): r = S.ComplexInfinity elif fl < 0: fl = -fl d = Pow(10, int(mpmath.log(fl)/mpmath.log(10))) r = -Rational(str(fl/d))*d elif fl > 0: d = Pow(10, int(mpmath.log(fl)/mpmath.log(10))) r = Rational(str(fl/d))*d else: r = S.Zero reps[key] = r return p.subs(reps, simultaneous=True) def clear_coefficients(expr, rhs=S.Zero): """Return `p, r` where `p` is the expression obtained when Rational additive and multiplicative coefficients of `expr` have been stripped away in a naive fashion (i.e. without simplification). The operations needed to remove the coefficients will be applied to `rhs` and returned as `r`. Examples ======== >>> from sympy.simplify.simplify import clear_coefficients >>> from sympy.abc import x, y >>> from sympy import Dummy >>> expr = 4*y*(6*x + 3) >>> clear_coefficients(expr - 2) (y*(2*x + 1), 1/6) When solving 2 or more expressions like `expr = a`, `expr = b`, etc..., it is advantageous to provide a Dummy symbol for `rhs` and simply replace it with `a`, `b`, etc... in `r`. >>> rhs = Dummy('rhs') >>> clear_coefficients(expr, rhs) (y*(2*x + 1), _rhs/12) >>> _[1].subs(rhs, 2) 1/6 """ was = None free = expr.free_symbols if expr.is_Rational: return (S.Zero, rhs - expr) while expr and was != expr: was = expr m, expr = ( expr.as_content_primitive() if free else factor_terms(expr).as_coeff_Mul(rational=True)) rhs /= m c, expr = expr.as_coeff_Add(rational=True) rhs -= c expr = signsimp(expr, evaluate = False) if expr.could_extract_minus_sign(): expr = -expr rhs = -rhs return expr, rhs def nc_simplify(expr, deep=True): ''' Simplify a non-commutative expression composed of multiplication and raising to a power by grouping repeated subterms into one power. Priority is given to simplifications that give the fewest number of arguments in the end (for example, in a*b*a*b*c*a*b*c simplifying to (a*b)**2*c*a*b*c gives 5 arguments while a*b*(a*b*c)**2 has 3). If ``expr`` is a sum of such terms, the sum of the simplified terms is returned. Keyword argument ``deep`` controls whether or not subexpressions nested deeper inside the main expression are simplified. See examples below. Setting `deep` to `False` can save time on nested expressions that do not need simplifying on all levels. Examples ======== >>> from sympy import symbols >>> from sympy.simplify.simplify import nc_simplify >>> a, b, c = symbols("a b c", commutative=False) >>> nc_simplify(a*b*a*b*c*a*b*c) a*b*(a*b*c)**2 >>> expr = a**2*b*a**4*b*a**4 >>> nc_simplify(expr) a**2*(b*a**4)**2 >>> nc_simplify(a*b*a*b*c**2*(a*b)**2*c**2) ((a*b)**2*c**2)**2 >>> nc_simplify(a*b*a*b + 2*a*c*a**2*c*a**2*c*a) (a*b)**2 + 2*(a*c*a)**3 >>> nc_simplify(b**-1*a**-1*(a*b)**2) a*b >>> nc_simplify(a**-1*b**-1*c*a) (b*a)**(-1)*c*a >>> expr = (a*b*a*b)**2*a*c*a*c >>> nc_simplify(expr) (a*b)**4*(a*c)**2 >>> nc_simplify(expr, deep=False) (a*b*a*b)**2*(a*c)**2 ''' from sympy.matrices.expressions import (MatrixExpr, MatAdd, MatMul, MatPow, MatrixSymbol) if isinstance(expr, MatrixExpr): expr = expr.doit(inv_expand=False) _Add, _Mul, _Pow, _Symbol = MatAdd, MatMul, MatPow, MatrixSymbol else: _Add, _Mul, _Pow, _Symbol = Add, Mul, Pow, Symbol # =========== Auxiliary functions ======================== def _overlaps(args): # Calculate a list of lists m such that m[i][j] contains the lengths # of all possible overlaps between args[:i+1] and args[i+1+j:]. # An overlap is a suffix of the prefix that matches a prefix # of the suffix. # For example, let expr=c*a*b*a*b*a*b*a*b. Then m[3][0] contains # the lengths of overlaps of c*a*b*a*b with a*b*a*b. The overlaps # are a*b*a*b, a*b and the empty word so that m[3][0]=[4,2,0]. # All overlaps rather than only the longest one are recorded # because this information helps calculate other overlap lengths. m = [[([1, 0] if a == args[0] else [0]) for a in args[1:]]] for i in range(1, len(args)): overlaps = [] j = 0 for j in range(len(args) - i - 1): overlap = [] for v in m[i-1][j+1]: if j + i + 1 + v < len(args) and args[i] == args[j+i+1+v]: overlap.append(v + 1) overlap += [0] overlaps.append(overlap) m.append(overlaps) return m def _reduce_inverses(_args): # replace consecutive negative powers by an inverse # of a product of positive powers, e.g. a**-1*b**-1*c # will simplify to (a*b)**-1*c; # return that new args list and the number of negative # powers in it (inv_tot) inv_tot = 0 # total number of inverses inverses = [] args = [] for arg in _args: if isinstance(arg, _Pow) and arg.args[1] < 0: inverses = [arg**-1] + inverses inv_tot += 1 else: if len(inverses) == 1: args.append(inverses[0]**-1) elif len(inverses) > 1: args.append(_Pow(_Mul(*inverses), -1)) inv_tot -= len(inverses) - 1 inverses = [] args.append(arg) if inverses: args.append(_Pow(_Mul(*inverses), -1)) inv_tot -= len(inverses) - 1 return inv_tot, tuple(args) def get_score(s): # compute the number of arguments of s # (including in nested expressions) overall # but ignore exponents if isinstance(s, _Pow): return get_score(s.args[0]) elif isinstance(s, (_Add, _Mul)): return sum([get_score(a) for a in s.args]) return 1 def compare(s, alt_s): # compare two possible simplifications and return a # "better" one if s != alt_s and get_score(alt_s) < get_score(s): return alt_s return s # ======================================================== if not isinstance(expr, (_Add, _Mul, _Pow)) or expr.is_commutative: return expr args = expr.args[:] if isinstance(expr, _Pow): if deep: return _Pow(nc_simplify(args[0]), args[1]).doit() else: return expr elif isinstance(expr, _Add): return _Add(*[nc_simplify(a, deep=deep) for a in args]).doit() else: # get the non-commutative part c_args, args = expr.args_cnc() com_coeff = Mul(*c_args) if com_coeff != 1: return com_coeff*nc_simplify(expr/com_coeff, deep=deep) inv_tot, args = _reduce_inverses(args) # if most arguments are negative, work with the inverse # of the expression, e.g. a**-1*b*a**-1*c**-1 will become # (c*a*b**-1*a)**-1 at the end so can work with c*a*b**-1*a invert = False if inv_tot > len(args)/2: invert = True args = [a**-1 for a in args[::-1]] if deep: args = tuple(nc_simplify(a) for a in args) m = _overlaps(args) # simps will be {subterm: end} where `end` is the ending # index of a sequence of repetitions of subterm; # this is for not wasting time with subterms that are part # of longer, already considered sequences simps = {} post = 1 pre = 1 # the simplification coefficient is the number of # arguments by which contracting a given sequence # would reduce the word; e.g. in a*b*a*b*c*a*b*c, # contracting a*b*a*b to (a*b)**2 removes 3 arguments # while a*b*c*a*b*c to (a*b*c)**2 removes 6. It's # better to contract the latter so simplification # with a maximum simplification coefficient will be chosen max_simp_coeff = 0 simp = None # information about future simplification for i in range(1, len(args)): simp_coeff = 0 l = 0 # length of a subterm p = 0 # the power of a subterm if i < len(args) - 1: rep = m[i][0] start = i # starting index of the repeated sequence end = i+1 # ending index of the repeated sequence if i == len(args)-1 or rep == [0]: # no subterm is repeated at this stage, at least as # far as the arguments are concerned - there may be # a repetition if powers are taken into account if (isinstance(args[i], _Pow) and not isinstance(args[i].args[0], _Symbol)): subterm = args[i].args[0].args l = len(subterm) if args[i-l:i] == subterm: # e.g. a*b in a*b*(a*b)**2 is not repeated # in args (= [a, b, (a*b)**2]) but it # can be matched here p += 1 start -= l if args[i+1:i+1+l] == subterm: # e.g. a*b in (a*b)**2*a*b p += 1 end += l if p: p += args[i].args[1] else: continue else: l = rep[0] # length of the longest repeated subterm at this point start -= l - 1 subterm = args[start:end] p = 2 end += l if subterm in simps and simps[subterm] >= start: # the subterm is part of a sequence that # has already been considered continue # count how many times it's repeated while end < len(args): if l in m[end-1][0]: p += 1 end += l elif isinstance(args[end], _Pow) and args[end].args[0].args == subterm: # for cases like a*b*a*b*(a*b)**2*a*b p += args[end].args[1] end += 1 else: break # see if another match can be made, e.g. # for b*a**2 in b*a**2*b*a**3 or a*b in # a**2*b*a*b pre_exp = 0 pre_arg = 1 if start - l >= 0 and args[start-l+1:start] == subterm[1:]: if isinstance(subterm[0], _Pow): pre_arg = subterm[0].args[0] exp = subterm[0].args[1] else: pre_arg = subterm[0] exp = 1 if isinstance(args[start-l], _Pow) and args[start-l].args[0] == pre_arg: pre_exp = args[start-l].args[1] - exp start -= l p += 1 elif args[start-l] == pre_arg: pre_exp = 1 - exp start -= l p += 1 post_exp = 0 post_arg = 1 if end + l - 1 < len(args) and args[end:end+l-1] == subterm[:-1]: if isinstance(subterm[-1], _Pow): post_arg = subterm[-1].args[0] exp = subterm[-1].args[1] else: post_arg = subterm[-1] exp = 1 if isinstance(args[end+l-1], _Pow) and args[end+l-1].args[0] == post_arg: post_exp = args[end+l-1].args[1] - exp end += l p += 1 elif args[end+l-1] == post_arg: post_exp = 1 - exp end += l p += 1 # Consider a*b*a**2*b*a**2*b*a: # b*a**2 is explicitly repeated, but note # that in this case a*b*a is also repeated # so there are two possible simplifications: # a*(b*a**2)**3*a**-1 or (a*b*a)**3 # The latter is obviously simpler. # But in a*b*a**2*b**2*a**2 the simplifications are # a*(b*a**2)**2 and (a*b*a)**3*a in which case # it's better to stick with the shorter subterm if post_exp and exp % 2 == 0 and start > 0: exp = exp/2 _pre_exp = 1 _post_exp = 1 if isinstance(args[start-1], _Pow) and args[start-1].args[0] == post_arg: _post_exp = post_exp + exp _pre_exp = args[start-1].args[1] - exp elif args[start-1] == post_arg: _post_exp = post_exp + exp _pre_exp = 1 - exp if _pre_exp == 0 or _post_exp == 0: if not pre_exp: start -= 1 post_exp = _post_exp pre_exp = _pre_exp pre_arg = post_arg subterm = (post_arg**exp,) + subterm[:-1] + (post_arg**exp,) simp_coeff += end-start if post_exp: simp_coeff -= 1 if pre_exp: simp_coeff -= 1 simps[subterm] = end if simp_coeff > max_simp_coeff: max_simp_coeff = simp_coeff simp = (start, _Mul(*subterm), p, end, l) pre = pre_arg**pre_exp post = post_arg**post_exp if simp: subterm = _Pow(nc_simplify(simp[1], deep=deep), simp[2]) pre = nc_simplify(_Mul(*args[:simp[0]])*pre, deep=deep) post = post*nc_simplify(_Mul(*args[simp[3]:]), deep=deep) simp = pre*subterm*post if pre != 1 or post != 1: # new simplifications may be possible but no need # to recurse over arguments simp = nc_simplify(simp, deep=False) else: simp = _Mul(*args) if invert: simp = _Pow(simp, -1) # see if factor_nc(expr) is simplified better if not isinstance(expr, MatrixExpr): f_expr = factor_nc(expr) if f_expr != expr: alt_simp = nc_simplify(f_expr, deep=deep) simp = compare(simp, alt_simp) else: simp = simp.doit(inv_expand=False) return simp def dotprodsimp(expr, withsimp=False): """Simplification for a sum of products targeted at the kind of blowup that occurs during summation of products. Intended to reduce expression blowup during matrix multiplication or other similar operations. Only works with algebraic expressions and does not recurse into non. Parameters ========== withsimp : bool, optional Specifies whether a flag should be returned along with the expression to indicate roughly whether simplification was successful. It is used in ``MatrixArithmetic._eval_pow_by_recursion`` to avoid attempting to simplify an expression repetitively which does not simplify. """ def count_ops_alg(expr): """Optimized count algebraic operations with no recursion into non-algebraic args that ``core.function.count_ops`` does. Also returns whether rational functions may be present according to negative exponents of powers or non-number fractions. Returns ======= ops, ratfunc : int, bool ``ops`` is the number of algebraic operations starting at the top level expression (not recursing into non-alg children). ``ratfunc`` specifies whether the expression MAY contain rational functions which ``cancel`` MIGHT optimize. """ ops = 0 args = [expr] ratfunc = False while args: a = args.pop() if not isinstance(a, Basic): continue if a.is_Rational: if a is not S.One: # -1/3 = NEG + DIV ops += bool (a.p < 0) + bool (a.q != 1) elif a.is_Mul: if a.could_extract_minus_sign(): ops += 1 if a.args[0] is S.NegativeOne: a = a.as_two_terms()[1] else: a = -a n, d = fraction(a) if n.is_Integer: ops += 1 + bool (n < 0) args.append(d) # won't be -Mul but could be Add elif d is not S.One: if not d.is_Integer: args.append(d) ratfunc=True ops += 1 args.append(n) # could be -Mul else: ops += len(a.args) - 1 args.extend(a.args) elif a.is_Add: laargs = len(a.args) negs = 0 for ai in a.args: if ai.could_extract_minus_sign(): negs += 1 ai = -ai args.append(ai) ops += laargs - (negs != laargs) # -x - y = NEG + SUB elif a.is_Pow: ops += 1 args.append(a.base) if not ratfunc: ratfunc = a.exp.is_negative is not False return ops, ratfunc def nonalg_subs_dummies(expr, dummies): """Substitute dummy variables for non-algebraic expressions to avoid evaluation of non-algebraic terms that ``polys.polytools.cancel`` does. """ if not expr.args: return expr if expr.is_Add or expr.is_Mul or expr.is_Pow: args = None for i, a in enumerate(expr.args): c = nonalg_subs_dummies(a, dummies) if c is a: continue if args is None: args = list(expr.args) args[i] = c if args is None: return expr return expr.func(*args) return dummies.setdefault(expr, Dummy()) simplified = False # doesn't really mean simplified, rather "can simplify again" if isinstance(expr, Basic) and (expr.is_Add or expr.is_Mul or expr.is_Pow): expr2 = expr.expand(deep=True, modulus=None, power_base=False, power_exp=False, mul=True, log=False, multinomial=True, basic=False) if expr2 != expr: expr = expr2 simplified = True exprops, ratfunc = count_ops_alg(expr) if exprops >= 6: # empirically tested cutoff for expensive simplification if ratfunc: dummies = {} expr2 = nonalg_subs_dummies(expr, dummies) if expr2 is expr or count_ops_alg(expr2)[0] >= 6: # check again after substitution expr3 = cancel(expr2) if expr3 != expr2: expr = expr3.subs([(d, e) for e, d in dummies.items()]) simplified = True # very special case: x/(x-1) - 1/(x-1) -> 1 elif (exprops == 5 and expr.is_Add and expr.args [0].is_Mul and expr.args [1].is_Mul and expr.args [0].args [-1].is_Pow and expr.args [1].args [-1].is_Pow and expr.args [0].args [-1].exp is S.NegativeOne and expr.args [1].args [-1].exp is S.NegativeOne): expr2 = together (expr) expr2ops = count_ops_alg(expr2)[0] if expr2ops < exprops: expr = expr2 simplified = True else: simplified = True return (expr, simplified) if withsimp else expr bottom_up = deprecated( useinstead="sympy.core.traversal.bottom_up", deprecated_since_version="1.10", issue=22288)(_bottom_up) walk = deprecated( useinstead="sympy.core.traversal.walk", deprecated_since_version="1.10", issue=22288)(_walk)
54bcc2af4960b25afdf622464e8832e4da3486d31876afbab55e219e96df1620
from collections import defaultdict from functools import reduce from sympy.core.function import expand_log, count_ops, _coeff_isneg from sympy.core import sympify, Basic, Dummy, S, Add, Mul, Pow, expand_mul, factor_terms from sympy.core.sorting import ordered, default_sort_key from sympy.core.numbers import Integer, Rational from sympy.core.mul import prod, _keep_coeff from sympy.core.rules import Transform from sympy.functions import exp_polar, exp, log, root, polarify, unpolarify from sympy.polys import lcm, gcd from sympy.ntheory.factor_ import multiplicity def powsimp(expr, deep=False, combine='all', force=False, measure=count_ops): """ reduces expression by combining powers with similar bases and exponents. Explanation =========== If ``deep`` is ``True`` then powsimp() will also simplify arguments of functions. By default ``deep`` is set to ``False``. If ``force`` is ``True`` then bases will be combined without checking for assumptions, e.g. sqrt(x)*sqrt(y) -> sqrt(x*y) which is not true if x and y are both negative. You can make powsimp() only combine bases or only combine exponents by changing combine='base' or combine='exp'. By default, combine='all', which does both. combine='base' will only combine:: a a a 2x x x * y => (x*y) as well as things like 2 => 4 and combine='exp' will only combine :: a b (a + b) x * x => x combine='exp' will strictly only combine exponents in the way that used to be automatic. Also use deep=True if you need the old behavior. When combine='all', 'exp' is evaluated first. Consider the first example below for when there could be an ambiguity relating to this. This is done so things like the second example can be completely combined. If you want 'base' combined first, do something like powsimp(powsimp(expr, combine='base'), combine='exp'). Examples ======== >>> from sympy import powsimp, exp, log, symbols >>> from sympy.abc import x, y, z, n >>> powsimp(x**y*x**z*y**z, combine='all') x**(y + z)*y**z >>> powsimp(x**y*x**z*y**z, combine='exp') x**(y + z)*y**z >>> powsimp(x**y*x**z*y**z, combine='base', force=True) x**y*(x*y)**z >>> powsimp(x**z*x**y*n**z*n**y, combine='all', force=True) (n*x)**(y + z) >>> powsimp(x**z*x**y*n**z*n**y, combine='exp') n**(y + z)*x**(y + z) >>> powsimp(x**z*x**y*n**z*n**y, combine='base', force=True) (n*x)**y*(n*x)**z >>> x, y = symbols('x y', positive=True) >>> powsimp(log(exp(x)*exp(y))) log(exp(x)*exp(y)) >>> powsimp(log(exp(x)*exp(y)), deep=True) x + y Radicals with Mul bases will be combined if combine='exp' >>> from sympy import sqrt >>> x, y = symbols('x y') Two radicals are automatically joined through Mul: >>> a=sqrt(x*sqrt(y)) >>> a*a**3 == a**4 True But if an integer power of that radical has been autoexpanded then Mul does not join the resulting factors: >>> a**4 # auto expands to a Mul, no longer a Pow x**2*y >>> _*a # so Mul doesn't combine them x**2*y*sqrt(x*sqrt(y)) >>> powsimp(_) # but powsimp will (x*sqrt(y))**(5/2) >>> powsimp(x*y*a) # but won't when doing so would violate assumptions x*y*sqrt(x*sqrt(y)) """ from sympy.matrices.expressions.matexpr import MatrixSymbol def recurse(arg, **kwargs): _deep = kwargs.get('deep', deep) _combine = kwargs.get('combine', combine) _force = kwargs.get('force', force) _measure = kwargs.get('measure', measure) return powsimp(arg, _deep, _combine, _force, _measure) expr = sympify(expr) if (not isinstance(expr, Basic) or isinstance(expr, MatrixSymbol) or ( expr.is_Atom or expr in (exp_polar(0), exp_polar(1)))): return expr if deep or expr.is_Add or expr.is_Mul and _y not in expr.args: expr = expr.func(*[recurse(w) for w in expr.args]) if expr.is_Pow: return recurse(expr*_y, deep=False)/_y if not expr.is_Mul: return expr # handle the Mul if combine in ('exp', 'all'): # Collect base/exp data, while maintaining order in the # non-commutative parts of the product c_powers = defaultdict(list) nc_part = [] newexpr = [] coeff = S.One for term in expr.args: if term.is_Rational: coeff *= term continue if term.is_Pow: term = _denest_pow(term) if term.is_commutative: b, e = term.as_base_exp() if deep: b, e = [recurse(i) for i in [b, e]] if b.is_Pow or isinstance(b, exp): # don't let smthg like sqrt(x**a) split into x**a, 1/2 # or else it will be joined as x**(a/2) later b, e = b**e, S.One c_powers[b].append(e) else: # This is the logic that combines exponents for equal, # but non-commutative bases: A**x*A**y == A**(x+y). if nc_part: b1, e1 = nc_part[-1].as_base_exp() b2, e2 = term.as_base_exp() if (b1 == b2 and e1.is_commutative and e2.is_commutative): nc_part[-1] = Pow(b1, Add(e1, e2)) continue nc_part.append(term) # add up exponents of common bases for b, e in ordered(iter(c_powers.items())): # allow 2**x/4 -> 2**(x - 2); don't do this when b and e are # Numbers since autoevaluation will undo it, e.g. # 2**(1/3)/4 -> 2**(1/3 - 2) -> 2**(1/3)/4 if (b and b.is_Rational and not all(ei.is_Number for ei in e) and \ coeff is not S.One and b not in (S.One, S.NegativeOne)): m = multiplicity(abs(b), abs(coeff)) if m: e.append(m) coeff /= b**m c_powers[b] = Add(*e) if coeff is not S.One: if coeff in c_powers: c_powers[coeff] += S.One else: c_powers[coeff] = S.One # convert to plain dictionary c_powers = dict(c_powers) # check for base and inverted base pairs be = list(c_powers.items()) skip = set() # skip if we already saw them for b, e in be: if b in skip: continue bpos = b.is_positive or b.is_polar if bpos: binv = 1/b if b != binv and binv in c_powers: if b.as_numer_denom()[0] is S.One: c_powers.pop(b) c_powers[binv] -= e else: skip.add(binv) e = c_powers.pop(binv) c_powers[b] -= e # check for base and negated base pairs be = list(c_powers.items()) _n = S.NegativeOne for b, e in be: if (b.is_Symbol or b.is_Add) and -b in c_powers and b in c_powers: if (b.is_positive is not None or e.is_integer): if e.is_integer or b.is_negative: c_powers[-b] += c_powers.pop(b) else: # (-b).is_positive so use its e e = c_powers.pop(-b) c_powers[b] += e if _n in c_powers: c_powers[_n] += e else: c_powers[_n] = e # filter c_powers and convert to a list c_powers = [(b, e) for b, e in c_powers.items() if e] # ============================================================== # check for Mul bases of Rational powers that can be combined with # separated bases, e.g. x*sqrt(x*y)*sqrt(x*sqrt(x*y)) -> # (x*sqrt(x*y))**(3/2) # ---------------- helper functions def ratq(x): '''Return Rational part of x's exponent as it appears in the bkey. ''' return bkey(x)[0][1] def bkey(b, e=None): '''Return (b**s, c.q), c.p where e -> c*s. If e is not given then it will be taken by using as_base_exp() on the input b. e.g. x**3/2 -> (x, 2), 3 x**y -> (x**y, 1), 1 x**(2*y/3) -> (x**y, 3), 2 exp(x/2) -> (exp(a), 2), 1 ''' if e is not None: # coming from c_powers or from below if e.is_Integer: return (b, S.One), e elif e.is_Rational: return (b, Integer(e.q)), Integer(e.p) else: c, m = e.as_coeff_Mul(rational=True) if c is not S.One: if m.is_integer: return (b, Integer(c.q)), m*Integer(c.p) return (b**m, Integer(c.q)), Integer(c.p) else: return (b**e, S.One), S.One else: return bkey(*b.as_base_exp()) def update(b): '''Decide what to do with base, b. If its exponent is now an integer multiple of the Rational denominator, then remove it and put the factors of its base in the common_b dictionary or update the existing bases if necessary. If it has been zeroed out, simply remove the base. ''' newe, r = divmod(common_b[b], b[1]) if not r: common_b.pop(b) if newe: for m in Mul.make_args(b[0]**newe): b, e = bkey(m) if b not in common_b: common_b[b] = 0 common_b[b] += e if b[1] != 1: bases.append(b) # ---------------- end of helper functions # assemble a dictionary of the factors having a Rational power common_b = {} done = [] bases = [] for b, e in c_powers: b, e = bkey(b, e) if b in common_b: common_b[b] = common_b[b] + e else: common_b[b] = e if b[1] != 1 and b[0].is_Mul: bases.append(b) bases.sort(key=default_sort_key) # this makes tie-breaking canonical bases.sort(key=measure, reverse=True) # handle longest first for base in bases: if base not in common_b: # it may have been removed already continue b, exponent = base last = False # True when no factor of base is a radical qlcm = 1 # the lcm of the radical denominators while True: bstart = b qstart = qlcm bb = [] # list of factors ee = [] # (factor's expo. and it's current value in common_b) for bi in Mul.make_args(b): bib, bie = bkey(bi) if bib not in common_b or common_b[bib] < bie: ee = bb = [] # failed break ee.append([bie, common_b[bib]]) bb.append(bib) if ee: # find the number of integral extractions possible # e.g. [(1, 2), (2, 2)] -> min(2/1, 2/2) -> 1 min1 = ee[0][1]//ee[0][0] for i in range(1, len(ee)): rat = ee[i][1]//ee[i][0] if rat < 1: break min1 = min(min1, rat) else: # update base factor counts # e.g. if ee = [(2, 5), (3, 6)] then min1 = 2 # and the new base counts will be 5-2*2 and 6-2*3 for i in range(len(bb)): common_b[bb[i]] -= min1*ee[i][0] update(bb[i]) # update the count of the base # e.g. x**2*y*sqrt(x*sqrt(y)) the count of x*sqrt(y) # will increase by 4 to give bkey (x*sqrt(y), 2, 5) common_b[base] += min1*qstart*exponent if (last # no more radicals in base or len(common_b) == 1 # nothing left to join with or all(k[1] == 1 for k in common_b) # no rad's in common_b ): break # see what we can exponentiate base by to remove any radicals # so we know what to search for # e.g. if base were x**(1/2)*y**(1/3) then we should # exponentiate by 6 and look for powers of x and y in the ratio # of 2 to 3 qlcm = lcm([ratq(bi) for bi in Mul.make_args(bstart)]) if qlcm == 1: break # we are done b = bstart**qlcm qlcm *= qstart if all(ratq(bi) == 1 for bi in Mul.make_args(b)): last = True # we are going to be done after this next pass # this base no longer can find anything to join with and # since it was longer than any other we are done with it b, q = base done.append((b, common_b.pop(base)*Rational(1, q))) # update c_powers and get ready to continue with powsimp c_powers = done # there may be terms still in common_b that were bases that were # identified as needing processing, so remove those, too for (b, q), e in common_b.items(): if (b.is_Pow or isinstance(b, exp)) and \ q is not S.One and not b.exp.is_Rational: b, be = b.as_base_exp() b = b**(be/q) else: b = root(b, q) c_powers.append((b, e)) check = len(c_powers) c_powers = dict(c_powers) assert len(c_powers) == check # there should have been no duplicates # ============================================================== # rebuild the expression newexpr = expr.func(*(newexpr + [Pow(b, e) for b, e in c_powers.items()])) if combine == 'exp': return expr.func(newexpr, expr.func(*nc_part)) else: return recurse(expr.func(*nc_part), combine='base') * \ recurse(newexpr, combine='base') elif combine == 'base': # Build c_powers and nc_part. These must both be lists not # dicts because exp's are not combined. c_powers = [] nc_part = [] for term in expr.args: if term.is_commutative: c_powers.append(list(term.as_base_exp())) else: nc_part.append(term) # Pull out numerical coefficients from exponent if assumptions allow # e.g., 2**(2*x) => 4**x for i in range(len(c_powers)): b, e = c_powers[i] if not (all(x.is_nonnegative for x in b.as_numer_denom()) or e.is_integer or force or b.is_polar): continue exp_c, exp_t = e.as_coeff_Mul(rational=True) if exp_c is not S.One and exp_t is not S.One: c_powers[i] = [Pow(b, exp_c), exp_t] # Combine bases whenever they have the same exponent and # assumptions allow # first gather the potential bases under the common exponent c_exp = defaultdict(list) for b, e in c_powers: if deep: e = recurse(e) if e.is_Add and (b.is_positive or e.is_integer): e = factor_terms(e) if _coeff_isneg(e): e = -e b = 1/b c_exp[e].append(b) del c_powers # Merge back in the results of the above to form a new product c_powers = defaultdict(list) for e in c_exp: bases = c_exp[e] # calculate the new base for e if len(bases) == 1: new_base = bases[0] elif e.is_integer or force: new_base = expr.func(*bases) else: # see which ones can be joined unk = [] nonneg = [] neg = [] for bi in bases: if bi.is_negative: neg.append(bi) elif bi.is_nonnegative: nonneg.append(bi) elif bi.is_polar: nonneg.append( bi) # polar can be treated like non-negative else: unk.append(bi) if len(unk) == 1 and not neg or len(neg) == 1 and not unk: # a single neg or a single unk can join the rest nonneg.extend(unk + neg) unk = neg = [] elif neg: # their negative signs cancel in groups of 2*q if we know # that e = p/q else we have to treat them as unknown israt = False if e.is_Rational: israt = True else: p, d = e.as_numer_denom() if p.is_integer and d.is_integer: israt = True if israt: neg = [-w for w in neg] unk.extend([S.NegativeOne]*len(neg)) else: unk.extend(neg) neg = [] del israt # these shouldn't be joined for b in unk: c_powers[b].append(e) # here is a new joined base new_base = expr.func(*(nonneg + neg)) # if there are positive parts they will just get separated # again unless some change is made def _terms(e): # return the number of terms of this expression # when multiplied out -- assuming no joining of terms if e.is_Add: return sum([_terms(ai) for ai in e.args]) if e.is_Mul: return prod([_terms(mi) for mi in e.args]) return 1 xnew_base = expand_mul(new_base, deep=False) if len(Add.make_args(xnew_base)) < _terms(new_base): new_base = factor_terms(xnew_base) c_powers[new_base].append(e) # break out the powers from c_powers now c_part = [Pow(b, ei) for b, e in c_powers.items() for ei in e] # we're done return expr.func(*(c_part + nc_part)) else: raise ValueError("combine must be one of ('all', 'exp', 'base').") def powdenest(eq, force=False, polar=False): r""" Collect exponents on powers as assumptions allow. Explanation =========== Given ``(bb**be)**e``, this can be simplified as follows: * if ``bb`` is positive, or * ``e`` is an integer, or * ``|be| < 1`` then this simplifies to ``bb**(be*e)`` Given a product of powers raised to a power, ``(bb1**be1 * bb2**be2...)**e``, simplification can be done as follows: - if e is positive, the gcd of all bei can be joined with e; - all non-negative bb can be separated from those that are negative and their gcd can be joined with e; autosimplification already handles this separation. - integer factors from powers that have integers in the denominator of the exponent can be removed from any term and the gcd of such integers can be joined with e Setting ``force`` to ``True`` will make symbols that are not explicitly negative behave as though they are positive, resulting in more denesting. Setting ``polar`` to ``True`` will do simplifications on the Riemann surface of the logarithm, also resulting in more denestings. When there are sums of logs in exp() then a product of powers may be obtained e.g. ``exp(3*(log(a) + 2*log(b)))`` - > ``a**3*b**6``. Examples ======== >>> from sympy.abc import a, b, x, y, z >>> from sympy import Symbol, exp, log, sqrt, symbols, powdenest >>> powdenest((x**(2*a/3))**(3*x)) (x**(2*a/3))**(3*x) >>> powdenest(exp(3*x*log(2))) 2**(3*x) Assumptions may prevent expansion: >>> powdenest(sqrt(x**2)) sqrt(x**2) >>> p = symbols('p', positive=True) >>> powdenest(sqrt(p**2)) p No other expansion is done. >>> i, j = symbols('i,j', integer=True) >>> powdenest((x**x)**(i + j)) # -X-> (x**x)**i*(x**x)**j x**(x*(i + j)) But exp() will be denested by moving all non-log terms outside of the function; this may result in the collapsing of the exp to a power with a different base: >>> powdenest(exp(3*y*log(x))) x**(3*y) >>> powdenest(exp(y*(log(a) + log(b)))) (a*b)**y >>> powdenest(exp(3*(log(a) + log(b)))) a**3*b**3 If assumptions allow, symbols can also be moved to the outermost exponent: >>> i = Symbol('i', integer=True) >>> powdenest(((x**(2*i))**(3*y))**x) ((x**(2*i))**(3*y))**x >>> powdenest(((x**(2*i))**(3*y))**x, force=True) x**(6*i*x*y) >>> powdenest(((x**(2*a/3))**(3*y/i))**x) ((x**(2*a/3))**(3*y/i))**x >>> powdenest((x**(2*i)*y**(4*i))**z, force=True) (x*y**2)**(2*i*z) >>> n = Symbol('n', negative=True) >>> powdenest((x**i)**y, force=True) x**(i*y) >>> powdenest((n**i)**x, force=True) (n**i)**x """ from sympy.simplify.simplify import posify if force: def _denest(b, e): if not isinstance(b, (Pow, exp)): return b.is_positive, Pow(b, e, evaluate=False) return _denest(b.base, b.exp*e) reps = [] for p in eq.atoms(Pow, exp): if isinstance(p.base, (Pow, exp)): ok, dp = _denest(*p.args) if ok is not False: reps.append((p, dp)) if reps: eq = eq.subs(reps) eq, reps = posify(eq) return powdenest(eq, force=False, polar=polar).xreplace(reps) if polar: eq, rep = polarify(eq) return unpolarify(powdenest(unpolarify(eq, exponents_only=True)), rep) new = powsimp(sympify(eq)) return new.xreplace(Transform( _denest_pow, filter=lambda m: m.is_Pow or isinstance(m, exp))) _y = Dummy('y') def _denest_pow(eq): """ Denest powers. This is a helper function for powdenest that performs the actual transformation. """ from sympy.simplify.simplify import logcombine b, e = eq.as_base_exp() if b.is_Pow or isinstance(b, exp) and e != 1: new = b._eval_power(e) if new is not None: eq = new b, e = new.as_base_exp() # denest exp with log terms in exponent if b is S.Exp1 and e.is_Mul: logs = [] other = [] for ei in e.args: if any(isinstance(ai, log) for ai in Add.make_args(ei)): logs.append(ei) else: other.append(ei) logs = logcombine(Mul(*logs)) return Pow(exp(logs), Mul(*other)) _, be = b.as_base_exp() if be is S.One and not (b.is_Mul or b.is_Rational and b.q != 1 or b.is_positive): return eq # denest eq which is either pos**e or Pow**e or Mul**e or # Mul(b1**e1, b2**e2) # handle polar numbers specially polars, nonpolars = [], [] for bb in Mul.make_args(b): if bb.is_polar: polars.append(bb.as_base_exp()) else: nonpolars.append(bb) if len(polars) == 1 and not polars[0][0].is_Mul: return Pow(polars[0][0], polars[0][1]*e)*powdenest(Mul(*nonpolars)**e) elif polars: return Mul(*[powdenest(bb**(ee*e)) for (bb, ee) in polars]) \ *powdenest(Mul(*nonpolars)**e) if b.is_Integer: # use log to see if there is a power here logb = expand_log(log(b)) if logb.is_Mul: c, logb = logb.args e *= c base = logb.args[0] return Pow(base, e) # if b is not a Mul or any factor is an atom then there is nothing to do if not b.is_Mul or any(s.is_Atom for s in Mul.make_args(b)): return eq # let log handle the case of the base of the argument being a Mul, e.g. # sqrt(x**(2*i)*y**(6*i)) -> x**i*y**(3**i) if x and y are positive; we # will take the log, expand it, and then factor out the common powers that # now appear as coefficient. We do this manually since terms_gcd pulls out # fractions, terms_gcd(x+x*y/2) -> x*(y + 2)/2 and we don't want the 1/2; # gcd won't pull out numerators from a fraction: gcd(3*x, 9*x/2) -> x but # we want 3*x. Neither work with noncommutatives. def nc_gcd(aa, bb): a, b = [i.as_coeff_Mul() for i in [aa, bb]] c = gcd(a[0], b[0]).as_numer_denom()[0] g = Mul(*(a[1].args_cnc(cset=True)[0] & b[1].args_cnc(cset=True)[0])) return _keep_coeff(c, g) glogb = expand_log(log(b)) if glogb.is_Add: args = glogb.args g = reduce(nc_gcd, args) if g != 1: cg, rg = g.as_coeff_Mul() glogb = _keep_coeff(cg, rg*Add(*[a/g for a in args])) # now put the log back together again if isinstance(glogb, log) or not glogb.is_Mul: if glogb.args[0].is_Pow or isinstance(glogb.args[0], exp): glogb = _denest_pow(glogb.args[0]) if (abs(glogb.exp) < 1) == True: return Pow(glogb.base, glogb.exp*e) return eq # the log(b) was a Mul so join any adds with logcombine add = [] other = [] for a in glogb.args: if a.is_Add: add.append(a) else: other.append(a) return Pow(exp(logcombine(Mul(*add))), e*Mul(*other))
f23ef0a04c7549bb96580f6bcc2f08669c44d8ea1d42630969e3b4f133f776ab
from sympy.core import Function, S, Mul, Pow, Add from sympy.core.sorting import ordered, default_sort_key from sympy.core.function import expand_func from sympy.core.symbol import Dummy from sympy.functions import gamma, sqrt, sin from sympy.polys import factor, cancel from sympy.utilities.iterables import sift, uniq def gammasimp(expr): r""" Simplify expressions with gamma functions. Explanation =========== This function takes as input an expression containing gamma functions or functions that can be rewritten in terms of gamma functions and tries to minimize the number of those functions and reduce the size of their arguments. The algorithm works by rewriting all gamma functions as expressions involving rising factorials (Pochhammer symbols) and applies recurrence relations and other transformations applicable to rising factorials, to reduce their arguments, possibly letting the resulting rising factorial to cancel. Rising factorials with the second argument being an integer are expanded into polynomial forms and finally all other rising factorial are rewritten in terms of gamma functions. Then the following two steps are performed. 1. Reduce the number of gammas by applying the reflection theorem gamma(x)*gamma(1-x) == pi/sin(pi*x). 2. Reduce the number of gammas by applying the multiplication theorem gamma(x)*gamma(x+1/n)*...*gamma(x+(n-1)/n) == C*gamma(n*x). It then reduces the number of prefactors by absorbing them into gammas where possible and expands gammas with rational argument. All transformation rules can be found (or were derived from) here: .. [1] http://functions.wolfram.com/GammaBetaErf/Pochhammer/17/01/02/ .. [2] http://functions.wolfram.com/GammaBetaErf/Pochhammer/27/01/0005/ Examples ======== >>> from sympy.simplify import gammasimp >>> from sympy import gamma, Symbol >>> from sympy.abc import x >>> n = Symbol('n', integer = True) >>> gammasimp(gamma(x)/gamma(x - 3)) (x - 3)*(x - 2)*(x - 1) >>> gammasimp(gamma(n + 3)) gamma(n + 3) """ expr = expr.rewrite(gamma) # compute_ST will be looking for Functions and we don't want # it looking for non-gamma functions: issue 22606 # so we mask free, non-gamma functions f = expr.atoms(Function) # take out gammas gammas = {i for i in f if isinstance(i, gamma)} if not gammas: return expr # avoid side effects like factoring f -= gammas # keep only those without bound symbols f = f & expr.as_dummy().atoms(Function) if f: dum, fun, simp = zip(*[ (Dummy(), fi, fi.func(*[ _gammasimp(a, as_comb=False) for a in fi.args])) for fi in ordered(f)]) d = expr.xreplace(dict(zip(fun, dum))) return _gammasimp(d, as_comb=False).xreplace(dict(zip(dum, simp))) return _gammasimp(expr, as_comb=False) def _gammasimp(expr, as_comb): """ Helper function for gammasimp and combsimp. Explanation =========== Simplifies expressions written in terms of gamma function. If as_comb is True, it tries to preserve integer arguments. See docstring of gammasimp for more information. This was part of combsimp() in combsimp.py. """ expr = expr.replace(gamma, lambda n: _rf(1, (n - 1).expand())) if as_comb: expr = expr.replace(_rf, lambda a, b: gamma(b + 1)) else: expr = expr.replace(_rf, lambda a, b: gamma(a + b)/gamma(a)) def rule_gamma(expr, level=0): """ Simplify products of gamma functions further. """ if expr.is_Atom: return expr def gamma_rat(x): # helper to simplify ratios of gammas was = x.count(gamma) xx = x.replace(gamma, lambda n: _rf(1, (n - 1).expand() ).replace(_rf, lambda a, b: gamma(a + b)/gamma(a))) if xx.count(gamma) < was: x = xx return x def gamma_factor(x): # return True if there is a gamma factor in shallow args if isinstance(x, gamma): return True if x.is_Add or x.is_Mul: return any(gamma_factor(xi) for xi in x.args) if x.is_Pow and (x.exp.is_integer or x.base.is_positive): return gamma_factor(x.base) return False # recursion step if level == 0: expr = expr.func(*[rule_gamma(x, level + 1) for x in expr.args]) level += 1 if not expr.is_Mul: return expr # non-commutative step if level == 1: args, nc = expr.args_cnc() if not args: return expr if nc: return rule_gamma(Mul._from_args(args), level + 1)*Mul._from_args(nc) level += 1 # pure gamma handling, not factor absorption if level == 2: T, F = sift(expr.args, gamma_factor, binary=True) gamma_ind = Mul(*F) d = Mul(*T) nd, dd = d.as_numer_denom() for ipass in range(2): args = list(ordered(Mul.make_args(nd))) for i, ni in enumerate(args): if ni.is_Add: ni, dd = Add(*[ rule_gamma(gamma_rat(a/dd), level + 1) for a in ni.args] ).as_numer_denom() args[i] = ni if not dd.has(gamma): break nd = Mul(*args) if ipass == 0 and not gamma_factor(nd): break nd, dd = dd, nd # now process in reversed order expr = gamma_ind*nd/dd if not (expr.is_Mul and (gamma_factor(dd) or gamma_factor(nd))): return expr level += 1 # iteration until constant if level == 3: while True: was = expr expr = rule_gamma(expr, 4) if expr == was: return expr numer_gammas = [] denom_gammas = [] numer_others = [] denom_others = [] def explicate(p): if p is S.One: return None, [] b, e = p.as_base_exp() if e.is_Integer: if isinstance(b, gamma): return True, [b.args[0]]*e else: return False, [b]*e else: return False, [p] newargs = list(ordered(expr.args)) while newargs: n, d = newargs.pop().as_numer_denom() isg, l = explicate(n) if isg: numer_gammas.extend(l) elif isg is False: numer_others.extend(l) isg, l = explicate(d) if isg: denom_gammas.extend(l) elif isg is False: denom_others.extend(l) # =========== level 2 work: pure gamma manipulation ========= if not as_comb: # Try to reduce the number of gamma factors by applying the # reflection formula gamma(x)*gamma(1-x) = pi/sin(pi*x) for gammas, numer, denom in [( numer_gammas, numer_others, denom_others), (denom_gammas, denom_others, numer_others)]: new = [] while gammas: g1 = gammas.pop() if g1.is_integer: new.append(g1) continue for i, g2 in enumerate(gammas): n = g1 + g2 - 1 if not n.is_Integer: continue numer.append(S.Pi) denom.append(sin(S.Pi*g1)) gammas.pop(i) if n > 0: for k in range(n): numer.append(1 - g1 + k) elif n < 0: for k in range(-n): denom.append(-g1 - k) break else: new.append(g1) # /!\ updating IN PLACE gammas[:] = new # Try to reduce the number of gammas by using the duplication # theorem to cancel an upper and lower: gamma(2*s)/gamma(s) = # 2**(2*s + 1)/(4*sqrt(pi))*gamma(s + 1/2). Although this could # be done with higher argument ratios like gamma(3*x)/gamma(x), # this would not reduce the number of gammas as in this case. for ng, dg, no, do in [(numer_gammas, denom_gammas, numer_others, denom_others), (denom_gammas, numer_gammas, denom_others, numer_others)]: while True: for x in ng: for y in dg: n = x - 2*y if n.is_Integer: break else: continue break else: break ng.remove(x) dg.remove(y) if n > 0: for k in range(n): no.append(2*y + k) elif n < 0: for k in range(-n): do.append(2*y - 1 - k) ng.append(y + S.Half) no.append(2**(2*y - 1)) do.append(sqrt(S.Pi)) # Try to reduce the number of gamma factors by applying the # multiplication theorem (used when n gammas with args differing # by 1/n mod 1 are encountered). # # run of 2 with args differing by 1/2 # # >>> gammasimp(gamma(x)*gamma(x+S.Half)) # 2*sqrt(2)*2**(-2*x - 1/2)*sqrt(pi)*gamma(2*x) # # run of 3 args differing by 1/3 (mod 1) # # >>> gammasimp(gamma(x)*gamma(x+S(1)/3)*gamma(x+S(2)/3)) # 6*3**(-3*x - 1/2)*pi*gamma(3*x) # >>> gammasimp(gamma(x)*gamma(x+S(1)/3)*gamma(x+S(5)/3)) # 2*3**(-3*x - 1/2)*pi*(3*x + 2)*gamma(3*x) # def _run(coeffs): # find runs in coeffs such that the difference in terms (mod 1) # of t1, t2, ..., tn is 1/n u = list(uniq(coeffs)) for i in range(len(u)): dj = ([((u[j] - u[i]) % 1, j) for j in range(i + 1, len(u))]) for one, j in dj: if one.p == 1 and one.q != 1: n = one.q got = [i] get = list(range(1, n)) for d, j in dj: m = n*d if m.is_Integer and m in get: get.remove(m) got.append(j) if not get: break else: continue for i, j in enumerate(got): c = u[j] coeffs.remove(c) got[i] = c return one.q, got[0], got[1:] def _mult_thm(gammas, numer, denom): # pull off and analyze the leading coefficient from each gamma arg # looking for runs in those Rationals # expr -> coeff + resid -> rats[resid] = coeff rats = {} for g in gammas: c, resid = g.as_coeff_Add() rats.setdefault(resid, []).append(c) # look for runs in Rationals for each resid keys = sorted(rats, key=default_sort_key) for resid in keys: coeffs = list(sorted(rats[resid])) new = [] while True: run = _run(coeffs) if run is None: break # process the sequence that was found: # 1) convert all the gamma functions to have the right # argument (could be off by an integer) # 2) append the factors corresponding to the theorem # 3) append the new gamma function n, ui, other = run # (1) for u in other: con = resid + u - 1 for k in range(int(u - ui)): numer.append(con - k) con = n*(resid + ui) # for (2) and (3) # (2) numer.append((2*S.Pi)**(S(n - 1)/2)* n**(S.Half - con)) # (3) new.append(con) # restore resid to coeffs rats[resid] = [resid + c for c in coeffs] + new # rebuild the gamma arguments g = [] for resid in keys: g += rats[resid] # /!\ updating IN PLACE gammas[:] = g for l, numer, denom in [(numer_gammas, numer_others, denom_others), (denom_gammas, denom_others, numer_others)]: _mult_thm(l, numer, denom) # =========== level >= 2 work: factor absorption ========= if level >= 2: # Try to absorb factors into the gammas: x*gamma(x) -> gamma(x + 1) # and gamma(x)/(x - 1) -> gamma(x - 1) # This code (in particular repeated calls to find_fuzzy) can be very # slow. def find_fuzzy(l, x): if not l: return S1, T1 = compute_ST(x) for y in l: S2, T2 = inv[y] if T1 != T2 or (not S1.intersection(S2) and (S1 != set() or S2 != set())): continue # XXX we want some simplification (e.g. cancel or # simplify) but no matter what it's slow. a = len(cancel(x/y).free_symbols) b = len(x.free_symbols) c = len(y.free_symbols) # TODO is there a better heuristic? if a == 0 and (b > 0 or c > 0): return y # We thus try to avoid expensive calls by building the following # "invariants": For every factor or gamma function argument # - the set of free symbols S # - the set of functional components T # We will only try to absorb if T1==T2 and (S1 intersect S2 != emptyset # or S1 == S2 == emptyset) inv = {} def compute_ST(expr): if expr in inv: return inv[expr] return (expr.free_symbols, expr.atoms(Function).union( {e.exp for e in expr.atoms(Pow)})) def update_ST(expr): inv[expr] = compute_ST(expr) for expr in numer_gammas + denom_gammas + numer_others + denom_others: update_ST(expr) for gammas, numer, denom in [( numer_gammas, numer_others, denom_others), (denom_gammas, denom_others, numer_others)]: new = [] while gammas: g = gammas.pop() cont = True while cont: cont = False y = find_fuzzy(numer, g) if y is not None: numer.remove(y) if y != g: numer.append(y/g) update_ST(y/g) g += 1 cont = True y = find_fuzzy(denom, g - 1) if y is not None: denom.remove(y) if y != g - 1: numer.append((g - 1)/y) update_ST((g - 1)/y) g -= 1 cont = True new.append(g) # /!\ updating IN PLACE gammas[:] = new # =========== rebuild expr ================================== return Mul(*[gamma(g) for g in numer_gammas]) \ / Mul(*[gamma(g) for g in denom_gammas]) \ * Mul(*numer_others) / Mul(*denom_others) was = factor(expr) # (for some reason we cannot use Basic.replace in this case) expr = rule_gamma(was) if expr != was: expr = factor(expr) expr = expr.replace(gamma, lambda n: expand_func(gamma(n)) if n.is_Rational else gamma(n)) return expr class _rf(Function): @classmethod def eval(cls, a, b): if b.is_Integer: if not b: return S.One n, result = int(b), S.One if n > 0: for i in range(n): result *= a + i return result elif n < 0: for i in range(1, -n + 1): result *= a - i return 1/result else: if b.is_Add: c, _b = b.as_coeff_Add() if c.is_Integer: if c > 0: return _rf(a, _b)*_rf(a + _b, c) elif c < 0: return _rf(a, _b)/_rf(a + _b + c, -c) if a.is_Add: c, _a = a.as_coeff_Add() if c.is_Integer: if c > 0: return _rf(_a, b)*_rf(_a + b, c)/_rf(_a, c) elif c < 0: return _rf(_a, b)*_rf(_a + c, -c)/_rf(_a + b + c, -c)
5e9d713ce1670cb7a88f35c38d4bbceb68d11f401f737578ee89dc9726dffbf6
from collections import defaultdict from sympy.core.add import Add from sympy.core.expr import Expr from sympy.core.exprtools import Factors, gcd_terms, factor_terms from sympy.core.function import expand_mul from sympy.core.mul import Mul from sympy.core.numbers import pi, I from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.sorting import ordered from sympy.core.symbol import Dummy from sympy.core.sympify import sympify from sympy.core.traversal import bottom_up from sympy.functions.combinatorial.factorials import binomial from sympy.functions.elementary.hyperbolic import ( cosh, sinh, tanh, coth, sech, csch, HyperbolicFunction) from sympy.functions.elementary.trigonometric import ( cos, sin, tan, cot, sec, csc, sqrt, TrigonometricFunction) from sympy.ntheory.factor_ import perfect_power from sympy.polys.polytools import factor from sympy.strategies.tree import greedy from sympy.strategies.core import identity, debug from sympy import SYMPY_DEBUG # ================== Fu-like tools =========================== def TR0(rv): """Simplification of rational polynomials, trying to simplify the expression, e.g. combine things like 3*x + 2*x, etc.... """ # although it would be nice to use cancel, it doesn't work # with noncommutatives return rv.normal().factor().expand() def TR1(rv): """Replace sec, csc with 1/cos, 1/sin Examples ======== >>> from sympy.simplify.fu import TR1, sec, csc >>> from sympy.abc import x >>> TR1(2*csc(x) + sec(x)) 1/cos(x) + 2/sin(x) """ def f(rv): if isinstance(rv, sec): a = rv.args[0] return S.One/cos(a) elif isinstance(rv, csc): a = rv.args[0] return S.One/sin(a) return rv return bottom_up(rv, f) def TR2(rv): """Replace tan and cot with sin/cos and cos/sin Examples ======== >>> from sympy.simplify.fu import TR2 >>> from sympy.abc import x >>> from sympy import tan, cot, sin, cos >>> TR2(tan(x)) sin(x)/cos(x) >>> TR2(cot(x)) cos(x)/sin(x) >>> TR2(tan(tan(x) - sin(x)/cos(x))) 0 """ def f(rv): if isinstance(rv, tan): a = rv.args[0] return sin(a)/cos(a) elif isinstance(rv, cot): a = rv.args[0] return cos(a)/sin(a) return rv return bottom_up(rv, f) def TR2i(rv, half=False): """Converts ratios involving sin and cos as follows:: sin(x)/cos(x) -> tan(x) sin(x)/(cos(x) + 1) -> tan(x/2) if half=True Examples ======== >>> from sympy.simplify.fu import TR2i >>> from sympy.abc import x, a >>> from sympy import sin, cos >>> TR2i(sin(x)/cos(x)) tan(x) Powers of the numerator and denominator are also recognized >>> TR2i(sin(x)**2/(cos(x) + 1)**2, half=True) tan(x/2)**2 The transformation does not take place unless assumptions allow (i.e. the base must be positive or the exponent must be an integer for both numerator and denominator) >>> TR2i(sin(x)**a/(cos(x) + 1)**a) sin(x)**a/(cos(x) + 1)**a """ def f(rv): if not rv.is_Mul: return rv n, d = rv.as_numer_denom() if n.is_Atom or d.is_Atom: return rv def ok(k, e): # initial filtering of factors return ( (e.is_integer or k.is_positive) and ( k.func in (sin, cos) or (half and k.is_Add and len(k.args) >= 2 and any(any(isinstance(ai, cos) or ai.is_Pow and ai.base is cos for ai in Mul.make_args(a)) for a in k.args)))) n = n.as_powers_dict() ndone = [(k, n.pop(k)) for k in list(n.keys()) if not ok(k, n[k])] if not n: return rv d = d.as_powers_dict() ddone = [(k, d.pop(k)) for k in list(d.keys()) if not ok(k, d[k])] if not d: return rv # factoring if necessary def factorize(d, ddone): newk = [] for k in d: if k.is_Add and len(k.args) > 1: knew = factor(k) if half else factor_terms(k) if knew != k: newk.append((k, knew)) if newk: for i, (k, knew) in enumerate(newk): del d[k] newk[i] = knew newk = Mul(*newk).as_powers_dict() for k in newk: v = d[k] + newk[k] if ok(k, v): d[k] = v else: ddone.append((k, v)) del newk factorize(n, ndone) factorize(d, ddone) # joining t = [] for k in n: if isinstance(k, sin): a = cos(k.args[0], evaluate=False) if a in d and d[a] == n[k]: t.append(tan(k.args[0])**n[k]) n[k] = d[a] = None elif half: a1 = 1 + a if a1 in d and d[a1] == n[k]: t.append((tan(k.args[0]/2))**n[k]) n[k] = d[a1] = None elif isinstance(k, cos): a = sin(k.args[0], evaluate=False) if a in d and d[a] == n[k]: t.append(tan(k.args[0])**-n[k]) n[k] = d[a] = None elif half and k.is_Add and k.args[0] is S.One and \ isinstance(k.args[1], cos): a = sin(k.args[1].args[0], evaluate=False) if a in d and d[a] == n[k] and (d[a].is_integer or \ a.is_positive): t.append(tan(a.args[0]/2)**-n[k]) n[k] = d[a] = None if t: rv = Mul(*(t + [b**e for b, e in n.items() if e]))/\ Mul(*[b**e for b, e in d.items() if e]) rv *= Mul(*[b**e for b, e in ndone])/Mul(*[b**e for b, e in ddone]) return rv return bottom_up(rv, f) def TR3(rv): """Induced formula: example sin(-a) = -sin(a) Examples ======== >>> from sympy.simplify.fu import TR3 >>> from sympy.abc import x, y >>> from sympy import pi >>> from sympy import cos >>> TR3(cos(y - x*(y - x))) cos(x*(x - y) + y) >>> cos(pi/2 + x) -sin(x) >>> cos(30*pi/2 + x) -cos(x) """ from sympy.simplify.simplify import signsimp # Negative argument (already automatic for funcs like sin(-x) -> -sin(x) # but more complicated expressions can use it, too). Also, trig angles # between pi/4 and pi/2 are not reduced to an angle between 0 and pi/4. # The following are automatically handled: # Argument of type: pi/2 +/- angle # Argument of type: pi +/- angle # Argument of type : 2k*pi +/- angle def f(rv): if not isinstance(rv, TrigonometricFunction): return rv rv = rv.func(signsimp(rv.args[0])) if not isinstance(rv, TrigonometricFunction): return rv if (rv.args[0] - S.Pi/4).is_positive is (S.Pi/2 - rv.args[0]).is_positive is True: fmap = {cos: sin, sin: cos, tan: cot, cot: tan, sec: csc, csc: sec} rv = fmap[type(rv)](S.Pi/2 - rv.args[0]) return rv return bottom_up(rv, f) def TR4(rv): """Identify values of special angles. a= 0 pi/6 pi/4 pi/3 pi/2 ---------------------------------------------------- sin(a) 0 1/2 sqrt(2)/2 sqrt(3)/2 1 cos(a) 1 sqrt(3)/2 sqrt(2)/2 1/2 0 tan(a) 0 sqt(3)/3 1 sqrt(3) -- Examples ======== >>> from sympy import pi >>> from sympy import cos, sin, tan, cot >>> for s in (0, pi/6, pi/4, pi/3, pi/2): ... print('%s %s %s %s' % (cos(s), sin(s), tan(s), cot(s))) ... 1 0 0 zoo sqrt(3)/2 1/2 sqrt(3)/3 sqrt(3) sqrt(2)/2 sqrt(2)/2 1 1 1/2 sqrt(3)/2 sqrt(3) sqrt(3)/3 0 1 zoo 0 """ # special values at 0, pi/6, pi/4, pi/3, pi/2 already handled return rv def _TR56(rv, f, g, h, max, pow): """Helper for TR5 and TR6 to replace f**2 with h(g**2) Options ======= max : controls size of exponent that can appear on f e.g. if max=4 then f**4 will be changed to h(g**2)**2. pow : controls whether the exponent must be a perfect power of 2 e.g. if pow=True (and max >= 6) then f**6 will not be changed but f**8 will be changed to h(g**2)**4 >>> from sympy.simplify.fu import _TR56 as T >>> from sympy.abc import x >>> from sympy import sin, cos >>> h = lambda x: 1 - x >>> T(sin(x)**3, sin, cos, h, 4, False) (1 - cos(x)**2)*sin(x) >>> T(sin(x)**6, sin, cos, h, 6, False) (1 - cos(x)**2)**3 >>> T(sin(x)**6, sin, cos, h, 6, True) sin(x)**6 >>> T(sin(x)**8, sin, cos, h, 10, True) (1 - cos(x)**2)**4 """ def _f(rv): # I'm not sure if this transformation should target all even powers # or only those expressible as powers of 2. Also, should it only # make the changes in powers that appear in sums -- making an isolated # change is not going to allow a simplification as far as I can tell. if not (rv.is_Pow and rv.base.func == f): return rv if not rv.exp.is_real: return rv if (rv.exp < 0) == True: return rv if (rv.exp > max) == True: return rv if rv.exp == 1: return rv if rv.exp == 2: return h(g(rv.base.args[0])**2) else: if rv.exp % 2 == 1: e = rv.exp//2 return f(rv.base.args[0])*h(g(rv.base.args[0])**2)**e elif rv.exp == 4: e = 2 elif not pow: if rv.exp % 2: return rv e = rv.exp//2 else: p = perfect_power(rv.exp) if not p: return rv e = rv.exp//2 return h(g(rv.base.args[0])**2)**e return bottom_up(rv, _f) def TR5(rv, max=4, pow=False): """Replacement of sin**2 with 1 - cos(x)**2. See _TR56 docstring for advanced use of ``max`` and ``pow``. Examples ======== >>> from sympy.simplify.fu import TR5 >>> from sympy.abc import x >>> from sympy import sin >>> TR5(sin(x)**2) 1 - cos(x)**2 >>> TR5(sin(x)**-2) # unchanged sin(x)**(-2) >>> TR5(sin(x)**4) (1 - cos(x)**2)**2 """ return _TR56(rv, sin, cos, lambda x: 1 - x, max=max, pow=pow) def TR6(rv, max=4, pow=False): """Replacement of cos**2 with 1 - sin(x)**2. See _TR56 docstring for advanced use of ``max`` and ``pow``. Examples ======== >>> from sympy.simplify.fu import TR6 >>> from sympy.abc import x >>> from sympy import cos >>> TR6(cos(x)**2) 1 - sin(x)**2 >>> TR6(cos(x)**-2) #unchanged cos(x)**(-2) >>> TR6(cos(x)**4) (1 - sin(x)**2)**2 """ return _TR56(rv, cos, sin, lambda x: 1 - x, max=max, pow=pow) def TR7(rv): """Lowering the degree of cos(x)**2. Examples ======== >>> from sympy.simplify.fu import TR7 >>> from sympy.abc import x >>> from sympy import cos >>> TR7(cos(x)**2) cos(2*x)/2 + 1/2 >>> TR7(cos(x)**2 + 1) cos(2*x)/2 + 3/2 """ def f(rv): if not (rv.is_Pow and rv.base.func == cos and rv.exp == 2): return rv return (1 + cos(2*rv.base.args[0]))/2 return bottom_up(rv, f) def TR8(rv, first=True): """Converting products of ``cos`` and/or ``sin`` to a sum or difference of ``cos`` and or ``sin`` terms. Examples ======== >>> from sympy.simplify.fu import TR8 >>> from sympy import cos, sin >>> TR8(cos(2)*cos(3)) cos(5)/2 + cos(1)/2 >>> TR8(cos(2)*sin(3)) sin(5)/2 + sin(1)/2 >>> TR8(sin(2)*sin(3)) -cos(5)/2 + cos(1)/2 """ def f(rv): if not ( rv.is_Mul or rv.is_Pow and rv.base.func in (cos, sin) and (rv.exp.is_integer or rv.base.is_positive)): return rv if first: n, d = [expand_mul(i) for i in rv.as_numer_denom()] newn = TR8(n, first=False) newd = TR8(d, first=False) if newn != n or newd != d: rv = gcd_terms(newn/newd) if rv.is_Mul and rv.args[0].is_Rational and \ len(rv.args) == 2 and rv.args[1].is_Add: rv = Mul(*rv.as_coeff_Mul()) return rv args = {cos: [], sin: [], None: []} for a in ordered(Mul.make_args(rv)): if a.func in (cos, sin): args[type(a)].append(a.args[0]) elif (a.is_Pow and a.exp.is_Integer and a.exp > 0 and \ a.base.func in (cos, sin)): # XXX this is ok but pathological expression could be handled # more efficiently as in TRmorrie args[type(a.base)].extend([a.base.args[0]]*a.exp) else: args[None].append(a) c = args[cos] s = args[sin] if not (c and s or len(c) > 1 or len(s) > 1): return rv args = args[None] n = min(len(c), len(s)) for i in range(n): a1 = s.pop() a2 = c.pop() args.append((sin(a1 + a2) + sin(a1 - a2))/2) while len(c) > 1: a1 = c.pop() a2 = c.pop() args.append((cos(a1 + a2) + cos(a1 - a2))/2) if c: args.append(cos(c.pop())) while len(s) > 1: a1 = s.pop() a2 = s.pop() args.append((-cos(a1 + a2) + cos(a1 - a2))/2) if s: args.append(sin(s.pop())) return TR8(expand_mul(Mul(*args))) return bottom_up(rv, f) def TR9(rv): """Sum of ``cos`` or ``sin`` terms as a product of ``cos`` or ``sin``. Examples ======== >>> from sympy.simplify.fu import TR9 >>> from sympy import cos, sin >>> TR9(cos(1) + cos(2)) 2*cos(1/2)*cos(3/2) >>> TR9(cos(1) + 2*sin(1) + 2*sin(2)) cos(1) + 4*sin(3/2)*cos(1/2) If no change is made by TR9, no re-arrangement of the expression will be made. For example, though factoring of common term is attempted, if the factored expression wasn't changed, the original expression will be returned: >>> TR9(cos(3) + cos(3)*cos(2)) cos(3) + cos(2)*cos(3) """ def f(rv): if not rv.is_Add: return rv def do(rv, first=True): # cos(a)+/-cos(b) can be combined into a product of cosines and # sin(a)+/-sin(b) can be combined into a product of cosine and # sine. # # If there are more than two args, the pairs which "work" will # have a gcd extractable and the remaining two terms will have # the above structure -- all pairs must be checked to find the # ones that work. args that don't have a common set of symbols # are skipped since this doesn't lead to a simpler formula and # also has the arbitrariness of combining, for example, the x # and y term instead of the y and z term in something like # cos(x) + cos(y) + cos(z). if not rv.is_Add: return rv args = list(ordered(rv.args)) if len(args) != 2: hit = False for i in range(len(args)): ai = args[i] if ai is None: continue for j in range(i + 1, len(args)): aj = args[j] if aj is None: continue was = ai + aj new = do(was) if new != was: args[i] = new # update in place args[j] = None hit = True break # go to next i if hit: rv = Add(*[_f for _f in args if _f]) if rv.is_Add: rv = do(rv) return rv # two-arg Add split = trig_split(*args) if not split: return rv gcd, n1, n2, a, b, iscos = split # application of rule if possible if iscos: if n1 == n2: return gcd*n1*2*cos((a + b)/2)*cos((a - b)/2) if n1 < 0: a, b = b, a return -2*gcd*sin((a + b)/2)*sin((a - b)/2) else: if n1 == n2: return gcd*n1*2*sin((a + b)/2)*cos((a - b)/2) if n1 < 0: a, b = b, a return 2*gcd*cos((a + b)/2)*sin((a - b)/2) return process_common_addends(rv, do) # DON'T sift by free symbols return bottom_up(rv, f) def TR10(rv, first=True): """Separate sums in ``cos`` and ``sin``. Examples ======== >>> from sympy.simplify.fu import TR10 >>> from sympy.abc import a, b, c >>> from sympy import cos, sin >>> TR10(cos(a + b)) -sin(a)*sin(b) + cos(a)*cos(b) >>> TR10(sin(a + b)) sin(a)*cos(b) + sin(b)*cos(a) >>> TR10(sin(a + b + c)) (-sin(a)*sin(b) + cos(a)*cos(b))*sin(c) + \ (sin(a)*cos(b) + sin(b)*cos(a))*cos(c) """ def f(rv): if rv.func not in (cos, sin): return rv f = rv.func arg = rv.args[0] if arg.is_Add: if first: args = list(ordered(arg.args)) else: args = list(arg.args) a = args.pop() b = Add._from_args(args) if b.is_Add: if f == sin: return sin(a)*TR10(cos(b), first=False) + \ cos(a)*TR10(sin(b), first=False) else: return cos(a)*TR10(cos(b), first=False) - \ sin(a)*TR10(sin(b), first=False) else: if f == sin: return sin(a)*cos(b) + cos(a)*sin(b) else: return cos(a)*cos(b) - sin(a)*sin(b) return rv return bottom_up(rv, f) def TR10i(rv): """Sum of products to function of sum. Examples ======== >>> from sympy.simplify.fu import TR10i >>> from sympy import cos, sin, sqrt >>> from sympy.abc import x >>> TR10i(cos(1)*cos(3) + sin(1)*sin(3)) cos(2) >>> TR10i(cos(1)*sin(3) + sin(1)*cos(3) + cos(3)) cos(3) + sin(4) >>> TR10i(sqrt(2)*cos(x)*x + sqrt(6)*sin(x)*x) 2*sqrt(2)*x*sin(x + pi/6) """ global _ROOT2, _ROOT3, _invROOT3 if _ROOT2 is None: _roots() def f(rv): if not rv.is_Add: return rv def do(rv, first=True): # args which can be expressed as A*(cos(a)*cos(b)+/-sin(a)*sin(b)) # or B*(cos(a)*sin(b)+/-cos(b)*sin(a)) can be combined into # A*f(a+/-b) where f is either sin or cos. # # If there are more than two args, the pairs which "work" will have # a gcd extractable and the remaining two terms will have the above # structure -- all pairs must be checked to find the ones that # work. if not rv.is_Add: return rv args = list(ordered(rv.args)) if len(args) != 2: hit = False for i in range(len(args)): ai = args[i] if ai is None: continue for j in range(i + 1, len(args)): aj = args[j] if aj is None: continue was = ai + aj new = do(was) if new != was: args[i] = new # update in place args[j] = None hit = True break # go to next i if hit: rv = Add(*[_f for _f in args if _f]) if rv.is_Add: rv = do(rv) return rv # two-arg Add split = trig_split(*args, two=True) if not split: return rv gcd, n1, n2, a, b, same = split # identify and get c1 to be cos then apply rule if possible if same: # coscos, sinsin gcd = n1*gcd if n1 == n2: return gcd*cos(a - b) return gcd*cos(a + b) else: #cossin, cossin gcd = n1*gcd if n1 == n2: return gcd*sin(a + b) return gcd*sin(b - a) rv = process_common_addends( rv, do, lambda x: tuple(ordered(x.free_symbols))) # need to check for inducible pairs in ratio of sqrt(3):1 that # appeared in different lists when sorting by coefficient while rv.is_Add: byrad = defaultdict(list) for a in rv.args: hit = 0 if a.is_Mul: for ai in a.args: if ai.is_Pow and ai.exp is S.Half and \ ai.base.is_Integer: byrad[ai].append(a) hit = 1 break if not hit: byrad[S.One].append(a) # no need to check all pairs -- just check for the onees # that have the right ratio args = [] for a in byrad: for b in [_ROOT3*a, _invROOT3]: if b in byrad: for i in range(len(byrad[a])): if byrad[a][i] is None: continue for j in range(len(byrad[b])): if byrad[b][j] is None: continue was = Add(byrad[a][i] + byrad[b][j]) new = do(was) if new != was: args.append(new) byrad[a][i] = None byrad[b][j] = None break if args: rv = Add(*(args + [Add(*[_f for _f in v if _f]) for v in byrad.values()])) else: rv = do(rv) # final pass to resolve any new inducible pairs break return rv return bottom_up(rv, f) def TR11(rv, base=None): """Function of double angle to product. The ``base`` argument can be used to indicate what is the un-doubled argument, e.g. if 3*pi/7 is the base then cosine and sine functions with argument 6*pi/7 will be replaced. Examples ======== >>> from sympy.simplify.fu import TR11 >>> from sympy import cos, sin, pi >>> from sympy.abc import x >>> TR11(sin(2*x)) 2*sin(x)*cos(x) >>> TR11(cos(2*x)) -sin(x)**2 + cos(x)**2 >>> TR11(sin(4*x)) 4*(-sin(x)**2 + cos(x)**2)*sin(x)*cos(x) >>> TR11(sin(4*x/3)) 4*(-sin(x/3)**2 + cos(x/3)**2)*sin(x/3)*cos(x/3) If the arguments are simply integers, no change is made unless a base is provided: >>> TR11(cos(2)) cos(2) >>> TR11(cos(4), 2) -sin(2)**2 + cos(2)**2 There is a subtle issue here in that autosimplification will convert some higher angles to lower angles >>> cos(6*pi/7) + cos(3*pi/7) -cos(pi/7) + cos(3*pi/7) The 6*pi/7 angle is now pi/7 but can be targeted with TR11 by supplying the 3*pi/7 base: >>> TR11(_, 3*pi/7) -sin(3*pi/7)**2 + cos(3*pi/7)**2 + cos(3*pi/7) """ def f(rv): if rv.func not in (cos, sin): return rv if base: f = rv.func t = f(base*2) co = S.One if t.is_Mul: co, t = t.as_coeff_Mul() if t.func not in (cos, sin): return rv if rv.args[0] == t.args[0]: c = cos(base) s = sin(base) if f is cos: return (c**2 - s**2)/co else: return 2*c*s/co return rv elif not rv.args[0].is_Number: # make a change if the leading coefficient's numerator is # divisible by 2 c, m = rv.args[0].as_coeff_Mul(rational=True) if c.p % 2 == 0: arg = c.p//2*m/c.q c = TR11(cos(arg)) s = TR11(sin(arg)) if rv.func == sin: rv = 2*s*c else: rv = c**2 - s**2 return rv return bottom_up(rv, f) def _TR11(rv): """ Helper for TR11 to find half-arguments for sin in factors of num/den that appear in cos or sin factors in the den/num. Examples ======== >>> from sympy.simplify.fu import TR11, _TR11 >>> from sympy import cos, sin >>> from sympy.abc import x >>> TR11(sin(x/3)/(cos(x/6))) sin(x/3)/cos(x/6) >>> _TR11(sin(x/3)/(cos(x/6))) 2*sin(x/6) >>> TR11(sin(x/6)/(sin(x/3))) sin(x/6)/sin(x/3) >>> _TR11(sin(x/6)/(sin(x/3))) 1/(2*cos(x/6)) """ def f(rv): if not isinstance(rv, Expr): return rv def sincos_args(flat): # find arguments of sin and cos that # appears as bases in args of flat # and have Integer exponents args = defaultdict(set) for fi in Mul.make_args(flat): b, e = fi.as_base_exp() if e.is_Integer and e > 0: if b.func in (cos, sin): args[type(b)].add(b.args[0]) return args num_args, den_args = map(sincos_args, rv.as_numer_denom()) def handle_match(rv, num_args, den_args): # for arg in sin args of num_args, look for arg/2 # in den_args and pass this half-angle to TR11 # for handling in rv for narg in num_args[sin]: half = narg/2 if half in den_args[cos]: func = cos elif half in den_args[sin]: func = sin else: continue rv = TR11(rv, half) den_args[func].remove(half) return rv # sin in num, sin or cos in den rv = handle_match(rv, num_args, den_args) # sin in den, sin or cos in num rv = handle_match(rv, den_args, num_args) return rv return bottom_up(rv, f) def TR12(rv, first=True): """Separate sums in ``tan``. Examples ======== >>> from sympy.abc import x, y >>> from sympy import tan >>> from sympy.simplify.fu import TR12 >>> TR12(tan(x + y)) (tan(x) + tan(y))/(-tan(x)*tan(y) + 1) """ def f(rv): if not rv.func == tan: return rv arg = rv.args[0] if arg.is_Add: if first: args = list(ordered(arg.args)) else: args = list(arg.args) a = args.pop() b = Add._from_args(args) if b.is_Add: tb = TR12(tan(b), first=False) else: tb = tan(b) return (tan(a) + tb)/(1 - tan(a)*tb) return rv return bottom_up(rv, f) def TR12i(rv): """Combine tan arguments as (tan(y) + tan(x))/(tan(x)*tan(y) - 1) -> -tan(x + y). Examples ======== >>> from sympy.simplify.fu import TR12i >>> from sympy import tan >>> from sympy.abc import a, b, c >>> ta, tb, tc = [tan(i) for i in (a, b, c)] >>> TR12i((ta + tb)/(-ta*tb + 1)) tan(a + b) >>> TR12i((ta + tb)/(ta*tb - 1)) -tan(a + b) >>> TR12i((-ta - tb)/(ta*tb - 1)) tan(a + b) >>> eq = (ta + tb)/(-ta*tb + 1)**2*(-3*ta - 3*tc)/(2*(ta*tc - 1)) >>> TR12i(eq.expand()) -3*tan(a + b)*tan(a + c)/(2*(tan(a) + tan(b) - 1)) """ def f(rv): if not (rv.is_Add or rv.is_Mul or rv.is_Pow): return rv n, d = rv.as_numer_denom() if not d.args or not n.args: return rv dok = {} def ok(di): m = as_f_sign_1(di) if m: g, f, s = m if s is S.NegativeOne and f.is_Mul and len(f.args) == 2 and \ all(isinstance(fi, tan) for fi in f.args): return g, f d_args = list(Mul.make_args(d)) for i, di in enumerate(d_args): m = ok(di) if m: g, t = m s = Add(*[_.args[0] for _ in t.args]) dok[s] = S.One d_args[i] = g continue if di.is_Add: di = factor(di) if di.is_Mul: d_args.extend(di.args) d_args[i] = S.One elif di.is_Pow and (di.exp.is_integer or di.base.is_positive): m = ok(di.base) if m: g, t = m s = Add(*[_.args[0] for _ in t.args]) dok[s] = di.exp d_args[i] = g**di.exp else: di = factor(di) if di.is_Mul: d_args.extend(di.args) d_args[i] = S.One if not dok: return rv def ok(ni): if ni.is_Add and len(ni.args) == 2: a, b = ni.args if isinstance(a, tan) and isinstance(b, tan): return a, b n_args = list(Mul.make_args(factor_terms(n))) hit = False for i, ni in enumerate(n_args): m = ok(ni) if not m: m = ok(-ni) if m: n_args[i] = S.NegativeOne else: if ni.is_Add: ni = factor(ni) if ni.is_Mul: n_args.extend(ni.args) n_args[i] = S.One continue elif ni.is_Pow and ( ni.exp.is_integer or ni.base.is_positive): m = ok(ni.base) if m: n_args[i] = S.One else: ni = factor(ni) if ni.is_Mul: n_args.extend(ni.args) n_args[i] = S.One continue else: continue else: n_args[i] = S.One hit = True s = Add(*[_.args[0] for _ in m]) ed = dok[s] newed = ed.extract_additively(S.One) if newed is not None: if newed: dok[s] = newed else: dok.pop(s) n_args[i] *= -tan(s) if hit: rv = Mul(*n_args)/Mul(*d_args)/Mul(*[(Add(*[ tan(a) for a in i.args]) - 1)**e for i, e in dok.items()]) return rv return bottom_up(rv, f) def TR13(rv): """Change products of ``tan`` or ``cot``. Examples ======== >>> from sympy.simplify.fu import TR13 >>> from sympy import tan, cot >>> TR13(tan(3)*tan(2)) -tan(2)/tan(5) - tan(3)/tan(5) + 1 >>> TR13(cot(3)*cot(2)) cot(2)*cot(5) + 1 + cot(3)*cot(5) """ def f(rv): if not rv.is_Mul: return rv # XXX handle products of powers? or let power-reducing handle it? args = {tan: [], cot: [], None: []} for a in ordered(Mul.make_args(rv)): if a.func in (tan, cot): args[type(a)].append(a.args[0]) else: args[None].append(a) t = args[tan] c = args[cot] if len(t) < 2 and len(c) < 2: return rv args = args[None] while len(t) > 1: t1 = t.pop() t2 = t.pop() args.append(1 - (tan(t1)/tan(t1 + t2) + tan(t2)/tan(t1 + t2))) if t: args.append(tan(t.pop())) while len(c) > 1: t1 = c.pop() t2 = c.pop() args.append(1 + cot(t1)*cot(t1 + t2) + cot(t2)*cot(t1 + t2)) if c: args.append(cot(c.pop())) return Mul(*args) return bottom_up(rv, f) def TRmorrie(rv): """Returns cos(x)*cos(2*x)*...*cos(2**(k-1)*x) -> sin(2**k*x)/(2**k*sin(x)) Examples ======== >>> from sympy.simplify.fu import TRmorrie, TR8, TR3 >>> from sympy.abc import x >>> from sympy import Mul, cos, pi >>> TRmorrie(cos(x)*cos(2*x)) sin(4*x)/(4*sin(x)) >>> TRmorrie(7*Mul(*[cos(x) for x in range(10)])) 7*sin(12)*sin(16)*cos(5)*cos(7)*cos(9)/(64*sin(1)*sin(3)) Sometimes autosimplification will cause a power to be not recognized. e.g. in the following, cos(4*pi/7) automatically simplifies to -cos(3*pi/7) so only 2 of the 3 terms are recognized: >>> TRmorrie(cos(pi/7)*cos(2*pi/7)*cos(4*pi/7)) -sin(3*pi/7)*cos(3*pi/7)/(4*sin(pi/7)) A touch by TR8 resolves the expression to a Rational >>> TR8(_) -1/8 In this case, if eq is unsimplified, the answer is obtained directly: >>> eq = cos(pi/9)*cos(2*pi/9)*cos(3*pi/9)*cos(4*pi/9) >>> TRmorrie(eq) 1/16 But if angles are made canonical with TR3 then the answer is not simplified without further work: >>> TR3(eq) sin(pi/18)*cos(pi/9)*cos(2*pi/9)/2 >>> TRmorrie(_) sin(pi/18)*sin(4*pi/9)/(8*sin(pi/9)) >>> TR8(_) cos(7*pi/18)/(16*sin(pi/9)) >>> TR3(_) 1/16 The original expression would have resolve to 1/16 directly with TR8, however: >>> TR8(eq) 1/16 References ========== .. [1] https://en.wikipedia.org/wiki/Morrie%27s_law """ def f(rv, first=True): if not rv.is_Mul: return rv if first: n, d = rv.as_numer_denom() return f(n, 0)/f(d, 0) args = defaultdict(list) coss = {} other = [] for c in rv.args: b, e = c.as_base_exp() if e.is_Integer and isinstance(b, cos): co, a = b.args[0].as_coeff_Mul() args[a].append(co) coss[b] = e else: other.append(c) new = [] for a in args: c = args[a] c.sort() while c: k = 0 cc = ci = c[0] while cc in c: k += 1 cc *= 2 if k > 1: newarg = sin(2**k*ci*a)/2**k/sin(ci*a) # see how many times this can be taken take = None ccs = [] for i in range(k): cc /= 2 key = cos(a*cc, evaluate=False) ccs.append(cc) take = min(coss[key], take or coss[key]) # update exponent counts for i in range(k): cc = ccs.pop() key = cos(a*cc, evaluate=False) coss[key] -= take if not coss[key]: c.remove(cc) new.append(newarg**take) else: b = cos(c.pop(0)*a) other.append(b**coss[b]) if new: rv = Mul(*(new + other + [ cos(k*a, evaluate=False) for a in args for k in args[a]])) return rv return bottom_up(rv, f) def TR14(rv, first=True): """Convert factored powers of sin and cos identities into simpler expressions. Examples ======== >>> from sympy.simplify.fu import TR14 >>> from sympy.abc import x, y >>> from sympy import cos, sin >>> TR14((cos(x) - 1)*(cos(x) + 1)) -sin(x)**2 >>> TR14((sin(x) - 1)*(sin(x) + 1)) -cos(x)**2 >>> p1 = (cos(x) + 1)*(cos(x) - 1) >>> p2 = (cos(y) - 1)*2*(cos(y) + 1) >>> p3 = (3*(cos(y) - 1))*(3*(cos(y) + 1)) >>> TR14(p1*p2*p3*(x - 1)) -18*(x - 1)*sin(x)**2*sin(y)**4 """ def f(rv): if not rv.is_Mul: return rv if first: # sort them by location in numerator and denominator # so the code below can just deal with positive exponents n, d = rv.as_numer_denom() if d is not S.One: newn = TR14(n, first=False) newd = TR14(d, first=False) if newn != n or newd != d: rv = newn/newd return rv other = [] process = [] for a in rv.args: if a.is_Pow: b, e = a.as_base_exp() if not (e.is_integer or b.is_positive): other.append(a) continue a = b else: e = S.One m = as_f_sign_1(a) if not m or m[1].func not in (cos, sin): if e is S.One: other.append(a) else: other.append(a**e) continue g, f, si = m process.append((g, e.is_Number, e, f, si, a)) # sort them to get like terms next to each other process = list(ordered(process)) # keep track of whether there was any change nother = len(other) # access keys keys = (g, t, e, f, si, a) = list(range(6)) while process: A = process.pop(0) if process: B = process[0] if A[e].is_Number and B[e].is_Number: # both exponents are numbers if A[f] == B[f]: if A[si] != B[si]: B = process.pop(0) take = min(A[e], B[e]) # reinsert any remainder # the B will likely sort after A so check it first if B[e] != take: rem = [B[i] for i in keys] rem[e] -= take process.insert(0, rem) elif A[e] != take: rem = [A[i] for i in keys] rem[e] -= take process.insert(0, rem) if isinstance(A[f], cos): t = sin else: t = cos other.append((-A[g]*B[g]*t(A[f].args[0])**2)**take) continue elif A[e] == B[e]: # both exponents are equal symbols if A[f] == B[f]: if A[si] != B[si]: B = process.pop(0) take = A[e] if isinstance(A[f], cos): t = sin else: t = cos other.append((-A[g]*B[g]*t(A[f].args[0])**2)**take) continue # either we are done or neither condition above applied other.append(A[a]**A[e]) if len(other) != nother: rv = Mul(*other) return rv return bottom_up(rv, f) def TR15(rv, max=4, pow=False): """Convert sin(x)**-2 to 1 + cot(x)**2. See _TR56 docstring for advanced use of ``max`` and ``pow``. Examples ======== >>> from sympy.simplify.fu import TR15 >>> from sympy.abc import x >>> from sympy import sin >>> TR15(1 - 1/sin(x)**2) -cot(x)**2 """ def f(rv): if not (isinstance(rv, Pow) and isinstance(rv.base, sin)): return rv e = rv.exp if e % 2 == 1: return TR15(rv.base**(e + 1))/rv.base ia = 1/rv a = _TR56(ia, sin, cot, lambda x: 1 + x, max=max, pow=pow) if a != ia: rv = a return rv return bottom_up(rv, f) def TR16(rv, max=4, pow=False): """Convert cos(x)**-2 to 1 + tan(x)**2. See _TR56 docstring for advanced use of ``max`` and ``pow``. Examples ======== >>> from sympy.simplify.fu import TR16 >>> from sympy.abc import x >>> from sympy import cos >>> TR16(1 - 1/cos(x)**2) -tan(x)**2 """ def f(rv): if not (isinstance(rv, Pow) and isinstance(rv.base, cos)): return rv e = rv.exp if e % 2 == 1: return TR15(rv.base**(e + 1))/rv.base ia = 1/rv a = _TR56(ia, cos, tan, lambda x: 1 + x, max=max, pow=pow) if a != ia: rv = a return rv return bottom_up(rv, f) def TR111(rv): """Convert f(x)**-i to g(x)**i where either ``i`` is an integer or the base is positive and f, g are: tan, cot; sin, csc; or cos, sec. Examples ======== >>> from sympy.simplify.fu import TR111 >>> from sympy.abc import x >>> from sympy import tan >>> TR111(1 - 1/tan(x)**2) 1 - cot(x)**2 """ def f(rv): if not ( isinstance(rv, Pow) and (rv.base.is_positive or rv.exp.is_integer and rv.exp.is_negative)): return rv if isinstance(rv.base, tan): return cot(rv.base.args[0])**-rv.exp elif isinstance(rv.base, sin): return csc(rv.base.args[0])**-rv.exp elif isinstance(rv.base, cos): return sec(rv.base.args[0])**-rv.exp return rv return bottom_up(rv, f) def TR22(rv, max=4, pow=False): """Convert tan(x)**2 to sec(x)**2 - 1 and cot(x)**2 to csc(x)**2 - 1. See _TR56 docstring for advanced use of ``max`` and ``pow``. Examples ======== >>> from sympy.simplify.fu import TR22 >>> from sympy.abc import x >>> from sympy import tan, cot >>> TR22(1 + tan(x)**2) sec(x)**2 >>> TR22(1 + cot(x)**2) csc(x)**2 """ def f(rv): if not (isinstance(rv, Pow) and rv.base.func in (cot, tan)): return rv rv = _TR56(rv, tan, sec, lambda x: x - 1, max=max, pow=pow) rv = _TR56(rv, cot, csc, lambda x: x - 1, max=max, pow=pow) return rv return bottom_up(rv, f) def TRpower(rv): """Convert sin(x)**n and cos(x)**n with positive n to sums. Examples ======== >>> from sympy.simplify.fu import TRpower >>> from sympy.abc import x >>> from sympy import cos, sin >>> TRpower(sin(x)**6) -15*cos(2*x)/32 + 3*cos(4*x)/16 - cos(6*x)/32 + 5/16 >>> TRpower(sin(x)**3*cos(2*x)**4) (3*sin(x)/4 - sin(3*x)/4)*(cos(4*x)/2 + cos(8*x)/8 + 3/8) References ========== .. [1] https://en.wikipedia.org/wiki/List_of_trigonometric_identities#Power-reduction_formulae """ def f(rv): if not (isinstance(rv, Pow) and isinstance(rv.base, (sin, cos))): return rv b, n = rv.as_base_exp() x = b.args[0] if n.is_Integer and n.is_positive: if n.is_odd and isinstance(b, cos): rv = 2**(1-n)*Add(*[binomial(n, k)*cos((n - 2*k)*x) for k in range((n + 1)/2)]) elif n.is_odd and isinstance(b, sin): rv = 2**(1-n)*S.NegativeOne**((n-1)/2)*Add(*[binomial(n, k)* S.NegativeOne**k*sin((n - 2*k)*x) for k in range((n + 1)/2)]) elif n.is_even and isinstance(b, cos): rv = 2**(1-n)*Add(*[binomial(n, k)*cos((n - 2*k)*x) for k in range(n/2)]) elif n.is_even and isinstance(b, sin): rv = 2**(1-n)*S.NegativeOne**(n/2)*Add(*[binomial(n, k)* S.NegativeOne**k*cos((n - 2*k)*x) for k in range(n/2)]) if n.is_even: rv += 2**(-n)*binomial(n, n/2) return rv return bottom_up(rv, f) def L(rv): """Return count of trigonometric functions in expression. Examples ======== >>> from sympy.simplify.fu import L >>> from sympy.abc import x >>> from sympy import cos, sin >>> L(cos(x)+sin(x)) 2 """ return S(rv.count(TrigonometricFunction)) # ============== end of basic Fu-like tools ===================== if SYMPY_DEBUG: (TR0, TR1, TR2, TR3, TR4, TR5, TR6, TR7, TR8, TR9, TR10, TR11, TR12, TR13, TR2i, TRmorrie, TR14, TR15, TR16, TR12i, TR111, TR22 )= list(map(debug, (TR0, TR1, TR2, TR3, TR4, TR5, TR6, TR7, TR8, TR9, TR10, TR11, TR12, TR13, TR2i, TRmorrie, TR14, TR15, TR16, TR12i, TR111, TR22))) # tuples are chains -- (f, g) -> lambda x: g(f(x)) # lists are choices -- [f, g] -> lambda x: min(f(x), g(x), key=objective) CTR1 = [(TR5, TR0), (TR6, TR0), identity] CTR2 = (TR11, [(TR5, TR0), (TR6, TR0), TR0]) CTR3 = [(TRmorrie, TR8, TR0), (TRmorrie, TR8, TR10i, TR0), identity] CTR4 = [(TR4, TR10i), identity] RL1 = (TR4, TR3, TR4, TR12, TR4, TR13, TR4, TR0) # XXX it's a little unclear how this one is to be implemented # see Fu paper of reference, page 7. What is the Union symbol referring to? # The diagram shows all these as one chain of transformations, but the # text refers to them being applied independently. Also, a break # if L starts to increase has not been implemented. RL2 = [ (TR4, TR3, TR10, TR4, TR3, TR11), (TR5, TR7, TR11, TR4), (CTR3, CTR1, TR9, CTR2, TR4, TR9, TR9, CTR4), identity, ] def fu(rv, measure=lambda x: (L(x), x.count_ops())): """Attempt to simplify expression by using transformation rules given in the algorithm by Fu et al. :func:`fu` will try to minimize the objective function ``measure``. By default this first minimizes the number of trig terms and then minimizes the number of total operations. Examples ======== >>> from sympy.simplify.fu import fu >>> from sympy import cos, sin, tan, pi, S, sqrt >>> from sympy.abc import x, y, a, b >>> fu(sin(50)**2 + cos(50)**2 + sin(pi/6)) 3/2 >>> fu(sqrt(6)*cos(x) + sqrt(2)*sin(x)) 2*sqrt(2)*sin(x + pi/3) CTR1 example >>> eq = sin(x)**4 - cos(y)**2 + sin(y)**2 + 2*cos(x)**2 >>> fu(eq) cos(x)**4 - 2*cos(y)**2 + 2 CTR2 example >>> fu(S.Half - cos(2*x)/2) sin(x)**2 CTR3 example >>> fu(sin(a)*(cos(b) - sin(b)) + cos(a)*(sin(b) + cos(b))) sqrt(2)*sin(a + b + pi/4) CTR4 example >>> fu(sqrt(3)*cos(x)/2 + sin(x)/2) sin(x + pi/3) Example 1 >>> fu(1-sin(2*x)**2/4-sin(y)**2-cos(x)**4) -cos(x)**2 + cos(y)**2 Example 2 >>> fu(cos(4*pi/9)) sin(pi/18) >>> fu(cos(pi/9)*cos(2*pi/9)*cos(3*pi/9)*cos(4*pi/9)) 1/16 Example 3 >>> fu(tan(7*pi/18)+tan(5*pi/18)-sqrt(3)*tan(5*pi/18)*tan(7*pi/18)) -sqrt(3) Objective function example >>> fu(sin(x)/cos(x)) # default objective function tan(x) >>> fu(sin(x)/cos(x), measure=lambda x: -x.count_ops()) # maximize op count sin(x)/cos(x) References ========== .. [1] https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.657.2478&rep=rep1&type=pdf """ fRL1 = greedy(RL1, measure) fRL2 = greedy(RL2, measure) was = rv rv = sympify(rv) if not isinstance(rv, Expr): return rv.func(*[fu(a, measure=measure) for a in rv.args]) rv = TR1(rv) if rv.has(tan, cot): rv1 = fRL1(rv) if (measure(rv1) < measure(rv)): rv = rv1 if rv.has(tan, cot): rv = TR2(rv) if rv.has(sin, cos): rv1 = fRL2(rv) rv2 = TR8(TRmorrie(rv1)) rv = min([was, rv, rv1, rv2], key=measure) return min(TR2i(rv), rv, key=measure) def process_common_addends(rv, do, key2=None, key1=True): """Apply ``do`` to addends of ``rv`` that (if ``key1=True``) share at least a common absolute value of their coefficient and the value of ``key2`` when applied to the argument. If ``key1`` is False ``key2`` must be supplied and will be the only key applied. """ # collect by absolute value of coefficient and key2 absc = defaultdict(list) if key1: for a in rv.args: c, a = a.as_coeff_Mul() if c < 0: c = -c a = -a # put the sign on `a` absc[(c, key2(a) if key2 else 1)].append(a) elif key2: for a in rv.args: absc[(S.One, key2(a))].append(a) else: raise ValueError('must have at least one key') args = [] hit = False for k in absc: v = absc[k] c, _ = k if len(v) > 1: e = Add(*v, evaluate=False) new = do(e) if new != e: e = new hit = True args.append(c*e) else: args.append(c*v[0]) if hit: rv = Add(*args) return rv fufuncs = ''' TR0 TR1 TR2 TR3 TR4 TR5 TR6 TR7 TR8 TR9 TR10 TR10i TR11 TR12 TR13 L TR2i TRmorrie TR12i TR14 TR15 TR16 TR111 TR22'''.split() FU = dict(list(zip(fufuncs, list(map(locals().get, fufuncs))))) def _roots(): global _ROOT2, _ROOT3, _invROOT3 _ROOT2, _ROOT3 = sqrt(2), sqrt(3) _invROOT3 = 1/_ROOT3 _ROOT2 = None def trig_split(a, b, two=False): """Return the gcd, s1, s2, a1, a2, bool where If two is False (default) then:: a + b = gcd*(s1*f(a1) + s2*f(a2)) where f = cos if bool else sin else: if bool, a + b was +/- cos(a1)*cos(a2) +/- sin(a1)*sin(a2) and equals n1*gcd*cos(a - b) if n1 == n2 else n1*gcd*cos(a + b) else a + b was +/- cos(a1)*sin(a2) +/- sin(a1)*cos(a2) and equals n1*gcd*sin(a + b) if n1 = n2 else n1*gcd*sin(b - a) Examples ======== >>> from sympy.simplify.fu import trig_split >>> from sympy.abc import x, y, z >>> from sympy import cos, sin, sqrt >>> trig_split(cos(x), cos(y)) (1, 1, 1, x, y, True) >>> trig_split(2*cos(x), -2*cos(y)) (2, 1, -1, x, y, True) >>> trig_split(cos(x)*sin(y), cos(y)*sin(y)) (sin(y), 1, 1, x, y, True) >>> trig_split(cos(x), -sqrt(3)*sin(x), two=True) (2, 1, -1, x, pi/6, False) >>> trig_split(cos(x), sin(x), two=True) (sqrt(2), 1, 1, x, pi/4, False) >>> trig_split(cos(x), -sin(x), two=True) (sqrt(2), 1, -1, x, pi/4, False) >>> trig_split(sqrt(2)*cos(x), -sqrt(6)*sin(x), two=True) (2*sqrt(2), 1, -1, x, pi/6, False) >>> trig_split(-sqrt(6)*cos(x), -sqrt(2)*sin(x), two=True) (-2*sqrt(2), 1, 1, x, pi/3, False) >>> trig_split(cos(x)/sqrt(6), sin(x)/sqrt(2), two=True) (sqrt(6)/3, 1, 1, x, pi/6, False) >>> trig_split(-sqrt(6)*cos(x)*sin(y), -sqrt(2)*sin(x)*sin(y), two=True) (-2*sqrt(2)*sin(y), 1, 1, x, pi/3, False) >>> trig_split(cos(x), sin(x)) >>> trig_split(cos(x), sin(z)) >>> trig_split(2*cos(x), -sin(x)) >>> trig_split(cos(x), -sqrt(3)*sin(x)) >>> trig_split(cos(x)*cos(y), sin(x)*sin(z)) >>> trig_split(cos(x)*cos(y), sin(x)*sin(y)) >>> trig_split(-sqrt(6)*cos(x), sqrt(2)*sin(x)*sin(y), two=True) """ global _ROOT2, _ROOT3, _invROOT3 if _ROOT2 is None: _roots() a, b = [Factors(i) for i in (a, b)] ua, ub = a.normal(b) gcd = a.gcd(b).as_expr() n1 = n2 = 1 if S.NegativeOne in ua.factors: ua = ua.quo(S.NegativeOne) n1 = -n1 elif S.NegativeOne in ub.factors: ub = ub.quo(S.NegativeOne) n2 = -n2 a, b = [i.as_expr() for i in (ua, ub)] def pow_cos_sin(a, two): """Return ``a`` as a tuple (r, c, s) such that ``a = (r or 1)*(c or 1)*(s or 1)``. Three arguments are returned (radical, c-factor, s-factor) as long as the conditions set by ``two`` are met; otherwise None is returned. If ``two`` is True there will be one or two non-None values in the tuple: c and s or c and r or s and r or s or c with c being a cosine function (if possible) else a sine, and s being a sine function (if possible) else oosine. If ``two`` is False then there will only be a c or s term in the tuple. ``two`` also require that either two cos and/or sin be present (with the condition that if the functions are the same the arguments are different or vice versa) or that a single cosine or a single sine be present with an optional radical. If the above conditions dictated by ``two`` are not met then None is returned. """ c = s = None co = S.One if a.is_Mul: co, a = a.as_coeff_Mul() if len(a.args) > 2 or not two: return None if a.is_Mul: args = list(a.args) else: args = [a] a = args.pop(0) if isinstance(a, cos): c = a elif isinstance(a, sin): s = a elif a.is_Pow and a.exp is S.Half: # autoeval doesn't allow -1/2 co *= a else: return None if args: b = args[0] if isinstance(b, cos): if c: s = b else: c = b elif isinstance(b, sin): if s: c = b else: s = b elif b.is_Pow and b.exp is S.Half: co *= b else: return None return co if co is not S.One else None, c, s elif isinstance(a, cos): c = a elif isinstance(a, sin): s = a if c is None and s is None: return co = co if co is not S.One else None return co, c, s # get the parts m = pow_cos_sin(a, two) if m is None: return coa, ca, sa = m m = pow_cos_sin(b, two) if m is None: return cob, cb, sb = m # check them if (not ca) and cb or ca and isinstance(ca, sin): coa, ca, sa, cob, cb, sb = cob, cb, sb, coa, ca, sa n1, n2 = n2, n1 if not two: # need cos(x) and cos(y) or sin(x) and sin(y) c = ca or sa s = cb or sb if not isinstance(c, s.func): return None return gcd, n1, n2, c.args[0], s.args[0], isinstance(c, cos) else: if not coa and not cob: if (ca and cb and sa and sb): if isinstance(ca, sa.func) is not isinstance(cb, sb.func): return args = {j.args for j in (ca, sa)} if not all(i.args in args for i in (cb, sb)): return return gcd, n1, n2, ca.args[0], sa.args[0], isinstance(ca, sa.func) if ca and sa or cb and sb or \ two and (ca is None and sa is None or cb is None and sb is None): return c = ca or sa s = cb or sb if c.args != s.args: return if not coa: coa = S.One if not cob: cob = S.One if coa is cob: gcd *= _ROOT2 return gcd, n1, n2, c.args[0], pi/4, False elif coa/cob == _ROOT3: gcd *= 2*cob return gcd, n1, n2, c.args[0], pi/3, False elif coa/cob == _invROOT3: gcd *= 2*coa return gcd, n1, n2, c.args[0], pi/6, False def as_f_sign_1(e): """If ``e`` is a sum that can be written as ``g*(a + s)`` where ``s`` is ``+/-1``, return ``g``, ``a``, and ``s`` where ``a`` does not have a leading negative coefficient. Examples ======== >>> from sympy.simplify.fu import as_f_sign_1 >>> from sympy.abc import x >>> as_f_sign_1(x + 1) (1, x, 1) >>> as_f_sign_1(x - 1) (1, x, -1) >>> as_f_sign_1(-x + 1) (-1, x, -1) >>> as_f_sign_1(-x - 1) (-1, x, 1) >>> as_f_sign_1(2*x + 2) (2, x, 1) """ if not e.is_Add or len(e.args) != 2: return # exact match a, b = e.args if a in (S.NegativeOne, S.One): g = S.One if b.is_Mul and b.args[0].is_Number and b.args[0] < 0: a, b = -a, -b g = -g return g, b, a # gcd match a, b = [Factors(i) for i in e.args] ua, ub = a.normal(b) gcd = a.gcd(b).as_expr() if S.NegativeOne in ua.factors: ua = ua.quo(S.NegativeOne) n1 = -1 n2 = 1 elif S.NegativeOne in ub.factors: ub = ub.quo(S.NegativeOne) n1 = 1 n2 = -1 else: n1 = n2 = 1 a, b = [i.as_expr() for i in (ua, ub)] if a is S.One: a, b = b, a n1, n2 = n2, n1 if n1 == -1: gcd = -gcd n2 = -n2 if b is S.One: return gcd, a, n2 def _osborne(e, d): """Replace all hyperbolic functions with trig functions using the Osborne rule. Notes ===== ``d`` is a dummy variable to prevent automatic evaluation of trigonometric/hyperbolic functions. References ========== .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function """ def f(rv): if not isinstance(rv, HyperbolicFunction): return rv a = rv.args[0] a = a*d if not a.is_Add else Add._from_args([i*d for i in a.args]) if isinstance(rv, sinh): return I*sin(a) elif isinstance(rv, cosh): return cos(a) elif isinstance(rv, tanh): return I*tan(a) elif isinstance(rv, coth): return cot(a)/I elif isinstance(rv, sech): return sec(a) elif isinstance(rv, csch): return csc(a)/I else: raise NotImplementedError('unhandled %s' % rv.func) return bottom_up(e, f) def _osbornei(e, d): """Replace all trig functions with hyperbolic functions using the Osborne rule. Notes ===== ``d`` is a dummy variable to prevent automatic evaluation of trigonometric/hyperbolic functions. References ========== .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function """ def f(rv): if not isinstance(rv, TrigonometricFunction): return rv const, x = rv.args[0].as_independent(d, as_Add=True) a = x.xreplace({d: S.One}) + const*I if isinstance(rv, sin): return sinh(a)/I elif isinstance(rv, cos): return cosh(a) elif isinstance(rv, tan): return tanh(a)/I elif isinstance(rv, cot): return coth(a)*I elif isinstance(rv, sec): return sech(a) elif isinstance(rv, csc): return csch(a)*I else: raise NotImplementedError('unhandled %s' % rv.func) return bottom_up(e, f) def hyper_as_trig(rv): """Return an expression containing hyperbolic functions in terms of trigonometric functions. Any trigonometric functions initially present are replaced with Dummy symbols and the function to undo the masking and the conversion back to hyperbolics is also returned. It should always be true that:: t, f = hyper_as_trig(expr) expr == f(t) Examples ======== >>> from sympy.simplify.fu import hyper_as_trig, fu >>> from sympy.abc import x >>> from sympy import cosh, sinh >>> eq = sinh(x)**2 + cosh(x)**2 >>> t, f = hyper_as_trig(eq) >>> f(fu(t)) cosh(2*x) References ========== .. [1] https://en.wikipedia.org/wiki/Hyperbolic_function """ from sympy.simplify.simplify import signsimp from sympy.simplify.radsimp import collect # mask off trig functions trigs = rv.atoms(TrigonometricFunction) reps = [(t, Dummy()) for t in trigs] masked = rv.xreplace(dict(reps)) # get inversion substitutions in place reps = [(v, k) for k, v in reps] d = Dummy() return _osborne(masked, d), lambda x: collect(signsimp( _osbornei(x, d).xreplace(dict(reps))), S.ImaginaryUnit) def sincos_to_sum(expr): """Convert products and powers of sin and cos to sums. Explanation =========== Applied power reduction TRpower first, then expands products, and converts products to sums with TR8. Examples ======== >>> from sympy.simplify.fu import sincos_to_sum >>> from sympy.abc import x >>> from sympy import cos, sin >>> sincos_to_sum(16*sin(x)**3*cos(2*x)**2) 7*sin(x) - 5*sin(3*x) + 3*sin(5*x) - sin(7*x) """ if not expr.has(cos, sin): return expr else: return TR8(expand_mul(TRpower(expr)))
834643a32c3f104d15ee0d1d2dd79eaf3a1fd16ceb0fd0c3f608530cb2dbaf8a
from typing import Any, Set as tSet from functools import reduce from itertools import permutations from sympy.combinatorics import Permutation from sympy.core import ( Basic, Expr, Function, diff, Pow, Mul, Add, Lambda, S, Tuple, Dict ) from sympy.core.cache import cacheit from sympy.core.symbol import Symbol, Dummy from sympy.core.symbol import Str from sympy.core.sympify import _sympify from sympy.functions import factorial from sympy.matrices import ImmutableDenseMatrix as Matrix from sympy.solvers import solve from sympy.utilities.exceptions import SymPyDeprecationWarning # TODO you are a bit excessive in the use of Dummies # TODO dummy point, literal field # TODO too often one needs to call doit or simplify on the output, check the # tests and find out why from sympy.tensor.array import ImmutableDenseNDimArray class Manifold(Basic): """ A mathematical manifold. Explanation =========== A manifold is a topological space that locally resembles Euclidean space near each point [1]. This class does not provide any means to study the topological characteristics of the manifold that it represents, though. Parameters ========== name : str The name of the manifold. dim : int The dimension of the manifold. Examples ======== >>> from sympy.diffgeom import Manifold >>> m = Manifold('M', 2) >>> m M >>> m.dim 2 References ========== .. [1] https://en.wikipedia.org/wiki/Manifold """ def __new__(cls, name, dim, **kwargs): if not isinstance(name, Str): name = Str(name) dim = _sympify(dim) obj = super().__new__(cls, name, dim) obj.patches = _deprecated_list( "Manifold.patches", "external container for registry", 19321, "1.7", [] ) return obj @property def name(self): return self.args[0] @property def dim(self): return self.args[1] class Patch(Basic): """ A patch on a manifold. Explanation =========== Coordinate patch, or patch in short, is a simply-connected open set around a point in the manifold [1]. On a manifold one can have many patches that do not always include the whole manifold. On these patches coordinate charts can be defined that permit the parameterization of any point on the patch in terms of a tuple of real numbers (the coordinates). This class does not provide any means to study the topological characteristics of the patch that it represents. Parameters ========== name : str The name of the patch. manifold : Manifold The manifold on which the patch is defined. Examples ======== >>> from sympy.diffgeom import Manifold, Patch >>> m = Manifold('M', 2) >>> p = Patch('P', m) >>> p P >>> p.dim 2 References ========== .. [1] G. Sussman, J. Wisdom, W. Farr, Functional Differential Geometry (2013) """ def __new__(cls, name, manifold, **kwargs): if not isinstance(name, Str): name = Str(name) obj = super().__new__(cls, name, manifold) obj.manifold.patches.append(obj) # deprecated obj.coord_systems = _deprecated_list( "Patch.coord_systems", "external container for registry", 19321, "1.7", [] ) return obj @property def name(self): return self.args[0] @property def manifold(self): return self.args[1] @property def dim(self): return self.manifold.dim class CoordSystem(Basic): """ A coordinate system defined on the patch. Explanation =========== Coordinate system is a system that uses one or more coordinates to uniquely determine the position of the points or other geometric elements on a manifold [1]. By passing ``Symbols`` to *symbols* parameter, user can define the name and assumptions of coordinate symbols of the coordinate system. If not passed, these symbols are generated automatically and are assumed to be real valued. By passing *relations* parameter, user can define the tranform relations of coordinate systems. Inverse transformation and indirect transformation can be found automatically. If this parameter is not passed, coordinate transformation cannot be done. Parameters ========== name : str The name of the coordinate system. patch : Patch The patch where the coordinate system is defined. symbols : list of Symbols, optional Defines the names and assumptions of coordinate symbols. relations : dict, optional Key is a tuple of two strings, who are the names of the systems where the coordinates transform from and transform to. Value is a tuple of the symbols before transformation and a tuple of the expressions after transformation. Examples ======== We define two-dimensional Cartesian coordinate system and polar coordinate system. >>> from sympy import symbols, pi, sqrt, atan2, cos, sin >>> from sympy.diffgeom import Manifold, Patch, CoordSystem >>> m = Manifold('M', 2) >>> p = Patch('P', m) >>> x, y = symbols('x y', real=True) >>> r, theta = symbols('r theta', nonnegative=True) >>> relation_dict = { ... ('Car2D', 'Pol'): [(x, y), (sqrt(x**2 + y**2), atan2(y, x))], ... ('Pol', 'Car2D'): [(r, theta), (r*cos(theta), r*sin(theta))] ... } >>> Car2D = CoordSystem('Car2D', p, (x, y), relation_dict) >>> Pol = CoordSystem('Pol', p, (r, theta), relation_dict) ``symbols`` property returns ``CoordinateSymbol`` instances. These symbols are not same with the symbols used to construct the coordinate system. >>> Car2D Car2D >>> Car2D.dim 2 >>> Car2D.symbols (x, y) >>> _[0].func <class 'sympy.diffgeom.diffgeom.CoordinateSymbol'> ``transformation()`` method returns the transformation function from one coordinate system to another. ``transform()`` method returns the transformed coordinates. >>> Car2D.transformation(Pol) Lambda((x, y), Matrix([ [sqrt(x**2 + y**2)], [ atan2(y, x)]])) >>> Car2D.transform(Pol) Matrix([ [sqrt(x**2 + y**2)], [ atan2(y, x)]]) >>> Car2D.transform(Pol, [1, 2]) Matrix([ [sqrt(5)], [atan(2)]]) ``jacobian()`` method returns the Jacobian matrix of coordinate transformation between two systems. ``jacobian_determinant()`` method returns the Jacobian determinant of coordinate transformation between two systems. >>> Pol.jacobian(Car2D) Matrix([ [cos(theta), -r*sin(theta)], [sin(theta), r*cos(theta)]]) >>> Pol.jacobian(Car2D, [1, pi/2]) Matrix([ [0, -1], [1, 0]]) >>> Car2D.jacobian_determinant(Pol) 1/sqrt(x**2 + y**2) >>> Car2D.jacobian_determinant(Pol, [1,0]) 1 References ========== .. [1] https://en.wikipedia.org/wiki/Coordinate_system """ def __new__(cls, name, patch, symbols=None, relations={}, **kwargs): if not isinstance(name, Str): name = Str(name) # canonicallize the symbols if symbols is None: names = kwargs.get('names', None) if names is None: symbols = Tuple( *[Symbol('%s_%s' % (name.name, i), real=True) for i in range(patch.dim)] ) else: SymPyDeprecationWarning( feature="Class signature 'names' of CoordSystem", useinstead="class signature 'symbols'", issue=19321, deprecated_since_version="1.7" ).warn() symbols = Tuple( *[Symbol(n, real=True) for n in names] ) else: syms = [] for s in symbols: if isinstance(s, Symbol): syms.append(Symbol(s.name, **s._assumptions.generator)) elif isinstance(s, str): SymPyDeprecationWarning( feature="Passing str as coordinate symbol's name", useinstead="Symbol which contains the name and assumption for coordinate symbol", issue=19321, deprecated_since_version="1.7" ).warn() syms.append(Symbol(s, real=True)) symbols = Tuple(*syms) # canonicallize the relations rel_temp = {} for k,v in relations.items(): s1, s2 = k if not isinstance(s1, Str): s1 = Str(s1) if not isinstance(s2, Str): s2 = Str(s2) key = Tuple(s1, s2) # Old version used Lambda as a value. if isinstance(v, Lambda): v = (tuple(v.signature), tuple(v.expr)) else: v = (tuple(v[0]), tuple(v[1])) rel_temp[key] = v relations = Dict(rel_temp) # construct the object obj = super().__new__(cls, name, patch, symbols, relations) # Add deprecated attributes obj.transforms = _deprecated_dict( "Mutable CoordSystem.transforms", "'relations' parameter in class signature", 19321, "1.7", {} ) obj._names = [str(n) for n in symbols] obj.patch.coord_systems.append(obj) # deprecated obj._dummies = [Dummy(str(n)) for n in symbols] # deprecated obj._dummy = Dummy() return obj @property def name(self): return self.args[0] @property def patch(self): return self.args[1] @property def manifold(self): return self.patch.manifold @property def symbols(self): return tuple(CoordinateSymbol(self, i, **s._assumptions.generator) for i,s in enumerate(self.args[2])) @property def relations(self): return self.args[3] @property def dim(self): return self.patch.dim ########################################################################## # Finding transformation relation ########################################################################## def transformation(self, sys): """ Return coordinate transformation function from *self* to *sys*. Parameters ========== sys : CoordSystem Returns ======= sympy.Lambda Examples ======== >>> from sympy.diffgeom.rn import R2_r, R2_p >>> R2_r.transformation(R2_p) Lambda((x, y), Matrix([ [sqrt(x**2 + y**2)], [ atan2(y, x)]])) """ signature = self.args[2] key = Tuple(self.name, sys.name) if self == sys: expr = Matrix(self.symbols) elif key in self.relations: expr = Matrix(self.relations[key][1]) elif key[::-1] in self.relations: expr = Matrix(self._inverse_transformation(sys, self)) else: expr = Matrix(self._indirect_transformation(self, sys)) return Lambda(signature, expr) @staticmethod def _solve_inverse(sym1, sym2, exprs, sys1_name, sys2_name): ret = solve( [t[0] - t[1] for t in zip(sym2, exprs)], list(sym1), dict=True) if len(ret) == 0: temp = "Cannot solve inverse relation from {} to {}." raise NotImplementedError(temp.format(sys1_name, sys2_name)) elif len(ret) > 1: temp = "Obtained multiple inverse relation from {} to {}." raise ValueError(temp.format(sys1_name, sys2_name)) return ret[0] @classmethod def _inverse_transformation(cls, sys1, sys2): # Find the transformation relation from sys2 to sys1 forward = sys1.transform(sys2) inv_results = cls._solve_inverse(sys1.symbols, sys2.symbols, forward, sys1.name, sys2.name) signature = tuple(sys1.symbols) return [inv_results[s] for s in signature] @classmethod @cacheit def _indirect_transformation(cls, sys1, sys2): # Find the transformation relation between two indirectly connected # coordinate systems rel = sys1.relations path = cls._dijkstra(sys1, sys2) transforms = [] for s1, s2 in zip(path, path[1:]): if (s1, s2) in rel: transforms.append(rel[(s1, s2)]) else: sym2, inv_exprs = rel[(s2, s1)] sym1 = tuple(Dummy() for i in sym2) ret = cls._solve_inverse(sym2, sym1, inv_exprs, s2, s1) ret = tuple(ret[s] for s in sym2) transforms.append((sym1, ret)) syms = sys1.args[2] exprs = syms for newsyms, newexprs in transforms: exprs = tuple(e.subs(zip(newsyms, exprs)) for e in newexprs) return exprs @staticmethod def _dijkstra(sys1, sys2): # Use Dijkstra algorithm to find the shortest path between two indirectly-connected # coordinate systems # return value is the list of the names of the systems. relations = sys1.relations graph = {} for s1, s2 in relations.keys(): if s1 not in graph: graph[s1] = {s2} else: graph[s1].add(s2) if s2 not in graph: graph[s2] = {s1} else: graph[s2].add(s1) path_dict = {sys:[0, [], 0] for sys in graph} # minimum distance, path, times of visited def visit(sys): path_dict[sys][2] = 1 for newsys in graph[sys]: distance = path_dict[sys][0] + 1 if path_dict[newsys][0] >= distance or not path_dict[newsys][1]: path_dict[newsys][0] = distance path_dict[newsys][1] = [i for i in path_dict[sys][1]] path_dict[newsys][1].append(sys) visit(sys1.name) while True: min_distance = max(path_dict.values(), key=lambda x:x[0])[0] newsys = None for sys, lst in path_dict.items(): if 0 < lst[0] <= min_distance and not lst[2]: min_distance = lst[0] newsys = sys if newsys is None: break visit(newsys) result = path_dict[sys2.name][1] result.append(sys2.name) if result == [sys2.name]: raise KeyError("Two coordinate systems are not connected.") return result def connect_to(self, to_sys, from_coords, to_exprs, inverse=True, fill_in_gaps=False): SymPyDeprecationWarning( feature="CoordSystem.connect_to", useinstead="new instance generated with new 'transforms' parameter", issue=19321, deprecated_since_version="1.7" ).warn() from_coords, to_exprs = dummyfy(from_coords, to_exprs) self.transforms[to_sys] = Matrix(from_coords), Matrix(to_exprs) if inverse: to_sys.transforms[self] = self._inv_transf(from_coords, to_exprs) if fill_in_gaps: self._fill_gaps_in_transformations() @staticmethod def _inv_transf(from_coords, to_exprs): # Will be removed when connect_to is removed inv_from = [i.as_dummy() for i in from_coords] inv_to = solve( [t[0] - t[1] for t in zip(inv_from, to_exprs)], list(from_coords), dict=True)[0] inv_to = [inv_to[fc] for fc in from_coords] return Matrix(inv_from), Matrix(inv_to) @staticmethod def _fill_gaps_in_transformations(): # Will be removed when connect_to is removed raise NotImplementedError ########################################################################## # Coordinate transformations ########################################################################## def transform(self, sys, coordinates=None): """ Return the result of coordinate transformation from *self* to *sys*. If coordinates are not given, coordinate symbols of *self* are used. Parameters ========== sys : CoordSystem coordinates : Any iterable, optional. Returns ======= sympy.ImmutableDenseMatrix containing CoordinateSymbol Examples ======== >>> from sympy.diffgeom.rn import R2_r, R2_p >>> R2_r.transform(R2_p) Matrix([ [sqrt(x**2 + y**2)], [ atan2(y, x)]]) >>> R2_r.transform(R2_p, [0, 1]) Matrix([ [ 1], [pi/2]]) """ if coordinates is None: coordinates = self.symbols if self != sys: transf = self.transformation(sys) coordinates = transf(*coordinates) else: coordinates = Matrix(coordinates) return coordinates def coord_tuple_transform_to(self, to_sys, coords): """Transform ``coords`` to coord system ``to_sys``.""" SymPyDeprecationWarning( feature="CoordSystem.coord_tuple_transform_to", useinstead="CoordSystem.transform", issue=19321, deprecated_since_version="1.7" ).warn() coords = Matrix(coords) if self != to_sys: transf = self.transforms[to_sys] coords = transf[1].subs(list(zip(transf[0], coords))) return coords def jacobian(self, sys, coordinates=None): """ Return the jacobian matrix of a transformation on given coordinates. If coordinates are not given, coordinate symbols of *self* are used. Parameters ========== sys : CoordSystem coordinates : Any iterable, optional. Returns ======= sympy.ImmutableDenseMatrix Examples ======== >>> from sympy.diffgeom.rn import R2_r, R2_p >>> R2_p.jacobian(R2_r) Matrix([ [cos(theta), -rho*sin(theta)], [sin(theta), rho*cos(theta)]]) >>> R2_p.jacobian(R2_r, [1, 0]) Matrix([ [1, 0], [0, 1]]) """ result = self.transform(sys).jacobian(self.symbols) if coordinates is not None: result = result.subs(list(zip(self.symbols, coordinates))) return result jacobian_matrix = jacobian def jacobian_determinant(self, sys, coordinates=None): """ Return the jacobian determinant of a transformation on given coordinates. If coordinates are not given, coordinate symbols of *self* are used. Parameters ========== sys : CoordSystem coordinates : Any iterable, optional. Returns ======= sympy.Expr Examples ======== >>> from sympy.diffgeom.rn import R2_r, R2_p >>> R2_r.jacobian_determinant(R2_p) 1/sqrt(x**2 + y**2) >>> R2_r.jacobian_determinant(R2_p, [1, 0]) 1 """ return self.jacobian(sys, coordinates).det() ########################################################################## # Points ########################################################################## def point(self, coords): """Create a ``Point`` with coordinates given in this coord system.""" return Point(self, coords) def point_to_coords(self, point): """Calculate the coordinates of a point in this coord system.""" return point.coords(self) ########################################################################## # Base fields. ########################################################################## def base_scalar(self, coord_index): """Return ``BaseScalarField`` that takes a point and returns one of the coordinates.""" return BaseScalarField(self, coord_index) coord_function = base_scalar def base_scalars(self): """Returns a list of all coordinate functions. For more details see the ``base_scalar`` method of this class.""" return [self.base_scalar(i) for i in range(self.dim)] coord_functions = base_scalars def base_vector(self, coord_index): """Return a basis vector field. The basis vector field for this coordinate system. It is also an operator on scalar fields.""" return BaseVectorField(self, coord_index) def base_vectors(self): """Returns a list of all base vectors. For more details see the ``base_vector`` method of this class.""" return [self.base_vector(i) for i in range(self.dim)] def base_oneform(self, coord_index): """Return a basis 1-form field. The basis one-form field for this coordinate system. It is also an operator on vector fields.""" return Differential(self.coord_function(coord_index)) def base_oneforms(self): """Returns a list of all base oneforms. For more details see the ``base_oneform`` method of this class.""" return [self.base_oneform(i) for i in range(self.dim)] class CoordinateSymbol(Symbol): """A symbol which denotes an abstract value of i-th coordinate of the coordinate system with given context. Explanation =========== Each coordinates in coordinate system are represented by unique symbol, such as x, y, z in Cartesian coordinate system. You may not construct this class directly. Instead, use `symbols` method of CoordSystem. Parameters ========== coord_sys : CoordSystem index : integer Examples ======== >>> from sympy import symbols, Lambda, Matrix, sqrt, atan2, cos, sin >>> from sympy.diffgeom import Manifold, Patch, CoordSystem >>> m = Manifold('M', 2) >>> p = Patch('P', m) >>> x, y = symbols('x y', real=True) >>> r, theta = symbols('r theta', nonnegative=True) >>> relation_dict = { ... ('Car2D', 'Pol'): Lambda((x, y), Matrix([sqrt(x**2 + y**2), atan2(y, x)])), ... ('Pol', 'Car2D'): Lambda((r, theta), Matrix([r*cos(theta), r*sin(theta)])) ... } >>> Car2D = CoordSystem('Car2D', p, [x, y], relation_dict) >>> Pol = CoordSystem('Pol', p, [r, theta], relation_dict) >>> x, y = Car2D.symbols ``CoordinateSymbol`` contains its coordinate symbol and index. >>> x.name 'x' >>> x.coord_sys == Car2D True >>> x.index 0 >>> x.is_real True You can transform ``CoordinateSymbol`` into other coordinate system using ``rewrite()`` method. >>> x.rewrite(Pol) r*cos(theta) >>> sqrt(x**2 + y**2).rewrite(Pol).simplify() r """ def __new__(cls, coord_sys, index, **assumptions): name = coord_sys.args[2][index].name obj = super().__new__(cls, name, **assumptions) obj.coord_sys = coord_sys obj.index = index return obj def __getnewargs__(self): return (self.coord_sys, self.index) def _hashable_content(self): return ( self.coord_sys, self.index ) + tuple(sorted(self.assumptions0.items())) def _eval_rewrite(self, rule, args, **hints): if isinstance(rule, CoordSystem): return rule.transform(self.coord_sys)[self.index] return super()._eval_rewrite(rule, args, **hints) class Point(Basic): """Point defined in a coordinate system. Explanation =========== Mathematically, point is defined in the manifold and does not have any coordinates by itself. Coordinate system is what imbues the coordinates to the point by coordinate chart. However, due to the difficulty of realizing such logic, you must supply a coordinate system and coordinates to define a Point here. The usage of this object after its definition is independent of the coordinate system that was used in order to define it, however due to limitations in the simplification routines you can arrive at complicated expressions if you use inappropriate coordinate systems. Parameters ========== coord_sys : CoordSystem coords : list The coordinates of the point. Examples ======== >>> from sympy import pi >>> from sympy.diffgeom import Point >>> from sympy.diffgeom.rn import R2, R2_r, R2_p >>> rho, theta = R2_p.symbols >>> p = Point(R2_p, [rho, 3*pi/4]) >>> p.manifold == R2 True >>> p.coords() Matrix([ [ rho], [3*pi/4]]) >>> p.coords(R2_r) Matrix([ [-sqrt(2)*rho/2], [ sqrt(2)*rho/2]]) """ def __new__(cls, coord_sys, coords, **kwargs): coords = Matrix(coords) obj = super().__new__(cls, coord_sys, coords) obj._coord_sys = coord_sys obj._coords = coords return obj @property def patch(self): return self._coord_sys.patch @property def manifold(self): return self._coord_sys.manifold @property def dim(self): return self.manifold.dim def coords(self, sys=None): """ Coordinates of the point in given coordinate system. If coordinate system is not passed, it returns the coordinates in the coordinate system in which the poin was defined. """ if sys is None: return self._coords else: return self._coord_sys.transform(sys, self._coords) @property def free_symbols(self): return self._coords.free_symbols class BaseScalarField(Expr): """Base scalar field over a manifold for a given coordinate system. Explanation =========== A scalar field takes a point as an argument and returns a scalar. A base scalar field of a coordinate system takes a point and returns one of the coordinates of that point in the coordinate system in question. To define a scalar field you need to choose the coordinate system and the index of the coordinate. The use of the scalar field after its definition is independent of the coordinate system in which it was defined, however due to limitations in the simplification routines you may arrive at more complicated expression if you use unappropriate coordinate systems. You can build complicated scalar fields by just building up SymPy expressions containing ``BaseScalarField`` instances. Parameters ========== coord_sys : CoordSystem index : integer Examples ======== >>> from sympy import Function, pi >>> from sympy.diffgeom import BaseScalarField >>> from sympy.diffgeom.rn import R2_r, R2_p >>> rho, _ = R2_p.symbols >>> point = R2_p.point([rho, 0]) >>> fx, fy = R2_r.base_scalars() >>> ftheta = BaseScalarField(R2_r, 1) >>> fx(point) rho >>> fy(point) 0 >>> (fx**2+fy**2).rcall(point) rho**2 >>> g = Function('g') >>> fg = g(ftheta-pi) >>> fg.rcall(point) g(-pi) """ is_commutative = True def __new__(cls, coord_sys, index, **kwargs): index = _sympify(index) obj = super().__new__(cls, coord_sys, index) obj._coord_sys = coord_sys obj._index = index return obj @property def coord_sys(self): return self.args[0] @property def index(self): return self.args[1] @property def patch(self): return self.coord_sys.patch @property def manifold(self): return self.coord_sys.manifold @property def dim(self): return self.manifold.dim def __call__(self, *args): """Evaluating the field at a point or doing nothing. If the argument is a ``Point`` instance, the field is evaluated at that point. The field is returned itself if the argument is any other object. It is so in order to have working recursive calling mechanics for all fields (check the ``__call__`` method of ``Expr``). """ point = args[0] if len(args) != 1 or not isinstance(point, Point): return self coords = point.coords(self._coord_sys) # XXX Calling doit is necessary with all the Subs expressions # XXX Calling simplify is necessary with all the trig expressions return simplify(coords[self._index]).doit() # XXX Workaround for limitations on the content of args free_symbols = set() # type: tSet[Any] def doit(self): return self class BaseVectorField(Expr): r"""Base vector field over a manifold for a given coordinate system. Explanation =========== A vector field is an operator taking a scalar field and returning a directional derivative (which is also a scalar field). A base vector field is the same type of operator, however the derivation is specifically done with respect to a chosen coordinate. To define a base vector field you need to choose the coordinate system and the index of the coordinate. The use of the vector field after its definition is independent of the coordinate system in which it was defined, however due to limitations in the simplification routines you may arrive at more complicated expression if you use unappropriate coordinate systems. Parameters ========== coord_sys : CoordSystem index : integer Examples ======== >>> from sympy import Function >>> from sympy.diffgeom.rn import R2_p, R2_r >>> from sympy.diffgeom import BaseVectorField >>> from sympy import pprint >>> x, y = R2_r.symbols >>> rho, theta = R2_p.symbols >>> fx, fy = R2_r.base_scalars() >>> point_p = R2_p.point([rho, theta]) >>> point_r = R2_r.point([x, y]) >>> g = Function('g') >>> s_field = g(fx, fy) >>> v = BaseVectorField(R2_r, 1) >>> pprint(v(s_field)) / d \| |---(g(x, xi))|| \dxi /|xi=y >>> pprint(v(s_field).rcall(point_r).doit()) d --(g(x, y)) dy >>> pprint(v(s_field).rcall(point_p)) / d \| |---(g(rho*cos(theta), xi))|| \dxi /|xi=rho*sin(theta) """ is_commutative = False def __new__(cls, coord_sys, index, **kwargs): index = _sympify(index) obj = super().__new__(cls, coord_sys, index) obj._coord_sys = coord_sys obj._index = index return obj @property def coord_sys(self): return self.args[0] @property def index(self): return self.args[1] @property def patch(self): return self.coord_sys.patch @property def manifold(self): return self.coord_sys.manifold @property def dim(self): return self.manifold.dim def __call__(self, scalar_field): """Apply on a scalar field. The action of a vector field on a scalar field is a directional differentiation. If the argument is not a scalar field an error is raised. """ if covariant_order(scalar_field) or contravariant_order(scalar_field): raise ValueError('Only scalar fields can be supplied as arguments to vector fields.') if scalar_field is None: return self base_scalars = list(scalar_field.atoms(BaseScalarField)) # First step: e_x(x+r**2) -> e_x(x) + 2*r*e_x(r) d_var = self._coord_sys._dummy # TODO: you need a real dummy function for the next line d_funcs = [Function('_#_%s' % i)(d_var) for i, b in enumerate(base_scalars)] d_result = scalar_field.subs(list(zip(base_scalars, d_funcs))) d_result = d_result.diff(d_var) # Second step: e_x(x) -> 1 and e_x(r) -> cos(atan2(x, y)) coords = self._coord_sys.symbols d_funcs_deriv = [f.diff(d_var) for f in d_funcs] d_funcs_deriv_sub = [] for b in base_scalars: jac = self._coord_sys.jacobian(b._coord_sys, coords) d_funcs_deriv_sub.append(jac[b._index, self._index]) d_result = d_result.subs(list(zip(d_funcs_deriv, d_funcs_deriv_sub))) # Remove the dummies result = d_result.subs(list(zip(d_funcs, base_scalars))) result = result.subs(list(zip(coords, self._coord_sys.coord_functions()))) return result.doit() def _find_coords(expr): # Finds CoordinateSystems existing in expr fields = expr.atoms(BaseScalarField, BaseVectorField) result = set() for f in fields: result.add(f._coord_sys) return result class Commutator(Expr): r"""Commutator of two vector fields. Explanation =========== The commutator of two vector fields `v_1` and `v_2` is defined as the vector field `[v_1, v_2]` that evaluated on each scalar field `f` is equal to `v_1(v_2(f)) - v_2(v_1(f))`. Examples ======== >>> from sympy.diffgeom.rn import R2_p, R2_r >>> from sympy.diffgeom import Commutator >>> from sympy import simplify >>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> e_r = R2_p.base_vector(0) >>> c_xy = Commutator(e_x, e_y) >>> c_xr = Commutator(e_x, e_r) >>> c_xy 0 Unfortunately, the current code is not able to compute everything: >>> c_xr Commutator(e_x, e_rho) >>> simplify(c_xr(fy**2)) -2*cos(theta)*y**2/(x**2 + y**2) """ def __new__(cls, v1, v2): if (covariant_order(v1) or contravariant_order(v1) != 1 or covariant_order(v2) or contravariant_order(v2) != 1): raise ValueError( 'Only commutators of vector fields are supported.') if v1 == v2: return S.Zero coord_sys = set().union(*[_find_coords(v) for v in (v1, v2)]) if len(coord_sys) == 1: # Only one coordinate systems is used, hence it is easy enough to # actually evaluate the commutator. if all(isinstance(v, BaseVectorField) for v in (v1, v2)): return S.Zero bases_1, bases_2 = [list(v.atoms(BaseVectorField)) for v in (v1, v2)] coeffs_1 = [v1.expand().coeff(b) for b in bases_1] coeffs_2 = [v2.expand().coeff(b) for b in bases_2] res = 0 for c1, b1 in zip(coeffs_1, bases_1): for c2, b2 in zip(coeffs_2, bases_2): res += c1*b1(c2)*b2 - c2*b2(c1)*b1 return res else: obj = super().__new__(cls, v1, v2) obj._v1 = v1 # deprecated assignment obj._v2 = v2 # deprecated assignment return obj @property def v1(self): return self.args[0] @property def v2(self): return self.args[1] def __call__(self, scalar_field): """Apply on a scalar field. If the argument is not a scalar field an error is raised. """ return self.v1(self.v2(scalar_field)) - self.v2(self.v1(scalar_field)) class Differential(Expr): r"""Return the differential (exterior derivative) of a form field. Explanation =========== The differential of a form (i.e. the exterior derivative) has a complicated definition in the general case. The differential `df` of the 0-form `f` is defined for any vector field `v` as `df(v) = v(f)`. Examples ======== >>> from sympy import Function >>> from sympy.diffgeom.rn import R2_r >>> from sympy.diffgeom import Differential >>> from sympy import pprint >>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> g = Function('g') >>> s_field = g(fx, fy) >>> dg = Differential(s_field) >>> dg d(g(x, y)) >>> pprint(dg(e_x)) / d \| |---(g(xi, y))|| \dxi /|xi=x >>> pprint(dg(e_y)) / d \| |---(g(x, xi))|| \dxi /|xi=y Applying the exterior derivative operator twice always results in: >>> Differential(dg) 0 """ is_commutative = False def __new__(cls, form_field): if contravariant_order(form_field): raise ValueError( 'A vector field was supplied as an argument to Differential.') if isinstance(form_field, Differential): return S.Zero else: obj = super().__new__(cls, form_field) obj._form_field = form_field # deprecated assignment return obj @property def form_field(self): return self.args[0] def __call__(self, *vector_fields): """Apply on a list of vector_fields. Explanation =========== If the number of vector fields supplied is not equal to 1 + the order of the form field inside the differential the result is undefined. For 1-forms (i.e. differentials of scalar fields) the evaluation is done as `df(v)=v(f)`. However if `v` is ``None`` instead of a vector field, the differential is returned unchanged. This is done in order to permit partial contractions for higher forms. In the general case the evaluation is done by applying the form field inside the differential on a list with one less elements than the number of elements in the original list. Lowering the number of vector fields is achieved through replacing each pair of fields by their commutator. If the arguments are not vectors or ``None``s an error is raised. """ if any((contravariant_order(a) != 1 or covariant_order(a)) and a is not None for a in vector_fields): raise ValueError('The arguments supplied to Differential should be vector fields or Nones.') k = len(vector_fields) if k == 1: if vector_fields[0]: return vector_fields[0].rcall(self._form_field) return self else: # For higher form it is more complicated: # Invariant formula: # https://en.wikipedia.org/wiki/Exterior_derivative#Invariant_formula # df(v1, ... vn) = +/- vi(f(v1..no i..vn)) # +/- f([vi,vj],v1..no i, no j..vn) f = self._form_field v = vector_fields ret = 0 for i in range(k): t = v[i].rcall(f.rcall(*v[:i] + v[i + 1:])) ret += (-1)**i*t for j in range(i + 1, k): c = Commutator(v[i], v[j]) if c: # TODO this is ugly - the Commutator can be Zero and # this causes the next line to fail t = f.rcall(*(c,) + v[:i] + v[i + 1:j] + v[j + 1:]) ret += (-1)**(i + j)*t return ret class TensorProduct(Expr): """Tensor product of forms. Explanation =========== The tensor product permits the creation of multilinear functionals (i.e. higher order tensors) out of lower order fields (e.g. 1-forms and vector fields). However, the higher tensors thus created lack the interesting features provided by the other type of product, the wedge product, namely they are not antisymmetric and hence are not form fields. Examples ======== >>> from sympy.diffgeom.rn import R2_r >>> from sympy.diffgeom import TensorProduct >>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> dx, dy = R2_r.base_oneforms() >>> TensorProduct(dx, dy)(e_x, e_y) 1 >>> TensorProduct(dx, dy)(e_y, e_x) 0 >>> TensorProduct(dx, fx*dy)(fx*e_x, e_y) x**2 >>> TensorProduct(e_x, e_y)(fx**2, fy**2) 4*x*y >>> TensorProduct(e_y, dx)(fy) dx You can nest tensor products. >>> tp1 = TensorProduct(dx, dy) >>> TensorProduct(tp1, dx)(e_x, e_y, e_x) 1 You can make partial contraction for instance when 'raising an index'. Putting ``None`` in the second argument of ``rcall`` means that the respective position in the tensor product is left as it is. >>> TP = TensorProduct >>> metric = TP(dx, dx) + 3*TP(dy, dy) >>> metric.rcall(e_y, None) 3*dy Or automatically pad the args with ``None`` without specifying them. >>> metric.rcall(e_y) 3*dy """ def __new__(cls, *args): scalar = Mul(*[m for m in args if covariant_order(m) + contravariant_order(m) == 0]) multifields = [m for m in args if covariant_order(m) + contravariant_order(m)] if multifields: if len(multifields) == 1: return scalar*multifields[0] return scalar*super().__new__(cls, *multifields) else: return scalar def __call__(self, *fields): """Apply on a list of fields. If the number of input fields supplied is not equal to the order of the tensor product field, the list of arguments is padded with ``None``'s. The list of arguments is divided in sublists depending on the order of the forms inside the tensor product. The sublists are provided as arguments to these forms and the resulting expressions are given to the constructor of ``TensorProduct``. """ tot_order = covariant_order(self) + contravariant_order(self) tot_args = len(fields) if tot_args != tot_order: fields = list(fields) + [None]*(tot_order - tot_args) orders = [covariant_order(f) + contravariant_order(f) for f in self._args] indices = [sum(orders[:i + 1]) for i in range(len(orders) - 1)] fields = [fields[i:j] for i, j in zip([0] + indices, indices + [None])] multipliers = [t[0].rcall(*t[1]) for t in zip(self._args, fields)] return TensorProduct(*multipliers) class WedgeProduct(TensorProduct): """Wedge product of forms. Explanation =========== In the context of integration only completely antisymmetric forms make sense. The wedge product permits the creation of such forms. Examples ======== >>> from sympy.diffgeom.rn import R2_r >>> from sympy.diffgeom import WedgeProduct >>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> dx, dy = R2_r.base_oneforms() >>> WedgeProduct(dx, dy)(e_x, e_y) 1 >>> WedgeProduct(dx, dy)(e_y, e_x) -1 >>> WedgeProduct(dx, fx*dy)(fx*e_x, e_y) x**2 >>> WedgeProduct(e_x, e_y)(fy, None) -e_x You can nest wedge products. >>> wp1 = WedgeProduct(dx, dy) >>> WedgeProduct(wp1, dx)(e_x, e_y, e_x) 0 """ # TODO the calculation of signatures is slow # TODO you do not need all these permutations (neither the prefactor) def __call__(self, *fields): """Apply on a list of vector_fields. The expression is rewritten internally in terms of tensor products and evaluated.""" orders = (covariant_order(e) + contravariant_order(e) for e in self.args) mul = 1/Mul(*(factorial(o) for o in orders)) perms = permutations(fields) perms_par = (Permutation( p).signature() for p in permutations(list(range(len(fields))))) tensor_prod = TensorProduct(*self.args) return mul*Add(*[tensor_prod(*p[0])*p[1] for p in zip(perms, perms_par)]) class LieDerivative(Expr): """Lie derivative with respect to a vector field. Explanation =========== The transport operator that defines the Lie derivative is the pushforward of the field to be derived along the integral curve of the field with respect to which one derives. Examples ======== >>> from sympy.diffgeom.rn import R2_r, R2_p >>> from sympy.diffgeom import (LieDerivative, TensorProduct) >>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> e_rho, e_theta = R2_p.base_vectors() >>> dx, dy = R2_r.base_oneforms() >>> LieDerivative(e_x, fy) 0 >>> LieDerivative(e_x, fx) 1 >>> LieDerivative(e_x, e_x) 0 The Lie derivative of a tensor field by another tensor field is equal to their commutator: >>> LieDerivative(e_x, e_rho) Commutator(e_x, e_rho) >>> LieDerivative(e_x + e_y, fx) 1 >>> tp = TensorProduct(dx, dy) >>> LieDerivative(e_x, tp) LieDerivative(e_x, TensorProduct(dx, dy)) >>> LieDerivative(e_x, tp) LieDerivative(e_x, TensorProduct(dx, dy)) """ def __new__(cls, v_field, expr): expr_form_ord = covariant_order(expr) if contravariant_order(v_field) != 1 or covariant_order(v_field): raise ValueError('Lie derivatives are defined only with respect to' ' vector fields. The supplied argument was not a ' 'vector field.') if expr_form_ord > 0: obj = super().__new__(cls, v_field, expr) # deprecated assignments obj._v_field = v_field obj._expr = expr return obj if expr.atoms(BaseVectorField): return Commutator(v_field, expr) else: return v_field.rcall(expr) @property def v_field(self): return self.args[0] @property def expr(self): return self.args[1] def __call__(self, *args): v = self.v_field expr = self.expr lead_term = v(expr(*args)) rest = Add(*[Mul(*args[:i] + (Commutator(v, args[i]),) + args[i + 1:]) for i in range(len(args))]) return lead_term - rest class BaseCovarDerivativeOp(Expr): """Covariant derivative operator with respect to a base vector. Examples ======== >>> from sympy.diffgeom.rn import R2_r >>> from sympy.diffgeom import BaseCovarDerivativeOp >>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct >>> TP = TensorProduct >>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> dx, dy = R2_r.base_oneforms() >>> ch = metric_to_Christoffel_2nd(TP(dx, dx) + TP(dy, dy)) >>> ch [[[0, 0], [0, 0]], [[0, 0], [0, 0]]] >>> cvd = BaseCovarDerivativeOp(R2_r, 0, ch) >>> cvd(fx) 1 >>> cvd(fx*e_x) e_x """ def __new__(cls, coord_sys, index, christoffel): index = _sympify(index) christoffel = ImmutableDenseNDimArray(christoffel) obj = super().__new__(cls, coord_sys, index, christoffel) # deprecated assignments obj._coord_sys = coord_sys obj._index = index obj._christoffel = christoffel return obj @property def coord_sys(self): return self.args[0] @property def index(self): return self.args[1] @property def christoffel(self): return self.args[2] def __call__(self, field): """Apply on a scalar field. The action of a vector field on a scalar field is a directional differentiation. If the argument is not a scalar field the behaviour is undefined. """ if covariant_order(field) != 0: raise NotImplementedError() field = vectors_in_basis(field, self._coord_sys) wrt_vector = self._coord_sys.base_vector(self._index) wrt_scalar = self._coord_sys.coord_function(self._index) vectors = list(field.atoms(BaseVectorField)) # First step: replace all vectors with something susceptible to # derivation and do the derivation # TODO: you need a real dummy function for the next line d_funcs = [Function('_#_%s' % i)(wrt_scalar) for i, b in enumerate(vectors)] d_result = field.subs(list(zip(vectors, d_funcs))) d_result = wrt_vector(d_result) # Second step: backsubstitute the vectors in d_result = d_result.subs(list(zip(d_funcs, vectors))) # Third step: evaluate the derivatives of the vectors derivs = [] for v in vectors: d = Add(*[(self._christoffel[k, wrt_vector._index, v._index] *v._coord_sys.base_vector(k)) for k in range(v._coord_sys.dim)]) derivs.append(d) to_subs = [wrt_vector(d) for d in d_funcs] # XXX: This substitution can fail when there are Dummy symbols and the # cache is disabled: https://github.com/sympy/sympy/issues/17794 result = d_result.subs(list(zip(to_subs, derivs))) # Remove the dummies result = result.subs(list(zip(d_funcs, vectors))) return result.doit() class CovarDerivativeOp(Expr): """Covariant derivative operator. Examples ======== >>> from sympy.diffgeom.rn import R2_r >>> from sympy.diffgeom import CovarDerivativeOp >>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct >>> TP = TensorProduct >>> fx, fy = R2_r.base_scalars() >>> e_x, e_y = R2_r.base_vectors() >>> dx, dy = R2_r.base_oneforms() >>> ch = metric_to_Christoffel_2nd(TP(dx, dx) + TP(dy, dy)) >>> ch [[[0, 0], [0, 0]], [[0, 0], [0, 0]]] >>> cvd = CovarDerivativeOp(fx*e_x, ch) >>> cvd(fx) x >>> cvd(fx*e_x) x*e_x """ def __new__(cls, wrt, christoffel): if len({v._coord_sys for v in wrt.atoms(BaseVectorField)}) > 1: raise NotImplementedError() if contravariant_order(wrt) != 1 or covariant_order(wrt): raise ValueError('Covariant derivatives are defined only with ' 'respect to vector fields. The supplied argument ' 'was not a vector field.') christoffel = ImmutableDenseNDimArray(christoffel) obj = super().__new__(cls, wrt, christoffel) # deprecated assigments obj._wrt = wrt obj._christoffel = christoffel return obj @property def wrt(self): return self.args[0] @property def christoffel(self): return self.args[1] def __call__(self, field): vectors = list(self._wrt.atoms(BaseVectorField)) base_ops = [BaseCovarDerivativeOp(v._coord_sys, v._index, self._christoffel) for v in vectors] return self._wrt.subs(list(zip(vectors, base_ops))).rcall(field) ############################################################################### # Integral curves on vector fields ############################################################################### def intcurve_series(vector_field, param, start_point, n=6, coord_sys=None, coeffs=False): r"""Return the series expansion for an integral curve of the field. Explanation =========== Integral curve is a function `\gamma` taking a parameter in `R` to a point in the manifold. It verifies the equation: `V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)` where the given ``vector_field`` is denoted as `V`. This holds for any value `t` for the parameter and any scalar field `f`. This equation can also be decomposed of a basis of coordinate functions `V(f_i)\big(\gamma(t)\big) = \frac{d}{dt}f_i\big(\gamma(t)\big) \quad \forall i` This function returns a series expansion of `\gamma(t)` in terms of the coordinate system ``coord_sys``. The equations and expansions are necessarily done in coordinate-system-dependent way as there is no other way to represent movement between points on the manifold (i.e. there is no such thing as a difference of points for a general manifold). Parameters ========== vector_field the vector field for which an integral curve will be given param the argument of the function `\gamma` from R to the curve start_point the point which corresponds to `\gamma(0)` n the order to which to expand coord_sys the coordinate system in which to expand coeffs (default False) - if True return a list of elements of the expansion Examples ======== Use the predefined R2 manifold: >>> from sympy.abc import t, x, y >>> from sympy.diffgeom.rn import R2_p, R2_r >>> from sympy.diffgeom import intcurve_series Specify a starting point and a vector field: >>> start_point = R2_r.point([x, y]) >>> vector_field = R2_r.e_x Calculate the series: >>> intcurve_series(vector_field, t, start_point, n=3) Matrix([ [t + x], [ y]]) Or get the elements of the expansion in a list: >>> series = intcurve_series(vector_field, t, start_point, n=3, coeffs=True) >>> series[0] Matrix([ [x], [y]]) >>> series[1] Matrix([ [t], [0]]) >>> series[2] Matrix([ [0], [0]]) The series in the polar coordinate system: >>> series = intcurve_series(vector_field, t, start_point, ... n=3, coord_sys=R2_p, coeffs=True) >>> series[0] Matrix([ [sqrt(x**2 + y**2)], [ atan2(y, x)]]) >>> series[1] Matrix([ [t*x/sqrt(x**2 + y**2)], [ -t*y/(x**2 + y**2)]]) >>> series[2] Matrix([ [t**2*(-x**2/(x**2 + y**2)**(3/2) + 1/sqrt(x**2 + y**2))/2], [ t**2*x*y/(x**2 + y**2)**2]]) See Also ======== intcurve_diffequ """ if contravariant_order(vector_field) != 1 or covariant_order(vector_field): raise ValueError('The supplied field was not a vector field.') def iter_vfield(scalar_field, i): """Return ``vector_field`` called `i` times on ``scalar_field``.""" return reduce(lambda s, v: v.rcall(s), [vector_field, ]*i, scalar_field) def taylor_terms_per_coord(coord_function): """Return the series for one of the coordinates.""" return [param**i*iter_vfield(coord_function, i).rcall(start_point)/factorial(i) for i in range(n)] coord_sys = coord_sys if coord_sys else start_point._coord_sys coord_functions = coord_sys.coord_functions() taylor_terms = [taylor_terms_per_coord(f) for f in coord_functions] if coeffs: return [Matrix(t) for t in zip(*taylor_terms)] else: return Matrix([sum(c) for c in taylor_terms]) def intcurve_diffequ(vector_field, param, start_point, coord_sys=None): r"""Return the differential equation for an integral curve of the field. Explanation =========== Integral curve is a function `\gamma` taking a parameter in `R` to a point in the manifold. It verifies the equation: `V(f)\big(\gamma(t)\big) = \frac{d}{dt}f\big(\gamma(t)\big)` where the given ``vector_field`` is denoted as `V`. This holds for any value `t` for the parameter and any scalar field `f`. This function returns the differential equation of `\gamma(t)` in terms of the coordinate system ``coord_sys``. The equations and expansions are necessarily done in coordinate-system-dependent way as there is no other way to represent movement between points on the manifold (i.e. there is no such thing as a difference of points for a general manifold). Parameters ========== vector_field the vector field for which an integral curve will be given param the argument of the function `\gamma` from R to the curve start_point the point which corresponds to `\gamma(0)` coord_sys the coordinate system in which to give the equations Returns ======= a tuple of (equations, initial conditions) Examples ======== Use the predefined R2 manifold: >>> from sympy.abc import t >>> from sympy.diffgeom.rn import R2, R2_p, R2_r >>> from sympy.diffgeom import intcurve_diffequ Specify a starting point and a vector field: >>> start_point = R2_r.point([0, 1]) >>> vector_field = -R2.y*R2.e_x + R2.x*R2.e_y Get the equation: >>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point) >>> equations [f_1(t) + Derivative(f_0(t), t), -f_0(t) + Derivative(f_1(t), t)] >>> init_cond [f_0(0), f_1(0) - 1] The series in the polar coordinate system: >>> equations, init_cond = intcurve_diffequ(vector_field, t, start_point, R2_p) >>> equations [Derivative(f_0(t), t), Derivative(f_1(t), t) - 1] >>> init_cond [f_0(0) - 1, f_1(0) - pi/2] See Also ======== intcurve_series """ if contravariant_order(vector_field) != 1 or covariant_order(vector_field): raise ValueError('The supplied field was not a vector field.') coord_sys = coord_sys if coord_sys else start_point._coord_sys gammas = [Function('f_%d' % i)(param) for i in range( start_point._coord_sys.dim)] arbitrary_p = Point(coord_sys, gammas) coord_functions = coord_sys.coord_functions() equations = [simplify(diff(cf.rcall(arbitrary_p), param) - vector_field.rcall(cf).rcall(arbitrary_p)) for cf in coord_functions] init_cond = [simplify(cf.rcall(arbitrary_p).subs(param, 0) - cf.rcall(start_point)) for cf in coord_functions] return equations, init_cond ############################################################################### # Helpers ############################################################################### def dummyfy(args, exprs): # TODO Is this a good idea? d_args = Matrix([s.as_dummy() for s in args]) reps = dict(zip(args, d_args)) d_exprs = Matrix([_sympify(expr).subs(reps) for expr in exprs]) return d_args, d_exprs ############################################################################### # Helpers ############################################################################### def contravariant_order(expr, _strict=False): """Return the contravariant order of an expression. Examples ======== >>> from sympy.diffgeom import contravariant_order >>> from sympy.diffgeom.rn import R2 >>> from sympy.abc import a >>> contravariant_order(a) 0 >>> contravariant_order(a*R2.x + 2) 0 >>> contravariant_order(a*R2.x*R2.e_y + R2.e_x) 1 """ # TODO move some of this to class methods. # TODO rewrite using the .as_blah_blah methods if isinstance(expr, Add): orders = [contravariant_order(e) for e in expr.args] if len(set(orders)) != 1: raise ValueError('Misformed expression containing contravariant fields of varying order.') return orders[0] elif isinstance(expr, Mul): orders = [contravariant_order(e) for e in expr.args] not_zero = [o for o in orders if o != 0] if len(not_zero) > 1: raise ValueError('Misformed expression containing multiplication between vectors.') return 0 if not not_zero else not_zero[0] elif isinstance(expr, Pow): if covariant_order(expr.base) or covariant_order(expr.exp): raise ValueError( 'Misformed expression containing a power of a vector.') return 0 elif isinstance(expr, BaseVectorField): return 1 elif isinstance(expr, TensorProduct): return sum(contravariant_order(a) for a in expr.args) elif not _strict or expr.atoms(BaseScalarField): return 0 else: # If it does not contain anything related to the diffgeom module and it is _strict return -1 def covariant_order(expr, _strict=False): """Return the covariant order of an expression. Examples ======== >>> from sympy.diffgeom import covariant_order >>> from sympy.diffgeom.rn import R2 >>> from sympy.abc import a >>> covariant_order(a) 0 >>> covariant_order(a*R2.x + 2) 0 >>> covariant_order(a*R2.x*R2.dy + R2.dx) 1 """ # TODO move some of this to class methods. # TODO rewrite using the .as_blah_blah methods if isinstance(expr, Add): orders = [covariant_order(e) for e in expr.args] if len(set(orders)) != 1: raise ValueError('Misformed expression containing form fields of varying order.') return orders[0] elif isinstance(expr, Mul): orders = [covariant_order(e) for e in expr.args] not_zero = [o for o in orders if o != 0] if len(not_zero) > 1: raise ValueError('Misformed expression containing multiplication between forms.') return 0 if not not_zero else not_zero[0] elif isinstance(expr, Pow): if covariant_order(expr.base) or covariant_order(expr.exp): raise ValueError( 'Misformed expression containing a power of a form.') return 0 elif isinstance(expr, Differential): return covariant_order(*expr.args) + 1 elif isinstance(expr, TensorProduct): return sum(covariant_order(a) for a in expr.args) elif not _strict or expr.atoms(BaseScalarField): return 0 else: # If it does not contain anything related to the diffgeom module and it is _strict return -1 ############################################################################### # Coordinate transformation functions ############################################################################### def vectors_in_basis(expr, to_sys): """Transform all base vectors in base vectors of a specified coord basis. While the new base vectors are in the new coordinate system basis, any coefficients are kept in the old system. Examples ======== >>> from sympy.diffgeom import vectors_in_basis >>> from sympy.diffgeom.rn import R2_r, R2_p >>> vectors_in_basis(R2_r.e_x, R2_p) -y*e_theta/(x**2 + y**2) + x*e_rho/sqrt(x**2 + y**2) >>> vectors_in_basis(R2_p.e_r, R2_r) sin(theta)*e_y + cos(theta)*e_x """ vectors = list(expr.atoms(BaseVectorField)) new_vectors = [] for v in vectors: cs = v._coord_sys jac = cs.jacobian(to_sys, cs.coord_functions()) new = (jac.T*Matrix(to_sys.base_vectors()))[v._index] new_vectors.append(new) return expr.subs(list(zip(vectors, new_vectors))) ############################################################################### # Coordinate-dependent functions ############################################################################### def twoform_to_matrix(expr): """Return the matrix representing the twoform. For the twoform `w` return the matrix `M` such that `M[i,j]=w(e_i, e_j)`, where `e_i` is the i-th base vector field for the coordinate system in which the expression of `w` is given. Examples ======== >>> from sympy.diffgeom.rn import R2 >>> from sympy.diffgeom import twoform_to_matrix, TensorProduct >>> TP = TensorProduct >>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) Matrix([ [1, 0], [0, 1]]) >>> twoform_to_matrix(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) Matrix([ [x, 0], [0, 1]]) >>> twoform_to_matrix(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy) - TP(R2.dx, R2.dy)/2) Matrix([ [ 1, 0], [-1/2, 1]]) """ if covariant_order(expr) != 2 or contravariant_order(expr): raise ValueError('The input expression is not a two-form.') coord_sys = _find_coords(expr) if len(coord_sys) != 1: raise ValueError('The input expression concerns more than one ' 'coordinate systems, hence there is no unambiguous ' 'way to choose a coordinate system for the matrix.') coord_sys = coord_sys.pop() vectors = coord_sys.base_vectors() expr = expr.expand() matrix_content = [[expr.rcall(v1, v2) for v1 in vectors] for v2 in vectors] return Matrix(matrix_content) def metric_to_Christoffel_1st(expr): """Return the nested list of Christoffel symbols for the given metric. This returns the Christoffel symbol of first kind that represents the Levi-Civita connection for the given metric. Examples ======== >>> from sympy.diffgeom.rn import R2 >>> from sympy.diffgeom import metric_to_Christoffel_1st, TensorProduct >>> TP = TensorProduct >>> metric_to_Christoffel_1st(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[[0, 0], [0, 0]], [[0, 0], [0, 0]]] >>> metric_to_Christoffel_1st(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[[1/2, 0], [0, 0]], [[0, 0], [0, 0]]] """ matrix = twoform_to_matrix(expr) if not matrix.is_symmetric(): raise ValueError( 'The two-form representing the metric is not symmetric.') coord_sys = _find_coords(expr).pop() deriv_matrices = [matrix.applyfunc(d) for d in coord_sys.base_vectors()] indices = list(range(coord_sys.dim)) christoffel = [[[(deriv_matrices[k][i, j] + deriv_matrices[j][i, k] - deriv_matrices[i][j, k])/2 for k in indices] for j in indices] for i in indices] return ImmutableDenseNDimArray(christoffel) def metric_to_Christoffel_2nd(expr): """Return the nested list of Christoffel symbols for the given metric. This returns the Christoffel symbol of second kind that represents the Levi-Civita connection for the given metric. Examples ======== >>> from sympy.diffgeom.rn import R2 >>> from sympy.diffgeom import metric_to_Christoffel_2nd, TensorProduct >>> TP = TensorProduct >>> metric_to_Christoffel_2nd(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[[0, 0], [0, 0]], [[0, 0], [0, 0]]] >>> metric_to_Christoffel_2nd(R2.x*TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[[1/(2*x), 0], [0, 0]], [[0, 0], [0, 0]]] """ ch_1st = metric_to_Christoffel_1st(expr) coord_sys = _find_coords(expr).pop() indices = list(range(coord_sys.dim)) # XXX workaround, inverting a matrix does not work if it contains non # symbols #matrix = twoform_to_matrix(expr).inv() matrix = twoform_to_matrix(expr) s_fields = set() for e in matrix: s_fields.update(e.atoms(BaseScalarField)) s_fields = list(s_fields) dums = coord_sys.symbols matrix = matrix.subs(list(zip(s_fields, dums))).inv().subs(list(zip(dums, s_fields))) # XXX end of workaround christoffel = [[[Add(*[matrix[i, l]*ch_1st[l, j, k] for l in indices]) for k in indices] for j in indices] for i in indices] return ImmutableDenseNDimArray(christoffel) def metric_to_Riemann_components(expr): """Return the components of the Riemann tensor expressed in a given basis. Given a metric it calculates the components of the Riemann tensor in the canonical basis of the coordinate system in which the metric expression is given. Examples ======== >>> from sympy import exp >>> from sympy.diffgeom.rn import R2 >>> from sympy.diffgeom import metric_to_Riemann_components, TensorProduct >>> TP = TensorProduct >>> metric_to_Riemann_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[[[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]] >>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \ R2.r**2*TP(R2.dtheta, R2.dtheta) >>> non_trivial_metric exp(2*rho)*TensorProduct(drho, drho) + rho**2*TensorProduct(dtheta, dtheta) >>> riemann = metric_to_Riemann_components(non_trivial_metric) >>> riemann[0, :, :, :] [[[0, 0], [0, 0]], [[0, exp(-2*rho)*rho], [-exp(-2*rho)*rho, 0]]] >>> riemann[1, :, :, :] [[[0, -1/rho], [1/rho, 0]], [[0, 0], [0, 0]]] """ ch_2nd = metric_to_Christoffel_2nd(expr) coord_sys = _find_coords(expr).pop() indices = list(range(coord_sys.dim)) deriv_ch = [[[[d(ch_2nd[i, j, k]) for d in coord_sys.base_vectors()] for k in indices] for j in indices] for i in indices] riemann_a = [[[[deriv_ch[rho][sig][nu][mu] - deriv_ch[rho][sig][mu][nu] for nu in indices] for mu in indices] for sig in indices] for rho in indices] riemann_b = [[[[Add(*[ch_2nd[rho, l, mu]*ch_2nd[l, sig, nu] - ch_2nd[rho, l, nu]*ch_2nd[l, sig, mu] for l in indices]) for nu in indices] for mu in indices] for sig in indices] for rho in indices] riemann = [[[[riemann_a[rho][sig][mu][nu] + riemann_b[rho][sig][mu][nu] for nu in indices] for mu in indices] for sig in indices] for rho in indices] return ImmutableDenseNDimArray(riemann) def metric_to_Ricci_components(expr): """Return the components of the Ricci tensor expressed in a given basis. Given a metric it calculates the components of the Ricci tensor in the canonical basis of the coordinate system in which the metric expression is given. Examples ======== >>> from sympy import exp >>> from sympy.diffgeom.rn import R2 >>> from sympy.diffgeom import metric_to_Ricci_components, TensorProduct >>> TP = TensorProduct >>> metric_to_Ricci_components(TP(R2.dx, R2.dx) + TP(R2.dy, R2.dy)) [[0, 0], [0, 0]] >>> non_trivial_metric = exp(2*R2.r)*TP(R2.dr, R2.dr) + \ R2.r**2*TP(R2.dtheta, R2.dtheta) >>> non_trivial_metric exp(2*rho)*TensorProduct(drho, drho) + rho**2*TensorProduct(dtheta, dtheta) >>> metric_to_Ricci_components(non_trivial_metric) [[1/rho, 0], [0, exp(-2*rho)*rho]] """ riemann = metric_to_Riemann_components(expr) coord_sys = _find_coords(expr).pop() indices = list(range(coord_sys.dim)) ricci = [[Add(*[riemann[k, i, k, j] for k in indices]) for j in indices] for i in indices] return ImmutableDenseNDimArray(ricci) ############################################################################### # Classes for deprecation ############################################################################### class _deprecated_container: # This class gives deprecation warning. # When deprecated features are completely deleted, this should be removed as well. # See https://github.com/sympy/sympy/pull/19368 def __init__(self, feature, useinstead, issue, version, data): super().__init__(data) self.feature = feature self.useinstead = useinstead self.issue = issue self.version = version def warn(self): SymPyDeprecationWarning( feature=self.feature, useinstead=self.useinstead, issue=self.issue, deprecated_since_version=self.version).warn() def __iter__(self): self.warn() return super().__iter__() def __getitem__(self, key): self.warn() return super().__getitem__(key) def __contains__(self, key): self.warn() return super().__contains__(key) class _deprecated_list(_deprecated_container, list): pass class _deprecated_dict(_deprecated_container, dict): pass # Import at end to avoid cyclic imports from sympy.simplify.simplify import simplify
c16e092714204780d390f6358d67df9bf484016766a3d1d3de8ea8ddc1b236a8
"""This module provides containers for python objects that are valid printing targets but are not a subclass of SymPy's Printable. """ from sympy.core.containers import Tuple class List(Tuple): """Represents a (frozen) (Python) list (for code printing purposes).""" def __eq__(self, other): if isinstance(other, list): return self == List(*other) else: return self.args == other